diff --git a/apps/extension/src/browser-driver/__tests__/chromium-cdp.test.ts b/apps/extension/src/browser-driver/__tests__/chromium-cdp.test.ts index 41b6719..ffa4a0b 100644 --- a/apps/extension/src/browser-driver/__tests__/chromium-cdp.test.ts +++ b/apps/extension/src/browser-driver/__tests__/chromium-cdp.test.ts @@ -29,6 +29,103 @@ function fakeApi() { } describe("ChromiumCdp", () => { + it("configures frame auto-attach once per debugger session and reapplies after detach", async () => { + const { api, onDetach } = fakeApi(); + vi.mocked(api.sendCommand).mockResolvedValue({ frameTree: { frame: { id: "main" } } }); + const cdp = new ChromiumCdp(api); + const calls = () => + vi.mocked(api.sendCommand).mock.calls.filter((c) => c[1] === "Target.setAutoAttach"); + await cdp.ensureAttached(4); + await Promise.all([cdp.getFrameGraph(4), cdp.getFrameGraph(4)]); + await cdp.getFrameGraph(4); + expect(calls()).toHaveLength(1); + onDetach.fire({ tabId: 4 }, "canceled_by_user"); + await cdp.getFrameGraph(4); + expect(calls()).toHaveLength(2); + await cdp.detachAll(); + await cdp.getFrameGraph(4); + expect(calls()).toHaveLength(3); + cdp.dispose(); + }); + + it("retries frame discovery after a failed configuration", async () => { + const { api } = fakeApi(); + let attempts = 0; + vi.mocked(api.sendCommand).mockImplementation(async (_target, method) => { + if (method === "Target.setAutoAttach" && ++attempts === 1) throw new Error("transient"); + return { frameTree: { frame: { id: "main" } } }; + }); + const cdp = new ChromiumCdp(api); + await cdp.ensureAttached(4); + await cdp.getFrameGraph(4); + await cdp.getFrameGraph(4); + expect(attempts).toBe(2); + cdp.dispose(); + }); + + it("does not send another screenshot after a local timeout while Chrome is still working", async () => { + vi.useFakeTimers(); + const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); + const { api } = fakeApi(); + let finish!: (value: unknown) => void; + vi.mocked(api.sendCommand).mockImplementation(async (_target, method) => { + if (method === "Page.captureScreenshot") + return new Promise((resolve) => { + finish = resolve; + }); + return {}; + }); + const cdp = new ChromiumCdp(api); + try { + await cdp.ensureAttached(4); + const first = expect(cdp.send(4, "Page.captureScreenshot")).rejects.toThrow("timed out"); + await vi.advanceTimersByTimeAsync(3000); + await first; + expect(cdp.hasPendingScreenshot(4)).toBe(true); + await expect(cdp.send(4, "Page.captureScreenshot")).rejects.toThrow("still running"); + expect( + vi.mocked(api.sendCommand).mock.calls.filter((c) => c[1] === "Page.captureScreenshot"), + ).toHaveLength(1); + finish({ data: "late" }); + await vi.advanceTimersByTimeAsync(0); + expect(cdp.hasPendingScreenshot(4)).toBe(false); + const next = cdp.send(4, "Page.captureScreenshot"); + await vi.advanceTimersByTimeAsync(0); + finish({ data: "new" }); + await expect(next).resolves.toEqual({ data: "new" }); + } finally { + cdp.dispose(); + warning.mockRestore(); + vi.useRealTimers(); + } + }); + + it("emulates activity only for owned task tabs and reapplies after detach", async () => { + const { api, onDetach } = fakeApi(); + const owned = new Set([4]); + const cdp = new ChromiumCdp(api, { shouldKeepTaskActive: (id) => owned.has(id) }); + await Promise.all([cdp.ensureAttached(4), cdp.ensureAttached(4)]); + await cdp.ensureAttached(5); + const focusCalls = () => + vi + .mocked(api.sendCommand) + .mock.calls.filter((call) => call[1] === "Emulation.setFocusEmulationEnabled"); + expect(focusCalls()).toEqual([ + [{ tabId: 4 }, "Emulation.setFocusEmulationEnabled", { enabled: true }], + ]); + // A previously observed user tab becomes eligible only once explicitly borrowed. + owned.add(5); + await cdp.send(5, "Page.getLayoutMetrics"); + expect(focusCalls()).toHaveLength(2); + onDetach.fire({ tabId: 4 }, "canceled_by_user"); + await cdp.ensureAttached(4); + expect(focusCalls()).toHaveLength(3); + await cdp.detach(4); + await cdp.ensureAttached(4); + expect(focusCalls()).toHaveLength(4); + cdp.dispose(); + }); + it("changes attachment identity only across real debugger attachments", async () => { const { api, onEvent, onDetach } = fakeApi(); const cdp = new ChromiumCdp(api); @@ -429,6 +526,7 @@ describe("ChromiumCdp", () => { expect(api.sendCommand).toHaveBeenCalledWith({ tabId: 3 }, "Page.handleJavaScriptDialog", { accept: true, }); + await vi.waitFor(() => expect(cdp.dialogsSince(3, cursor)).toHaveLength(1)); const dialogs = cdp.dialogsSince(3, cursor); expect(dialogs).toHaveLength(1); expect(dialogs[0]).toMatchObject({ @@ -478,7 +576,7 @@ describe("ChromiumCdp", () => { url: "https://example.com/", }); await Promise.resolve(); - expect(cdp.dialogsSince(11, 0)).toHaveLength(1); + await vi.waitFor(() => expect(cdp.dialogsSince(11, 0)).toHaveLength(1)); await cdp.detach(11); expect(cdp.dialogsSince(11, 0)).toHaveLength(0); }); diff --git a/apps/extension/src/browser-driver/__tests__/command-deadline.test.ts b/apps/extension/src/browser-driver/__tests__/command-deadline.test.ts new file mode 100644 index 0000000..796cf76 --- /dev/null +++ b/apps/extension/src/browser-driver/__tests__/command-deadline.test.ts @@ -0,0 +1,75 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { captureObservationFacts } from "@/tools/vom/capture-coordinator"; +import { CdpReadTimeoutError, runCdpCommand } from "../command-deadline"; + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); +}); +it("times out stuck snapshots with the actual method and stops fallback reads", async () => { + vi.useFakeTimers(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.spyOn(console, "debug").mockImplementation(() => {}); + const send = vi.fn(async (_tab: number, method: string) => + runCdpCommand({ tabId: 4 }, method, () => + method === "DOMSnapshot.captureSnapshot" ? new Promise(() => {}) : Promise.resolve({}), + ), + ); + const work = captureObservationFacts({ send: send as never }, 4); + const checked = expect(work).rejects.toThrow( + "DOMSnapshot.captureSnapshot timed out after 10000ms (tab 4)", + ); + await vi.advanceTimersByTimeAsync(10_000); + await checked; + expect(send.mock.calls.map((call) => call[1])).toEqual([ + "DOMSnapshot.captureSnapshot", + ]); + expect(vi.getTimerCount()).toBe(0); +}); +it("bounds screenshots and ignores their late reply", async () => { + vi.useFakeTimers(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.spyOn(console, "debug").mockImplementation(() => {}); + let finish!: (value: string) => void; + const work = runCdpCommand( + { tabId: 4 }, + "Page.captureScreenshot", + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const checked = expect(work).rejects.toBeInstanceOf(CdpReadTimeoutError); + await vi.advanceTimersByTimeAsync(3_000); + await checked; + finish("late image"); + await Promise.resolve(); + expect(vi.getTimerCount()).toBe(0); +}); + +it("distinguishes caller timeout from a late Chrome completion", async () => { + vi.useFakeTimers(); + const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); + let finish!: (value: string) => void; + const work = runCdpCommand( + { tabId: 4 }, + "Page.captureScreenshot", + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const checked = expect(work).rejects.toBeInstanceOf(CdpReadTimeoutError); + await vi.advanceTimersByTimeAsync(3000); + await checked; + expect(warning.mock.calls.filter((c) => c[0] === "[bsk cdp] slow command settled")).toHaveLength( + 0, + ); + await vi.advanceTimersByTimeAsync(5000); + finish("image"); + await vi.advanceTimersByTimeAsync(0); + expect(warning).toHaveBeenCalledWith( + "[bsk cdp] slow command settled", + expect.objectContaining({ elapsedMs: 8000, outcome: "returned", late: true }), + ); +}); diff --git a/apps/extension/src/browser-driver/__tests__/task-focus.browser.test.ts b/apps/extension/src/browser-driver/__tests__/task-focus.browser.test.ts new file mode 100644 index 0000000..deed38f --- /dev/null +++ b/apps/extension/src/browser-driver/__tests__/task-focus.browser.test.ts @@ -0,0 +1,94 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +import { captureVomObservation } from "@/tools/observation"; +import { type CdpDebuggerApi, ChromiumCdp } from "../chromium-cdp"; + +describe.skipIf(!process.env.BSK_GEOMETRY_CHROME)("real background task rendering", () => { + it.each([ + 0, 2000, + ])("renders a background page with %i repeated controls and restores visibility on detach", async (controlCount) => { + // Raw CDP deliberately avoids Playwright, which enables focus emulation by default + // and would mask this exact regression even when a Chrome tab is inactive. + const { withChrome } = await import( + new URL( + "../../../../../evals/browser/cases/regression/snapshot-coordinates/chrome.mjs", + import.meta.url, + ).href + ); + await withChrome( + { executable: process.env.BSK_GEOMETRY_CHROME, deviceScale: 1, zoom: 1 }, + async (send: any) => { + const foreground = (await send("Target.getTargets")).targetInfos.find( + (t: any) => t.type === "page", + ); + const { sessionId: foregroundSession } = await send("Target.attachToTarget", { + targetId: foreground.targetId, + flatten: true, + }); + const url = + "data:text/html," + + encodeURIComponent( + 'Background task

Loading

' + + "

Entry

Sample page content

".repeat( + controlCount, + ), + ); + const { targetId } = await send("Target.createTarget", { url, background: true }); + let sessionId = (await send("Target.attachToTarget", { targetId, flatten: true })) + .sessionId; + const evaluate = async (expression: string, session = sessionId) => + ( + await send( + "Runtime.evaluate", + { expression, awaitPromise: true, returnByValue: true }, + session, + ) + ).result.value; + await expect.poll(() => evaluate("document.readyState")).toBe("complete"); + expect( + await evaluate( + '({visibility:document.visibilityState,text:document.querySelector("p").textContent})', + ), + ).toEqual({ visibility: "hidden", text: "Loading" }); + await send("Target.detachFromTarget", { sessionId }); + const event = { addListener() {}, removeListener() {} }; + const api = { + attach: async () => { + sessionId = (await send("Target.attachToTarget", { targetId, flatten: true })) + .sessionId; + }, + detach: async () => { + await send("Target.detachFromTarget", { sessionId }); + }, + sendCommand: (_target: unknown, method: string, params: object) => + send(method, params, sessionId), + onEvent: event, + onDetach: event, + } as unknown as CdpDebuggerApi; + const cdp = new ChromiumCdp(api, { shouldKeepTaskActive: () => true }); + try { + await cdp.ensureAttached(4); + expect( + await evaluate( + 'new Promise(resolve=>requestAnimationFrame(()=>resolve(document.querySelector("p").textContent)))', + ), + ).toBe("Rendered"); + const observation = await captureVomObservation(cdp, 4, url); + expect(observation.text).toContain("Rendered"); + expect(observation.refs).toHaveLength(controlCount); + const image = await cdp.send<{ data: string }>(4, "Page.captureScreenshot", { + format: "jpeg", + fromSurface: true, + }); + expect(image.data.length).toBeGreaterThan(100); + expect(await evaluate("document.visibilityState", foregroundSession)).toBe("visible"); + await cdp.detach(4); + sessionId = (await send("Target.attachToTarget", { targetId, flatten: true })).sessionId; + expect(await evaluate("document.visibilityState")).toBe("hidden"); + } finally { + cdp.dispose(); + } + }, + ); + }, 20_000); +}); diff --git a/apps/extension/src/browser-driver/chromium-cdp.ts b/apps/extension/src/browser-driver/chromium-cdp.ts index ddbf5ee..a602adb 100644 --- a/apps/extension/src/browser-driver/chromium-cdp.ts +++ b/apps/extension/src/browser-driver/chromium-cdp.ts @@ -31,6 +31,7 @@ import type { NetworkEntryKind, NetworkResult, } from "@/transport/types"; +import { runCdpCommand } from "./command-deadline"; import { buildFrameGraph, type CdpFrameGraph, @@ -140,6 +141,7 @@ interface FrameDiscoveryState { sessions: Set; pending: Set>; generation: number; + enabled: Map>; } async function settleBeforeDeadline(promises: Promise[], deadline: number): Promise { @@ -164,6 +166,8 @@ async function settleBeforeDeadline(promises: Promise[], deadline: number) export class ChromiumCdp { private readonly api: CdpDebuggerApi; private readonly attachedTabs = new Set(); + private readonly pendingScreenshots = new Map>(); + private readonly taskFocus = new Map>(); private readonly attachmentIds = new Map(); private readonly attachInFlight = new Map>(); private readonly detachInFlight = new Map>(); @@ -189,6 +193,8 @@ export class ChromiumCdp { private readonly options: { /** CDP observation alone does not authorize dismissing user dialogs. */ shouldAutoAcceptDialog?: (tabId: number) => boolean | Promise; + /** Only explicitly controlled task tabs may emulate foreground page activity. */ + shouldKeepTaskActive?: (tabId: number) => boolean; } = {}, ) { this.api = api; @@ -210,7 +216,10 @@ export class ChromiumCdp { // New observers must wait before opening the next connection to that tab. const detaching = this.detachInFlight.get(tabId); if (detaching) await detaching; - if (this.attachedTabs.has(tabId)) return; + if (this.attachedTabs.has(tabId)) { + await this.keepTaskActive(tabId); + return; + } const existing = this.attachInFlight.get(tabId); if (existing) { await existing; @@ -219,6 +228,7 @@ export class ChromiumCdp { const attach = (async () => { await this.api.attach({ tabId }, CDP_PROTOCOL_VERSION); try { + await this.keepTaskActive(tabId); await this.enablePageDomain(tabId); await this.enableConsoleDomains(tabId); await this.enableNetworkDomainBestEffort(tabId); @@ -240,6 +250,7 @@ export class ChromiumCdp { await this.api.detach({ tabId }).catch((detachErr) => { console.debug("[bsk cdp] rollback detach failed", { tabId, detachErr }); }); + this.taskFocus.delete(tabId); throw err; } })() @@ -261,11 +272,9 @@ export class ChromiumCdp { * `chrome.runtime.lastError`. */ async send(tabId: number, method: string, params?: object): Promise { - if (!this.attachedTabs.has(tabId)) { - await this.ensureAttached(tabId); - } + await this.ensureAttached(tabId); try { - const result = await this.api.sendCommand({ tabId }, method, params ?? {}); + const result = await this.command({ tabId }, method, params ?? {}); return result as T; } catch (err) { throw normalizeError(err); @@ -273,11 +282,9 @@ export class ChromiumCdp { } async sendToTarget(target: CdpTarget, method: string, params?: object): Promise { - if (!this.attachedTabs.has(target.tabId)) { - await this.ensureAttached(target.tabId); - } + await this.ensureAttached(target.tabId); try { - return (await this.api.sendCommand(target, method, params ?? {})) as T; + return (await this.command(target, method, params ?? {})) as T; } catch (err) { throw normalizeError(err); } @@ -452,6 +459,7 @@ export class ChromiumCdp { if (!this.attachedTabs.has(tabId)) return; this.attachedTabs.delete(tabId); this.attachmentIds.delete(tabId); + this.taskFocus.delete(tabId); this.clearDialogState(tabId); this.clearConsoleState(tabId); this.clearNetworkState(tabId); @@ -511,6 +519,7 @@ export class ChromiumCdp { this.tabOwners.clear(); this.attachedTabs.clear(); this.attachmentIds.clear(); + this.taskFocus.clear(); this.dialogBuffers.clear(); this.dialogSequences.clear(); this.consoleBuffers.clear(); @@ -521,6 +530,7 @@ export class ChromiumCdp { this.networkDomainsEnabledTabs.clear(); this.networkRequestMeta.clear(); this.frameDiscovery.clear(); + this.pendingScreenshots.clear(); await Promise.all( tabs.map(async (tabId) => { try { @@ -532,8 +542,48 @@ export class ChromiumCdp { ); } + hasPendingScreenshot(tabId: number): boolean { + return this.pendingScreenshots.has(tabId); + } + + private command(target: CdpDebuggee, method: string, params: object): Promise { + return runCdpCommand(target, method, () => { + const tabId = target.tabId; + if (method !== "Page.captureScreenshot" || tabId === undefined) + return this.api.sendCommand(target, method, params); + // A local deadline cannot cancel a Chrome command. Keep this fence until + // Chrome actually replies (or detaches), so polling cannot pile up captures. + if (this.pendingScreenshots.has(tabId)) + throw new Error("Previous screenshot is still running in Chrome"); + const pending = this.api.sendCommand(target, method, params); + this.pendingScreenshots.set(tabId, pending); + const clear = () => { + if (this.pendingScreenshots.get(tabId) === pending) this.pendingScreenshots.delete(tabId); + }; + void pending.then(clear, clear); + return pending; + }); + } + + private async keepTaskActive(tabId: number): Promise { + if (!this.options.shouldKeepTaskActive?.(tabId)) return; + let work = this.taskFocus.get(tabId); + if (!work) { + // Emulate page visibility/focus without activating a Chrome tab or window. + // Chrome resets this per-debugger override when we detach at turn end. + work = this.command({ tabId }, "Emulation.setFocusEmulationEnabled", { enabled: true }) + .then(() => {}) + .catch((error) => { + this.taskFocus.delete(tabId); + throw error; + }); + this.taskFocus.set(tabId, work); + } + await work; + } + private async enablePageDomain(tabId: number): Promise { - await this.api.sendCommand({ tabId }, "Page.enable", {}); + await this.command({ tabId }, "Page.enable", {}); } private async enableConsoleDomains(tabId: number): Promise { @@ -546,7 +596,7 @@ export class ChromiumCdp { let failed = false; for (const method of ["Runtime.enable", "Log.enable"]) { try { - await this.api.sendCommand({ tabId }, method, {}); + await this.command({ tabId }, method, {}); } catch (err) { failed = true; console.debug("[bsk cdp] console domain enable failed", { tabId, method, err }); @@ -559,7 +609,7 @@ export class ChromiumCdp { private async enableNetworkDomain(tabId: number): Promise { if (this.networkDomainsEnabledTabs.has(tabId)) return; - await this.api.sendCommand({ tabId }, "Network.enable", {}); + await this.command({ tabId }, "Network.enable", {}); this.networkDomainsEnabledTabs.add(tabId); } @@ -571,13 +621,27 @@ export class ChromiumCdp { } } - private async enableFrameDiscovery(target: CdpTarget): Promise { - await this.api.sendCommand(target, "Target.setAutoAttach", { + private enableFrameDiscovery(target: CdpTarget): Promise { + const state = this.frameDiscoveryState(target.tabId); + const key = target.sessionId ?? "root"; + const existing = state.enabled.get(key); + if (existing) return existing; + // Auto-attach remains enabled for this debugger session, including later + // navigation and new iframes. Reconfiguring it on every observation adds a + // browser round trip and needlessly repeats child-target discovery. + const work = this.command(target, "Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: false, flatten: true, filter: [{ type: "iframe", exclude: false }], - }); + }) + .then(() => {}) + .catch((error) => { + if (state.enabled.get(key) === work) state.enabled.delete(key); + throw error; + }); + state.enabled.set(key, work); + return work; } private bindFrameTargetHandler(): void { @@ -591,6 +655,7 @@ export class ChromiumCdp { if (method === "Target.detachedFromTarget") { const state = this.frameDiscovery.get(tabId); + state?.enabled.delete(sessionId); if (state?.sessions.delete(sessionId)) state.generation += 1; return; } @@ -657,6 +722,7 @@ export class ChromiumCdp { sessions: new Set(), pending: new Set(), generation: 0, + enabled: new Map(), }; this.frameDiscovery.set(tabId, created); return created; @@ -664,6 +730,7 @@ export class ChromiumCdp { private clearFrameState(tabId: number): void { this.frameDiscovery.delete(tabId); + this.pendingScreenshots.delete(tabId); } private bindDialogHandler(): void { @@ -696,7 +763,7 @@ export class ChromiumCdp { if (parsed.type === "prompt") { handleParams.promptText = parsed.defaultPrompt ?? ""; } - await this.api.sendCommand({ tabId }, "Page.handleJavaScriptDialog", handleParams); + await this.command({ tabId }, "Page.handleJavaScriptDialog", handleParams); if (!this.attachedTabs.has(tabId) && !this.attachInFlight.has(tabId)) return; const sequence = (this.dialogSequences.get(tabId) ?? 0) + 1; this.dialogSequences.set(tabId, sequence); @@ -858,6 +925,7 @@ export class ChromiumCdp { if (typeof source.tabId === "number") { this.attachedTabs.delete(source.tabId); this.attachmentIds.delete(source.tabId); + this.taskFocus.delete(source.tabId); this.attachInFlight.delete(source.tabId); this.tabOwners.delete(source.tabId); this.clearDialogState(source.tabId); diff --git a/apps/extension/src/browser-driver/command-deadline.ts b/apps/extension/src/browser-driver/command-deadline.ts new file mode 100644 index 0000000..540d804 --- /dev/null +++ b/apps/extension/src/browser-driver/command-deadline.ts @@ -0,0 +1,78 @@ +import type { CdpDebuggee } from "./chromium-cdp"; + +// Bound renderer reads, not user-requested waits or mutations. An expired +// CDP read cannot be cancelled individually; its late reply is ignored and +// observation must stop rather than issue fallback reads against the same page. +const READ_COMMANDS = new Set([ + "Target.setAutoAttach", + "DOMSnapshot.enable", + "DOMSnapshot.captureSnapshot", + "Accessibility.enable", + "Accessibility.getFullAXTree", + "Page.getLayoutMetrics", + "Page.getFrameTree", + "DOM.getFrameOwner", + "Page.captureScreenshot", + "Emulation.setFocusEmulationEnabled", +]); +export class CdpReadTimeoutError extends Error { + constructor(method: string, tabId: number | undefined, timeout: number) { + super( + `Browser read ${method} timed out after ${timeout}ms (tab ${tabId}). Do not repeat the same read in a loop; report the timeout and let the browser task release control before retrying.`, + ); + this.name = "CdpReadTimeoutError"; + } +} + +export async function runCdpCommand( + target: CdpDebuggee, + method: string, + run: () => Promise, +): Promise { + const started = Date.now(); + const details = () => ({ + tabId: target.tabId, + frameSessionId: target.sessionId, + method, + elapsedMs: Date.now() - started, + }); + const slow = setTimeout(() => console.warn("[bsk cdp] slow command", details()), 2_000); + let deadline: ReturnType | undefined; + let timedOut = false; + const settled = (outcome: "returned" | "failed") => { + if (Date.now() - started >= 2_000) + console.warn("[bsk cdp] slow command settled", { ...details(), outcome, late: timedOut }); + }; + try { + const pending = run().then( + (value) => { + settled("returned"); + return value; + }, + (error) => { + settled("failed"); + throw error; + }, + ); + if (!READ_COMMANDS.has(method)) return await pending; + const timeout = method === "Page.captureScreenshot" ? 3_000 : 10_000; + return await Promise.race([ + pending, + new Promise((_, reject) => { + deadline = setTimeout(() => { + timedOut = true; + reject(new CdpReadTimeoutError(method, target.tabId, timeout)); + }, timeout); + }), + ]); + } catch (error) { + console.warn("[bsk cdp] command failed", { + ...details(), + error: error instanceof Error ? error.message : String(error), + }); + throw error; + } finally { + clearTimeout(slow); + clearTimeout(deadline); + } +} diff --git a/apps/extension/src/entrypoints/background.ts b/apps/extension/src/entrypoints/background.ts index 72819fa..ec6e0ac 100644 --- a/apps/extension/src/entrypoints/background.ts +++ b/apps/extension/src/entrypoints/background.ts @@ -1,7 +1,8 @@ +import { TaskActivity } from "@/lib/task-activity"; import { i18n } from "@browser-skill/i18n"; import { ChromiumCdp } from "@/browser-driver/chromium-cdp"; import { ConnectionController } from "@/lib/connection-controller"; -import { watchDaemonPort } from "@/lib/daemon-port-preference"; +import { watchDaemonConnection } from "@/lib/daemon-connection-preference"; import { startHeartbeat } from "@/lib/heartbeat"; import { getConnectionEnabled, @@ -24,6 +25,7 @@ import { import { POPUP_PORT_NAME, type PopupInbound, type PopupOutbound } from "@/lib/popup-bridge"; import { recordFrameCoordinator } from "@/lib/recording/frame-coordinator"; import { attachSessionsLiveFlag } from "@/lib/sessions-live-flag"; +import { captureTaskPreview } from "@/lib/task-preview"; import { createDisconnectCleanup } from "@/session-manager/disconnect-cleanup"; import { attachSessionEventHandler } from "@/session-manager/event-handler"; import { isAgentControlledTab, SessionManager } from "@/session-manager/manager"; @@ -44,28 +46,80 @@ import { } from "@/tools/record"; import { chromeTabsApi } from "@/tools/shared"; import { chromeTabMutationApi } from "@/tools/tabs"; -import { resolveDaemonWsUrl } from "@/transport/daemon-endpoint"; import { detectBrowserMeta } from "@/transport/handshake"; +import { watchRemoteAuthorization } from "@/transport/remote-authorization"; +import { type RemoteEndpoint, remoteSocket } from "@/transport/remote-endpoint"; +import { getTaskWindowEnabled } from "@/lib/task-window-preference"; import type { Transport } from "@/transport/transport"; import { WSTransport } from "@/transport/ws-transport"; export default defineBackground(() => { const controller = new ConnectionController(); - const transport = new WSTransport({ url: __BSK_DAEMON_WS_URL__ }); - const sessions = new SessionManager(); + let remoteEndpoint: RemoteEndpoint | null = null; + const transport = new WSTransport({ + url: __BSK_DAEMON_WS_URL__, + webSocketFactory: (url) => + remoteSocket( + url, + remoteEndpoint, + async (sessionId) => { + const task = sessions.get(sessionId); + if (!task) throw new Error("Browser task unavailable"); + const tabId = + task.activeTabId !== undefined && isAgentControlledTab(task, task.activeTabId) + ? task.activeTabId + : [...task.agentCreatedTabs, ...task.borrowedTabs.keys()][0]; + if (tabId === undefined || !isAgentControlledTab(task, tabId)) + throw new Error("Task tab unavailable"); + const tab = await chrome.tabs.get(tabId); + await chrome.tabs.update(tabId, { active: true }); + await chrome.windows.update(tab.windowId, { focused: true }); + }, + (sessionId) => + taskActivity.preview(sessionId, () => captureTaskPreview(sessions, cdp, sessionId)), + async (sessionId) => { + if (!sessions.get(sessionId)) throw new Error("Browser task unavailable"); + await taskActivity.release(sessionId); + return { released: true }; + }, + ), + }); + const sessions = new SessionManager({ + taskTabs: () => remoteEndpoint !== null, + taskWindow: getTaskWindowEnabled, + taskLabel: () => remoteEndpoint?.serviceName ?? "BrowserSkill", + }); const cdp = new ChromiumCdp(undefined, { + shouldKeepTaskActive: (tabId) => sessions.findByTabId(tabId)?.tabMode === true, shouldAutoAcceptDialog: async (tabId) => { const tab = await chrome.tabs.get(tabId); - return sessions.findByWindowId(tab.windowId) !== null; + return ( + (typeof tab.id === "number" && sessions.findByTabId(tab.id) !== null) || + sessions.findByWindowId(tab.windowId) !== null + ); }, }); + const taskActivity: TaskActivity = new TaskActivity(sessions, (id) => + dispatcher.releaseTaskControl(id), + ); const sessionsLive = attachSessionsLiveFlag({ manager: sessions }); let overlayGeneration = 0; const controlModes = new Map(); - const daemonPort = watchDaemonPort((port) => { - const url = resolveDaemonWsUrl(port); - void controller.reconfigureTransport(url, () => { + const remoteAuthorization = watchRemoteAuthorization(); + const daemonPort = watchDaemonConnection((url, remote) => { + remoteAuthorization.changed(); + // Token rotation for the same device must not interrupt a running task. + if ( + remote?.deviceId && + remoteEndpoint?.deviceId === remote.deviceId && + remoteEndpoint.url === remote.url + ) { + remoteEndpoint = remote; + return; + } + void controller.reconfigureTransport(JSON.stringify([url, remote]), () => { + remoteEndpoint = remote; transport.setUrl(url); }); }); @@ -104,8 +158,14 @@ export default defineBackground(() => { */ function overlayStateForTab(tabId?: number, windowId?: number): OverlayAgentStateMessage { if (typeof tabId === "number" && typeof windowId === "number") { - const ctx = sessions.findByWindowId(windowId); - if (ctx && isAgentControlledTab(ctx, tabId)) return overlayStateForWindow(windowId); + const ctx = sessions.findByTabId(tabId) ?? sessions.findByWindowId(windowId); + if (ctx && isAgentControlledTab(ctx, tabId)) + return { + type: OVERLAY_AGENT_STATE, + sessionId: ctx.sessionId, + mode: controlModes.get(ctx.sessionId) ?? "control", + generation: overlayGeneration, + }; } return { type: OVERLAY_AGENT_STATE, @@ -165,7 +225,7 @@ export default defineBackground(() => { } function pushOverlayStateForAgentWindow(windowId: number): void { - if (!sessions.findByWindowId(windowId)) return; + if (!sessions.list().some((ctx) => ctx.agentWindowId === windowId)) return; void pushOverlayStateForWindow(windowId); } chrome.tabs.onActivated.addListener((activeInfo) => { @@ -181,11 +241,32 @@ export default defineBackground(() => { // state; it never infers or mutates ownership from event ordering. chrome.tabs.onCreated.addListener((tab) => { if (typeof tab.windowId !== "number" || typeof tab.id !== "number") return; - if (!sessions.findByWindowId(tab.windowId)) return; + if (!sessions.list().some((ctx) => ctx.agentWindowId === tab.windowId)) return; void pushOverlayStateForTab(tab.id, tab.windowId); }); + chrome.tabs.onAttached.addListener((tabId, info) => { + const task = sessions.findByTabId(tabId); + if (task?.tabMode) void pushOverlayStateForTab(tabId, info.newWindowId); + }); chrome.tabs.onRemoved.addListener((tabId, removeInfo) => { + const task = sessions.findByTabId(tabId); sessions.forgetClosedTab(tabId, { isWindowClosing: removeInfo.isWindowClosing }); + if (task?.tabMode && !task.stopping && !task.agentCreatedTabs.size && !task.borrowedTabs.size) { + task.stopping = true; + void cdp + .detachSession(task.sessionId) + .then(() => sessions.stop(task.sessionId, { dropOnly: true })) + .then(() => { + onOverlaySessionStateChanged(); + transport.send({ + event: "session.window_closed", + payload: { session_id: task.sessionId, reason: "user_closed_window" }, + }); + }) + .catch(() => { + /* Connection cleanup also drops the task if disconnected. */ + }); + } }); // Re-sync the storage.session flag on SW startup so a previous SW's // stale `true` does not keep waking us on every page load until the @@ -227,6 +308,7 @@ export default defineBackground(() => { attachRecordQueryListener(recordDeps); const dispatcher = new ToolDispatcher({ + taskActivity, transport, sessions, cdp, @@ -247,6 +329,7 @@ export default defineBackground(() => { // Resolve i18n strings per-borrow so language switches take effect // without re-creating the dispatcher. notificationCopy: makeBorrowNotificationCopy(), + focusOnRequest: !remoteEndpoint, }, }), helpNotificationCopy: () => ({ @@ -355,7 +438,7 @@ export default defineBackground(() => { if (msg.kind === OVERLAY_MSG_WHO_AM_I) { const windowId = sender.tab?.windowId; - const ctx = typeof windowId === "number" ? sessions.findByWindowId(windowId) : null; + const ctx = sender.tab?.id !== undefined ? sessions.findByTabId(sender.tab.id) : null; sendResponse({ sessionId: ctx?.sessionId ?? null }); return false; } @@ -372,7 +455,11 @@ export default defineBackground(() => { if (msg.kind === OVERLAY_MSG_INTERRUPT) { const req = msg as OverlayInterruptRequest; const ctx = sessions.get(req.sessionId); - if (ctx) setControlMode(req.sessionId, "interrupting"); + if (!ctx || sender.tab?.id === undefined || !isAgentControlledTab(ctx, sender.tab.id)) { + sendResponse({ ok: false, error: "Task tab is not authorized" }); + return false; + } + setControlMode(req.sessionId, "interrupting"); void handleOverlayInterrupt(transport, req.sessionId).then((reply) => { if (reply.ok && sessions.get(req.sessionId)) { setControlMode(req.sessionId, "paused"); diff --git a/apps/extension/src/entrypoints/popup/App.tsx b/apps/extension/src/entrypoints/popup/App.tsx index 29ee388..2ea435f 100644 --- a/apps/extension/src/entrypoints/popup/App.tsx +++ b/apps/extension/src/entrypoints/popup/App.tsx @@ -13,6 +13,8 @@ import { PROTOCOL_VERSION } from "@/transport/handshake"; import functionIconUrl from "../../../assets/function.svg"; import { ConnectionStatusIndicator } from "./connection-status-indicator"; import { POPUP_FEATURES, type PopupView } from "./features"; +import { RemoteConnection } from "./remote-connection"; +import { TaskWindowMode } from "./task-window-mode"; import { Switch } from "./switch"; import { type PopupStatusState, useConnectionState } from "./use-connection-state"; import { useControlHintsHidden } from "./use-control-hints-hidden"; @@ -54,6 +56,7 @@ export function App() { dirty: daemonPortDirty, error: daemonPortError, } = useDaemonPort(); + const [remoteConfigured, setRemoteConfigured] = useState(false); const [view, setView] = useState("main"); const [copiedInstanceId, setCopiedInstanceId] = useState(false); const [purposeDraft, setPurposeDraft] = useState(""); @@ -275,9 +278,12 @@ export function App() { + + {remoteConfigured && }