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.

feat(sessions): give every tab its own conversation, running side by side

Shahriar6c00d6cc7c71
diff --git a/entrypoints/background.ts b/entrypoints/background.ts
index 86df88d..50e0b1e 100644
--- a/entrypoints/background.ts
+++ b/entrypoints/background.ts
@@ -9,7 +9,7 @@ import { nameStoredSession } from '@/lib/bridge/session-store';
import { analyzeStoredRecording, resumePendingAnalyses } from '@/lib/bridge/recording-store';
import { ingestSample, monitorsForTab, serveMonitor } from '@/lib/bridge/monitor';
import { appendEvents, recordingStateFor, serveRecorder } from '@/lib/bridge/recorder';
-import { serveRunPorts } from '@/lib/bridge/run-port';
+import { serveRunPorts, serveTabSessions } from '@/lib/bridge/run-port';
import { openSidePanel } from '@/lib/bridge/side-panel';
import { isAgentKind } from '@/lib/agents/catalog';
import {
@@ -150,6 +150,7 @@ export default defineBackground(() => {
serveRecorder();
serveMonitor();
serveRunPorts();
+ serveTabSessions();
onWelcome(() => {
void resyncSkills();
diff --git a/entrypoints/sidepanel/App.tsx b/entrypoints/sidepanel/App.tsx
index d33bfb5..3dcf3c2 100644
--- a/entrypoints/sidepanel/App.tsx
+++ b/entrypoints/sidepanel/App.tsx
@@ -38,7 +38,7 @@ const PINNED_SLACK_PX = 56;
export default function App() {
const daemon = useDaemonState();
- const run = useRun({ persist: true });
+ const run = useRun();
const [voiceEnabled, setVoiceEnabled] = useVoiceEnabled();
const files = useStoredFiles();
const sessions = useStoredSessions();
@@ -157,7 +157,8 @@ export default function App() {
setVoiceEnabled(false);
}
- const offChatRun = run.running && tab !== 'chat';
+ const runningCount = run.sessions.filter((session) => session.runId).length;
+ const offChatRun = runningCount > 0 && tab !== 'chat';
const hasBanners = offChatRun || !!run.recording || run.monitors.length > 0 || !!run.draft;
return (
@@ -202,7 +203,9 @@ export default function App() {
className="enters mb-2 flex w-full items-center gap-2 rounded-xl border border-brand/35 bg-brand/8 px-2.5 py-2 text-left transition-colors hover:bg-brand/12"
>
<span className="glow-dot size-1.5 shrink-0 animate-pulse rounded-full bg-brand text-brand" />
- <span className="flex-1 text-xs text-ink">A run is in progress</span>
+ <span className="flex-1 text-xs text-ink">
+ {runningCount === 1 ? 'A run is in progress' : `${runningCount} runs are in progress`}
+ </span>
<span className="shrink-0 font-mono text-[10px] tracking-[0.12em] text-brand uppercase">Watch</span>
</button>
)}
@@ -231,7 +234,7 @@ export default function App() {
) : tab === 'history' ? (
<SessionList
sessions={sessions}
- currentId={run.sessionId}
+ currentId={run.sessionId ?? undefined}
busy={run.running}
onOpen={openSession}
onRemove={(id) => void removeSession(id)}
diff --git a/lib/bridge/run-port.ts b/lib/bridge/run-port.ts
index 5a3af13..7389290 100644
--- a/lib/bridge/run-port.ts
+++ b/lib/bridge/run-port.ts
@@ -2,15 +2,16 @@ import { browser, type Browser } from 'wxt/browser';
import {
EXTERNAL_RUN_ID,
type AttachedFile,
- type RunContext,
type RunEvent,
type SavedRecording,
} from '@/lib/actions/protocol';
import type { MonitorState } from '@/lib/monitor/events';
import type { RecordingState } from '@/lib/recordings/events';
import type { SiteMapDraft } from '@/lib/skills/site-map';
+import { navigate } from '@/lib/actions/page/navigate';
import { tryFastPath } from './fast-path';
import { listMeta } from './file-store';
+import { invokeForHarness } from './invoke';
import {
acknowledgeCompleted,
activeMonitorStates,
@@ -20,7 +21,17 @@ import {
} from './monitor';
import { currentRecording, onRecordingState, startActiveTabRecording, stopRecording } from './recorder';
import { asSavedRecording, listRecordings } from './recording-store';
+import { forgetTab, syncRunIndicator } from './run-indicator';
+import { attachPreview, monitorNotice, notice, patchTool, reduce, type RunItem } from './run-items';
import { onScreenshotPreview, type ScreenshotPreview } from './screenshot-preview';
+import {
+ listSessions,
+ nameStoredSession,
+ putSession,
+ readTranscript,
+ titleDueAt,
+ type StoredSessionMeta,
+} from './session-store';
import { recordGeneratedSkill } from './skill-store';
import {
activateSiteMap,
@@ -33,20 +44,38 @@ import {
sendDecision,
sendInstruction,
} from './socket';
+import {
+ bindStoredSession,
+ dropSession,
+ ensureSessionForTab,
+ hostOf,
+ patchSession,
+ readTabSessions,
+ releaseTab,
+ remapTab,
+ sessionForRun,
+ sessionForTab,
+ type TabAnchor,
+ type TabSession,
+} from './tab-sessions';
export const RUN_PORT = 'browsentic/run';
const LOCAL_RUN = 'local';
-const UNWATCHED_GRACE_MS = 10_000;
-
const CANCEL_CONFIRM_MS = 4_000;
+const PERSIST_DEBOUNCE_MS = 800;
+
+const MAX_EXTERNAL_ITEMS = 100;
+
export type RunCommand =
- | { op: 'instruct'; text: string; context?: RunContext }
- | { op: 'cancel' }
- | { op: 'decision'; toolId: string; allow: boolean; remember?: boolean }
- | { op: 'reset' }
+ | { op: 'instruct'; text: string; tab: TabAnchor }
+ | { op: 'cancel'; sessionId: string }
+ | { op: 'decision'; sessionId: string; toolId: string; allow: boolean; remember?: boolean }
+ | { op: 'endSession'; sessionId: string }
+ | { op: 'replay'; sessionId: string }
+ | { op: 'restore'; sessionId: string; tab: TabAnchor }
| { op: 'activateMap'; stagingId: string; exactHost?: boolean }
| { op: 'discardMap'; stagingId: string }
| { op: 'startRecording'; captureValues: boolean }
@@ -54,34 +83,55 @@ export type RunCommand =
| { op: 'stopMonitor'; monitorId: string };
export type RunMessage =
- | { op: 'event'; runId: string; event: RunEvent }
- | { op: 'active'; runId: string | null }
+ | { op: 'event'; sessionId?: string; runId: string; event: RunEvent }
+ | { op: 'item'; sessionId?: string; item: RunItem }
+ | { op: 'items'; sessionId?: string; items: RunItem[] }
| { op: 'mapDraft'; draft: SiteMapDraft }
| { op: 'mapSettled'; stagingId: string; ok: boolean; message?: string }
| { op: 'recording'; state: RecordingState | null }
- | { op: 'preview'; preview: ScreenshotPreview }
+ | { op: 'preview'; sessionId?: string; preview: ScreenshotPreview }
| { op: 'monitor'; state: MonitorState };
const ports = new Set<Browser.runtime.Port>();
-let activeRunId: string | null = null;
-let actingLocally = false;
-let unwatchedTimer: ReturnType<typeof setTimeout> | undefined;
-let cancelTimer: ReturnType<typeof setTimeout> | undefined;
+const buffers = new Map<string, RunItem[]>();
+const busy = new Set<string>();
+const persistTimers = new Map<string, ReturnType<typeof setTimeout>>();
+const cancelTimers = new Map<string, ReturnType<typeof setTimeout>>();
+let externalItems: RunItem[] = [];
let pendingDraft: SiteMapDraft | null = null;
+let queue: Promise<unknown> = Promise.resolve();
+
+function serialized<T>(task: () => Promise<T>): Promise<T> {
+ const run = queue.then(task, task);
+ queue = run.catch(() => undefined);
+ return run;
+}
export function serveRunPorts(): void {
onRunEvent((runId, event) => {
- if (runId === EXTERNAL_RUN_ID) return broadcast({ op: 'event', runId, event });
- const ends = event.kind === 'done' || event.kind === 'error';
- if (ends && (activeRunId === null || activeRunId === runId)) setActiveRun(null);
- broadcast({ op: 'event', runId, event });
+ void serialized(() => absorb(runId, event));
});
- onScreenshotPreview((preview) => broadcast({ op: 'preview', preview }));
+ onScreenshotPreview((preview, runId) => {
+ void serialized(async () => {
+ const session = runId ? await sessionForRun(runId) : null;
+ if (session) {
+ const items = attachPreview(await bufferFor(session.sessionId), preview);
+ buffers.set(session.sessionId, items);
+ }
+ broadcast({ op: 'preview', sessionId: session?.sessionId, preview });
+ });
+ });
onMonitorState((state) => {
broadcast({ op: 'monitor', state });
- if (state.phase !== 'watching' && ports.size > 0) void acknowledgeCompleted(state.monitorId);
+ if (state.phase !== 'watching') {
+ void serialized(async () => {
+ const session = state.tabId != null ? await sessionForTab(state.tabId) : null;
+ if (session) await append(session.sessionId, notice(...noticeOf(state)));
+ });
+ if (ports.size > 0) void acknowledgeCompleted(state.monitorId);
+ }
});
onSiteMapDraft((_runId, draft) => {
@@ -90,7 +140,12 @@ export function serveRunPorts(): void {
});
onWelcome(() => {
- if (activeRunId) endRun('The connection to the daemon dropped, so that run is over.');
+ void serialized(async () => {
+ for (const session of Object.values(await readTabSessions())) {
+ if (!session.runId) continue;
+ await endRun(session.sessionId, 'The connection to the daemon dropped, so that run is over.');
+ }
+ });
});
onRecordingState((state) => {
@@ -107,8 +162,6 @@ export function serveRunPorts(): void {
browser.runtime.onConnect.addListener((port) => {
if (port.name !== RUN_PORT) return;
ports.add(port);
- clearTimeout(unwatchedTimer);
- post(port, { op: 'active', runId: activeRunId });
if (pendingDraft) post(port, { op: 'mapDraft', draft: pendingDraft });
void currentRecording().then((state) => post(port, { op: 'recording', state }));
void activeMonitorStates().then((states) => {
@@ -121,36 +174,37 @@ export function serveRunPorts(): void {
});
port.onMessage.addListener((message) => handle(message as RunCommand));
- port.onDisconnect.addListener(() => {
- ports.delete(port);
- if (ports.size === 0 && activeRunId) scheduleUnwatchedCancel();
- });
+ port.onDisconnect.addListener(() => ports.delete(port));
});
}
function handle(command: RunCommand): void {
switch (command.op) {
case 'instruct':
- if (activeRunId || actingLocally) {
- broadcast({
- op: 'event',
- runId: LOCAL_RUN,
- event: {
- kind: 'error',
- code: 'RUN_IN_PROGRESS',
- message: 'Something is already running — stop it before sending another instruction.',
- },
- });
- broadcast({ op: 'active', runId: activeRunId ?? LOCAL_RUN });
- return;
- }
- void instruct(command.text, command.context);
+ void serialized(() => instruct(command.text, command.tab));
return;
case 'cancel':
- stopRun();
+ void serialized(() => stopRun(command.sessionId));
return;
case 'decision':
- if (activeRunId) sendDecision(activeRunId, command.toolId, command.allow, command.remember);
+ void serialized(async () => {
+ const session = (await readTabSessions())[command.sessionId];
+ if (!session?.runId) return;
+ buffers.set(command.sessionId, patchTool(await bufferFor(command.sessionId), command.toolId, { awaiting: false }));
+ await patchSession(command.sessionId, { pendingApproval: undefined });
+ sendDecision(session.runId, command.toolId, command.allow, command.remember);
+ });
+ return;
+ case 'endSession':
+ void serialized(() => endSession(command.sessionId));
+ return;
+ case 'replay':
+ void serialized(async () => {
+ broadcast({ op: 'items', sessionId: command.sessionId, items: await bufferFor(command.sessionId) });
+ });
+ return;
+ case 'restore':
+ void serialized(() => restore(command.sessionId, command.tab));
return;
case 'activateMap':
case 'discardMap': {
@@ -188,82 +242,306 @@ function handle(command: RunCommand): void {
case 'stopMonitor':
void stopTabMonitor(command.monitorId);
return;
- case 'reset':
- resetConversation();
- return;
}
}
-async function beginRecording(captureValues: boolean): Promise<void> {
- const result = await startActiveTabRecording(captureValues);
- if (result.ok) return;
- broadcast({
- op: 'event',
- runId: LOCAL_RUN,
- event: { kind: 'error', code: result.error.code, message: result.error.message },
- });
+async function absorb(runId: string, event: RunEvent): Promise<void> {
+ if (runId === EXTERNAL_RUN_ID) {
+ externalItems = reduce(externalItems, event).slice(-MAX_EXTERNAL_ITEMS);
+ broadcast({ op: 'event', runId, event });
+ return;
+ }
+
+ const session = await sessionForRun(runId);
+ if (!session) return;
+ const { sessionId } = session;
+
+ buffers.set(sessionId, reduce(await bufferFor(sessionId), event));
+ broadcast({ op: 'event', sessionId, runId, event });
+
+ if (event.kind === 'session') {
+ await patchSession(sessionId, { agent: event.agent, agentSessionId: event.agentSessionId ?? undefined });
+ } else if (event.kind === 'approval') {
+ await patchSession(sessionId, {
+ pendingApproval: { toolId: event.toolId, action: event.action, input: event.input, site: event.site },
+ });
+ } else if (event.kind === 'toolResult') {
+ await patchSession(sessionId, { pendingApproval: undefined });
+ }
+
+ if (event.kind === 'done' || event.kind === 'error') await settle(sessionId);
+ else schedulePersist(sessionId);
}
-async function instruct(text: string, context?: RunContext): Promise<void> {
- actingLocally = true;
+async function settle(sessionId: string): Promise<void> {
+ clearTimeout(cancelTimers.get(sessionId));
+ cancelTimers.delete(sessionId);
+ await patchSession(sessionId, { runId: null, pendingApproval: undefined });
+ await syncRunIndicator();
+
+ const session = (await readTabSessions())[sessionId];
+ if (session) {
+ const tab = await browser.tabs.get(session.currentTabId).catch(() => null);
+ if (tab?.url) await patchSession(sessionId, { url: tab.url, host: hostOf(tab.url) });
+ }
+ await persist(sessionId);
+
+ const stored = (await listSessions()).find((s) => s.id === sessionId);
+ if (!stored || titleDueAt(stored.turns, stored.titledAtTurn) === null) return;
+ await nameStoredSession(sessionId).catch(() => undefined);
+}
+
+async function instruct(text: string, anchor: TabAnchor): Promise<void> {
+ const ensured = await ensureSessionForTab(anchor);
+ if (!ensured.ok) {
+ broadcast({
+ op: 'event',
+ runId: LOCAL_RUN,
+ event: { kind: 'error', code: 'SESSION_LIMIT', message: ensured.message },
+ });
+ return;
+ }
+ const session = ensured.session;
+ const { sessionId } = session;
+
+ if (session.runId || busy.has(sessionId)) {
+ await append(
+ sessionId,
+ notice('error', 'RUN_IN_PROGRESS: This conversation is still running — stop it before sending another instruction.'),
+ );
+ return;
+ }
+
+ await append(sessionId, { kind: 'user', id: crypto.randomUUID(), text });
+ await patchSession(sessionId, { turns: session.turns + 1 });
+
+ busy.add(sessionId);
try {
- if (await handledLocally(text)) {
- setActiveRun(null);
+ if (await handledLocally(text, session)) {
+ await persist(sessionId);
return;
}
const runId = sendInstruction(text, {
- ...context,
+ url: session.url,
+ tabId: session.currentTabId,
+ sessionId,
+ agent: session.agent,
+ agentSessionId: session.agentSessionId,
files: await attachedFiles(),
recordings: await attachedRecordings(),
});
if (!runId) {
- broadcast({
- op: 'event',
- runId: LOCAL_RUN,
- event: {
- kind: 'error',
- code: 'EXTENSION_OFFLINE',
- message:
- 'No Browsentic daemon is attached, so only quick browser commands work. Pair the browser to do more.',
- },
- });
+ await append(
+ sessionId,
+ notice(
+ 'error',
+ 'EXTENSION_OFFLINE: No Browsentic daemon is attached, so only quick browser commands work. Pair the browser to do more.',
+ ),
+ );
+ await persist(sessionId);
+ return;
}
- setActiveRun(runId);
+ await patchSession(sessionId, { runId });
+ await syncRunIndicator();
} finally {
- actingLocally = false;
+ busy.delete(sessionId);
}
}
-async function handledLocally(text: string): Promise<boolean> {
+async function handledLocally(text: string, session: TabSession): Promise<boolean> {
try {
- return await tryFastPath(text, (event) => broadcast({ op: 'event', runId: LOCAL_RUN, event }));
+ return await tryFastPath(
+ text,
+ (event) => {
+ buffers.set(session.sessionId, reduce(buffers.get(session.sessionId) ?? [], event));
+ broadcast({ op: 'event', sessionId: session.sessionId, runId: LOCAL_RUN, event });
+ },
+ session.currentTabId,
+ );
} catch (error) {
console.warn('[browsentic] fast path threw, escalating:', error);
return false;
}
}
-function stopRun(): void {
- const runId = activeRunId;
- if (!runId) {
- broadcast({ op: 'active', runId: null });
+async function stopRun(sessionId: string): Promise<void> {
+ const session = (await readTabSessions())[sessionId];
+ const runId = session?.runId;
+ if (!runId) return;
+ if (!cancelRun(runId)) {
+ await endRun(sessionId, 'The daemon is not connected, so there was nothing left to stop.');
return;
}
- if (!cancelRun(runId)) {
- endRun('The daemon is not connected, so there was nothing left to stop.');
+ clearTimeout(cancelTimers.get(sessionId));
+ cancelTimers.set(
+ sessionId,
+ setTimeout(() => {
+ void serialized(async () => {
+ const still = (await readTabSessions())[sessionId];
+ if (still?.runId !== runId) return;
+ await endRun(sessionId, 'Stopped. The daemon never confirmed it, so check for a run still finishing there.');
+ });
+ }, CANCEL_CONFIRM_MS),
+ );
+}
+
+async function endRun(sessionId: string, message: string): Promise<void> {
+ await append(sessionId, notice('error', `CANCELLED: ${message}`));
+ await settle(sessionId);
+}
+
+async function endSession(sessionId: string): Promise<void> {
+ const session = (await readTabSessions())[sessionId];
+ if (session?.runId) cancelRun(session.runId);
+ clearTimeout(cancelTimers.get(sessionId));
+ cancelTimers.delete(sessionId);
+ await persist(sessionId);
+ await dropSession(sessionId);
+ buffers.delete(sessionId);
+ busy.delete(sessionId);
+ resetConversation(sessionId);
+ await syncRunIndicator();
+}
+
+async function restore(sessionId: string, anchor: TabAnchor): Promise<void> {
+ const live = Object.values(await readTabSessions()).find((s) => s.sessionId === sessionId);
+ if (live) return;
+
+ const owner = await sessionForTab(anchor.tabId);
+ if (owner?.runId) {
+ await append(
+ owner.sessionId,
+ notice('error', 'RUN_IN_PROGRESS: This tab is still running — stop it before opening another conversation here.'),
+ );
return;
}
- clearTimeout(cancelTimer);
- cancelTimer = setTimeout(() => {
- if (activeRunId !== runId) return;
- endRun('Stopped. The daemon never confirmed it, so check for a run still finishing there.');
- }, CANCEL_CONFIRM_MS);
+ if (owner) {
+ await persist(owner.sessionId);
+ await dropSession(owner.sessionId);
+ buffers.delete(owner.sessionId);
+ }
+
+ const meta = (await listSessions()).find((s) => s.id === sessionId);
+ if (!meta) return;
+ const transcript = await readTranscript(sessionId);
+ buffers.set(
+ sessionId,
+ transcript?.items ?? [notice('error', 'That conversation’s messages are no longer stored.')],
+ );
+
+ const session = await bindStoredSession(
+ {
+ sessionId,
+ turns: meta.turns,
+ agent: meta.agent,
+ agentSessionId: meta.agentSessionId,
+ url: meta.url,
+ title: titleOf(meta) ?? anchor.title,
+ },
+ anchor,
+ );
+ broadcast({ op: 'items', sessionId, items: buffers.get(sessionId) ?? [] });
+
+ if (meta.url && /^https?:$/.test(safeProtocol(meta.url))) {
+ await invokeForHarness(navigate.name, { url: meta.url }, session.currentTabId).catch(() => undefined);
+ }
+}
+
+async function bufferFor(sessionId: string): Promise<RunItem[]> {
+ const held = buffers.get(sessionId);
+ if (held) return held;
+ const transcript = await readTranscript(sessionId);
+ const items = transcript?.items ?? [];
+ buffers.set(sessionId, items);
+ return items;
+}
+
+async function append(sessionId: string, item: RunItem): Promise<void> {
+ buffers.set(sessionId, [...(await bufferFor(sessionId)), item]);
+ broadcast({ op: 'item', sessionId, item });
+ schedulePersist(sessionId);
+}
+
+function schedulePersist(sessionId: string): void {
+ clearTimeout(persistTimers.get(sessionId));
+ persistTimers.set(
+ sessionId,
+ setTimeout(() => void serialized(() => persist(sessionId)), PERSIST_DEBOUNCE_MS),
+ );
}
-function endRun(message: string): void {
- broadcast({ op: 'event', runId: LOCAL_RUN, event: { kind: 'error', code: 'CANCELLED', message } });
- setActiveRun(null);
+async function persist(sessionId: string): Promise<void> {
+ clearTimeout(persistTimers.get(sessionId));
+ persistTimers.delete(sessionId);
+ const items = buffers.get(sessionId);
+ if (!items?.length) return;
+ const session = (await readTabSessions())[sessionId];
+ const stored = session ? null : (await listSessions()).find((s) => s.id === sessionId);
+ const now = Date.now();
+ await putSession(
+ {
+ id: sessionId,
+ turns: session?.turns ?? stored?.turns ?? 0,
+ url: session?.url ?? stored?.url,
+ host: session?.host ?? stored?.host,
+ agent: session?.agent ?? stored?.agent,
+ agentSessionId: session?.agentSessionId ?? stored?.agentSessionId,
+ createdAt: session?.createdAt ?? stored?.createdAt ?? now,
+ updatedAt: now,
+ },
+ items,
+ );
+}
+
+export function serveTabSessions(): void {
+ browser.tabs.onRemoved.addListener((tabId) => {
+ forgetTab(tabId);
+ void serialized(async () => {
+ const { closed } = await releaseTab(tabId);
+ if (!closed) return await syncRunIndicator();
+ if (closed.runId) {
+ cancelRun(closed.runId);
+ await append(closed.sessionId, notice('error', 'CANCELLED: The tab was closed, so that run is over.'));
+ }
+ clearTimeout(cancelTimers.get(closed.sessionId));
+ cancelTimers.delete(closed.sessionId);
+ await persist(closed.sessionId);
+ buffers.delete(closed.sessionId);
+ busy.delete(closed.sessionId);
+ if (closed.runId) resetConversation(closed.sessionId);
+ await syncRunIndicator();
+ });
+ });
+
+ browser.tabs.onReplaced.addListener((added, removed) => {
+ void serialized(() => remapTab(removed, added));
+ });
+
+ browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
+ if (changeInfo.title === undefined && changeInfo.url === undefined) return;
+ void serialized(async () => {
+ const session = await sessionForTab(tabId);
+ if (!session) return;
+ const patch: Partial<TabSession> = {};
+ if (tabId === session.mainTabId && tab.title && tab.title !== session.title) patch.title = tab.title;
+ if (tabId === session.currentTabId && changeInfo.url) {
+ patch.url = changeInfo.url;
+ patch.host = hostOf(changeInfo.url);
+ }
+ if (Object.keys(patch).length) await patchSession(session.sessionId, patch);
+ });
+ });
+}
+
+async function beginRecording(captureValues: boolean): Promise<void> {
+ const result = await startActiveTabRecording(captureValues);
+ if (result.ok) return;
+ broadcast({
+ op: 'event',
+ runId: LOCAL_RUN,
+ event: { kind: 'error', code: result.error.code, message: result.error.message },
+ });
}
const MAX_CONTEXT_FILES = 6;
@@ -298,20 +576,19 @@ async function attachedRecordings(): Promise<SavedRecording[]> {
}
}
-function setActiveRun(runId: string | null): void {
- activeRunId = runId;
- clearTimeout(cancelTimer);
- if (runId) clearTimeout(unwatchedTimer);
- broadcast({ op: 'active', runId });
-}
+const noticeOf = (state: MonitorState): ['info' | 'error', string] => {
+ const { tone, text } = monitorNotice(state);
+ return [tone, text];
+};
+
+const titleOf = (meta: StoredSessionMeta): string | undefined => meta.title ?? undefined;
-function scheduleUnwatchedCancel(): void {
- clearTimeout(unwatchedTimer);
- unwatchedTimer = setTimeout(() => {
- if (ports.size > 0 || !activeRunId) return;
- cancelRun(activeRunId);
- setActiveRun(null);
- }, UNWATCHED_GRACE_MS);
+function safeProtocol(url: string): string {
+ try {
+ return new URL(url).protocol;
+ } catch {
+ return '';
+ }
}
function broadcast(message: RunMessage): void {
diff --git a/lib/bridge/use-run.ts b/lib/bridge/use-run.ts
index b3643d6..d4fb61e 100644
--- a/lib/bridge/use-run.ts
+++ b/lib/bridge/use-run.ts
@@ -1,45 +1,32 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { browser, type Browser } from 'wxt/browser';
-import { screenshot } from '@/lib/actions/page/screenshot';
-import { BRIDGE_CHANNEL, type RunEvent } from '@/lib/actions/protocol';
import type { MonitorState } from '@/lib/monitor/events';
import type { RecordingState } from '@/lib/recordings/events';
import { SITE_MAPPER_SKILL, type SiteMapDraft } from '@/lib/skills/site-map';
-import { redactInput } from './redact';
+import { attachPreview, notice, reduce, type RunItem } from './run-items';
import { RUN_PORT, type RunCommand, type RunMessage } from './run-port';
-import type { ScreenshotPreview } from './screenshot-preview';
-import { isNaming, listSessions, putSession, readTranscript, titleDueAt, type SessionFields } from './session-store';
+import { useActiveTab } from './use-active-tab';
+import { useTabSessions } from './use-tab-sessions';
+import type { TabSession } from './tab-sessions';
const RECONNECT_MS = 1_000;
-const PERSIST_DEBOUNCE_MS = 800;
+const EXTERNAL_VIEW = 'external';
-export type RunItem =
- | { kind: 'user'; id: string; text: string }
- | { kind: 'assistant'; id: string; text: string }
- | { kind: 'notice'; id: string; tone: 'info' | 'error'; text: string }
- | {
- kind: 'tool';
- id: string;
- action: string;
- input: unknown;
- summary?: string;
- ok?: boolean;
- awaiting?: boolean;
- site?: string;
- source?: 'local' | 'external';
- preview?: ScreenshotPreview;
- };
+export type { RunItem };
export interface Run {
items: RunItem[];
running: boolean;
- sessionId: string;
+ sessionId: string | null;
+ sessions: TabSession[];
send: (text: string) => void;
cancel: () => void;
decide: (toolId: string, allow: boolean, remember?: boolean) => void;
clear: () => void;
restore: (sessionId: string) => Promise<void>;
+ focusSession: (sessionId: string) => void;
+ endSession: (sessionId: string) => void;
draft: SiteMapDraft | null;
mapSite: () => void;
activateMap: (exactHost?: boolean) => void;
@@ -51,32 +38,32 @@ export interface Run {
stopMonitor: (monitorId: string) => void;
}
-type SessionState = SessionFields;
-
-const freshSession = (): SessionState => {
- const now = Date.now();
- return { id: crypto.randomUUID(), turns: 0, createdAt: now, updatedAt: now };
-};
-
-export function useRun({ persist = false }: { persist?: boolean } = {}): Run {
- const [items, setItems] = useState<RunItem[]>([]);
- const [running, setRunning] = useState(false);
+export function useRun(): Run {
const [draft, setDraft] = useState<SiteMapDraft | null>(null);
const [recording, setRecording] = useState<RecordingState | null>(null);
const [monitors, setMonitors] = useState<MonitorState[]>([]);
+ const [bySession, setBySession] = useState<Record<string, RunItem[]>>({});
const port = useRef<Browser.runtime.Port | null>(null);
- const session = useRef<SessionState>(freshSession());
- const latestItems = useRef<RunItem[]>(items);
- const flushTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
- const [sessionId, setSessionId] = useState(session.current.id);
+ const tab = useActiveTab();
+ const sessions = useTabSessions();
+ const displayed = useMemo(
+ () => (tab.tabId == null ? null : (sessions.find((s) => s.tabIds.includes(tab.tabId!)) ?? null)),
+ [sessions, tab.tabId],
+ );
+ const sessionId = displayed?.sessionId ?? null;
+
+ const write = useCallback((key: string, change: (items: RunItem[]) => RunItem[]) => {
+ setBySession((previous) => ({ ...previous, [key]: change(previous[key] ?? []) }));
+ }, []);
- const flush = useCallback(async () => {
- clearTimeout(flushTimer.current);
- if (!persist || !latestItems.current.length) return;
- session.current.updatedAt = Date.now();
- await putSession({ ...session.current }, latestItems.current);
- }, [persist]);
+ const forget = useCallback((...keys: string[]) => {
+ setBySession((previous) => {
+ const next = { ...previous };
+ for (const key of keys) delete next[key];
+ return next;
+ });
+ }, []);
useEffect(() => {
let live = true;
@@ -95,37 +82,27 @@ export function useRun({ persist = false }: { persist?: boolean } = {}): Run {
connected.onMessage.addListener((message) => {
const runMessage = message as RunMessage;
- if (runMessage.op === 'active') setRunning(runMessage.runId !== null);
- else if (runMessage.op === 'mapDraft') setDraft(runMessage.draft);
+ if (runMessage.op === 'mapDraft') setDraft(runMessage.draft);
else if (runMessage.op === 'mapSettled') {
setDraft((current) => (current?.stagingId === runMessage.stagingId ? null : current));
if (!runMessage.ok && runMessage.message) {
- setItems((previous) => [
- ...previous,
- { kind: 'notice', id: nextId(), tone: 'error', text: runMessage.message! },
- ]);
+ write(EXTERNAL_VIEW, (items) => [...items, notice('error', runMessage.message!)]);
}
} else if (runMessage.op === 'recording') setRecording(runMessage.state);
else if (runMessage.op === 'monitor') {
const state = runMessage.state;
- if (state.phase === 'watching') {
- setMonitors((previous) => {
- const others = previous.filter((m) => m.monitorId !== state.monitorId);
- return [...others, state];
- });
- } else {
- setMonitors((previous) => previous.filter((m) => m.monitorId !== state.monitorId));
- const notice = monitorNotice(state);
- setItems((previous) => [...previous, { kind: 'notice', id: nextId(), ...notice }]);
- }
+ setMonitors((previous) => {
+ const others = previous.filter((m) => m.monitorId !== state.monitorId);
+ return state.phase === 'watching' ? [...others, state] : others;
+ });
+ } else if (runMessage.op === 'items') {
+ write(runMessage.sessionId ?? EXTERNAL_VIEW, () => runMessage.items);
+ } else if (runMessage.op === 'item') {
+ write(runMessage.sessionId ?? EXTERNAL_VIEW, (items) => [...items, runMessage.item]);
} else if (runMessage.op === 'preview') {
- setItems((previous) => attachPreview(previous, runMessage.preview));
+ write(runMessage.sessionId ?? EXTERNAL_VIEW, (items) => attachPreview(items, runMessage.preview));
} else {
- if (runMessage.event.kind === 'session') {
- session.current.agent = runMessage.event.agent;
- session.current.agentSessionId = runMessage.event.agentSessionId ?? undefined;
- }
- setItems((previous) => reduce(previous, runMessage.event));
+ write(runMessage.sessionId ?? EXTERNAL_VIEW, (items) => reduce(items, runMessage.event));
}
});
@@ -143,43 +120,7 @@ export function useRun({ persist = false }: { persist?: boolean } = {}): Run {
port.current = null;
open?.disconnect();
};
- }, []);
-
- useEffect(() => {
- latestItems.current = items;
- if (!persist || !items.length) return;
- clearTimeout(flushTimer.current);
- flushTimer.current = setTimeout(() => void flush(), PERSIST_DEBOUNCE_MS);
- }, [items, persist, flush]);
-
- useEffect(
- () => () => {
- void flush();
- },
- [flush],
- );
-
- const settle = useCallback(async () => {
- if (!persist || !latestItems.current.length) return;
- const [tab] = await browser.tabs.query({ active: true, currentWindow: true }).catch(() => []);
- if (tab?.url) {
- session.current.url = tab.url;
- session.current.host = hostOf(tab.url) ?? session.current.host;
- }
- await flush();
- const id = session.current.id;
- const stored = (await listSessions()).find((s) => s.id === id);
- if (!stored || isNaming(stored)) return;
- if (titleDueAt(stored.turns, stored.titledAtTurn) === null) return;
- void browser.runtime.sendMessage({ channel: BRIDGE_CHANNEL, op: 'nameSession', sessionId: id }).catch(() => {
- });
- }, [persist, flush]);
-
- const wasRunning = useRef(false);
- useEffect(() => {
- if (wasRunning.current && !running) void settle();
- wasRunning.current = running;
- }, [running, settle]);
+ }, [write]);
const post = useCallback((command: RunCommand): boolean => {
const open = port.current;
@@ -193,79 +134,57 @@ export function useRun({ persist = false }: { persist?: boolean } = {}): Run {
}
}, []);
- const lost = useCallback((text: string) => {
- setRunning(false);
- setItems((previous) => [...previous, { kind: 'notice', id: nextId(), tone: 'error', text }]);
- }, []);
+ useEffect(() => {
+ if (sessionId) post({ op: 'replay', sessionId });
+ }, [sessionId, post]);
+
+ const items = useMemo(() => {
+ const own = sessionId ? (bySession[sessionId] ?? []) : [];
+ const external = bySession[EXTERNAL_VIEW] ?? [];
+ return external.length ? [...own, ...external] : own;
+ }, [sessionId, bySession]);
const send = useCallback(
(text: string) => {
const trimmed = text.trim();
- if (!trimmed) return;
- setItems((previous) => [...previous, { kind: 'user', id: nextId(), text: trimmed }]);
- setRunning(true);
- session.current.turns += 1;
- const { agent, agentSessionId } = session.current;
- const failed = () => lost('Lost the connection to the extension — that never went anywhere. Try again.');
- void browser.tabs
- .query({ active: true, currentWindow: true })
- .then(([tab]) => {
- if (tab?.url) {
- session.current.url = tab.url;
- session.current.host = hostOf(tab.url) ?? session.current.host;
- }
- const context = tab?.url
- ? { url: tab.url, tabId: tab.id, agent, agentSessionId }
- : { agent, agentSessionId };
- if (!post({ op: 'instruct', text: trimmed, context })) failed();
- })
- .catch(() => {
- if (!post({ op: 'instruct', text: trimmed, context: { agent, agentSessionId } })) failed();
- });
+ if (!trimmed || tab.tabId == null) return;
+ post({
+ op: 'instruct',
+ text: trimmed,
+ tab: { tabId: tab.tabId, url: tab.url, windowId: tab.windowId, title: tab.title },
+ });
},
- [post, lost],
+ [post, tab],
);
- const clear = useCallback(() => {
- void flush().then(() => {
- session.current = freshSession();
- setSessionId(session.current.id);
- });
- setItems([]);
- post({ op: 'reset' });
- }, [post, flush]);
+ const focusSession = useCallback((target: string) => {
+ const session = sessions.find((s) => s.sessionId === target);
+ if (!session) return;
+ void (async () => {
+ if (session.windowId >= 0) await browser.windows.update(session.windowId, { focused: true }).catch(() => undefined);
+ await browser.tabs.update(session.currentTabId, { active: true }).catch(() => undefined);
+ })();
+ }, [sessions]);
const restore = useCallback(
- async (sessionId: string) => {
- if (running) return;
- const meta = (await listSessions()).find((s) => s.id === sessionId);
- if (!meta) return;
- const transcript = await readTranscript(sessionId);
- await flush();
-
- const { title: _title, titledAtTurn: _titled, namingAt: _naming, ...fields } = meta;
- session.current = fields;
- setSessionId(fields.id);
- setItems(
- transcript
- ? transcript.items
- : [{ kind: 'notice', id: nextId(), tone: 'error', text: 'That conversation’s messages are no longer stored.' }],
- );
-
- if (meta.url && /^https?:$/.test(safeProtocol(meta.url))) {
- await browser.runtime
- .sendMessage({ channel: BRIDGE_CHANNEL, op: 'invoke', action: 'page.navigate', input: { url: meta.url } })
- .catch(() => {
- });
- }
+ async (target: string) => {
+ if (tab.tabId == null) return;
+ const live = sessions.find((s) => s.sessionId === target);
+ if (live) return focusSession(target);
+ post({
+ op: 'restore',
+ sessionId: target,
+ tab: { tabId: tab.tabId, url: tab.url, windowId: tab.windowId, title: tab.title },
+ });
},
- [flush, running],
+ [post, sessions, tab, focusSession],
);
return {
items,
- running,
+ running: displayed?.runId != null,
sessionId,
+ sessions,
send,
draft,
mapSite: useCallback(() => send(`@${SITE_MAPPER_SKILL} map this site`), [send]),
@@ -296,121 +215,27 @@ export function useRun({ persist = false }: { persist?: boolean } = {}): Run {
[post],
),
cancel: useCallback(() => {
- if (!post({ op: 'cancel' })) lost('Lost the connection to the extension, so this run is no longer being watched.');
- }, [post, lost]),
+ if (sessionId) post({ op: 'cancel', sessionId });
+ }, [post, sessionId]),
decide: useCallback(
(toolId: string, allow: boolean, remember?: boolean) => {
- setItems((previous) => patchTool(previous, toolId, { awaiting: false }));
- post({ op: 'decision', toolId, allow, remember });
+ if (sessionId) post({ op: 'decision', sessionId, toolId, allow, remember });
},
- [post],
+ [post, sessionId],
+ ),
+ clear: useCallback(() => {
+ if (!sessionId) return;
+ forget(sessionId, EXTERNAL_VIEW);
+ post({ op: 'endSession', sessionId });
+ }, [post, sessionId, forget]),
+ endSession: useCallback(
+ (target: string) => {
+ forget(target);
+ post({ op: 'endSession', sessionId: target });
+ },
+ [post, forget],
),
- clear,
restore,
+ focusSession,
};
}
-
-function monitorNotice(state: MonitorState): { tone: 'info' | 'error'; text: string } {
- const name = state.label ?? state.host;
- const elapsed = clock(state.elapsedMs);
- switch (state.phase) {
- case 'done':
- return { tone: 'info', text: `Monitor “${name}” finished after ${elapsed}.` };
- case 'stopped':
- return { tone: 'info', text: `Monitor “${name}” stopped.` };
- case 'timeout':
- return { tone: 'error', text: `Monitor “${name}” gave up after ${elapsed} without completing.` };
- case 'tab-closed':
- return { tone: 'error', text: `Monitor “${name}” ended — the tab was closed.` };
- default:
- return { tone: 'error', text: `Monitor “${name}” ended — ${state.message ?? 'the tab left the watched site.'}` };
- }
-}
-
-function clock(ms: number): string {
- const total = Math.floor(ms / 1000);
- return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
-}
-
-function hostOf(url: string): string | null {
- try {
- return new URL(url).host || null;
- } catch {
- return null;
- }
-}
-
-function safeProtocol(url: string): string {
- try {
- return new URL(url).protocol;
- } catch {
- return '';
- }
-}
-
-function reduce(items: RunItem[], event: RunEvent): RunItem[] {
- switch (event.kind) {
- case 'started': {
- const overlays = event.overlays?.length ? ` + site notes: ${event.overlays.join(', ')}` : '';
- return [
- ...items,
- { kind: 'notice', id: nextId(), tone: 'info', text: `Loaded skill: ${event.skill}${overlays}` },
- ];
- }
-
- case 'text': {
- const last = items.at(-1);
- if (last?.kind === 'assistant') {
- return [...items.slice(0, -1), { ...last, text: last.text + event.delta }];
- }
- return [...items, { kind: 'assistant', id: nextId(), text: event.delta }];
- }
-
- case 'tool':
- return [
- ...items,
- {
- kind: 'tool',
- id: event.toolId,
- action: event.action,
- input: redactInput(event.action, event.input),
- source: event.source,
- },
- ];
-
- case 'approval':
- return patchTool(items, event.toolId, { awaiting: true, site: event.site });
-
- case 'toolResult':
- return patchTool(items, event.toolId, { ok: event.ok, summary: event.summary, awaiting: false });
-
- case 'session':
- return items;
-
- case 'done':
- return event.stopReason === 'end_turn'
- ? items
- : [...items, { kind: 'notice', id: nextId(), tone: 'info', text: `Stopped: ${event.stopReason}` }];
-
- case 'error':
- return [...items, { kind: 'notice', id: nextId(), tone: 'error', text: `${event.code}: ${event.message}` }];
- }
-}
-
-function attachPreview(items: RunItem[], preview: ScreenshotPreview): RunItem[] {
- for (let i = items.length - 1; i >= 0; i--) {
- const item = items[i];
- if (item.kind === 'tool' && item.action === screenshot.name && !item.preview) {
- const next = [...items];
- next[i] = { ...item, preview };
- return next;
- }
- }
- return items;
-}
-
-function patchTool(items: RunItem[], toolId: string, patch: Partial<Extract<RunItem, { kind: 'tool' }>>): RunItem[] {
- return items.map((item) => (item.kind === 'tool' && item.id === toolId ? { ...item, ...patch } : item));
-}
-
-const nextId = () => crypto.randomUUID();