Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

fix(agents): a close that names no tab asks first when the run has switched to one of the user's tabs, as the daemon now follows the tab each tab action lands on, and a tab that takes over a conversation's first tab no longer counts as one the user chose

Shahriarfba14890a9c1
diff --git a/src/daemon/agent/service.test.ts b/src/daemon/agent/service.test.ts
index bcd3d5b..609c29f 100644
--- a/src/daemon/agent/service.test.ts
+++ b/src/daemon/agent/service.test.ts
@@ -275,6 +275,38 @@ describe('a conversation across several tabs', () => {
asked: ['page.closeTab'],
});
});
+
+ test('asks before closing the tab it switched to when the close names no tab', async () => {
+ const agent = stubCli(join(dirname(configPath), 'agent-bare-close'), 'setTimeout(() => {}, 30_000);');
+ writeFileSync(configPath, JSON.stringify(onlyAgent('claude', agent)));
+ const events: RunEvent[] = [];
+ const invoked: unknown[] = [];
+ const across = new AgentSession({
+ invoke: async (action, input) => {
+ invoked.push([action, input]);
+ return success(action === 'page.switchTab' ? { activeTabId: 9 } : { done: true });
+ },
+ emit: (_runId: string, event: RunEvent) => void events.push(event),
+ draft: () => {},
+ actionNames: () => [],
+ });
+ const tabs = [
+ { tabId: 3, title: 'Board', host: 'jira.example.com', current: true as const, chosen: true as const },
+ { tabId: 9, title: 'Ticket', host: 'zendesk.example.com', chosen: true as const },
+ ];
+ across.handle({ t: 'instruct', id: 'r1', text: 'tidy up', context: { sessionId: 's1', url: 'https://jira.example.com/b', tabId: 3, tabs } });
+ await vi.waitFor(() => expect(across.offerFor('r1')).not.toBeNull());
+
+ await across.invokeForRun('r1', 'page.switchTab', { tabId: 9 });
+ void across.invokeForRun('r1', 'page.closeTab', {});
+ await vi.waitFor(() => expect(events.some((event) => event.kind === 'approval')).toBe(true));
+ across.dispose();
+
+ expect({
+ invoked,
+ asked: events.flatMap((event) => (event.kind === 'approval' ? [event.action] : [])),
+ }).toEqual({ invoked: [['page.switchTab', { tabId: 9 }]], asked: ['page.closeTab'] });
+ });
});
// Cursor abandons a tool call at 60 s, so an approval cannot simply hold the call open until the user answers.
diff --git a/src/daemon/agent/service.ts b/src/daemon/agent/service.ts
index b0363f7..1713a50 100644
--- a/src/daemon/agent/service.ts
+++ b/src/daemon/agent/service.ts
@@ -14,10 +14,12 @@ import {
import { awaitMonitor } from '@/lib/actions/page/await-monitor';
import { callSiteTool } from '@/lib/actions/page/call-site-tool';
import { captureDownload } from '@/lib/actions/page/capture-download';
+import { closeTab } from '@/lib/actions/page/close-tab';
import { openTab } from '@/lib/actions/page/open-tab';
import { pickElement } from '@/lib/actions/page/pick-element';
import { runCode } from '@/lib/actions/page/run-code';
import { solveCaptcha } from '@/lib/actions/page/solve-captcha';
+import { switchTab } from '@/lib/actions/page/switch-tab';
import { waitForElement } from '@/lib/actions/page/wait-for-element';
import { notOnPhone, phoneOffers } from '@/lib/phone/features';
import { FOCUS_SHOT_ACTION, READ_SITEMAP_ACTION } from '@/lib/actions/reserved';
@@ -97,6 +99,8 @@ interface ActiveRun {
pending: Map<string, (answer: Decision) => void>;
/** Tabs this run opened itself, which its own scope may therefore reach. */
ownedTabIds: number[];
+ /** The tab a tab action left it on, null when the browser chose one; unset until it first moves. */
+ currentTabId?: number | null;
/** Host of the tab this run started on — what "this site" means on an approval card. */
site?: string;
map?: MapRun;
@@ -124,6 +128,11 @@ const FOCUS_SHOT_TOOL_NAME = toolNameFor(FOCUS_SHOT_ACTION);
/** Getting past a captcha takes a call per round; one yes covers every round of that run. */
const HELD_FOR_RUN = new Set([CAPTCHA_ACTION]);
+/** Each reports the tab the browser shows afterwards, which is where the run's next action lands. */
+const TAB_ACTIONS = new Set([openTab.name, switchTab.name, closeTab.name]);
+
+const scopeOf = (run: ActiveRun): Scope => ({ ...run.scope, ownedTabIds: run.ownedTabIds, currentTabId: run.currentTabId });
+
/** Actions whose `timeoutMs` is how long the call itself waits, not how long something runs after it. */
const WAITS = [awaitMonitor, pickElement, solveCaptcha, waitForElement, runCode, callSiteTool, captureDownload];
@@ -314,8 +323,7 @@ export class AgentSession {
return result;
}
- const scope = run.ownedTabIds.length ? { ...run.scope, ownedTabIds: run.ownedTabIds } : run.scope;
- const decision = decide({ action, input, caller: 'agent', scope }, run.policy);
+ const decision = decide({ action, input, caller: 'agent', scope: scopeOf(run) }, run.policy);
if (decision.effect === 'deny') {
log(`agent run ${runId} blocked ${action}: ${describeDecision(decision)}`);
emit({ kind: 'toolResult', toolId, ok: false, summary: `blocked: ${summarizeDecision(decision)}` });
@@ -367,12 +375,15 @@ export class AgentSession {
}
private async perform(run: ActiveRun, toolId: string, action: string, input: unknown, startedAt: number): Promise<ActionResult> {
- const scope = run.ownedTabIds.length ? { ...run.scope, ownedTabIds: run.ownedTabIds } : run.scope;
- const result = await this.deps.invoke(action, this.withinCall(run, action, input, startedAt), { runId: run.id, hosts: scope.hosts });
+ const result = await this.deps.invoke(action, this.withinCall(run, action, input, startedAt), { runId: run.id, hosts: run.scope.hosts });
if (action === openTab.name && result.ok) {
const opened = (result.data as { tabId?: unknown } | null)?.tabId;
if (typeof opened === 'number') run.ownedTabIds.push(opened);
}
+ if (TAB_ACTIONS.has(action) && result.ok) {
+ const landed = (result.data as { activeTabId?: unknown } | null)?.activeTabId;
+ run.currentTabId = typeof landed === 'number' ? landed : null;
+ }
log(`agent → ${action} ${result.ok ? 'ok' : result.error.code}`);
this.deps.emit(run.id, { kind: 'toolResult', toolId, ok: result.ok, summary: summarize(input, result) });
return result;
diff --git a/src/daemon/guardrails/policy.test.ts b/src/daemon/guardrails/policy.test.ts
index eca885e..a1c0dad 100644
--- a/src/daemon/guardrails/policy.test.ts
+++ b/src/daemon/guardrails/policy.test.ts
@@ -224,6 +224,21 @@ describe('decisions for a watched run', () => {
expect(rules(across('page.closeTab', { tabId: 9 }))).toEqual(['leaves-pinned-tab']);
});
+ test('closing the one it switched to, by naming no tab, still confirms', () => {
+ const switched = decide({ action: 'page.closeTab', input: {}, caller: 'agent', scope: { ...spanning, currentTabId: 9 } });
+ expect(rules(switched)).toEqual(['leaves-pinned-tab']);
+ });
+
+ test('closing whichever tab the browser left it on confirms', () => {
+ expect(decide({ action: 'page.closeTab', input: {}, caller: 'agent', scope: { ...spanning, currentTabId: null } }).effect).toBe('confirm');
+ });
+
+ test('closing its own tab by naming no tab is fine', () => {
+ expect(across('page.closeTab', {}).effect).toBe('allow');
+ const opened = { ...spanning, ownedTabIds: [20], currentTabId: 20 };
+ expect(decide({ action: 'page.closeTab', input: {}, caller: 'agent', scope: opened }).effect).toBe('allow');
+ });
+
test('a tab outside the conversation still confirms', () => {
expect(across('page.switchTab', { tabId: 12 }).effect).toBe('confirm');
});
diff --git a/src/daemon/guardrails/scope.ts b/src/daemon/guardrails/scope.ts
index e37bf2f..16c1c2f 100644
--- a/src/daemon/guardrails/scope.ts
+++ b/src/daemon/guardrails/scope.ts
@@ -25,6 +25,8 @@ export interface Scope {
readonly ownedTabIds?: readonly number[];
/** The conversation's other tabs, which the run may switch to without asking but not close. */
readonly sharedTabIds?: readonly number[];
+ /** Where the run's actions land since a tab action moved it, or null when the browser picked the tab. */
+ readonly currentTabId?: number | null;
}
/** A tab of the conversation as the run begins. Only one the user chose brings its site into scope. */
@@ -191,14 +193,19 @@ export function urlPayloadBytes(url: URL): number {
/**
* Whether an action would move the run off the tab it is pinned to. A bare
* `page.switchTab` with no arguments only lists the open tabs, so it is not a move,
- * and switching to another of the conversation's tabs is not one either. Closing one is.
+ * and switching to another of the conversation's tabs is not one either. Closing one is,
+ * and a bare `page.closeTab` closes whichever tab the run is on now.
*/
export function targetsAnotherTab(action: string, input: unknown, scope: Scope): boolean {
if (scope.tabId === undefined || !TAB_MOVES.has(action)) return false;
const args = (input ?? {}) as { tabId?: unknown; match?: unknown };
if (typeof args.tabId === 'number') {
- if (args.tabId === scope.tabId || scope.ownedTabIds?.includes(args.tabId)) return false;
+ if (isRunsOwnTab(args.tabId, scope)) return false;
return !(action === 'page.switchTab' && scope.sharedTabIds?.includes(args.tabId));
}
- return typeof args.match === 'string' && args.match.length > 0;
+ if (typeof args.match === 'string' && args.match.length > 0) return true;
+ return action === 'page.closeTab' && !isRunsOwnTab(scope.currentTabId === undefined ? scope.tabId : scope.currentTabId, scope);
}
+
+const isRunsOwnTab = (tabId: number | null, scope: Scope) =>
+ tabId !== null && (tabId === scope.tabId || !!scope.ownedTabIds?.includes(tabId));
diff --git a/src/lib/bridge/tab-sessions.test.ts b/src/lib/bridge/tab-sessions.test.ts
index 2bda685..32b5ce9 100644
--- a/src/lib/bridge/tab-sessions.test.ts
+++ b/src/lib/bridge/tab-sessions.test.ts
@@ -118,6 +118,13 @@ describe('taking a tab out', () => {
expect(lists((await readTabSessions())[session.sessionId])).toEqual({ main: 2, current: 2, tabs: [2], user: [2], opened: [] });
});
+ test('hands the conversation to a tab the agent opened without making it one the user chose', async () => {
+ const { adoptSubtab, removeTab, readTabSessions, session } = await begun(1);
+ await adoptSubtab(session.sessionId, 2, { activate: false, opened: true });
+ expect(await removeTab(session.sessionId, 1)).toBe('removed');
+ expect(lists((await readTabSessions())[session.sessionId])).toEqual({ main: 2, current: 2, tabs: [2], user: [], opened: [2] });
+ });
+
test('is refused for the last tab, and while a run is going', async () => {
const { addTabs, patchSession, removeTab, session } = await begun(1);
expect(await removeTab(session.sessionId, 1)).toBe('last');
@@ -144,6 +151,13 @@ describe('closing a tab', () => {
expect(lists(released.handed)).toEqual({ main: 3, current: 3, tabs: [2, 3], user: [3], opened: [2] });
});
+ test('the conversation began in hands it to a tab the agent reached without making it one the user chose', async () => {
+ const { adoptSubtab, releaseTab, session } = await begun(1);
+ await adoptSubtab(session.sessionId, 2, { activate: false, opened: false });
+ const released = await releaseTab(1, [2]);
+ expect(lists(released.handed)).toEqual({ main: 2, current: 2, tabs: [2], user: [], opened: [] });
+ });
+
test('with only tabs the agent opened left ends it, as it always did', async () => {
const { adoptSubtab, releaseTab, readTabSessions, session } = await begun(1);
await adoptSubtab(session.sessionId, 2, { activate: true, opened: true });
diff --git a/src/lib/bridge/tab-sessions.ts b/src/lib/bridge/tab-sessions.ts
index c9e8510..5272319 100644
--- a/src/lib/bridge/tab-sessions.ts
+++ b/src/lib/bridge/tab-sessions.ts
@@ -318,7 +318,6 @@ function leave(session: TabSession, tabId: number, heirs: readonly number[]): bo
const heir = heirs.find((id) => session.tabIds.includes(id));
if (heir === undefined) return false;
session.mainTabId = heir;
- if (!session.userTabIds.includes(heir)) session.userTabIds.push(heir);
}
if (session.currentTabId === tabId) session.currentTabId = session.mainTabId;
return true;