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): route harness invokes to the active tab
Shahriarea5741759279
diff --git a/lib/bridge/file-store.ts b/lib/bridge/file-store.tsnew file mode 100644index 0000000..bda0619--- /dev/null+++ b/lib/bridge/file-store.ts@@ -0,0 +1,109 @@+import { browser } from 'wxt/browser';+import { analyzeFile } from './socket';++/**+ * The extension's file repository, kept entirely in `browser.storage.local` (the+ * `unlimitedStorage` permission lifts the default quota). Two shapes, split so a status or+ * summary update never rewrites the file bytes:+ *+ * 'voicelink:files' -> StoredFileMeta[] the small, reactive index the UI and+ * page.listFiles read+ * 'voicelink:file:<id>' -> StoredFileBytes base64 bytes, read only when attaching+ *+ * Content-script actions cannot read this store directly (they run in the page's origin), so+ * page.listFiles / page.attachFile are resolved in the background via `lib/bridge/invoke.ts`,+ * which imports the readers here.+ */++/** The reactive metadata index — never holds file bytes. */+export const FILES_INDEX_KEY = 'voicelink:files';++const fileBytesKey = (id: string) => `voicelink:file:${id}`;++export type FileStatus = 'pending' | 'ready' | 'error';++export interface StoredFileMeta {+ id: string;+ name: string;+ mime: string;+ size: number;+ status: FileStatus;+ /** Present once the daemon has summarized the file. */+ summary?: string;+ /** Present when analysis failed. */+ error?: string;+ addedAt: number;+}++export interface StoredFileBytes {+ id: string;+ name: string;+ mime: string;+ /** Raw base64, with no `data:` prefix. */+ content: string;+}++/** The file index, or an empty list when nothing is stored. */+export async function listMeta(): Promise<StoredFileMeta[]> {+ const stored = await browser.storage.local.get(FILES_INDEX_KEY);+ const list = stored[FILES_INDEX_KEY];+ return Array.isArray(list) ? (list as StoredFileMeta[]) : [];+}++async function writeIndex(list: StoredFileMeta[]): Promise<void> {+ await browser.storage.local.set({ [FILES_INDEX_KEY]: list });+}++/** Store a file: its bytes under their own key, its metadata at the head of the index. */+export async function putFile(meta: StoredFileMeta, content: string): Promise<void> {+ const bytes: StoredFileBytes = { id: meta.id, name: meta.name, mime: meta.mime, content };+ await browser.storage.local.set({ [fileBytesKey(meta.id)]: bytes });+ const list = await listMeta();+ await writeIndex([meta, ...list.filter((f) => f.id !== meta.id)]);+}++/** The raw bytes for a stored file, or null when the id is unknown. */+export async function readBytes(id: string): Promise<StoredFileBytes | null> {+ const key = fileBytesKey(id);+ const stored = await browser.storage.local.get(key);+ const bytes = stored[key] as StoredFileBytes | undefined;+ return bytes && typeof bytes.content === 'string' ? bytes : null;+}++/** Patch one file's metadata in place, leaving its bytes untouched. */+export async function updateMeta(id: string, patch: Partial<StoredFileMeta>): Promise<void> {+ const list = await listMeta();+ await writeIndex(list.map((f) => (f.id === id ? { ...f, ...patch } : f)));+}++/** Remove a file and its bytes. */+export async function removeFile(id: string): Promise<void> {+ await browser.storage.local.remove(fileBytesKey(id));+ const list = await listMeta();+ await writeIndex(list.filter((f) => f.id !== id));+}++/**+ * The daemon round-trip for a stored file: read its bytes, ask the daemon to summarize, and+ * fold the result back into the index. Called from the background worker (it owns the socket),+ * so the summary lands even if the side panel that started it has since closed.+ */+export async function analyzeStoredFile(fileId: string): Promise<void> {+ const bytes = await readBytes(fileId);+ if (!bytes) {+ await updateMeta(fileId, { status: 'error', error: 'File bytes are missing from storage.' });+ return;+ }+ const meta = (await listMeta()).find((f) => f.id === fileId);+ const result = await analyzeFile({+ name: bytes.name,+ mime: bytes.mime,+ size: meta?.size ?? 0,+ content: bytes.content,+ });+ if (result.ok) {+ await updateMeta(fileId, { status: 'ready', summary: result.data.summary, error: undefined });+ } else {+ await updateMeta(fileId, { status: 'error', error: `${result.error.code}: ${result.error.message}` });+ }+}diff --git a/lib/bridge/invoke.ts b/lib/bridge/invoke.tsnew file mode 100644index 0000000..1a1026d--- /dev/null+++ b/lib/bridge/invoke.ts@@ -0,0 +1,156 @@+import { browser } from 'wxt/browser';+import { z } from 'zod';+import { invokeInTab } from '@/lib/actions/client';+import { ActionError } from '@/lib/actions/core';+import { attachFile } from '@/lib/actions/page/attach-file';+import { listFiles } from '@/lib/actions/page/list-files';+import { navigate, resolveNavigation, type NavigateInput } from '@/lib/actions/page/navigate';+import { screenshot } from '@/lib/actions/page/screenshot';+import { failure, success, type ActionResult } from '@/lib/actions/protocol';+import { listMeta, readBytes } from '@/lib/bridge/file-store';+import { screenshotTab } from '@/lib/bridge/screenshot';++const LOAD_TIMEOUT_MS = 10_000;++/**+ * Run an action in the active tab on behalf of an outside caller (the MCP daemon or the+ * side panel). Same path as `invokeInActiveTab`, except for navigation — see below.+ */+export async function invokeForHarness(action: string, input?: unknown): Promise<ActionResult> {+ // The file repository lives in extension storage, which a content script cannot read, so both+ // file actions resolve here. listFiles needs no tab at all — it only reads storage.+ if (action === listFiles.name) return listStoredFiles(input);++ const [tab] = await browser.tabs.query({ active: true, currentWindow: true });+ if (tab?.id == null) return failure('NO_ACTIVE_TAB', 'No active tab to control');+ // Navigation and screenshots are special-cased: both need background-only APIs (the tabs API,+ // captureVisibleTab) that a content script cannot reach, so they run here rather than in-page.+ if (action === navigate.name) return navigateTab(tab.id, input);+ if (action === screenshot.name) return screenshotTab({ id: tab.id, windowId: tab.windowId }, input);+ // attachFile reads the stored bytes here (a page cannot), then runs the DOM write in-page.+ if (action === attachFile.name) return attachStoredFile(tab.id, input);+ return invokeInTab(tab.id, action, input);+}++/** page.listFiles: read the file index from extension storage; hand back metadata, never bytes. */+async function listStoredFiles(input: unknown): Promise<ActionResult> {+ const filter = (input as { nameContains?: unknown } | undefined)?.nameContains;+ const needle = typeof filter === 'string' ? filter.toLowerCase() : null;+ const files = (await listMeta())+ .filter((f) => !needle || f.name.toLowerCase().includes(needle))+ .map(({ id, name, mime, size, status, summary, addedAt }) => ({ id, name, mime, size, status, summary, addedAt }));+ return success({ files });+}++/** page.attachFile: fetch the stored bytes here, then hand them to the in-page DOM action. */+async function attachStoredFile(tabId: number, input: unknown): Promise<ActionResult> {+ const { fileId, target } = (input ?? {}) as { fileId?: unknown; target?: unknown };+ if (typeof fileId !== 'string' || !fileId) {+ return failure('INVALID_INPUT', 'attachFile needs a "fileId" from page.listFiles.');+ }+ const bytes = await readBytes(fileId);+ if (!bytes) {+ return failure('FILE_NOT_FOUND', `No stored file with id "${fileId}". Call page.listFiles to see stored files.`);+ }+ return invokeInTab(tabId, attachFile.name, {+ fileId,+ target,+ name: bytes.name,+ mime: bytes.mime,+ content: bytes.content,+ });+}++/** Chrome's wording for "no listener was there", i.e. the message never reached a page. */+const NO_CONTENT_SCRIPT = 'Receiving end does not exist';++/**+ * Navigate the active tab, preferring the in-page action and falling back to the tabs API.+ *+ * In-page navigation is authoritative and pushes a history entry, so `back` works+ * afterwards — but it cannot run where no content script does, and `tabs.update` works+ * everywhere but *replaces* the current history entry. `invokeInTab` already injects the+ * content script into tabs that merely lack it (opened before the extension loaded), so by+ * the time "Receiving end does not exist" surfaces here the page genuinely refuses content+ * scripts (a new tab, a chrome:// page) and the tabs API is the only route.+ *+ * Falling back is only safe when the action provably never ran. Chrome distinguishes the+ * two failures: "Receiving end does not exist" is a pre-delivery error (no content script,+ * nothing happened), while "message port closed" means the page received it and then+ * unloaded — already navigating, so re-issuing would navigate twice.+ */+async function navigateTab(tabId: number, input: unknown): Promise<ActionResult> {+ const inPage = await invokeInTab(tabId, navigate.name, input);+ if (inPage.ok) {+ return success({ ...(inPage.data as object), loaded: await watchForLoad(tabId).settled });+ }+ if (inPage.error.code !== 'TAB_UNREACHABLE') return inPage;+ if (!inPage.error.message.includes(NO_CONTENT_SCRIPT)) {+ // Delivered, then the page unloaded: the navigation is already under way.+ return success({ navigating: true, loaded: await watchForLoad(tabId).settled });+ }+ return navigateViaTabsApi(tabId, input);+}++async function navigateViaTabsApi(tabId: number, input: unknown): Promise<ActionResult> {+ // Same validation and wording as `dispatch`, which the in-page path would have used.+ const parsed = navigate.input.safeParse(input ?? {});+ if (!parsed.success) return failure('INVALID_INPUT', z.prettifyError(parsed.error));++ let plan;+ try {+ // No base URL: relative navigation stays unsupported by choice, so the daemon never has+ // to read the tab's URL to resolve one (host_permissions would now allow that read).+ plan = resolveNavigation(parsed.data as NavigateInput);+ } catch (error) {+ return error instanceof ActionError+ ? failure(error.code, error.message)+ : failure('ACTION_FAILED', String(error));+ }++ const loaded = watchForLoad(tabId);+ try {+ if (plan.kind === 'url') await browser.tabs.update(tabId, { url: plan.href });+ else if (plan.action === 'reload') await browser.tabs.reload(tabId);+ else if (plan.action === 'back') await browser.tabs.goBack(tabId);+ else await browser.tabs.goForward(tabId);+ } catch (error) {+ loaded.cancel();+ const detail = error instanceof Error ? error.message : String(error);+ // goBack/goForward reject when there is nowhere to go, and Chrome's wording does not+ // say which direction failed — name it so the caller can tell what to try instead.+ return failure(+ 'ACTION_FAILED',+ plan.kind === 'history' && plan.action !== 'reload'+ ? `Cannot go ${plan.action}: this tab has no ${plan.action === 'back' ? 'previous' : 'next'} page in its history (${detail})`+ : detail,+ );+ }++ const completed = await loaded.settled;+ return success(+ plan.kind === 'url'+ ? { navigatedTo: plan.href, loaded: completed }+ : { performed: plan.action, loaded: completed },+ );+}++function watchForLoad(tabId: number) {+ let settle!: (loaded: boolean) => void;+ const settled = new Promise<boolean>((resolve) => {+ settle = resolve;+ });+ const finish = (loaded: boolean) => {+ browser.tabs.onUpdated.removeListener(listener);+ clearTimeout(timer);+ settle(loaded);+ };+ // Only `status` is needed to know the load finished; we deliberately ignore `changeInfo.url`+ // (now readable under host_permissions) so this stays a pure load-completion watcher.+ const listener = (updatedTabId: number, changeInfo: { status?: string }) => {+ if (updatedTabId === tabId && changeInfo.status === 'complete') finish(true);+ };+ const timer = setTimeout(() => finish(false), LOAD_TIMEOUT_MS);+ browser.tabs.onUpdated.addListener(listener);+ return { settled, cancel: () => finish(false) };+}diff --git a/lib/bridge/screenshot.ts b/lib/bridge/screenshot.tsnew file mode 100644index 0000000..98e5d19--- /dev/null+++ b/lib/bridge/screenshot.ts@@ -0,0 +1,219 @@+import { browser } from 'wxt/browser';+import { invokeInTab } from '@/lib/actions/client';+import { ActionError } from '@/lib/actions/core';+import { failure, success, type ActionResult } from '@/lib/actions/protocol';++/**+ * Background half of `page.screenshot`. The action runs in the page only to *measure* and hand+ * back a capture plan (see `lib/actions/page/screenshot.ts`); the pixels are produced here,+ * because only the background worker can call `chrome.tabs.captureVisibleTab`. We scroll the tab+ * one viewport at a time, capture each, and paint every viewport onto one `OffscreenCanvas` at+ * its region-relative offset — which stitches a full page *and* crops an element for free, since+ * the canvas is sized to the requested region and clips whatever overflows it.+ *+ * Routed from `invokeForHarness` exactly like navigation, the other cross-context action.+ *+ * Geometry is driven by the *actual* captured bitmap, not `window.devicePixelRatio`: the real+ * device scale (`bitmap.width / viewport.w`) is exact under browser zoom and fractional DPI,+ * where trusting `dpr` leaves seam lines between tiles. The output canvas is sized to the final+ * (downscaled) dimensions and each tile is drawn scaled to fit — so a very tall or HiDPI page is+ * never allocated as an over-limit backing store.+ */++interface CapturePlan {+ mode: 'fullPage' | 'viewport' | 'element';+ dpr: number;+ viewport: { w: number; h: number };+ page: { w: number; h: number };+ region: { x: number; y: number; w: number; h: number };+ scroll: { x: number; y: number };+ format: 'png' | 'jpeg';+ quality?: number;+ maxLongSide: number;+}++/** Chrome throttles captureVisibleTab to ~2/sec; stay under it and let content settle per tile. */+const CAPTURE_INTERVAL_MS = 500;+/** Total viewports we will ever tile — bounds wall-clock and memory on runaway/huge pages. */+const MAX_TILES = 48;+/** Chrome refuses to allocate a canvas past these; keep the backing store safely within them. */+const MAX_CANVAS_SIDE = 16384;+const MAX_CANVAS_AREA = MAX_CANVAS_SIDE * MAX_CANVAS_SIDE;++export async function screenshotTab(+ tab: { id: number; windowId?: number },+ input?: unknown,+): Promise<ActionResult> {+ // Run the action in-page purely to measure — this yields the capture plan, no side effects.+ const planned = await invokeInTab(tab.id, 'page.screenshot', input);+ if (!planned.ok) return planned;+ const plan = planned.data as CapturePlan;++ try {+ return success(await capture(tab, plan));+ } catch (error) {+ if (error instanceof ActionError) return failure(error.code, error.message);+ return failure('CAPTURE_FAILED', error instanceof Error ? error.message : String(error));+ } finally {+ // Put the page back where the user had it, whether we succeeded or threw.+ void invokeInTab(tab.id, 'page.scrollTo', {+ position: { x: plan.scroll.x, y: plan.scroll.y },+ behavior: 'instant',+ });+ }+}++async function capture(+ tab: { id: number; windowId?: number },+ plan: CapturePlan,+): Promise<{ format: string; width: number; height: number; dataUrl: string; truncated?: boolean }> {+ const { viewport, format, quality, maxLongSide } = plan;+ const region = { ...plan.region };++ // Clamp the region so we never tile more than MAX_TILES viewports — this bounds BOTH axes, so a+ // wide page can't multiply the row cap into hundreds of captures. If clipped, the canvas matches+ // what we actually capture (no blank band) and we flag the shot as partial.+ const cols = Math.max(1, Math.ceil(region.w / viewport.w));+ const maxRows = Math.max(1, Math.floor(MAX_TILES / Math.min(cols, MAX_TILES)));+ let truncated = false;+ if (cols > MAX_TILES) {+ region.w = MAX_TILES * viewport.w;+ truncated = true;+ }+ if (Math.ceil(region.h / viewport.h) > maxRows) {+ region.h = maxRows * viewport.h;+ truncated = true;+ }++ const xs = tileStarts(region.x, region.w, viewport.w);+ const ys = tileStarts(region.y, region.h, viewport.h);++ let ctx: OffscreenCanvasRenderingContext2D | null = null;+ let out: OffscreenCanvas | null = null;+ let scale = 1; // CSS px → output px (device scale × downscale); set from the first real capture+ let outScale = 1; // downscale applied to each captured bitmap when painting it++ let first = true;+ for (const y of ys) {+ for (const x of xs) {+ // Scroll may clamp near the edges; use where the page *actually* landed to place the tile.+ const scrolled = await invokeInTab(tab.id, 'page.scrollTo', {+ position: { x, y },+ behavior: 'instant',+ });+ if (!scrolled.ok) throw new ActionError(scrolled.error.message, scrolled.error.code);+ const at = scrolled.data as { scrollX: number; scrollY: number };++ // Settle the freshly-scrolled tile AND respect the capture quota — after the scroll, before+ // the capture, so lazy images and reveal animations have a beat to paint. The first tile,+ // already on screen, needs no wait.+ if (!first) await delay(CAPTURE_INTERVAL_MS);+ first = false;++ const bitmap = await captureViewport(tab.windowId, format, quality);++ // Size the output canvas from the first *actual* bitmap: derive the true device scale, apply+ // the maxLongSide cap and Chrome's hard limits, and allocate at the final size directly.+ if (!out) {+ const capScale = bitmap.width / viewport.w || plan.dpr || 1;+ outScale = fitScale(region.w * capScale, region.h * capScale, maxLongSide);+ scale = capScale * outScale;+ out = new OffscreenCanvas(+ Math.max(1, Math.round(region.w * scale)),+ Math.max(1, Math.round(region.h * scale)),+ );+ ctx = out.getContext('2d');+ if (!ctx) {+ bitmap.close();+ throw new ActionError('OffscreenCanvas 2D context unavailable', 'CAPTURE_FAILED');+ }+ }++ // Draw the whole viewport at its scaled offset within the region; the canvas clips overflow,+ // and consecutive tiles abut exactly because pitch and draw-size share the same scale.+ ctx!.drawImage(+ bitmap,+ (at.scrollX - region.x) * scale,+ (at.scrollY - region.y) * scale,+ bitmap.width * outScale,+ bitmap.height * outScale,+ );+ bitmap.close();+ }+ }++ if (!out) throw new ActionError('Nothing was captured', 'CAPTURE_FAILED');+ return encode(out, format, quality, truncated);+}++async function encode(+ canvas: OffscreenCanvas,+ format: 'png' | 'jpeg',+ quality: number | undefined,+ truncated: boolean,+): Promise<{ format: string; width: number; height: number; dataUrl: string; truncated?: boolean }> {+ const mime = format === 'jpeg' ? 'image/jpeg' : 'image/png';+ const blob = await canvas.convertToBlob(+ format === 'jpeg' ? { type: mime, quality: (quality ?? 90) / 100 } : { type: mime },+ );+ const dataUrl = await blobToDataUrl(blob, mime);+ return { format, width: canvas.width, height: canvas.height, dataUrl, ...(truncated ? { truncated } : {}) };+}++/** Largest scale ≤ 1 that keeps the long side under maxLongSide and the buffer within Chrome's limits. */+function fitScale(deviceW: number, deviceH: number, maxLongSide: number): number {+ const longest = Math.max(deviceW, deviceH, 1);+ const byLong = Math.min(maxLongSide, MAX_CANVAS_SIDE) / longest;+ const byArea = Math.sqrt(MAX_CANVAS_AREA / Math.max(deviceW * deviceH, 1));+ return Math.min(1, byLong, byArea);+}++/** captureVisibleTab throws on pages that forbid capture (chrome://, the Web Store, the PDF viewer). */+async function captureViewport(+ windowId: number | undefined,+ format: 'png' | 'jpeg',+ quality: number | undefined,+): Promise<ImageBitmap> {+ for (let attempt = 0; ; attempt++) {+ try {+ const dataUrl =+ windowId == null+ ? await browser.tabs.captureVisibleTab({ format, quality })+ : await browser.tabs.captureVisibleTab(windowId, { format, quality });+ return createImageBitmap(await (await fetch(dataUrl)).blob());+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ // Chrome's per-second capture quota is transient — back off once and try again.+ if (attempt < 2 && /MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND/i.test(message)) {+ await delay(CAPTURE_INTERVAL_MS);+ continue;+ }+ throw new ActionError(+ `Cannot capture this tab (${message}) — it may be a chrome:// page, the Web Store, or a PDF, which browsers refuse to screenshot`,+ 'CAPTURE_UNSUPPORTED',+ );+ }+ }+}++/** Start positions of viewport-sized windows covering [start, start+size); never empty. */+function tileStarts(start: number, size: number, step: number): number[] {+ const starts: number[] = [];+ for (let p = start; p < start + size; p += step) starts.push(p);+ return starts.length ? starts : [start];+}++const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++/** btoa needs a binary string; chunk the bytes so a large image never overflows the call stack. */+function blobToDataUrl(blob: Blob, mime: string): Promise<string> {+ return blob.arrayBuffer().then((buffer) => {+ const bytes = new Uint8Array(buffer);+ let binary = '';+ const chunk = 0x8000;+ for (let i = 0; i < bytes.length; i += chunk) {+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));+ }+ return `data:${mime};base64,${btoa(binary)}`;+ });+}