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(sessions): preview screenshots inline on the run timeline
Shahriar4c654aab3585
diff --git a/components/run-timeline.tsx b/components/run-timeline.tsxindex 1b402d8..caf3882 100644--- a/components/run-timeline.tsx+++ b/components/run-timeline.tsx@@ -2,6 +2,7 @@ import { AlertTriangle, Bot, Check, Info, Terminal, User, Wrench, X, Zap } fromimport { Markdown } from '@/components/markdown';import { Button } from '@/components/ui/button';+import { openScreenshot } from '@/lib/bridge/screenshot-preview';import type { RunItem } from '@/lib/bridge/use-run';import { cn } from '@/lib/utils';@@ -81,6 +82,23 @@ function ToolRow({)}</div>+ {item.preview && (+ <button+ type="button"+ onClick={() => void openScreenshot(item.preview!)}+ title={`Open the ${item.preview.full ? 'full-size' : 'captured'} screenshot in a new tab`}+ className="group max-w-[85%] overflow-hidden rounded-lg border bg-muted/40 transition hover:border-primary/60 hover:opacity-90"+ >+ <img+ src={item.preview.thumbnail}+ alt={`Screenshot, ${item.preview.width}×${item.preview.height}`}+ width={item.preview.width}+ height={item.preview.height}+ className="block h-auto w-full"+ />+ </button>+ )}+{item.awaiting && (<div className="flex items-center gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-2.5 py-2"><p className="flex-1 text-xs">Allow this action?</p>diff --git a/lib/bridge/run-port.ts b/lib/bridge/run-port.tsindex e805162..80696c0 100644--- a/lib/bridge/run-port.ts+++ b/lib/bridge/run-port.ts@@ -12,6 +12,7 @@ import { tryFastPath } from './fast-path';import { listMeta } from './file-store';import { currentRecording, onRecordingState, startActiveTabRecording, stopRecording } from './recorder';import { asSavedRecording, listRecordings } from './recording-store';+import { onScreenshotPreview, type ScreenshotPreview } from './screenshot-preview';import { recordGeneratedSkill } from './skill-store';import {activateSiteMap,@@ -48,7 +49,8 @@ export type RunMessage =| { op: 'active'; runId: string | null }| { op: 'mapDraft'; draft: SiteMapDraft }| { op: 'mapSettled'; stagingId: string; ok: boolean; message?: string }- | { op: 'recording'; state: RecordingState | null };+ | { op: 'recording'; state: RecordingState | null }+ | { op: 'preview'; preview: ScreenshotPreview };const ports = new Set<Browser.runtime.Port>();let activeRunId: string | null = null;@@ -65,6 +67,8 @@ export function serveRunPorts(): void {broadcast({ op: 'event', runId, event });});+ onScreenshotPreview((preview) => broadcast({ op: 'preview', preview }));+onSiteMapDraft((_runId, draft) => {pendingDraft = draft;broadcast({ op: 'mapDraft', draft });diff --git a/lib/bridge/screenshot-preview.ts b/lib/bridge/screenshot-preview.tsnew file mode 100644index 0000000..b3b1805--- /dev/null+++ b/lib/bridge/screenshot-preview.ts@@ -0,0 +1,67 @@+import { browser } from 'wxt/browser';++export interface ScreenshotPreview {+ previewId: string;+ thumbnail: string;+ width: number;+ height: number;+ full: boolean;+}++const INDEX_KEY = 'browsentic:shots';+const bodyKey = (id: string) => `browsentic:shot:${id}`;++const MAX_KEPT = 2;+const MAX_FULL_CHARS = 4_000_000;++type Listener = (preview: ScreenshotPreview) => void;++const listeners = new Set<Listener>();++export function onScreenshotPreview(listener: Listener): void {+ listeners.add(listener);+}++export async function publishScreenshot(+ image: { dataUrl: string; thumbnail: string; width: number; height: number },+): Promise<void> {+ if (!image.thumbnail) return;+ const previewId = crypto.randomUUID();+ const full = await keepFullImage(previewId, image.dataUrl);+ const preview: ScreenshotPreview = {+ previewId,+ thumbnail: image.thumbnail,+ width: image.width,+ height: image.height,+ full,+ };+ for (const listener of listeners) listener(preview);+}++export async function readFullImage(previewId: string): Promise<string | null> {+ const key = bodyKey(previewId);+ const stored = await browser.storage.session.get(key).catch(() => ({}) as Record<string, unknown>);+ const dataUrl = stored[key];+ return typeof dataUrl === 'string' ? dataUrl : null;+}++export async function openScreenshot(preview: ScreenshotPreview): Promise<void> {+ const stored = preview.full ? await readFullImage(preview.previewId) : null;+ const blob = await (await fetch(stored ?? preview.thumbnail)).blob();+ await browser.tabs.create({ url: URL.createObjectURL(blob) });+}++async function keepFullImage(previewId: string, dataUrl: string): Promise<boolean> {+ if (dataUrl.length > MAX_FULL_CHARS) return false;+ try {+ const stored = await browser.storage.session.get(INDEX_KEY);+ const kept = Array.isArray(stored[INDEX_KEY]) ? (stored[INDEX_KEY] as string[]) : [];+ const next = [previewId, ...kept.filter((id) => id !== previewId)];+ const dropped = next.slice(MAX_KEPT);+ await browser.storage.session.set({ [bodyKey(previewId)]: dataUrl, [INDEX_KEY]: next.slice(0, MAX_KEPT) });+ if (dropped.length) await browser.storage.session.remove(dropped.map(bodyKey));+ return true;+ } catch {+ return false;+ }+}diff --git a/lib/bridge/screenshot.ts b/lib/bridge/screenshot.tsindex d3f84e2..923f674 100644--- a/lib/bridge/screenshot.ts+++ b/lib/bridge/screenshot.ts@@ -2,6 +2,7 @@ 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';+import { publishScreenshot } from './screenshot-preview';interface CapturePlan {mode: 'fullPage' | 'viewport' | 'element';@@ -29,7 +30,9 @@ export async function screenshotTab(const plan = planned.data as CapturePlan;try {- return success(await capture(tab, plan));+ const { thumbnail, ...data } = await capture(tab, plan);+ await publishScreenshot({ ...data, thumbnail }).catch(() => {});+ return success(data);} catch (error) {if (error instanceof ActionError) return failure(error.code, error.message);return failure('CAPTURE_FAILED', error instanceof Error ? error.message : String(error));@@ -44,7 +47,14 @@ export async function screenshotTab(async function capture(tab: { id: number; windowId?: number },plan: CapturePlan,-): Promise<{ format: string; width: number; height: number; dataUrl: string; truncated?: boolean }> {+): Promise<{+ format: string;+ width: number;+ height: number;+ dataUrl: string;+ truncated?: boolean;+ thumbnail: string;+}> {const { viewport, format, quality, maxLongSide } = plan;const region = { ...plan.region };@@ -110,7 +120,22 @@ async function capture(}if (!out) throw new ActionError('Nothing was captured', 'CAPTURE_FAILED');- return encode(out, format, quality, truncated);+ return { ...(await encode(out, format, quality, truncated)), thumbnail: await thumbnail(out) };+}++const THUMB_MAX_SIDE = 640;+const THUMB_QUALITY = 0.6;++async function thumbnail(source: OffscreenCanvas): Promise<string> {+ const scale = Math.min(1, THUMB_MAX_SIDE / Math.max(source.width, source.height, 1));+ const small = new OffscreenCanvas(+ Math.max(1, Math.round(source.width * scale)),+ Math.max(1, Math.round(source.height * scale)),+ );+ const ctx = small.getContext('2d');+ if (!ctx) return '';+ ctx.drawImage(source, 0, 0, small.width, small.height);+ return blobToDataUrl(await small.convertToBlob({ type: 'image/jpeg', quality: THUMB_QUALITY }), 'image/jpeg');}async function encode(diff --git a/lib/bridge/session-store.ts b/lib/bridge/session-store.tsindex afa4a78..67db9c5 100644--- a/lib/bridge/session-store.ts+++ b/lib/bridge/session-store.ts@@ -49,7 +49,7 @@ export type SessionFields = Omit<StoredSessionMeta, 'title' | 'titledAtTurn' | '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) };+ const transcript: StoredSessionTranscript = { id: fields.id, items: items.slice(-MAX_ITEMS).map(withoutPreview) };await browser.storage.local.set({ [transcriptKey(fields.id)]: transcript });const list = await listSessions();@@ -60,6 +60,12 @@ export async function putSession(fields: SessionFields, items: RunItem[]): Promiawait writeIndex(kept.slice(0, MAX_SESSIONS));}+function withoutPreview(item: RunItem): RunItem {+ if (item.kind !== 'tool' || !item.preview) return item;+ const { preview: _preview, ...rest } = item;+ return rest;+}+export async function readTranscript(id: string): Promise<StoredSessionTranscript | null> {const key = transcriptKey(id);const stored = await browser.storage.local.get(key);diff --git a/lib/bridge/use-run.ts b/lib/bridge/use-run.tsindex e666c22..fd1c81a 100644--- a/lib/bridge/use-run.ts+++ b/lib/bridge/use-run.ts@@ -1,10 +1,12 @@import { useCallback, useEffect, 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 { RecordingState } from '@/lib/recordings/events';import { SITE_MAPPER_SKILL, type SiteMapDraft } from '@/lib/skills/site-map';import { redactInput } from './redact';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';const RECONNECT_MS = 1_000;@@ -24,6 +26,7 @@ export type RunItem =ok?: boolean;awaiting?: boolean;source?: 'local' | 'external';+ preview?: ScreenshotPreview;};export interface Run {@@ -98,7 +101,9 @@ export function useRun({ persist = false }: { persist?: boolean } = {}): Run {]);}} else if (runMessage.op === 'recording') setRecording(runMessage.state);- else {+ else if (runMessage.op === 'preview') {+ setItems((previous) => attachPreview(previous, runMessage.preview));+ } else {if (runMessage.event.kind === 'session') {session.current.claudeSessionId = runMessage.event.claudeSessionId ?? undefined;}@@ -343,6 +348,18 @@ function reduce(items: RunItem[], event: RunEvent): RunItem[] {}}+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));}