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.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(extension): a conversation holds the tabs the user adds, works in the one they send from, carries on when its first tab closes, and a finished task closes only the tabs it opened
Shahriar685ac18bf318
diff --git a/src/extension/components/task-panel.tsx b/src/extension/components/task-panel.tsxindex 38b7043..13fe997 100644--- a/src/extension/components/task-panel.tsx+++ b/src/extension/components/task-panel.tsx@@ -164,7 +164,7 @@ export function TaskPanel({onEdit={() => setView({ kind: 'edit', task })}onHistory={() => setView({ kind: 'runs', taskId: task.id })}onWatch={session ? () => onWatch(session.sessionId) : undefined}- onStop={session ? () => void browser.tabs.remove(session.tabIds).catch(() => undefined) : undefined}+ onStop={session ? () => void browser.tabs.remove(session.openedTabIds).catch(() => undefined) : undefined}/>);})diff --git a/src/lib/bridge/hands-free.test.ts b/src/lib/bridge/hands-free.test.tsindex 7ade2ef..f12761f 100644--- a/src/lib/bridge/hands-free.test.ts+++ b/src/lib/bridge/hands-free.test.ts@@ -17,6 +17,8 @@ const session = (patch: Partial<TabSession>): TabSession => ({sessionId: 's',mainTabId: 7,tabIds: [7],+ userTabIds: [7],+ openedTabIds: [],currentTabId: 7,windowId: 1,title: 'Page',diff --git a/src/lib/bridge/invoke.ts b/src/lib/bridge/invoke.tsindex 88a83b3..05a1df5 100644--- a/src/lib/bridge/invoke.ts+++ b/src/lib/bridge/invoke.ts@@ -299,7 +299,10 @@ async function openSessionTab(input: unknown, owner: TabSession | null): Promiseif (!result.ok) return result;const opened = (result.data as { tabId?: unknown; activeTabId?: unknown }).tabId;if (typeof opened === 'number') {- await adoptSubtab(owner.sessionId, opened, (result.data as { activeTabId?: unknown }).activeTabId === opened);+ await adoptSubtab(owner.sessionId, opened, {+ activate: (result.data as { activeTabId?: unknown }).activeTabId === opened,+ opened: true,+ });}return result;}@@ -324,7 +327,7 @@ async function switchSessionTab(current: TabRef, input: unknown, owner: TabSessiif (typeof landed !== 'number' || landed === current.id) return result;if (owner.tabIds.includes(landed)) await setCurrentTab(owner.sessionId, landed);- else if (!(await sessionForTab(landed))) await adoptSubtab(owner.sessionId, landed, true);+ else if (!(await sessionForTab(landed))) await adoptSubtab(owner.sessionId, landed, { activate: true, opened: false });return result;}diff --git a/src/lib/bridge/run-indicator.test.ts b/src/lib/bridge/run-indicator.test.tsindex 1bf9ce9..ce4b306 100644--- a/src/lib/bridge/run-indicator.test.ts+++ b/src/lib/bridge/run-indicator.test.ts@@ -24,6 +24,8 @@ describe('syncRunIndicator', () => {sessionId: 'running',mainTabId: tab.id!,tabIds: [tab.id!, frozen.id!],+ userTabIds: [tab.id!],+ openedTabIds: [frozen.id!],currentTabId: tab.id!,windowId: -1,title: 'Example',diff --git a/src/lib/bridge/run-indicator.ts b/src/lib/bridge/run-indicator.tsindex 305ec0d..5265f54 100644--- a/src/lib/bridge/run-indicator.ts+++ b/src/lib/bridge/run-indicator.ts@@ -24,8 +24,10 @@ export async function syncRunIndicator(): Promise<void> {for (const session of Object.values(await readTabSessions())) {if (session.runId) for (const tabId of session.tabIds) busy.add(tabId);}- for (const tabId of busy) if (!marked.has(tabId)) await paint(tabId, true);- for (const tabId of [...marked]) if (!busy.has(tabId)) await paint(tabId, false);+ await Promise.all([+ ...[...busy].filter((tabId) => !marked.has(tabId)).map((tabId) => paint(tabId, true)),+ ...[...marked].filter((tabId) => !busy.has(tabId)).map((tabId) => paint(tabId, false)),+ ]);await syncRail();}diff --git a/src/lib/bridge/run-port.ts b/src/lib/bridge/run-port.tsindex 722f455..74e766e 100644--- a/src/lib/bridge/run-port.ts+++ b/src/lib/bridge/run-port.ts@@ -3,8 +3,10 @@ import {EXTERNAL_RUN_ID,failure,success,+ TABS_PROTOCOL,type ActionResult,type AttachedFile,+ type ConversationTab,type FocusedElement,type RunEvent,type SavedRecording,@@ -48,6 +50,7 @@ import {import { currentRecording, onRecordingState, startActiveTabRecording, stopRecording } from './recorder';import { asSavedRecording, listRecordings, readRecordingBody } from './recording-store';import { redactInput } from './redact';+import { sealForPage } from './secret-vault';import { forgetTab, syncRunIndicator } from './run-indicator';import { attachPreview, monitorNotice, nextId, notice, patchTool, reduce, type RunItem } from './run-items';import { onScreenshotPreview, type ScreenshotPreview } from './screenshot-preview';@@ -69,6 +72,7 @@ import { onToastAnswer } from './toast';import {activateSiteMap,cancelRun,+ daemonSpeaks,discardSiteMap,onPhoneClosed,onRunEvent,@@ -81,14 +85,18 @@ import {sendInstruction,} from './socket';import {+ addTabs,bindStoredSession,dropSession,ensureSessionForTab,+ focusTab,+ heirsOf,hostOf,patchSession,readTabSessions,releaseTab,remapTab,+ removeTab,sessionForRun,sessionForTab,siteUrlOf,@@ -110,6 +118,10 @@ const MAX_EXTERNAL_ITEMS = 100;const TAB_LOAD_WAIT_MS = 15_000;+const MAX_ROSTER = 20;++const MAX_ROSTER_TITLE = 120;+export type RunCommand =| { op: 'instruct'; text: string; tab: TabAnchor; agentSkillId?: string; focus?: FocusedElement; liveTools?: boolean }| { op: 'cancel'; sessionId: string }@@ -117,6 +129,8 @@ export type RunCommand =| { op: 'endSession'; sessionId: string }| { op: 'replay'; sessionId: string }| { op: 'restore'; sessionId: string; tab: TabAnchor }+ | { op: 'addTabs'; tabIds: number[]; tab: TabAnchor }+ | { op: 'removeTab'; sessionId: string; tabId: number }| { op: 'activateMap'; stagingId: string; exactHost?: boolean }| { op: 'discardMap'; stagingId: string }| { op: 'startRecording'; captureValues: boolean }@@ -300,6 +314,39 @@ function turnOver(tabId: number, items: readonly RunItem[]): void {for (const watch of settleWatchers) watch(tabId, items);}+/** The right-click menu's add, into a conversation already open on another tab. */+export function addTabsTo(sessionId: string, tabIds: number[]): Promise<void> {+ return serialized(() => gather(sessionId, tabIds));+}++/** Tabs the user put in a conversation: only web pages they have not blocked, and none another conversation is working in. */+async function gather(sessionId: string, tabIds: number[]): Promise<void> {+ const blocked = await siteCheck();+ const tabs = await Promise.all(tabIds.map((tabId) => browser.tabs.get(tabId).catch(() => null)));+ const usable = tabs.flatMap((tab) => (tab?.id != null && hostOf(tab.url) && !blocked(...tabUrls(tab)) ? [tab.id] : []));+ const outcome = await addTabs(sessionId, usable);+ if (!outcome) return;+ for (const absorbed of outcome.absorbed) {+ await fileAway(absorbed);+ if (absorbed.turns > 0) await append(sessionId, notice('info', `“${absorbed.title}” joined. Its own conversation is in History.`));+ }+ if (outcome.refused.length) {+ const count = outcome.refused.length;+ await append(sessionId, notice('info', `${count === 1 ? 'A tab' : `${count} tabs`} stayed where ${count === 1 ? 'it was' : 'they were'}: another conversation is working there.`));+ }+ await syncRunIndicator();+}++/** An idle conversation leaves the open tabs for History, as when another takes over its tab. */+async function fileAway(session: TabSession): Promise<void> {+ await persist(session.sessionId, session);+ await dropSession(session.sessionId);+ await dropTimersForSession(session.sessionId);+ await dropDiagnosticsForSession(session.sessionId);+ buffers.delete(session.sessionId);+ orphanDrafts(session.sessionId);+}+/** The orb's attach, answered once the file belongs to a conversation, or with why it cannot. */export function attachFile(file: NewFile, anchor: TabAnchor): Promise<Attached> {return serialized(() => attach(file, anchor));@@ -332,6 +379,18 @@ function handle(command: RunCommand): void {case 'restore':void serialized(() => restore(command.sessionId, command.tab));return;+ case 'addTabs':+ void serialized(async () => {+ const ensured = await ensureConversation(command.tab);+ if (ensured.ok) await gather(ensured.session.sessionId, command.tabIds);+ else broadcast({ op: 'event', runId: LOCAL_RUN, event: { kind: 'error', code: 'SESSION_LIMIT', message: ensured.message } });+ });+ return;+ case 'removeTab':+ void serialized(async () => {+ if ((await removeTab(command.sessionId, command.tabId)) === 'removed') await syncRunIndicator();+ });+ return;case 'activateMap':case 'discardMap': {const held = pendingDrafts.get(command.stagingId);@@ -583,7 +642,8 @@ async function instruct(return;}- const outcome = await startTurn(ensured.session, text, { agentSkillId, focus, liveTools, fastPath: true });+ const session = (await focusTab(sessionId, anchor)) ?? ensured.session;+ const outcome = await startTurn(session, text, { agentSkillId, focus, liveTools, fastPath: true });if (outcome === 'busy') {await append(sessionId,@@ -618,6 +678,7 @@ async function startTurn(const current = await browser.tabs.get(session.currentTabId).catch(() => null);const hidden = await siteBlocked(session.url, ...tabUrls(current), focus?.url);+ const tabs = daemonSpeaks(TABS_PROTOCOL) ? await rosterOf(session, current) : undefined;const runId = sendInstruction(text, {url: hidden ? undefined : siteUrlOf(session.url),tabId: session.currentTabId,@@ -631,6 +692,7 @@ async function startTurn(recordings: session.phone ? undefined : await attachedRecordings(),task,phone: await phoneContext(session),+ tabs,});if (!runId) {await append(@@ -651,6 +713,30 @@ async function startTurn(}}+/** The conversation's tabs as the agent may use them: this window's, in tab-strip order, with blocked sites left out entirely. */+async function rosterOf(session: TabSession, current: Browser.tabs.Tab | null): Promise<ConversationTab[] | undefined> {+ if (session.phone || session.tabIds.length < 2 || current?.windowId == null) return undefined;+ const blocked = await siteCheck();+ const tabs = (await browser.tabs.query({ windowId: current.windowId }))+ .filter((tab) => tab.id != null && session.tabIds.includes(tab.id) && !blocked(...tabUrls(tab)))+ .sort((a, b) => a.index - b.index);+ const roster: ConversationTab[] = [];+ for (const tab of tabs) {+ const host = hostOf(tab.url);+ const isCurrent = tab.id === session.currentTabId;+ if (!host && !isCurrent) continue;+ const { value: title } = await sealForPage((tab.title ?? '').replace(/\s+/g, ' ').trim().slice(0, MAX_ROSTER_TITLE), host);+ roster.push({+ tabId: tab.id!,+ title,+ ...(host ? { host } : {}),+ ...(isCurrent ? { current: true as const } : {}),+ ...(session.userTabIds.includes(tab.id!) ? { chosen: true as const } : {}),+ });+ }+ return roster.length > 1 ? roster.slice(0, MAX_ROSTER) : undefined;+}+async function handledLocally(text: string, session: TabSession): Promise<boolean> {try {return await tryFastPath(@@ -731,12 +817,7 @@ async function restore(sessionId: string, anchor: TabAnchor): Promise<void> {);return;}- if (owner) {- await persist(owner.sessionId);- await dropSession(owner.sessionId);- buffers.delete(owner.sessionId);- orphanDrafts(owner.sessionId);- }+ if (owner) await fileAway(owner);const meta = (await listSessions()).find((s) => s.id === sessionId);if (!meta) return;@@ -758,6 +839,7 @@ async function restore(sessionId: string, anchor: TabAnchor): Promise<void> {title: titleOf(meta) ?? anchored.title,},anchored,+ owner,);if (serial) await patchSession(sessionId, { phone: { serial } });broadcast({ op: 'items', sessionId, items: buffers.get(sessionId) ?? [] });@@ -820,10 +902,11 @@ async function persist(sessionId: string, known?: TabSession): Promise<void> {}export function serveTabSessions(): void {- browser.tabs.onRemoved.addListener((tabId) => {+ browser.tabs.onRemoved.addListener((tabId, removeInfo) => {forgetTab(tabId);void serialized(async () => {- const { closed } = await releaseTab(tabId);+ const { closed, handed, wasCurrent } = await releaseTab(tabId, await survivors(tabId, removeInfo));+ if (handed) await carryOn(handed, wasCurrent);if (!closed) return await syncRunIndicator();cancelAnalysesFor(await filesFor(closed.sessionId));if (closed.runId) {@@ -844,6 +927,31 @@ export function serveTabSessions(): void {});});+ /** The tabs that could carry a conversation on once its main tab closes: still open, and not going with their window. */+ async function survivors(tabId: number, removeInfo: { windowId: number; isWindowClosing: boolean }): Promise<number[]> {+ const session = await sessionForTab(tabId);+ if (session?.mainTabId !== tabId) return [];+ const open = await Promise.all(heirsOf(session, tabId).map((id) => browser.tabs.get(id).catch(() => null)));+ return open.flatMap((tab) =>+ tab?.id != null && !(removeInfo.isWindowClosing && tab.windowId === removeInfo.windowId) ? [tab.id] : [],+ );+ }++ /** Its first tab went, so the conversation lives on in another of the user's tabs and takes that tab's name. */+ async function carryOn(session: TabSession, wasCurrent: boolean): Promise<void> {+ const tab = await browser.tabs.get(session.mainTabId).catch(() => null);+ await patchSession(session.sessionId, {+ ...(tab?.title ? { title: tab.title } : {}),+ ...(tab?.windowId != null ? { windowId: tab.windowId } : {}),+ ...(wasCurrent && tab?.url ? { url: tab.url, host: hostOf(tab.url) } : {}),+ });+ if (session.runId && wasCurrent) {+ await stopRun(session.sessionId);+ await append(session.sessionId, notice('error', 'CANCELLED: The tab it was working in was closed, so that run is over.'));+ }+ await append(session.sessionId, notice('info', `The tab it began on was closed. It carries on in “${tab?.title ?? session.title}”.`));+ }+onPhoneClosed(() => {void serialized(async () => {for (const session of Object.values(await readTabSessions())) {@@ -908,7 +1016,7 @@ async function openTaskSession(order: TaskOrder): Promise<ActionResult<{ sessionstartedAt: Date.now(),...(order.previous ? { previous: order.previous } : {}),};- await patchSession(ensured.session.sessionId, { task });+ await patchSession(ensured.session.sessionId, { task, userTabIds: [], openedTabIds: [tab.id] });return success({ sessionId: ensured.session.sessionId, tabId: tab.id });}@@ -1045,12 +1153,12 @@ async function finishTask(session: TabSession, verdict: TaskVerdict): Promise<voawait persist(session.sessionId);void announceTask(task, result, session.currentTabId);if (task.keepTab) await patchSession(session.sessionId, { task: undefined });- else await browser.tabs.remove(session.tabIds).catch(() => undefined);+ else await browser.tabs.remove(session.openedTabIds).catch(() => undefined);}async function abandonTask(session: TabSession): Promise<void> {if (session.task) await patchSession(session.sessionId, { task: { ...session.task, done: true } });- await browser.tabs.remove(session.tabIds).catch(() => undefined);+ await browser.tabs.remove(session.openedTabIds).catch(() => undefined);}function reportAbandoned(session: TabSession, reason: string): void {diff --git a/src/lib/bridge/tab-sessions.test.ts b/src/lib/bridge/tab-sessions.test.tsindex 174a1ee..2bda685 100644--- a/src/lib/bridge/tab-sessions.test.ts+++ b/src/lib/bridge/tab-sessions.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, test } from 'vitest';+import { beforeEach, describe, expect, test, vi } from 'vitest';import { fakeBrowser } from 'wxt/testing';import { ensureSessionForTab, hostOf, siteUrlOf } from './tab-sessions';@@ -31,3 +31,170 @@ describe('a conversation on a site', () => {expect(hostOf('file:///Users/you/notes.html')).toBeUndefined();});});++/** A fresh registry: the module caches what it read, and that cache outlives fakeBrowser.reset(). */+async function registry() {+ vi.resetModules();+ return import('./tab-sessions');+}++async function begun(tabId: number, title = `Tab ${tabId}`) {+ const sessions = await registry();+ const ensured = await sessions.ensureSessionForTab({ tabId, windowId: 1, url: `https://site${tabId}.example/`, title });+ if (!ensured.ok) throw new Error(ensured.message);+ return { ...sessions, session: ensured.session };+}++const lists = (session: { mainTabId: number; currentTabId: number; tabIds: number[]; userTabIds: number[]; openedTabIds: number[] } | null | undefined) =>+ session && {+ main: session.mainTabId,+ current: session.currentTabId,+ tabs: session.tabIds,+ user: session.userTabIds,+ opened: session.openedTabIds,+ };++describe('a conversation the user spread across tabs', () => {+ test('keeps its name from the tab it began on, and its address from the tab it is working in', async () => {+ const { ensureSessionForTab, addTabs, session } = await begun(1, 'Board');+ await addTabs(session.sessionId, [2]);+ const again = await ensureSessionForTab({ tabId: 2, url: 'https://site2.example/ticket', title: 'Ticket' });+ expect(again.ok && [again.session.title, again.session.url]).toEqual(['Board', 'https://site1.example/']);+ });++ test('works in the tab the user sent from', async () => {+ const { addTabs, focusTab, session } = await begun(1);+ await addTabs(session.sessionId, [2]);+ const focused = await focusTab(session.sessionId, { tabId: 2, url: 'https://site2.example/t' });+ expect([focused?.currentTabId, focused?.host]).toEqual([2, 'site2.example']);+ });++ test('never moves a run that is going, nor onto a tab that is not its own', async () => {+ const { addTabs, focusTab, patchSession, session } = await begun(1);+ await addTabs(session.sessionId, [2]);+ expect((await focusTab(session.sessionId, { tabId: 9 }))?.currentTabId).toBe(1);+ await patchSession(session.sessionId, { runId: 'r1' });+ expect((await focusTab(session.sessionId, { tabId: 2 }))?.currentTabId).toBe(1);+ });++ test('takes a tab the agent reached as one the user chose', async () => {+ const { adoptSubtab, addTabs, readTabSessions, session } = await begun(1);+ await adoptSubtab(session.sessionId, 2, { activate: false, opened: true });+ const outcome = await addTabs(session.sessionId, [2, 3]);+ expect([outcome?.added, lists((await readTabSessions())[session.sessionId])]).toEqual([+ [2, 3],+ { main: 1, current: 1, tabs: [1, 2, 3], user: [1, 2, 3], opened: [] },+ ]);+ });++ test('moves a tab out of an idle conversation, and hands one left with nothing back to be filed away', async () => {+ const { ensureSessionForTab, addTabs, readTabSessions, session } = await begun(1);+ const other = await ensureSessionForTab({ tabId: 2, title: 'Other' });+ const outcome = await addTabs(session.sessionId, [2]);+ const map = await readTabSessions();+ expect([outcome?.absorbed.map((s) => s.title), Object.keys(map)]).toEqual([['Other'], [session.sessionId]]);+ expect(other.ok).toBe(true);+ });++ test('leaves alone a tab another conversation is working in', async () => {+ const { ensureSessionForTab, addTabs, patchSession, session } = await begun(1);+ const other = await ensureSessionForTab({ tabId: 2 });+ if (other.ok) await patchSession(other.session.sessionId, { runId: 'busy' });+ expect((await addTabs(session.sessionId, [2]))?.refused).toEqual([{ tabId: 2, reason: 'running' }]);+ });++ test('is never put on the phone', async () => {+ const { addTabs, patchSession, session } = await begun(1);+ await patchSession(session.sessionId, { phone: { serial: 'emulator-5554' } });+ expect(await addTabs(session.sessionId, [2])).toBeNull();+ });+});++describe('taking a tab out', () => {+ test('hands the conversation to another of its tabs when it was the first', async () => {+ const { addTabs, removeTab, readTabSessions, session } = await begun(1);+ await addTabs(session.sessionId, [2]);+ expect(await removeTab(session.sessionId, 1)).toBe('removed');+ expect(lists((await readTabSessions())[session.sessionId])).toEqual({ main: 2, current: 2, tabs: [2], user: [2], opened: [] });+ });++ 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');+ await addTabs(session.sessionId, [2]);+ await patchSession(session.sessionId, { runId: 'r1' });+ expect(await removeTab(session.sessionId, 2)).toBe('running');+ });+});++describe('closing a tab', () => {+ test('of a tab beside the first only shrinks the conversation, and the agent goes back to the first', async () => {+ const { addTabs, focusTab, releaseTab, session } = await begun(1);+ await addTabs(session.sessionId, [2]);+ await focusTab(session.sessionId, { tabId: 2 });+ const released = await releaseTab(2);+ expect([released.shrunk?.currentTabId, released.wasCurrent, released.closed, released.handed]).toEqual([1, true, null, null]);+ });++ test('the conversation began in hands it to the user’s next open tab', async () => {+ const { addTabs, adoptSubtab, releaseTab, session } = await begun(1);+ await adoptSubtab(session.sessionId, 2, { activate: false, opened: true });+ await addTabs(session.sessionId, [3]);+ const released = await releaseTab(1, [2, 3]);+ expect(lists(released.handed)).toEqual({ main: 3, current: 3, tabs: [2, 3], user: [3], opened: [2] });+ });++ 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 });+ const released = await releaseTab(1, [2]);+ expect([released.closed?.sessionId, Object.keys(await readTabSessions())]).toEqual([session.sessionId, []]);+ });++ test('with no heir still open ends it', async () => {+ const { addTabs, releaseTab, session } = await begun(1);+ await addTabs(session.sessionId, [3]);+ expect((await releaseTab(1, [])).closed?.sessionId).toBe(session.sessionId);+ });++ test('that a scheduled task began in ends it, whatever else it holds', async () => {+ const { addTabs, patchSession, releaseTab, session } = await begun(1);+ await addTabs(session.sessionId, [3]);+ await patchSession(session.sessionId, {+ task: { id: 't', runId: 'r', name: 'Check', keepTab: false, notify: 'always', startedAt: 0 },+ });+ expect((await releaseTab(1, [3])).closed?.sessionId).toBe(session.sessionId);+ });+});++describe('heirsOf', () => {+ test('puts the tab the agent is on first when the user chose it, then the user’s tabs, then the rest it reached', async () => {+ const { adoptSubtab, addTabs, focusTab, heirsOf, readTabSessions, session } = await begun(1);+ await addTabs(session.sessionId, [4, 5]);+ await adoptSubtab(session.sessionId, 6, { activate: false, opened: false });+ await adoptSubtab(session.sessionId, 7, { activate: false, opened: true });+ await focusTab(session.sessionId, { tabId: 5 });+ expect(heirsOf((await readTabSessions())[session.sessionId], 1)).toEqual([5, 4, 6]);+ });+});++describe('a conversation from History', () => {+ test('takes over the tabs of the idle one it replaces', async () => {+ const { addTabs, adoptSubtab, bindStoredSession, readTabSessions, session } = await begun(1);+ await addTabs(session.sessionId, [2]);+ await adoptSubtab(session.sessionId, 3, { activate: false, opened: true });+ const replaced = (await readTabSessions())[session.sessionId];+ const restored = await bindStoredSession({ sessionId: 'old', turns: 4 }, { tabId: 1 }, replaced);+ expect([lists(restored), Object.keys(await readTabSessions())]).toEqual([+ { main: 1, current: 1, tabs: [1, 2, 3], user: [1, 2], opened: [3] },+ ['old'],+ ]);+ });+});++test('a replaced tab keeps its place in every list', async () => {+ const { addTabs, readTabSessions, remapTab, session } = await begun(1);+ await addTabs(session.sessionId, [2]);+ await remapTab(2, 20);+ expect(lists((await readTabSessions())[session.sessionId])).toEqual({ main: 1, current: 1, tabs: [1, 20], user: [1, 20], opened: [] });+});diff --git a/src/lib/bridge/tab-sessions.ts b/src/lib/bridge/tab-sessions.tsindex ebf95db..c9e8510 100644--- a/src/lib/bridge/tab-sessions.ts+++ b/src/lib/bridge/tab-sessions.ts@@ -29,8 +29,12 @@ export interface TaskTag {export interface TabSession {sessionId: string;mainTabId: number;- /** The main tab plus every tab this session's runs opened. */+ /** Every tab the conversation spans: the main tab, the tabs the user put in it, and the tabs its runs reached. */tabIds: number[];+ /** The tabs the user put here themselves: the one it began on and every one they added. */+ userTabIds: number[];+ /** The tabs its runs or its task opened, the only ones a finished task closes. */+ openedTabIds: number[];/** Where this session's next untargeted action lands. */currentTabId: number;windowId: number;@@ -106,11 +110,11 @@ export async function ensureSessionForTab(anchor: TabAnchor): Promise<Ensured> {const existing = Object.values(map).find((session) => session.tabIds.includes(anchor.tabId));if (existing) {existing.lastActivityAt = Date.now();- if (anchor.url) {+ if (anchor.url && anchor.tabId === existing.currentTabId) {existing.url = anchor.url;existing.host = hostOf(anchor.url) ?? existing.host;}- if (anchor.title) existing.title = anchor.title;+ if (anchor.title && anchor.tabId === existing.mainTabId) existing.title = anchor.title;return { ok: true, session: existing } as Ensured;}if (Object.keys(map).length >= MAX_ACTIVE_SESSIONS) {@@ -124,6 +128,8 @@ export async function ensureSessionForTab(anchor: TabAnchor): Promise<Ensured> {sessionId: crypto.randomUUID(),mainTabId: anchor.tabId,tabIds: [anchor.tabId],+ userTabIds: [anchor.tabId],+ openedTabIds: [],currentTabId: anchor.tabId,windowId: anchor.windowId ?? -1,title: anchor.title ?? hostOf(anchor.url) ?? 'This tab',@@ -139,6 +145,10 @@ export async function ensureSessionForTab(anchor: TabAnchor): Promise<Ensured> {});}+/**+ * A conversation from History, back on the tab the user opened it on. It takes over the tabs of the+ * idle conversation it replaces there, so tabs the user gathered stay together.+ */export function bindStoredSession(fields: {sessionId: string;@@ -150,16 +160,21 @@ export function bindStoredSession(title?: string;},anchor: TabAnchor,+ replaced?: Pick<TabSession, 'tabIds' | 'userTabIds' | 'openedTabIds'> | null,): Promise<TabSession> {return mutateTabSessions((map) => {for (const [id, session] of Object.entries(map)) {if (session.tabIds.includes(anchor.tabId) && !session.runId) delete map[id];}+ const held = new Set(Object.values(map).flatMap((session) => session.tabIds));+ const inherited = (replaced?.tabIds ?? []).filter((tabId) => tabId !== anchor.tabId && !held.has(tabId));const now = Date.now();const session: TabSession = {sessionId: fields.sessionId,mainTabId: anchor.tabId,- tabIds: [anchor.tabId],+ tabIds: [anchor.tabId, ...inherited],+ userTabIds: [anchor.tabId, ...inherited.filter((tabId) => replaced?.userTabIds.includes(tabId))],+ openedTabIds: inherited.filter((tabId) => replaced?.openedTabIds.includes(tabId)),currentTabId: anchor.tabId,windowId: anchor.windowId ?? -1,title: fields.title ?? anchor.title ?? hostOf(fields.url) ?? 'This tab',@@ -178,20 +193,137 @@ export function bindStoredSession(});}-export function adoptSubtab(sessionId: string, tabId: number, activate: boolean): Promise<void> {+/** A tab one of the conversation's runs reached: `opened` when the run opened it, which makes it one a finished task closes. */+export function adoptSubtab(sessionId: string, tabId: number, { activate, opened }: { activate: boolean; opened: boolean }): Promise<void> {return mutateTabSessions((map) => {const session = map[sessionId];if (!session) return;for (const other of Object.values(map)) {- if (other.sessionId === sessionId) continue;- other.tabIds = other.tabIds.filter((id) => id !== tabId);+ if (other.sessionId !== sessionId && other.tabIds.includes(tabId)) leave(other, tabId, []);}if (!session.tabIds.includes(tabId)) session.tabIds.push(tabId);+ if (opened && !session.openedTabIds.includes(tabId)) session.openedTabIds.push(tabId);if (activate) session.currentTabId = tabId;session.lastActivityAt = Date.now();});}+/** When the user sends from one of the conversation's tabs, that tab is the one they mean. Never while a run is going. */+export function focusTab(sessionId: string, anchor: TabAnchor): Promise<TabSession | null> {+ return mutateTabSessions((map) => {+ const session = map[sessionId];+ if (!session || session.runId || session.currentTabId === anchor.tabId || !session.tabIds.includes(anchor.tabId)) {+ return session ?? null;+ }+ session.currentTabId = anchor.tabId;+ if (anchor.url) {+ session.url = anchor.url;+ session.host = hostOf(anchor.url);+ }+ return session;+ });+}++export type AddRefusal = 'running' | 'phone' | 'task';++export interface TabsAdded {+ added: number[];+ refused: { tabId: number; reason: AddRefusal }[];+ /** Conversations left with no tab once theirs moved here, to be filed to History. */+ absorbed: TabSession[];+}++/**+ * Tabs the user put in a conversation. A tab another idle conversation holds moves here, and that+ * conversation keeps its other tabs or, left with none, is handed back to be filed away.+ */+export function addTabs(sessionId: string, tabIds: readonly number[]): Promise<TabsAdded | null> {+ return mutateTabSessions((map) => {+ const session = map[sessionId];+ if (!session || session.phone) return null;+ const outcome: TabsAdded = { added: [], refused: [], absorbed: [] };+ for (const tabId of new Set(tabIds)) {+ const holder = Object.values(map).find((other) => other.tabIds.includes(tabId));+ if (holder && holder !== session) {+ const reason = refusalOf(holder);+ if (reason) {+ outcome.refused.push({ tabId, reason });+ continue;+ }+ if (holder.tabIds.length === 1) {+ delete map[holder.sessionId];+ outcome.absorbed.push(holder);+ } else {+ leave(holder, tabId, fallbacksOf(holder, tabId));+ }+ }+ if (!session.tabIds.includes(tabId)) session.tabIds.push(tabId);+ if (!session.userTabIds.includes(tabId)) {+ session.userTabIds.push(tabId);+ outcome.added.push(tabId);+ }+ session.openedTabIds = session.openedTabIds.filter((id) => id !== tabId);+ }+ if (outcome.added.length) session.lastActivityAt = Date.now();+ return outcome;+ });+}++export type TabRemoval = 'removed' | 'running' | 'last' | 'missing';++/** The user took a tab out of a conversation. The tab stays open, with no conversation of its own. */+export function removeTab(sessionId: string, tabId: number): Promise<TabRemoval> {+ return mutateTabSessions((map) => {+ const session = map[sessionId];+ if (!session?.tabIds.includes(tabId)) return 'missing';+ if (session.runId) return 'running';+ if (session.tabIds.length === 1) return 'last';+ leave(session, tabId, fallbacksOf(session, tabId));+ session.lastActivityAt = Date.now();+ return 'removed';+ });+}++function refusalOf(session: TabSession): AddRefusal | null {+ if (session.runId) return 'running';+ if (session.phone) return 'phone';+ return session.task ? 'task' : null;+}++/**+ * Who carries the conversation on when its main tab goes: the tab the agent was on if the user put it+ * there, then the user's other tabs, then any tab the runs reached but did not open themselves.+ */+export function heirsOf(session: TabSession, leaving: number): number[] {+ const chosen = session.userTabIds.includes(session.currentTabId) ? [session.currentTabId] : [];+ const reached = session.tabIds.filter((tabId) => !session.openedTabIds.includes(tabId));+ return [...new Set([...chosen, ...session.userTabIds, ...reached])].filter(+ (tabId) => tabId !== leaving && session.tabIds.includes(tabId),+ );+}++/** Taking a tab out by hand leaves the conversation somewhere to be, its runs' own tabs included. */+const fallbacksOf = (session: TabSession, leaving: number): number[] => [+ ...heirsOf(session, leaving),+ ...session.tabIds.filter((tabId) => tabId !== leaving),+];++/** Takes a tab out of a conversation. False when the main tab left and none of `heirs` could take its place. */+function leave(session: TabSession, tabId: number, heirs: readonly number[]): boolean {+ const drop = (ids: number[]) => ids.filter((id) => id !== tabId);+ session.tabIds = drop(session.tabIds);+ session.userTabIds = drop(session.userTabIds);+ session.openedTabIds = drop(session.openedTabIds);+ if (session.mainTabId === tabId) {+ 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;+}+export function setCurrentTab(sessionId: string, tabId: number): Promise<void> {return mutateTabSessions((map) => {const session = map[sessionId];@@ -217,19 +349,35 @@ export function dropSession(sessionId: string): Promise<TabSession | null> {});}-export function releaseTab(tabId: number): Promise<{ closed: TabSession | null; shrunk: TabSession | null }> {+export interface Released {+ /** The conversation ended with its tab. */+ closed: TabSession | null;+ /** It lost one of its other tabs. */+ shrunk: TabSession | null;+ /** Its main tab went and another of the user's tabs carries it on. */+ handed: TabSession | null;+ /** The tab was the one the agent was working in. */+ wasCurrent: boolean;+}++/**+ * A closed tab leaves its conversation. When it was the main tab, the first of `alive` that is one of+ * its heirs takes over; with none, or for a task's or the phone's conversation, the conversation ends.+ */+export function releaseTab(tabId: number, alive: readonly number[] = []): Promise<Released> {return mutateTabSessions((map) => {for (const session of Object.values(map)) {if (!session.tabIds.includes(tabId)) continue;- if (session.mainTabId === tabId) {+ const wasCurrent = session.currentTabId === tabId;+ const main = session.mainTabId === tabId;+ const heirs = session.task || session.phone ? [] : heirsOf(session, tabId).filter((id) => alive.includes(id));+ if (!leave(session, tabId, heirs)) {delete map[session.sessionId];- return { closed: session, shrunk: null };+ return { closed: session, shrunk: null, handed: null, wasCurrent };}- session.tabIds = session.tabIds.filter((id) => id !== tabId);- if (session.currentTabId === tabId) session.currentTabId = session.mainTabId;- return { closed: null, shrunk: session };+ return { closed: null, shrunk: main ? null : session, handed: main ? session : null, wasCurrent };}- return { closed: null, shrunk: null };+ return { closed: null, shrunk: null, handed: null, wasCurrent: false };});}@@ -237,7 +385,10 @@ export function remapTab(from: number, to: number): Promise<void> {return mutateTabSessions((map) => {for (const session of Object.values(map)) {if (!session.tabIds.includes(from)) continue;- session.tabIds = session.tabIds.map((id) => (id === from ? to : id));+ const swap = (ids: number[]) => ids.map((id) => (id === from ? to : id));+ session.tabIds = swap(session.tabIds);+ session.userTabIds = swap(session.userTabIds);+ session.openedTabIds = swap(session.openedTabIds);if (session.mainTabId === from) session.mainTabId = to;if (session.currentTabId === from) session.currentTabId = to;}