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): funnel every instruction through the fast path first
Shahriarfa30594e0b97
diff --git a/components/run-timeline.tsx b/components/run-timeline.tsxindex a050930..12716af 100644--- a/components/run-timeline.tsx+++ b/components/run-timeline.tsx@@ -1,4 +1,4 @@-import { AlertTriangle, Bot, Check, Info, User, Wrench, X } from 'lucide-react';+import { AlertTriangle, Bot, Check, Info, User, Wrench, X, Zap } from 'lucide-react';import { Button } from '@/components/ui/button';import type { RunItem } from '@/lib/bridge/use-run';@@ -64,6 +64,9 @@ function ToolRow({<div className="flex items-center gap-2 text-xs"><StatusIcon ok={item.ok} awaiting={item.awaiting} /><span className="font-mono text-muted-foreground">{item.action.replace(/^page\./, '')}</span>+ {item.source === 'local' && (+ <Zap className="size-3 shrink-0 text-amber-500" aria-label="Handled in the browser" />+ )}{item.summary && (<span className={cn('truncate', item.ok === false ? 'text-destructive' : 'text-muted-foreground')}>{item.summary}diff --git a/lib/bridge/fast-path.ts b/lib/bridge/fast-path.tsnew file mode 100644index 0000000..8f76b7d--- /dev/null+++ b/lib/bridge/fast-path.ts@@ -0,0 +1,47 @@+import type { RunEvent } from '@/lib/actions/protocol';+import { routeIntent } from '@/lib/intent';+import { invokeForHarness } from './invoke';++/**+ * Try to carry out an instruction here in the browser, without waking the agent.+ *+ * Most of what people say to a voice assistant on a page is one unambiguous action — back,+ * reload, scroll down, open github.com, click Sign in. Sending those out to the daemon to be+ * spawned as a Claude Code run costs a socket round trip and several seconds of thinking to+ * reach a tool call the extension could have made in milliseconds. `routeIntent` scores the+ * utterance against a fixed grammar; only a confident, single-step, non-consequential match+ * runs here. Everything else — questions, multi-step asks, anything the grammar is unsure of+ * — returns false and takes the normal path.+ *+ * Returns true when the instruction is fully dealt with. A *failed* local action returns+ * false on purpose: "click Sign in" that finds no such control is exactly the case where the+ * agent, which can look at the page first, does better. The failed step stays on the+ * timeline so the handover is visible rather than mysterious.+ */+export async function tryFastPath(text: string, emit: (event: RunEvent) => void): Promise<boolean> {+ const routing = routeIntent(text);+ if (routing.decision !== 'act') return false;++ const { action, input, label, ruleId, score } = routing.intent;+ // A uuid rather than a counter: the worker is torn down and restarted routinely, and a+ // panel that outlives it must never see a fresh step reuse an old row's id.+ const toolId = `local-${crypto.randomUUID()}`;+ emit({ kind: 'tool', toolId, action, input, source: 'local' });++ const startedAt = Date.now();+ const result = await invokeForHarness(action, input);+ const elapsed = Date.now() - startedAt;+ emit({+ kind: 'toolResult',+ toolId,+ ok: result.ok,+ // The timing is the point of this path — show it, so a slow one is obvious.+ summary: result.ok ? `${label} · ${elapsed} ms` : `${result.error.code}: ${result.error.message}`,+ });++ if (!result.ok) {+ console.debug(`[voicelink] fast path ${ruleId} (${score}) failed, escalating:`, result.error.code);+ return false;+ }+ return true;+}diff --git a/lib/bridge/run-port.ts b/lib/bridge/run-port.tsindex 896b0d2..cb6dc52 100644--- a/lib/bridge/run-port.ts+++ b/lib/bridge/run-port.ts@@ -1,9 +1,24 @@import { browser, type Browser } from 'wxt/browser';-import type { RunEvent } from '@/lib/actions/protocol';-import { cancelRun, onRunEvent, resetConversation, sendDecision, sendInstruction } from './socket';+import type { RunContext, RunEvent } from '@/lib/actions/protocol';+import type { SiteMapDraft } from '@/lib/skills/site-map';+import { tryFastPath } from './fast-path';+import { recordGeneratedSkill } from './skill-store';+import {+ activateSiteMap,+ cancelRun,+ discardSiteMap,+ onRunEvent,+ onSiteMapDraft,+ resetConversation,+ sendDecision,+ sendInstruction,+} from './socket';export const RUN_PORT = 'voicelink/run';+/** Correlation id for events the extension produced itself, with no run behind them. */+const LOCAL_RUN = 'local';+/*** How long a run keeps going after the last extension page stops watching. Long enough for the* popup to hand off to the side panel it just opened, short enough that nothing drives the@@ -13,20 +28,32 @@ const UNWATCHED_GRACE_MS = 10_000;/** Extension page → background worker. */export type RunCommand =- | { op: 'instruct'; text: string }+ /** `context` names the tab the instruction was typed against; the daemon routes site skills on it. */+ | { op: 'instruct'; text: string; context?: RunContext }| { op: 'cancel' }| { op: 'decision'; toolId: string; allow: boolean }- | { op: 'reset' };+ | { op: 'reset' }+ /** Arm or bin a staged site map. Both outlive the run that produced them. */+ | { op: 'activateMap'; stagingId: string; exactHost?: boolean }+ | { op: 'discardMap'; stagingId: string };/** Background worker → extension pages. */export type RunMessage =| { op: 'event'; runId: string; event: RunEvent }/** Sent on connect, and whenever a run starts or ends, so a late page knows where it stands. */- | { op: 'active'; runId: string | null };+ | { op: 'active'; runId: string | null }+ /** A mapping run produced a map; the panel shows it for review. */+ | { op: 'mapDraft'; draft: SiteMapDraft }+ /** The staged map is gone — armed or binned — so the review sheet can close. */+ | { op: 'mapSettled'; stagingId: string; ok: boolean; message?: string };const ports = new Set<Browser.runtime.Port>();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;+/** The staged map nobody has decided on yet. Replayed to a page that connects late. */+let pendingDraft: SiteMapDraft | null = null;/*** Bridge the daemon's run events to whichever extension pages are open. A one-shot@@ -38,11 +65,19 @@ export function serveRunPorts(): void {broadcast({ op: 'event', runId, event });});+ // A staged map outlives its run, so the worker keeps the last one and replays it to a page+ // that connects afterwards — closing the panel mid-crawl must not lose the review.+ onSiteMapDraft((_runId, draft) => {+ pendingDraft = draft;+ broadcast({ op: 'mapDraft', draft });+ });+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 });port.onMessage.addListener((message) => handle(message as RunCommand));port.onDisconnect.addListener(() => {@@ -56,8 +91,8 @@ 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) return;- setActiveRun(sendInstruction(command.text));+ if (activeRunId || actingLocally) return;+ void instruct(command.text, command.context);return;case 'cancel':if (activeRunId) cancelRun(activeRunId);@@ -65,12 +100,77 @@ function handle(command: RunCommand): void {case 'decision':if (activeRunId) sendDecision(activeRunId, command.toolId, command.allow);return;+ case 'activateMap':+ case 'discardMap': {+ const draft = pendingDraft;+ const settle =+ command.op === 'activateMap'+ ? activateSiteMap(command.stagingId, command.exactHost)+ : discardSiteMap(command.stagingId);+ void settle.then((result) => {+ // Note it in the extension's own index so it appears beside uploads. Metadata only: the+ // body stays on disk, so nothing here can ever re-push over the daemon's copy.+ if (result.ok && command.op === 'activateMap' && draft?.stagingId === command.stagingId) {+ void recordGeneratedSkill({+ name: draft.name,+ domain: command.exactHost ? draft.host : draft.domain,+ directory: draft.directory,+ pages: draft.pages,+ generatedAt: draft.generatedAt,+ });+ }+ if (pendingDraft?.stagingId === command.stagingId) pendingDraft = null;+ broadcast({+ op: 'mapSettled',+ stagingId: command.stagingId,+ ok: result.ok,+ message: result.ok ? undefined : `${result.error.code}: ${result.error.message}`,+ });+ });+ return;+ }case 'reset':resetConversation();return;}}+/**+ * The single funnel every instruction passes through, spoken or typed, from either surface.+ * The local grammar gets first refusal; only what it declines — or attempts and fails —+ * becomes a daemon run. Callers see one `active` message either way, so a page cannot tell+ * the two apart except by the `source` marker on the steps.+ */+async function instruct(text: string, context?: RunContext): Promise<void> {+ actingLocally = true;+ try {+ if (await tryFastPath(text, (event) => broadcast({ op: 'event', runId: LOCAL_RUN, event }))) {+ // 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);+ } finally {+ actingLocally = false;+ }++ const runId = sendInstruction(text, context);+ 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);+}+function setActiveRun(runId: string | null): void {activeRunId = runId;if (runId) clearTimeout(unwatchedTimer);diff --git a/lib/bridge/use-run.ts b/lib/bridge/use-run.tsindex c80531c..96e5a65 100644--- a/lib/bridge/use-run.ts+++ b/lib/bridge/use-run.ts@@ -1,6 +1,7 @@import { useCallback, useEffect, useRef, useState } from 'react';import { browser, type Browser } from 'wxt/browser';import 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';/** One rendered row of the transcript. Tool rows mutate in place as their result arrives. */@@ -17,6 +18,8 @@ export type RunItem =ok?: boolean;/** True while the run is blocked waiting for the user to allow or deny this call. */awaiting?: boolean;+ /** Set when the extension took this step itself, without involving the agent. */+ source?: 'local';};export interface Run {@@ -26,6 +29,12 @@ export interface Run {cancel: () => void;decide: (toolId: string, allow: boolean) => void;clear: () => 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. */+ mapSite: () => void;+ activateMap: (exactHost?: boolean) => void;+ discardMap: () => void;}/**@@ -35,6 +44,7 @@ export interface Run {export function useRun(): 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);useEffect(() => {@@ -44,7 +54,16 @@ export function useRun(): Run {connected.onMessage.addListener((message) => {const runMessage = message as RunMessage;if (runMessage.op === 'active') setRunning(runMessage.runId !== null);- else setItems((previous) => reduce(previous, runMessage.event));+ 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 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(() => {@@ -65,7 +84,19 @@ export function useRun(): Run {if (!trimmed) return;setItems((previous) => [...previous, { kind: 'user', id: nextId(), text: trimmed }]);setRunning(true);- post({ op: 'instruct', text: trimmed });+ // 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 }));},[post],);@@ -79,6 +110,19 @@ export function useRun(): Run {items,running,send,+ draft,+ // The `@` prefix is not decoration: the daemon refuses to enter mapping mode without it, so+ // an overheard phrase can never start a ten-minute crawl of the user's foreground tab.+ mapSite: useCallback(() => send(`@${SITE_MAPPER_SKILL} map this site`), [send]),+ activateMap: useCallback(+ (exactHost?: boolean) => {+ if (draft) post({ op: 'activateMap', stagingId: draft.stagingId, exactHost });+ },+ [draft, post],+ ),+ discardMap: useCallback(() => {+ if (draft) post({ op: 'discardMap', stagingId: draft.stagingId });+ }, [draft, post]),cancel: useCallback(() => post({ op: 'cancel' }), [post]),decide: useCallback((toolId: string, allow: boolean) => {@@ -93,8 +137,15 @@ export function useRun(): Run {function reduce(items: RunItem[], event: RunEvent): RunItem[] {switch (event.kind) {- case 'started':- return [...items, { kind: 'notice', id: nextId(), tone: 'info', text: `Loaded skill: ${event.skill}` }];+ case 'started': {+ // Name the site notes too: an uploaded skill changes what the agent does, so its being+ // in play should never be invisible.+ 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': {// Deltas append to the assistant row still being written; a tool call between two@@ -107,7 +158,10 @@ function reduce(items: RunItem[], event: RunEvent): RunItem[] {}case 'tool':- return [...items, { kind: 'tool', id: event.toolId, action: event.action, input: event.input }];+ return [+ ...items,+ { kind: 'tool', id: event.toolId, action: event.action, input: event.input, source: event.source },+ ];case 'approval':return patchTool(items, event.toolId, { awaiting: true });