From 2bb33640921cfecc8b4cedce7b29b97251c09248 Mon Sep 17 00:00:00 2001 From: Wenhao Date: Sat, 21 Nov 2026 10:47:36 +0800 Subject: [PATCH 1/2] fix(multi-panel): support Gemini multi-account switching and reliable Kimi/DeepSeek Send All - Add Gemini header account selector (Default, /u/0..4) persisted in sync storage and preserve /u/ across refresh, Temporary Chat exit, New Chat URL fallbacks, and Open in New Tab - Intercept same-origin Google /u/ and ?authuser= target=_blank/_top links inside Multi-Panel frames so account switching stays in-frame - Fix Kimi Lexical multiline prompt truncation via cancelable paste injection, tighten Kimi/DeepSeek send & input selectors, and retry slow disabled-to-enabled send buttons - Re-target all panels on Send All after partial image fill failures with fallbackImages and sync React main-world _valueTracker across isolated worlds so cleared DeepSeek composers re-populate cleanly Refs: #118 --- .../text-injection-all-providers.js | 463 +++++++++++++++--- modules/gemini-account.js | 128 +++++ modules/panel-message-contract.js | 1 + modules/provider-open-url.js | 52 +- modules/settings.js | 2 + multi-panel/multi-panel.css | 6 +- multi-panel/multi-panel.js | 191 +++++++- tests/deepseek-content-script.test.js | 83 ++++ ...118-multi-account-and-send-all.e2e.test.js | 333 +++++++++++++ tests/gemini-account.test.js | 346 +++++++++++++ tests/gemini-content-script.test.js | 36 ++ ...ovider-image-upload-content-script.test.js | 121 +++++ tests/provider-open-url.test.js | 13 + 13 files changed, 1699 insertions(+), 76 deletions(-) create mode 100644 modules/gemini-account.js create mode 100644 tests/e2e/issue-118-multi-account-and-send-all.e2e.test.js create mode 100644 tests/gemini-account.test.js diff --git a/content-scripts/text-injection-all-providers.js b/content-scripts/text-injection-all-providers.js index b93c590..95c9196 100644 --- a/content-scripts/text-injection-all-providers.js +++ b/content-scripts/text-injection-all-providers.js @@ -149,16 +149,19 @@ gemini: ['.ql-editor'], grok: ['.tiptap', '.ProseMirror', 'textarea'], deepseek: [ + 'textarea[placeholder="Message DeepSeek"]', + 'textarea[placeholder*="DeepSeek"]:not([name="user query"])', 'textarea[placeholder="How can I help you?"]', - 'textarea.ds-scroll-area', - 'textarea[class*="ds-"]', - 'textarea', + 'textarea.ds-scroll-area:not([name="user query"])', + 'textarea[class*="ds-"]:not([name="user query"])', + 'textarea:not([name="user query"])', 'div[contenteditable="true"]' ], kimi: [ - '.chat-input-editor', 'div[contenteditable="true"].chat-input-editor', 'div.chat-input-editor[contenteditable]', + '.chat-input-editor[data-lexical-editor="true"]', + '.chat-input-editor', 'div[contenteditable="true"]' ], doubao: [ @@ -324,13 +327,16 @@ deepseek: [ // Current site: a design-system div button that is disabled by class. 'div[role="button"].ds-button--primary.ds-button--filled:not(.ds-button--disabled)', + '.ds-icon-button[role="button"]:not([aria-disabled="true"]):not(.ds-icon-button--disabled)', + 'button.ds-icon-button:not([aria-disabled="true"]):not(.ds-icon-button--disabled)', 'button[aria-label="Send"]', 'button[type="submit"]' ], kimi: [ // Priority: clickable send button containers that are not disabled '.send-button-container:not(.disabled)', - 'div[class*="send"]:not([class*="disabled"])', + '.send-button:not(.disabled)', + '[role="button"][class*="send"]:not([class*="disabled"])', // Backup: look for send icon and click its parent 'svg[name="Send"]', '.send-icon', @@ -733,6 +739,85 @@ }); } + function getCurrentGoogleAccountPrefix() { + const match = /^\/u\/(\d+)(?:\/|$)/.exec(window.location.pathname || ''); + return match ? `/u/${match[1]}` : ''; + } + + function isSameOriginGoogleAccountNavigationUrl(provider, targetUrl) { + if (!targetUrl || targetUrl.origin !== window.location.origin) { + return false; + } + + if (provider === 'gemini' || provider === 'aistudio') { + return /^\/u\/\d+(?:\/|$)/.test(targetUrl.pathname) || targetUrl.searchParams.has('authuser'); + } + + if (provider === 'google') { + return targetUrl.searchParams.has('authuser'); + } + + return false; + } + + /** + * Keeps same-origin Google multi-account links (`/u//...`, `?authuser=`) + * inside the embedded panel iframe when the page marks them `target="_blank"` + * or `target="_top"`, instead of opening an external tab or hitting sandbox + * top-navigation restrictions. + */ + function setupSameOriginAccountNavigation() { + document.addEventListener('click', (event) => { + if (!isMultiPanelFrame()) { + return; + } + + if ( + event.defaultPrevented || + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) { + return; + } + + const provider = detectProvider(); + if (provider !== 'gemini' && provider !== 'aistudio' && provider !== 'google') { + return; + } + + const rawTarget = event.composedPath?.()[0] || event.target; + const anchor = typeof rawTarget?.closest === 'function' + ? rawTarget.closest('a[href]') + : rawTarget?.parentElement?.closest?.('a[href]') || null; + if (!anchor) { + return; + } + + const targetAttr = (anchor.getAttribute('target') || '').trim().toLowerCase(); + if (targetAttr !== '_blank' && targetAttr !== '_top' && targetAttr !== '_parent') { + return; + } + + let resolvedUrl; + try { + resolvedUrl = new URL(anchor.getAttribute('href'), window.location.href); + } catch { + return; + } + + if (!isSameOriginGoogleAccountNavigationUrl(provider, resolvedUrl)) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + window.location.assign(resolvedUrl.toString()); + }, true); + } + function setupProviderLocationReporting() { let lastReportedUrl = null; @@ -1186,23 +1271,89 @@ return findFirstVisibleElement(getGoogleInputSelectors(mode)); } + const touchedFormControls = new WeakSet(); + function setFormControlValue(element, value) { + const previousValue = element.value ?? ''; + const wasPreviouslyTouched = touchedFormControls.has(element); + touchedFormControls.add(element); + + try { + element.focus({ preventScroll: true }); + } catch { + element.focus?.(); + } + const prototype = element.tagName === 'INPUT' ? window.HTMLInputElement.prototype : window.HTMLTextAreaElement.prototype; const nativeSetter = Object.getOwnPropertyDescriptor(prototype, 'value')?.set; + // Chrome MV3 content scripts run in an isolated world where React's main-world + // `node._valueTracker` expando is invisible. When re-filling a previously touched + // control that was cleared or left at the same value, flush an empty input event + // first so React's main-world tracker syncs to '' before observing the new value. + if ( + wasPreviouslyTouched && + !element._valueTracker && + value !== '' && + (previousValue === '' || previousValue === value) + ) { + if (previousValue !== '') { + if (nativeSetter) { + nativeSetter.call(element, ''); + } else { + element.value = ''; + } + } + try { + element.dispatchEvent(new InputEvent('input', { + bubbles: true, + composed: true, + inputType: 'deleteContentBackward', + data: null + })); + } catch { + element.dispatchEvent(new Event('input', { bubbles: true })); + } + } + if (nativeSetter) { nativeSetter.call(element, value); } else { element.value = value; } - element.dispatchEvent(new Event('input', { bubbles: true })); + // Reset React's internal _valueTracker so controlled inputs (e.g. DeepSeek) + // always observe programmatic refills even after clearing or deleting text. + if (element._valueTracker && typeof element._valueTracker.setValue === 'function') { + try { + element._valueTracker.setValue( + previousValue === value ? (value === '' ? '__panelize_cleared__' : '') : previousValue + ); + } catch { + // Ignore React tracker errors + } + } + + try { + element.dispatchEvent(new InputEvent('input', { + bubbles: true, + composed: true, + inputType: value === '' ? 'deleteContentBackward' : 'insertText', + data: value === '' ? null : value + })); + } catch { + element.dispatchEvent(new Event('input', { bubbles: true })); + } element.dispatchEvent(new Event('change', { bubbles: true })); if (typeof element.value === 'string') { - element.selectionStart = element.selectionEnd = element.value.length; + try { + element.selectionStart = element.selectionEnd = element.value.length; + } catch { + // Ignore selection range errors on unsupported input types + } } } @@ -1333,7 +1484,16 @@ return true; } - return !element.classList.contains('disabled'); + if ( + element.classList.contains('disabled') || + element.classList.contains('ds-button--disabled') || + element.classList.contains('ds-icon-button--disabled') || + element.closest?.('.disabled, .ds-button--disabled, .ds-icon-button--disabled, [aria-disabled="true"]') + ) { + return false; + } + + return true; } function fillGoogleSearchInput(text) { @@ -1495,14 +1655,49 @@ } } - // Find text input element by selector + function isUsableTextInputCandidate(element) { + if (!element || element.disabled || element.readOnly || element.hidden) { + return false; + } + if ( + element.getAttribute('aria-hidden') === 'true' || + element.getAttribute('aria-disabled') === 'true' || + element.getAttribute('aria-readonly') === 'true' || + element.getAttribute('contenteditable') === 'false' + ) { + return false; + } + const style = typeof window.getComputedStyle === 'function' + ? window.getComputedStyle(element) + : null; + if (style && (style.display === 'none' || style.visibility === 'hidden' || style.visibility === 'collapse')) { + return false; + } + return true; + } + + // Find text input element by selector, preferring visible & enabled composers + // over hidden helper/inline-edit textareas earlier in DOM order. function findTextInputElement(selector) { if (!selector || typeof selector !== 'string') { return null; } try { - return document.querySelector(selector); + const matches = document.querySelectorAll(selector); + let nonHiddenFallback = null; + for (const candidate of matches) { + if (!isUsableTextInputCandidate(candidate)) { + continue; + } + if (isVisibleElement(candidate)) { + return candidate; + } + if (!nonHiddenFallback) { + nonHiddenFallback = candidate; + } + } + return nonHiddenFallback; } catch (error) { console.error('Error finding element:', error); return null; @@ -1586,7 +1781,7 @@ } // Find and click send button - function clickSendButton(provider, providerMode = null) { + function clickSendButton(provider, providerMode = null, { allowEnterFallback = true } = {}) { if (provider === 'google') { return clickGoogleSendButton(providerMode); } @@ -1669,25 +1864,27 @@ } } + if (!allowEnterFallback) { + return false; + } + // Special handling for DeepSeek - trigger Enter key if button not found if (provider === 'deepseek') { console.log('[Text Injection] DeepSeek send button not found, trying Enter key'); try { - const inputSelectors = PROVIDER_SELECTORS.deepseek; - for (const selector of inputSelectors) { - const input = document.querySelector(selector); - if (input) { - console.log('[Text Injection] Triggering Enter key on DeepSeek input'); - // Trigger multiple events for better compatibility - const events = [ - new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true }), - new KeyboardEvent('keypress', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true }), - new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true }) - ]; - - events.forEach(event => input.dispatchEvent(event)); - return true; - } + const input = findProviderInput('deepseek'); + if (input) { + console.log('[Text Injection] Triggering Enter key on DeepSeek input'); + input.focus(); + // Trigger multiple events for better compatibility + const events = [ + new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true }), + new KeyboardEvent('keypress', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true }), + new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true }) + ]; + + events.forEach(event => input.dispatchEvent(event)); + return true; } } catch (error) { console.warn('[Text Injection] Error in DeepSeek Enter key fallback:', error); @@ -1733,6 +1930,53 @@ return false; } + function hasDisabledSlowSendControl(provider) { + if (provider === 'deepseek') { + return Boolean( + document.querySelector( + 'div[role="button"].ds-button--primary.ds-button--filled.ds-button--disabled, .ds-icon-button[aria-disabled="true"], .ds-icon-button--disabled' + ) + ); + } + if (provider === 'kimi') { + return Boolean( + document.querySelector('.send-button-container.disabled, .send-button.disabled') + ); + } + return false; + } + + function scheduleAutoSubmit(provider, providerMode = null) { + const initialDelay = SLOW_COMPOSER_PROVIDERS.has(provider) ? 800 : 500; + const extraRetryDelays = SLOW_COMPOSER_PROVIDERS.has(provider) ? [400, 800, 1200] : []; + + setTimeout(() => { + const waitForSlowControl = hasDisabledSlowSendControl(provider); + if (clickSendButton(provider, providerMode, { allowEnterFallback: !waitForSlowControl })) { + return; + } + if (!waitForSlowControl || extraRetryDelays.length === 0) { + console.warn('[Text Injection] Failed to click send button for', provider); + return; + } + + let settled = false; + extraRetryDelays.forEach((retryOffset, index) => { + setTimeout(() => { + if (settled) { + return; + } + const isLastAttempt = index === extraRetryDelays.length - 1; + if (clickSendButton(provider, providerMode, { allowEnterFallback: isLastAttempt })) { + settled = true; + } else if (isLastAttempt) { + console.warn('[Text Injection] Failed to click send button for', provider); + } + }, retryOffset); + }); + }, initialDelay); + } + // Special handler for Google to create "new search" function handleGoogleNewSearch(mode) { const normalizedMode = normalizeGoogleProviderMode(mode); @@ -1935,9 +2179,10 @@ function handleAiStudioNewChat(options = {}) { const shouldUseTemporaryChat = options?.temporaryChat === true || (options?.temporaryChat !== false && isTemporaryChatAlreadyEnabled('aistudio')); - const targetUrl = shouldUseTemporaryChat - ? AISTUDIO_TEMP_CHAT_URL - : AISTUDIO_NEW_CHAT_URL; + const accountPrefix = getCurrentGoogleAccountPrefix(); + const targetUrl = accountPrefix + ? `https://aistudio.google.com${accountPrefix}/prompts/new_chat${shouldUseTemporaryChat ? '?temporary=true' : ''}` + : (shouldUseTemporaryChat ? AISTUDIO_TEMP_CHAT_URL : AISTUDIO_NEW_CHAT_URL); console.log('[Text Injection] Navigating AI Studio to new chat URL:', targetUrl); window.location.href = targetUrl; return true; @@ -2190,9 +2435,10 @@ // Ultimate fallback: navigate to new chat URL const fallbackUrl = NEW_CHAT_URLS[provider]; if (fallbackUrl) { + const geminiAccountPrefix = provider === 'gemini' ? getCurrentGoogleAccountPrefix() : ''; const resolvedFallbackUrl = (provider === 'chatgpt' && options?.temporaryChat === true) ? 'https://chatgpt.com/?temporary-chat=true' - : fallbackUrl; + : (geminiAccountPrefix ? `https://gemini.google.com${geminiAccountPrefix}/app` : fallbackUrl); if (provider === 'chatgpt') { clearChatgptComposerDraftOnce(); markPendingChatgptNewChatComposerClear(); @@ -2243,6 +2489,7 @@ range.collapse(false); // Collapse to end selection.removeAllRanges(); selection.addRange(range); + document.dispatchEvent(new Event('selectionchange')); } catch (e) { // Ignore selection errors in cross-origin context } @@ -2263,6 +2510,53 @@ } } + if (provider === 'kimi' || element.getAttribute('data-lexical-editor') === 'true') { + // Kimi's Lexical editor reconciles `beforeinput` asynchronously on microtasks; + // Chromium's synchronous `execCommand('insertText')` splits multiline text on `\n` + // and drops lines during long prompts. Dispatching a cancelable `paste` event lets + // Lexical insert the full text atomically, falling back cleanly when unhandled. + try { + if (typeof DataTransfer === 'function' && typeof ClipboardEvent === 'function') { + const beforeText = element.textContent || ''; + const dataTransfer = new DataTransfer(); + dataTransfer.setData('text/plain', text); + const pasteEvent = new ClipboardEvent('paste', { + bubbles: true, + cancelable: true, + composed: true, + clipboardData: dataTransfer + }); + if (!pasteEvent.clipboardData) { + Object.defineProperty(pasteEvent, 'clipboardData', { + configurable: true, + value: dataTransfer + }); + } + element.dispatchEvent(pasteEvent); + if (pasteEvent.defaultPrevented) { + queueMicrotask(() => { + if ((element.textContent || '') !== beforeText) { + return; + } + let fallbackInserted = false; + try { + fallbackInserted = document.execCommand('insertText', false, text); + } catch { + // Ignore unsupported execCommand fallback + } + if (!fallbackInserted && (element.textContent || '') === beforeText) { + element.appendChild(document.createTextNode(text)); + element.dispatchEvent(new Event('input', { bubbles: true })); + } + }); + return true; + } + } + } catch (e) { + // Fall through to execCommand / DOM insertion if synthetic paste is unavailable + } + } + // Use execCommand insertText to append - works well with ProseMirror/Lexical/Quill let inserted = false; try { @@ -2359,9 +2653,7 @@ if (success) { console.log('[Text Injection] Text injected via injectText helper for', provider); if (autoSubmit) { - // Use longer delay for providers whose composer state updates asynchronously - const delay = SLOW_COMPOSER_PROVIDERS.has(provider) ? 800 : 500; - setTimeout(() => clickSendButton(provider, providerMode), delay); + scheduleAutoSubmit(provider, providerMode); } return true; } @@ -2371,9 +2663,55 @@ return false; } + function isProviderComposerCleared(provider, candidateImages = [], providerMode = null) { + const input = provider === 'google' + ? findGoogleInput(providerMode) + : findProviderInput(provider); + if (!input) { + return false; + } + + const isFormControl = input.tagName === 'TEXTAREA' || input.tagName === 'INPUT'; + const currentText = isFormControl ? (input.value || '') : (input.textContent || ''); + if (currentText.trim().length > 0) { + return false; + } + + if ((candidateImages || []).some(img => img?.name && countFilenamePreviewEvidence(document, img.name) > 0)) { + return false; + } + + if (provider === 'deepseek') { + const composer = getDeepSeekComposer(); + if (composer && composer.querySelectorAll('img[src^="blob:"]').length > 0) { + return false; + } + } else if (provider === 'kimi') { + const composer = getKimiComposer(); + if ( + composer && + (countKimiAttachmentPreviews(composer) > 0 || countKimiPendingAttachmentPreviews(composer) > 0) + ) { + return false; + } + } else if (provider === 'grok') { + const composer = getGrokComposer(); + const attachmentList = composer?.querySelector('[role="list"][aria-label="Conversation attachments"]'); + if ((attachmentList?.children.length || 0) > 0) { + return false; + } + } else if (provider === 'yuanbao') { + if ((candidateImages || []).some(img => img?.name && countYuanbaoCompletedPreviews(img.name) > 0)) { + return false; + } + } + + return true; + } + // Handle image injection message async function handleImageInjection(event) { - const { text, images, autoSubmit, requestId, retry = false } = event.data; + const { text, images, fallbackImages, autoSubmit, requestId, retry = false } = event.data; const provider = detectProvider(); const providerMode = provider === 'google' ? normalizeGoogleProviderMode(event.data.providerMode) @@ -2401,7 +2739,19 @@ return createImageInjectionFailure(IMAGE_INJECTION_REASONS.UNSUPPORTED, []); } - if (!images || images.length === 0) { + const normalizedFallbackImages = Array.isArray(fallbackImages) ? fallbackImages : []; + const fallbackSucceededIds = normalizedFallbackImages + .map(img => img?.id) + .filter(id => typeof id === 'string'); + const composerClearedOnRetry = Boolean( + retry && + normalizedFallbackImages.length > 0 && + isProviderComposerCleared(provider, normalizedFallbackImages, providerMode) + ); + const effectiveImages = composerClearedOnRetry ? normalizedFallbackImages : images; + const effectiveRetry = composerClearedOnRetry ? false : retry; + + if (!effectiveImages || effectiveImages.length === 0) { if (retry && text && text.trim()) { const textInjected = injectText( provider, @@ -2411,14 +2761,17 @@ { skipIfAlreadyPresent: true } ); return textInjected - ? createImageInjectionSuccess([]) + ? createImageInjectionSuccess(fallbackSucceededIds) : createImageInjectionFailure(IMAGE_INJECTION_REASONS.CONTROL_NOT_FOUND, []); } + if (retry && normalizedFallbackImages.length > 0) { + return createImageInjectionSuccess(fallbackSucceededIds); + } console.warn('[Image Injection] No images provided'); return createImageInjectionFailure(IMAGE_INJECTION_REASONS.INJECTION_ERROR, []); } - console.log(`[Image Injection] Injecting ${images.length} images to ${provider}`); + console.log(`[Image Injection] Injecting ${effectiveImages.length} images to ${provider}`); try { // Fills protect the unified input's focus too, so report a click in @@ -2437,8 +2790,8 @@ const imageInjectionResults = []; // Inject images first - for (const image of images) { - const result = await injectSingleImage(provider, image, { retry }); + for (const image of effectiveImages) { + const result = await injectSingleImage(provider, image, { retry: effectiveRetry }); imageInjectionResults.push(result); if (result.ok) { if (image.id && typeof image.id === 'string') { @@ -2451,7 +2804,7 @@ await sleep(200); } - const allImagesInjected = imageInjectionResults.length === images.length && + const allImagesInjected = imageInjectionResults.length === effectiveImages.length && imageInjectionResults.every(result => result.ok); if (!allImagesInjected) { console.warn('[Image Injection] One or more images failed to inject for:', provider); @@ -2469,7 +2822,7 @@ text, autoSubmit && allImagesInjected, providerMode, - { skipIfAlreadyPresent: retry } + { skipIfAlreadyPresent: effectiveRetry } ); } else if (autoSubmit) { if (!allImagesInjected) { @@ -2946,15 +3299,20 @@ } // DeepSeek renders attachment previews beside the composer controls rather - // than consistently inside the nearest file-input ancestor. - const previousCount = countFilenamePreviewEvidence(document, imageData.name); + // than consistently inside the nearest file-input ancestor; also count blob + // thumbnail images inside the composer when narrow chips truncate filenames. + const countDeepSeekPreviews = () => Math.max( + countFilenamePreviewEvidence(document, imageData.name), + composer.querySelectorAll('img[src^="blob:"]').length + ); + const previousCount = countDeepSeekPreviews(); if (!assignFilesToInput(fileInput, [file])) { return createImageInjectionFailure(IMAGE_INJECTION_REASONS.INJECTION_ERROR); } dispatchFileInputEvents(fileInput); const accepted = await waitForPreviewIncrease( - () => countFilenamePreviewEvidence(document, imageData.name), + countDeepSeekPreviews, previousCount ); return accepted @@ -4108,15 +4466,7 @@ // Auto-submit if requested (only from multi-panel context) if (shouldAutoSubmit) { - // Wait for framework-managed composer state to catch up before sending. - const delay = SLOW_COMPOSER_PROVIDERS.has(provider) ? 800 : 500; - setTimeout(() => { - console.log('[Text Injection] Attempting to click send button for', provider); - const clicked = clickSendButton(provider, providerMode); - if (!clicked) { - console.warn('[Text Injection] Failed to click send button for', provider); - } - }, delay); + scheduleAutoSubmit(provider, providerMode); } } else { console.error(`[Text Injection] Failed to inject text into ${provider}`); @@ -4135,11 +4485,7 @@ if (success) { console.log('[Text Injection] Text injected on retry into', provider); if (shouldAutoSubmit) { - const submitDelay = SLOW_COMPOSER_PROVIDERS.has(provider) ? 800 : 500; - setTimeout(() => { - console.log('[Text Injection] Attempting to click send button for', provider, 'after retry'); - clickSendButton(provider, providerMode); - }, submitDelay); + scheduleAutoSubmit(provider, providerMode); } } } else if (index === retryDelays.length - 1) { @@ -5167,6 +5513,7 @@ } // Listen for messages from the multi-panel host + setupSameOriginAccountNavigation(); setupProviderLocationReporting(); setupPageWidthReporting(); resumePendingChatgptNewChatComposerClear(); diff --git a/modules/gemini-account.js b/modules/gemini-account.js new file mode 100644 index 0000000..bae707b --- /dev/null +++ b/modules/gemini-account.js @@ -0,0 +1,128 @@ +/** + * Shared Gemini Google account index helpers (`/u/0`, `/u/1`, ...). + */ + +export const DEFAULT_GEMINI_ACCOUNT_INDEX = null; +export const GEMINI_ACCOUNT_OPTIONS = Object.freeze([null, 0, 1, 2, 3, 4]); +const MAX_GOOGLE_ACCOUNT_INDEX = 9; + +/** + * Normalize an arbitrary value to a supported Google account index or null (default session). + * @param {number | string | null | undefined} value + * @returns {number | null} + */ +export function normalizeGeminiAccountIndex(value) { + if (value === null || value === undefined || value === '' || value === 'default') { + return DEFAULT_GEMINI_ACCOUNT_INDEX; + } + + if (typeof value === 'number') { + return Number.isInteger(value) && value >= 0 && value <= MAX_GOOGLE_ACCOUNT_INDEX + ? value + : DEFAULT_GEMINI_ACCOUNT_INDEX; + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!/^\d+$/.test(trimmed)) { + return DEFAULT_GEMINI_ACCOUNT_INDEX; + } + const parsed = Number(trimmed); + return Number.isInteger(parsed) && parsed >= 0 && parsed <= MAX_GOOGLE_ACCOUNT_INDEX + ? parsed + : DEFAULT_GEMINI_ACCOUNT_INDEX; + } + + return DEFAULT_GEMINI_ACCOUNT_INDEX; +} + +/** + * Extract the `/u/` Google account index from an https URL, if present. + * @param {string | null | undefined} rawUrl + * @returns {number | null} + */ +export function extractGoogleAccountIndexFromUrl(rawUrl) { + if (!rawUrl || typeof rawUrl !== 'string') { + return null; + } + + try { + const parsed = new URL(rawUrl); + if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') { + return null; + } + const match = /^\/u\/(\d+)(?:\/|$)/.exec(parsed.pathname); + return match ? normalizeGeminiAccountIndex(match[1]) : null; + } catch { + return null; + } +} + +/** + * Strip a leading `/u/` segment from a URL pathname while keeping a leading slash. + * @param {string | null | undefined} pathname + * @returns {string} + */ +export function stripGoogleAccountPathPrefix(pathname) { + if (typeof pathname !== 'string' || pathname.length === 0) { + return '/'; + } + const stripped = pathname.replace(/^\/u\/\d+(?=\/|$)/, ''); + return stripped || '/'; +} + +/** + * Resolve the initial/reload iframe URL for Gemini given an account index. + * @param {number | string | null | undefined} accountIndex + * @returns {string} + */ +export function getGeminiProviderUrl(accountIndex) { + const normalized = normalizeGeminiAccountIndex(accountIndex); + return normalized === null + ? 'https://gemini.google.com' + : `https://gemini.google.com/u/${normalized}/app`; +} + +/** + * Resolve the normal (non-temporary) URL for Gemini given an account index. + * @param {number | string | null | undefined} accountIndex + * @returns {string} + */ +export function getGeminiTemporaryChatNormalUrl(accountIndex) { + const normalized = normalizeGeminiAccountIndex(accountIndex); + return normalized === null + ? 'https://gemini.google.com/' + : `https://gemini.google.com/u/${normalized}/app`; +} + +/** + * Resolve the top-level fallback URL for Gemini given an account index. + * @param {number | string | null | undefined} accountIndex + * @returns {string} + */ +export function getGeminiTopLevelFallbackUrl(accountIndex) { + const normalized = normalizeGeminiAccountIndex(accountIndex); + return normalized === null + ? 'https://gemini.google.com/app' + : `https://gemini.google.com/u/${normalized}/app`; +} + +/** + * Convert a normalized account index to its ` +
+ + +
+ +
+ Send +
+
+ + +`; +} + +function renderKimiFixture({ failFirstImageUpload = false } = {}) { + return ` + +Kimi fixture + +
+
+
+
+
+ +
+
+
Send
+
+
+
+ + +`; +} + +test('Gemini multi-account selector and in-frame /u/1/app account link stay inside Panelize without opening a new tab', async ({}, testInfo) => { + const extension = await launchExtension({ viewport: { width: 1280, height: 800 } }); + const pageErrors = []; + try { + await extension.context.route(/^https:\/\/gemini\.google\.com(\/|$)/, (route) => + route.fulfill({ + contentType: 'text/html', + body: renderGeminiAccountFixture(route.request().url()), + }) + ); + + const page = await openMultiPanel(extension, { providers: ['gemini'], layout: '1x1' }); + page.on('pageerror', (err) => pageErrors.push(err.message)); + + const accountSelect = page.locator('.panel-gemini-account-select'); + await expect(accountSelect).toBeVisible(); + await expect(accountSelect).toHaveValue(''); + + const panelFrame = page.frameLocator('iframe'); + await expect(panelFrame.locator('#current-path')).toHaveText('/'); + + const tabCountBeforeClick = (await getTabUrls(page)).length; + + // Clicking a target="_blank" /u/1/app?pageId=none link inside Gemini navigates in-frame instead of spawning an external tab + await panelFrame.locator('#switch-account-u1').click(); + await expect(panelFrame.locator('#current-path')).toHaveText('/u/1/app?pageId=none'); + await expect(accountSelect).toHaveValue('1'); + expect((await getTabUrls(page)).length).toBe(tabCountBeforeClick); + + // Switching the header dropdown to /u/2 navigates the panel iframe to /u/2/app + await accountSelect.selectOption('2'); + await expect(panelFrame.locator('#current-path')).toHaveText('/u/2/app'); + + // Also verify narrow/mobile viewport rendering of header controls + await page.setViewportSize({ width: 390, height: 844 }); + await expect(accountSelect).toBeVisible(); + await page.screenshot({ path: testInfo.outputPath('gemini-multi-account-mobile.png'), fullPage: true }); + + expect(pageErrors).toEqual([]); + } finally { + await extension.close(); + } +}); + +test('Send All delivers full 10-line prompts to Kimi & DeepSeek and re-populates cleared DeepSeek on Send All retry', async ({}, testInfo) => { + test.setTimeout(90000); + const extension = await launchExtension({ viewport: { width: 1280, height: 800 } }); + const pageErrors = []; + try { + await extension.context.route('https://chat.deepseek.com/**', (route) => + route.fulfill({ contentType: 'text/html', body: renderDeepSeekFixture() }) + ); + await extension.context.route('https://www.kimi.com/**', (route) => + route.fulfill({ contentType: 'text/html', body: renderKimiFixture({ failFirstImageUpload: true }) }) + ); + + const page = await openMultiPanel(extension, { providers: ['deepseek', 'kimi'], layout: '1x2' }); + page.on('pageerror', (err) => pageErrors.push(err.message)); + + const readProviderState = (host) => { + const frame = page.frames().find((candidate) => candidate.url().startsWith(`https://${host}/`)); + return frame ? frame.evaluate(() => window.__fixture).catch(() => null) : null; + }; + + await expect.poll(async () => Boolean(await readProviderState('chat.deepseek.com'))).toBe(true); + await expect.poll(async () => Boolean(await readProviderState('www.kimi.com'))).toBe(true); + + // Part 1: 10-line plain-text Send All -> both DeepSeek and Kimi must receive all 10/10 lines and auto-submit cleanly + const tenLines = Array.from({ length: 10 }, (_, idx) => `Step ${idx + 1}: Verify full prompt delivery`).join('\n'); + await page.locator('#unified-input').fill(tenLines); + await page.locator('#send-all-btn').click(); + + await expect.poll(async () => (await readProviderState('chat.deepseek.com'))?.sentPayloads).toEqual([ + { text: tenLines, previewCount: 0 }, + ]); + await expect.poll(async () => (await readProviderState('www.kimi.com'))?.sentPayloads).toEqual([ + { text: tenLines, previewCount: 0 }, + ]); + expect((await readProviderState('www.kimi.com')).prematureDisabledClicks).toBe(0); + + // Part 2: Image + prompt fill where Kimi fails on Pass 1, user deletes DeepSeek's prompt, and clicks Send All again + await page.locator('#image-file-input').setInputFiles({ + name: 'diagram.png', + mimeType: 'image/png', + buffer: PNG_BYTES, + }); + await expect(page.locator('.image-preview-item').first()).toBeVisible(); + await page.locator('#unified-input').fill('Compare architecture diagram'); + await page.locator('#send-all-btn').click(); + + // Pass 1 settles with DeepSeek filled and Kimi failed (preview-timeout) + await expect(page.locator('#send-status')).toHaveText('Filled 1/2; 1 failed', { timeout: 15000 }); + expect((await readProviderState('chat.deepseek.com')).reactStateText).toBe('Compare architecture diagram'); + + // User deletes the prompt & preview inside DeepSeek, then Kimi becomes healthy and user clicks Send All again + const deepseekFrame = page.frameLocator('iframe[src*="deepseek"]'); + await deepseekFrame.locator('#deepseek-clear-user').click(); + expect((await readProviderState('chat.deepseek.com')).reactStateText).toBe(''); + + const kimiFrameObj = page.frames().find((candidate) => candidate.url().startsWith('https://www.kimi.com/')); + await kimiFrameObj.evaluate(() => { + document.getElementById('kimi-previews').innerHTML = ''; + window.__fixture.allowUploadSuccess = true; + }); + + await page.locator('#send-all-btn').click(); + await expect(page.locator('#send-status')).toHaveText('Filled 2 inputs', { timeout: 15000 }); + + // Cleared DeepSeek must be re-populated with both the prompt and image, not left null! + expect((await readProviderState('chat.deepseek.com')).reactStateText).toBe('Compare architecture diagram'); + + // Clicking Send All now triggers send across both filled panels + await page.locator('#send-all-btn').click(); + await expect.poll(async () => (await readProviderState('chat.deepseek.com'))?.sentPayloads.at(-1)).toEqual({ + text: 'Compare architecture diagram', + previewCount: 1, + }); + await expect.poll(async () => (await readProviderState('www.kimi.com'))?.sentPayloads.at(-1)).toEqual({ + text: 'Compare architecture diagram', + previewCount: 1, + }); + + await page.screenshot({ path: testInfo.outputPath('deepseek-kimi-send-all-desktop.png'), fullPage: true }); + expect(pageErrors).toEqual([]); + } finally { + await extension.close(); + } +}); diff --git a/tests/gemini-account.test.js b/tests/gemini-account.test.js new file mode 100644 index 0000000..f738664 --- /dev/null +++ b/tests/gemini-account.test.js @@ -0,0 +1,346 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + DEFAULT_GEMINI_ACCOUNT_INDEX, + extractGoogleAccountIndexFromUrl, + getGeminiAccountOptionLabel, + getGeminiProviderUrl, + getGeminiTemporaryChatNormalUrl, + getGeminiTopLevelFallbackUrl, + normalizeGeminiAccountIndex, + stripGoogleAccountPathPrefix, + toGeminiAccountSelectValue, +} from '../modules/gemini-account.js'; + +const MULTI_PANEL_HTML = readFileSync( + resolve(process.cwd(), 'multi-panel/multi-panel.html'), + 'utf8' +); +const MULTI_PANEL_BODY_HTML = MULTI_PANEL_HTML + .match(/]*>([\s\S]*?)<\/body>/i)[1] + .replace(/]*>[\s\S]*?<\/script>/gi, ''); + +const SAMPLE_PNG_DATA_URL = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO2Z2ioAAAAASUVORK5CYII='; + +describe('Gemini multi-account helpers', () => { + it('normalizes account indices and falls back to default null for unset or out-of-range values', () => { + expect(normalizeGeminiAccountIndex(null)).toBe(DEFAULT_GEMINI_ACCOUNT_INDEX); + expect(normalizeGeminiAccountIndex(undefined)).toBe(null); + expect(normalizeGeminiAccountIndex('')).toBe(null); + expect(normalizeGeminiAccountIndex('default')).toBe(null); + expect(normalizeGeminiAccountIndex(0)).toBe(0); + expect(normalizeGeminiAccountIndex('1')).toBe(1); + expect(normalizeGeminiAccountIndex(' 4 ')).toBe(4); + expect(normalizeGeminiAccountIndex(-1)).toBe(null); + expect(normalizeGeminiAccountIndex(12)).toBe(null); + expect(normalizeGeminiAccountIndex('u1')).toBe(null); + }); + + it('extracts and strips /u/ path prefixes cleanly', () => { + expect(extractGoogleAccountIndexFromUrl('https://gemini.google.com/u/1/app?pageId=none')).toBe(1); + expect(extractGoogleAccountIndexFromUrl('https://aistudio.google.com/u/2/prompts/abc123')).toBe(2); + expect(extractGoogleAccountIndexFromUrl('https://gemini.google.com/app')).toBe(null); + expect(extractGoogleAccountIndexFromUrl('javascript:alert(1)')).toBe(null); + + expect(stripGoogleAccountPathPrefix('/u/1/app/abc123')).toBe('/app/abc123'); + expect(stripGoogleAccountPathPrefix('/u/0')).toBe('/'); + expect(stripGoogleAccountPathPrefix('/app')).toBe('/app'); + }); + + it('formats Gemini URLs and option labels for default and explicit accounts', () => { + expect(getGeminiProviderUrl(null)).toBe('https://gemini.google.com'); + expect(getGeminiProviderUrl(1)).toBe('https://gemini.google.com/u/1/app'); + expect(getGeminiTemporaryChatNormalUrl(null)).toBe('https://gemini.google.com/'); + expect(getGeminiTemporaryChatNormalUrl(1)).toBe('https://gemini.google.com/u/1/app'); + expect(getGeminiTopLevelFallbackUrl(null)).toBe('https://gemini.google.com/app'); + expect(getGeminiTopLevelFallbackUrl(1)).toBe('https://gemini.google.com/u/1/app'); + expect(toGeminiAccountSelectValue(null)).toBe(''); + expect(toGeminiAccountSelectValue(1)).toBe('1'); + expect(getGeminiAccountOptionLabel(null)).toBe('Default'); + expect(getGeminiAccountOptionLabel(1)).toBe('/u/1'); + }); +}); + +describe('multi-panel Gemini account selector & Send All cleared-panel retry', () => { + let cleanupListeners = []; + + beforeEach(() => { + vi.clearAllMocks(); + cleanupListeners = []; + + if (window.happyDOM?.settings?.navigation) { + window.happyDOM.settings.navigation.disableChildFrameNavigation = true; + } + + const origWinAdd = window.addEventListener.bind(window); + const origWinRemove = window.removeEventListener.bind(window); + const origDocAdd = document.addEventListener.bind(document); + const origDocRemove = document.removeEventListener.bind(document); + + vi.spyOn(window, 'addEventListener').mockImplementation((type, listener, options) => { + cleanupListeners.push(() => origWinRemove(type, listener, options)); + return origWinAdd(type, listener, options); + }); + vi.spyOn(document, 'addEventListener').mockImplementation((type, listener, options) => { + cleanupListeners.push(() => origDocRemove(type, listener, options)); + return origDocAdd(type, listener, options); + }); + + chrome.permissions = { + contains: vi.fn(() => Promise.resolve(true)), + request: vi.fn(() => Promise.resolve(true)), + }; + chrome.windows = { + getCurrent: vi.fn(() => Promise.resolve({ type: 'normal' })), + create: vi.fn(() => Promise.resolve({ id: 1 })), + }; + chrome.tabs = { + create: vi.fn(() => Promise.resolve({ id: 99 })), + }; + chrome.storage.session = { + get: vi.fn(() => Promise.resolve({})), + set: vi.fn(() => Promise.resolve()), + remove: vi.fn(() => Promise.resolve()), + }; + chrome.storage.local.get.mockImplementation((keys) => + Promise.resolve( + typeof keys === 'object' && keys !== null && !Array.isArray(keys) ? { ...keys } : {} + ) + ); + chrome.storage.local.set.mockResolvedValue(); + chrome.storage.local.remove.mockResolvedValue(); + chrome.storage.sync.set.mockResolvedValue(); + chrome.runtime.sendMessage.mockImplementation((_msg, callback) => { + if (callback) callback({ success: true }); + return Promise.resolve({ success: true }); + }); + globalThis.fetch = vi.fn(() => + Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({}) }) + ); + }); + + afterEach(() => { + for (const cleanup of cleanupListeners.splice(0)) { + cleanup(); + } + vi.useRealTimers(); + vi.restoreAllMocks(); + delete globalThis.fetch; + document.body.innerHTML = ''; + }); + + async function bootMultiPanel(providerIds, extraSyncSettings = {}) { + for (const cleanup of cleanupListeners.splice(0)) { + cleanup(); + } + vi.resetModules(); + chrome.storage.session.get.mockClear(); + document.body.innerHTML = MULTI_PANEL_BODY_HTML; + + const layout = `1x${Math.max(1, Math.min(providerIds.length, 12))}`; + chrome.storage.sync.get.mockImplementation((defaults) => { + const base = + typeof defaults === 'object' && defaults !== null && !Array.isArray(defaults) + ? { ...defaults } + : {}; + return Promise.resolve({ + ...base, + theme: 'light', + language: 'en', + multiPanelLayout: layout, + enabledProviders: [...providerIds], + providerOrder: [...providerIds], + multiPanelProviders: [...providerIds], + ...extraSyncSettings, + }); + }); + + const mod = await import('../multi-panel/multi-panel.js'); + await vi.waitFor(() => { + const calls = chrome.storage.session.get.mock.calls.map(([arg]) => arg); + expect(calls).toContain('pendingMultiPanelAction'); + }); + + const panelItems = Array.from(document.querySelectorAll('#panel-grid .panel-item')); + const handleByProvider = {}; + panelItems.forEach((panelEl, index) => { + const providerId = providerIds[index]; + const iframe = panelEl.querySelector('iframe'); + const fakeWindow = { + marker: providerId, + postMessage: vi.fn(), + }; + Object.defineProperty(iframe, 'contentWindow', { + configurable: true, + value: fakeWindow, + }); + iframe.focus = vi.fn(); + handleByProvider[providerId] = { + providerId, + panelId: panelEl.id, + panelEl, + iframe, + fakeWindow, + }; + }); + + return { mod, handleByProvider }; + } + + it('switches Gemini panel to /u/1/app, persists geminiAccountIndex, and syncs on in-frame /u/ navigation', async () => { + const { handleByProvider } = await bootMultiPanel(['gemini', 'chatgpt']); + const geminiHandle = handleByProvider.gemini; + const chatgptHandle = handleByProvider.chatgpt; + + const accountSelect = geminiHandle.panelEl.querySelector('.panel-gemini-account-select'); + expect(accountSelect).not.toBeNull(); + expect(chatgptHandle.panelEl.querySelector('.panel-gemini-account-select')).toBeNull(); + expect(accountSelect.value).toBe(''); + expect(geminiHandle.iframe.getAttribute('src')).toBe('https://gemini.google.com'); + + accountSelect.value = '1'; + accountSelect.dispatchEvent(new Event('change', { bubbles: true })); + + await vi.waitFor(() => { + expect(chrome.storage.sync.set).toHaveBeenCalledWith({ geminiAccountIndex: 1 }); + }); + expect(geminiHandle.iframe.getAttribute('src')).toBe('https://gemini.google.com/u/1/app'); + + // Simulate user switching to /u/2 inside the Gemini iframe + window.dispatchEvent( + new MessageEvent('message', { + data: { + type: 'PANELIZE_PROVIDER_LOCATION', + context: 'multi-panel-provider-status', + provider: 'gemini', + url: 'https://gemini.google.com/u/2/app?pageId=none', + }, + source: geminiHandle.fakeWindow, + origin: 'https://gemini.google.com', + }) + ); + + await vi.waitFor(() => { + expect(accountSelect.value).toBe('2'); + }); + expect(chrome.storage.sync.set).toHaveBeenCalledWith({ geminiAccountIndex: 2 }); + + // Open in new tab falls back to /u/2/app when on landing page + geminiHandle.panelEl.querySelector('.open-provider-top-level-btn').click(); + await vi.waitFor(() => { + expect(chrome.tabs.create).toHaveBeenCalledWith({ + url: 'https://gemini.google.com/u/2/app', + }); + }); + }); + + it('re-targets all panels on Send All after a partial image fill failure while Retry Failed targets only failed panels', async () => { + const { mod, handleByProvider } = await bootMultiPanel(['deepseek', 'kimi']); + const deepseek = handleByProvider.deepseek; + const kimi = handleByProvider.kimi; + + // Auto-reply to fill action messages from each fake panel window + let kimiShouldSucceed = false; + deepseek.fakeWindow.postMessage.mockImplementation((msg) => { + if (msg?.type === 'INJECT_TEXT_WITH_IMAGES') { + queueMicrotask(() => { + window.dispatchEvent( + new MessageEvent('message', { + data: { + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: msg.requestId, + provider: 'deepseek', + action: 'fill', + status: 'succeeded', + succeededImageIds: (msg.fallbackImages || msg.images).map((i) => i.id), + }, + source: deepseek.fakeWindow, + origin: 'https://chat.deepseek.com', + }) + ); + }); + } + }); + kimi.fakeWindow.postMessage.mockImplementation((msg) => { + if (msg?.type === 'INJECT_TEXT_WITH_IMAGES') { + // Kimi has two origins (`www.kimi.com` and `kimi.com`); respond once per requestId + if (kimi.fakeWindow._lastAckedRequestId === msg.requestId) return; + kimi.fakeWindow._lastAckedRequestId = msg.requestId; + queueMicrotask(() => { + window.dispatchEvent( + new MessageEvent('message', { + data: { + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: msg.requestId, + provider: 'kimi', + action: 'fill', + status: kimiShouldSucceed ? 'succeeded' : 'failed', + ...(kimiShouldSucceed ? {} : { reason: 'preview-timeout' }), + succeededImageIds: kimiShouldSucceed + ? (msg.fallbackImages || msg.images).map((i) => i.id) + : [], + }, + source: kimi.fakeWindow, + origin: 'https://www.kimi.com', + }) + ); + }); + } + }); + + // Attach an image via FileReader + const fileInput = document.getElementById('image-file-input'); + const file = new File([new Uint8Array([137, 80, 78, 71])], 'chart.png', { type: 'image/png' }); + const origFileReader = globalThis.FileReader; + globalThis.FileReader = class MockFileReader { + readAsDataURL() { + this.result = SAMPLE_PNG_DATA_URL; + if (this.onload) this.onload({ target: { result: SAMPLE_PNG_DATA_URL } }); + } + }; + try { + Object.defineProperty(fileInput, 'files', { configurable: true, value: [file] }); + fileInput.dispatchEvent(new Event('change', { bubbles: true })); + } finally { + globalThis.FileReader = origFileReader; + } + + await vi.waitFor(() => { + expect(document.querySelectorAll('.image-preview-item')).toHaveLength(1); + }); + + // Pass 1: Send All -> DeepSeek succeeds, Kimi fails + await mod.broadcastMessage('Analyze this chart', true); + expect(document.getElementById('send-status').textContent).toBe('Filled 1/2; 1 failed'); + + deepseek.fakeWindow.postMessage.mockClear(); + kimi.fakeWindow.postMessage.mockClear(); + + // Pass 2: Retry Failed (autoSubmit = false) -> ONLY targets Kimi, NOT DeepSeek + await mod.broadcastMessage('Analyze this chart', false); + expect(deepseek.fakeWindow.postMessage).not.toHaveBeenCalled(); + expect(kimi.fakeWindow.postMessage).toHaveBeenCalled(); + + deepseek.fakeWindow.postMessage.mockClear(); + kimi.fakeWindow.postMessage.mockClear(); + + // Pass 3: User deleted DeepSeek's prompt and clicks Send All (autoSubmit = true) again! + // Must reach DeepSeek too with fallbackImages so cleared DeepSeek is re-populated. + kimiShouldSucceed = true; + await mod.broadcastMessage('Analyze this chart', true); + expect(deepseek.fakeWindow.postMessage).toHaveBeenCalledTimes(1); + const deepseekPayload = deepseek.fakeWindow.postMessage.mock.calls[0][0]; + expect(deepseekPayload).toMatchObject({ + type: 'INJECT_TEXT_WITH_IMAGES', + text: 'Analyze this chart', + images: [], + retry: true, + }); + expect(deepseekPayload.fallbackImages).toHaveLength(1); + expect(document.getElementById('send-status').textContent).toBe('Filled 2 inputs'); + }); +}); diff --git a/tests/gemini-content-script.test.js b/tests/gemini-content-script.test.js index b34b83a..d16fd36 100644 --- a/tests/gemini-content-script.test.js +++ b/tests/gemini-content-script.test.js @@ -139,4 +139,40 @@ describe('Gemini content script integration', () => { expect(sendClickSpy).not.toHaveBeenCalled(); expect(uploadClickSpy).not.toHaveBeenCalled(); }); + + it('intercepts same-origin /u/1/app?pageId=none target="_blank" account links inside Multi-Panel frames while leaving external links alone', () => { + const fakeHost = { postMessage: vi.fn() }; + Object.defineProperty(window, 'parent', { configurable: true, value: fakeHost }); + Object.defineProperty(window, 'top', { configurable: true, value: fakeHost }); + + const assignSpy = vi.spyOn(window.location, 'assign').mockImplementation(() => {}); + document.body.innerHTML = ` + Account 1 + Sign out + `; + + const accountLink = document.getElementById('gemini-u1-link'); + const accountClick = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 }); + accountLink.dispatchEvent(accountClick); + + expect(accountClick.defaultPrevented).toBe(true); + expect(assignSpy).toHaveBeenCalledWith('https://gemini.google.com/u/1/app?pageId=none'); + + assignSpy.mockClear(); + const externalLink = document.getElementById('gemini-external-link'); + const externalClick = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 }); + externalLink.dispatchEvent(externalClick); + + expect(externalClick.defaultPrevented).toBe(false); + expect(assignSpy).not.toHaveBeenCalled(); + }); + + it('preserves the active /u/ account prefix on Gemini NEW_CHAT URL fallback', () => { + window.happyDOM.setURL('https://gemini.google.com/u/1/app/conv-abc123'); + createGeminiDom(); + + dispatchMultiPanelMessage({ type: 'NEW_CHAT', context: 'multi-panel' }); + + expect(window.location.href).toBe('https://gemini.google.com/u/1/app'); + }); }); diff --git a/tests/provider-image-upload-content-script.test.js b/tests/provider-image-upload-content-script.test.js index 0bd3988..20332f5 100644 --- a/tests/provider-image-upload-content-script.test.js +++ b/tests/provider-image-upload-content-script.test.js @@ -747,4 +747,125 @@ describe('provider image upload adapters', () => { succeededImageIds: [], }, EXTENSION_ORIGIN); }); + + it('re-uploads fallbackImages and re-injects text when a DeepSeek composer was cleared before Send All retry', async () => { + window.happyDOM.setURL('https://chat.deepseek.com/'); + const { composer, uploadedNames } = createDeepSeekDom(); + const textarea = composer.querySelector('textarea'); + + // User deleted DeepSeek's text and attachments before clicking Send All again + textarea.value = ''; + composer.querySelector('#deepseek-previews').innerHTML = ''; + + dispatchMultiPanelMessage({ + type: 'INJECT_TEXT_WITH_IMAGES', + context: 'multi-panel', + images: [], + fallbackImages: SAMPLE_IMAGES, + text: 'Restored DeepSeek prompt', + autoSubmit: false, + requestId: 'deepseek-cleared-retry-req', + retry: true, + }); + await vi.advanceTimersByTimeAsync(4500); + + expect(uploadedNames).toEqual(['sample-one.png', 'sample-two.png']); + expect(textarea.value).toBe('Restored DeepSeek prompt'); + expect(window.parent.postMessage).toHaveBeenCalledWith({ + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: 'deepseek-cleared-retry-req', + provider: 'deepseek', + action: 'fill', + status: 'succeeded', + succeededImageIds: ['sample-one-id', 'sample-two-id'], + }, EXTENSION_ORIGIN); + }); + + it('does not duplicate uploads or text when fallbackImages are passed to an untouched DeepSeek composer', async () => { + window.happyDOM.setURL('https://chat.deepseek.com/'); + const { composer, uploadedNames } = createDeepSeekDom(); + const textarea = composer.querySelector('textarea'); + textarea.value = 'Already filled prompt'; + + dispatchMultiPanelMessage({ + type: 'INJECT_TEXT_WITH_IMAGES', + context: 'multi-panel', + images: [], + fallbackImages: SAMPLE_IMAGES, + text: 'Already filled prompt', + autoSubmit: false, + requestId: 'deepseek-untouched-retry-req', + retry: true, + }); + await finishSuccessfulInjection(); + + expect(uploadedNames).toEqual([]); + expect(textarea.value).toBe('Already filled prompt'); + expect(window.parent.postMessage).toHaveBeenCalledWith({ + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: 'deepseek-untouched-retry-req', + provider: 'deepseek', + action: 'fill', + status: 'succeeded', + succeededImageIds: ['sample-one-id', 'sample-two-id'], + }, EXTENSION_ORIGIN); + }); + + it('injects all 10 lines into Kimi Lexical editor via paste without premature click on disabled send wrapper', async () => { + window.happyDOM.setURL('https://www.kimi.com/'); + const { composer, sendButton } = createKimiDom(); + const editor = composer.querySelector('.chat-input-editor'); + editor.setAttribute('data-lexical-editor', 'true'); + markVisible(editor); + + // Add a non-disabled inner send-icon wrapper inside a disabled `.send-button-container.disabled` + sendButton.classList.add('disabled'); + const straySendIcon = document.createElement('div'); + straySendIcon.className = 'send-icon-wrapper'; + markVisible(straySendIcon); + sendButton.appendChild(straySendIcon); + + const strayClickSpy = vi.fn(); + const realSendClickSpy = vi.fn(); + straySendIcon.addEventListener('click', strayClickSpy); + sendButton.addEventListener('click', (event) => { + if (!sendButton.classList.contains('disabled') && event.target === sendButton) { + realSendClickSpy(); + } + }); + + // Simulate Lexical's paste handler preserving all 10 lines atomically + editor.addEventListener('paste', (event) => { + const pasted = event.clipboardData?.getData('text/plain') || ''; + event.preventDefault(); + Promise.resolve().then(() => { + editor.textContent = pasted; + setTimeout(() => { + sendButton.classList.remove('disabled'); + }, 1000); + }); + }); + + const tenLinePrompt = Array.from({ length: 10 }, (_, idx) => `Line ${idx + 1}: Kimi test payload`).join('\n'); + + dispatchMultiPanelMessage({ + type: 'INJECT_TEXT', + context: 'multi-panel', + text: tenLinePrompt, + autoSubmit: true, + }); + + await vi.advanceTimersByTimeAsync(850); + expect(editor.textContent.split('\n')).toHaveLength(10); + expect(editor.textContent).toBe(tenLinePrompt); + // Must not click `.send-icon-wrapper` while `.send-button-container` is still `.disabled` + expect(strayClickSpy).not.toHaveBeenCalled(); + expect(realSendClickSpy).not.toHaveBeenCalled(); + + // Once Lexical enables `.send-button-container` at 1000ms, retry clicks it cleanly + await vi.advanceTimersByTimeAsync(500); + expect(realSendClickSpy).toHaveBeenCalledTimes(1); + }); }); diff --git a/tests/provider-open-url.test.js b/tests/provider-open-url.test.js index 5e6ea6e..e0f8121 100644 --- a/tests/provider-open-url.test.js +++ b/tests/provider-open-url.test.js @@ -13,6 +13,7 @@ describe('provider open URL helpers', () => { expect(isProviderCurrentUrl('chatgpt', 'https://chatgpt.com/c/abc123')).toBe(true); expect(isProviderCurrentUrl('claude', 'https://claude.ai/chat/abc123')).toBe(true); expect(isProviderCurrentUrl('gemini', 'https://gemini.google.com/app/abc123')).toBe(true); + expect(isProviderCurrentUrl('gemini', 'https://gemini.google.com/u/1/app/abc123')).toBe(true); expect(isProviderCurrentUrl('grok', 'https://grok.com/c/abc123')).toBe(true); expect(isProviderCurrentUrl('deepseek', 'https://chat.deepseek.com/a/chat/s/abc123')).toBe(true); expect(isProviderCurrentUrl('kimi', 'https://www.kimi.com/chat/abc123')).toBe(true); @@ -22,6 +23,7 @@ describe('provider open URL helpers', () => { expect(isProviderCurrentUrl('zai-global', 'https://chat.z.ai/c/abc123')).toBe(true); expect(isProviderCurrentUrl('yuanbao', 'https://yuanbao.tencent.com/chat/agent123/chat456')).toBe(true); expect(isProviderCurrentUrl('aistudio', 'https://aistudio.google.com/prompts/1abcDEF234')).toBe(true); + expect(isProviderCurrentUrl('aistudio', 'https://aistudio.google.com/u/1/prompts/1abcDEF234')).toBe(true); }); it('accepts current Google pages for both AI Mode and Search', () => { @@ -87,5 +89,16 @@ describe('provider open URL helpers', () => { 'https://aistudio.google.com/prompts/new_chat?temporary=true' ) ).toBe('https://aistudio.google.com/prompts/new_chat'); + expect(isProviderCurrentUrl('gemini', 'https://gemini.google.com/u/1/app')).toBe(false); + expect(isProviderCurrentUrl('aistudio', 'https://aistudio.google.com/u/1/prompts/new_chat')).toBe(false); + expect( + getProviderOpenUrl( + getProviderById('gemini'), + 'https://gemini.google.com/u/1/app?pageId=none' + ) + ).toBe('https://gemini.google.com/u/1/app'); + expect( + getProviderFallbackUrl(getProviderById('gemini'), null, { geminiAccountIndex: 1 }) + ).toBe('https://gemini.google.com/u/1/app'); }); }); From e480d8372d9389d6d6cbbeb3e5ec8bcd3a15c50c Mon Sep 17 00:00:00 2001 From: Wenhao Date: Sat, 21 Nov 2026 21:15:20 +0800 Subject: [PATCH 2/2] fix(multi-panel): isolate per-panel Gemini accounts and tighten Send All fallback handling - Scope Gemini account index per panel so side-by-side Gemini panels do not clobber or reload each other while keeping sync storage as default for new panels - Revert out-of-scope AI Studio and Google account URL hunks and narrow Gemini _blank interception to genuine account-switch links - Report attemptedImageIds on failed cleared-composer fallback retries and support fallbackImages on Custom Web and Custom API panels - Make inputEndsWithText block-line aware, scope composer attachment checks, narrow DeepSeek icon send selectors, and track DeepSeek preview baselines independently Refs: #118 --- api-panel/api-panel.js | 27 ++- content-scripts/custom-provider-driver.js | 42 +++- .../text-injection-all-providers.js | 213 ++++++++++++++---- modules/panel-action-results.js | 11 +- modules/panel-message-contract.js | 1 + modules/provider-open-url.js | 14 +- multi-panel/multi-panel.js | 187 ++++++++++----- tests/custom-api-options-and-panel.test.js | 67 ++++++ tests/custom-provider-driver.test.js | 109 +++++++++ tests/deepseek-content-script.test.js | 37 +++ ...118-multi-account-and-send-all.e2e.test.js | 37 +-- tests/gemini-account.test.js | 139 ++++++++++++ tests/gemini-content-script.test.js | 17 ++ ...ovider-image-upload-content-script.test.js | 75 ++++++ tests/provider-open-url.test.js | 2 - 15 files changed, 825 insertions(+), 153 deletions(-) diff --git a/api-panel/api-panel.js b/api-panel/api-panel.js index 6b873bd..464ed49 100644 --- a/api-panel/api-panel.js +++ b/api-panel/api-panel.js @@ -630,16 +630,33 @@ export function initApiPanel({ rootWindow = window, rootDocument = document } = break; } case 'INJECT_TEXT_WITH_IMAGES': { - if (typeof data.text === 'string') { + const fallbackImages = Array.isArray(data.fallbackImages) ? data.fallbackImages : []; + const fallbackIds = fallbackImages + .map((img) => img?.id) + .filter((id) => typeof id === 'string'); + const isClearedOnRetry = Boolean( + data.retry && + fallbackImages.length > 0 && + composerInputEl.value.trim().length === 0 && + stagedImages.length === 0 + ); + if (typeof data.text === 'string' && (data.text.length > 0 || !data.retry || isClearedOnRetry)) { composerInputEl.value = data.text; } - const incomingImages = Array.isArray(data.images) ? data.images : []; - const succeededIds = mergeIncomingImages(incomingImages); + const incomingImages = isClearedOnRetry + ? fallbackImages + : (Array.isArray(data.images) ? data.images : []); + const succeededIds = incomingImages.length === 0 && data.retry && fallbackIds.length > 0 + ? fallbackIds + : mergeIncomingImages(incomingImages); + const expectedCount = incomingImages.length === 0 && data.retry && fallbackIds.length > 0 + ? fallbackIds.length + : incomingImages.length; syncComposerControls(); if (data.action === 'fill') { - postFillActionResult(data.requestId, incomingImages.length, succeededIds); + postFillActionResult(data.requestId, expectedCount, succeededIds); } - if (data.autoSubmit && succeededIds.length === incomingImages.length) { + if (data.autoSubmit && succeededIds.length === expectedCount) { submitCurrentPayload(); } break; diff --git a/content-scripts/custom-provider-driver.js b/content-scripts/custom-provider-driver.js index 655165c..f370455 100644 --- a/content-scripts/custom-provider-driver.js +++ b/content-scripts/custom-provider-driver.js @@ -406,6 +406,9 @@ if (Array.isArray(result.succeededImageIds)) { message.succeededImageIds = result.succeededImageIds; } + if (!result.ok && Array.isArray(result.attemptedImageIds)) { + message.attemptedImageIds = result.attemptedImageIds; + } if (!result.ok) { message.reason = result.reason || ACTION_FAILURE_REASONS.INJECTION_ERROR; } @@ -1865,9 +1868,14 @@ // ===== Message Dispatch ===== async function handleFillWithResult(eventData, providerId) { - const { text, images, autoSubmit, requestId, retry = false } = eventData; + const { text, images, fallbackImages, autoSubmit, requestId, retry = false } = eventData; const hasImages = Array.isArray(images) && images.length > 0; + const normalizedFallbackImages = Array.isArray(fallbackImages) ? fallbackImages : []; + const fallbackSucceededIds = normalizedFallbackImages + .map((img) => img?.id) + .filter((id) => typeof id === 'string'); const hasText = typeof text === 'string' && text.length > 0; + const hasFallbackRetry = Boolean(retry && normalizedFallbackImages.length > 0); if (requestId && providerId) { startUserInteractionTracking(requestId, providerId); @@ -1884,7 +1892,7 @@ return; } - if (!hasImages && !hasText) { + if (!hasImages && !hasText && !hasFallbackRetry) { postActionResult(requestId, providerId, { ok: false, reason: ACTION_FAILURE_REASONS.INJECTION_ERROR, @@ -1893,7 +1901,7 @@ return; } - const composer = await findComposerWithRetry(hasImages ? 600 : 1000); + const composer = await findComposerWithRetry(hasImages || hasFallbackRetry ? 600 : 1000); if (!composer) { postActionResult(requestId, providerId, { ok: false, @@ -1903,16 +1911,31 @@ return; } - let succeededImageIds = []; - if (hasImages) { - const uploadResult = await uploadImagesToComposer(composer, images); + const composerClearedOnRetry = Boolean( + hasFallbackRetry && + isComposerEmpty(composer) && + inspectComposerAttachments(composer).count === 0 + ); + const effectiveImages = composerClearedOnRetry + ? normalizedFallbackImages + : (Array.isArray(images) ? images : []); + const effectiveRetry = composerClearedOnRetry ? false : Boolean(retry); + const failureAttemptedIds = composerClearedOnRetry + ? effectiveImages.map((img) => img?.id).filter((id) => typeof id === 'string') + : undefined; + + let succeededImageIds = effectiveImages.length === 0 && hasFallbackRetry + ? fallbackSucceededIds + : []; + if (effectiveImages.length > 0) { + const uploadResult = await uploadImagesToComposer(composer, effectiveImages); succeededImageIds = uploadResult.succeededImageIds || []; if (!uploadResult.ok) { if (hasText) { const refreshedComposer = composer.isConnected ? composer : findComposerElement(); if (refreshedComposer) { await injectTextIntoComposer(refreshedComposer, text, { - skipIfAlreadyPresent: Boolean(retry), + skipIfAlreadyPresent: effectiveRetry, }); } } @@ -1920,6 +1943,7 @@ ok: false, reason: uploadResult.reason || ACTION_FAILURE_REASONS.INJECTION_ERROR, succeededImageIds, + attemptedImageIds: failureAttemptedIds, }); return; } @@ -1932,17 +1956,19 @@ ok: false, reason: ACTION_FAILURE_REASONS.CONTROL_NOT_FOUND, succeededImageIds, + attemptedImageIds: failureAttemptedIds, }); return; } const injected = await injectTextIntoComposer(activeComposer, text, { - skipIfAlreadyPresent: Boolean(retry), + skipIfAlreadyPresent: effectiveRetry, }); if (!injected) { postActionResult(requestId, providerId, { ok: false, reason: ACTION_FAILURE_REASONS.INJECTION_ERROR, succeededImageIds, + attemptedImageIds: failureAttemptedIds, }); return; } diff --git a/content-scripts/text-injection-all-providers.js b/content-scripts/text-injection-all-providers.js index 95c9196..f6b9a75 100644 --- a/content-scripts/text-injection-all-providers.js +++ b/content-scripts/text-injection-all-providers.js @@ -327,10 +327,10 @@ deepseek: [ // Current site: a design-system div button that is disabled by class. 'div[role="button"].ds-button--primary.ds-button--filled:not(.ds-button--disabled)', - '.ds-icon-button[role="button"]:not([aria-disabled="true"]):not(.ds-icon-button--disabled)', - 'button.ds-icon-button:not([aria-disabled="true"]):not(.ds-icon-button--disabled)', 'button[aria-label="Send"]', - 'button[type="submit"]' + 'button[type="submit"]', + '.ds-icon-button[role="button"]:not([aria-disabled="true"]):not(.ds-icon-button--disabled):has(svg path[d*="M8.3125"])', + 'button.ds-icon-button:not([aria-disabled="true"]):not(.ds-icon-button--disabled):has(svg path[d*="M8.3125"])' ], kimi: [ // Priority: clickable send button containers that are not disabled @@ -707,6 +707,10 @@ message.succeededImageIds = result.succeededImageIds; } + if (!result.ok && Array.isArray(result?.attemptedImageIds)) { + message.attemptedImageIds = result.attemptedImageIds; + } + if (!result.ok) { message.reason = result.reason || IMAGE_INJECTION_REASONS.INJECTION_ERROR; } @@ -744,27 +748,32 @@ return match ? `/u/${match[1]}` : ''; } - function isSameOriginGoogleAccountNavigationUrl(provider, targetUrl) { + function isSameOriginGeminiAccountSwitchUrl(targetUrl) { if (!targetUrl || targetUrl.origin !== window.location.origin) { return false; } - if (provider === 'gemini' || provider === 'aistudio') { - return /^\/u\/\d+(?:\/|$)/.test(targetUrl.pathname) || targetUrl.searchParams.has('authuser'); + if (targetUrl.searchParams.has('authuser')) { + return true; } - if (provider === 'google') { - return targetUrl.searchParams.has('authuser'); + const match = /^\/u\/(\d+)(?:\/|$)/.exec(targetUrl.pathname); + if (!match) { + return false; } - return false; + const strippedPath = targetUrl.pathname.replace(/^\/u\/\d+(?=\/|$)/, '') || '/'; + if (strippedPath === '/' || strippedPath === '/app' || strippedPath === '/app/') { + return true; + } + + return `/u/${match[1]}` !== getCurrentGoogleAccountPrefix(); } /** - * Keeps same-origin Google multi-account links (`/u//...`, `?authuser=`) + * Keeps same-origin Gemini Google account-switch links (`/u//app`, `?authuser=`) * inside the embedded panel iframe when the page marks them `target="_blank"` - * or `target="_top"`, instead of opening an external tab or hitting sandbox - * top-navigation restrictions. + * or `target="_top"`, without hijacking ordinary same-account conversation links. */ function setupSameOriginAccountNavigation() { document.addEventListener('click', (event) => { @@ -784,7 +793,7 @@ } const provider = detectProvider(); - if (provider !== 'gemini' && provider !== 'aistudio' && provider !== 'google') { + if (provider !== 'gemini') { return; } @@ -808,7 +817,7 @@ return; } - if (!isSameOriginGoogleAccountNavigationUrl(provider, resolvedUrl)) { + if (!isSameOriginGeminiAccountSwitchUrl(resolvedUrl)) { return; } @@ -1808,14 +1817,21 @@ console.log('[Text Injection] Attempting to click send button for provider:', provider); - // ChatGPT's send button lives in the composer's form; searching only there - // keeps another form's Send (e.g. an inline edit) from being clicked. + // ChatGPT's send button lives in the composer's form; DeepSeek's lives in the + // composer ancestor. Scoping the search keeps unrelated toolbar/inline buttons + // from being clicked. const searchRoot = provider === 'chatgpt' ? getChatgptComposer()?.findForm() || document - : document; + : provider === 'deepseek' + ? findClosestAncestorContaining(findProviderInput('deepseek'), 'div[role="button"], button') || document + : document; - // Try each selector - for (const selector of selectors) { + const hasDisabledPrimaryDeepSeekSend = provider === 'deepseek' && Boolean( + searchRoot.querySelector('div[role="button"].ds-button--primary.ds-button--filled.ds-button--disabled') + ); + + // Try each selector (unless DeepSeek's primary send button is present and disabled) + for (const selector of hasDisabledPrimaryDeepSeekSend ? [] : selectors) { try { const elements = searchRoot.querySelectorAll(selector); console.log(`[Text Injection] Found ${elements.length} elements with selector:`, selector); @@ -2179,10 +2195,9 @@ function handleAiStudioNewChat(options = {}) { const shouldUseTemporaryChat = options?.temporaryChat === true || (options?.temporaryChat !== false && isTemporaryChatAlreadyEnabled('aistudio')); - const accountPrefix = getCurrentGoogleAccountPrefix(); - const targetUrl = accountPrefix - ? `https://aistudio.google.com${accountPrefix}/prompts/new_chat${shouldUseTemporaryChat ? '?temporary=true' : ''}` - : (shouldUseTemporaryChat ? AISTUDIO_TEMP_CHAT_URL : AISTUDIO_NEW_CHAT_URL); + const targetUrl = shouldUseTemporaryChat + ? AISTUDIO_TEMP_CHAT_URL + : AISTUDIO_NEW_CHAT_URL; console.log('[Text Injection] Navigating AI Studio to new chat URL:', targetUrl); window.location.href = targetUrl; return true; @@ -2617,11 +2632,86 @@ // ===== Image Injection Functions ===== + const CONTENTEDITABLE_BLOCK_TAGS = new Set([ + 'P', 'DIV', 'LI', 'PRE', 'BLOCKQUOTE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' + ]); + + function readContentEditableBlockText(root) { + if (!root) { + return ''; + } + + const extractInline = (node) => { + if (!node) return ''; + if (node.nodeType === 3) { + return node.nodeValue || ''; + } + if (node.nodeType !== 1) { + return ''; + } + if (node.tagName === 'BR') { + return '\n'; + } + let out = ''; + for (const child of node.childNodes) { + out += extractInline(child); + } + return out; + }; + + const children = [...(root.childNodes || [])]; + const hasBlockChild = children.some( + child => child.nodeType === 1 && CONTENTEDITABLE_BLOCK_TAGS.has(child.tagName) + ); + if (!hasBlockChild) { + return extractInline(root).replace(/\r\n/g, '\n'); + } + + const lines = []; + let inlineBuffer = ''; + const flushInline = () => { + if (inlineBuffer.length > 0) { + lines.push(inlineBuffer.replace(/\n$/, '')); + inlineBuffer = ''; + } + }; + + for (const child of children) { + if (child.nodeType === 1 && CONTENTEDITABLE_BLOCK_TAGS.has(child.tagName)) { + flushInline(); + const rawBlock = extractInline(child).replace(/\r\n/g, '\n'); + // Empty paragraph `


` represents a single blank line `''` + lines.push(rawBlock === '\n' ? '' : rawBlock.replace(/\n$/, '')); + } else { + inlineBuffer += extractInline(child); + } + } + flushInline(); + return lines.join('\n'); + } + // Helper function to inject text into provider's input field function inputEndsWithText(element, text) { - const isFormControl = element?.tagName === 'TEXTAREA' || element?.tagName === 'INPUT'; - const currentText = isFormControl ? element.value : element?.textContent; - return typeof currentText === 'string' && currentText.endsWith(text); + if (!element || typeof text !== 'string') { + return false; + } + const isFormControl = element.tagName === 'TEXTAREA' || element.tagName === 'INPUT'; + const currentText = isFormControl ? element.value : element.textContent; + if (typeof currentText === 'string' && currentText.endsWith(text)) { + return true; + } + if (isFormControl) { + return false; + } + const normalizedTarget = text.replace(/\r\n/g, '\n').trimEnd(); + if (!normalizedTarget) { + return false; + } + const blockText = readContentEditableBlockText(element).trimEnd(); + if (blockText.endsWith(normalizedTarget)) { + return true; + } + return blockText.replace(/\n+/g, '\n').endsWith(normalizedTarget.replace(/\n+/g, '\n')); } function injectText( @@ -2663,6 +2753,16 @@ return false; } + function getComposerRootForAttachmentCheck(provider, input) { + if (provider === 'deepseek') return getDeepSeekComposer(); + if (provider === 'kimi') return getKimiComposer(); + if (provider === 'grok') return getGrokComposer(); + if (provider === 'yuanbao') return getYuanbaoComposer(); + return input?.closest?.('form, ms-prompt-box, .input-area-container, .chat-editor, #chat-box') || + input?.parentElement || + null; + } + function isProviderComposerCleared(provider, candidateImages = [], providerMode = null) { const input = provider === 'google' ? findGoogleInput(providerMode) @@ -2677,26 +2777,27 @@ return false; } - if ((candidateImages || []).some(img => img?.name && countFilenamePreviewEvidence(document, img.name) > 0)) { + const composerRoot = getComposerRootForAttachmentCheck(provider, input); + if ( + composerRoot && + (candidateImages || []).some(img => img?.name && countFilenamePreviewEvidence(composerRoot, img.name) > 0) + ) { return false; } if (provider === 'deepseek') { - const composer = getDeepSeekComposer(); - if (composer && composer.querySelectorAll('img[src^="blob:"]').length > 0) { + if (composerRoot && composerRoot.querySelectorAll('img[src^="blob:"]').length > 0) { return false; } } else if (provider === 'kimi') { - const composer = getKimiComposer(); if ( - composer && - (countKimiAttachmentPreviews(composer) > 0 || countKimiPendingAttachmentPreviews(composer) > 0) + composerRoot && + (countKimiAttachmentPreviews(composerRoot) > 0 || countKimiPendingAttachmentPreviews(composerRoot) > 0) ) { return false; } } else if (provider === 'grok') { - const composer = getGrokComposer(); - const attachmentList = composer?.querySelector('[role="list"][aria-label="Conversation attachments"]'); + const attachmentList = composerRoot?.querySelector('[role="list"][aria-label="Conversation attachments"]'); if ((attachmentList?.children.length || 0) > 0) { return false; } @@ -2750,6 +2851,9 @@ ); const effectiveImages = composerClearedOnRetry ? normalizedFallbackImages : images; const effectiveRetry = composerClearedOnRetry ? false : retry; + const failureAttemptedIds = composerClearedOnRetry + ? effectiveImages.map(img => img?.id).filter(id => typeof id === 'string') + : undefined; if (!effectiveImages || effectiveImages.length === 0) { if (retry && text && text.trim()) { @@ -2830,7 +2934,8 @@ const firstFailure = imageInjectionResults.find(result => !result.ok); return createImageInjectionFailure( firstFailure?.reason || IMAGE_INJECTION_REASONS.INJECTION_ERROR, - succeededImageIds + succeededImageIds, + failureAttemptedIds ); } // If no text but autoSubmit is true, click send button @@ -2842,21 +2947,23 @@ const firstFailure = imageInjectionResults.find(result => !result.ok); return createImageInjectionFailure( firstFailure?.reason || IMAGE_INJECTION_REASONS.INJECTION_ERROR, - succeededImageIds + succeededImageIds, + failureAttemptedIds ); } if (!textInjected) { return createImageInjectionFailure( IMAGE_INJECTION_REASONS.CONTROL_NOT_FOUND, - succeededImageIds + succeededImageIds, + failureAttemptedIds ); } return createImageInjectionSuccess(succeededImageIds); } catch (error) { console.error('[Image Injection] Error:', error); - return createImageInjectionFailure(IMAGE_INJECTION_REASONS.INJECTION_ERROR, []); + return createImageInjectionFailure(IMAGE_INJECTION_REASONS.INJECTION_ERROR, [], failureAttemptedIds); } } @@ -2864,8 +2971,13 @@ return { ok: true, succeededImageIds }; } - function createImageInjectionFailure(reason, succeededImageIds = []) { - return { ok: false, reason, succeededImageIds }; + function createImageInjectionFailure(reason, succeededImageIds = [], attemptedImageIds = undefined) { + return { + ok: false, + reason, + succeededImageIds, + ...(Array.isArray(attemptedImageIds) ? { attemptedImageIds } : {}) + }; } function normalizeImageInjectionResult(result) { @@ -3299,21 +3411,24 @@ } // DeepSeek renders attachment previews beside the composer controls rather - // than consistently inside the nearest file-input ancestor; also count blob - // thumbnail images inside the composer when narrow chips truncate filenames. - const countDeepSeekPreviews = () => Math.max( - countFilenamePreviewEvidence(document, imageData.name), - composer.querySelectorAll('img[src^="blob:"]').length - ); - const previousCount = countDeepSeekPreviews(); + // than consistently inside the nearest file-input ancestor; track filename + // and composer blob thumbnail baselines independently so historical chat + // attachments with the same filename never mask a newly uploaded preview. + const previousFilenameCount = countFilenamePreviewEvidence(document, imageData.name); + const previousBlobCount = composer.querySelectorAll('img[src^="blob:"]').length; if (!assignFilesToInput(fileInput, [file])) { return createImageInjectionFailure(IMAGE_INJECTION_REASONS.INJECTION_ERROR); } dispatchFileInputEvents(fileInput); const accepted = await waitForPreviewIncrease( - countDeepSeekPreviews, - previousCount + () => ( + countFilenamePreviewEvidence(document, imageData.name) > previousFilenameCount || + composer.querySelectorAll('img[src^="blob:"]').length > previousBlobCount + ? 1 + : 0 + ), + 0 ); return accepted ? createImageInjectionSuccess() diff --git a/modules/panel-action-results.js b/modules/panel-action-results.js index 782705c..85b5999 100644 --- a/modules/panel-action-results.js +++ b/modules/panel-action-results.js @@ -200,7 +200,16 @@ export function createPanelActionResultWaiter({ settle({ ...createFailure(panel, event.data.reason), - succeededImageIds: normalizeSucceededImageIds(event.data.succeededImageIds, expectedImageIds, false) + succeededImageIds: normalizeSucceededImageIds(event.data.succeededImageIds, expectedImageIds, false), + ...(Array.isArray(event.data.attemptedImageIds) + ? { + attemptedImageIds: normalizeSucceededImageIds( + event.data.attemptedImageIds, + expectedImageIds, + false + ) + } + : {}) }); }; diff --git a/modules/panel-message-contract.js b/modules/panel-message-contract.js index 2b3a795..e5cebd3 100644 --- a/modules/panel-message-contract.js +++ b/modules/panel-message-contract.js @@ -190,6 +190,7 @@ export const FRAME_TO_HOST_MESSAGES = Object.freeze([ 'action', 'status', 'succeededImageIds', + 'attemptedImageIds', 'reason' ], senderFiles: [ diff --git a/modules/provider-open-url.js b/modules/provider-open-url.js index 2ddca02..f44325a 100644 --- a/modules/provider-open-url.js +++ b/modules/provider-open-url.js @@ -214,8 +214,7 @@ export function isProviderCurrentUrl(providerId, rawUrl) { url.searchParams.get('chatMode') !== 'temp' ); case 'aistudio': { - const aistudioPath = stripGoogleAccountPathPrefix(url.pathname); - const promptMatch = aistudioPath.match(/^\/prompts\/([^/]+)\/?$/); + const promptMatch = url.pathname.match(/^\/prompts\/([^/]+)\/?$/); return Boolean( promptMatch && !AISTUDIO_NON_CONVERSATION_IDS.has(promptMatch[1]) && @@ -245,16 +244,5 @@ export function getProviderOpenUrl(provider, reportedUrl = null, providerMode = } } - if (provider?.id === 'aistudio') { - const parsedReported = parseHttpUrl(reportedUrl); - const reportedAccountIndex = - parsedReported && hasAllowedProviderHost('aistudio', parsedReported) - ? extractGoogleAccountIndexFromUrl(reportedUrl) - : null; - if (reportedAccountIndex !== null) { - return `https://aistudio.google.com/u/${reportedAccountIndex}/prompts/new_chat`; - } - } - return getProviderFallbackUrl(provider, providerMode, options); } diff --git a/multi-panel/multi-panel.js b/multi-panel/multi-panel.js index 54975d1..cdb0892 100644 --- a/multi-panel/multi-panel.js +++ b/multi-panel/multi-panel.js @@ -241,6 +241,7 @@ function refreshThemeAwareProviderIcons() { } let currentGoogleProviderMode = DEFAULT_GOOGLE_PROVIDER_MODE; let currentGeminiAccountIndex = DEFAULT_GEMINI_ACCOUNT_INDEX; +let pendingRestoredPanelAccounts = null; // 提示词编辑器状态 let currentEditingPromptId = null; @@ -453,9 +454,19 @@ async function requestGrokWebSocketCookieSync() { } } -function getTemporaryChatNormalUrl(providerId) { - if (isGeminiProvider(providerId) && currentGeminiAccountIndex !== null) { - return getGeminiTemporaryChatNormalUrl(currentGeminiAccountIndex); +function getPanelGeminiAccountIndex(panel) { + if (!panel || !isGeminiProvider(panel.providerId)) { + return DEFAULT_GEMINI_ACCOUNT_INDEX; + } + return normalizeGeminiAccountIndex( + panel.geminiAccountIndex !== undefined ? panel.geminiAccountIndex : currentGeminiAccountIndex + ); +} + +function getTemporaryChatNormalUrl(providerId, panel = null) { + const geminiAccountIndex = panel ? getPanelGeminiAccountIndex(panel) : currentGeminiAccountIndex; + if (isGeminiProvider(providerId) && geminiAccountIndex !== null) { + return getGeminiTemporaryChatNormalUrl(geminiAccountIndex); } const configuredNormalUrl = getProviderTemporaryChatNormalUrl(providerId); @@ -510,7 +521,7 @@ function postNewChatToPanel(panel, { reloadUrl = null } = {}) { customApiHostBridge?.abortPanelStream(panel.id); if (!supportsInPageNewChat(panel.providerId)) { - reloadPanelIframe(panel, reloadUrl || getProviderFrameUrl(panel.providerId)); + reloadPanelIframe(panel, reloadUrl || getProviderFrameUrl(panel.providerId, panel)); return; } @@ -525,7 +536,7 @@ function postNewChatToPanel(panel, { reloadUrl = null } = {}) { }); } -function getProviderFrameUrl(providerId) { +function getProviderFrameUrl(providerId, panelOrAccountIndex = undefined) { const provider = getProviderById(providerId); if (!provider) { return ''; @@ -541,8 +552,13 @@ function getProviderFrameUrl(providerId) { return getTemporaryChatUrl(providerId); } - if (isGeminiProvider(providerId) && currentGeminiAccountIndex !== null) { - return getGeminiProviderUrl(currentGeminiAccountIndex); + const geminiAccountIndex = panelOrAccountIndex && typeof panelOrAccountIndex === 'object' + ? getPanelGeminiAccountIndex(panelOrAccountIndex) + : (panelOrAccountIndex !== undefined + ? normalizeGeminiAccountIndex(panelOrAccountIndex) + : currentGeminiAccountIndex); + if (isGeminiProvider(providerId) && geminiAccountIndex !== null) { + return getGeminiProviderUrl(geminiAccountIndex); } return isGoogleProvider(providerId) @@ -655,12 +671,16 @@ function createGeminiAccountSelectElement(accountIndex = currentGeminiAccountInd return select; } -function populatePanelHeaderRight(headerRightEl, providerId) { +function populatePanelHeaderRight( + headerRightEl, + providerId, + geminiAccountIndex = currentGeminiAccountIndex +) { const children = []; if (isGoogleProvider(providerId)) { children.push(createGoogleModeSelectElement()); } else if (isGeminiProvider(providerId)) { - children.push(createGeminiAccountSelectElement()); + children.push(createGeminiAccountSelectElement(geminiAccountIndex)); } const descriptor = getProviderDescriptor(providerId); if (descriptor?.topLevelUrl !== null) { @@ -696,23 +716,31 @@ function syncGoogleModeControls() { }); } -function syncGeminiAccountControls() { - const expectedValue = toGeminiAccountSelectValue(currentGeminiAccountIndex); - document.querySelectorAll('.panel-gemini-account-select').forEach((select) => { - if ( - expectedValue !== '' && - !Array.from(select.options).some((opt) => opt.value === expectedValue) - ) { - const extraOption = document.createElement('option'); - extraOption.value = expectedValue; - extraOption.textContent = getGeminiAccountOptionLabel(currentGeminiAccountIndex); - select.appendChild(extraOption); - } - if (select.value !== expectedValue) { - select.value = expectedValue; - } - fitPanelSelectWidth(select); - }); +function syncPanelGeminiAccountControl(panel) { + if (!panel || !isGeminiProvider(panel.providerId)) { + return; + } + const panelEl = document.getElementById(panel.id); + const select = panelEl?.querySelector('.panel-gemini-account-select'); + if (!select) { + return; + } + + const accountIndex = getPanelGeminiAccountIndex(panel); + const expectedValue = toGeminiAccountSelectValue(accountIndex); + if ( + expectedValue !== '' && + !Array.from(select.options).some((opt) => opt.value === expectedValue) + ) { + const extraOption = document.createElement('option'); + extraOption.value = expectedValue; + extraOption.textContent = getGeminiAccountOptionLabel(accountIndex); + select.appendChild(extraOption); + } + if (select.value !== expectedValue) { + select.value = expectedValue; + } + fitPanelSelectWidth(select); } function renderPanelLoadingContent(loadingEl, provider, messageText) { @@ -746,7 +774,7 @@ function reloadPanelIframe(panel, overrideUrl = null, { isRecoveryReload = false return; } - const nextUrl = overrideUrl || getProviderFrameUrl(panel.providerId); + const nextUrl = overrideUrl || getProviderFrameUrl(panel.providerId, panel); showPanelLoadingState(panelEl, provider); loadingPanelIds.add(panel.id); panel.currentUrl = null; @@ -767,7 +795,7 @@ async function openProviderTopLevel(panel) { panel.currentUrl || panel.lastReportedAllowedUrl || null, getPanelProviderMode(panel), { - geminiAccountIndex: isGeminiProvider(panel.providerId) ? currentGeminiAccountIndex : null + geminiAccountIndex: getPanelGeminiAccountIndex(panel) } ); @@ -845,7 +873,10 @@ function bindPanelHeaderActions(panelId) { }); geminiAccountSelect.addEventListener('change', async (event) => { fitPanelSelectWidth(event.target); - await updateGeminiAccountIndex(event.target.value, { persist: true, reloadPanels: true }); + await updatePanelGeminiAccountIndex(panel, event.target.value, { + persist: true, + reloadPanel: true + }); }); } } @@ -867,19 +898,23 @@ async function updateGoogleProviderMode(mode, { persist = false, reloadPanels = } } -async function updateGeminiAccountIndex( +async function updatePanelGeminiAccountIndex( + panel, accountIndex, - { persist = false, reloadPanels = false, excludePanelId = null } = {} + { persist = false, reloadPanel = false } = {} ) { const normalizedAccount = normalizeGeminiAccountIndex(accountIndex); - const accountChanged = currentGeminiAccountIndex !== normalizedAccount; + const previousPanelAccount = getPanelGeminiAccountIndex(panel); + const panelAccountChanged = previousPanelAccount !== normalizedAccount; + + if (panel && isGeminiProvider(panel.providerId)) { + panel.geminiAccountIndex = normalizedAccount; + syncPanelGeminiAccountControl(panel); + } currentGeminiAccountIndex = normalizedAccount; - syncGeminiAccountControls(); - if (reloadPanels && accountChanged) { - panels - .filter(panel => isGeminiProvider(panel.providerId) && panel.id !== excludePanelId) - .forEach(panel => reloadPanelIframe(panel)); + if (reloadPanel && panelAccountChanged && panel) { + reloadPanelIframe(panel); } if (persist) { @@ -964,14 +999,9 @@ function registerStorageChangeListener() { } if ('geminiAccountIndex' in changes) { - const nextAccount = normalizeGeminiAccountIndex(changes.geminiAccountIndex?.newValue); - if (nextAccount === currentGeminiAccountIndex) { - syncGeminiAccountControls(); - } else { - updateGeminiAccountIndex(nextAccount, { reloadPanels: true }).catch((error) => { - console.error('Error syncing Gemini account index:', error); - }); - } + currentGeminiAccountIndex = normalizeGeminiAccountIndex( + changes.geminiAccountIndex?.newValue + ); } }); } @@ -1131,7 +1161,7 @@ function startFreshChatForPanel(panel, options = {}) { } if (!supportsInPageNewChat(panel.providerId)) { - reloadPanelIframe(panel, getProviderFrameUrl(panel.providerId)); + reloadPanelIframe(panel, getProviderFrameUrl(panel.providerId, panel)); return; } @@ -1342,11 +1372,13 @@ function handleProviderStatusMessage(event) { panel.currentUrl = isProviderCurrentUrl(panel.providerId, data.url) ? data.url : null; if (isGeminiProvider(panel.providerId)) { const reportedAccountIndex = extractGoogleAccountIndexFromUrl(data.url); - if (reportedAccountIndex !== null && reportedAccountIndex !== currentGeminiAccountIndex) { - void updateGeminiAccountIndex(reportedAccountIndex, { + if ( + reportedAccountIndex !== null && + reportedAccountIndex !== getPanelGeminiAccountIndex(panel) + ) { + void updatePanelGeminiAccountIndex(panel, reportedAccountIndex, { persist: true, - reloadPanels: true, - excludePanelId: panel.id + reloadPanel: false }); } } @@ -1587,7 +1619,10 @@ function collectCurrentState() { uploadedImages: [...uploadedImages], currentLayout: currentLayout, panels: panels.map(p => ({ - providerId: p.providerId + providerId: p.providerId, + ...(isGeminiProvider(p.providerId) + ? { geminiAccountIndex: getPanelGeminiAccountIndex(p) } + : {}) })), googleProviderMode: currentGoogleProviderMode, geminiAccountIndex: currentGeminiAccountIndex, @@ -1779,6 +1814,10 @@ async function restoreStateIfNeeded() { // Restore panel configuration (save to multiPanelProviders) if (state.panels && state.panels.length > 0) { + pendingRestoredPanelAccounts = state.panels.map((p) => ({ + providerId: p.providerId, + geminiAccountIndex: normalizeGeminiAccountIndex(p.geminiAccountIndex) + })); const providerIds = state.panels.map(p => p.providerId); const existing = await chrome.storage.sync.get({ multiPanelProviders: null }); const nextMultiPanelProviders = preserveForeignCustomIds( @@ -1839,9 +1878,24 @@ async function initializePanels() { await requestOptionalProviderAccessSync(); } + const restoredQueue = Array.isArray(pendingRestoredPanelAccounts) + ? [...pendingRestoredPanelAccounts] + : null; + pendingRestoredPanelAccounts = null; + // Create all panels and load in parallel for fastest total time for (let i = 0; i < count; i++) { - await addPanel(providerIds[i], { saveConfig: false }); + let restoredGeminiAccountIndex; + if (restoredQueue && isGeminiProvider(providerIds[i])) { + const matchIdx = restoredQueue.findIndex(entry => entry.providerId === providerIds[i]); + if (matchIdx !== -1) { + restoredGeminiAccountIndex = restoredQueue.splice(matchIdx, 1)[0].geminiAccountIndex; + } + } + await addPanel(providerIds[i], { + saveConfig: false, + geminiAccountIndex: restoredGeminiAccountIndex + }); } if (count > 0) { @@ -1907,7 +1961,7 @@ function appendMenuOriginBadgeIfCustom(itemEl, nameSpan, providerId) { itemEl.appendChild(originBadgeEl); } -async function addPanel(providerId, { saveConfig = true } = {}) { +async function addPanel(providerId, { saveConfig = true, geminiAccountIndex } = {}) { // Sync before the capacity check so no await separates the check from the // panel being added. if (saveConfig && requiresOptionalProviderAccessSync(providerId)) { @@ -1948,6 +2002,11 @@ async function addPanel(providerId, { saveConfig = true } = {}) { } const panelId = `panel-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; + const resolvedGeminiAccountIndex = isGeminiProvider(providerId) + ? normalizeGeminiAccountIndex( + geminiAccountIndex !== undefined ? geminiAccountIndex : currentGeminiAccountIndex + ) + : DEFAULT_GEMINI_ACCOUNT_INDEX; const panelGrid = document.getElementById('panel-grid'); @@ -1969,7 +2028,7 @@ async function addPanel(providerId, { saveConfig = true } = {}) { const headerRightEl = document.createElement('div'); headerRightEl.className = 'panel-header-right'; - populatePanelHeaderRight(headerRightEl, providerId); + populatePanelHeaderRight(headerRightEl, providerId, resolvedGeminiAccountIndex); headerEl.append(headerLeftEl, headerRightEl); @@ -1981,7 +2040,7 @@ async function addPanel(providerId, { saveConfig = true } = {}) { renderPanelLoadingContent(loadingEl, provider, `Loading ${provider.name}...`); const iframe = document.createElement('iframe'); - const initialFrameUrl = getProviderFrameUrl(providerId); + const initialFrameUrl = getProviderFrameUrl(providerId, resolvedGeminiAccountIndex); iframe.setAttribute( 'sandbox', 'allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox' @@ -1992,6 +2051,7 @@ async function addPanel(providerId, { saveConfig = true } = {}) { const panel = { id: panelId, providerId, + geminiAccountIndex: resolvedGeminiAccountIndex, iframe, currentUrl: null, state: 'loading', @@ -2122,8 +2182,6 @@ async function switchPanelProvider(panelId, newProviderId) { if (isGoogleProvider(newProviderId)) { syncGoogleModeControls(); - } else if (isGeminiProvider(newProviderId)) { - syncGeminiAccountControls(); } if (requiresOptionalProviderAccessSync(newProviderId)) { @@ -2134,6 +2192,10 @@ async function switchPanelProvider(panelId, newProviderId) { await requestGrokWebSocketCookieSync(); } + const nextGeminiAccountIndex = isGeminiProvider(newProviderId) + ? currentGeminiAccountIndex + : DEFAULT_GEMINI_ACCOUNT_INDEX; + // Update panel header const headerLeft = panelEl.querySelector('.panel-header-left'); const headerIcon = headerLeft.querySelector('img'); @@ -2144,13 +2206,14 @@ async function switchPanelProvider(panelId, newProviderId) { headerIcon.setAttribute('alt', provider.name); headerName.textContent = provider.name; syncPanelCustomOriginBadge(panelEl, headerLeft, headerName, newProviderId); - populatePanelHeaderRight(headerRight, newProviderId); + populatePanelHeaderRight(headerRight, newProviderId, nextGeminiAccountIndex); // Update iframe const iframe = panelEl.querySelector('iframe'); // Update panel data panel.providerId = newProviderId; + panel.geminiAccountIndex = nextGeminiAccountIndex; panel.iframe = iframe; panel.currentUrl = null; panel.lastReportedAllowedUrl = null; @@ -2446,7 +2509,9 @@ export async function broadcastMessage(text, autoSubmit = true) { normalizedResults.forEach(result => { if (!result?.panelId) return; const attempted = attemptedImagesByPanel.get(result.panelId) || uploadedImages; - const attemptedIds = (attempted.length > 0 ? attempted : uploadedImages).map(img => img.id); + const attemptedIds = Array.isArray(result.attemptedImageIds) && result.attemptedImageIds.length > 0 + ? result.attemptedImageIds + : (attempted.length > 0 ? attempted : uploadedImages).map(img => img.id); if (result.ok) { failedFillPanelIds.delete(result.panelId); @@ -3577,11 +3642,11 @@ async function temporaryChatAllProviders() { if (isCustomWebProvider(panel.providerId)) { tempChatDeactivationPendingPanelIds.add(panel.id); } - reloadPanelIframe(panel, getTemporaryChatNormalUrl(panel.providerId)); + reloadPanelIframe(panel, getTemporaryChatNormalUrl(panel.providerId, panel)); return; } - postNewChatToPanel(panel, { reloadUrl: getTemporaryChatNormalUrl(panel.providerId) }); + postNewChatToPanel(panel, { reloadUrl: getTemporaryChatNormalUrl(panel.providerId, panel) }); }); restoreUnifiedInputFocusAfterNewChat(); diff --git a/tests/custom-api-options-and-panel.test.js b/tests/custom-api-options-and-panel.test.js index 5fb6893..eca9cef 100644 --- a/tests/custom-api-options-and-panel.test.js +++ b/tests/custom-api-options-and-panel.test.js @@ -1349,6 +1349,73 @@ describe('M3 Custom API Options UI, secret isolation, and built-in API compariso succeededImageIds: ['img-1'], }); + // Untouched API panel on Send All retry (`images: []`, `fallbackImages: [img-1]`) acknowledges `img-1` without duplicating staged image + sendHostMessage({ + context: 'multi-panel', + type: 'INJECT_TEXT_WITH_IMAGES', + action: 'fill', + requestId: 'fill-req-untouched-retry', + text: 'Compare this diagram', + autoSubmit: false, + retry: true, + images: [], + fallbackImages: [ + { + id: 'img-1', + dataUrl: 'data:image/png;base64,iVBORw0KGgo=', + name: 'diagram.png', + type: 'image/png', + }, + ], + }); + expect(childDoc.querySelectorAll('#staged-images .staged-image-item')).toHaveLength(1); + expect(hostReceivedMessages).toContainEqual({ + context: 'multi-panel-action-result', + type: 'PANELIZE_ACTION_RESULT', + requestId: 'fill-req-untouched-retry', + provider: PROVIDER_ID, + action: 'fill', + status: 'succeeded', + reason: null, + succeededImageIds: ['img-1'], + }); + + // Cleared API panel on Send All retry restores both caption and staged image from `fallbackImages` + sendHostMessage({ context: 'multi-panel', type: 'CLEAR_INPUT', clearImages: true }); + expect(childDoc.getElementById('composer-input').value).toBe(''); + expect(childDoc.querySelectorAll('#staged-images .staged-image-item')).toHaveLength(0); + + sendHostMessage({ + context: 'multi-panel', + type: 'INJECT_TEXT_WITH_IMAGES', + action: 'fill', + requestId: 'fill-req-cleared-retry', + text: 'Compare this diagram', + autoSubmit: false, + retry: true, + images: [], + fallbackImages: [ + { + id: 'img-1', + dataUrl: 'data:image/png;base64,iVBORw0KGgo=', + name: 'diagram.png', + type: 'image/png', + }, + ], + }); + expect(childDoc.getElementById('composer-input').value).toBe('Compare this diagram'); + expect(childDoc.querySelectorAll('#staged-images .staged-image-item')).toHaveLength(1); + expect(hostReceivedMessages).toContainEqual({ + context: 'multi-panel-action-result', + type: 'PANELIZE_ACTION_RESULT', + requestId: 'fill-req-cleared-retry', + provider: PROVIDER_ID, + action: 'fill', + status: 'succeeded', + reason: null, + succeededImageIds: ['img-1'], + }); + // Broadcast TRIGGER_SEND sendHostMessage({ context: 'multi-panel', diff --git a/tests/custom-provider-driver.test.js b/tests/custom-provider-driver.test.js index e18c754..afbc9b1 100644 --- a/tests/custom-provider-driver.test.js +++ b/tests/custom-provider-driver.test.js @@ -1809,4 +1809,113 @@ describe('content-scripts/custom-provider-driver.js', () => { await env.close(); } }); + + it('acknowledges image-only fallbackImages retry without error when staged preview remains and re-uploads when cleared', async () => { + const env = createDriverEnvironment({ ancestorOrigins: [EXTENSION_ORIGIN] }); + try { + env.document.body.innerHTML = ` +
+ +
+ chart.png +
+ + +
+ `; + const composer = setLayoutRect(env.document.getElementById('composer')); + setLayoutRect(env.document.getElementById('send-btn'), { + left: 640, + top: 500, + width: 40, + height: 40, + }); + const fileInput = env.document.getElementById('file-in'); + const previews = env.document.getElementById('previews'); + let uploadCount = 0; + fileInput.addEventListener('change', () => { + uploadCount += 1; + const img = env.document.createElement('img'); + img.src = `blob:http://127.0.0.1:3000/reupload-${uploadCount}`; + previews.appendChild(img); + }); + + env.evaluateDriver(); + env.parent.postMessage.mockClear(); + + const fallbackImages = [ + { + id: 'img-fallback-1', + name: 'chart.png', + type: 'image/png', + dataUrl: + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO2Z2ioAAAAASUVORK5CYII=', + }, + ]; + + // 1. Untouched panel with staged image and empty caption on Send All retry -> succeeds without re-uploading! + env.postFromHost({ + type: 'INJECT_TEXT_WITH_IMAGES', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + requestId: 'req-img-only-fallback-untouched', + action: 'fill', + text: '', + images: [], + fallbackImages, + autoSubmit: false, + retry: true, + }); + + await wait(60); + expect(uploadCount).toBe(0); + expect(env.parent.postMessage).toHaveBeenCalledWith( + { + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: 'req-img-only-fallback-untouched', + provider: CUSTOM_PROVIDER_ID, + action: 'fill', + status: 'succeeded', + succeededImageIds: ['img-fallback-1'], + }, + EXTENSION_ORIGIN + ); + + // 2. User clears staged preview and text -> next Send All retry re-uploads fallbackImages! + previews.innerHTML = ''; + composer.value = ''; + env.parent.postMessage.mockClear(); + + env.postFromHost({ + type: 'INJECT_TEXT_WITH_IMAGES', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + requestId: 'req-img-only-fallback-cleared', + action: 'fill', + text: '', + images: [], + fallbackImages, + autoSubmit: false, + retry: true, + }); + + await wait(200); + expect(uploadCount).toBe(1); + expect(env.parent.postMessage).toHaveBeenCalledWith( + { + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: 'req-img-only-fallback-cleared', + provider: CUSTOM_PROVIDER_ID, + action: 'fill', + status: 'succeeded', + succeededImageIds: ['img-fallback-1'], + }, + EXTENSION_ORIGIN + ); + } finally { + await env.close(); + } + }); }); diff --git a/tests/deepseek-content-script.test.js b/tests/deepseek-content-script.test.js index ed123a3..6f86a66 100644 --- a/tests/deepseek-content-script.test.js +++ b/tests/deepseek-content-script.test.js @@ -190,4 +190,41 @@ describe('deepseek content script integration', () => { vi.useRealTimers(); } }); + + it('does not click an enabled unrelated .ds-icon-button while the primary DeepSeek send button is disabled', async () => { + vi.useFakeTimers(); + try { + const { sendButton } = createDeepSeekDom({ sendDisabled: true }); + const unrelatedIconBtn = document.createElement('button'); + unrelatedIconBtn.type = 'button'; + unrelatedIconBtn.className = 'ds-icon-button'; + unrelatedIconBtn.innerHTML = ''; + markVisible(unrelatedIconBtn); + sendButton.parentElement.prepend(unrelatedIconBtn); + + const unrelatedSpy = vi.fn(); + const sendSpy = vi.fn(); + unrelatedIconBtn.addEventListener('click', unrelatedSpy); + sendButton.addEventListener('click', sendSpy); + + dispatchMultiPanelMessage({ + type: 'INJECT_TEXT', + text: 'Avoid unrelated icon buttons', + autoSubmit: true, + context: 'multi-panel', + }); + + await vi.advanceTimersByTimeAsync(850); + expect(unrelatedSpy).not.toHaveBeenCalled(); + expect(sendSpy).not.toHaveBeenCalled(); + + sendButton.classList.remove('ds-button--disabled'); + await vi.advanceTimersByTimeAsync(450); + + expect(unrelatedSpy).not.toHaveBeenCalled(); + expect(sendSpy).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } + }); }); diff --git a/tests/e2e/issue-118-multi-account-and-send-all.e2e.test.js b/tests/e2e/issue-118-multi-account-and-send-all.e2e.test.js index 7db6250..1be1db8 100644 --- a/tests/e2e/issue-118-multi-account-and-send-all.e2e.test.js +++ b/tests/e2e/issue-118-multi-account-and-send-all.e2e.test.js @@ -214,31 +214,40 @@ test('Gemini multi-account selector and in-frame /u/1/app account link stay insi }) ); - const page = await openMultiPanel(extension, { providers: ['gemini'], layout: '1x1' }); + const page = await openMultiPanel(extension, { providers: ['gemini', 'gemini'], layout: '1x2' }); page.on('pageerror', (err) => pageErrors.push(err.message)); - const accountSelect = page.locator('.panel-gemini-account-select'); - await expect(accountSelect).toBeVisible(); - await expect(accountSelect).toHaveValue(''); + const firstAccountSelect = page.locator('.panel-gemini-account-select').nth(0); + const secondAccountSelect = page.locator('.panel-gemini-account-select').nth(1); + await expect(firstAccountSelect).toBeVisible(); + await expect(secondAccountSelect).toBeVisible(); + await expect(firstAccountSelect).toHaveValue(''); + await expect(secondAccountSelect).toHaveValue(''); - const panelFrame = page.frameLocator('iframe'); - await expect(panelFrame.locator('#current-path')).toHaveText('/'); + const firstPanelFrame = page.frameLocator('iframe').nth(0); + const secondPanelFrame = page.frameLocator('iframe').nth(1); + await expect(firstPanelFrame.locator('#current-path')).toHaveText('/'); + await expect(secondPanelFrame.locator('#current-path')).toHaveText('/'); const tabCountBeforeClick = (await getTabUrls(page)).length; - // Clicking a target="_blank" /u/1/app?pageId=none link inside Gemini navigates in-frame instead of spawning an external tab - await panelFrame.locator('#switch-account-u1').click(); - await expect(panelFrame.locator('#current-path')).toHaveText('/u/1/app?pageId=none'); - await expect(accountSelect).toHaveValue('1'); + // Clicking a target="_blank" /u/1/app?pageId=none link inside the first Gemini panel navigates in-frame without spawning a new tab or disturbing the second Gemini panel + await firstPanelFrame.locator('#switch-account-u1').click(); + await expect(firstPanelFrame.locator('#current-path')).toHaveText('/u/1/app?pageId=none'); + await expect(firstAccountSelect).toHaveValue('1'); + await expect(secondPanelFrame.locator('#current-path')).toHaveText('/'); + await expect(secondAccountSelect).toHaveValue(''); expect((await getTabUrls(page)).length).toBe(tabCountBeforeClick); - // Switching the header dropdown to /u/2 navigates the panel iframe to /u/2/app - await accountSelect.selectOption('2'); - await expect(panelFrame.locator('#current-path')).toHaveText('/u/2/app'); + // Switching the second Gemini panel's header dropdown to /u/2 navigates ONLY the second panel while keeping the first panel's /u/1 session intact + await secondAccountSelect.selectOption('2'); + await expect(secondPanelFrame.locator('#current-path')).toHaveText('/u/2/app'); + await expect(firstPanelFrame.locator('#current-path')).toHaveText('/u/1/app?pageId=none'); + await expect(firstAccountSelect).toHaveValue('1'); // Also verify narrow/mobile viewport rendering of header controls await page.setViewportSize({ width: 390, height: 844 }); - await expect(accountSelect).toBeVisible(); + await expect(firstAccountSelect).toBeVisible(); await page.screenshot({ path: testInfo.outputPath('gemini-multi-account-mobile.png'), fullPage: true }); expect(pageErrors).toEqual([]); diff --git a/tests/gemini-account.test.js b/tests/gemini-account.test.js index f738664..ce398ee 100644 --- a/tests/gemini-account.test.js +++ b/tests/gemini-account.test.js @@ -343,4 +343,143 @@ describe('multi-panel Gemini account selector & Send All cleared-panel retry', ( expect(deepseekPayload.fallbackImages).toHaveLength(1); expect(document.getElementById('send-status').textContent).toBe('Filled 2 inputs'); }); + + it('keeps per-panel Gemini accounts independent so changing one Gemini panel does not reload another', async () => { + await bootMultiPanel(['gemini', 'gemini']); + const panelEls = Array.from(document.querySelectorAll('#panel-grid .panel-item')); + expect(panelEls).toHaveLength(2); + + const [firstPanelEl, secondPanelEl] = panelEls; + const firstIframe = firstPanelEl.querySelector('iframe'); + const secondIframe = secondPanelEl.querySelector('iframe'); + const firstSelect = firstPanelEl.querySelector('.panel-gemini-account-select'); + const secondSelect = secondPanelEl.querySelector('.panel-gemini-account-select'); + + // Select /u/0 in the first Gemini panel + firstSelect.value = '0'; + firstSelect.dispatchEvent(new Event('change', { bubbles: true })); + await vi.waitFor(() => { + expect(firstIframe.getAttribute('src')).toBe('https://gemini.google.com/u/0/app'); + }); + expect(secondIframe.getAttribute('src')).toBe('https://gemini.google.com'); + expect(secondSelect.value).toBe(''); + + // Simulate active conversation on first Gemini panel, then switch second Gemini panel to /u/1 + firstIframe.setAttribute('src', 'https://gemini.google.com/u/0/app/live-conv-1'); + secondSelect.value = '1'; + secondSelect.dispatchEvent(new Event('change', { bubbles: true })); + + await vi.waitFor(() => { + expect(secondIframe.getAttribute('src')).toBe('https://gemini.google.com/u/1/app'); + }); + // First Gemini panel must NOT be reloaded or have its account selector overwritten + expect(firstIframe.getAttribute('src')).toBe('https://gemini.google.com/u/0/app/live-conv-1'); + expect(firstSelect.value).toBe('0'); + expect(secondSelect.value).toBe('1'); + }); + + it('preserves missing image IDs via attemptedImageIds when a cleared-composer fallback retry partially fails', async () => { + const { mod, handleByProvider } = await bootMultiPanel(['deepseek']); + const deepseek = handleByProvider.deepseek; + + // Attach 3 images A, B, C + const fileInput = document.getElementById('image-file-input'); + const files = ['a.png', 'b.png', 'c.png'].map( + (name) => new File([new Uint8Array([137, 80, 78, 71])], name, { type: 'image/png' }) + ); + const origFileReader = globalThis.FileReader; + globalThis.FileReader = class MockFileReader { + readAsDataURL() { + this.result = SAMPLE_PNG_DATA_URL; + if (this.onload) this.onload({ target: { result: SAMPLE_PNG_DATA_URL } }); + } + }; + try { + Object.defineProperty(fileInput, 'files', { configurable: true, value: files }); + fileInput.dispatchEvent(new Event('change', { bubbles: true })); + } finally { + globalThis.FileReader = origFileReader; + } + + await vi.waitFor(() => { + expect(document.querySelectorAll('.image-preview-item')).toHaveLength(3); + }); + + let pass = 0; + deepseek.fakeWindow.postMessage.mockImplementation((msg) => { + if (msg?.type !== 'INJECT_TEXT_WITH_IMAGES') return; + pass += 1; + const allIds = (msg.fallbackImages || msg.images).map((img) => img.id); + queueMicrotask(() => { + if (pass === 1) { + // Pass 1: A and B succeed, C fails -> pending=[C] + window.dispatchEvent( + new MessageEvent('message', { + data: { + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: msg.requestId, + provider: 'deepseek', + action: 'fill', + status: 'failed', + reason: 'preview-timeout', + succeededImageIds: [allIds[0], allIds[1]], + }, + source: deepseek.fakeWindow, + origin: 'https://chat.deepseek.com', + }) + ); + } else if (pass === 2) { + // Pass 2: composer was cleared, frame attempted all [A, B, C]; A succeeded, B failed! + window.dispatchEvent( + new MessageEvent('message', { + data: { + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: msg.requestId, + provider: 'deepseek', + action: 'fill', + status: 'failed', + reason: 'preview-timeout', + succeededImageIds: [allIds[0]], + attemptedImageIds: allIds, + }, + source: deepseek.fakeWindow, + origin: 'https://chat.deepseek.com', + }) + ); + } else { + // Pass 3: must receive BOTH B and C in msg.images! + window.dispatchEvent( + new MessageEvent('message', { + data: { + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: msg.requestId, + provider: 'deepseek', + action: 'fill', + status: 'succeeded', + succeededImageIds: msg.images.map((img) => img.id), + }, + source: deepseek.fakeWindow, + origin: 'https://chat.deepseek.com', + }) + ); + } + }); + }); + + // Pass 1 + await mod.broadcastMessage('Three images', true); + const allThreeIds = deepseek.fakeWindow.postMessage.mock.calls[0][0].images.map((i) => i.id); + + // Pass 2 (user cleared composer, clicks Send All; A succeeds, B fails) + await mod.broadcastMessage('Three images', true); + + // Pass 3 (Retry Failed): must retry BOTH B and C, never dropping B + deepseek.fakeWindow.postMessage.mockClear(); + await mod.broadcastMessage('Three images', false); + const pass3Payload = deepseek.fakeWindow.postMessage.mock.calls[0][0]; + expect(pass3Payload.images.map((i) => i.id)).toEqual([allThreeIds[1], allThreeIds[2]]); + }); }); diff --git a/tests/gemini-content-script.test.js b/tests/gemini-content-script.test.js index d16fd36..28c160f 100644 --- a/tests/gemini-content-script.test.js +++ b/tests/gemini-content-script.test.js @@ -165,6 +165,23 @@ describe('Gemini content script integration', () => { expect(externalClick.defaultPrevented).toBe(false); expect(assignSpy).not.toHaveBeenCalled(); + + // Ordinary conversation deep links on the SAME /u/1 account must NOT be hijacked when opened with target="_blank" + window.happyDOM.setURL('https://gemini.google.com/u/1/app'); + document.body.innerHTML = ` + Open chat in new tab + Switch to account 2 chat + `; + + const sameAccountConvClick = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 }); + document.getElementById('gemini-same-account-conv').dispatchEvent(sameAccountConvClick); + expect(sameAccountConvClick.defaultPrevented).toBe(false); + expect(assignSpy).not.toHaveBeenCalled(); + + const crossAccountConvClick = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 }); + document.getElementById('gemini-cross-account-conv').dispatchEvent(crossAccountConvClick); + expect(crossAccountConvClick.defaultPrevented).toBe(true); + expect(assignSpy).toHaveBeenCalledWith('https://gemini.google.com/u/2/app/conv-xyz789'); }); it('preserves the active /u/ account prefix on Gemini NEW_CHAT URL fallback', () => { diff --git a/tests/provider-image-upload-content-script.test.js b/tests/provider-image-upload-content-script.test.js index 20332f5..7125dad 100644 --- a/tests/provider-image-upload-content-script.test.js +++ b/tests/provider-image-upload-content-script.test.js @@ -868,4 +868,79 @@ describe('provider image upload adapters', () => { await vi.advanceTimersByTimeAsync(500); expect(realSendClickSpy).toHaveBeenCalledTimes(1); }); + + it('does not duplicate block-rendered multiline text (

lines) on Kimi Send All retry', async () => { + window.happyDOM.setURL('https://www.kimi.com/'); + createKimiDom(); + const editor = document.querySelector('.chat-input-editor'); + editor.innerHTML = '

Alpha line

Beta line

'; + + dispatchMultiPanelMessage({ + type: 'INJECT_TEXT_WITH_IMAGES', + context: 'multi-panel', + images: [], + fallbackImages: SAMPLE_IMAGES, + text: 'Alpha line\nBeta line', + autoSubmit: false, + requestId: 'kimi-block-multiline-retry', + retry: true, + }); + await finishSuccessfulInjection(); + + // Must recognize `

Alpha line

Beta line

` as ending with `Alpha line\nBeta line` + expect(editor.innerHTML).toBe('

Alpha line

Beta line

'); + expect(window.parent.postMessage).toHaveBeenCalledWith({ + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: 'kimi-block-multiline-retry', + provider: 'kimi', + action: 'fill', + status: 'succeeded', + succeededImageIds: ['sample-one-id', 'sample-two-id'], + }, EXTENSION_ORIGIN); + }); + + it('re-uploads fallbackImages into cleared DeepSeek composer even when historical messages have matching filenames and unnamed blob previews', async () => { + window.happyDOM.setURL('https://chat.deepseek.com/'); + const { composer, fileInput, uploadedNames } = createDeepSeekDom({ previewOnChange: false }); + + // Seed two historical chat attachments outside `#deepseek-composer` sharing `sample-one.png` + const historyTurn = document.createElement('section'); + historyTurn.innerHTML = ` + sample-one.png + sample-one.png + `; + document.body.prepend(historyTurn); + + // Mount an unnamed blob thumbnail inside the composer (simulating narrow truncated chip) + fileInput.addEventListener('change', () => { + const unnamedBlob = document.createElement('img'); + unnamedBlob.src = `blob:https://chat.deepseek.com/${uploadedNames.length}`; + composer.querySelector('#deepseek-previews').appendChild(unnamedBlob); + }); + + dispatchMultiPanelMessage({ + type: 'INJECT_TEXT_WITH_IMAGES', + context: 'multi-panel', + images: [], + fallbackImages: [SAMPLE_IMAGES[0]], + text: 'Fresh prompt after clear', + autoSubmit: false, + requestId: 'deepseek-history-filename-req', + retry: true, + }); + await finishSuccessfulInjection(); + + expect(uploadedNames).toEqual(['sample-one.png']); + expect(composer.querySelector('textarea').value).toBe('Fresh prompt after clear'); + expect(window.parent.postMessage).toHaveBeenCalledWith({ + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: 'deepseek-history-filename-req', + provider: 'deepseek', + action: 'fill', + status: 'succeeded', + succeededImageIds: ['sample-one-id'], + }, EXTENSION_ORIGIN); + }); }); diff --git a/tests/provider-open-url.test.js b/tests/provider-open-url.test.js index e0f8121..7e8de6f 100644 --- a/tests/provider-open-url.test.js +++ b/tests/provider-open-url.test.js @@ -23,7 +23,6 @@ describe('provider open URL helpers', () => { expect(isProviderCurrentUrl('zai-global', 'https://chat.z.ai/c/abc123')).toBe(true); expect(isProviderCurrentUrl('yuanbao', 'https://yuanbao.tencent.com/chat/agent123/chat456')).toBe(true); expect(isProviderCurrentUrl('aistudio', 'https://aistudio.google.com/prompts/1abcDEF234')).toBe(true); - expect(isProviderCurrentUrl('aistudio', 'https://aistudio.google.com/u/1/prompts/1abcDEF234')).toBe(true); }); it('accepts current Google pages for both AI Mode and Search', () => { @@ -90,7 +89,6 @@ describe('provider open URL helpers', () => { ) ).toBe('https://aistudio.google.com/prompts/new_chat'); expect(isProviderCurrentUrl('gemini', 'https://gemini.google.com/u/1/app')).toBe(false); - expect(isProviderCurrentUrl('aistudio', 'https://aistudio.google.com/u/1/prompts/new_chat')).toBe(false); expect( getProviderOpenUrl( getProviderById('gemini'),