diff --git a/content-scripts/text-injection-all-providers.js b/content-scripts/text-injection-all-providers.js index b93c590..4c1ce7e 100644 --- a/content-scripts/text-injection-all-providers.js +++ b/content-scripts/text-injection-all-providers.js @@ -295,6 +295,7 @@ const SEND_BUTTON_SELECTORS = { chatgpt: [ 'button[data-testid="send-button"]', + 'button[data-testid="fruitjuice-send-button"]', 'button[aria-label="Send prompt"]', 'button[aria-label="Send message"]', 'button[aria-label="Send"]', @@ -742,8 +743,12 @@ return; } + const previousUrl = lastReportedUrl; lastReportedUrl = currentUrl; postProviderLocation(); + if (previousUrl && detectProvider() === 'chatgpt') { + handleChatgptRouteChange(previousUrl, currentUrl); + } }; const wrapHistoryMethod = (methodName) => { @@ -1221,8 +1226,10 @@ })); } - function clearRichTextInput(provider, element) { - element.focus(); + function clearRichTextInput(provider, element, { focus = true } = {}) { + if (focus !== false) { + element.focus(); + } if (provider !== 'kimi' && provider !== 'doubao') { element.innerHTML = ''; @@ -1646,6 +1653,13 @@ // Check if element or its parent is disabled if (isProviderSendControlEnabled(provider, targetElement)) { + const chatgptCandidateText = provider === 'chatgpt' + ? readChatgptEditorText(findProviderInput('chatgpt')) + : ''; + const chatgptStartHref = provider === 'chatgpt' ? window.location.href : ''; + const chatgptWasBusyBeforeSend = provider === 'chatgpt' + ? Boolean(findChatgptBusyButton()) + : false; console.log('[Text Injection] Clicking send button:', selector); if (provider === 'chatglm') { // ChatGLM submits from its mousedown handler; HTMLElement.click() skips it. @@ -1659,6 +1673,11 @@ } else { targetElement.click(); } + if (provider === 'chatgpt' && chatgptCandidateText.trim().length > 0) { + confirmAndRecordChatgptSend(chatgptCandidateText, chatgptStartHref, { + wasBusyBeforeSend: chatgptWasBusyBeforeSend + }); + } return true; } else { console.log('[Text Injection] Button found but disabled:', selector); @@ -1944,15 +1963,191 @@ } // ChatGPT persists the new-chat composer draft (it survives the New chat button, - // reloads, and is restored with the last sent prompt), so a Multi-Panel New Chat - // must clear it explicitly. The composer re-renders after navigation and may - // restore the draft late, so clear a few times, stopping once the user types. - const CHATGPT_NEW_CHAT_CLEAR_DELAYS_MS = [0, 250, 600, 1200, 2000]; + // reloads, and is restored with the last sent prompt), so both Multi-Panel New + // Chat and post-send reloads must clear it explicitly. The composer re-renders + // after navigation and may restore the draft late, so clear across a short + // hydration window, stopping once the user types. + const CHATGPT_NEW_CHAT_CLEAR_DELAYS_MS = [0, 150, 400, 900, 1800, 3500]; const CHATGPT_NEW_CHAT_MOUNT_POLL_MS = 250; const CHATGPT_PENDING_NEW_CHAT_CLEAR_KEY = 'panelize:chatgpt-pending-new-chat-clear'; const CHATGPT_PENDING_NEW_CHAT_CLEAR_TTL_MS = 15000; + const CHATGPT_SENT_DRAFTS_KEY = 'panelize:chatgpt-sent-drafts'; + const CHATGPT_SENT_DRAFTS_MAX = 20; + const CHATGPT_SENT_DRAFTS_TTL_MS = 24 * 60 * 60 * 1000; + const CHATGPT_RELOAD_CLEAR_WINDOW_MS = 15000; + const CHATGPT_SEND_CONFIRM_POLL_MS = 150; + const CHATGPT_SEND_CONFIRM_MAX_ATTEMPTS = 10; + const CHATGPT_NON_EDITING_KEYS = new Set([ + 'Shift', 'Control', 'Alt', 'Meta', 'CapsLock', 'NumLock', 'ScrollLock', + 'Tab', 'Escape', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', + 'Home', 'End', 'PageUp', 'PageDown', 'ContextMenu', 'Pause', 'PrintScreen' + ]); let chatgptNewChatClearTimerIds = []; let chatgptNewChatMountObserver = null; + let chatgptActiveClearMatchSentOnly = false; + + function isEmbeddedChatgptFrame() { + return window.self !== window.top && detectProvider() === 'chatgpt'; + } + + function isChatgptHomePath(pathname = window.location?.pathname || '') { + return pathname === '' || pathname === '/'; + } + + function normalizeChatgptDraftText(text) { + if (typeof text !== 'string') { + return ''; + } + return text.replace(/\r\n?/g, '\n').trim(); + } + + function readChatgptEditorText(editor) { + if (!editor) { + return ''; + } + if (editor.tagName === 'TEXTAREA' || editor.tagName === 'INPUT') { + return editor.value || ''; + } + const blockChildren = Array.from(editor.children || []).filter( + child => child.tagName === 'P' || child.tagName === 'DIV' + ); + if (blockChildren.length > 0) { + return blockChildren + .map(block => { + const clone = block.cloneNode(true); + clone.querySelectorAll('br').forEach(br => br.replaceWith('\n')); + return (clone.textContent || '').replace(/\n$/, ''); + }) + .join('\n'); + } + return editor.textContent || ''; + } + + function getChatgptDraftStorages() { + const storages = []; + const isTemporaryChat = + new URLSearchParams(window.location?.search || '').get('temporary-chat') === 'true'; + if (!isTemporaryChat) { + try { + if (window.localStorage) storages.push(window.localStorage); + } catch (error) { + // Ignore restricted storage contexts. + } + } + try { + if (window.sessionStorage) storages.push(window.sessionStorage); + } catch (error) { + // Ignore restricted storage contexts. + } + return storages; + } + + function readSentChatgptDrafts() { + const now = Date.now(); + const seen = new Set(); + const entries = []; + for (const storage of getChatgptDraftStorages()) { + let raw = null; + try { + raw = storage.getItem(CHATGPT_SENT_DRAFTS_KEY); + } catch (error) { + continue; + } + if (!raw) continue; + try { + const parsed = JSON.parse(raw); + if (!Array.isArray(parsed)) continue; + for (const item of parsed) { + const text = normalizeChatgptDraftText(item?.text); + const at = Number(item?.at); + if (!text || !Number.isFinite(at) || now - at > CHATGPT_SENT_DRAFTS_TTL_MS || seen.has(text)) { + continue; + } + seen.add(text); + entries.push({ text, at }); + } + } catch (error) { + // Ignore malformed storage data. + } + } + entries.sort((a, b) => b.at - a.at); + return entries.slice(0, CHATGPT_SENT_DRAFTS_MAX); + } + + function recordSentChatgptDraft(rawText) { + const text = normalizeChatgptDraftText(rawText); + if (!text) { + return; + } + const next = [ + { text, at: Date.now() }, + ...readSentChatgptDrafts().filter(entry => entry.text !== text) + ].slice(0, CHATGPT_SENT_DRAFTS_MAX); + const serialized = JSON.stringify(next); + for (const storage of getChatgptDraftStorages()) { + try { + storage.setItem(CHATGPT_SENT_DRAFTS_KEY, serialized); + break; + } catch (error) { + // Fall through to the next available storage backend. + } + } + } + + function isRecordedSentChatgptDraft(rawText) { + const normalized = normalizeChatgptDraftText(rawText); + if (!normalized) { + return false; + } + return readSentChatgptDrafts().some(entry => entry.text === normalized); + } + + function confirmAndRecordChatgptSend( + candidateText, + startHref = window.location.href, + { wasBusyBeforeSend = false } = {} + ) { + if (!isEmbeddedChatgptFrame()) { + return; + } + const normalized = normalizeChatgptDraftText(candidateText); + if (!normalized) { + return; + } + + const isConfirmedSent = () => { + const editor = findProviderInput('chatgpt'); + const current = normalizeChatgptDraftText(readChatgptEditorText(editor)); + if (!current) { + return true; + } + if (!wasBusyBeforeSend && findChatgptBusyButton()) { + return true; + } + if (window.location.href !== startHref && !isChatgptHomePath()) { + return true; + } + return false; + }; + + if (isConfirmedSent()) { + recordSentChatgptDraft(normalized); + return; + } + + let attempts = 0; + const poll = () => { + attempts += 1; + if (isConfirmedSent()) { + recordSentChatgptDraft(normalized); + return; + } + if (attempts < CHATGPT_SEND_CONFIRM_MAX_ATTEMPTS) { + setTimeout(poll, CHATGPT_SEND_CONFIRM_POLL_MS); + } + }; + setTimeout(poll, CHATGPT_SEND_CONFIRM_POLL_MS); + } function clearPendingChatgptNewChatComposerClearMarker() { try { @@ -1970,21 +2165,26 @@ } } - function clearChatgptComposerDraftOnce() { + function clearChatgptComposerDraftOnce({ matchSentOnly = false, focus = true } = {}) { const editor = findProviderInput('chatgpt'); if (!editor) { return false; } - const currentText = editor.tagName === 'TEXTAREA' || editor.tagName === 'INPUT' - ? (editor.value || '') - : (editor.textContent || ''); + const currentText = readChatgptEditorText(editor); if (currentText.trim().length > 0) { + if (matchSentOnly && !isRecordedSentChatgptDraft(currentText)) { + return true; + } if (editor.tagName === 'TEXTAREA' || editor.tagName === 'INPUT') { setFormControlValue(editor, ''); } else { - clearRichTextInput('chatgpt', editor); + clearRichTextInput('chatgpt', editor, { focus }); } - console.log('[Text Injection] Cleared persisted ChatGPT draft after new chat'); + console.log( + matchSentOnly + ? '[Text Injection] Cleared restored sent ChatGPT draft after reload' + : '[Text Injection] Cleared persisted ChatGPT draft after new chat' + ); } return true; } @@ -2004,6 +2204,7 @@ function cancelChatgptNewChatComposerClear({ clearReloadMarker = true } = {}) { clearChatgptNewChatScheduledTimers(); disconnectChatgptNewChatMountObserver(); + chatgptActiveClearMatchSentOnly = false; if (clearReloadMarker) { clearPendingChatgptNewChatComposerClearMarker(); } @@ -2012,20 +2213,50 @@ } function handleChatgptNewChatUserInput(event) { - if (event.isTrusted) { - cancelChatgptNewChatComposerClear(); + if (!event?.isTrusted) { + return; } + if (event.type === 'keydown') { + if ( + event.metaKey || + event.ctrlKey || + event.altKey || + CHATGPT_NON_EDITING_KEYS.has(event.key) || + /^F\d{1,2}$/.test(event.key || '') + ) { + return; + } + } + cancelChatgptNewChatComposerClear(); } - function startChatgptPostMountClearPasses({ consumeReloadMarker = false } = {}) { + function startChatgptPostMountClearPasses({ + consumeReloadMarker = false, + matchSentOnly = false, + focus = true + } = {}) { clearChatgptNewChatScheduledTimers(); disconnectChatgptNewChatMountObserver(); + chatgptActiveClearMatchSentOnly = matchSentOnly; if (consumeReloadMarker) { clearPendingChatgptNewChatComposerClearMarker(); } + if (matchSentOnly) { + const observeRoot = document.body || document.documentElement; + if (typeof MutationObserver === 'function' && observeRoot) { + chatgptNewChatMountObserver = new MutationObserver(() => { + clearChatgptComposerDraftOnce({ matchSentOnly: true, focus }); + }); + chatgptNewChatMountObserver.observe(observeRoot, { + childList: true, + subtree: true, + characterData: true + }); + } + } CHATGPT_NEW_CHAT_CLEAR_DELAYS_MS.forEach((delay, index) => { const timerId = setTimeout(() => { - clearChatgptComposerDraftOnce(); + clearChatgptComposerDraftOnce({ matchSentOnly, focus }); if (index === CHATGPT_NEW_CHAT_CLEAR_DELAYS_MS.length - 1) { cancelChatgptNewChatComposerClear({ clearReloadMarker: consumeReloadMarker }); } @@ -2036,30 +2267,41 @@ function scheduleChatgptNewChatComposerClear({ waitForMountUntilMs = 0, - consumeReloadMarkerOnMount = false + consumeReloadMarkerOnMount = false, + matchSentOnly = false, + focus = true } = {}) { cancelChatgptNewChatComposerClear({ clearReloadMarker: false }); + chatgptActiveClearMatchSentOnly = matchSentOnly; document.addEventListener('keydown', handleChatgptNewChatUserInput, true); document.addEventListener('beforeinput', handleChatgptNewChatUserInput, true); if (!waitForMountUntilMs || findProviderInput('chatgpt')) { - startChatgptPostMountClearPasses({ consumeReloadMarker: consumeReloadMarkerOnMount }); + startChatgptPostMountClearPasses({ + consumeReloadMarker: consumeReloadMarkerOnMount, + matchSentOnly, + focus + }); return; } const remainingTtlMs = Math.max(0, waitForMountUntilMs - Date.now()); if (remainingTtlMs === 0) { - cancelChatgptNewChatComposerClear({ clearReloadMarker: true }); + cancelChatgptNewChatComposerClear({ clearReloadMarker: consumeReloadMarkerOnMount }); return; } const checkMountedOrExpired = () => { if (findProviderInput('chatgpt')) { - startChatgptPostMountClearPasses({ consumeReloadMarker: consumeReloadMarkerOnMount }); + startChatgptPostMountClearPasses({ + consumeReloadMarker: consumeReloadMarkerOnMount, + matchSentOnly, + focus + }); return true; } if (Date.now() >= waitForMountUntilMs) { - cancelChatgptNewChatComposerClear({ clearReloadMarker: true }); + cancelChatgptNewChatComposerClear({ clearReloadMarker: consumeReloadMarkerOnMount }); return true; } return false; @@ -2080,7 +2322,7 @@ const scheduleNextMountPoll = () => { const msLeft = waitForMountUntilMs - Date.now(); if (msLeft <= 0) { - cancelChatgptNewChatComposerClear({ clearReloadMarker: true }); + cancelChatgptNewChatComposerClear({ clearReloadMarker: consumeReloadMarkerOnMount }); return; } const pollTimerId = setTimeout(() => { @@ -2094,33 +2336,123 @@ scheduleNextMountPoll(); } - function resumePendingChatgptNewChatComposerClear() { - if (window.self === window.top || detectProvider() !== 'chatgpt') { + function scheduleChatgptSentDraftReloadClear() { + if (!isEmbeddedChatgptFrame() || !isChatgptHomePath()) { + return; + } + if ( + (chatgptNewChatClearTimerIds.length > 0 || Boolean(chatgptNewChatMountObserver)) && + !chatgptActiveClearMatchSentOnly + ) { + return; + } + if (readSentChatgptDrafts().length === 0) { return; } + scheduleChatgptNewChatComposerClear({ + waitForMountUntilMs: Date.now() + CHATGPT_RELOAD_CLEAR_WINDOW_MS, + consumeReloadMarkerOnMount: false, + matchSentOnly: true, + focus: false + }); + } - let rawTimestamp = null; + function handleChatgptRouteChange(previousUrl, currentUrl) { + if (!isEmbeddedChatgptFrame()) { + return; + } try { - rawTimestamp = window.sessionStorage?.getItem(CHATGPT_PENDING_NEW_CHAT_CLEAR_KEY) || null; + const prevPath = new URL(previousUrl).pathname; + const nextPath = new URL(currentUrl).pathname; + if (!isChatgptHomePath(prevPath) && isChatgptHomePath(nextPath)) { + scheduleChatgptSentDraftReloadClear(); + } } catch (error) { - return; + // Ignore malformed URLs. } + } - if (rawTimestamp === null) { + function setupChatgptSentDraftTracking() { + if (!isEmbeddedChatgptFrame()) { return; } + const sendButtonSelector = SEND_BUTTON_SELECTORS.chatgpt.join(', '); + const captureFromEditor = () => { + const editor = findProviderInput('chatgpt'); + const text = readChatgptEditorText(editor); + if (!text.trim()) { + return; + } + const startHref = window.location.href; + const wasBusyBeforeSend = Boolean(findChatgptBusyButton()); + setTimeout(() => confirmAndRecordChatgptSend(text, startHref, { wasBusyBeforeSend }), 0); + }; - const timestamp = Number(rawTimestamp); - const deadlineMs = timestamp + CHATGPT_PENDING_NEW_CHAT_CLEAR_TTL_MS; - if (!Number.isFinite(timestamp) || Date.now() >= deadlineMs) { - clearPendingChatgptNewChatComposerClearMarker(); + document.addEventListener('click', (event) => { + const target = event?.target; + if (!(target instanceof Element)) return; + const sendButton = target.closest(sendButtonSelector); + if (!sendButton || !isProviderSendControlEnabled('chatgpt', sendButton)) return; + const composerForm = getChatgptComposer()?.findForm(); + if (composerForm && sendButton.closest('form') !== composerForm) return; + captureFromEditor(); + }, true); + + document.addEventListener('submit', (event) => { + const composerForm = getChatgptComposer()?.findForm(); + if (composerForm && event?.target !== composerForm) return; + captureFromEditor(); + }, true); + + document.addEventListener('keydown', (event) => { + if ( + !event || + event.key !== 'Enter' || + event.shiftKey || + event.metaKey || + event.ctrlKey || + event.altKey || + event.isComposing + ) { + return; + } + const editor = findProviderInput('chatgpt'); + if (!editor) return; + const target = event.target; + if (target !== editor && !(target instanceof Node && editor.contains(target))) { + return; + } + captureFromEditor(); + }, true); + } + + function resumePendingChatgptNewChatComposerClear() { + if (!isEmbeddedChatgptFrame()) { return; } - scheduleChatgptNewChatComposerClear({ - waitForMountUntilMs: deadlineMs, - consumeReloadMarkerOnMount: true - }); + let rawTimestamp = null; + try { + rawTimestamp = window.sessionStorage?.getItem(CHATGPT_PENDING_NEW_CHAT_CLEAR_KEY) || null; + } catch (error) { + rawTimestamp = null; + } + + if (rawTimestamp !== null) { + const timestamp = Number(rawTimestamp); + const deadlineMs = timestamp + CHATGPT_PENDING_NEW_CHAT_CLEAR_TTL_MS; + if (!Number.isFinite(timestamp) || Date.now() >= deadlineMs) { + clearPendingChatgptNewChatComposerClearMarker(); + } else { + scheduleChatgptNewChatComposerClear({ + waitForMountUntilMs: deadlineMs, + consumeReloadMarkerOnMount: true + }); + return; + } + } + + scheduleChatgptSentDraftReloadClear(); } // Find and click new chat button @@ -4007,6 +4339,9 @@ // Handle INJECT_TEXT_WITH_IMAGES messages if (event.data.type === 'INJECT_TEXT_WITH_IMAGES' && event.data.context === 'multi-panel') { const provider = detectProvider(); + if (provider === 'chatgpt' && chatgptActiveClearMatchSentOnly) { + clearChatgptComposerDraftOnce({ matchSentOnly: true, focus: false }); + } // A fill right after New Chat must not be wiped by the pending draft clear. cancelChatgptNewChatComposerClear(); void handleImageInjection(event) @@ -4028,6 +4363,9 @@ if (event.data.type !== 'INJECT_TEXT') { return; } + if (detectProvider() === 'chatgpt' && chatgptActiveClearMatchSentOnly) { + clearChatgptComposerDraftOnce({ matchSentOnly: true, focus: false }); + } cancelChatgptNewChatComposerClear(); // Validate text payload @@ -5169,6 +5507,7 @@ // Listen for messages from the multi-panel host setupProviderLocationReporting(); setupPageWidthReporting(); + setupChatgptSentDraftTracking(); resumePendingChatgptNewChatComposerClear(); window.addEventListener('message', handleTextInjection); })(); diff --git a/tests/chatgpt-content-script.test.js b/tests/chatgpt-content-script.test.js index d0a4d87..7a4dc18 100644 --- a/tests/chatgpt-content-script.test.js +++ b/tests/chatgpt-content-script.test.js @@ -61,6 +61,8 @@ describe('chatgpt content script provider status', () => { beforeEach(() => { vi.restoreAllMocks(); window.happyDOM.setURL('https://chatgpt.com/c/test'); + window.localStorage?.removeItem('panelize:chatgpt-sent-drafts'); + window.sessionStorage?.removeItem('panelize:chatgpt-sent-drafts'); Object.defineProperty(window, 'parent', { configurable: true, value: { postMessage: vi.fn() }, @@ -532,4 +534,292 @@ describe('chatgpt content script provider status', () => { } }); }); + + describe('reload sent-draft clearing', () => { + async function bootEmbeddedChatgptFrame({ + url = 'https://chatgpt.com/', + sharedStorage = new Map(), + composerHtml = ` +
+
+ +
+ `, + } = {}) { + const { Window: HappyWindow } = await import('happy-dom'); + const frameWin = new HappyWindow({ url }); + const hostStub = { postMessage: vi.fn() }; + const extOrigin = chrome.runtime.getURL('').replace(/\/+$/, ''); + frameWin.chrome = globalThis.chrome; + Object.defineProperty(frameWin, 'parent', { configurable: true, value: hostStub }); + Object.defineProperty(frameWin, 'top', { configurable: true, value: hostStub }); + Object.defineProperty(frameWin, 'localStorage', { + configurable: true, + value: { + getItem: (key) => (sharedStorage.has(key) ? sharedStorage.get(key) : null), + setItem: (key, value) => sharedStorage.set(key, String(value)), + removeItem: (key) => sharedStorage.delete(key), + }, + }); + frameWin.document.body.innerHTML = composerHtml; + const editor = frameWin.document.querySelector('[contenteditable="true"], textarea'); + if (editor) { + Object.defineProperty(editor, 'offsetParent', { + configurable: true, + get: () => frameWin.document.body, + }); + } + const sendBtn = frameWin.document.querySelector('button[data-testid="send-button"]'); + if (sendBtn) { + Object.defineProperty(sendBtn, 'offsetParent', { + configurable: true, + get: () => frameWin.document.body, + }); + } + + frameWin.eval(composerScriptSource); + frameWin.eval(contentScriptSource); + + const postFromHost = (data) => { + frameWin.dispatchEvent( + new frameWin.MessageEvent('message', { + data, + source: hostStub, + origin: extOrigin, + }) + ); + }; + + return { frameWin, editor, sendBtn, postFromHost, sharedStorage }; + } + + it('clears a sent prompt restored after browser reload without stealing focus, including late hydration', async () => { + const sharedStorage = new Map(); + + // 1. Send a prompt via Multi-Panel and let ChatGPT clear the composer on send. + const first = await bootEmbeddedChatgptFrame({ sharedStorage }); + try { + first.sendBtn.addEventListener('click', () => { + first.editor.innerHTML = ''; + }); + first.postFromHost({ + type: 'INJECT_TEXT', + text: 'Hello after reload', + autoSubmit: true, + context: 'multi-panel', + }); + await wait(600); + expect(sharedStorage.get('panelize:chatgpt-sent-drafts')).toContain('Hello after reload'); + } finally { + await first.frameWin.happyDOM.close(); + } + + // 2. Simulate direct browser refresh: ChatGPT restores the sent prompt without New Chat marker. + const reloaded = await bootEmbeddedChatgptFrame({ sharedStorage }); + try { + const focusSpy = vi.spyOn(reloaded.editor, 'focus'); + reloaded.editor.innerHTML = '

Hello after reload

'; + await wait(250); + expect(reloaded.editor.textContent).toBe(''); + expect(focusSpy).not.toHaveBeenCalled(); + + // Late React hydration re-inserts the same sent draft -> cleared again without focus. + reloaded.editor.innerHTML = '

Hello after reload

'; + await wait(250); + expect(reloaded.editor.textContent).toBe(''); + expect(focusSpy).not.toHaveBeenCalled(); + } finally { + await reloaded.frameWin.happyDOM.close(); + } + }); + + it('preserves unsent drafts and unconfirmed failed sends across reload', async () => { + const sharedStorage = new Map(); + + // Send click does not clear the composer, show stop button, or navigate -> must not be recorded. + const first = await bootEmbeddedChatgptFrame({ sharedStorage }); + try { + first.postFromHost({ + type: 'INJECT_TEXT', + text: 'Failed send draft', + autoSubmit: true, + context: 'multi-panel', + }); + await wait(600); + expect(sharedStorage.get('panelize:chatgpt-sent-drafts')).toBeUndefined(); + } finally { + await first.frameWin.happyDOM.close(); + } + + // Record one real sent prompt, then reload with an unsent draft in the composer. + sharedStorage.set( + 'panelize:chatgpt-sent-drafts', + JSON.stringify([{ text: 'Already sent prompt', at: Date.now() }]) + ); + const reloaded = await bootEmbeddedChatgptFrame({ sharedStorage }); + try { + reloaded.editor.innerHTML = '

Unsent work in progress

'; + await wait(300); + expect(reloaded.editor.textContent).toBe('Unsent work in progress'); + } finally { + await reloaded.frameWin.happyDOM.close(); + } + }); + + it('records in-panel manual sends, clears on SPA return to home, ignores Cmd+R, and stops on trusted typing', async () => { + const sharedStorage = new Map(); + const frame = await bootEmbeddedChatgptFrame({ + url: 'https://chatgpt.com/c/conv-1', + sharedStorage, + }); + try { + frame.sendBtn.addEventListener('click', () => { + frame.editor.innerHTML = ''; + }); + frame.editor.innerHTML = '

Manual panel prompt

'; + frame.sendBtn.click(); + await wait(50); + expect(sharedStorage.get('panelize:chatgpt-sent-drafts')).toContain('Manual panel prompt'); + + // Navigate back to '/' via SPA pushState and restore the sent draft + frame.frameWin.history.pushState({}, '', '/'); + frame.editor.innerHTML = '

Manual panel prompt

'; + await wait(250); + expect(frame.editor.textContent).toBe(''); + + // Cmd+R shortcut does not cancel reload clearing + const cmdR = new frame.frameWin.KeyboardEvent('keydown', { key: 'r', metaKey: true, bubbles: true }); + Object.defineProperty(cmdR, 'isTrusted', { value: true }); + frame.frameWin.document.dispatchEvent(cmdR); + frame.editor.innerHTML = '

Manual panel prompt

'; + await wait(250); + expect(frame.editor.textContent).toBe(''); + + // Trusted editing key stops clearing so new user input is preserved + const typing = new frame.frameWin.KeyboardEvent('keydown', { key: 'a', bubbles: true }); + Object.defineProperty(typing, 'isTrusted', { value: true }); + frame.editor.dispatchEvent(typing); + frame.editor.innerHTML = '

Manual panel prompt

'; + await wait(300); + expect(frame.editor.textContent).toBe('Manual panel prompt'); + } finally { + await frame.frameWin.happyDOM.close(); + } + }); + + it('clears a restored sent draft right before a fresh Multi-Panel INJECT_TEXT fill', async () => { + const sharedStorage = new Map([ + [ + 'panelize:chatgpt-sent-drafts', + JSON.stringify([{ text: 'Old sent prompt', at: Date.now() }]), + ], + ]); + const reloaded = await bootEmbeddedChatgptFrame({ sharedStorage }); + try { + reloaded.editor.innerHTML = '

Old sent prompt

'; + reloaded.postFromHost({ + type: 'INJECT_TEXT', + text: 'Fresh prompt', + autoSubmit: false, + context: 'multi-panel', + }); + await wait(300); + expect(reloaded.editor.textContent).toBe('Fresh prompt'); + } finally { + await reloaded.frameWin.happyDOM.close(); + } + }); + + it('does not let SPA route-change reload clear override an active unconditional New Chat clear', async () => { + const sharedStorage = new Map([ + [ + 'panelize:chatgpt-sent-drafts', + JSON.stringify([{ text: 'Earlier sent prompt', at: Date.now() }]), + ], + ]); + const frame = await bootEmbeddedChatgptFrame({ + url: 'https://chatgpt.com/c/abc', + sharedStorage, + composerHtml: ` + New chat +
+
+ +
+ `, + }); + try { + const newChatLink = frame.frameWin.document.getElementById('spa-new-chat'); + Object.defineProperty(newChatLink, 'offsetParent', { + configurable: true, + get: () => frame.frameWin.document.body, + }); + newChatLink.getBoundingClientRect = () => ({ + x: 8, + y: 8, + width: 80, + height: 32, + top: 8, + left: 8, + right: 88, + bottom: 40, + }); + newChatLink.addEventListener('click', (event) => { + event.preventDefault(); + frame.frameWin.history.pushState({}, '', '/'); + }); + + frame.postFromHost({ + type: 'NEW_CHAT', + context: 'multi-panel', + }); + await wait(30); + + frame.editor.innerHTML = '

Unsent persisted home draft

'; + await wait(250); + expect(frame.editor.textContent).toBe(''); + } finally { + await frame.frameWin.happyDOM.close(); + } + }); + + it('does not record an Enter key press while already streaming as a sent draft or clear it after reload', async () => { + const sharedStorage = new Map(); + const streamingFrame = await bootEmbeddedChatgptFrame({ + url: 'https://chatgpt.com/c/streaming', + sharedStorage, + composerHtml: ` +
+

Follow-up typed while streaming

+ +
+ `, + }); + try { + const enterEvent = new streamingFrame.frameWin.KeyboardEvent('keydown', { + key: 'Enter', + code: 'Enter', + bubbles: true, + cancelable: true, + }); + streamingFrame.editor.dispatchEvent(enterEvent); + await wait(200); + expect(sharedStorage.get('panelize:chatgpt-sent-drafts')).toBeUndefined(); + } finally { + await streamingFrame.frameWin.happyDOM.close(); + } + + const reloaded = await bootEmbeddedChatgptFrame({ + url: 'https://chatgpt.com/', + sharedStorage, + }); + try { + reloaded.editor.innerHTML = '

Follow-up typed while streaming

'; + await wait(250); + expect(reloaded.editor.textContent).toBe('Follow-up typed while streaming'); + } finally { + await reloaded.frameWin.happyDOM.close(); + } + }); + }); }); diff --git a/tests/e2e/chatgpt-send-all.e2e.test.js b/tests/e2e/chatgpt-send-all.e2e.test.js index 9930b9c..fbed785 100644 --- a/tests/e2e/chatgpt-send-all.e2e.test.js +++ b/tests/e2e/chatgpt-send-all.e2e.test.js @@ -31,3 +31,46 @@ test('Send All supports the current ChatGPT composer without a legacy id', async await extension.close(); } }); + +test('direct page reload clears restored sent ChatGPT draft without erasing unsent drafts', async () => { + const extension = await launchExtension({ viewport: { width: 1280, height: 800 } }); + try { + await extension.context.route('https://chatgpt.com/**', route => route.fulfill({ + contentType: 'text/html', + body: renderChatgptFixture({ composer: 'current', persistDraftOnReload: true }), + })); + const page = await openMultiPanel(extension, { providers: ['chatgpt'] }); + const panel = page.frameLocator('iframe'); + const editor = panel.locator('[data-composer-placement="thread"] [data-composer-markdown]'); + await expect(editor).toBeVisible(); + + const readFixture = () => { + const frame = page.frames().find(candidate => candidate.url().startsWith('https://chatgpt.com/')); + return frame ? frame.evaluate(() => window.__fixture).catch(() => null) : null; + }; + + // 1. Send a prompt via Multi-Panel Send All and wait for confirmed submission + await page.locator('#unified-input').fill('Sent prompt before browser reload'); + await page.locator('#send-all-btn').click(); + await expect.poll(async () => (await readFixture())?.sentTexts) + .toEqual(['Sent prompt before browser reload']); + await expect(editor).toHaveText(''); + + // 2. Directly reload the Multi-Panel page (not clicking New Chat) + await page.reload(); + await expect(editor).toBeVisible(); + await page.waitForTimeout(450); + await expect(editor).toHaveText(''); + await expect(page.locator('#unified-input')).toBeFocused(); + + // 3. Fill an unsent draft (without sending) and reload -> must be preserved + await page.locator('#unified-input').fill('Unsent draft to keep'); + await page.locator('#fill-input-btn').click(); + await expect(editor).toHaveText('Unsent draft to keep'); + await page.reload(); + await expect(editor).toBeVisible(); + await expect(editor).toHaveText('Unsent draft to keep'); + } finally { + await extension.close(); + } +}); diff --git a/tests/e2e/fixtures/chatgpt-fixture.js b/tests/e2e/fixtures/chatgpt-fixture.js index 71496e3..89bb23e 100644 --- a/tests/e2e/fixtures/chatgpt-fixture.js +++ b/tests/e2e/fixtures/chatgpt-fixture.js @@ -26,8 +26,15 @@ export function renderChatgptFixture({ sendStealDelays = [], busyAfterSendMs = 0, composer = 'legacy', + persistDraftOnReload = false, } = {}) { - const config = { loadStealDelays, newChatStealDelays, sendStealDelays, busyAfterSendMs }; + const config = { + loadStealDelays, + newChatStealDelays, + sendStealDelays, + busyAfterSendMs, + persistDraftOnReload, + }; const composerHtml = COMPOSER_HTML[composer]; if (!composerHtml) { throw new Error(`Unknown ChatGPT fixture composer: ${composer}`); @@ -71,6 +78,22 @@ ${composerHtml} scheduleComposerFocus(config.loadStealDelays, 'load'); + if (config.persistDraftOnReload) { + const DRAFT_KEY = '__fixture_persisted_draft'; + const savedDraft = window.localStorage.getItem(DRAFT_KEY); + if (savedDraft) { + setTimeout(() => { + composer.innerHTML = '

' + savedDraft + '

'; + }, 120); + } + composer.addEventListener('input', () => { + const text = (composer.textContent || '').trim(); + if (text) { + window.localStorage.setItem(DRAFT_KEY, text); + } + }); + } + document.querySelector('[data-testid="new-chat-button"]').addEventListener('click', () => { window.__fixture.newChats += 1; composer.textContent = '';