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(bridge): persist conversations and make stop always answer
Shahriar51d302d7b560
diff --git a/entrypoints/background.ts b/entrypoints/background.tsindex 1a4292c..50c035c 100644--- a/entrypoints/background.ts+++ b/entrypoints/background.ts@@ -4,6 +4,7 @@ import { injectContentScript } from '@/lib/actions/client';import { invokeForHarness } from '@/lib/bridge/invoke';import { analyzeStoredFile } from '@/lib/bridge/file-store';import { pushSkill, removeSkill, resyncSkills } from '@/lib/bridge/skill-store';+import { nameStoredSession } from '@/lib/bridge/session-store';import { serveRunPorts } from '@/lib/bridge/run-port';import { RECONNECT_ALARM, connectDaemon, disconnectDaemon, onWelcome, pairDaemon } from '@/lib/bridge/socket';@@ -44,6 +45,14 @@ export default defineBackground(() => {sendResponse(success(true));return;}+ // Name a saved conversation. Same fire-and-forget shape again: the worker reads the transcript+ // from storage and writes the title back to the session index, so the name arrives even if the+ // panel that crossed the turn threshold has since been closed.+ if (message.op === 'nameSession' && typeof message.sessionId === 'string') {+ void nameStoredSession(message.sessionId);+ sendResponse(success(true));+ return;+ }// Pairing is driven from the popup: the worker owns the socket, the UI just asks.if (message.op === 'pair' && typeof message.token === 'string') {pairDaemon(message.token)@@ -62,7 +71,7 @@ export default defineBackground(() => {sendResponse(failure('INVALID_REQUEST',- 'Expected {op:"describe"|"invoke"|"analyzeFile"|"saveSkill"|"removeSkill"|"pair"|"disconnect"}',+ 'Expected {op:"describe"|"invoke"|"analyzeFile"|"saveSkill"|"removeSkill"|"nameSession"|"pair"|"disconnect"}',),);return;diff --git a/lib/bridge/file-store.ts b/lib/bridge/file-store.tsindex bda0619..b9b5262 100644--- a/lib/bridge/file-store.ts+++ b/lib/bridge/file-store.ts@@ -28,8 +28,14 @@ export interface StoredFileMeta {mime: string;size: number;status: FileStatus;- /** Present once the daemon has summarized the file. */+ /** Present once the daemon has summarized the file. The one line the panel shows. */summary?: string;+ /**+ * The longer extract of the file's contents, sent along as run context so the agent can answer+ * questions about an attached file — there is no tool that reads one during a run. Kept in the+ * index rather than beside the bytes: it is small, and every instruction needs it.+ */+ digest?: string;/** Present when analysis failed. */error?: string;addedAt: number;@@ -102,7 +108,12 @@ export async function analyzeStoredFile(fileId: string): Promise<void> {content: bytes.content,});if (result.ok) {- await updateMeta(fileId, { status: 'ready', summary: result.data.summary, error: undefined });+ await updateMeta(fileId, {+ status: 'ready',+ summary: result.data.summary,+ digest: result.data.digest,+ error: undefined,+ });} else {await updateMeta(fileId, { status: 'error', error: `${result.error.code}: ${result.error.message}` });}diff --git a/lib/bridge/run-port.ts b/lib/bridge/run-port.tsindex cb6dc52..201ea03 100644--- a/lib/bridge/run-port.ts+++ b/lib/bridge/run-port.ts@@ -1,7 +1,8 @@import { browser, type Browser } from 'wxt/browser';-import type { RunContext, RunEvent } from '@/lib/actions/protocol';+import type { AttachedFile, RunContext, RunEvent } from '@/lib/actions/protocol';import type { SiteMapDraft } from '@/lib/skills/site-map';import { tryFastPath } from './fast-path';+import { listMeta } from './file-store';import { recordGeneratedSkill } from './skill-store';import {activateSiteMap,@@ -9,6 +10,7 @@ import {discardSiteMap,onRunEvent,onSiteMapDraft,+ onWelcome,resetConversation,sendDecision,sendInstruction,@@ -26,6 +28,17 @@ const LOCAL_RUN = 'local';*/const UNWATCHED_GRACE_MS = 10_000;+/**+ * How long a cancellation may go unanswered before the worker ends the run on its own account.+ *+ * A `cancel` frame is only a request: the daemon answers it by ending the run, which is what+ * clears `activeRunId` here. If the daemon has already forgotten the run — it was cancelled from+ * the other side, the socket was replaced, the run errored somewhere that never emitted — no+ * answer is coming, and without this the panel is stuck showing a Stop button that does nothing+ * for as long as the worker lives.+ */+const CANCEL_CONFIRM_MS = 4_000;+/** Extension page → background worker. */export type RunCommand =/** `context` names the tab the instruction was typed against; the daemon routes site skills on it. */@@ -52,6 +65,7 @@ let activeRunId: string | null = null;/** True while a local action is in flight — it holds the same one-at-a-time lock as a run. */let actingLocally = false;let unwatchedTimer: ReturnType<typeof setTimeout> | undefined;+let cancelTimer: ReturnType<typeof setTimeout> | undefined;/** The staged map nobody has decided on yet. Replayed to a page that connects late. */let pendingDraft: SiteMapDraft | null = null;@@ -61,7 +75,11 @@ let pendingDraft: SiteMapDraft | null = null;*/export function serveRunPorts(): void {onRunEvent((runId, event) => {- if (event.kind === 'done' || event.kind === 'error') setActiveRun(null);+ // Only the run we are actually tracking gets to end it. A daemon that refuses a second+ // instruction answers with an error carrying *that* instruction's id, and treating it as the+ // end of the run already in progress would hand the composer back mid-run.+ const ends = event.kind === 'done' || event.kind === 'error';+ if (ends && (activeRunId === null || activeRunId === runId)) setActiveRun(null);broadcast({ op: 'event', runId, event });});@@ -72,6 +90,13 @@ export function serveRunPorts(): void {broadcast({ op: 'mapDraft', draft });});+ // A fresh `welcome` means the daemon accepted a new connection, and accepting one disposes the+ // agent session the previous connection was using. So any run this worker still believes in is+ // definitively over — the event that would have said so went to a socket that is already gone.+ onWelcome(() => {+ if (activeRunId) endRun('The connection to the daemon dropped, so that run is over.');+ });+browser.runtime.onConnect.addListener((port) => {if (port.name !== RUN_PORT) return;ports.add(port);@@ -90,12 +115,26 @@ export function serveRunPorts(): void {function handle(command: RunCommand): void {switch (command.op) {case 'instruct':- // One run at a time: the daemon rejects a second, but not starting it is clearer.- if (activeRunId || actingLocally) return;+ // One run at a time: the daemon rejects a second, but not starting it is clearer. Say so+ // rather than dropping it — the page set itself "working" when it sent this, and silence+ // leaves it that way with nothing on the way to correct it.+ 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);return;case 'cancel':- if (activeRunId) cancelRun(activeRunId);+ stopRun();return;case 'decision':if (activeRunId) sendDecision(activeRunId, command.toolId, command.allow);@@ -142,37 +181,108 @@ function handle(command: RunCommand): void {* the two apart except by the `source` marker on the steps.*/async function instruct(text: string, context?: RunContext): Promise<void> {+ // Held for the whole funnel, not just the fast path: reading the file index below is another+ // await, and releasing the lock before it leaves a window where neither this nor `activeRunId`+ // is set — long enough for a second instruction to start a run alongside this one.actingLocally = true;try {- if (await tryFastPath(text, (event) => broadcast({ op: 'event', runId: LOCAL_RUN, event }))) {+ if (await handledLocally(text)) {// Release the composer: the page set itself "working" the moment it sent this.setActiveRun(null);return;}- } catch (error) {- // A broken fast path must never swallow the instruction — fall through to the agent.- console.warn('[voicelink] fast path threw, escalating:', error);++ // Read the file index here rather than in the page that typed this: the worker owns storage,+ // and the popup and the side panel then describe the same library without either doing it.+ const runId = sendInstruction(text, { ...context, files: await attachedFiles() });+ if (!runId) {+ broadcast({+ op: 'event',+ runId: LOCAL_RUN,+ event: {+ kind: 'error',+ code: 'EXTENSION_OFFLINE',+ message:+ 'No VoiceLink daemon is attached, so only quick browser commands work. Pair the browser to do more.',+ },+ });+ }+ setActiveRun(runId);} finally {actingLocally = false;}+}- const runId = sendInstruction(text, context);+/** The local grammar's attempt. A fast path that throws must never swallow the instruction. */+async function handledLocally(text: string): Promise<boolean> {+ try {+ return await tryFastPath(text, (event) => broadcast({ op: 'event', runId: LOCAL_RUN, event }));+ } catch (error) {+ console.warn('[voicelink] fast path threw, escalating:', error);+ return false;+ }+}++/**+ * Stop whatever is running, and make sure the answer arrives either way.+ *+ * Ordinarily the daemon ends the run and the `done`/`error` event clears the state. The two cases+ * that used to wedge the panel are both handled here: nothing to send the frame on, and a frame+ * that goes out to a daemon which no longer has this run to cancel.+ */+function stopRun(): void {+ const runId = activeRunId;if (!runId) {- broadcast({- op: 'event',- runId: LOCAL_RUN,- event: {- kind: 'error',- code: 'EXTENSION_OFFLINE',- message: 'No VoiceLink daemon is attached, so only quick browser commands work. Pair the browser to do more.',- },- });+ // Nothing running here. Re-answer anyway: a page showing a Stop button disagrees with us.+ broadcast({ op: 'active', runId: null });+ return;+ }+ if (!cancelRun(runId)) {+ endRun('The daemon is not connected, so there was nothing left to stop.');+ 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);+}++/** End the run from this side, with a line on the timeline saying why it ended here. */+function endRun(message: string): void {+ broadcast({ op: 'event', runId: LOCAL_RUN, event: { kind: 'error', code: 'CANCELLED', message } });+ setActiveRun(null);+}++/** Newest first, and only this many: past a handful the prompt is mostly file notes. */+const MAX_CONTEXT_FILES = 6;+/** Per-file cap on the extract. The daemon caps the assembled block again on its own terms. */+const MAX_DIGEST_CHARS = 2_000;++/**+ * The attached-file library as run context. Metadata and notes only — the bytes never leave+ * storage except through `page.attachFile`, which reads them in the invoke path.+ */+async function attachedFiles(): Promise<AttachedFile[]> {+ try {+ return (await listMeta()).slice(0, MAX_CONTEXT_FILES).map((file) => ({+ id: file.id,+ name: file.name,+ mime: file.mime,+ size: file.size,+ status: file.status,+ summary: file.summary,+ digest: file.digest?.slice(0, MAX_DIGEST_CHARS),+ }));+ } catch {+ // An unreadable index must not cost the user their instruction.+ return [];}- setActiveRun(runId);}function setActiveRun(runId: string | null): void {activeRunId = runId;+ clearTimeout(cancelTimer);if (runId) clearTimeout(unwatchedTimer);broadcast({ op: 'active', runId });}diff --git a/lib/bridge/session-store.ts b/lib/bridge/session-store.tsnew file mode 100644index 0000000..971e9d0--- /dev/null+++ b/lib/bridge/session-store.ts@@ -0,0 +1,196 @@+import { browser } from 'wxt/browser';+import type { RunItem } from './use-run';+import { nameSession } from './socket';++/**+ * The extension's library of past conversations, in `browser.storage.local` (the+ * `unlimitedStorage` permission lifts the default quota). Same two shapes as the file and skill+ * stores, split so a title arriving never rewrites the transcript:+ *+ * 'voicelink:sessions' -> StoredSessionMeta[] the small, reactive index the list reads+ * 'voicelink:session:<id>' -> StoredSessionTranscript the rows, read only on restore+ *+ * Unlike those two, this store is written continuously while a conversation happens rather than+ * once per user action, so it is the first store here that enforces its own caps — see MAX_SESSIONS+ * and MAX_ITEMS below. The side panel owns the writes (`use-run.ts`); the background worker only+ * reads, to run the naming round-trip.+ */++/** The reactive index — never holds transcript rows. */+export const SESSIONS_INDEX_KEY = 'voicelink:sessions';++const transcriptKey = (id: string) => `voicelink:session:${id}`;++/**+ * How many conversations to keep. Sessions accumulate on their own, with no user action to prompt+ * pruning, so something has to bound them; the oldest fall off the tail and their transcripts are+ * removed with them.+ */+const MAX_SESSIONS = 50;++/**+ * How many rows to keep per conversation. Trimmed from the *head*, so a long session restores as+ * its most recent 500 rows rather than its first 500 — the tail is what the next message follows on+ * from. The agent's own memory is unaffected either way: that lives in the Claude Code session.+ */+const MAX_ITEMS = 500;++/** Turn counts at which the name is (re)generated, so a session that drifted gets a name that fits. */+export const TITLE_TURNS = [1, 5, 15] as const;++/** A saved conversation, as the history list sees it. */+export interface StoredSessionMeta {+ id: string;+ /** Model-generated. Absent until the first naming round-trip lands. */+ title?: string;+ /** The host the conversation was about, shown on the row before a title exists. */+ host?: string;+ /** Where the conversation left off. Restoring navigates the active tab back here. */+ url?: string;+ /**+ * The Claude Code session this conversation lives in, so restoring can resume it. Only ever an id+ * the daemon confirmed (a `session` run event) — an unconfirmed one is not resumable, and passing+ * it would fail every run from here on.+ */+ claudeSessionId?: string;+ /** User messages, which is what "turn" means for the naming thresholds. */+ turns: number;+ /** The turn count the current title was generated from, so a title is never re-requested. */+ titledAtTurn?: number;+ /**+ * When a naming round-trip started, so a second one is not queued alongside it. A timestamp+ * rather than a flag because Chrome can stop the worker mid-request: a flag would then sit true+ * forever and this conversation would never be named again, where a stale timestamp is ignored.+ */+ namingAt?: number;+ createdAt: number;+ updatedAt: number;+}++/** Past this, a naming request is assumed dead rather than slow. Comfortably over its own timeout. */+export const NAMING_STALE_MS = 60_000;++/** True while a naming round-trip is plausibly still running. */+export const isNaming = (session: StoredSessionMeta): boolean =>+ session.namingAt !== undefined && Date.now() - session.namingAt < NAMING_STALE_MS;++export interface StoredSessionTranscript {+ id: string;+ items: RunItem[];+}++/** The session index, newest first, or an empty list when nothing is stored. */+export async function listSessions(): Promise<StoredSessionMeta[]> {+ const stored = await browser.storage.local.get(SESSIONS_INDEX_KEY);+ const list = stored[SESSIONS_INDEX_KEY];+ return Array.isArray(list) ? (list as StoredSessionMeta[]) : [];+}++async function writeIndex(list: StoredSessionMeta[]): Promise<void> {+ await browser.storage.local.set({ [SESSIONS_INDEX_KEY]: list });+}++/** What the panel owns and rewrites on every flush. The rest of the record is the worker's. */+export type SessionFields = Omit<StoredSessionMeta, 'title' | 'titledAtTurn' | 'namingAt'>;++/**+ * Write a conversation: its rows under their own key, its metadata at the head of the index.+ *+ * Merged rather than replaced, because two writers share this record: the panel rewrites the+ * fields above on every flush, while the worker writes the title alongside. A wholesale replace+ * would erase whichever one wrote second — in practice, the title, on the panel's next keystroke.+ *+ * An empty transcript is never stored. A panel opened and closed without a word said would+ * otherwise leave a blank row in the list every time.+ */+export async function putSession(fields: SessionFields, items: RunItem[]): Promise<void> {+ if (!items.length) return;+ const transcript: StoredSessionTranscript = { id: fields.id, items: items.slice(-MAX_ITEMS) };+ await browser.storage.local.set({ [transcriptKey(fields.id)]: transcript });++ const list = await listSessions();+ const existing = list.find((s) => s.id === fields.id);+ const kept = [{ ...existing, ...fields }, ...list.filter((s) => s.id !== fields.id)];+ // Bodies are keyed separately, so dropping a session from the index is not enough to reclaim+ // its space — the transcripts have to go explicitly, as in `skill-store.ts`.+ const dropped = kept.slice(MAX_SESSIONS);+ if (dropped.length) await browser.storage.local.remove(dropped.map((s) => transcriptKey(s.id)));+ await writeIndex(kept.slice(0, MAX_SESSIONS));+}++/** The rows of a saved conversation, or null when the id is unknown. */+export async function readTranscript(id: string): Promise<StoredSessionTranscript | null> {+ const key = transcriptKey(id);+ const stored = await browser.storage.local.get(key);+ const transcript = stored[key] as StoredSessionTranscript | undefined;+ return transcript && Array.isArray(transcript.items) ? transcript : null;+}++/**+ * Patch one session's metadata in place, leaving its transcript untouched. Silently does nothing+ * for an unknown id — a session trimmed off the tail while its naming round-trip was in flight+ * must not come back as a row with nothing behind it.+ */+export async function updateSessionMeta(id: string, patch: Partial<StoredSessionMeta>): Promise<void> {+ const list = await listSessions();+ if (!list.some((s) => s.id === id)) return;+ await writeIndex(list.map((s) => (s.id === id ? { ...s, ...patch } : s)));+}++/** Remove a conversation and its transcript. */+export async function removeSession(id: string): Promise<void> {+ await browser.storage.local.remove(transcriptKey(id));+ const list = await listSessions();+ await writeIndex(list.filter((s) => s.id !== id));+}++/** A title is one line on a list row, so it is capped like one. Also clamped daemon-side. */+const MAX_TITLE_CHARS = 60;++/** How many of the user's messages to hand the namer. The recent ones say what it became about. */+const MAX_TITLE_MESSAGES = 12;++/**+ * The daemon round-trip that names a conversation: read its transcript, ask the daemon, and fold+ * the title back into the index. Called from the background worker (it owns the socket), so the+ * name lands even if the side panel that asked for it has since closed.+ *+ * Only the user's own messages are sent. An assistant turn restates whatever page it was reading,+ * so including one would let a site influence the name of a session in the user's own history.+ */+export async function nameStoredSession(sessionId: string): Promise<void> {+ const meta = (await listSessions()).find((s) => s.id === sessionId);+ if (!meta) return;+ const transcript = await readTranscript(sessionId);+ const messages = (transcript?.items ?? [])+ .filter((item): item is Extract<RunItem, { kind: 'user' }> => item.kind === 'user')+ .map((item) => item.text)+ .slice(-MAX_TITLE_MESSAGES);+ if (!messages.length) return;++ // Recorded before the round-trip so the row can show that a name is coming, and so a second+ // threshold crossing during a slow one does not queue a duplicate.+ const turns = meta.turns;+ await updateSessionMeta(sessionId, { namingAt: Date.now() });+ const result = await nameSession({ host: meta.host, messages });+ if (result.ok && result.data.title.trim()) {+ await updateSessionMeta(sessionId, {+ // Flattened and clamped again on this side: the daemon already does both, and neither end+ // should be the only thing standing between model output and a row in the user's history.+ title: result.data.title.replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE_CHARS),+ titledAtTurn: turns,+ namingAt: undefined,+ });+ return;+ }+ // A failed naming is not worth surfacing — the session is saved and usable without a name — but+ // the turn is marked so a daemon that is simply down does not get asked again on every run.+ await updateSessionMeta(sessionId, { titledAtTurn: turns, namingAt: undefined });+}++/** The turn count a name is owed for, or null when the current title is still current enough. */+export function titleDueAt(turns: number, titledAtTurn = 0): number | null {+ const crossed = TITLE_TURNS.filter((threshold) => turns >= threshold);+ const latest = crossed.at(-1);+ return latest !== undefined && latest > titledAtTurn ? latest : null;+}diff --git a/lib/bridge/socket.ts b/lib/bridge/socket.tsindex e526a75..3f455c7 100644--- a/lib/bridge/socket.ts+++ b/lib/bridge/socket.ts@@ -41,7 +41,7 @@ let socket: WebSocket | null = null;let attempts = 0;let reconnectTimer: ReturnType<typeof setTimeout> | undefined;let runListener: ((runId: string, event: RunEvent) => void) | null = null;-let welcomeListener: (() => void) | null = null;+const welcomeListeners = new Set<() => void>();let draftListener: ((runId: string, draft: SiteMapDraft) => void) | null = null;/** Register the sink for a staged site map awaiting review. The background worker owns it. */@@ -56,11 +56,13 @@ export function onRunEvent(listener: (runId: string, event: RunEvent) => void):/*** Called on every accepted connection, so the worker can push anything that queued up while- * the daemon was away. A listener rather than a direct call because the things that need to- * re-sync already import from this module, and the arrow has to stay one-way.+ * the daemon was away — and so anything that assumed daemon state can reconcile, since a fresh+ * `welcome` means the daemon dropped whatever it was holding for the previous connection.+ * Listeners rather than direct calls because the things that need this already import from+ * here, and the arrow has to stay one-way.*/export function onWelcome(listener: () => void): void {- welcomeListener = listener;+ welcomeListeners.add(listener);}/**@@ -76,7 +78,10 @@ export function sendInstruction(text: string, context?: RunContext): string | nu/** Reply must arrive before this, or the caller gets a TIMEOUT. Longer than the daemon's own. */const ANALYZE_TIMEOUT_MS = 90_000;-const pendingAnalyses = new Map<string, (result: ActionResult<{ summary: string }>) => void>();+/** What the daemon sends back for an attached file: the panel's line, and the run's extract. */+type FileNotes = { summary: string; digest?: string };++const pendingAnalyses = new Map<string, (result: ActionResult<FileNotes>) => void>();/*** Send a file to the daemon for one-shot summarization and resolve with its summary. The@@ -88,7 +93,7 @@ export function analyzeFile(file: {mime: string;size: number;content: string;-}): Promise<ActionResult<{ summary: string }>> {+}): Promise<ActionResult<FileNotes>> {const id = crypto.randomUUID();if (!post({ t: 'analyzeFile', id, ...file })) {return Promise.resolve(failure('EXTENSION_OFFLINE', 'No VoiceLink daemon is attached — pair the browser first.'));@@ -105,6 +110,33 @@ export function analyzeFile(file: {});}+/** One short line from one small spawn. Generous enough for a cold start, short enough to give up on. */+const TITLE_TIMEOUT_MS = 20_000;++const pendingSessionNames = new Map<string, (result: ActionResult<{ title: string }>) => void>();++/**+ * Ask the daemon to name a conversation. Same correlate-by-id shape as `analyzeFile`, and the same+ * failure-envelope-rather-than-hang contract: an unnamed session is a cosmetic loss, so nothing here+ * is allowed to leave a caller waiting.+ */+export function nameSession(session: { host?: string; messages: string[] }): Promise<ActionResult<{ title: string }>> {+ const id = crypto.randomUUID();+ if (!post({ t: 'nameSession', id, ...session })) {+ return Promise.resolve(failure('EXTENSION_OFFLINE', 'No VoiceLink daemon is attached — pair the browser first.'));+ }+ return new Promise((resolve) => {+ const timer = setTimeout(() => {+ pendingSessionNames.delete(id);+ resolve(failure('TIMEOUT', 'The daemon did not return a name in time.'));+ }, TITLE_TIMEOUT_MS);+ pendingSessionNames.set(id, (result) => {+ clearTimeout(timer);+ resolve(result);+ });+ });+}+/** The daemon answers these synchronously, so a slow reply means something is wrong. */const SKILL_TIMEOUT_MS = 15_000;@@ -155,8 +187,9 @@ function skillOp(});}-export function cancelRun(id: string): void {- post({ t: 'cancel', id });+/** False when there was no open socket to send it on, i.e. nothing received the cancellation. */+export function cancelRun(id: string): boolean {+ return post({ t: 'cancel', id });}export function sendDecision(id: string, toolId: string, allow: boolean): void {@@ -307,7 +340,7 @@ async function handle(ws: WebSocket, raw: string, port: number, auth: SocketAuthlastChangeAt: Date.now(),});// The daemon is reachable again; anything that failed to reach it can go now.- welcomeListener?.();+ for (const listener of welcomeListeners) listener();return;case 'describe':@@ -335,6 +368,12 @@ async function handle(ws: WebSocket, raw: string, port: number, auth: SocketAuthreturn;}+ case 'sessionName': {+ pendingSessionNames.get(frame.id)?.(frame.result);+ pendingSessionNames.delete(frame.id);+ return;+ }+case 'siteMapDraft':return draftListener?.(frame.id, frame.draft);diff --git a/lib/bridge/use-run.ts b/lib/bridge/use-run.tsindex 96e5a65..d58302c 100644--- a/lib/bridge/use-run.ts+++ b/lib/bridge/use-run.ts@@ -1,8 +1,20 @@import { useCallback, useEffect, useRef, useState } from 'react';import { browser, type Browser } from 'wxt/browser';-import type { RunEvent } from '@/lib/actions/protocol';+import { BRIDGE_CHANNEL, type RunEvent } from '@/lib/actions/protocol';import { SITE_MAPPER_SKILL, type SiteMapDraft } from '@/lib/skills/site-map';import { RUN_PORT, type RunCommand, type RunMessage } from './run-port';+import { isNaming, listSessions, putSession, readTranscript, titleDueAt, type SessionFields } from './session-store';++/** How long to wait before redialling the worker after it went away. */+const RECONNECT_MS = 1_000;++/**+ * How long the transcript may sit unwritten. `text` events arrive token by token, so writing on+ * every change would be one `storage.local.set` per token. The cost of the delay is bounded: every+ * run end forces a flush, so only closing the panel mid-stream can lose anything, and only the last+ * window of it.+ */+const PERSIST_DEBOUNCE_MS = 800;/** One rendered row of the transcript. Tool rows mutate in place as their result arrives. */export type RunItem =@@ -25,10 +37,15 @@ export type RunItem =export interface Run {items: RunItem[];running: boolean;+ /** The conversation on screen, so the history list can mark which row is already open. */+ sessionId: string;send: (text: string) => void;cancel: () => void;decide: (toolId: string, allow: boolean) => void;+ /** Close out the conversation and start a fresh one. The old one stays in the session library. */clear: () => void;+ /** Reopen a saved conversation: its rows, its agent memory, and the page it was left on. */+ restore: (sessionId: string) => Promise<void>;/** A finished map waiting to be read and armed, or null. */draft: SiteMapDraft | null;/** Ask for the current site to be mapped. Explicit by design — never inferred from phrasing. */@@ -37,46 +54,175 @@ export interface Run {discardMap: () => void;}+/** The panel's live copy of the session record it is writing. See `SessionFields`. */+type SessionState = SessionFields;++const freshSession = (): SessionState => {+ const now = Date.now();+ return { id: crypto.randomUUID(), turns: 0, createdAt: now, updatedAt: now };+};+/*** Live view of the agent, for an extension page. Holds a port to the background worker, which* owns the daemon socket — pages come and go, the connection does not.+ *+ * With `persist`, the conversation is also saved to the session library as it happens, and this+ * hook becomes the owner of its Claude Code session id — which is what lets a restored conversation+ * carry on rather than start over. Off by default: the popup fires one instruction and closes, so it+ * would only ever mint half a session, and the panel it hands over to would mint another.+ *+ * A newly mounted panel always starts a new conversation rather than adopting the last one. Closing+ * the panel mid-conversation therefore does not resume on reopen — but nothing is lost, the session+ * is one click away in the history list.*/-export function useRun(): Run {+export function useRun({ persist = false }: { persist?: boolean } = {}): Run {const [items, setItems] = useState<RunItem[]>([]);const [running, setRunning] = useState(false);const [draft, setDraft] = useState<SiteMapDraft | null>(null);const port = useRef<Browser.runtime.Port | null>(null);+ // Refs, not state: the flush timer and the port listener both need the current values without+ // being re-created — and re-creating the port effect would drop the connection.+ const session = useRef<SessionState>(freshSession());+ const latestItems = useRef<RunItem[]>(items);+ const flushTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ // Mirrored as state only so switching conversations re-renders the history list's "open" mark.+ const [sessionId, setSessionId] = useState(session.current.id);++ /** Write the conversation now, cancelling any pending debounced write. */+ 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]);+useEffect(() => {- const connected = browser.runtime.connect({ name: RUN_PORT });- port.current = connected;-- 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);- 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! },- ]);+ let live = true;+ let retry: ReturnType<typeof setTimeout> | undefined;++ const connect = () => {+ if (!live) return;+ let connected: Browser.runtime.Port;+ try {+ connected = browser.runtime.connect({ name: RUN_PORT });+ } catch {+ // Thrown outright once the extension context is gone (a reload or update). Keep trying:+ // this page is about to be torn down with it, and if it is not, the worker will be back.+ retry = setTimeout(connect, RECONNECT_MS);+ return;+ }+ port.current = connected;++ 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);+ 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! },+ ]);+ }+ } else {+ // `session` names the Claude Code conversation this run landed in. It is not a row —+ // `reduce` passes it through — so record it here, where the session record lives.+ if (runMessage.event.kind === 'session') {+ session.current.claudeSessionId = runMessage.event.claudeSessionId ?? undefined;+ }+ setItems((previous) => reduce(previous, runMessage.event));}- } else setItems((previous) => reduce(previous, runMessage.event));- });- // The worker can be torn down; a page that outlives it must not hold a dead port.- connected.onDisconnect.addListener(() => {- if (port.current === connected) port.current = null;- });+ });++ // Chrome can tear the worker down under an open panel. Redialling is also what wakes it+ // back up, and the `active` message it answers with is how the panel re-learns whether+ // anything is still running — without this a page that lost its port keeps whatever+ // "working" state it happened to be in, with nothing able to correct it.+ connected.onDisconnect.addListener(() => {+ if (port.current === connected) port.current = null;+ if (live) retry = setTimeout(connect, RECONNECT_MS);+ });+ };+ connect();return () => {+ live = false;+ clearTimeout(retry);+ const open = port.current;port.current = null;- connected.disconnect();+ open?.disconnect();};}, []);- const post = useCallback((command: RunCommand) => port.current?.postMessage(command), []);+ // Debounced save of whatever is on screen. `latestItems` is updated here rather than in every+ // producer, so there is one place the flush timer and the unmount path read from.+ useEffect(() => {+ latestItems.current = items;+ if (!persist || !items.length) return;+ clearTimeout(flushTimer.current);+ flushTimer.current = setTimeout(() => void flush(), PERSIST_DEBOUNCE_MS);+ }, [items, persist, flush]);++ // Last write before this page goes away. Separate from the effect above, whose cleanup runs on+ // every keystroke and must only cancel the timer, never write.+ useEffect(+ () => () => {+ void flush();+ },+ [flush],+ );++ /**+ * A run just ended. Refresh where the conversation is (the agent may have navigated since the+ * instruction was sent — this is the URL a restore returns to), get it on disk, then let the+ * worker name it if enough has been said since the last name.+ */+ 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;+ }+ // Before the request, not after: the worker reads the transcript back out of storage.+ 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(() => {+ // The worker is down; the session is saved and usable, it just has no name yet.+ });+ }, [persist, flush]);++ // Only the falling edge — `active` also arrives on every reconnect, and re-settling on those+ // would re-query the tab and re-check the name for a conversation that has not moved.+ const wasRunning = useRef(false);+ useEffect(() => {+ if (wasRunning.current && !running) void settle();+ wasRunning.current = running;+ }, [running, settle]);++ /** False when there was no live port to carry the command, so the caller can say so. */+ const post = useCallback((command: RunCommand): boolean => {+ const open = port.current;+ if (!open) return false;+ try {+ open.postMessage(command);+ return true;+ } catch {+ // Disconnected between the check and the send.+ port.current = null;+ return false;+ }+ }, []);++ const lost = useCallback((text: string) => {+ setRunning(false);+ setItems((previous) => [...previous, { kind: 'notice', id: nextId(), tone: 'error', text }]);+ }, []);const send = useCallback((text: string) => {@@ -84,31 +230,82 @@ export function useRun(): Run {if (!trimmed) return;setItems((previous) => [...previous, { kind: 'user', id: nextId(), text: trimmed }]);setRunning(true);+ session.current.turns += 1;+ // The stored id, so a conversation reopened from the library carries on instead of starting+ // over. Undefined until the daemon has confirmed one: an id Claude Code never created is not+ // resumable, and sending it would fail every run from here on.+ const claudeSessionId = session.current.claudeSessionId;+ const failed = () => lost('Lost the connection to the extension — that never went anywhere. Try again.');// Resolve the tab here rather than in the worker: this page belongs to one window, so// `currentWindow` is unambiguous, and the worker's one-run-at-a-time guard stays sync.// The id travels too — a mapping run pins itself to this tab for its whole crawl.void browser.tabs.query({ active: true, currentWindow: true })- .then(([tab]) =>- post({- op: 'instruct',- text: trimmed,- context: tab?.url ? { url: tab.url, tabId: tab.id } : undefined,- }),- )- .catch(() => post({ op: 'instruct', text: trimmed }));+ .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, claudeSessionId } : { claudeSessionId };+ if (!post({ op: 'instruct', text: trimmed, context })) failed();+ })+ .catch(() => {+ if (!post({ op: 'instruct', text: trimmed, context: { claudeSessionId } })) failed();+ });},- [post],+ [post, lost],);const clear = useCallback(() => {+ // Save what is there before letting go of it, then mint a new conversation. The daemon is told+ // too: it keeps its own copy of the session id as a fallback for callers that send none.+ void flush().then(() => {+ session.current = freshSession();+ setSessionId(session.current.id);+ });setItems([]);post({ op: 'reset' });- }, [post]);+ }, [post, flush]);++ const restore = useCallback(+ async (sessionId: string) => {+ // Swapping the transcript out from under a live run would leave its remaining events — and+ // its reply, mid-sentence — appending to the conversation just reopened, and saved into it.+ if (running) return;+ const meta = (await listSessions()).find((s) => s.id === sessionId);+ if (!meta) return;+ const transcript = await readTranscript(sessionId);+ await flush();++ // Only the panel-owned fields are adopted; the title and its bookkeeping stay the worker's.+ 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.' }],+ );+ // Deliberately no `reset`: that would tell the daemon to forget the very conversation being+ // restored. Continuity comes from `claudeSessionId` riding along on the next instruction.++ // Put the tab back where the conversation was left. Routed through the bridge so it gets the+ // in-page-then-tabs-API fallback in `invoke.ts`, rather than reimplementing it here.+ 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(() => {+ // Restoring the transcript is the point; a tab that would not move is not worth failing.+ });+ }+ },+ [flush, running],+ );return {items,running,+ sessionId,send,draft,// The `@` prefix is not decoration: the daemon refuses to enter mapping mode without it, so@@ -123,7 +320,11 @@ export function useRun(): Run {discardMap: useCallback(() => {if (draft) post({ op: 'discardMap', stagingId: draft.stagingId });}, [draft, post]),- cancel: useCallback(() => post({ op: 'cancel' }), [post]),+ // The worker answers every cancel, one way or another (see `stopRun`), so the button never+ // has to guess. It only decides for itself when there is no port left to ask through.+ cancel: useCallback(() => {+ if (!post({ op: 'cancel' })) lost('Lost the connection to the extension, so this run is no longer being watched.');+ }, [post, lost]),decide: useCallback((toolId: string, allow: boolean) => {setItems((previous) => patchTool(previous, toolId, { awaiting: false }));@@ -132,9 +333,28 @@ export function useRun(): Run {[post],),clear,+ restore,};}+/** The host of a URL for the session's site indication, or null when it has none to give. */+function hostOf(url: string): string | null {+ try {+ return new URL(url).host || null;+ } catch {+ return null;+ }+}++/** A URL's scheme, or the empty string when it does not parse — never throws at a call site. */+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': {@@ -169,6 +389,10 @@ function reduce(items: RunItem[], event: RunEvent): RunItem[] {case 'toolResult':return patchTool(items, event.toolId, { ok: event.ok, summary: event.summary, awaiting: false });+ // Bookkeeping for the session record, handled by the port listener. Nothing to draw.+ case 'session':+ return items;+case 'done':// `end_turn` is the ordinary ending and needs no announcement; anything else does.return event.stopReason === 'end_turn'@@ -184,5 +408,7 @@ function patchTool(items: RunItem[], toolId: string, patch: Partial<Extract<RunIreturn items.map((item) => (item.kind === 'tool' && item.id === toolId ? { ...item, ...patch } : item));}-let counter = 0;-const nextId = () => `item-${counter++}`;+// A uuid rather than a counter: rows now outlive the page that made them, so a restored transcript+// and the run that follows it are two producers of ids at once, and a counter would have the second+// one reusing the first's — patching, or replacing, a row from the conversation just reopened.+const nextId = () => crypto.randomUUID();diff --git a/lib/bridge/use-stored-sessions.ts b/lib/bridge/use-stored-sessions.tsnew file mode 100644index 0000000..e6b3753--- /dev/null+++ b/lib/bridge/use-stored-sessions.ts@@ -0,0 +1,32 @@+import { useEffect, useState } from 'react';+import { browser } from 'wxt/browser';+import { SESSIONS_INDEX_KEY, type StoredSessionMeta } from './session-store';++/**+ * The saved-conversation index, kept live through `storage.local.onChanged` so the history list+ * re-renders as the current session grows and as the background worker writes each title back.+ */+export function useStoredSessions(): StoredSessionMeta[] {+ const [sessions, setSessions] = useState<StoredSessionMeta[]>([]);++ useEffect(() => {+ let live = true;+ void browser.storage.local.get(SESSIONS_INDEX_KEY).then((stored) => {+ const list = stored[SESSIONS_INDEX_KEY];+ if (live && Array.isArray(list)) setSessions(list as StoredSessionMeta[]);+ });+ const listener = (changes: Record<string, { newValue?: unknown }>) => {+ if (SESSIONS_INDEX_KEY in changes) {+ const next = changes[SESSIONS_INDEX_KEY].newValue;+ setSessions(Array.isArray(next) ? (next as StoredSessionMeta[]) : []);+ }+ };+ browser.storage.local.onChanged.addListener(listener);+ return () => {+ live = false;+ browser.storage.local.onChanged.removeListener(listener);+ };+ }, []);++ return sessions;+}