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 b93c590..f6b9a75 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: [ @@ -325,12 +328,15 @@ // 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)', '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 '.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', @@ -701,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; } @@ -733,6 +743,90 @@ }); } + function getCurrentGoogleAccountPrefix() { + const match = /^\/u\/(\d+)(?:\/|$)/.exec(window.location.pathname || ''); + return match ? `/u/${match[1]}` : ''; + } + + function isSameOriginGeminiAccountSwitchUrl(targetUrl) { + if (!targetUrl || targetUrl.origin !== window.location.origin) { + return false; + } + + if (targetUrl.searchParams.has('authuser')) { + return true; + } + + const match = /^\/u\/(\d+)(?:\/|$)/.exec(targetUrl.pathname); + if (!match) { + 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 Gemini Google account-switch links (`/u//app`, `?authuser=`) + * inside the embedded panel iframe when the page marks them `target="_blank"` + * or `target="_top"`, without hijacking ordinary same-account conversation links. + */ + 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') { + 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 (!isSameOriginGeminiAccountSwitchUrl(resolvedUrl)) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + window.location.assign(resolvedUrl.toString()); + }, true); + } + function setupProviderLocationReporting() { let lastReportedUrl = null; @@ -1186,23 +1280,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 +1493,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 +1664,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 +1790,7 @@ } // Find and click send button - function clickSendButton(provider, providerMode = null) { + function clickSendButton(provider, providerMode = null, { allowEnterFallback = true } = {}) { if (provider === 'google') { return clickGoogleSendButton(providerMode); } @@ -1613,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); @@ -1669,25 +1880,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 +1946,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); @@ -2190,9 +2450,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 +2504,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 +2525,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 { @@ -2323,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( @@ -2359,9 +2743,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 +2753,66 @@ 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) + : 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; + } + + const composerRoot = getComposerRootForAttachmentCheck(provider, input); + if ( + composerRoot && + (candidateImages || []).some(img => img?.name && countFilenamePreviewEvidence(composerRoot, img.name) > 0) + ) { + return false; + } + + if (provider === 'deepseek') { + if (composerRoot && composerRoot.querySelectorAll('img[src^="blob:"]').length > 0) { + return false; + } + } else if (provider === 'kimi') { + if ( + composerRoot && + (countKimiAttachmentPreviews(composerRoot) > 0 || countKimiPendingAttachmentPreviews(composerRoot) > 0) + ) { + return false; + } + } else if (provider === 'grok') { + const attachmentList = composerRoot?.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 +2840,22 @@ 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; + const failureAttemptedIds = composerClearedOnRetry + ? effectiveImages.map(img => img?.id).filter(id => typeof id === 'string') + : undefined; + + if (!effectiveImages || effectiveImages.length === 0) { if (retry && text && text.trim()) { const textInjected = injectText( provider, @@ -2411,14 +2865,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 +2894,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 +2908,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 +2926,7 @@ text, autoSubmit && allImagesInjected, providerMode, - { skipIfAlreadyPresent: retry } + { skipIfAlreadyPresent: effectiveRetry } ); } else if (autoSubmit) { if (!allImagesInjected) { @@ -2477,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 @@ -2489,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); } } @@ -2511,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) { @@ -2946,16 +3411,24 @@ } // 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; 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( - () => countFilenamePreviewEvidence(document, imageData.name), - previousCount + () => ( + countFilenamePreviewEvidence(document, imageData.name) > previousFilenameCount || + composer.querySelectorAll('img[src^="blob:"]').length > previousBlobCount + ? 1 + : 0 + ), + 0 ); return accepted ? createImageInjectionSuccess() @@ -4108,15 +4581,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 +4600,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 +5628,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 ` +
+ 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 5072737..6f86a66 100644 --- a/tests/deepseek-content-script.test.js +++ b/tests/deepseek-content-script.test.js @@ -107,4 +107,124 @@ describe('deepseek content script integration', () => { expect(clickSpy).toHaveBeenCalledTimes(1); expect(window.location.href).toBe('https://chat.deepseek.com/'); }); + + it('re-populates the visible React-controlled DeepSeek composer after deleting its prompt even with an inline-edit textarea earlier in the DOM', () => { + const { editor } = createDeepSeekDom(); + + // Prepend a hidden/inline-edit textarea earlier in DOM order + const inlineEdit = document.createElement('textarea'); + inlineEdit.setAttribute('name', 'user query'); + inlineEdit.value = 'old edited turn'; + document.body.prepend(inlineEdit); + + // Simulate React 18 controlled input value tracker on the composer textarea + let trackedValue = ''; + const reactSeenValues = []; + editor._valueTracker = { + getValue: () => trackedValue, + setValue: (next) => { + trackedValue = String(next); + }, + }; + editor.addEventListener('input', () => { + if (editor._valueTracker.getValue() !== editor.value) { + editor._valueTracker.setValue(editor.value); + reactSeenValues.push(editor.value); + } + }); + + // Pass 1: initial fill + dispatchMultiPanelMessage({ + type: 'INJECT_TEXT', + text: 'First DeepSeek prompt', + autoSubmit: false, + context: 'multi-panel', + }); + expect(editor.value).toBe('First DeepSeek prompt'); + expect(reactSeenValues).toEqual(['First DeepSeek prompt']); + + // Simulate user deleting the prompt inside DeepSeek while _valueTracker goes stale + const nativeSetter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set; + nativeSetter.call(editor, ''); + editor._valueTracker.setValue('First DeepSeek prompt'); + + // Pass 2: re-sending the exact same prompt after deletion must still notify React and populate editor + dispatchMultiPanelMessage({ + type: 'INJECT_TEXT', + text: 'First DeepSeek prompt', + autoSubmit: false, + context: 'multi-panel', + }); + + expect(editor.value).toBe('First DeepSeek prompt'); + expect(inlineEdit.value).toBe('old edited turn'); + expect(reactSeenValues).toEqual(['First DeepSeek prompt', 'First DeepSeek prompt']); + }); + + it('retries auto-submit when DeepSeek send button transitions from disabled to enabled asynchronously', async () => { + vi.useFakeTimers(); + try { + const { editor, sendButton } = createDeepSeekDom({ sendDisabled: true }); + const sendSpy = vi.fn(); + sendButton.addEventListener('click', sendSpy); + + dispatchMultiPanelMessage({ + type: 'INJECT_TEXT', + text: 'Delayed enablement prompt', + autoSubmit: true, + context: 'multi-panel', + }); + + expect(editor.value).toBe('Delayed enablement prompt'); + + // Still disabled at initial 800ms check -> should wait rather than firing premature Enter + await vi.advanceTimersByTimeAsync(850); + expect(sendSpy).not.toHaveBeenCalled(); + + // DeepSeek React composer finishes enabling the send button at ~1000ms + sendButton.classList.remove('ds-button--disabled'); + await vi.advanceTimersByTimeAsync(450); + + expect(sendSpy).toHaveBeenCalledTimes(1); + } finally { + 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 new file mode 100644 index 0000000..1be1db8 --- /dev/null +++ b/tests/e2e/issue-118-multi-account-and-send-all.e2e.test.js @@ -0,0 +1,342 @@ +import { test, expect } from '@playwright/test'; +import { getTabUrls, launchExtension, openMultiPanel } from './extension-harness.js'; + +const PNG_BYTES = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', + 'base64' +); + +function renderGeminiAccountFixture(urlString) { + const parsed = new URL(urlString); + return ` + +Gemini ${parsed.pathname} + +
+
${parsed.pathname}${parsed.search}
+ Switch to account 1 + Help +
+
+
+ +
+ +`; +} + +function renderDeepSeekFixture() { + return ` + +DeepSeek fixture + + + +
+ + +
+ +
+ 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', 'gemini'], layout: '1x2' }); + page.on('pageerror', (err) => pageErrors.push(err.message)); + + 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 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 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 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(firstAccountSelect).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..ce398ee --- /dev/null +++ b/tests/gemini-account.test.js @@ -0,0 +1,485 @@ +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'); + }); + + 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 b34b83a..28c160f 100644 --- a/tests/gemini-content-script.test.js +++ b/tests/gemini-content-script.test.js @@ -139,4 +139,57 @@ 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(); + + // 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', () => { + 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..7125dad 100644 --- a/tests/provider-image-upload-content-script.test.js +++ b/tests/provider-image-upload-content-script.test.js @@ -747,4 +747,200 @@ 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); + }); + + 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 5e6ea6e..7e8de6f 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); @@ -87,5 +88,15 @@ 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( + 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'); }); });