From 699602c042c9abd93e5a71637358de173a83d6d3 Mon Sep 17 00:00:00 2001 From: ujiro99 Date: Mon, 23 Nov 2026 19:31:13 +0900 Subject: [PATCH 1/3] fix(extension): open the side panel from the context menu and shortcuts A command started from the native context menu or a keyboard shortcut is run by the content script, so chrome.sidePanel.open() was called after the user gesture was lost. Open the side panel with a blank page synchronously in the event handler, and let the later openSidePanel request only set the page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pd1sH2SVL35AWHUxzVCAqk --- .../src/action/__tests__/helper.test.ts | 51 +++++- packages/extension/src/action/helper.ts | 15 +- packages/extension/src/service_worker.ts | 2 + .../__tests__/chrome.sidePanel.test.ts | 15 ++ .../services/__tests__/contextMenus.test.ts | 38 +++- .../__tests__/sidePanelPreOpen.test.ts | 172 ++++++++++++++++++ packages/extension/src/services/chrome.ts | 19 +- .../extension/src/services/contextMenus.ts | 48 ++++- .../src/services/shortcut/serviceWorker.ts | 89 ++++++++- .../src/services/sidePanelPreOpen.ts | 119 ++++++++++++ 10 files changed, 545 insertions(+), 23 deletions(-) create mode 100644 packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts create mode 100644 packages/extension/src/services/sidePanelPreOpen.ts diff --git a/packages/extension/src/action/__tests__/helper.test.ts b/packages/extension/src/action/__tests__/helper.test.ts index 35240f80..3e80b9dc 100644 --- a/packages/extension/src/action/__tests__/helper.test.ts +++ b/packages/extension/src/action/__tests__/helper.test.ts @@ -18,6 +18,10 @@ import { enhancedSettings } from "@/services/settings/enhancedSettings" import { incrementCommandExecutionCount } from "@/services/commandMetrics" import { registerSidePanelHostTab as _registerSidePanelHostTab } from "@/services/pageAction/serviceWorker-sidePanel" import { isSidePanelSupported } from "@/services/sidePanelSupport" +import { + preOpenSidePanel, + resetPreOpenedSidePanels, +} from "@/services/sidePanelPreOpen" // Mock dependencies vi.mock("@/services/serviceWorkerData", () => ({ @@ -58,6 +62,7 @@ describe("helper", () => { beforeEach(() => { vi.clearAllMocks() vi.mocked(ServiceWorkerData.ready).mockResolvedValue(undefined) + resetPreOpenedSidePanels() }) describe("navigateSidePanel", () => { @@ -297,7 +302,7 @@ describe("helper", () => { await new Promise((resolve) => setTimeout(resolve, 10)) - expect(_openSidePanel).toHaveBeenCalledWith({ ...param, tabId }) + expect(_openSidePanel).toHaveBeenCalledWith({ ...param, tabId }, false) }) it("OSP-02: Should fall back to serviceWorkerData.activeTabId when sender.tab.id is null", async () => { @@ -323,10 +328,10 @@ describe("helper", () => { await new Promise((resolve) => setTimeout(resolve, 10)) - expect(_openSidePanel).toHaveBeenCalledWith({ - ...param, - tabId: activeTabId, - }) + expect(_openSidePanel).toHaveBeenCalledWith( + { ...param, tabId: activeTabId }, + false, + ) expect(response).toHaveBeenCalledWith(true) }) @@ -422,7 +427,10 @@ describe("helper", () => { openSidePanel(param, sender, response) // Called synchronously to keep the user gesture - expect(_openSidePanel).toHaveBeenCalledWith({ ...param, tabId: 123 }) + expect(_openSidePanel).toHaveBeenCalledWith( + { ...param, tabId: 123 }, + false, + ) expect(ServiceWorkerData.ready).not.toHaveBeenCalled() }) @@ -461,10 +469,10 @@ describe("helper", () => { await vi.waitFor(() => { expect(response).toHaveBeenCalledWith(true) }) - expect(_openSidePanel).toHaveBeenCalledWith({ - ...param, - tabId: activeTabId, - }) + expect(_openSidePanel).toHaveBeenCalledWith( + { ...param, tabId: activeTabId }, + false, + ) }) it("OSP-08: Should respond false when ServiceWorkerData fails to load", async () => { @@ -512,6 +520,29 @@ describe("helper", () => { consoleDebugSpy.mockRestore() }) + + it("OSP-10: Should only set the page when the side panel was pre-opened", async () => { + const tabId = 123 + const param = { url: "https://example.com", isLinkCommand: false } + const sender = { tab: { id: tabId } } as chrome.runtime.MessageSender + const response = vi.fn() + + vi.mocked(_openSidePanel).mockResolvedValue({ tabId } as any) + vi.mocked(ServiceWorkerData.update).mockResolvedValue(true as any) + + preOpenSidePanel(tabId) + openSidePanel(param, sender, response) + + await vi.waitFor(() => { + expect(response).toHaveBeenCalledWith(true) + }) + expect(_openSidePanel).toHaveBeenCalledWith({ ...param, tabId }, true) + + // The pre-opened state is used only once. + vi.mocked(_openSidePanel).mockClear() + openSidePanel(param, sender, vi.fn()) + expect(_openSidePanel).toHaveBeenCalledWith({ ...param, tabId }, false) + }) }) describe("closeSidePanel", () => { diff --git a/packages/extension/src/action/helper.ts b/packages/extension/src/action/helper.ts index 045f66e5..c58ffc5d 100644 --- a/packages/extension/src/action/helper.ts +++ b/packages/extension/src/action/helper.ts @@ -26,6 +26,7 @@ import { enhancedSettings } from "@/services/settings/enhancedSettings" import { Ipc, TabCommand, NavigateSidePanelProps } from "@/services/ipc" import { ServiceWorkerData } from "@/services/serviceWorkerData" import { isSidePanelSupported } from "@/services/sidePanelSupport" +import { consumePreOpenedSidePanel } from "@/services/sidePanelPreOpen" import { SIDE_PANEL_RELAY_PATH, isRelayableUrl, @@ -145,10 +146,16 @@ export const openSidePanel = ( } const open = (tabId: number) => { - _openSidePanel({ - ...param, - tabId, - }) + // The side panel may have been opened by the service worker before the + // command ran, when the command started from the browser UI. + const preOpened = consumePreOpenedSidePanel(tabId) + _openSidePanel( + { + ...param, + tabId, + }, + preOpened, + ) .then(() => { incrementCommandExecutionCount(tabId) }) diff --git a/packages/extension/src/service_worker.ts b/packages/extension/src/service_worker.ts index 99233c17..7578a05c 100644 --- a/packages/extension/src/service_worker.ts +++ b/packages/extension/src/service_worker.ts @@ -566,6 +566,8 @@ if (isDebug) { // syncCommandIdObj catches its own errors, so this promise never rejects. const commandIdObjReady = ContextMenu.syncCommandIdObj() chrome.contextMenus.onClicked.addListener(async (info, tab) => { + // Must run before any await to keep the user gesture. + ContextMenu.preOpenSidePanel(info, tab) await commandIdObjReady await ContextMenu.onClicked(info, tab) }) diff --git a/packages/extension/src/services/__tests__/chrome.sidePanel.test.ts b/packages/extension/src/services/__tests__/chrome.sidePanel.test.ts index b1af492b..f5145955 100644 --- a/packages/extension/src/services/__tests__/chrome.sidePanel.test.ts +++ b/packages/extension/src/services/__tests__/chrome.sidePanel.test.ts @@ -67,6 +67,21 @@ describe("chrome.ts side panel functions", () => { }) }) + it("CSP-OP-04: 正常系: 事前オープン済みなら setOptions だけを呼び出す", async () => { + const result = await openSidePanel( + { url: "https://example.com", tabId: 1 }, + true, + ) + + expect(sidePanel.setOptions).toHaveBeenCalledWith({ + tabId: 1, + path: buildRelayPath("https://example.com", 1), + enabled: true, + }) + expect(sidePanel.open).not.toHaveBeenCalled() + expect(result).toEqual({ tabId: 1 }) + }) + it("CSP-OP-02: 異常系: API 非対応時は reject し API を呼び出さない", async () => { setSidePanel(undefined) diff --git a/packages/extension/src/services/__tests__/contextMenus.test.ts b/packages/extension/src/services/__tests__/contextMenus.test.ts index 6e2895d7..2cedf36b 100644 --- a/packages/extension/src/services/__tests__/contextMenus.test.ts +++ b/packages/extension/src/services/__tests__/contextMenus.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest" import { enhancedSettings } from "@/services/settings/enhancedSettings" -import { ContextMenu } from "../contextMenus" +import { ContextMenu, toMenuId } from "../contextMenus" import { OPEN_MODE, OPTION_FOLDER, ROOT_FOLDER } from "@/const" import type { Command, CommandFolder } from "@/types" @@ -630,6 +630,42 @@ describe("Context Menu Multi-level Hierarchy", () => { ) }) + it("CM-17: should prefix the menu ID of a side panel command", () => { + const sidePanelCommand = { + ...createCommand("cmd-sp", "Side panel", "folder1"), + openMode: OPEN_MODE.SIDE_PANEL, + } + const popupCommand = createCommand("cmd-popup", "Popup", "folder1") + + expect(toMenuId(sidePanelCommand)).toBe("sidePanel:cmd-sp") + expect(toMenuId(popupCommand)).toBe("cmd-popup") + }) + + it("CM-18: should pre-open the side panel only for a side panel menu ID", () => { + const original = global.chrome.sidePanel + const open = vi.fn().mockResolvedValue(undefined) + global.chrome.sidePanel = { + open, + setOptions: vi.fn().mockResolvedValue(undefined), + } as any + + // Works without commandIdObj, which may not be restored yet. + ContextMenu.commandIdObj = {} + ContextMenu.preOpenSidePanel( + { menuItemId: "cmd-popup" } as any, + { id: 123 } as any, + ) + expect(open).not.toHaveBeenCalled() + + ContextMenu.preOpenSidePanel( + { menuItemId: "sidePanel:cmd-sp" } as any, + { id: 123 } as any, + ) + expect(open).toHaveBeenCalledWith({ tabId: 123 }) + + global.chrome.sidePanel = original + }) + it("CM-16: should not send executeAction when command is not found", async () => { const mockSendMessage = vi.fn().mockResolvedValue("success") global.chrome.tabs = { diff --git a/packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts b/packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts new file mode 100644 index 00000000..8c598d04 --- /dev/null +++ b/packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts @@ -0,0 +1,172 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest" +import { OPEN_MODE, PAGE_ACTION_OPEN_MODE } from "@/const" +import type { Command } from "@/types" +import { + usesSidePanel, + preOpenSidePanel, + consumePreOpenedSidePanel, + cancelPreOpenedSidePanel, + resetPreOpenedSidePanels, + PRE_OPEN_TIMEOUT_MS, +} from "../sidePanelPreOpen" +import { closeSidePanel } from "@/services/chrome" +import { isSidePanelSupported } from "@/services/sidePanelSupport" +import { SIDE_PANEL_RELAY_PATH } from "@/services/sidePanelUrl" + +vi.mock("@/services/chrome", () => ({ + closeSidePanel: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("@/services/sidePanelSupport", () => ({ + isSidePanelSupported: vi.fn(() => true), +})) + +const createCommand = (props: Partial): Command => + ({ + id: "cmd", + title: "Command", + searchUrl: "https://example.com/?q=%s", + iconUrl: "", + ...props, + }) as Command + +describe("sidePanelPreOpen", () => { + beforeEach(() => { + vi.useFakeTimers() + vi.clearAllMocks() + vi.mocked(chrome.sidePanel.open).mockResolvedValue(undefined) + vi.mocked(chrome.sidePanel.setOptions).mockResolvedValue(undefined) + resetPreOpenedSidePanels() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + describe("usesSidePanel", () => { + it("SPO-US-01: サイドパネルを開くコマンドを判定する", () => { + expect( + usesSidePanel(createCommand({ openMode: OPEN_MODE.SIDE_PANEL })), + ).toBe(true) + expect( + usesSidePanel( + createCommand({ + openMode: OPEN_MODE.AI_PROMPT, + aiPromptOption: { openMode: OPEN_MODE.SIDE_PANEL }, + } as Partial), + ), + ).toBe(true) + expect( + usesSidePanel( + createCommand({ + openMode: OPEN_MODE.PAGE_ACTION, + pageActionOption: { openMode: PAGE_ACTION_OPEN_MODE.SIDE_PANEL }, + } as Partial), + ), + ).toBe(true) + }) + + it("SPO-US-02: サイドパネルを開かないコマンドは false を返す", () => { + expect(usesSidePanel(createCommand({ openMode: OPEN_MODE.POPUP }))).toBe( + false, + ) + expect( + usesSidePanel( + createCommand({ + openMode: OPEN_MODE.AI_PROMPT, + aiPromptOption: { openMode: OPEN_MODE.POPUP }, + } as Partial), + ), + ).toBe(false) + expect( + usesSidePanel( + createCommand({ + openMode: OPEN_MODE.PAGE_ACTION, + pageActionOption: { openMode: PAGE_ACTION_OPEN_MODE.TAB }, + } as Partial), + ), + ).toBe(false) + }) + }) + + describe("preOpenSidePanel", () => { + it("SPO-PO-01: 空白ページを設定して同期的に open を呼び出す", () => { + preOpenSidePanel(1) + + expect(chrome.sidePanel.setOptions).toHaveBeenCalledWith({ + tabId: 1, + path: SIDE_PANEL_RELAY_PATH, + enabled: true, + }) + // Called synchronously, without waiting for setOptions. + expect(chrome.sidePanel.open).toHaveBeenCalledWith({ tabId: 1 }) + }) + + it("SPO-PO-02: API 非対応時は何もしない", () => { + vi.mocked(isSidePanelSupported).mockReturnValueOnce(false) + + preOpenSidePanel(1) + + expect(chrome.sidePanel.open).not.toHaveBeenCalled() + expect(consumePreOpenedSidePanel(1)).toBe(false) + }) + + it("SPO-PO-03: open に失敗したら事前オープン状態を破棄する", async () => { + vi.mocked(chrome.sidePanel.open).mockRejectedValueOnce( + new Error("no user gesture"), + ) + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + preOpenSidePanel(1) + await vi.waitFor(() => expect(errorSpy).toHaveBeenCalled()) + + expect(consumePreOpenedSidePanel(1)).toBe(false) + errorSpy.mockRestore() + }) + + it("SPO-PO-04: 期限内に使われなければサイドパネルを閉じる", () => { + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) + preOpenSidePanel(1) + + vi.advanceTimersByTime(PRE_OPEN_TIMEOUT_MS) + + expect(closeSidePanel).toHaveBeenCalledWith(1) + expect(consumePreOpenedSidePanel(1)).toBe(false) + warnSpy.mockRestore() + }) + }) + + describe("consumePreOpenedSidePanel", () => { + it("SPO-CO-01: 事前オープン状態を一度だけ返し、閉じるタイマーを止める", () => { + preOpenSidePanel(1) + + expect(consumePreOpenedSidePanel(2)).toBe(false) + expect(consumePreOpenedSidePanel(1)).toBe(true) + expect(consumePreOpenedSidePanel(1)).toBe(false) + + vi.advanceTimersByTime(PRE_OPEN_TIMEOUT_MS) + expect(closeSidePanel).not.toHaveBeenCalled() + }) + }) + + describe("cancelPreOpenedSidePanel", () => { + it("SPO-CA-01: 未使用の事前オープンしたサイドパネルを閉じる", () => { + preOpenSidePanel(1) + + cancelPreOpenedSidePanel(1) + + expect(closeSidePanel).toHaveBeenCalledWith(1) + expect(consumePreOpenedSidePanel(1)).toBe(false) + }) + + it("SPO-CA-02: 使用済みまたは未オープンなら何もしない", () => { + preOpenSidePanel(1) + consumePreOpenedSidePanel(1) + + cancelPreOpenedSidePanel(1) + cancelPreOpenedSidePanel(2) + + expect(closeSidePanel).not.toHaveBeenCalled() + }) + }) +}) diff --git a/packages/extension/src/services/chrome.ts b/packages/extension/src/services/chrome.ts index c45aa941..bf111508 100644 --- a/packages/extension/src/services/chrome.ts +++ b/packages/extension/src/services/chrome.ts @@ -688,10 +688,14 @@ export type UpdateSidePanelUrlProps = { /** * Open a side panel with the specified URL (service worker context only) * @param {OpenSidePanelProps} param - Parameters for opening the side panel + * @param {boolean} alreadyOpened - True if the side panel was already opened + * for the tab (see services/sidePanelPreOpen.ts). Then only the page is set, + * because open() fails without the user gesture. * @returns {Promise} Result containing tab ID and clipboard text */ export const openSidePanel = async ( param: OpenSidePanelProps, + alreadyOpened = false, ): Promise<{ tabId: number | undefined }> => { const { url, tabId } = param @@ -706,13 +710,20 @@ export const openSidePanel = async ( } } - // Set the side panel options for the tab - // Do not await here because sidePanel.open() must be executed within a user gesture. - chrome.sidePanel.setOptions({ + const options = { tabId, path: toSidePanelPath(toUrl(url), tabId), enabled: true, - }) + } + + if (alreadyOpened) { + await chrome.sidePanel.setOptions(options) + return { tabId } + } + + // Set the side panel options for the tab + // Do not await here because sidePanel.open() must be executed within a user gesture. + chrome.sidePanel.setOptions(options) // Open the side panel try { diff --git a/packages/extension/src/services/contextMenus.ts b/packages/extension/src/services/contextMenus.ts index 222acf41..08751f0e 100644 --- a/packages/extension/src/services/contextMenus.ts +++ b/packages/extension/src/services/contextMenus.ts @@ -5,6 +5,11 @@ import { Ipc, TabCommand } from "@/services/ipc" import { capitalize } from "@/lib/utils" import { isSelectionCommand } from "@/lib/commandGuards" import { APP_ID } from "@/const" +import { + usesSidePanel, + preOpenSidePanel, + cancelPreOpenedSidePanel, +} from "@/services/sidePanelPreOpen" import { toCommandTree, type CommandTreeNode, @@ -29,6 +34,24 @@ type Contexts = [ const callbacks = new Map() +/** + * Prefix of the menu ID for a command that opens the side panel. + * The menu ID tells it without commandIdObj, which is restored + * asynchronously after the service worker wakes up by the click. + */ +const SIDE_PANEL_MENU_PREFIX = "sidePanel:" + +/** + * Get the context menu ID of the command. + * @param {Command} command - The command shown in the menu. + * @returns {string} The menu ID. + */ +export const toMenuId = (command: Command): string => + usesSidePanel(command) ? `${SIDE_PANEL_MENU_PREFIX}${command.id}` : command.id + +const isSidePanelMenuId = (menuItemId: string | number): boolean => + String(menuItemId).startsWith(SIDE_PANEL_MENU_PREFIX) + const createMenu = ( options: chrome.contextMenus.CreateProperties, ): string | number => { @@ -144,7 +167,7 @@ export const ContextMenu = { title: command.title, parentId, contexts, - id: command.id, + id: toMenuId(command), }) ContextMenu.commandIdObj[menuId] = command } @@ -183,11 +206,27 @@ export const ContextMenu = { } else { // Add command to commandIdObj const command = node.content as Command - ContextMenu.commandIdObj[command.id] = command + ContextMenu.commandIdObj[toMenuId(command)] = command } } }, + /** + * Open the side panel ahead when the clicked command uses it. + * Must be called synchronously in the onClicked listener, before any await, + * to keep the user gesture. See services/sidePanelPreOpen.ts. + * The menu ID is checked instead of commandIdObj, which may not be + * restored yet when the click wakes up the service worker. + */ + preOpenSidePanel: ( + info: chrome.contextMenus.OnClickData, + tab?: chrome.tabs.Tab, + ) => { + if (tab?.id != null && isSidePanelMenuId(info.menuItemId)) { + preOpenSidePanel(tab.id) + } + }, + onClicked: async ( info: chrome.contextMenus.OnClickData, tab?: chrome.tabs.Tab, @@ -196,11 +235,16 @@ export const ContextMenu = { const command = ContextMenu.commandIdObj[info.menuItemId] if (!command) { console.warn("Command not found for menu item:", info.menuItemId) + cancelPreOpenedSidePanel(tab.id) return } const res = await Ipc.sendTab(tab.id, TabCommand.executeAction, { command, }) + if (res instanceof Error) { + // The command does not run, so do not leave a blank side panel. + cancelPreOpenedSidePanel(tab.id) + } if (res) console.debug(res) } }, diff --git a/packages/extension/src/services/shortcut/serviceWorker.ts b/packages/extension/src/services/shortcut/serviceWorker.ts index 87579bfc..75a5e041 100644 --- a/packages/extension/src/services/shortcut/serviceWorker.ts +++ b/packages/extension/src/services/shortcut/serviceWorker.ts @@ -8,13 +8,85 @@ import { execute } from "@/action/serviceWorker" import { ANALYTICS_EVENTS, sendEvent } from "@/services/analytics" import { getCenteredOffsetInCurrentWindow } from "@/services/screen" import { resolvePopupSize } from "@/services/option/defaultSettings" +import { Settings } from "@/services/settings/settings" +import { + usesSidePanel, + preOpenSidePanel, + cancelPreOpenedSidePanel, +} from "@/services/sidePanelPreOpen" + +/** + * Shortcut IDs whose command opens the side panel. + * Kept in memory so the shortcut listener can tell it synchronously, before + * any await, to keep the user gesture. See services/sidePanelPreOpen.ts. + */ +let sidePanelShortcutIds = new Set() + +/** + * Refresh sidePanelShortcutIds from the settings. + * Errors are logged and never thrown. + */ +const syncSidePanelShortcutIds = async (): Promise => { + try { + const settings = await enhancedSettings.get() + const ids = new Set() + for (const shortcut of settings.shortcuts?.shortcuts ?? []) { + const command = settings.commands.find((c) => c.id === shortcut.commandId) + if (command && usesSidePanel(command)) ids.add(shortcut.id) + } + sidePanelShortcutIds = ids + } catch (error) { + console.warn("Failed to sync side panel shortcuts:", error) + } +} + +let sidePanelShortcutIdsReady: Promise = Promise.resolve() +let sidePanelShortcutIdsLoaded = false + +/** + * Open the side panel ahead when the shortcut's command uses it. + * @returns {number | undefined} The tab ID the side panel was pre-opened for. + */ +const preOpenSidePanelForShortcut = ( + commandName: string, + tab?: chrome.tabs.Tab, +): number | undefined => { + if (tab?.id == null || !sidePanelShortcutIds.has(commandName)) return + preOpenSidePanel(tab.id) + return tab.id +} + +/** + * Listener of chrome.commands.onCommand. + */ +const onCommand = async ( + commandName: string, + tab?: chrome.tabs.Tab, +): Promise => { + // Must run before any await to keep the user gesture. + let preOpenedTabId = preOpenSidePanelForShortcut(commandName, tab) + if (!sidePanelShortcutIdsLoaded) { + // The shortcut woke up the service worker, so the IDs are not loaded yet. + // The user gesture may be lost after the await, but try it anyway. + await sidePanelShortcutIdsReady + preOpenedTabId = preOpenSidePanelForShortcut(commandName, tab) + } + await handleShortcutCommand(commandName, preOpenedTabId) +} /** * Run the command mapped to a keyboard shortcut. * Without a text selection, follows the shortcut's noSelectionBehavior. * Errors are logged and never thrown. + * @param {string} commandName - The shortcut ID. + * @param {number} preOpenedTabId - The tab the side panel was pre-opened for. + * The side panel is closed if the command does not run. */ -async function handleShortcutCommand(commandName: string) { +async function handleShortcutCommand( + commandName: string, + preOpenedTabId?: number, +) { + let executed = false try { // Get settings const settings = await enhancedSettings.get() @@ -105,6 +177,7 @@ async function handleShortcutCommand(commandName: string) { pageUrl: tab?.url ?? "", }) } + executed = true sendEvent( ANALYTICS_EVENTS.SHORTCUT, { @@ -114,6 +187,11 @@ async function handleShortcutCommand(commandName: string) { ) } catch (error) { console.error("Failed to execute shortcut command:", error) + } finally { + // Do not leave a blank side panel when the command does not run. + if (!executed && preOpenedTabId != null) { + cancelPreOpenedSidePanel(preOpenedTabId) + } } } @@ -122,7 +200,14 @@ async function handleShortcutCommand(commandName: string) { * Must be called synchronously while the service worker starts. */ export const registerShortcutListeners = (): void => { - chrome.commands.onCommand.addListener(handleShortcutCommand) + chrome.commands.onCommand.addListener(onCommand) + + sidePanelShortcutIdsReady = syncSidePanelShortcutIds().then(() => { + sidePanelShortcutIdsLoaded = true + }) + Settings.addChangedListener(() => { + syncSidePanelShortcutIds() + }) // Expose only in the E2E worker for Playwright evaluation, without a message endpoint. if (import.meta.env.MODE === "e2e") { diff --git a/packages/extension/src/services/sidePanelPreOpen.ts b/packages/extension/src/services/sidePanelPreOpen.ts new file mode 100644 index 00000000..84112af0 --- /dev/null +++ b/packages/extension/src/services/sidePanelPreOpen.ts @@ -0,0 +1,119 @@ +import { OPEN_MODE, PAGE_ACTION_OPEN_MODE } from "@/const" +import type { Command } from "@/types" +import { isAiPromptCommand, isPageActionCommand } from "@/lib/commandGuards" +import { closeSidePanel } from "@/services/chrome" +import { isSidePanelSupported } from "@/services/sidePanelSupport" +import { SIDE_PANEL_RELAY_PATH } from "@/services/sidePanelUrl" + +/** + * Opens the side panel ahead of a command started from a browser UI event + * (the native context menu or a keyboard shortcut). + * + * chrome.sidePanel.open() must be called while the user gesture is alive. + * A command started from those events is sent to the content script and + * then asks the service worker to open the side panel, but by then the + * gesture is lost: unlike a click on the page, the browser UI does not give + * the page a user activation. So the service worker opens the side panel + * with a blank page synchronously in the event handler, and the later + * openSidePanel request only sets the target page (see + * ActionHelper.openSidePanel). + */ + +/** + * How long a pre-opened side panel waits for the openSidePanel request. + * After that, the panel is closed so a blank panel is not left open when + * the command fails or is skipped. + */ +export const PRE_OPEN_TIMEOUT_MS = 10000 + +/** + * Blank page shown until the target page is set. The relay page does + * nothing without the url parameter. + */ +const PLACEHOLDER_PATH = SIDE_PANEL_RELAY_PATH + +// Tab ID → timer that closes the pre-opened side panel. +const preOpenedTabs = new Map>() + +/** + * Check whether the command shows its result in the side panel. + * @param {Command} command - The command to check. + * @returns {boolean} True if the command opens the side panel. + */ +export const usesSidePanel = (command: Command): boolean => { + if (isAiPromptCommand(command)) { + return command.aiPromptOption?.openMode === OPEN_MODE.SIDE_PANEL + } + if (isPageActionCommand(command)) { + return ( + command.pageActionOption?.openMode === PAGE_ACTION_OPEN_MODE.SIDE_PANEL + ) + } + return command.openMode === OPEN_MODE.SIDE_PANEL +} + +/** + * Open the side panel of the tab with a blank page. + * Must be called synchronously in the browser UI event handler, before any + * await, to keep the user gesture. + * @param {number} tabId - The tab to open the side panel for. + */ +export const preOpenSidePanel = (tabId: number): void => { + if (!isSidePanelSupported()) return + + // Do not await: open() must be called within the user gesture. + chrome.sidePanel + .setOptions({ tabId, path: PLACEHOLDER_PATH, enabled: true }) + .catch((e) => console.warn("Failed to set the side panel options:", e)) + + clearPreOpened(tabId) + preOpenedTabs.set( + tabId, + setTimeout(() => { + // The command did not request the side panel in time. + if (preOpenedTabs.delete(tabId)) { + console.warn("Close the pre-opened side panel:", tabId) + closeSidePanel(tabId) + } + }, PRE_OPEN_TIMEOUT_MS), + ) + + chrome.sidePanel.open({ tabId }).catch((e) => { + console.error("Failed to pre-open the side panel:", e) + clearPreOpened(tabId) + }) +} + +/** + * Take the pre-opened state of the tab. + * @param {number} tabId - The tab that requests the side panel. + * @returns {boolean} True if the side panel was pre-opened for the tab, so + * calling open() again is not needed. + */ +export const consumePreOpenedSidePanel = (tabId: number): boolean => { + return clearPreOpened(tabId) +} + +/** + * Close the pre-opened side panel when the command is not run after all. + * @param {number} tabId - The tab the side panel was pre-opened for. + */ +export const cancelPreOpenedSidePanel = (tabId: number): void => { + if (clearPreOpened(tabId)) { + closeSidePanel(tabId) + } +} + +const clearPreOpened = (tabId: number): boolean => { + const timer = preOpenedTabs.get(tabId) + if (timer === undefined) return false + clearTimeout(timer) + preOpenedTabs.delete(tabId) + return true +} + +/** Reset internal state — for testing only. */ +export const resetPreOpenedSidePanels = (): void => { + preOpenedTabs.forEach((timer) => clearTimeout(timer)) + preOpenedTabs.clear() +} From 21564b41c0203ce97b1af90f71e7cf01a3bc1112 Mon Sep 17 00:00:00 2001 From: ujiro99 Date: Mon, 23 Nov 2026 22:03:17 +0900 Subject: [PATCH 2/3] fix(extension): follow shortcut changes and keep newer pre-open state - Refresh the side panel shortcut cache when the shortcuts are changed. - Do not let a stale open() failure clear a newer pre-opened state. - Move test-only exports to __test and fix test names. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pd1sH2SVL35AWHUxzVCAqk --- .../src/action/__tests__/helper.test.ts | 4 +-- .../services/__tests__/contextMenus.test.ts | 4 ++- .../__tests__/sidePanelPreOpen.test.ts | 23 ++++++------ .../extension/src/services/contextMenus.ts | 7 +++- .../src/services/shortcut/serviceWorker.ts | 12 +++++-- .../src/services/sidePanelPreOpen.ts | 36 +++++++++++-------- 6 files changed, 55 insertions(+), 31 deletions(-) diff --git a/packages/extension/src/action/__tests__/helper.test.ts b/packages/extension/src/action/__tests__/helper.test.ts index 3e80b9dc..5af73a64 100644 --- a/packages/extension/src/action/__tests__/helper.test.ts +++ b/packages/extension/src/action/__tests__/helper.test.ts @@ -20,7 +20,7 @@ import { registerSidePanelHostTab as _registerSidePanelHostTab } from "@/service import { isSidePanelSupported } from "@/services/sidePanelSupport" import { preOpenSidePanel, - resetPreOpenedSidePanels, + __test as sidePanelPreOpenTest, } from "@/services/sidePanelPreOpen" // Mock dependencies @@ -62,7 +62,7 @@ describe("helper", () => { beforeEach(() => { vi.clearAllMocks() vi.mocked(ServiceWorkerData.ready).mockResolvedValue(undefined) - resetPreOpenedSidePanels() + sidePanelPreOpenTest.resetPreOpenedSidePanels() }) describe("navigateSidePanel", () => { diff --git a/packages/extension/src/services/__tests__/contextMenus.test.ts b/packages/extension/src/services/__tests__/contextMenus.test.ts index 2cedf36b..d7b04a4c 100644 --- a/packages/extension/src/services/__tests__/contextMenus.test.ts +++ b/packages/extension/src/services/__tests__/contextMenus.test.ts @@ -1,6 +1,8 @@ import { describe, it, expect, vi, beforeEach } from "vitest" import { enhancedSettings } from "@/services/settings/enhancedSettings" -import { ContextMenu, toMenuId } from "../contextMenus" +import { ContextMenu, __test } from "../contextMenus" + +const { toMenuId } = __test import { OPEN_MODE, OPTION_FOLDER, ROOT_FOLDER } from "@/const" import type { Command, CommandFolder } from "@/types" diff --git a/packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts b/packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts index 8c598d04..007d00d4 100644 --- a/packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts +++ b/packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts @@ -6,9 +6,10 @@ import { preOpenSidePanel, consumePreOpenedSidePanel, cancelPreOpenedSidePanel, - resetPreOpenedSidePanels, - PRE_OPEN_TIMEOUT_MS, + __test, } from "../sidePanelPreOpen" + +const { resetPreOpenedSidePanels, PRE_OPEN_TIMEOUT_MS } = __test import { closeSidePanel } from "@/services/chrome" import { isSidePanelSupported } from "@/services/sidePanelSupport" import { SIDE_PANEL_RELAY_PATH } from "@/services/sidePanelUrl" @@ -44,7 +45,7 @@ describe("sidePanelPreOpen", () => { }) describe("usesSidePanel", () => { - it("SPO-US-01: サイドパネルを開くコマンドを判定する", () => { + it("SPO-US-01: 正常系: サイドパネルを開くコマンドを判定する", () => { expect( usesSidePanel(createCommand({ openMode: OPEN_MODE.SIDE_PANEL })), ).toBe(true) @@ -66,7 +67,7 @@ describe("sidePanelPreOpen", () => { ).toBe(true) }) - it("SPO-US-02: サイドパネルを開かないコマンドは false を返す", () => { + it("SPO-US-02: 正常系: サイドパネルを開かないコマンドは false を返す", () => { expect(usesSidePanel(createCommand({ openMode: OPEN_MODE.POPUP }))).toBe( false, ) @@ -90,7 +91,7 @@ describe("sidePanelPreOpen", () => { }) describe("preOpenSidePanel", () => { - it("SPO-PO-01: 空白ページを設定して同期的に open を呼び出す", () => { + it("SPO-PO-01: 正常系: 空白ページを設定して同期的に open を呼び出す", () => { preOpenSidePanel(1) expect(chrome.sidePanel.setOptions).toHaveBeenCalledWith({ @@ -102,7 +103,7 @@ describe("sidePanelPreOpen", () => { expect(chrome.sidePanel.open).toHaveBeenCalledWith({ tabId: 1 }) }) - it("SPO-PO-02: API 非対応時は何もしない", () => { + it("SPO-PO-02: 異常系: API 非対応時は何もしない", () => { vi.mocked(isSidePanelSupported).mockReturnValueOnce(false) preOpenSidePanel(1) @@ -111,7 +112,7 @@ describe("sidePanelPreOpen", () => { expect(consumePreOpenedSidePanel(1)).toBe(false) }) - it("SPO-PO-03: open に失敗したら事前オープン状態を破棄する", async () => { + it("SPO-PO-03: 異常系: open に失敗したら事前オープン状態を破棄する", async () => { vi.mocked(chrome.sidePanel.open).mockRejectedValueOnce( new Error("no user gesture"), ) @@ -124,7 +125,7 @@ describe("sidePanelPreOpen", () => { errorSpy.mockRestore() }) - it("SPO-PO-04: 期限内に使われなければサイドパネルを閉じる", () => { + it("SPO-PO-04: 異常系: 期限内に使われなければサイドパネルを閉じる", () => { const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) preOpenSidePanel(1) @@ -137,7 +138,7 @@ describe("sidePanelPreOpen", () => { }) describe("consumePreOpenedSidePanel", () => { - it("SPO-CO-01: 事前オープン状態を一度だけ返し、閉じるタイマーを止める", () => { + it("SPO-CO-01: 正常系: 事前オープン状態を一度だけ返し、閉じるタイマーを止める", () => { preOpenSidePanel(1) expect(consumePreOpenedSidePanel(2)).toBe(false) @@ -150,7 +151,7 @@ describe("sidePanelPreOpen", () => { }) describe("cancelPreOpenedSidePanel", () => { - it("SPO-CA-01: 未使用の事前オープンしたサイドパネルを閉じる", () => { + it("SPO-CA-01: 正常系: 未使用の事前オープンしたサイドパネルを閉じる", () => { preOpenSidePanel(1) cancelPreOpenedSidePanel(1) @@ -159,7 +160,7 @@ describe("sidePanelPreOpen", () => { expect(consumePreOpenedSidePanel(1)).toBe(false) }) - it("SPO-CA-02: 使用済みまたは未オープンなら何もしない", () => { + it("SPO-CA-02: 正常系: 使用済みまたは未オープンなら何もしない", () => { preOpenSidePanel(1) consumePreOpenedSidePanel(1) diff --git a/packages/extension/src/services/contextMenus.ts b/packages/extension/src/services/contextMenus.ts index 08751f0e..9700d138 100644 --- a/packages/extension/src/services/contextMenus.ts +++ b/packages/extension/src/services/contextMenus.ts @@ -46,7 +46,7 @@ const SIDE_PANEL_MENU_PREFIX = "sidePanel:" * @param {Command} command - The command shown in the menu. * @returns {string} The menu ID. */ -export const toMenuId = (command: Command): string => +const toMenuId = (command: Command): string => usesSidePanel(command) ? `${SIDE_PANEL_MENU_PREFIX}${command.id}` : command.id const isSidePanelMenuId = (menuItemId: string | number): boolean => @@ -249,3 +249,8 @@ export const ContextMenu = { } }, } + +/** Test-only exports. Do not use in production code. */ +export const __test = { + toMenuId, +} diff --git a/packages/extension/src/services/shortcut/serviceWorker.ts b/packages/extension/src/services/shortcut/serviceWorker.ts index 75a5e041..3618ec5f 100644 --- a/packages/extension/src/services/shortcut/serviceWorker.ts +++ b/packages/extension/src/services/shortcut/serviceWorker.ts @@ -9,6 +9,7 @@ import { ANALYTICS_EVENTS, sendEvent } from "@/services/analytics" import { getCenteredOffsetInCurrentWindow } from "@/services/screen" import { resolvePopupSize } from "@/services/option/defaultSettings" import { Settings } from "@/services/settings/settings" +import { Storage, STORAGE_KEY } from "@/services/storage" import { usesSidePanel, preOpenSidePanel, @@ -28,7 +29,9 @@ let sidePanelShortcutIds = new Set() */ const syncSidePanelShortcutIds = async (): Promise => { try { - const settings = await enhancedSettings.get() + // Read fresh settings: the cache of the shortcuts is invalidated after a + // debounce, so it may still hold the old value when this runs. + const settings = await enhancedSettings.get({ forceFresh: true }) const ids = new Set() for (const shortcut of settings.shortcuts?.shortcuts ?? []) { const command = settings.commands.find((c) => c.id === shortcut.commandId) @@ -65,7 +68,7 @@ const onCommand = async ( ): Promise => { // Must run before any await to keep the user gesture. let preOpenedTabId = preOpenSidePanelForShortcut(commandName, tab) - if (!sidePanelShortcutIdsLoaded) { + if (preOpenedTabId == null && !sidePanelShortcutIdsLoaded) { // The shortcut woke up the service worker, so the IDs are not loaded yet. // The user gesture may be lost after the await, but try it anyway. await sidePanelShortcutIdsReady @@ -208,6 +211,11 @@ export const registerShortcutListeners = (): void => { Settings.addChangedListener(() => { syncSidePanelShortcutIds() }) + // The shortcuts are stored separately, and the listener above is not + // called when only the shortcuts change. + Storage.addListener(STORAGE_KEY.SHORTCUTS, () => { + syncSidePanelShortcutIds() + }) // Expose only in the E2E worker for Playwright evaluation, without a message endpoint. if (import.meta.env.MODE === "e2e") { diff --git a/packages/extension/src/services/sidePanelPreOpen.ts b/packages/extension/src/services/sidePanelPreOpen.ts index 84112af0..d7a79c2e 100644 --- a/packages/extension/src/services/sidePanelPreOpen.ts +++ b/packages/extension/src/services/sidePanelPreOpen.ts @@ -24,7 +24,7 @@ import { SIDE_PANEL_RELAY_PATH } from "@/services/sidePanelUrl" * After that, the panel is closed so a blank panel is not left open when * the command fails or is skipped. */ -export const PRE_OPEN_TIMEOUT_MS = 10000 +const PRE_OPEN_TIMEOUT_MS = 10000 /** * Blank page shown until the target page is set. The relay page does @@ -67,20 +67,22 @@ export const preOpenSidePanel = (tabId: number): void => { .catch((e) => console.warn("Failed to set the side panel options:", e)) clearPreOpened(tabId) - preOpenedTabs.set( - tabId, - setTimeout(() => { - // The command did not request the side panel in time. - if (preOpenedTabs.delete(tabId)) { - console.warn("Close the pre-opened side panel:", tabId) - closeSidePanel(tabId) - } - }, PRE_OPEN_TIMEOUT_MS), - ) + const timer = setTimeout(() => { + // The command did not request the side panel in time. + if (preOpenedTabs.delete(tabId)) { + console.warn("Close the pre-opened side panel:", tabId) + closeSidePanel(tabId) + } + }, PRE_OPEN_TIMEOUT_MS) + preOpenedTabs.set(tabId, timer) chrome.sidePanel.open({ tabId }).catch((e) => { console.error("Failed to pre-open the side panel:", e) - clearPreOpened(tabId) + // Clear only the state of this call. A later pre-open of the same tab + // may have replaced it before this rejection arrived. + if (preOpenedTabs.get(tabId) === timer) { + clearPreOpened(tabId) + } }) } @@ -112,8 +114,14 @@ const clearPreOpened = (tabId: number): boolean => { return true } -/** Reset internal state — for testing only. */ -export const resetPreOpenedSidePanels = (): void => { +/** Reset internal state. */ +const resetPreOpenedSidePanels = (): void => { preOpenedTabs.forEach((timer) => clearTimeout(timer)) preOpenedTabs.clear() } + +/** Test-only exports. Do not use in production code. */ +export const __test = { + resetPreOpenedSidePanels, + PRE_OPEN_TIMEOUT_MS, +} From cfa514e8cd7417749e5c529476cc1ddd414af626 Mon Sep 17 00:00:00 2001 From: ujiro99 Date: Mon, 23 Nov 2026 22:08:24 +0900 Subject: [PATCH 3/3] fix(extension): avoid blank or lost side panels around the pre-open - Respond to executeAction, so the sender can tell a tab without the content script and close the pre-opened side panel at once. - Keep an already open side panel instead of replacing it with a blank page, and do not close it when the command does not run. - Skip the delayed disable of a pre-open close when the side panel of the tab is opened again while closing. - Extend the pre-open timeout to 30 seconds for permission prompts. - Fix the service worker tests broken by the shortcut storage listener. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pd1sH2SVL35AWHUxzVCAqk --- .../src/__tests__/service_worker.test.ts | 4 + .../src/action/__tests__/helper.test.ts | 1 + .../extension/src/hooks/useContextMenu.ts | 6 + .../__tests__/chrome.sidePanel.test.ts | 9 ++ .../services/__tests__/contextMenus.test.ts | 30 +++++ .../__tests__/sidePanelPreOpen.test.ts | 84 ++++++++++++- packages/extension/src/services/chrome.ts | 9 +- .../extension/src/services/contextMenus.ts | 5 +- .../src/services/shortcut/serviceWorker.ts | 9 +- .../src/services/sidePanelPreOpen.ts | 112 ++++++++++++++---- 10 files changed, 235 insertions(+), 34 deletions(-) diff --git a/packages/extension/src/__tests__/service_worker.test.ts b/packages/extension/src/__tests__/service_worker.test.ts index d49cf925..109ffce3 100644 --- a/packages/extension/src/__tests__/service_worker.test.ts +++ b/packages/extension/src/__tests__/service_worker.test.ts @@ -385,6 +385,7 @@ describe("Service Worker Migration", () => { vi.doMock("@/services/storage", () => ({ Storage: { + addListener: vi.fn(), get: vi.fn(), }, SESSION_STORAGE_KEY: {}, @@ -619,6 +620,7 @@ describe("Popup Auto-Close Delay", () => { const mockStorageSet = vi.fn().mockResolvedValue(undefined) vi.doMock("@/services/storage", () => ({ Storage: { + addListener: vi.fn(), set: mockStorageSet, }, SESSION_STORAGE_KEY: {}, @@ -681,6 +683,7 @@ describe("Popup Auto-Close Delay", () => { const mockStorageSet = vi.fn().mockResolvedValue(undefined) vi.doMock("@/services/storage", () => ({ Storage: { + addListener: vi.fn(), set: mockStorageSet, }, SESSION_STORAGE_KEY: {}, @@ -746,6 +749,7 @@ describe("Popup Auto-Close Delay", () => { const mockStorageSet = vi.fn().mockResolvedValue(undefined) vi.doMock("@/services/storage", () => ({ Storage: { + addListener: vi.fn(), set: mockStorageSet, }, SESSION_STORAGE_KEY: {}, diff --git a/packages/extension/src/action/__tests__/helper.test.ts b/packages/extension/src/action/__tests__/helper.test.ts index 5af73a64..f46f3ef5 100644 --- a/packages/extension/src/action/__tests__/helper.test.ts +++ b/packages/extension/src/action/__tests__/helper.test.ts @@ -52,6 +52,7 @@ vi.mock("@/services/settings/enhancedSettings", () => ({ vi.mock("@/services/sidePanelSupport", () => ({ isSidePanelSupported: vi.fn(() => true), + getSidePanelEvent: vi.fn(() => undefined), })) vi.mock("@/services/commandMetrics", () => ({ diff --git a/packages/extension/src/hooks/useContextMenu.ts b/packages/extension/src/hooks/useContextMenu.ts index a3028c75..52efa914 100644 --- a/packages/extension/src/hooks/useContextMenu.ts +++ b/packages/extension/src/hooks/useContextMenu.ts @@ -9,8 +9,14 @@ export function useContextMenu() { useEffect(() => { return Ipc.addListener(TabCommand.executeAction, (( param: executeActionProps, + _sender, + response, ) => { setAction(param) + // Tell the sender that the command is accepted. Otherwise it cannot + // tell this from a tab without the content script, which also + // resolves to undefined. + response(true) return false }) as IpcCallback) }, []) diff --git a/packages/extension/src/services/__tests__/chrome.sidePanel.test.ts b/packages/extension/src/services/__tests__/chrome.sidePanel.test.ts index f5145955..a49717db 100644 --- a/packages/extension/src/services/__tests__/chrome.sidePanel.test.ts +++ b/packages/extension/src/services/__tests__/chrome.sidePanel.test.ts @@ -92,6 +92,15 @@ describe("chrome.ts side panel functions", () => { }) describe("closeSidePanel", () => { + it("CSP-CL-04: 正常系: アニメーション後に shouldDisable が false なら無効化しない", async () => { + const promise = closeSidePanel(1, () => false) + await vi.advanceTimersByTimeAsync(1000) + await promise + + expect(sidePanel.close).toHaveBeenCalledWith({ tabId: 1 }) + expect(sidePanel.setOptions).not.toHaveBeenCalled() + }) + it("CSP-CL-01: 正常系: close 後にアニメーションを待って無効化する", async () => { const promise = closeSidePanel(1) await vi.advanceTimersByTimeAsync(0) diff --git a/packages/extension/src/services/__tests__/contextMenus.test.ts b/packages/extension/src/services/__tests__/contextMenus.test.ts index d7b04a4c..a830aa67 100644 --- a/packages/extension/src/services/__tests__/contextMenus.test.ts +++ b/packages/extension/src/services/__tests__/contextMenus.test.ts @@ -668,6 +668,36 @@ describe("Context Menu Multi-level Hierarchy", () => { global.chrome.sidePanel = original }) + it("CM-19: should close the pre-opened side panel when the tab does not accept the command", async () => { + const original = global.chrome.sidePanel + const close = vi.fn().mockResolvedValue(undefined) + const setOptions = vi.fn().mockResolvedValue(undefined) + global.chrome.sidePanel = { + open: vi.fn().mockResolvedValue(undefined), + close, + setOptions, + } as any + // The tab without the content script resolves to undefined. + global.chrome.tabs = { + sendMessage: vi.fn().mockResolvedValue(undefined), + } as any + const command = { + ...createCommand("cmd-sp", "Side panel", "folder1"), + openMode: OPEN_MODE.SIDE_PANEL, + } + ContextMenu.commandIdObj = { "sidePanel:cmd-sp": command } + const info = { menuItemId: "sidePanel:cmd-sp" } as any + const tab = { id: 123 } as any + + ContextMenu.preOpenSidePanel(info, tab) + await ContextMenu.onClicked(info, tab) + + await vi.waitFor(() => { + expect(close).toHaveBeenCalledWith({ tabId: 123 }) + }) + global.chrome.sidePanel = original + }) + it("CM-16: should not send executeAction when command is not found", async () => { const mockSendMessage = vi.fn().mockResolvedValue("success") global.chrome.tabs = { diff --git a/packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts b/packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts index 007d00d4..3800731d 100644 --- a/packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts +++ b/packages/extension/src/services/__tests__/sidePanelPreOpen.test.ts @@ -11,7 +11,11 @@ import { const { resetPreOpenedSidePanels, PRE_OPEN_TIMEOUT_MS } = __test import { closeSidePanel } from "@/services/chrome" -import { isSidePanelSupported } from "@/services/sidePanelSupport" +import { + isSidePanelSupported, + getSidePanelEvent, +} from "@/services/sidePanelSupport" +import { ServiceWorkerData } from "@/services/serviceWorkerData" import { SIDE_PANEL_RELAY_PATH } from "@/services/sidePanelUrl" vi.mock("@/services/chrome", () => ({ @@ -20,6 +24,13 @@ vi.mock("@/services/chrome", () => ({ vi.mock("@/services/sidePanelSupport", () => ({ isSidePanelSupported: vi.fn(() => true), + getSidePanelEvent: vi.fn(() => undefined), +})) + +vi.mock("@/services/serviceWorkerData", () => ({ + ServiceWorkerData: { + get: vi.fn(() => ({ sidePanelTabs: [] })), + }, })) const createCommand = (props: Partial): Command => @@ -131,7 +142,7 @@ describe("sidePanelPreOpen", () => { vi.advanceTimersByTime(PRE_OPEN_TIMEOUT_MS) - expect(closeSidePanel).toHaveBeenCalledWith(1) + expect(closeSidePanel).toHaveBeenCalledWith(1, expect.any(Function)) expect(consumePreOpenedSidePanel(1)).toBe(false) warnSpy.mockRestore() }) @@ -156,7 +167,7 @@ describe("sidePanelPreOpen", () => { cancelPreOpenedSidePanel(1) - expect(closeSidePanel).toHaveBeenCalledWith(1) + expect(closeSidePanel).toHaveBeenCalledWith(1, expect.any(Function)) expect(consumePreOpenedSidePanel(1)).toBe(false) }) @@ -170,4 +181,71 @@ describe("sidePanelPreOpen", () => { expect(closeSidePanel).not.toHaveBeenCalled() }) }) + describe("already open side panel", () => { + const setOpenTabs = (tabIds: number[]) => { + vi.mocked(getSidePanelEvent).mockReturnValue({} as never) + vi.mocked(ServiceWorkerData.get).mockReturnValue({ + sidePanelTabs: tabIds.map((tabId) => ({ tabId, isLinkCommand: false })), + } as never) + } + + afterEach(() => { + vi.mocked(getSidePanelEvent).mockReturnValue(undefined) + vi.mocked(ServiceWorkerData.get).mockReturnValue({ + sidePanelTabs: [], + } as never) + }) + + it("SPO-AO-01: 正常系: 開いているサイドパネルは置き換えず、キャンセルしても閉じない", () => { + setOpenTabs([1]) + + preOpenSidePanel(1) + + expect(chrome.sidePanel.setOptions).not.toHaveBeenCalled() + expect(chrome.sidePanel.open).not.toHaveBeenCalled() + + cancelPreOpenedSidePanel(1) + expect(closeSidePanel).not.toHaveBeenCalled() + }) + + it("SPO-AO-02: 正常系: 開いているサイドパネルでもページの設定だけを行わせる", () => { + setOpenTabs([1]) + + preOpenSidePanel(1) + + expect(consumePreOpenedSidePanel(1)).toBe(true) + }) + + it("SPO-AO-03: 正常系: onClosed 非対応時は開閉状態を信用せず事前オープンする", () => { + setOpenTabs([1]) + vi.mocked(getSidePanelEvent).mockReturnValue(undefined) + + preOpenSidePanel(1) + + expect(chrome.sidePanel.open).toHaveBeenCalledWith({ tabId: 1 }) + }) + }) + + describe("delayed close", () => { + it("SPO-DC-01: 正常系: 閉じている間に再度開かれたら無効化しない", () => { + preOpenSidePanel(1) + cancelPreOpenedSidePanel(1) + const shouldDisable = vi.mocked(closeSidePanel).mock.calls[0][1]! + + expect(shouldDisable()).toBe(true) + + // The side panel is requested again before the close finishes. + consumePreOpenedSidePanel(1) + expect(shouldDisable()).toBe(false) + }) + + it("SPO-DC-02: 正常系: 閉じている間に再度事前オープンされたら無効化しない", () => { + preOpenSidePanel(1) + cancelPreOpenedSidePanel(1) + const shouldDisable = vi.mocked(closeSidePanel).mock.calls[0][1]! + + preOpenSidePanel(1) + expect(shouldDisable()).toBe(false) + }) + }) }) diff --git a/packages/extension/src/services/chrome.ts b/packages/extension/src/services/chrome.ts index bf111508..0fb9823d 100644 --- a/packages/extension/src/services/chrome.ts +++ b/packages/extension/src/services/chrome.ts @@ -741,9 +741,15 @@ const SIDE_PANEL_CLOSE_ANIMATION = 1000 /** * Close the side panel for the specified tab * @param {number} tabId - The ID of the tab to close the side panel for + * @param {() => boolean} shouldDisable - Checked after the close animation. + * Return false to keep the side panel enabled, e.g. when it was opened again + * while closing. * @returns {Promise} A promise that resolves when the side panel is closed */ -export const closeSidePanel = async (tabId: number): Promise => { +export const closeSidePanel = async ( + tabId: number, + shouldDisable: () => boolean = () => true, +): Promise => { if (!isSidePanelSupported()) return // close() is detected separately because it is newer than open(). When it // is unavailable, setOptions({ enabled: false }) below closes the panel by @@ -757,6 +763,7 @@ export const closeSidePanel = async (tabId: number): Promise => { // Wait for the side panel close animation to finish before disabling it to prevent visual glitches. await sleep(SIDE_PANEL_CLOSE_ANIMATION) } + if (!shouldDisable()) return try { await chrome.sidePanel.setOptions({ tabId: tabId, diff --git a/packages/extension/src/services/contextMenus.ts b/packages/extension/src/services/contextMenus.ts index 9700d138..e3886415 100644 --- a/packages/extension/src/services/contextMenus.ts +++ b/packages/extension/src/services/contextMenus.ts @@ -241,8 +241,9 @@ export const ContextMenu = { const res = await Ipc.sendTab(tab.id, TabCommand.executeAction, { command, }) - if (res instanceof Error) { - // The command does not run, so do not leave a blank side panel. + if (res !== true) { + // The command does not run (e.g. the tab has no content script), so + // do not leave a blank side panel. cancelPreOpenedSidePanel(tab.id) } if (res) console.debug(res) diff --git a/packages/extension/src/services/shortcut/serviceWorker.ts b/packages/extension/src/services/shortcut/serviceWorker.ts index 3618ec5f..18b9d82d 100644 --- a/packages/extension/src/services/shortcut/serviceWorker.ts +++ b/packages/extension/src/services/shortcut/serviceWorker.ts @@ -9,7 +9,9 @@ import { ANALYTICS_EVENTS, sendEvent } from "@/services/analytics" import { getCenteredOffsetInCurrentWindow } from "@/services/screen" import { resolvePopupSize } from "@/services/option/defaultSettings" import { Settings } from "@/services/settings/settings" -import { Storage, STORAGE_KEY } from "@/services/storage" +import { Storage } from "@/services/storage" +// Imported from const, as some tests replace the storage module. +import { STORAGE_KEY } from "@/services/storage/const" import { usesSidePanel, preOpenSidePanel, @@ -164,6 +166,8 @@ async function handleShortcutCommand( ) } + // The content script responds true when it accepts the command. + executed = ret === true if (!enableSendTab || ret instanceof Error) { // Execute command directly in the service worker. // There is no selection position here, so center the popup in the @@ -179,8 +183,9 @@ async function handleShortcutCommand( selectionFromClipboard, pageUrl: tab?.url ?? "", }) + // The pre-open timeout closes the side panel if it is not requested. + executed = true } - executed = true sendEvent( ANALYTICS_EVENTS.SHORTCUT, { diff --git a/packages/extension/src/services/sidePanelPreOpen.ts b/packages/extension/src/services/sidePanelPreOpen.ts index d7a79c2e..62119e71 100644 --- a/packages/extension/src/services/sidePanelPreOpen.ts +++ b/packages/extension/src/services/sidePanelPreOpen.ts @@ -2,7 +2,11 @@ import { OPEN_MODE, PAGE_ACTION_OPEN_MODE } from "@/const" import type { Command } from "@/types" import { isAiPromptCommand, isPageActionCommand } from "@/lib/commandGuards" import { closeSidePanel } from "@/services/chrome" -import { isSidePanelSupported } from "@/services/sidePanelSupport" +import { + isSidePanelSupported, + getSidePanelEvent, +} from "@/services/sidePanelSupport" +import { ServiceWorkerData } from "@/services/serviceWorkerData" import { SIDE_PANEL_RELAY_PATH } from "@/services/sidePanelUrl" /** @@ -17,14 +21,18 @@ import { SIDE_PANEL_RELAY_PATH } from "@/services/sidePanelUrl" * with a blank page synchronously in the event handler, and the later * openSidePanel request only sets the target page (see * ActionHelper.openSidePanel). + * + * When the side panel of the tab is already open, it is kept as is, so the + * shown page is not lost if the command does not run after all. */ /** * How long a pre-opened side panel waits for the openSidePanel request. * After that, the panel is closed so a blank panel is not left open when - * the command fails or is skipped. + * the command fails or is skipped. Long enough for a permission prompt + * (e.g. reading the clipboard) shown while the command runs. */ -const PRE_OPEN_TIMEOUT_MS = 10000 +const PRE_OPEN_TIMEOUT_MS = 30000 /** * Blank page shown until the target page is set. The relay page does @@ -32,8 +40,46 @@ const PRE_OPEN_TIMEOUT_MS = 10000 */ const PLACEHOLDER_PATH = SIDE_PANEL_RELAY_PATH -// Tab ID → timer that closes the pre-opened side panel. -const preOpenedTabs = new Map>() +type PreOpened = { + /** Timer that gives up waiting for the openSidePanel request. */ + timer: ReturnType + /** False if the side panel was already open, so it must not be closed. */ + closeOnCancel: boolean +} + +// Tab ID → the pre-opened state. +const preOpenedTabs = new Map() + +// Tab ID → counter incremented whenever the side panel of the tab is about +// to be opened. Used to skip a delayed close for an older pre-open. +const openGenerations = new Map() + +const nextGeneration = (tabId: number): number => { + const generation = (openGenerations.get(tabId) ?? 0) + 1 + openGenerations.set(tabId, generation) + return generation +} + +/** + * Check whether the side panel of the tab is known to be open. + * sidePanelTabs tells it only when onClosed is available, because otherwise + * a side panel closed by the user is never removed from it. + */ +const isSidePanelOpen = (tabId: number): boolean => { + if (!getSidePanelEvent("onClosed")) return false + return ServiceWorkerData.get().sidePanelTabs.some((t) => t.tabId === tabId) +} + +/** + * Close the side panel opened by a pre-open that was not used. + * The close is skipped when the side panel of the tab is opened again while + * closing, as closeSidePanel disables the panel after its close animation. + */ +const closePreOpened = (tabId: number, state: PreOpened): void => { + if (!state.closeOnCancel) return + const generation = openGenerations.get(tabId) + closeSidePanel(tabId, () => openGenerations.get(tabId) === generation) +} /** * Check whether the command shows its result in the side panel. @@ -61,26 +107,36 @@ export const usesSidePanel = (command: Command): boolean => { export const preOpenSidePanel = (tabId: number): void => { if (!isSidePanelSupported()) return + clearPreOpened(tabId) + nextGeneration(tabId) + const alreadyOpen = isSidePanelOpen(tabId) + + const state: PreOpened = { + timer: setTimeout(() => { + // The command did not request the side panel in time. + if (preOpenedTabs.get(tabId) === state) { + preOpenedTabs.delete(tabId) + console.warn("Close the pre-opened side panel:", tabId) + closePreOpened(tabId, state) + } + }, PRE_OPEN_TIMEOUT_MS), + closeOnCancel: !alreadyOpen, + } + preOpenedTabs.set(tabId, state) + + // Keep the shown page. The later request only sets the target page. + if (alreadyOpen) return + // Do not await: open() must be called within the user gesture. chrome.sidePanel .setOptions({ tabId, path: PLACEHOLDER_PATH, enabled: true }) .catch((e) => console.warn("Failed to set the side panel options:", e)) - clearPreOpened(tabId) - const timer = setTimeout(() => { - // The command did not request the side panel in time. - if (preOpenedTabs.delete(tabId)) { - console.warn("Close the pre-opened side panel:", tabId) - closeSidePanel(tabId) - } - }, PRE_OPEN_TIMEOUT_MS) - preOpenedTabs.set(tabId, timer) - chrome.sidePanel.open({ tabId }).catch((e) => { console.error("Failed to pre-open the side panel:", e) // Clear only the state of this call. A later pre-open of the same tab // may have replaced it before this rejection arrived. - if (preOpenedTabs.get(tabId) === timer) { + if (preOpenedTabs.get(tabId) === state) { clearPreOpened(tabId) } }) @@ -88,12 +144,16 @@ export const preOpenSidePanel = (tabId: number): void => { /** * Take the pre-opened state of the tab. + * Call this whenever the side panel of the tab is about to be opened, even + * when it was not pre-opened, so a delayed close of an older pre-open does + * not disable the new side panel. * @param {number} tabId - The tab that requests the side panel. * @returns {boolean} True if the side panel was pre-opened for the tab, so * calling open() again is not needed. */ export const consumePreOpenedSidePanel = (tabId: number): boolean => { - return clearPreOpened(tabId) + nextGeneration(tabId) + return clearPreOpened(tabId) != null } /** @@ -101,23 +161,23 @@ export const consumePreOpenedSidePanel = (tabId: number): boolean => { * @param {number} tabId - The tab the side panel was pre-opened for. */ export const cancelPreOpenedSidePanel = (tabId: number): void => { - if (clearPreOpened(tabId)) { - closeSidePanel(tabId) - } + const state = clearPreOpened(tabId) + if (state) closePreOpened(tabId, state) } -const clearPreOpened = (tabId: number): boolean => { - const timer = preOpenedTabs.get(tabId) - if (timer === undefined) return false - clearTimeout(timer) +const clearPreOpened = (tabId: number): PreOpened | undefined => { + const state = preOpenedTabs.get(tabId) + if (state === undefined) return undefined + clearTimeout(state.timer) preOpenedTabs.delete(tabId) - return true + return state } /** Reset internal state. */ const resetPreOpenedSidePanels = (): void => { - preOpenedTabs.forEach((timer) => clearTimeout(timer)) + preOpenedTabs.forEach((state) => clearTimeout(state.timer)) preOpenedTabs.clear() + openGenerations.clear() } /** Test-only exports. Do not use in production code. */