diff --git a/apps/extension/src/entrypoints/background.ts b/apps/extension/src/entrypoints/background.ts index 1a9a788..5a2f0ef 100644 --- a/apps/extension/src/entrypoints/background.ts +++ b/apps/extension/src/entrypoints/background.ts @@ -339,10 +339,12 @@ export default defineBackground(() => { }, ...(ctx.signal !== undefined ? { signal: ctx.signal } : {}), deps: { - // Skip every Agent Window when choosing where to render the - // overlay — Agent Windows boot on about:blank, which has no - // content script, so they cannot surface an authorization decision. - isAgentWindowId: (windowId) => sessions.findByWindowId(windowId) !== null, + // The requesting window may host consent for an in-place borrow. + // Candidate selection still excludes about:blank/restricted pages. + isAgentWindowId: (windowId) => { + const owner = sessions.findByWindowId(windowId); + return owner !== null && owner.sessionId !== ctx.sessionId; + }, // Resolve i18n strings per-borrow so language switches take effect // without re-creating the dispatcher. notificationCopy: makeBorrowNotificationCopy(), diff --git a/apps/extension/src/session-manager/__tests__/task-popups.test.ts b/apps/extension/src/session-manager/__tests__/task-popups.test.ts new file mode 100644 index 0000000..f859bdc --- /dev/null +++ b/apps/extension/src/session-manager/__tests__/task-popups.test.ts @@ -0,0 +1,79 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { SessionManager } from "../manager"; +import { withTaskPopups } from "../task-popups"; + +afterEach(() => vi.unstubAllGlobals()); +async function fixture() { + let next = 10; + const manager = new SessionManager({ + remote: () => true, + agentWindow: { + create: async () => next++, + remove: vi.fn(async () => {}), + ensureActiveTab: async (id) => id, + }, + }); + const task = await manager.start("one"); + const other = await manager.start("two"); + const tabs = new Map([ + [10, { id: 10, windowId: 10, active: true }], + [11, { id: 11, windowId: 11, active: true }], + ]); + const listeners = new Set<(event: { sourceTabId: number; tabId: number }) => void>(); + const move = vi.fn(async (id: number, props: { windowId: number }) => + Object.assign(tabs.get(id)!, props), + ); + vi.stubGlobal("chrome", { + tabs: { query: async () => [tabs.get(10)], get: async (id: number) => tabs.get(id), move }, + webNavigation: { + onCreatedNavigationTarget: { + addListener: (fn: (event: { sourceTabId: number; tabId: number }) => void) => + listeners.add(fn), + removeListener: (fn: (event: { sourceTabId: number; tabId: number }) => void) => + listeners.delete(fn), + }, + }, + }); + const create = (sourceTabId: number, tabId: number, windowId = 10) => { + tabs.set(tabId, { id: tabId, windowId }); + for (const fn of listeners) fn({ sourceTabId, tabId }); + }; + return { manager, task, other, tabs, listeners, create, move }; +} +describe("action-scoped popup ownership", () => { + it("claims noopener/nested targets and moves a popup window into its task", async () => { + const f = await fixture(); + await withTaskPopups(f.manager, { session_id: "one" }, async () => { + f.create(10, 20); + f.create(20, 21, 200); + f.create(11, 22); // Another task's source. + f.tabs.set(23, { id: 23, windowId: 10 }); // User-created/moved tab, no navigation event. + }); + expect(f.task.agentCreatedTabs).toEqual(new Set([10, 20, 21])); + expect(f.move).toHaveBeenCalledWith(21, { windowId: 10, index: -1 }); + expect(f.listeners.size).toBe(0); + f.create(10, 24); // Outside an agent action. + expect(f.task.agentCreatedTabs.has(24)).toBe(false); + }); + it("cannot take a tab from another task or use an unauthorized source", async () => { + const f = await fixture(); + await withTaskPopups(f.manager, { session_id: "one", tab_id: 11 }, async () => + f.create(11, 30), + ); + await withTaskPopups(f.manager, { session_id: "one" }, async () => f.create(10, 11, 11)); + expect(f.task.agentCreatedTabs).toEqual(new Set([10])); + expect(f.other.agentCreatedTabs).toEqual(new Set([11])); + }); + it("cleans listeners on failure and rejects targets after source authorization ends", async () => { + const f = await fixture(); + await expect( + withTaskPopups(f.manager, { session_id: "one" }, async () => { + f.task.agentCreatedTabs.delete(10); + f.create(10, 20); + throw new Error("input failed"); + }), + ).rejects.toThrow("input failed"); + expect(f.task.agentCreatedTabs.size).toBe(0); + expect(f.listeners.size).toBe(0); + }); +}); diff --git a/apps/extension/src/session-manager/task-popups.ts b/apps/extension/src/session-manager/task-popups.ts new file mode 100644 index 0000000..53db1bf --- /dev/null +++ b/apps/extension/src/session-manager/task-popups.ts @@ -0,0 +1,72 @@ +import { isAgentControlledTab, type SessionManager } from "./manager"; + +/** Attribute only Chrome-reported navigation targets created during an agent + * action on an owned source. Window membership and openerTabId are insufficient. + * Delayed/unattributed popups can still use the ordinary consent-based borrow. */ +export async function withTaskPopups( + manager: SessionManager, + params: { session_id?: string; tab_id?: number }, + run: () => Promise, + onClaimed?: (tabId: number, windowId: number) => void, +): Promise { + const task = params.session_id ? manager.get(params.session_id) : null; + const events = globalThis.chrome?.webNavigation?.onCreatedNavigationTarget; + if (!task?.remote || !events) return run(); + const source = + params.tab_id ?? + ( + await chrome.tabs.query({ + windowId: task.agentWindowId, + active: true, + }) + )[0]?.id; + if (source === undefined || !isAgentControlledTab(task, source)) return run(); + const sources = new Set([source]); + const pending = new Set>(); + const live = () => manager.get(task.sessionId) === task && !manager.isWindowCloseExpected(task); + const created = ({ sourceTabId, tabId }: { sourceTabId: number; tabId: number }) => { + if ( + !live() || + !sources.has(sourceTabId) || + !isAgentControlledTab(task, sourceTabId) || + manager.list().some((other) => isAgentControlledTab(other, tabId)) + ) + return; + // Record ownership synchronously so a nested popup and cleanup see it. + task.agentCreatedTabs.add(tabId); + sources.add(tabId); + const work = (async () => { + try { + let tab = await chrome.tabs.get(tabId); + if (!live() || !isAgentControlledTab(task, tabId)) return; + const other = manager.findByWindowId(tab.windowId); + if (other && other !== task) { + task.agentCreatedTabs.delete(tabId); + sources.delete(tabId); + return; + } + if (tab.windowId !== task.agentWindowId) { + await chrome.tabs.move(tabId, { windowId: task.agentWindowId, index: -1 }); + tab = await chrome.tabs.get(tabId); + } + if (!live() || !isAgentControlledTab(task, tabId)) return; + onClaimed?.(tabId, tab.windowId); + } catch (error) { + // Preserve a live tab's ownership if moving it failed, so stop can clean + // it up; Chrome's removal event forgets tabs that have already closed. + console.warn("[bsk] task popup setup failed", error); + } + })(); + pending.add(work); + void work.then(() => pending.delete(work)); + }; + events.addListener(created); + try { + return await run(); + } finally { + // Chrome can deliver this event just after the CDP input acknowledgement. + await new Promise((resolve) => setTimeout(resolve, 100)); + events.removeListener(created); + await Promise.all(pending); + } +} diff --git a/apps/extension/src/tools/__tests__/tabs.test.ts b/apps/extension/src/tools/__tests__/tabs.test.ts index dc9fdb5..ae9534d 100644 --- a/apps/extension/src/tools/__tests__/tabs.test.ts +++ b/apps/extension/src/tools/__tests__/tabs.test.ts @@ -297,7 +297,7 @@ describe("handleTabCreate", () => { }); describe("handleTabClose", () => { - it("does not infer remote popup ownership from its opener and explains how to borrow it", async () => { + it("does not infer ownership from opener metadata but permits an approved in-place borrow", async () => { const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]), remote: () => true }); const ctx = await sm.start("aa11"); const state: FakeTabState = { @@ -309,6 +309,15 @@ describe("handleTabClose", () => { expect( await handleTabClose(sm, { session_id: "aa11", tab_id: 5 }, { tabs: api }), ).toMatchObject({ code: "permission_denied" }); + expect( + await handleTabBorrow( + sm, + { session_id: "aa11", tab_id: 5 }, + { tabs: api, approveBorrow: async () => false }, + ), + ).toMatchObject({ code: "cancelled" }); + expect(ctx.borrowedTabs.has(5)).toBe(false); + expect(ctx.agentCreatedTabs.has(5)).toBe(false); const approval = vi.fn(async () => true); expect( await handleTabBorrow( @@ -316,13 +325,32 @@ describe("handleTabClose", () => { { session_id: "aa11", tab_id: 5 }, { tabs: api, approveBorrow: approval }, ), - ).toMatchObject({ - code: "invalid_params", - message: expect.stringContaining("regular browser window"), - }); + ).toMatchObject({ tab_id: 5, original_window_id: 100, agent_window_id: 100 }); expect(ctx.agentCreatedTabs.has(5)).toBe(false); + expect(ctx.borrowedTabs.has(5)).toBe(true); expect(spies.remove).not.toHaveBeenCalled(); - expect(approval).not.toHaveBeenCalled(); + expect(spies.move).not.toHaveBeenCalled(); + expect(approval).toHaveBeenCalledOnce(); + const windows = makeWindowsApi(state).api; + const release = vi.fn(async () => {}); + expect( + await handleTabReturn( + sm, + { session_id: "aa11", tab_id: 5 }, + { + tabs: api, + windows, + cdp: { releaseSessionTab: release }, + agentOverlayReset: { resetAgentOverlays: vi.fn(async () => {}) }, + }, + ), + ).toMatchObject({ tab_id: 5, returned_to_window_id: 100 }); + expect(release).toHaveBeenCalledWith("aa11", 5); + expect(ctx.borrowedTabs.has(5)).toBe(false); + expect(state.tabs.has(5)).toBe(true); + expect( + await handleTabSelect(sm, { session_id: "aa11", tab_id: 5 }, { tabs: api }), + ).toMatchObject({ code: "permission_denied" }); }); it("removes a tab inside the Agent Window", async () => { const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) }); diff --git a/apps/extension/src/tools/dispatcher.ts b/apps/extension/src/tools/dispatcher.ts index 0726f27..8afdedf 100644 --- a/apps/extension/src/tools/dispatcher.ts +++ b/apps/extension/src/tools/dispatcher.ts @@ -3,6 +3,7 @@ import { OVERLAY_AUTOMATION_BYPASS } from "@/lib/overlay-bridge"; import type { TaskActivity } from "@/lib/task-activity"; import { ScreenshotExports } from "@/long-screenshot/exports"; import type { SessionManager } from "@/session-manager/manager"; +import { withTaskPopups } from "@/session-manager/task-popups"; import type { Transport } from "@/transport/transport"; import type { BlurParams, @@ -279,7 +280,25 @@ export class ToolDispatcher { } catch { /* The daemon still has the original operation metadata. */ } - const invoke = () => this.invoke(req, ac.signal); + const createsPopup = [ + "tool.click", + "tool.press_key", + "tool.evaluate", + "tool.navigate", + "tool.navigate_back", + "tool.navigate_forward", + "tool.fill", + "tool.select", + ].includes(req.method); + const invoke = () => + createsPopup + ? withTaskPopups( + this.sessions, + (req.params ?? {}) as { session_id?: string; tab_id?: number }, + () => this.invoke(req, ac.signal), + this.onAgentTabClaimed, + ) + : this.invoke(req, ac.signal); const result = this.taskActivity ? await this.taskActivity.run( (req.params as { session_id?: string } | undefined)?.session_id, diff --git a/apps/extension/src/tools/tabs.ts b/apps/extension/src/tools/tabs.ts index 5e90e6b..2570c74 100644 --- a/apps/extension/src/tools/tabs.ts +++ b/apps/extension/src/tools/tabs.ts @@ -646,13 +646,12 @@ async function validateBorrowTarget( if (typeof tab.id !== "number" || typeof tab.windowId !== "number") { return { code: "not_found", message: `tab ${tabId} not found` }; } - if (tab.windowId === ctx.agentWindowId) { + // Remote unowned tabs can request normal approval in place. Merely moving + // a tab into this window never authorizes it; confirmation still runs below. + if (tab.windowId === ctx.agentWindowId && (!ctx.remote || isAgentControlledTab(ctx, tabId))) { return { code: "invalid_params", - message: - ctx.remote && !isAgentControlledTab(ctx, tabId) - ? `tab_borrow: tab ${tabId} is not authorized and already lives in the Agent Window; move it to a regular browser window, then borrow it` - : `tab_borrow: tab ${tabId} already lives in the Agent Window`, + message: `tab_borrow: tab ${tabId} already lives in the Agent Window`, }; } for (const s of manager.list()) { @@ -772,14 +771,17 @@ async function executeBorrowCore( const originalWindowId = currentTab.windowId; const originalIndex = typeof currentTab.index === "number" ? currentTab.index : 0; - const moveErr = await moveTabForBorrow( - p.tabsApi, - p.tabId, - p.ctx.agentWindowId, - originalWindowId, - originalIndex, - p.signal, - ); + const moveErr = + originalWindowId === p.ctx.agentWindowId + ? null + : await moveTabForBorrow( + p.tabsApi, + p.tabId, + p.ctx.agentWindowId, + originalWindowId, + originalIndex, + p.signal, + ); if (moveErr) return moveErr; return { originalWindowId, originalIndex };