diff --git a/modules/open-mode-switcher.js b/modules/open-mode-switcher.js new file mode 100644 index 0000000..fb2995e --- /dev/null +++ b/modules/open-mode-switcher.js @@ -0,0 +1,314 @@ +/** + * In-place open-mode switching between a normal browser tab and a standalone + * popup window. Moves the existing tab across windows so the Multi-Panel page + * and all embedded provider iframes keep their live state without reloading. + */ + +export const DEFAULT_POPUP_WIDTH = 1400; +export const DEFAULT_POPUP_HEIGHT = 900; +export const PRESERVED_STATE_KEY = 'preservedState'; +export const HANDOFF_QUERY_PARAM = 'openModeHandoff'; + +const TRANSIENT_TAB_EDIT_ERROR_PATTERN = /tabs cannot be edited right now/i; +const DEFAULT_TRANSIENT_MAX_RETRIES = 4; +const DEFAULT_TRANSIENT_RETRY_DELAY_MS = 60; + +/** + * Thrown only when the host environment lacks the tab/window APIs required for + * in-place tab adoption (indicating a legacy recreate fallback is needed). + */ +export class OpenModeSwitchUnsupportedError extends Error { + constructor(message) { + super(message); + this.name = 'OpenModeSwitchUnsupportedError'; + } +} + +/** + * Returns true when Chrome rejected a tab/window mutation because the tab strip + * is momentarily locked (for example, while the user is dragging a tab). + * + * @param {unknown} error + * @returns {boolean} + */ +export function isTransientTabEditError(error) { + const message = typeof error === 'string' ? error : error?.message; + return typeof message === 'string' && TRANSIENT_TAB_EDIT_ERROR_PATTERN.test(message); +} + +function defaultSleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** + * Retries a Chrome tab/window mutation on transient tab-strip-busy errors. + * + * @template T + * @param {() => Promise} operation + * @param {object} [options] + * @param {number} [options.maxRetries] + * @param {number} [options.retryDelayMs] + * @param {(ms: number) => Promise} [options.sleep] + * @returns {Promise} + */ +export async function retryOnTransientTabEditError( + operation, + { + maxRetries = DEFAULT_TRANSIENT_MAX_RETRIES, + retryDelayMs = DEFAULT_TRANSIENT_RETRY_DELAY_MS, + sleep = defaultSleep + } = {} +) { + let attempt = 0; + while (true) { + try { + return await operation(); + } catch (error) { + if (!isTransientTabEditError(error) || attempt >= maxRetries) { + throw error; + } + attempt += 1; + await sleep(retryDelayMs); + } + } +} + +export function createHandoffStorageKey(token) { + return `${PRESERVED_STATE_KEY}:${token}`; +} + +export function generateHandoffToken() { + if (typeof globalThis?.crypto?.randomUUID === 'function') { + return globalThis.crypto.randomUUID(); + } + return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; +} + +export function getHandoffTokenFromUrl(urlString) { + if (!urlString) { + return null; + } + try { + const token = new URL(urlString).searchParams.get(HANDOFF_QUERY_PARAM); + return token && token.trim() ? token.trim() : null; + } catch { + return null; + } +} + +export function stripHandoffTokenFromUrl(urlString) { + if (!urlString) { + return null; + } + try { + const parsed = new URL(urlString); + if (!parsed.searchParams.has(HANDOFF_QUERY_PARAM)) { + return null; + } + parsed.searchParams.delete(HANDOFF_QUERY_PARAM); + return parsed.toString(); + } catch { + return null; + } +} + +/** + * Finds the best existing normal browser window that can accept the tab when + * returning from popup mode to tab mode. + * + * @param {typeof chrome} chromeApi + * @param {object} [options] + * @param {number|null} [options.preferredWindowId] - Normal window the tab originally came from. + * @param {boolean} [options.incognito] - Required incognito profile match. + * @returns {Promise} + */ +export async function findTargetNormalWindow( + chromeApi, + { preferredWindowId = null, incognito = undefined } = {} +) { + if (typeof chromeApi?.windows?.getAll !== 'function') { + return null; + } + + const normalWindows = await chromeApi.windows.getAll({ windowTypes: ['normal'] }); + const candidates = (Array.isArray(normalWindows) ? normalWindows : []).filter( + (win) => + win && + win.id != null && + (typeof incognito !== 'boolean' || Boolean(win.incognito) === incognito) + ); + + if (candidates.length === 0) { + return null; + } + + if (preferredWindowId != null) { + const preferred = candidates.find((win) => win.id === preferredWindowId); + if (preferred) { + return preferred; + } + } + + if (typeof chromeApi?.windows?.getLastFocused === 'function') { + try { + const lastFocused = await chromeApi.windows.getLastFocused({ windowTypes: ['normal'] }); + if (lastFocused?.id != null) { + const matched = candidates.find((win) => win.id === lastFocused.id); + if (matched) { + return matched; + } + } + } catch { + // Ignore if Chrome has no focused normal window matching the filter. + } + } + + return candidates.find((win) => win.state !== 'minimized') || candidates[0]; +} + +/** + * Moves the current extension tab in-place between a normal browser window and + * a standalone popup window without reloading the document or its iframes. + * + * @param {typeof chrome} chromeApi + * @param {object} [options] + * @param {number|null} [options.preferredNormalWindowId] - Normal window to prefer when returning to tab mode. + * @param {number} [options.popupWidth] + * @param {number} [options.popupHeight] + * @param {number} [options.maxRetries] + * @param {number} [options.retryDelayMs] + * @param {(ms: number) => Promise} [options.sleep] + * @returns {Promise<{ + * mode: 'tab'|'popup', + * isPopupWindow: boolean, + * windowId: number|null, + * tabId: number, + * previousNormalWindowId: number|null + * }>} + */ +export async function switchTabOpenMode( + chromeApi, + { + preferredNormalWindowId = null, + popupWidth = DEFAULT_POPUP_WIDTH, + popupHeight = DEFAULT_POPUP_HEIGHT, + maxRetries = DEFAULT_TRANSIENT_MAX_RETRIES, + retryDelayMs = DEFAULT_TRANSIENT_RETRY_DELAY_MS, + sleep = defaultSleep + } = {} +) { + if ( + typeof chromeApi?.windows?.getCurrent !== 'function' || + typeof chromeApi?.tabs?.getCurrent !== 'function' || + typeof chromeApi?.windows?.create !== 'function' + ) { + throw new OpenModeSwitchUnsupportedError('Required chrome.windows/tabs APIs are unavailable'); + } + + const [currentWindow, currentTab] = await Promise.all([ + chromeApi.windows.getCurrent(), + chromeApi.tabs.getCurrent() + ]); + + if (!currentWindow || currentTab?.id == null) { + throw new OpenModeSwitchUnsupportedError('Unable to resolve current tab or window'); + } + + const retryOptions = { maxRetries, retryDelayMs, sleep }; + const wasPopup = currentWindow.type === 'popup'; + + if (!wasPopup) { + const previousNormalWindowId = currentWindow.id ?? currentTab.windowId ?? null; + const popupWindow = await retryOnTransientTabEditError( + () => + chromeApi.windows.create({ + tabId: currentTab.id, + type: 'popup', + width: popupWidth, + height: popupHeight, + focused: true + }), + retryOptions + ); + + return { + mode: 'popup', + isPopupWindow: true, + windowId: popupWindow?.id ?? null, + tabId: currentTab.id, + previousNormalWindowId + }; + } + + const targetWindow = await findTargetNormalWindow(chromeApi, { + preferredWindowId: preferredNormalWindowId, + incognito: currentWindow.incognito + }); + + if (targetWindow && typeof chromeApi?.tabs?.move === 'function') { + let moved = false; + try { + await retryOnTransientTabEditError( + () => + chromeApi.tabs.move(currentTab.id, { + windowId: targetWindow.id, + index: -1 + }), + retryOptions + ); + moved = true; + } catch (moveError) { + if (isTransientTabEditError(moveError)) { + throw moveError; + } + // Target window may have closed concurrently or refused cross-type move; + // fall through to creating a new normal window adopting the existing tab. + } + + if (moved) { + if (typeof chromeApi?.tabs?.update === 'function') { + try { + await chromeApi.tabs.update(currentTab.id, { active: true }); + } catch { + // Best-effort activation after the tab has already moved. + } + } + if (typeof chromeApi?.windows?.update === 'function') { + try { + const updateInfo = targetWindow.state === 'minimized' + ? { state: 'normal', focused: true } + : { focused: true }; + await chromeApi.windows.update(targetWindow.id, updateInfo); + } catch { + // Best-effort focus after the tab has already moved. + } + } + + return { + mode: 'tab', + isPopupWindow: false, + windowId: targetWindow.id, + tabId: currentTab.id, + previousNormalWindowId: targetWindow.id + }; + } + } + + const normalWindow = await retryOnTransientTabEditError( + () => + chromeApi.windows.create({ + tabId: currentTab.id, + type: 'normal', + focused: true + }), + retryOptions + ); + + return { + mode: 'tab', + isPopupWindow: false, + windowId: normalWindow?.id ?? null, + tabId: currentTab.id, + previousNormalWindowId: normalWindow?.id ?? null + }; +} diff --git a/multi-panel/multi-panel.js b/multi-panel/multi-panel.js index 7416f34..5b93d5a 100644 --- a/multi-panel/multi-panel.js +++ b/multi-panel/multi-panel.js @@ -118,6 +118,18 @@ import { updatePanelFitState } from '../modules/panel-fit.js'; import { setupPanelResize } from '../modules/panel-resize.js'; +import { + DEFAULT_POPUP_HEIGHT, + DEFAULT_POPUP_WIDTH, + HANDOFF_QUERY_PARAM, + OpenModeSwitchUnsupportedError, + PRESERVED_STATE_KEY, + createHandoffStorageKey, + generateHandoffToken, + getHandoffTokenFromUrl, + stripHandoffTokenFromUrl, + switchTabOpenMode +} from '../modules/open-mode-switcher.js'; import { createPointerGuard, createPointerTracker } from '../modules/pointer-guard.js'; @@ -222,9 +234,13 @@ let currentGoogleProviderMode = DEFAULT_GOOGLE_PROVIDER_MODE; // 提示词编辑器状态 let currentEditingPromptId = null; -// 打开模式状态 -let currentOpenMode = 'tab'; // 'tab' 或 'popup' -let isPopupWindow = false; // 当前窗口是否为弹出窗口 +// Open mode state +let isPopupWindow = false; // Whether the current window is a popup window +let currentTabId = null; +let lastNormalWindowId = null; +let isTogglingOpenMode = false; +let tabAttachmentListenerRegistered = false; +let pendingTabAttachmentWindowId = null; // Default panel configuration const DEFAULT_PROVIDERS = DEFAULT_PROVIDER_IDS; @@ -280,6 +296,7 @@ async function init() { translatePage(); registerRuntimeMessageListener(); registerStorageChangeListener(); + registerTabAttachmentListener(); // Detect window type and load mode await detectWindowType(); @@ -1351,12 +1368,10 @@ async function loadSettings() { const settings = await chrome.storage.sync.get({ multiPanelLayout: '1x3', multiPanelProviders: DEFAULT_PROVIDERS, - openMode: 'tab', googleProviderMode: DEFAULT_GOOGLE_PROVIDER_MODE }); currentLayout = normalizeLayout(settings.multiPanelLayout); - currentOpenMode = settings.openMode || 'tab'; currentGoogleProviderMode = normalizeGoogleProviderMode(settings.googleProviderMode); // Apply layout @@ -1368,15 +1383,42 @@ async function loadSettings() { } // ===== Open Mode Management ===== +function registerTabAttachmentListener() { + if (tabAttachmentListenerRegistered || !chrome?.tabs?.onAttached?.addListener) { + return; + } + + tabAttachmentListenerRegistered = true; + chrome.tabs.onAttached.addListener((attachedTabId, attachInfo) => { + if (currentTabId == null || attachedTabId !== currentTabId) { + return; + } + + if (isTogglingOpenMode) { + pendingTabAttachmentWindowId = attachInfo?.newWindowId ?? Symbol('attached'); + return; + } + + detectWindowType(); + }); +} + async function detectWindowType() { try { - const currentWindow = await chrome.windows.getCurrent(); - // popup 类型的窗口 type 为 'popup' - isPopupWindow = currentWindow.type === 'popup'; - - // 读取设置中的模式 - const settings = await chrome.storage.sync.get({ openMode: 'tab' }); - currentOpenMode = settings.openMode; + const [currentWindow, currentTab] = await Promise.all([ + chrome.windows.getCurrent(), + typeof chrome?.tabs?.getCurrent === 'function' + ? chrome.tabs.getCurrent().catch(() => null) + : Promise.resolve(null) + ]); + + isPopupWindow = currentWindow?.type === 'popup'; + if (currentTab?.id != null) { + currentTabId = currentTab.id; + } + if (!isPopupWindow && currentWindow?.id != null) { + lastNormalWindowId = currentWindow.id; + } updateToggleButton(); } catch (error) { @@ -1392,12 +1434,10 @@ function updateToggleButton() { const text = btn.querySelector('.btn-text'); if (isPopupWindow) { - // 当前是弹出窗口,提示可以切换到标签页 icon.textContent = 'tab'; text.textContent = t('switchToTabMode') || 'Tab Mode'; btn.title = t('switchToTabModeTitle') || 'Switch to Tab Mode'; } else { - // 当前是标签页,提示可以切换到弹出窗口 icon.textContent = 'open_in_new'; text.textContent = t('switchToPopupMode') || 'Popup Mode'; btn.title = t('switchToPopupModeTitle') || 'Switch to Popup Mode'; @@ -1418,62 +1458,165 @@ function collectCurrentState() { return state; } -async function toggleOpenMode() { - // 1. 收集当前状态 +async function clearPreservedStateKey(storageKey) { + const removals = []; + if (typeof chrome?.storage?.session?.remove === 'function') { + removals.push(chrome.storage.session.remove(storageKey)); + } + if (typeof chrome?.storage?.local?.remove === 'function') { + removals.push(chrome.storage.local.remove(storageKey)); + } + await Promise.allSettled(removals); +} + +async function fallbackRecreateForOpenMode(targetIsPopup) { const state = collectCurrentState(); + const handoffToken = generateHandoffToken(); + const storageKey = createHandoffStorageKey(handoffToken); - // 2. 保存状态到 storage(临时) try { await chrome.storage.session.set({ - preservedState: state + [storageKey]: state }); } catch (error) { console.error('Error saving state:', error); - // Fallback to local storage if session storage fails await chrome.storage.local.set({ - preservedState: state + [storageKey]: state }); } - // 3. 切换设置 - const newMode = isPopupWindow ? 'tab' : 'popup'; - await chrome.storage.sync.set({ openMode: newMode }); + const targetUrl = new URL(chrome.runtime.getURL('multi-panel/multi-panel.html')); + targetUrl.searchParams.set(HANDOFF_QUERY_PARAM, handoffToken); + const multiPanelUrl = targetUrl.toString(); + const newMode = targetIsPopup ? 'popup' : 'tab'; + + try { + if (!targetIsPopup) { + await chrome.tabs.create({ url: multiPanelUrl, active: true }); + } else { + await chrome.windows.create({ + url: multiPanelUrl, + type: 'popup', + width: DEFAULT_POPUP_WIDTH, + height: DEFAULT_POPUP_HEIGHT + }); + } + } catch (createError) { + await clearPreservedStateKey(storageKey); + throw createError; + } - // 4. 在新模式下打开 - const multiPanelUrl = chrome.runtime.getURL('multi-panel/multi-panel.html'); + try { + await chrome.storage.sync.set({ openMode: newMode }); + } catch (storageError) { + console.error('Error saving open mode setting:', storageError); + } - if (isPopupWindow) { - // 从弹出窗口切换到标签页:创建新标签页,关闭当前窗口 - await chrome.tabs.create({ url: multiPanelUrl, active: true }); - window.close(); // 关闭当前弹出窗口 + if (!targetIsPopup) { + window.close(); } else { - // 从标签页切换到弹出窗口:创建弹出窗口,关闭当前标签页 - await chrome.windows.create({ - url: multiPanelUrl, - type: 'popup', - width: 1400, - height: 900 - }); - // 获取当前标签页并关闭 - const currentTab = await chrome.tabs.getCurrent(); - if (currentTab) { + const currentTab = typeof chrome?.tabs?.getCurrent === 'function' + ? await chrome.tabs.getCurrent().catch(() => null) + : null; + if (currentTab?.id != null && typeof chrome?.tabs?.remove === 'function') { await chrome.tabs.remove(currentTab.id); + } else { + window.close(); + } + } +} + +export async function toggleOpenMode() { + if (isTogglingOpenMode) { + return; + } + + isTogglingOpenMode = true; + pendingTabAttachmentWindowId = null; + let expectedWindowId = null; + try { + try { + const result = await switchTabOpenMode(chrome, { + preferredNormalWindowId: lastNormalWindowId + }); + + expectedWindowId = result.windowId; + isPopupWindow = result.isPopupWindow; + currentTabId = result.tabId; + if (result.previousNormalWindowId != null) { + lastNormalWindowId = result.previousNormalWindowId; + } + + updateToggleButton(); + + try { + await chrome.storage.sync.set({ openMode: result.mode }); + } catch (storageError) { + console.error('Error saving open mode setting:', storageError); + } + + return; + } catch (reparentError) { + if (reparentError instanceof OpenModeSwitchUnsupportedError) { + console.warn('In-place mode switch unsupported, falling back to recreate:', reparentError); + try { + await fallbackRecreateForOpenMode(!isPopupWindow); + } catch (fallbackError) { + console.error('Fallback mode switch failed:', fallbackError); + showToast(t('msgOpenModeSwitchFailed') || 'Unable to switch window mode right now. Please try again.'); + } + return; + } + + // Keep the live page and active chats intact when Chrome rejects a tab + // or window edit transiently (for example while the user drags a tab). + console.warn('In-place mode switch failed; preserving current session:', reparentError); + showToast(t('msgOpenModeSwitchFailed') || 'Unable to switch window mode right now. Please try again.'); + } + } finally { + const observedWindowId = pendingTabAttachmentWindowId; + pendingTabAttachmentWindowId = null; + isTogglingOpenMode = false; + + if ( + observedWindowId != null && + (expectedWindowId == null || observedWindowId !== expectedWindowId) + ) { + await detectWindowType(); } } } async function restoreStateIfNeeded() { try { + const currentHref = typeof window !== 'undefined' ? window.location?.href : null; + const handoffToken = getHandoffTokenFromUrl(currentHref); + const storageKey = handoffToken + ? createHandoffStorageKey(handoffToken) + : PRESERVED_STATE_KEY; + // Try session storage first, then local storage - let result = await chrome.storage.session.get('preservedState'); - if (!result.preservedState) { - result = await chrome.storage.local.get('preservedState'); + let result = typeof chrome?.storage?.session?.get === 'function' + ? await chrome.storage.session.get(storageKey).catch(() => ({})) + : {}; + if (!result?.[storageKey] && typeof chrome?.storage?.local?.get === 'function') { + result = await chrome.storage.local.get(storageKey); } - if (result.preservedState) { - const state = result.preservedState; + if (handoffToken) { + const cleanedUrl = stripHandoffTokenFromUrl(currentHref); + if (cleanedUrl && typeof window?.history?.replaceState === 'function') { + try { + window.history.replaceState(null, '', cleanedUrl); + } catch { + // Ignore History API restrictions in synthetic test environments. + } + } + } - // 恢复输入文本 + const state = result?.[storageKey]; + if (state) { + // Restore unified input text const input = document.getElementById('unified-input'); if (input && state.inputText) { input.value = state.inputText; @@ -1481,13 +1624,13 @@ async function restoreStateIfNeeded() { resizeTextarea(); } - // 恢复图片 + // Restore uploaded images if (state.uploadedImages && state.uploadedImages.length > 0) { uploadedImages = state.uploadedImages; renderImagePreviews(); } - // 恢复布局 + // Restore layout if (state.currentLayout) { currentLayout = normalizeLayout(state.currentLayout); const panelGrid = document.getElementById('panel-grid'); @@ -1496,7 +1639,7 @@ async function restoreStateIfNeeded() { } } - // 恢复面板配置(保存到 multiPanelProviders) + // Restore panel configuration (save to multiPanelProviders) if (state.panels && state.panels.length > 0) { const providerIds = state.panels.map(p => p.providerId); const existing = await chrome.storage.sync.get({ multiPanelProviders: null }); @@ -1514,9 +1657,7 @@ async function restoreStateIfNeeded() { }); } - // 清除已恢复的状态 - await chrome.storage.session.remove('preservedState'); - await chrome.storage.local.remove('preservedState'); + await clearPreservedStateKey(storageKey); } } catch (error) { console.error('Error restoring state:', error); diff --git a/tests/e2e/open-mode-switch.e2e.test.js b/tests/e2e/open-mode-switch.e2e.test.js new file mode 100644 index 0000000..ce4a25b --- /dev/null +++ b/tests/e2e/open-mode-switch.e2e.test.js @@ -0,0 +1,218 @@ +import { test, expect } from '@playwright/test'; +import { launchExtension, openMultiPanel } from './extension-harness.js'; +import { renderChatgptFixture } from './fixtures/chatgpt-fixture.js'; + +async function readModeState(page) { + return page.evaluate(async () => { + const [win, syncSettings] = await Promise.all([ + chrome.windows.getCurrent(), + chrome.storage.sync.get({ openMode: null }) + ]); + return { + windowType: win.type, + toggleIcon: document.querySelector('#toggle-open-mode-btn .material-symbols-outlined')?.textContent, + openMode: syncSettings.openMode + }; + }); +} + +test('switching between Tab Mode and Popup Mode preserves live chat state without reloading', 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' }) + })); + + // Keep another tab open in the initial normal window so it stays alive after popout. + const companionTab = await extension.context.newPage(); + await companionTab.goto('about:blank'); + + 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 getProviderFrame = () => + page.frames().find((candidate) => candidate.url().startsWith('https://chatgpt.com/')); + + const initialMeta = await page.evaluate(async () => { + window.__panelizeHostSessionToken = 'host-session-alive'; + const [win, tab] = await Promise.all([ + chrome.windows.getCurrent(), + chrome.tabs.getCurrent() + ]); + return { windowId: win.id, windowType: win.type, tabId: tab.id }; + }); + expect(initialMeta.windowType).toBe('normal'); + + const providerFrame = getProviderFrame(); + expect(providerFrame).toBeTruthy(); + await providerFrame.evaluate(() => { + window.__providerChatSessionToken = 'iframe-session-alive'; + }); + + // Turn 1: send a message before switching modes, plus keep an unsent draft in the unified input. + await page.locator('#unified-input').fill('First turn before popup'); + await page.locator('#send-all-btn').click(); + await expect.poll(async () => (await getProviderFrame()?.evaluate(() => window.__fixture?.sentTexts)) ?? null) + .toEqual(['First turn before popup']); + + await page.locator('#unified-input').fill('Draft preserved across mode switch'); + + // Switch Tab Mode -> Popup Mode + await page.locator('#toggle-open-mode-btn').click(); + + await expect.poll(() => readModeState(page)).toEqual({ + windowType: 'popup', + toggleIcon: 'tab', + openMode: 'popup' + }); + + const popupState = await page.evaluate(async () => { + const [win, tab, sessionState, localState] = await Promise.all([ + chrome.windows.getCurrent(), + chrome.tabs.getCurrent(), + chrome.storage.session.get(null), + chrome.storage.local.get(null) + ]); + const hasPreservedState = (obj) => + Object.keys(obj || {}).some((key) => key === 'preservedState' || key.startsWith('preservedState:')); + return { + hostToken: window.__panelizeHostSessionToken, + windowType: win.type, + windowId: win.id, + tabId: tab.id, + draft: document.getElementById('unified-input')?.value, + hasSessionPreservedState: hasPreservedState(sessionState), + hasLocalPreservedState: hasPreservedState(localState) + }; + }); + + expect(popupState.hostToken).toBe('host-session-alive'); + expect(popupState.windowType).toBe('popup'); + expect(popupState.tabId).toBe(initialMeta.tabId); + expect(popupState.draft).toBe('Draft preserved across mode switch'); + expect(popupState.hasSessionPreservedState).toBe(false); + expect(popupState.hasLocalPreservedState).toBe(false); + + const frameStateInPopup = await getProviderFrame().evaluate(() => ({ + token: window.__providerChatSessionToken, + sentTexts: window.__fixture.sentTexts + })); + expect(frameStateInPopup).toEqual({ + token: 'iframe-session-alive', + sentTexts: ['First turn before popup'] + }); + + // Turn 2: continue chatting inside Popup Mode + await page.locator('#unified-input').fill('Second turn inside popup'); + await page.locator('#send-all-btn').click(); + await expect.poll(async () => (await getProviderFrame()?.evaluate(() => window.__fixture?.sentTexts)) ?? null) + .toEqual(['First turn before popup', 'Second turn inside popup']); + + // Switch Popup Mode -> Tab Mode + await page.locator('#toggle-open-mode-btn').click(); + + await expect.poll(() => readModeState(page)).toEqual({ + windowType: 'normal', + toggleIcon: 'open_in_new', + openMode: 'tab' + }); + + const backInTabState = await page.evaluate(async () => { + const [win, tab] = await Promise.all([ + chrome.windows.getCurrent(), + chrome.tabs.getCurrent() + ]); + return { + hostToken: window.__panelizeHostSessionToken, + windowType: win.type, + windowId: win.id, + tabId: tab.id + }; + }); + + expect(backInTabState.hostToken).toBe('host-session-alive'); + expect(backInTabState.windowType).toBe('normal'); + expect(backInTabState.windowId).toBe(initialMeta.windowId); + expect(backInTabState.tabId).toBe(initialMeta.tabId); + + const frameStateBackInTab = await getProviderFrame().evaluate(() => ({ + token: window.__providerChatSessionToken, + sentTexts: window.__fixture.sentTexts + })); + expect(frameStateBackInTab).toEqual({ + token: 'iframe-session-alive', + sentTexts: ['First turn before popup', 'Second turn inside popup'] + }); + + // Turn 3: continue chatting after returning to Tab Mode + await page.locator('#unified-input').fill('Third turn back in tab'); + await page.locator('#send-all-btn').click(); + await expect.poll(async () => (await getProviderFrame()?.evaluate(() => window.__fixture?.sentTexts)) ?? null) + .toEqual([ + 'First turn before popup', + 'Second turn inside popup', + 'Third turn back in tab' + ]); + } finally { + await extension.close(); + } +}); + +test('returning from Popup Mode to Tab Mode creates a normal window without reload when no normal window exists', 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' }) + })); + + const page = await openMultiPanel(extension, { providers: ['chatgpt'] }); + const panel = page.frameLocator('iframe'); + await expect(panel.locator('[data-composer-placement="thread"] [data-composer-markdown]')).toBeVisible(); + + const getProviderFrame = () => + page.frames().find((candidate) => candidate.url().startsWith('https://chatgpt.com/')); + + await page.evaluate(() => { + window.__panelizeHostSessionToken = 'solo-popup-alive'; + }); + await getProviderFrame().evaluate(() => { + window.__providerChatSessionToken = 'solo-iframe-alive'; + }); + + // Switch to Popup Mode + await page.locator('#toggle-open-mode-btn').click(); + await expect.poll(() => readModeState(page)).toEqual({ + windowType: 'popup', + toggleIcon: 'tab', + openMode: 'popup' + }); + + // Close every remaining normal window so none exist + await page.evaluate(async () => { + const normalWindows = await chrome.windows.getAll({ windowTypes: ['normal'] }); + for (const win of normalWindows) { + await chrome.windows.remove(win.id); + } + }); + + // Switch back to Tab Mode with zero normal windows open + await page.locator('#toggle-open-mode-btn').click(); + await expect.poll(() => readModeState(page)).toEqual({ + windowType: 'normal', + toggleIcon: 'open_in_new', + openMode: 'tab' + }); + + const hostToken = await page.evaluate(() => window.__panelizeHostSessionToken); + const frameToken = await getProviderFrame().evaluate(() => window.__providerChatSessionToken); + + expect(hostToken).toBe('solo-popup-alive'); + expect(frameToken).toBe('solo-iframe-alive'); + } finally { + await extension.close(); + } +}); diff --git a/tests/open-mode-switcher.test.js b/tests/open-mode-switcher.test.js new file mode 100644 index 0000000..2d4e467 --- /dev/null +++ b/tests/open-mode-switcher.test.js @@ -0,0 +1,689 @@ +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { + DEFAULT_POPUP_HEIGHT, + DEFAULT_POPUP_WIDTH, + HANDOFF_QUERY_PARAM, + OpenModeSwitchUnsupportedError, + createHandoffStorageKey, + findTargetNormalWindow, + getHandoffTokenFromUrl, + isTransientTabEditError, + retryOnTransientTabEditError, + stripHandoffTokenFromUrl, + switchTabOpenMode +} from '../modules/open-mode-switcher.js'; + +const multiPanelHtml = readFileSync( + path.resolve(process.cwd(), 'multi-panel/multi-panel.html'), + 'utf8' +); + +function createChromeMock({ + currentWindow = { id: 10, type: 'normal', incognito: false, state: 'normal' }, + currentTab = { id: 101, windowId: 10 }, + normalWindows = [currentWindow], + lastFocusedNormal = null +} = {}) { + return { + windows: { + getCurrent: vi.fn(async () => currentWindow), + getAll: vi.fn(async () => normalWindows), + getLastFocused: vi.fn(async () => { + if (lastFocusedNormal instanceof Error) { + throw lastFocusedNormal; + } + return lastFocusedNormal; + }), + create: vi.fn(async (createData) => ({ + id: createData.type === 'popup' ? 20 : 30, + type: createData.type, + incognito: Boolean(currentWindow.incognito) + })), + update: vi.fn(async (windowId, updateInfo) => ({ id: windowId, ...updateInfo })) + }, + tabs: { + getCurrent: vi.fn(async () => currentTab), + move: vi.fn(async (tabId, moveProps) => ({ id: tabId, windowId: moveProps.windowId })), + update: vi.fn(async (tabId, updateProps) => ({ id: tabId, ...updateProps })) + } + }; +} + +describe('open-mode-switcher', () => { + describe('transient error retry and handoff URL helpers', () => { + it('detects Chrome tab-strip-busy errors accurately', () => { + expect( + isTransientTabEditError( + new Error('Tabs cannot be edited right now (user may be dragging a tab).') + ) + ).toBe(true); + expect(isTransientTabEditError('Tabs cannot be edited right now')).toBe(true); + expect(isTransientTabEditError(new Error('No window with id: 10.'))).toBe(false); + expect(isTransientTabEditError(null)).toBe(false); + }); + + it('retries transient tab-edit errors until the operation succeeds', async () => { + const sleep = vi.fn(async () => {}); + let attempts = 0; + const result = await retryOnTransientTabEditError( + async () => { + attempts += 1; + if (attempts < 3) { + throw new Error('Tabs cannot be edited right now (user may be dragging a tab).'); + } + return 'moved'; + }, + { maxRetries: 4, retryDelayMs: 25, sleep } + ); + + expect(result).toBe('moved'); + expect(attempts).toBe(3); + expect(sleep).toHaveBeenCalledTimes(2); + expect(sleep).toHaveBeenCalledWith(25); + }); + + it('does not retry non-transient errors', async () => { + const sleep = vi.fn(async () => {}); + let attempts = 0; + + await expect( + retryOnTransientTabEditError( + async () => { + attempts += 1; + throw new Error('No window with id: 42.'); + }, + { maxRetries: 4, retryDelayMs: 25, sleep } + ) + ).rejects.toThrow('No window with id: 42.'); + + expect(attempts).toBe(1); + expect(sleep).not.toHaveBeenCalled(); + }); + + it('extracts and strips scoped handoff tokens from URLs', () => { + const url = `chrome-extension://abc/multi-panel/multi-panel.html?foo=1&${HANDOFF_QUERY_PARAM}=tok-123`; + expect(getHandoffTokenFromUrl(url)).toBe('tok-123'); + expect(stripHandoffTokenFromUrl(url)).toBe( + 'chrome-extension://abc/multi-panel/multi-panel.html?foo=1' + ); + expect(getHandoffTokenFromUrl('chrome-extension://abc/multi-panel/multi-panel.html')).toBeNull(); + expect(stripHandoffTokenFromUrl('chrome-extension://abc/multi-panel/multi-panel.html')).toBeNull(); + expect(createHandoffStorageKey('tok-123')).toBe('preservedState:tok-123'); + }); + }); + + describe('findTargetNormalWindow', () => { + it('prefers preferredWindowId when it is still open with matching incognito', async () => { + const chromeApi = createChromeMock({ + normalWindows: [ + { id: 1, type: 'normal', incognito: false, state: 'normal' }, + { id: 2, type: 'normal', incognito: false, state: 'normal' } + ], + lastFocusedNormal: { id: 1, type: 'normal', incognito: false } + }); + + const win = await findTargetNormalWindow(chromeApi, { + preferredWindowId: 2, + incognito: false + }); + + expect(win?.id).toBe(2); + }); + + it('falls back to last-focused normal window when preferredWindowId is gone', async () => { + const chromeApi = createChromeMock({ + normalWindows: [ + { id: 1, type: 'normal', incognito: false, state: 'normal' }, + { id: 3, type: 'normal', incognito: false, state: 'normal' } + ], + lastFocusedNormal: { id: 3, type: 'normal', incognito: false } + }); + + const win = await findTargetNormalWindow(chromeApi, { + preferredWindowId: 99, + incognito: false + }); + + expect(win?.id).toBe(3); + }); + + it('never crosses incognito boundaries', async () => { + const chromeApi = createChromeMock({ + normalWindows: [ + { id: 1, type: 'normal', incognito: false, state: 'normal' } + ], + lastFocusedNormal: { id: 1, type: 'normal', incognito: false } + }); + + const win = await findTargetNormalWindow(chromeApi, { + preferredWindowId: 1, + incognito: true + }); + + expect(win).toBeNull(); + }); + + it('prefers a non-minimized window when getLastFocused fails', async () => { + const chromeApi = createChromeMock({ + normalWindows: [ + { id: 1, type: 'normal', incognito: false, state: 'minimized' }, + { id: 2, type: 'normal', incognito: false, state: 'normal' } + ], + lastFocusedNormal: new Error('No last focused window') + }); + + const win = await findTargetNormalWindow(chromeApi, { incognito: false }); + + expect(win?.id).toBe(2); + }); + }); + + describe('switchTabOpenMode', () => { + it('moves a normal tab into a new popup window using tabId without recreating the tab', async () => { + const chromeApi = createChromeMock({ + currentWindow: { id: 10, type: 'normal', incognito: false }, + currentTab: { id: 101, windowId: 10 } + }); + + const result = await switchTabOpenMode(chromeApi); + + expect(chromeApi.windows.create).toHaveBeenCalledWith({ + tabId: 101, + type: 'popup', + width: DEFAULT_POPUP_WIDTH, + height: DEFAULT_POPUP_HEIGHT, + focused: true + }); + expect(chromeApi.tabs.move).not.toHaveBeenCalled(); + expect(result).toEqual({ + mode: 'popup', + isPopupWindow: true, + windowId: 20, + tabId: 101, + previousNormalWindowId: 10 + }); + }); + + it('retries transient tab-strip-busy errors when moving a tab to a popup window', async () => { + const sleep = vi.fn(async () => {}); + const chromeApi = createChromeMock({ + currentWindow: { id: 10, type: 'normal', incognito: false }, + currentTab: { id: 101, windowId: 10 } + }); + chromeApi.windows.create + .mockRejectedValueOnce(new Error('Tabs cannot be edited right now (user may be dragging a tab).')) + .mockResolvedValueOnce({ id: 25, type: 'popup', incognito: false }); + + const result = await switchTabOpenMode(chromeApi, { sleep, retryDelayMs: 10 }); + + expect(chromeApi.windows.create).toHaveBeenCalledTimes(2); + expect(sleep).toHaveBeenCalledTimes(1); + expect(result.windowId).toBe(25); + }); + + it('moves a popup tab back into the preferred normal window and activates/focuses it', async () => { + const chromeApi = createChromeMock({ + currentWindow: { id: 20, type: 'popup', incognito: false }, + currentTab: { id: 101, windowId: 20 }, + normalWindows: [ + { id: 10, type: 'normal', incognito: false, state: 'normal' }, + { id: 11, type: 'normal', incognito: false, state: 'normal' } + ] + }); + + const result = await switchTabOpenMode(chromeApi, { + preferredNormalWindowId: 10 + }); + + expect(chromeApi.tabs.move).toHaveBeenCalledWith(101, { + windowId: 10, + index: -1 + }); + expect(chromeApi.tabs.update).toHaveBeenCalledWith(101, { active: true }); + expect(chromeApi.windows.update).toHaveBeenCalledWith(10, { focused: true }); + expect(chromeApi.windows.create).not.toHaveBeenCalled(); + expect(result).toEqual({ + mode: 'tab', + isPopupWindow: false, + windowId: 10, + tabId: 101, + previousNormalWindowId: 10 + }); + }); + + it('unminimizes a minimized target normal window when returning from popup mode', async () => { + const chromeApi = createChromeMock({ + currentWindow: { id: 20, type: 'popup', incognito: false }, + currentTab: { id: 101, windowId: 20 }, + normalWindows: [ + { id: 10, type: 'normal', incognito: false, state: 'minimized' } + ] + }); + + await switchTabOpenMode(chromeApi, { preferredNormalWindowId: 10 }); + + expect(chromeApi.windows.update).toHaveBeenCalledWith(10, { + state: 'normal', + focused: true + }); + }); + + it('creates a new normal window adopting tabId when no compatible normal window exists', async () => { + const chromeApi = createChromeMock({ + currentWindow: { id: 20, type: 'popup', incognito: false }, + currentTab: { id: 101, windowId: 20 }, + normalWindows: [] + }); + + const result = await switchTabOpenMode(chromeApi, { + preferredNormalWindowId: 10 + }); + + expect(chromeApi.tabs.move).not.toHaveBeenCalled(); + expect(chromeApi.windows.create).toHaveBeenCalledWith({ + tabId: 101, + type: 'normal', + focused: true + }); + expect(result).toEqual({ + mode: 'tab', + isPopupWindow: false, + windowId: 30, + tabId: 101, + previousNormalWindowId: 30 + }); + }); + + it('falls back to windows.create({ tabId, type: normal }) if tabs.move rejects with a non-transient error', async () => { + const chromeApi = createChromeMock({ + currentWindow: { id: 20, type: 'popup', incognito: false }, + currentTab: { id: 101, windowId: 20 }, + normalWindows: [ + { id: 10, type: 'normal', incognito: false, state: 'normal' } + ] + }); + chromeApi.tabs.move.mockRejectedValueOnce(new Error('Window closed')); + + const result = await switchTabOpenMode(chromeApi, { + preferredNormalWindowId: 10 + }); + + expect(chromeApi.windows.create).toHaveBeenCalledWith({ + tabId: 101, + type: 'normal', + focused: true + }); + expect(result).toEqual({ + mode: 'tab', + isPopupWindow: false, + windowId: 30, + tabId: 101, + previousNormalWindowId: 30 + }); + }); + + it('rethrows without creating an extra window when tabs.move exhausts retries on transient errors', async () => { + const sleep = vi.fn(async () => {}); + const chromeApi = createChromeMock({ + currentWindow: { id: 20, type: 'popup', incognito: false }, + currentTab: { id: 101, windowId: 20 }, + normalWindows: [ + { id: 10, type: 'normal', incognito: false, state: 'normal' } + ] + }); + chromeApi.tabs.move.mockRejectedValue( + new Error('Tabs cannot be edited right now (user may be dragging a tab).') + ); + + await expect( + switchTabOpenMode(chromeApi, { + preferredNormalWindowId: 10, + maxRetries: 2, + retryDelayMs: 5, + sleep + }) + ).rejects.toThrow('Tabs cannot be edited right now'); + + expect(chromeApi.tabs.move).toHaveBeenCalledTimes(3); + expect(chromeApi.windows.create).not.toHaveBeenCalled(); + }); + + it('does not create a duplicate normal window when tabs.move succeeds but focus update fails', async () => { + const chromeApi = createChromeMock({ + currentWindow: { id: 20, type: 'popup', incognito: false }, + currentTab: { id: 101, windowId: 20 }, + normalWindows: [ + { id: 10, type: 'normal', incognito: false, state: 'normal' } + ] + }); + chromeApi.windows.update.mockRejectedValueOnce(new Error('Focus rejected')); + + const result = await switchTabOpenMode(chromeApi, { + preferredNormalWindowId: 10 + }); + + expect(chromeApi.tabs.move).toHaveBeenCalledWith(101, { + windowId: 10, + index: -1 + }); + expect(chromeApi.windows.create).not.toHaveBeenCalled(); + expect(result.windowId).toBe(10); + }); + + it('throws OpenModeSwitchUnsupportedError when current tab or window cannot be resolved', async () => { + const chromeApi = createChromeMock({ currentTab: null }); + + await expect(switchTabOpenMode(chromeApi)).rejects.toThrow( + OpenModeSwitchUnsupportedError + ); + }); + }); + + describe('multi-panel open-mode integration regressions', () => { + let cleanupListeners = []; + + function createStorageArea(initial = {}) { + const store = { ...initial }; + return { + store, + area: { + get: vi.fn(async (keys) => { + if (typeof keys === 'string') { + return keys in store ? { [keys]: store[keys] } : {}; + } + if (keys && typeof keys === 'object') { + const out = {}; + for (const [k, fallback] of Object.entries(keys)) { + out[k] = k in store ? store[k] : fallback; + } + return out; + } + return { ...store }; + }), + set: vi.fn(async (entries) => { + Object.assign(store, entries); + }), + remove: vi.fn(async (keys) => { + const list = Array.isArray(keys) ? keys : [keys]; + for (const key of list) { + delete store[key]; + } + }), + clear: vi.fn(async () => { + for (const key of Object.keys(store)) { + delete store[key]; + } + }) + } + }; + } + + function mountMultiPanel({ + currentWindow = { id: 10, type: 'normal', incognito: false }, + currentTab = { id: 101, windowId: 10 }, + syncInitial = {}, + sessionInitial = {}, + localInitial = {} + } = {}) { + const bodyMatch = multiPanelHtml.match(/]*>([\s\S]*?)<\/body>/i); + const bodyHtml = (bodyMatch ? bodyMatch[1] : '').replace(/]*>[\s\S]*?<\/script>/gi, ''); + document.body.innerHTML = bodyHtml; + + const sync = createStorageArea({ + theme: 'light', + language: 'en', + multiPanelLayout: '1x1', + enabledProviders: ['chatgpt'], + providerOrder: ['chatgpt'], + multiPanelProviders: ['chatgpt'], + ...syncInitial + }); + const session = createStorageArea(sessionInitial); + const local = createStorageArea(localInitial); + const attachedListeners = []; + + chrome.storage = { + sync: sync.area, + session: session.area, + local: local.area, + onChanged: { addListener: vi.fn() } + }; + chrome.i18n = { + getMessage: vi.fn((key) => key), + getUILanguage: vi.fn(() => 'en') + }; + chrome.runtime.getManifest = vi.fn(() => ({ version: '2.2.3' })); + chrome.management = { + getSelf: vi.fn(async () => ({ installType: 'normal' })) + }; + chrome.permissions = { + contains: vi.fn(async () => true), + request: vi.fn(async () => true), + onAdded: { addListener: vi.fn() }, + onRemoved: { addListener: vi.fn() } + }; + + let activeWindow = { ...currentWindow }; + chrome.windows = { + getCurrent: vi.fn(async () => activeWindow), + getAll: vi.fn(async () => (activeWindow.type === 'normal' ? [activeWindow] : [])), + getLastFocused: vi.fn(async () => activeWindow), + create: vi.fn(async (createData) => { + activeWindow = { + id: createData.type === 'popup' ? 20 : 30, + type: createData.type, + incognito: false + }; + return activeWindow; + }), + update: vi.fn(async () => activeWindow) + }; + chrome.tabs = { + getCurrent: vi.fn(async () => currentTab), + create: vi.fn(async () => ({ id: 999 })), + move: vi.fn(async () => currentTab), + update: vi.fn(async () => currentTab), + remove: vi.fn(async () => {}), + onAttached: { + addListener: vi.fn((listener) => { + attachedListeners.push(listener); + }) + } + }; + + return { + sync, + session, + local, + attachedListeners, + setCurrentWindow(nextWin) { + activeWindow = { ...nextWin }; + } + }; + } + + beforeEach(() => { + vi.resetModules(); + 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); + }); + + globalThis.fetch = vi.fn(async () => ({ + ok: true, + status: 200, + json: async () => ({ prompts: [] }) + })); + }); + + afterEach(() => { + for (const cleanup of cleanupListeners.splice(0)) { + cleanup(); + } + vi.restoreAllMocks(); + delete globalThis.fetch; + document.body.innerHTML = ''; + }); + + it('preserves the live tab and never recreates or closes it when Chrome throws a persistent transient tab-edit error', async () => { + const env = mountMultiPanel(); + const closeSpy = vi.spyOn(window, 'close').mockImplementation(() => {}); + const mpMod = await import('../multi-panel/multi-panel.js'); + + await vi.waitFor(() => { + expect(document.querySelector('#toggle-open-mode-btn .material-symbols-outlined')?.textContent).toBe('open_in_new'); + }); + + document.getElementById('unified-input').value = 'unsent chat draft'; + chrome.windows.create.mockRejectedValue( + new Error('Tabs cannot be edited right now (user may be dragging a tab).') + ); + + await mpMod.toggleOpenMode(); + + expect(chrome.tabs.create).not.toHaveBeenCalled(); + expect(chrome.tabs.remove).not.toHaveBeenCalled(); + expect(closeSpy).not.toHaveBeenCalled(); + expect(Object.keys(env.session.store)).toEqual([]); + expect(Object.keys(env.local.store).filter((k) => k.startsWith('preservedState'))).toEqual([]); + expect(document.getElementById('unified-input').value).toBe('unsent chat draft'); + }); + + it('scopes fallback preservedState to a unique token and cleans it up if fallback creation fails', async () => { + const env = mountMultiPanel({ currentTab: null }); + const mpMod = await import('../multi-panel/multi-panel.js'); + + await vi.waitFor(() => { + expect(document.querySelector('#toggle-open-mode-btn .material-symbols-outlined')?.textContent).toBe('open_in_new'); + }); + + document.getElementById('unified-input').value = 'fallback draft'; + chrome.windows.create.mockRejectedValueOnce(new Error('Window creation blocked')); + + await mpMod.toggleOpenMode(); + + expect(Object.keys(env.session.store)).toEqual([]); + expect(Object.keys(env.local.store).filter((k) => k.startsWith('preservedState'))).toEqual([]); + + let createdUrl = null; + chrome.windows.create.mockImplementationOnce(async (opts) => { + createdUrl = opts.url; + return { id: 55, type: 'popup' }; + }); + env.sync.area.set.mockRejectedValueOnce(new Error('Sync quota exceeded')); + + await mpMod.toggleOpenMode(); + + expect(createdUrl).toContain(`${HANDOFF_QUERY_PARAM}=`); + const token = getHandoffTokenFromUrl(createdUrl); + expect(token).toBeTruthy(); + expect(env.session.store[createHandoffStorageKey(token)]?.inputText).toBe('fallback draft'); + expect(env.session.store.preservedState).toBeUndefined(); + }); + + it('restores scoped handoff state only for the matching URL token and leaves other tokens untouched', async () => { + const targetKey = createHandoffStorageKey('tok-target'); + const otherKey = createHandoffStorageKey('tok-other'); + + const originalHref = window.location.href; + window.history.replaceState(null, '', `/?${HANDOFF_QUERY_PARAM}=tok-target`); + try { + const env = mountMultiPanel({ + sessionInitial: { + [targetKey]: { + inputText: 'scoped target draft', + uploadedImages: [], + currentLayout: '1x1', + panels: [{ providerId: 'chatgpt' }] + }, + [otherKey]: { + inputText: 'other tab draft', + uploadedImages: [], + currentLayout: '1x1', + panels: [{ providerId: 'chatgpt' }] + } + } + }); + + await import('../multi-panel/multi-panel.js'); + + await vi.waitFor(() => { + expect(document.getElementById('unified-input')?.value).toBe('scoped target draft'); + }); + expect(env.session.store[targetKey]).toBeUndefined(); + expect(env.session.store[otherKey]?.inputText).toBe('other tab draft'); + expect(getHandoffTokenFromUrl(window.location.href)).toBeNull(); + } finally { + window.history.replaceState(null, '', originalHref); + } + }); + + it('reconciles native tabs.onAttached fired while toggleOpenMode is awaiting storage.sync.set', async () => { + const env = mountMultiPanel({ + currentWindow: { id: 10, type: 'normal', incognito: false }, + currentTab: { id: 101, windowId: 10 } + }); + const mpMod = await import('../multi-panel/multi-panel.js'); + + await vi.waitFor(() => { + expect(env.attachedListeners).toHaveLength(1); + }); + + let resolveSyncSet; + env.sync.area.set.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveSyncSet = resolve; + }) + ); + + const togglePromise = mpMod.toggleOpenMode(); + + await vi.waitFor(() => { + expect(typeof resolveSyncSet).toBe('function'); + }); + + // Simulate native "Show as tab" moving the tab back to normal window 10 + // while toggleOpenMode is still awaiting chrome.storage.sync.set. + env.setCurrentWindow({ id: 10, type: 'normal', incognito: false }); + env.attachedListeners[0](101, { newWindowId: 10, newPosition: 0 }); + + resolveSyncSet(); + await togglePromise; + + expect(document.querySelector('#toggle-open-mode-btn .material-symbols-outlined')?.textContent).toBe('open_in_new'); + }); + + it('updates the toggle button even when chrome.storage.sync.get rejects during init', async () => { + const env = mountMultiPanel({ + currentWindow: { id: 20, type: 'popup', incognito: false }, + currentTab: { id: 101, windowId: 20 } + }); + env.sync.area.get.mockRejectedValue(new Error('Sync storage unavailable')); + + await import('../multi-panel/multi-panel.js'); + + await vi.waitFor(() => { + expect(document.querySelector('#toggle-open-mode-btn .material-symbols-outlined')?.textContent).toBe('tab'); + }); + }); + }); +});