graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(native): browser sidecar — a Kuri-driven Chrome tab per chat, with click-to-pin annotations for the agent
justrach9d9bb9619667
diff --git a/apps/native/README.md b/apps/native/README.mdindex 72058a88..1608e72f 100644--- a/apps/native/README.md+++ b/apps/native/README.md@@ -100,7 +100,29 @@ server only validates a root it is handed) with the active one checked:`/api/acp` bootstrap, `/api/sessions`, `/api/fs` and `/api/git` all takethe workspace root (`cwd` / `?root=`) and fall back to the default from-`GRAFF_CWD` or the repo root. The sidebar footer names the tab's graff+`GRAFF_CWD` or the repo root.++## Browser sidecar (experimental)++The **Browser** button in the tab bar (or the sidebar's Browser item)+opens a pane showing a live Chrome tab that belongs to the chat. It is+[Kuri](https://github.com/justrach/kuri)'s managed headless Chrome, driven+over `/api/browser`; install Kuri (`curl -fsSL https://kuri.trilok.ai/download | sh`)+or set `KURI_BIN`. Nothing runs until a pane is opened, and a browser that+sees no requests for `GRAFF_BROWSER_IDLE_MINS` (default 20, `0` = never) is+stopped again.++- **Browse** forwards clicks, scrolling and typing to the page.+- **Annotate** pins the element under a click with a note. Pins are drawn+ over the frame from geometry the page reports (one `Runtime.evaluate`+ per hover or click; nothing is injected, so any page works). They go+ ahead of the chat's next prompt as a block naming each element (role,+ name, selector, box), the note, and — when Kuri's snapshot names the+ same element — its `@eN` ref, plus the tab's address so the agent can+ snapshot, act on, and highlight the very page the user is looking at.++The design and what is deliberately left out are in+`plans/2026-09-03-browser-sidecar.md`. The sidebar footer names the tab's graffsession (`native-…`, the `--resume` target); clicking it copies thecommand that continues the same conversation in a terminal.diff --git a/apps/native/app/api/browser/route.ts b/apps/native/app/api/browser/route.tsnew file mode 100644index 00000000..60782686--- /dev/null+++ b/apps/native/app/api/browser/route.ts@@ -0,0 +1,250 @@+import { NextRequest } from "next/server";+import { matchRef, parseSnapshotRefs, type PinElement } from "@/lib/browser/annotations";+import { hoverExpression, inspectExpression } from "@/lib/browser/inspect-script";+import { ensureKuri, kuriAddress, kuriJson, kuriState, q, stopKuri } from "@/lib/browser/kuri-supervisor";+import { normalizeUrl } from "@/lib/browser/url";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++/** The sidecar browser: one Kuri (and its headless Chrome) per dev server,+ * one Chrome tab per chat. `GET ?frame=1` is the live picture the pane+ * polls; `POST {chat, method, params}` drives the tab and identifies the+ * element under a point for annotations. Only `open` spawns the browser —+ * status and frames never do, so a closed pane stays free. */++type Tab = { id: string; width: number; height: number };++const g = globalThis as typeof globalThis & { __graffBrowserTabs?: Map<string, Tab> };+const tabs = (g.__graffBrowserTabs ??= new Map<string, Tab>());+const DEFAULT_CHAT = "default";+const DEFAULT_SIZE = { width: 960, height: 640 };++type PageInfo = { tabId: string; url: string; title: string; width: number; height: number; ready: string };++type KuriPageInfo = {+ url?: string;+ title?: string;+ viewport_width?: number;+ viewport_height?: number;+ ready_state?: string;+};++async function setViewport(id: string, size: { width: number; height: number }): Promise<void> {+ await kuriJson(`/set/viewport${q({ tab_id: id, width: size.width, height: size.height })}`);+}++async function tabAlive(id: string): Promise<boolean> {+ const list = await kuriJson<{ id: string }[]>("/tabs");+ return Array.isArray(list) && list.some((t) => t.id === id);+}++async function ensureTab(chat: string, size?: { width: number; height: number }): Promise<Tab> {+ await ensureKuri();+ const have = tabs.get(chat);+ if (have && (await tabAlive(have.id))) {+ if (size && (size.width !== have.width || size.height !== have.height)) {+ await setViewport(have.id, size);+ have.width = size.width;+ have.height = size.height;+ }+ return have;+ }+ const created = await kuriJson<{ tab_id?: string }>(`/tab/new${q({ url: "about:blank", wait: "true" })}`);+ if (!created.tab_id) throw new Error("kuri /tab/new returned no tab_id");+ const tab: Tab = { id: created.tab_id, ...(size ?? DEFAULT_SIZE) };+ await setViewport(tab.id, tab);+ tabs.set(chat, tab);+ return tab;+}++async function pageInfo(tab: Tab): Promise<PageInfo> {+ const info = await kuriJson<KuriPageInfo>(`/page/info${q({ tab_id: tab.id })}`);+ return {+ tabId: tab.id,+ url: info.url ?? "",+ title: info.title ?? "",+ width: info.viewport_width ?? tab.width,+ height: info.viewport_height ?? tab.height,+ ready: info.ready_state ?? "",+ };+}++async function evaluate<T>(tab: Tab, expression: string): Promise<T | null> {+ const body = await kuriJson<{ result?: { result?: { value?: unknown } } }>(`/evaluate${q({ tab_id: tab.id, expression })}`);+ const value = body.result?.result?.value;+ return value === undefined || value === null ? null : (value as T);+}++function size(params: Record<string, unknown> | undefined): { width: number; height: number } | undefined {+ const w = Number(params?.width);+ const h = Number(params?.height);+ if (!Number.isFinite(w) || !Number.isFinite(h) || w < 200 || h < 150) return undefined;+ return { width: Math.min(4000, Math.round(w)), height: Math.min(4000, Math.round(h)) };+}++function num(v: unknown, fallback = 0): number {+ const n = Number(v);+ return Number.isFinite(n) ? n : fallback;+}++export async function GET(req: NextRequest) {+ const chat = req.nextUrl.searchParams.get("chat") || DEFAULT_CHAT;+ const tab = tabs.get(chat) ?? null;+ const live = kuriAddress();+ if (req.nextUrl.searchParams.get("frame")) {+ if (!live || !tab) return Response.json({ error: "no browser tab for this chat" }, { status: 404 });+ const quality = Math.min(95, Math.max(20, num(req.nextUrl.searchParams.get("q"), 55)));+ try {+ const shot = await kuriJson<{ result?: { data?: string } }>(+ `/screenshot${q({ tab_id: tab.id, format: "jpeg", quality })}`,+ );+ const data = shot.result?.data;+ if (!data) return Response.json({ error: "no frame" }, { status: 502 });+ return new Response(new Uint8Array(Buffer.from(data, "base64")), {+ headers: { "content-type": "image/jpeg", "cache-control": "no-store" },+ });+ } catch (err) {+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 502 });+ }+ }+ let page: PageInfo | null = null;+ if (live && tab) {+ try {+ page = await pageInfo(tab);+ } catch {+ page = null;+ }+ }+ return Response.json({ kuri: kuriState(), tab: page });+}++export async function POST(req: NextRequest) {+ const body = (await req.json()) as { chat?: string; method?: string; params?: Record<string, unknown> };+ const chat = typeof body.chat === "string" && body.chat ? body.chat : DEFAULT_CHAT;+ const method = body.method ?? "";+ const params = body.params ?? {};+ try {+ if (method === "stop") {+ tabs.clear();+ stopKuri();+ return Response.json({ kuri: kuriState() });+ }+ if (method === "close") {+ const tab = tabs.get(chat);+ tabs.delete(chat);+ if (tab && kuriAddress()) await kuriJson(`/tab/close${q({ tab_id: tab.id })}`).catch(() => undefined);+ return Response.json({ ok: true });+ }+ if (method === "handle") {+ const live = kuriAddress();+ const tab = tabs.get(chat);+ return Response.json(live && tab ? { port: live.port, token: live.token, tabId: tab.id } : null);+ }+ if (method === "open") {+ const tab = await ensureTab(chat, size(params));+ if (typeof params.url === "string" && params.url.trim()) {+ await kuriJson(`/navigate${q({ tab_id: tab.id, url: normalizeUrl(params.url) })}`);+ }+ return Response.json(await pageInfo(tab));+ }+ // Everything below drives a tab that must already exist; a pane that+ // was never opened has nothing to drive and must not spawn a browser.+ const tab = tabs.get(chat);+ if (!tab || !kuriAddress()) return Response.json({ error: "open the browser first" }, { status: 409 });+ switch (method) {+ case "navigate": {+ await kuriJson(`/navigate${q({ tab_id: tab.id, url: normalizeUrl(String(params.url ?? "")) })}`);+ return Response.json(await pageInfo(tab));+ }+ case "back":+ case "forward":+ case "reload": {+ await kuriJson(`/${method}${q({ tab_id: tab.id })}`);+ return Response.json(await pageInfo(tab));+ }+ case "info":+ return Response.json(await pageInfo(tab));+ case "viewport": {+ const s = size(params);+ if (s) {+ await setViewport(tab.id, s);+ tab.width = s.width;+ tab.height = s.height;+ }+ return Response.json({ width: tab.width, height: tab.height });+ }+ case "input": {+ const x = Math.round(num(params.x));+ const y = Math.round(num(params.y));+ const button = typeof params.button === "string" ? params.button : "left";+ switch (params.kind) {+ case "move":+ await kuriJson(`/mouse/move${q({ tab_id: tab.id, x, y })}`);+ break;+ case "down":+ await kuriJson(`/mouse/down${q({ tab_id: tab.id, x, y, button })}`);+ break;+ case "up":+ await kuriJson(`/mouse/up${q({ tab_id: tab.id, x, y, button })}`);+ break;+ case "click":+ await kuriJson(`/mouse/move${q({ tab_id: tab.id, x, y })}`);+ await kuriJson(`/mouse/down${q({ tab_id: tab.id, x, y, button })}`);+ await kuriJson(`/mouse/up${q({ tab_id: tab.id, x, y, button })}`);+ break;+ case "wheel":+ await kuriJson(+ `/mouse/wheel${q({ tab_id: tab.id, x, y, deltaX: Math.round(num(params.deltaX)), deltaY: Math.round(num(params.deltaY)) })}`,+ );+ break;+ case "key": {+ const key = String(params.key ?? "");+ if (!key) break;+ await kuriJson(`/keydown${q({ tab_id: tab.id, key })}`);+ await kuriJson(`/keyup${q({ tab_id: tab.id, key })}`);+ break;+ }+ case "type": {+ const text = String(params.text ?? "");+ if (text) await kuriJson(`/keyboard/type${q({ tab_id: tab.id, text })}`);+ break;+ }+ default:+ return Response.json({ error: `unknown input kind: ${String(params.kind)}` }, { status: 400 });+ }+ return Response.json({ ok: true });+ }+ case "hover": {+ const hit = await evaluate<{ rect: PinElement["rect"]; tag: string }>(tab, hoverExpression(num(params.x), num(params.y)));+ return Response.json(hit);+ }+ case "inspect": {+ const hit = await evaluate<PinElement & { url: string; title: string }>(tab, inspectExpression(num(params.x), num(params.y)));+ if (!hit) return Response.json(null);+ let ref: string | null = null;+ try {+ const snapshot = await kuriJson<string>(`/snapshot${q({ tab_id: tab.id, filter: "interactive", format: "compact" })}`);+ if (typeof snapshot === "string") ref = matchRef(parseSnapshotRefs(snapshot), hit);+ } catch {+ // a page mid-navigation has no snapshot; the pin still stands+ }+ const { url, title, ...element } = hit;+ return Response.json({ element, ref, url, title });+ }+ case "snapshot": {+ const snapshot = await kuriJson<string>(`/snapshot${q({ tab_id: tab.id, filter: "interactive", format: "compact" })}`);+ return Response.json({ snapshot: typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot) });+ }+ case "highlight": {+ const target = typeof params.ref === "string" ? { ref: params.ref } : { selector: String(params.selector ?? "") };+ await kuriJson(`/highlight${q({ tab_id: tab.id, ...target })}`);+ return Response.json({ ok: true });+ }+ default:+ return Response.json({ error: `unknown method: ${method}` }, { status: 400 });+ }+ } catch (err) {+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 502 });+ }+}diff --git a/apps/native/components/primitives/SidebarNav.tsx b/apps/native/components/primitives/SidebarNav.tsxindex baec1029..e25d88e3 100644--- a/apps/native/components/primitives/SidebarNav.tsx+++ b/apps/native/components/primitives/SidebarNav.tsx@@ -8,6 +8,7 @@ import {IconCrossSmall,IconEditBig,IconFolder,+ IconGlobe,IconHome,IconMagnifyingGlass,IconPlusMedium,@@ -31,6 +32,7 @@ const WORKSPACE = { key: "graff", name: "Codegraff", monogram: "G" };const NAV_ITEMS: { key: string; label: string; icon: ReactNode; count?: string }[] = [{ key: "home", label: "Home", icon: <IconHome size={18} /> },{ key: "workspace", label: "Workspace", icon: <IconFolder size={18} /> },+ { key: "browser", label: "Browser", icon: <IconGlobe size={18} /> },];export type SidebarRecent = {diff --git a/apps/native/components/site/BrowserPane.tsx b/apps/native/components/site/BrowserPane.tsxnew file mode 100644index 00000000..fd22677a--- /dev/null+++ b/apps/native/components/site/BrowserPane.tsx@@ -0,0 +1,555 @@+"use client";++import {+ useCallback,+ useEffect,+ useRef,+ useState,+ type KeyboardEvent as ReactKeyboardEvent,+ type PointerEvent as ReactPointerEvent,+ type WheelEvent as ReactWheelEvent,+} from "react";+import {+ browserHover,+ browserInput,+ browserInspect,+ browserNav,+ browserNavigate,+ browserOpen,+ browserStatus,+ browserViewport,+ frameUrl,+ type InspectHit,+ type PageInfo,+} from "@/lib/browser-client";+import type { BrowserPin, PinRect } from "@/lib/browser/annotations";+import { IconCrossSmall, IconGlobe } from "@/lib/icons";++/* ─────────────────────────────────────────────────────────+ * BROWSER PANE+ * The sidecar: a live picture of the headless Chrome tab Kuri drives for+ * this chat. In browse mode the pointer and keyboard are forwarded; in+ * annotate mode a click pins the element under it with a note. The pins+ * are drawn here, over the frame, from geometry the page reports — nothing+ * is injected into the page, so it works under any content security policy.+ * ───────────────────────────────────────────────────────── */++type Mode = "browse" | "annotate";++const FRAME_QUALITY = 55;+const FRAME_GAP_MS = 160;+const HIDDEN_GAP_MS = 2000;+const HOVER_GAP_MS = 90;+const MOVE_GAP_MS = 60;++const PIN_STYLE = "flex size-5 items-center justify-center rounded-full bg-accent text-[10.5px] font-semibold text-white shadow-btn";++function pct(n: number, of: number): string {+ return `${(n / Math.max(1, of)) * 100}%`;+}++function Glyph({ d, size = 13 }: { d: string; size?: number }) {+ return (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>+ <path d={d} />+ </svg>+ );+}++function BarButton({ label, onClick, disabled, children }: { label: string; onClick: () => void; disabled?: boolean; children: React.ReactNode }) {+ return (+ <button+ type="button"+ aria-label={label}+ title={label}+ disabled={disabled}+ onClick={onClick}+ className="flex size-7 shrink-0 items-center justify-center rounded-[6px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink disabled:opacity-40 disabled:hover:bg-transparent"+ >+ {children}+ </button>+ );+}++export default function BrowserPane({+ chat,+ pins,+ onPinsChange,+ onClose,+ initialUrl,+}: {+ /** The chat handle; the tab is the chat's own, like its agent. */+ chat: string;+ pins: BrowserPin[];+ onPinsChange: (next: BrowserPin[]) => void;+ onClose: () => void;+ initialUrl?: string;+}) {+ const [info, setInfo] = useState<PageInfo | null>(null);+ const [url, setUrl] = useState(initialUrl ?? "");+ const [mode, setMode] = useState<Mode>("browse");+ const [src, setSrc] = useState<string | null>(null);+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [hover, setHover] = useState<PinRect | null>(null);+ const [draft, setDraft] = useState<{ x: number; y: number; hit: InspectHit } | null>(null);+ const [comment, setComment] = useState("");+ const frameRef = useRef<HTMLDivElement>(null);+ const imgRef = useRef<HTMLImageElement>(null);+ const urlRef = useRef<HTMLInputElement>(null);+ const commentRef = useRef<HTMLInputElement>(null);+ const lastMove = useRef(0);+ const lastHover = useRef(0);+ const infoRef = useRef<PageInfo | null>(null);+ infoRef.current = info;++ const paneSize = useCallback(() => {+ const el = frameRef.current;+ if (!el) return { width: 960, height: 640 };+ return { width: Math.max(320, Math.round(el.clientWidth)), height: Math.max(240, Math.round(el.clientHeight)) };+ }, []);++ const open = useCallback(+ async (target: string) => {+ setBusy(infoRef.current ? "Loading…" : "Starting the browser…");+ setError(null);+ try {+ const { width, height } = paneSize();+ const next = infoRef.current ? await browserNavigate(chat, target) : await browserOpen(chat, target, width, height);+ setInfo(next);+ setUrl(next.url === "about:blank" ? "" : next.url);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(null);+ }+ },+ [chat, paneSize],+ );++ // Adopt the chat's tab when it already exists (the pane was closed and+ // reopened); otherwise open one. Only this path spawns the browser.+ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ const status = await browserStatus(chat);+ if (cancelled) return;+ if (status.tab) {+ setInfo(status.tab);+ setUrl(status.tab.url === "about:blank" ? "" : status.tab.url);+ const { width, height } = paneSize();+ void browserViewport(chat, width, height).catch(() => undefined);+ return;+ }+ } catch {+ // status is best effort; fall through to open+ }+ if (!cancelled) void open(initialUrl ?? "");+ })();+ return () => {+ cancelled = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [chat]);++ // The picture: one JPEG after another, the next requested only once the+ // last has decoded. A hidden tab drops to one frame every two seconds —+ // near free, and the picture is fresh the moment the tab comes back.+ const tabId = info?.tabId ?? null;+ useEffect(() => {+ if (!tabId) return;+ let alive = true;+ let timer = 0;+ const loop = () => {+ if (!alive) return;+ const next = frameUrl(chat, FRAME_QUALITY, Date.now());+ const im = new Image();+ im.onload = () => {+ if (!alive) return;+ setSrc(next);+ timer = window.setTimeout(loop, document.hidden ? HIDDEN_GAP_MS : FRAME_GAP_MS);+ };+ im.onerror = () => {+ if (alive) timer = window.setTimeout(loop, 1200);+ };+ im.src = next;+ };+ loop();+ return () => {+ alive = false;+ window.clearTimeout(timer);+ };+ }, [chat, tabId]);++ // The viewport follows the pane, so the picture is 1:1 and stays crisp.+ useEffect(() => {+ const el = frameRef.current;+ if (!el || !tabId) return;+ let timer = 0;+ const observer = new ResizeObserver(() => {+ window.clearTimeout(timer);+ timer = window.setTimeout(() => {+ const { width, height } = paneSize();+ const cur = infoRef.current;+ if (!cur || (width === cur.width && height === cur.height)) return;+ void browserViewport(chat, width, height)+ .then((v) => setInfo((c) => (c ? { ...c, ...v } : c)))+ .catch(() => undefined);+ }, 300);+ });+ observer.observe(el);+ return () => {+ observer.disconnect();+ window.clearTimeout(timer);+ };+ }, [chat, tabId, paneSize]);++ // Title and address follow the page (links clicked inside it, redirects).+ useEffect(() => {+ if (!tabId) return;+ const timer = window.setInterval(() => {+ void browserNav(chat, "info")+ .then((next) => {+ setInfo((cur) => (cur && (cur.url !== next.url || cur.title !== next.title) ? { ...cur, url: next.url, title: next.title } : cur));+ if (document.activeElement !== urlRef.current) setUrl(next.url === "about:blank" ? "" : next.url);+ })+ .catch(() => undefined);+ }, 2500);+ return () => window.clearInterval(timer);+ }, [chat, tabId]);++ /** Frame pixels → the page's CSS pixels. */+ const toPage = (e: { clientX: number; clientY: number }) => {+ const img = imgRef.current;+ const cur = infoRef.current;+ if (!img || !cur) return null;+ const r = img.getBoundingClientRect();+ if (!r.width || !r.height) return null;+ return { x: ((e.clientX - r.left) / r.width) * cur.width, y: ((e.clientY - r.top) / r.height) * cur.height };+ };++ const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {+ const p = toPage(e);+ if (!p || busy) return;+ const now = performance.now();+ if (mode === "browse") {+ if (now - lastMove.current < MOVE_GAP_MS) return;+ lastMove.current = now;+ void browserInput(chat, { kind: "move", x: p.x, y: p.y }).catch(() => undefined);+ return;+ }+ if (now - lastHover.current < HOVER_GAP_MS) return;+ lastHover.current = now;+ void browserHover(chat, p.x, p.y)+ .then((hit) => setHover(hit?.rect ?? null))+ .catch(() => undefined);+ };++ const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {+ frameRef.current?.focus();+ const p = toPage(e);+ if (!p || busy) return;+ if (mode === "browse") {+ e.preventDefault();+ void browserInput(chat, { kind: "down", x: p.x, y: p.y, button: e.button === 2 ? "right" : "left" }).catch(() => undefined);+ }+ };++ const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {+ const p = toPage(e);+ if (!p || busy) return;+ if (mode === "browse") {+ void browserInput(chat, { kind: "up", x: p.x, y: p.y, button: e.button === 2 ? "right" : "left" }).catch(() => undefined);+ return;+ }+ if (e.button !== 0) return;+ setBusy("Reading the element…");+ void browserInspect(chat, p.x, p.y)+ .then((hit) => {+ if (!hit) return;+ setDraft({ x: p.x, y: p.y, hit });+ setComment("");+ setHover(hit.element.rect);+ window.setTimeout(() => commentRef.current?.focus(), 0);+ })+ .catch((err) => setError(err instanceof Error ? err.message : String(err)))+ .finally(() => setBusy(null));+ };++ const onWheel = (e: ReactWheelEvent<HTMLDivElement>) => {+ if (mode !== "browse" || busy) return;+ const p = toPage(e);+ if (!p) return;+ void browserInput(chat, { kind: "wheel", x: p.x, y: p.y, deltaX: e.deltaX, deltaY: e.deltaY }).catch(() => undefined);+ };++ const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {+ if (mode !== "browse" || busy || e.metaKey || e.ctrlKey || e.altKey) return;+ if (e.target !== frameRef.current) return;+ e.preventDefault();+ if (e.key.length === 1) void browserInput(chat, { kind: "type", text: e.key }).catch(() => undefined);+ else void browserInput(chat, { kind: "key", key: e.key }).catch(() => undefined);+ };++ const commitPin = () => {+ if (!draft) return;+ const pin: BrowserPin = {+ id: Date.now(),+ comment: comment.trim(),+ url: draft.hit.url,+ title: draft.hit.title,+ ref: draft.hit.ref,+ element: draft.hit.element,+ point: { x: draft.x, y: draft.y },+ };+ onPinsChange([...pins, pin]);+ setDraft(null);+ setComment("");+ setHover(null);+ };++ const removePin = (id: number) => onPinsChange(pins.filter((p) => p.id !== id));++ const go = (target: string) => {+ const t = target.trim();+ if (t) void open(t);+ };++ const pageW = info?.width ?? 1;+ const pageH = info?.height ?? 1;+ const samePage = (p: BrowserPin) => !info || p.url === info.url;++ return (+ <aside+ className="hidden w-[560px] shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page lg:flex"+ style={{ animation: "fade-in 300ms ease both" }}+ >+ <div className="flex h-11 shrink-0 items-center gap-2 border-b border-line px-3">+ <span className="flex size-5 items-center justify-center text-ink-2">+ <IconGlobe size={16} />+ </span>+ <span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-ink" title={info?.url}>+ {info?.title || (info ? info.url : "Browser")}+ </span>+ <div className="flex h-7 shrink-0 items-center rounded-[7px] bg-hover p-0.5 text-[11.5px] font-medium">+ {(["browse", "annotate"] as const).map((m) => (+ <button+ key={m}+ type="button"+ aria-pressed={mode === m}+ onClick={() => {+ setMode(m);+ setHover(null);+ setDraft(null);+ }}+ className={`h-6 rounded-[6px] px-2 capitalize transition-colors ${mode === m ? "bg-surface text-ink shadow-hairline" : "text-ink-3 hover:text-ink"}`}+ >+ {m}+ </button>+ ))}+ </div>+ <button+ type="button"+ aria-label="Close browser"+ onClick={onClose}+ className="flex size-7 items-center justify-center rounded-[6px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"+ >+ <IconCrossSmall size={16} />+ </button>+ </div>++ <form+ className="flex h-9 shrink-0 items-center gap-1 border-b border-line px-2"+ onSubmit={(e) => {+ e.preventDefault();+ go(url);+ }}+ >+ <BarButton label="Back" disabled={!info} onClick={() => void browserNav(chat, "back").then(setInfo).catch(() => undefined)}>+ <Glyph d="M15 18l-6-6 6-6" />+ </BarButton>+ <BarButton label="Forward" disabled={!info} onClick={() => void browserNav(chat, "forward").then(setInfo).catch(() => undefined)}>+ <Glyph d="M9 18l6-6-6-6" />+ </BarButton>+ <BarButton label="Reload" disabled={!info} onClick={() => void browserNav(chat, "reload").then(setInfo).catch(() => undefined)}>+ <Glyph d="M21 12a9 9 0 1 1-3-6.7M21 3v6h-6" />+ </BarButton>+ <input+ ref={urlRef}+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ spellCheck={false}+ placeholder="localhost:3000 or a URL"+ aria-label="Address"+ className="h-7 min-w-0 flex-1 rounded-[7px] bg-field px-2 font-mono text-[12px] text-ink shadow-hairline outline-none placeholder:text-ink-3 focus:bg-hover"+ />+ <button type="submit" className="h-7 shrink-0 rounded-[7px] bg-hover-2 px-2.5 text-[12px] font-medium text-ink transition-colors hover:bg-line-strong">+ Go+ </button>+ </form>++ <div+ ref={frameRef}+ tabIndex={0}+ role="application"+ aria-label={mode === "browse" ? "Page, keyboard and pointer forwarded" : "Page, click an element to annotate it"}+ onPointerMove={onPointerMove}+ onPointerDown={onPointerDown}+ onPointerUp={onPointerUp}+ onPointerLeave={() => setHover(null)}+ onWheel={onWheel}+ onKeyDown={onKeyDown}+ onContextMenu={(e) => e.preventDefault()}+ className="relative min-h-0 flex-1 overflow-hidden bg-inset outline-none focus-visible:shadow-[inset_0_0_0_2px_var(--accent)]"+ style={{ cursor: mode === "annotate" ? "crosshair" : "default" }}+ >+ {src && info ? (+ <div className="relative w-full">+ <img ref={imgRef} src={src} alt="" draggable={false} className="block w-full select-none" />+ <div className="pointer-events-none absolute inset-0">+ {hover && mode === "annotate" && (+ <div+ className="absolute rounded-[3px]"+ style={{+ left: pct(hover.x, pageW),+ top: pct(hover.y, pageH),+ width: pct(hover.w, pageW),+ height: pct(hover.h, pageH),+ boxShadow: "0 0 0 2px var(--accent), 0 0 0 9999px color-mix(in oklab, var(--accent) 10%, transparent)",+ }}+ />+ )}+ {pins.filter(samePage).map((pin) => (+ <div+ key={pin.id}+ className="absolute"+ style={{ left: pct(pin.point.x, pageW), top: pct(pin.point.y, pageH), transform: "translate(-50%, -50%)" }}+ title={pin.comment || pin.element.name}+ >+ <span className={PIN_STYLE}>{pins.indexOf(pin) + 1}</span>+ </div>+ ))}+ {draft && (+ <div+ className="absolute"+ style={{ left: pct(draft.x, pageW), top: pct(draft.y, pageH), transform: "translate(-50%, -50%)" }}+ >+ <span className={`${PIN_STYLE} animate-pulse`}>{pins.length + 1}</span>+ </div>+ )}+ </div>+ {draft && (+ <form+ className="absolute z-10 flex w-[280px] flex-col gap-1.5 rounded-[10px] bg-surface p-2 shadow-overlay"+ style={{+ left: `min(calc(${pct(draft.x, pageW)} + 14px), calc(100% - 290px))`,+ top: `min(calc(${pct(draft.y, pageH)} + 14px), calc(100% - 110px))`,+ animation: "pop-in 160ms cubic-bezier(0.23,1,0.32,1) both",+ }}+ onSubmit={(e) => {+ e.preventDefault();+ commitPin();+ }}+ onPointerDown={(e) => e.stopPropagation()}+ onPointerUp={(e) => e.stopPropagation()}+ onPointerMove={(e) => e.stopPropagation()}+ >+ <div className="truncate text-[11.5px] text-ink-3" title={draft.hit.element.selector}>+ {draft.hit.ref ? <span className="mr-1 font-mono text-accent-ink">@{draft.hit.ref}</span> : null}+ {draft.hit.element.role || draft.hit.element.tag}+ {draft.hit.element.name ? ` “${draft.hit.element.name}”` : ""}+ </div>+ <input+ ref={commentRef}+ value={comment}+ onChange={(e) => setComment(e.target.value)}+ onKeyDown={(e) => {+ e.stopPropagation();+ if (e.key === "Escape") {+ setDraft(null);+ setHover(null);+ }+ }}+ placeholder="What should change here?"+ aria-label="Annotation"+ className="h-7 w-full rounded-[7px] bg-field px-2 text-[12.5px] text-ink shadow-hairline outline-none placeholder:text-ink-3 focus:bg-hover"+ />+ <div className="flex items-center justify-end gap-1">+ <button+ type="button"+ onClick={() => {+ setDraft(null);+ setHover(null);+ }}+ className="h-6 rounded-full px-2 text-[11.5px] font-medium text-ink-2 hover:bg-hover hover:text-ink"+ >+ Cancel+ </button>+ <button type="submit" className="h-6 rounded-full bg-ink px-2.5 text-[11.5px] font-medium text-canvas hover:opacity-90">+ Pin+ </button>+ </div>+ </form>+ )}+ </div>+ ) : (+ <div className="flex h-full items-center justify-center px-6 text-center text-[12.5px] text-ink-3">+ {busy ?? (error ? "" : "Enter an address above.")}+ </div>+ )}+ {busy && src && (+ <div className="pointer-events-none absolute top-2 left-1/2 -translate-x-1/2 rounded-full bg-surface px-2.5 py-1 text-[11.5px] text-ink-2 shadow-overlay">+ {busy}+ </div>+ )}+ {error && (+ <div className="absolute inset-x-2 bottom-2 rounded-[8px] bg-surface px-2.5 py-1.5 text-[12px] text-red shadow-overlay">+ {error}+ </div>+ )}+ </div>++ <div className="max-h-44 shrink-0 overflow-y-auto border-t border-line">+ {pins.length === 0 ? (+ <p className="px-3 py-2 text-[11.5px] text-ink-3">+ {mode === "annotate"+ ? "Click any element to pin it with a note. Pins go to the agent with your next message."+ : "Browse: clicks, scrolling and typing go to the page. Switch to Annotate to pin elements for the agent."}+ </p>+ ) : (+ <div className="flex flex-col px-2 py-1.5">+ {pins.map((pin, i) => (+ <div key={pin.id} className="group flex min-h-8 items-center gap-2 rounded-[7px] px-1.5 py-1 hover:bg-hover">+ <span className={`${PIN_STYLE} shrink-0`}>{i + 1}</span>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[12px] text-ink">{pin.comment || <span className="text-ink-3">no note</span>}</div>+ <div className="truncate font-mono text-[10.5px] text-ink-3" title={pin.element.selector}>+ {pin.ref ? `@${pin.ref} · ` : ""}+ {pin.element.role || pin.element.tag}+ {pin.element.name ? ` “${pin.element.name}”` : ""}+ </div>+ </div>+ <button+ type="button"+ aria-label="Remove pin"+ onClick={() => removePin(pin.id)}+ className="flex size-6 shrink-0 items-center justify-center rounded-[5px] text-ink-3 opacity-0 transition-opacity hover:bg-hover-2 hover:text-ink group-hover:opacity-100 focus:opacity-100"+ >+ <IconCrossSmall size={14} />+ </button>+ </div>+ ))}+ <button+ type="button"+ onClick={() => onPinsChange([])}+ className="mt-0.5 self-start rounded px-1.5 py-0.5 text-[11.5px] font-medium text-ink-3 hover:bg-hover hover:text-ink"+ >+ Clear all+ </button>+ </div>+ )}+ </div>+ </aside>+ );+}diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex aba1f93e..35d78eaa 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -4,7 +4,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import PromptBar, { type PromptModel } from "@/components/primitives/PromptBar";import SidebarNav from "@/components/primitives/SidebarNav";import FilesPane from "@/components/site/FilesPane";-import { IconFolder } from "@/lib/icons";+import BrowserPane from "@/components/site/BrowserPane";+import { IconFolder, IconGlobe } from "@/lib/icons";+import { annotationsBlock, type BrowserPin } from "@/lib/browser/annotations";+import { browserClose, browserHandle } from "@/lib/browser-client";import TaskRows from "@/components/primitives/TaskRows";import { ThemeToggle } from "@/components/site/ThemeToggle";import { AssistantBody, UserBubble } from "@/components/site/ChatBubbles";@@ -98,6 +101,11 @@ export default function GraffHarness() {const activePathRef = useRef<string | null>(null);const [dialog, setDialog] = useState<null | { mode: "new" } | { mode: "settings" }>(null);const [copiedResume, setCopiedResume] = useState(false);+ // The sidecar browser: one Chrome tab per chat, and the pins the user+ // drops on it, which ride ahead of the chat's next prompt.+ const [browserOpen, setBrowserOpen] = useState(false);+ const [pinsByChat, setPinsByChat] = useState<Record<number, BrowserPin[]>>({});+ const pinsRef = useRef<Record<number, BrowserPin[]>>({});const chatIdRef = useRef(1);const msgIdRef = useRef(0);const scrollRef = useRef<HTMLDivElement>(null);@@ -137,6 +145,10 @@ export default function GraffHarness() {queuesRef.current = { ...queuesRef.current, [chatId]: list };setQueues(queuesRef.current);};+ const setPins = (chatId: number, list: BrowserPin[]) => {+ pinsRef.current = { ...pinsRef.current, [chatId]: list };+ setPinsByChat(pinsRef.current);+ };const adoptCatalog = async (chatId: number) => {// What did the agent actually resolve? The picker should show graff's@@ -304,6 +316,16 @@ export default function GraffHarness() {saveHistory(window.localStorage, next);return next;});+ // Pins from the sidecar ride behind the prompt, with the tab's handle+ // so the agent can drive the same page; they are spent on send. Behind,+ // not ahead: graff titles the session from the message's first line.+ let wire = trimmed;+ const pins = pinsRef.current[chatId] ?? [];+ if (pins.length > 0) {+ const handle = await browserHandle(handleOf(chatId)).catch(() => null);+ wire = `${trimmed}\n\n${annotationsBlock(pins, handle)}`;+ setPins(chatId, []);+ }let turn: AssistantTurn = { ...emptyTurn(), model: spawnModel };const startedAt = Date.now();try {@@ -313,7 +335,7 @@ export default function GraffHarness() {// markdown block in the thread.let paint = 0;const turnRef = { current: turn };- for await (const update of prompt(handleOf(chatId), id, trimmed)) {+ for await (const update of prompt(handleOf(chatId), id, wire)) {turn = applyAcpUpdate(turn, update);if (turn.thoughtMs === undefined && turn.status !== "thinking") turn = { ...turn, thoughtMs: Date.now() - startedAt };turnRef.current = turn;@@ -409,7 +431,9 @@ export default function GraffHarness() {return rest;});setBusyFor(id, false);+ setPins(id, []);void disposeSession(handleOf(id));+ void browserClose(handleOf(id)).catch(() => undefined);};const closeChat = (id: number) => {@@ -532,6 +556,7 @@ export default function GraffHarness() {const chatCwd = chatThread.cwd ?? health?.cwd;const chatWorkspace = findWorkspace(workspaces, chatCwd);const workspaceName = chatWorkspace?.name ?? (chatCwd ? basename(chatCwd) : "workspace");+ const pinCount = (pinsByChat[chatThread.id] ?? []).length;const activeWorkspace = findWorkspace(workspaces, activePath);const sidebarWorkspace = activeWorkspace ?? (activePath ? { path: activePath, name: basename(activePath) } : undefined);const footerTitle = chatThread.session@@ -583,7 +608,10 @@ export default function GraffHarness() {<buttontype="button"aria-pressed={filesOpen}- onClick={() => setFilesOpen((open) => !open)}+ onClick={() => {+ setBrowserOpen(false);+ setFilesOpen((open) => !open);+ }}title={chatCwd ?? "Workspace files"}className={`flex h-7 items-center gap-1.5 rounded-[7px] px-2 text-[12px] font-medium transition-colors duration-100 ${filesOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"@@ -592,6 +620,24 @@ export default function GraffHarness() {<IconFolder size={14} /><span className="max-w-40 truncate font-mono text-[11.5px]">{workspaceName}</span></button>+ <button+ type="button"+ aria-pressed={browserOpen}+ onClick={() => {+ setFilesOpen(false);+ setBrowserOpen((open) => !open);+ }}+ title="Sidecar browser — a Chrome tab this chat and its agent share"+ className={`flex h-7 items-center gap-1.5 rounded-[7px] px-2 text-[12px] font-medium transition-colors duration-100 ${+ browserOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"+ }`}+ >+ <IconGlobe size={14} />+ <span className="text-[11.5px]">Browser</span>+ {pinCount > 0 && (+ <span className="rounded-full bg-accent px-1.5 text-[10px] font-semibold text-white tabular-nums">{pinCount}</span>+ )}+ </button><ThemeToggle /></div></div>@@ -609,8 +655,11 @@ export default function GraffHarness() {activeId={chatThread.session ?? null}onPick={pickRecent}onNewChat={newChat}- activeNav={filesOpen ? "workspace" : "chats"}- onNavigate={(key) => setFilesOpen(key === "workspace")}+ activeNav={filesOpen ? "workspace" : browserOpen ? "browser" : "chats"}+ onNavigate={(key) => {+ setFilesOpen(key === "workspace");+ setBrowserOpen(key === "browser");+ }}workspace={sidebarWorkspace}workspaces={workspaces.map((w) => ({ path: w.path, name: w.name }))}onSwitchWorkspace={switchWorkspace}@@ -647,6 +696,34 @@ export default function GraffHarness() {</div><div className="shrink-0 bg-page px-4 pt-3 pb-6 sm:px-8"><div className="mx-auto max-w-[720px]">+ {pinCount > 0 && (+ <div className="mb-2 flex items-center gap-2 rounded-[8px] bg-surface px-2.5 py-1.5 text-[12.5px] text-ink-2 shadow-hairline">+ <span className="shrink-0 text-[11px] font-medium tracking-wide text-ink-3 uppercase">Pinned</span>+ <span className="min-w-0 flex-1 truncate text-ink">+ {pinCount} element{pinCount === 1 ? "" : "s"} in the browser go with your next message+ </span>+ <button+ type="button"+ onClick={() => {+ setFilesOpen(false);+ setBrowserOpen(true);+ }}+ className="shrink-0 rounded px-1.5 text-[11.5px] font-medium text-ink-2 hover:bg-hover hover:text-ink"+ >+ Show+ </button>+ <button+ type="button"+ aria-label="Clear pins"+ onClick={() => setPins(chatThread.id, [])}+ className="flex size-5 shrink-0 items-center justify-center rounded-[5px] text-ink-3 hover:bg-hover hover:text-ink"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" aria-hidden>+ <path d="M18 6L6 18M6 6l12 12" />+ </svg>+ </button>+ </div>+ )}{queued.length > 0 && (<ul className="mb-2 flex flex-col gap-1">{queued.map((item) => (@@ -707,7 +784,17 @@ export default function GraffHarness() {{filesOpen && <FilesPane root={chatThread.cwd} requested={fileRequest} onClose={() => setFilesOpen(false)} />}- {!filesOpen && active && paneTodos.length > 0 && (+ {browserOpen && (+ <BrowserPane+ key={chatThread.id}+ chat={handleOf(chatThread.id)}+ pins={pinsByChat[chatThread.id] ?? []}+ onPinsChange={(next) => setPins(chatThread.id, next)}+ onClose={() => setBrowserOpen(false)}+ />+ )}++ {!filesOpen && !browserOpen && active && paneTodos.length > 0 && (<asideclassName="hidden w-[360px] shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page lg:flex"style={{ animation: "fade-in 300ms ease both" }}diff --git a/apps/native/lib/browser-client.ts b/apps/native/lib/browser-client.tsnew file mode 100644index 00000000..f1ec5af8--- /dev/null+++ b/apps/native/lib/browser-client.ts@@ -0,0 +1,68 @@+/** Browser side of /api/browser: the sidecar's live page, its controls,+ * and the element lookups behind annotations. */++import type { KuriState } from "@/lib/browser/kuri-supervisor";+import type { KuriHandle, PinElement } from "@/lib/browser/annotations";++const BASE = "/api/browser";++export type PageInfo = { tabId: string; url: string; title: string; width: number; height: number; ready: string };++export type BrowserStatus = { kuri: KuriState; tab: PageInfo | null };++export type InspectHit = { element: PinElement; ref: string | null; url: string; title: string };++export type HoverHit = { rect: PinElement["rect"]; tag: string };++export type InputEvent =+ | { kind: "move" | "down" | "up" | "click"; x: number; y: number; button?: "left" | "right" | "middle" }+ | { kind: "wheel"; x: number; y: number; deltaX: number; deltaY: number }+ | { kind: "key"; key: string }+ | { kind: "type"; text: string };++export async function browserCall<T>(chat: string, method: string, params?: Record<string, unknown>): Promise<T> {+ const res = await fetch(BASE, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ chat, method, params }),+ cache: "no-store",+ });+ const text = await res.text();+ let body: unknown = null;+ try {+ body = text ? JSON.parse(text) : null;+ } catch {+ body = null;+ }+ if (!res.ok) {+ const detail = body && typeof body === "object" && typeof (body as { error?: unknown }).error === "string" ? (body as { error: string }).error : text;+ throw new Error(detail || `browser ${method} → ${res.status}`);+ }+ return body as T;+}++export async function browserStatus(chat: string): Promise<BrowserStatus> {+ const res = await fetch(`${BASE}?chat=${encodeURIComponent(chat)}`, { cache: "no-store" });+ if (!res.ok) throw new Error(`browser status → ${res.status}`);+ return (await res.json()) as BrowserStatus;+}++/** The current picture of the chat's tab; `tick` defeats the image cache. */+export function frameUrl(chat: string, quality: number, tick: number): string {+ return `${BASE}?chat=${encodeURIComponent(chat)}&frame=1&q=${quality}&t=${tick}`;+}++export const browserOpen = (chat: string, url: string, width: number, height: number) =>+ browserCall<PageInfo>(chat, "open", { url, width, height });+export const browserNavigate = (chat: string, url: string) => browserCall<PageInfo>(chat, "navigate", { url });+export const browserNav = (chat: string, method: "back" | "forward" | "reload" | "info") => browserCall<PageInfo>(chat, method);+export const browserViewport = (chat: string, width: number, height: number) =>+ browserCall<{ width: number; height: number }>(chat, "viewport", { width, height });+export const browserInput = (chat: string, event: InputEvent) => browserCall<{ ok: true }>(chat, "input", event);+export const browserHover = (chat: string, x: number, y: number) => browserCall<HoverHit | null>(chat, "hover", { x, y });+export const browserInspect = (chat: string, x: number, y: number) => browserCall<InspectHit | null>(chat, "inspect", { x, y });+export const browserHighlight = (chat: string, target: { ref: string } | { selector: string }) =>+ browserCall<{ ok: true }>(chat, "highlight", target);+export const browserHandle = (chat: string) => browserCall<KuriHandle | null>(chat, "handle");+export const browserClose = (chat: string) => browserCall<{ ok: true }>(chat, "close");+export const browserStop = (chat: string) => browserCall<{ kuri: KuriState }>(chat, "stop");diff --git a/apps/native/lib/browser/annotations.test.ts b/apps/native/lib/browser/annotations.test.tsnew file mode 100644index 00000000..ea559dbc--- /dev/null+++ b/apps/native/lib/browser/annotations.test.ts@@ -0,0 +1,84 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { annotationsBlock, describePin, matchRef, parseSnapshotRefs, type BrowserPin } from "./annotations.ts";++const SNAP = `RootWebArea "Example Domain" [focused]+heading "Example Domain"+StaticText "This domain is for use in documentation"+link "Learn more" @e2_21+button "Say \\"hi\\"" @e5+button "Submit" @e6+link "Submit" @e7+`;++describe("parseSnapshotRefs", () => {+ it("keeps only lines with refs and unescapes names", () => {+ const rows = parseSnapshotRefs(SNAP);+ assert.deepEqual(rows, [+ { role: "link", name: "Learn more", ref: "e2_21" },+ { role: "button", name: 'Say "hi"', ref: "e5" },+ { role: "button", name: "Submit", ref: "e6" },+ { role: "link", name: "Submit", ref: "e7" },+ ]);+ });+});++describe("matchRef", () => {+ const rows = parseSnapshotRefs(SNAP);+ it("matches by accessible name, case and whitespace insensitive", () => {+ assert.equal(matchRef(rows, { name: " learn MORE ", role: "", text: "" }), "e2_21");+ });+ it("uses the role to disambiguate a shared name", () => {+ assert.equal(matchRef(rows, { name: "Submit", role: "button", text: "" }), "e6");+ assert.equal(matchRef(rows, { name: "Submit", role: "link", text: "" }), "e7");+ });+ it("refuses an ambiguous name and an empty one", () => {+ assert.equal(matchRef(rows, { name: "Submit", role: "", text: "" }), null);+ assert.equal(matchRef(rows, { name: "", role: "button", text: "" }), null);+ });+ it("falls back to the element text when it has no name", () => {+ assert.equal(matchRef(rows, { name: "", role: "link", text: "Learn more" }), "e2_21");+ });+});++const pin = (id: number, comment: string, ref: string | null = null): BrowserPin => ({+ id,+ comment,+ url: "https://example.com/",+ title: "Example Domain",+ ref,+ element: {+ tag: "a",+ role: "link",+ name: "Learn more",+ text: "Learn more",+ selector: "div > p:nth-of-type(2) > a",+ href: "https://www.iana.org/domains/example",+ rect: { x: 40.4, y: 300.6, w: 120.2, h: 24 },+ },+ point: { x: 60, y: 310 },+});++describe("annotationsBlock", () => {+ it("is empty without pins", () => {+ assert.equal(annotationsBlock([], null), "");+ });+ it("names the page, each pin, and how to drive the tab", () => {+ const block = annotationsBlock([pin(1, "make this blue", "e2_21"), pin(2, "")], {+ port: 8091,+ token: "tok",+ tabId: "ABC",+ });+ assert.match(block, /^### Browser annotations \(sidecar\)\nPage: Example Domain — https:\/\/example\.com\//);+ assert.match(block, /1\. \[@e2_21\] link "Learn more" \(div > p:nth-of-type\(2\) > a, 120×24 at 40,301\): make this blue/);+ assert.match(block, /2\. link "Learn more" \(div > p:nth-of-type\(2\) > a, 120×24 at 40,301\)\n/);+ assert.match(block, /tab_id=ABC/);+ assert.match(block, /Bearer tok/);+ assert.match(block, /8091/);+ });+ it("describes an element without a name by its tag", () => {+ const p = pin(3, "x");+ p.element = { ...p.element, role: "", name: "" };+ assert.equal(describePin(p), "a (div > p:nth-of-type(2) > a, 120×24 at 40,301)");+ });+});diff --git a/apps/native/lib/browser/annotations.ts b/apps/native/lib/browser/annotations.tsnew file mode 100644index 00000000..47415df3--- /dev/null+++ b/apps/native/lib/browser/annotations.ts@@ -0,0 +1,112 @@+/** Browser annotations: the pins a user drops on the sidecar's page and the+ * block that carries them to the agent. Pure helpers, shared by the pane+ * (browser) and the route (server), tested without a DOM. */++export type PinRect = { x: number; y: number; w: number; h: number };++/** What the page said about the element under the pointer. */+export type PinElement = {+ tag: string;+ role: string;+ name: string;+ text: string;+ selector: string;+ href: string | null;+ rect: PinRect;+};++export type BrowserPin = {+ id: number;+ /** What the user wants done here. */+ comment: string;+ url: string;+ title: string;+ /** Kuri's ref for the same element (`e7`), when the snapshot names it. */+ ref: string | null;+ element: PinElement;+ /** Viewport point of the click, CSS pixels. */+ point: { x: number; y: number };+};++export type SnapshotRow = { role: string; name: string; ref: string };++/** Kuri's compact snapshot: one element per line, `role "name" @eN`, refs+ * only on interactive nodes. Names may contain escaped quotes. */+export function parseSnapshotRefs(snapshot: string): SnapshotRow[] {+ const rows: SnapshotRow[] = [];+ for (const raw of snapshot.split("\n")) {+ const line = raw.trim();+ const at = line.lastIndexOf(" @");+ if (at < 0) continue;+ const ref = line.slice(at + 2).split(/\s/)[0];+ if (!/^e[\w]+$/.test(ref)) continue;+ const head = line.slice(0, at);+ const quote = head.indexOf(' "');+ const role = (quote < 0 ? head : head.slice(0, quote)).trim().split(/\s/)[0] ?? "";+ let name = "";+ if (quote >= 0) {+ const rest = head.slice(quote + 2);+ const close = rest.lastIndexOf('"');+ name = (close >= 0 ? rest.slice(0, close) : rest).replace(/\\"/g, '"');+ }+ rows.push({ role, name, ref });+ }+ return rows;+}++function norm(s: string): string {+ return s.trim().replace(/\s+/g, " ").toLowerCase();+}++/** The ref whose accessible name matches the pinned element. Role must+ * agree when the page gave one; a name shared by several nodes is no+ * match — a wrong ref is worse than none. */+export function matchRef(rows: readonly SnapshotRow[], element: Pick<PinElement, "name" | "role" | "text">): string | null {+ const wanted = norm(element.name) || norm(element.text);+ if (!wanted) return null;+ const role = norm(element.role);+ const byName = rows.filter((r) => norm(r.name) === wanted);+ const pool = role ? byName.filter((r) => norm(r.role) === role) : byName;+ const hits = pool.length > 0 ? pool : byName;+ return hits.length === 1 ? hits[0].ref : null;+}++export function describePin(pin: BrowserPin): string {+ const el = pin.element;+ const what = [el.role || el.tag, el.name ? `"${el.name}"` : ""].filter(Boolean).join(" ");+ const where = `${Math.round(el.rect.w)}×${Math.round(el.rect.h)} at ${Math.round(el.rect.x)},${Math.round(el.rect.y)}`;+ const ref = pin.ref ? `[@${pin.ref}] ` : "";+ return `${ref}${what} (${el.selector}, ${where})`;+}++export type KuriHandle = { port: number; token: string; tabId: string };++/** The markdown block that goes ahead of the user's prompt. It names the+ * page, lists every pin with the element's identity and the user's note,+ * and tells the agent how to drive the very same tab. */+export function annotationsBlock(pins: readonly BrowserPin[], kuri: KuriHandle | null): string {+ if (pins.length === 0) return "";+ const first = pins[0];+ const lines: string[] = [];+ lines.push("### Browser annotations (sidecar)");+ lines.push(`Page: ${first.title || "(untitled)"} — ${first.url}`);+ pins.forEach((pin, i) => {+ const note = pin.comment.trim() ? `: ${pin.comment.trim()}` : "";+ lines.push(`${i + 1}. ${describePin(pin)}${note}`);+ if (pin.element.text && pin.element.text !== pin.element.name) lines.push(` text: "${pin.element.text.slice(0, 120)}"`);+ if (pin.url !== first.url) lines.push(` on: ${pin.url}`);+ });+ if (kuri) {+ const ref = pins.find((p) => p.ref)?.ref ?? "e7";+ lines.push("");+ lines.push(+ `The page is open in the sidecar browser (kuri) at http://127.0.0.1:${kuri.port}, tab_id=${kuri.tabId}, ` ++ `header \`Authorization: Bearer ${kuri.token}\`. Re-read it with ` ++ `GET /snapshot?tab_id=${kuri.tabId}&filter=interactive&format=compact, act on a ref with ` ++ `GET /action?tab_id=${kuri.tabId}&ref=${ref}&action=click (also type/fill/hover/scroll), ` ++ `run JS with GET /evaluate?tab_id=${kuri.tabId}&expression=…, and GET /highlight?tab_id=${kuri.tabId}&ref=${ref} ` ++ `shows the user what you mean. The user sees that tab live.`,+ );+ }+ return lines.join("\n");+}diff --git a/apps/native/lib/browser/inspect-script.ts b/apps/native/lib/browser/inspect-script.tsnew file mode 100644index 00000000..6d0e5f3d--- /dev/null+++ b/apps/native/lib/browser/inspect-script.ts@@ -0,0 +1,79 @@+/** The JavaScript the route evaluates in the sidecar's page to identify+ * the element under a viewport point. Nothing is injected or persisted:+ * every hover or click is one `Runtime.evaluate`, so it works on any page+ * regardless of its content security policy. */++const SOURCE = String.raw`(function (x, y) {+ var el = document.elementFromPoint(x, y);+ if (!el) return null;+ var r = el.getBoundingClientRect();+ var attr = function (n) { return el.getAttribute(n) || ""; };+ var squash = function (s) { return (s || "").replace(/\s+/g, " ").trim(); };+ var ROLES = { A: "link", BUTTON: "button", INPUT: "textbox", TEXTAREA: "textbox", SELECT: "combobox", IMG: "img",+ H1: "heading", H2: "heading", H3: "heading", H4: "heading", NAV: "navigation", MAIN: "main", FORM: "form",+ LI: "listitem", UL: "list", OL: "list", TABLE: "table", LABEL: "label", SUMMARY: "button" };+ var tag = el.tagName;+ var role = attr("role") || ROLES[tag] || "";+ if (tag === "INPUT") {+ var t = (el.getAttribute("type") || "text").toLowerCase();+ role = t === "checkbox" ? "checkbox" : t === "radio" ? "radio" : t === "submit" || t === "button" ? "button" : "textbox";+ }+ var labelled = "";+ if (el.labels && el.labels.length) labelled = squash(el.labels[0].textContent);+ var name = attr("aria-label") || labelled || attr("alt") || attr("title") || attr("placeholder") || attr("value") || squash(el.innerText || el.textContent).slice(0, 80);+ var seg = function (e) {+ if (e.id) return "#" + CSS.escape(e.id);+ var tid = e.getAttribute("data-testid");+ if (tid) return e.tagName.toLowerCase() + "[data-testid=\"" + tid + "\"]";+ var s = e.tagName.toLowerCase();+ var cls = Array.prototype.filter.call(e.classList, function (c) { return !/[:\[\]\/!@]/.test(c); }).slice(0, 2);+ if (cls.length) s += "." + cls.map(function (c) { return CSS.escape(c); }).join(".");+ var p = e.parentElement;+ if (p) {+ var same = Array.prototype.filter.call(p.children, function (c) { return c.tagName === e.tagName; });+ if (same.length > 1) s += ":nth-of-type(" + (same.indexOf(e) + 1) + ")";+ }+ return s;+ };+ var parts = [];+ var cur = el;+ while (cur && cur !== document.body && cur !== document.documentElement && parts.length < 4) {+ parts.unshift(seg(cur));+ if (cur.id) break;+ cur = cur.parentElement;+ }+ return {+ tag: tag.toLowerCase(),+ role: role,+ name: squash(name).slice(0, 80),+ text: squash(el.innerText || el.textContent).slice(0, 160),+ selector: parts.join(" > "),+ href: el.href ? String(el.href) : null,+ rect: { x: r.left, y: r.top, w: r.width, h: r.height },+ url: location.href,+ title: document.title+ };+})(__X__, __Y__)`;++/** Kuri reads a request head into an 8 KB buffer, and the expression rides+ * in the query string, so the source is collapsed to one line first. No+ * string literal above spans lines or holds runs of spaces. */+function compact(source: string): string {+ return source.replace(/\s*\n\s*/g, " ").replace(/ {2,}/g, " ").trim();+}++export function inspectExpression(x: number, y: number): string {+ return compact(SOURCE).replace("__X__", String(Math.round(x))).replace("__Y__", String(Math.round(y)));+}++/** The same lookup, rect only: what hover needs at ten calls a second. */+export const HOVER_SOURCE = String.raw`(function (x, y) {+ var el = document.elementFromPoint(x, y);+ if (!el) return null;+ var r = el.getBoundingClientRect();+ return { rect: { x: r.left, y: r.top, w: r.width, h: r.height }, tag: el.tagName.toLowerCase() };+})(__X__, __Y__)`;++export function hoverExpression(x: number, y: number): string {+ return compact(HOVER_SOURCE).replace("__X__", String(Math.round(x))).replace("__Y__", String(Math.round(y)));+}diff --git a/apps/native/lib/browser/kuri-supervisor.ts b/apps/native/lib/browser/kuri-supervisor.tsnew file mode 100644index 00000000..936b3ec8--- /dev/null+++ b/apps/native/lib/browser/kuri-supervisor.ts@@ -0,0 +1,283 @@+import { spawn, spawnSync, type ChildProcess } from "node:child_process";+import { randomBytes } from "node:crypto";+import { existsSync, mkdirSync } from "node:fs";+import net from "node:net";+import os from "node:os";+import path from "node:path";++/** The sidecar's browser is Kuri's managed Chrome (headless, its own profile+ * under ~/.codegraff/browser). Nothing runs until the first request needs+ * it; a quiet spell stops it again, so a closed pane costs no processes.+ * One Kuri per dev server, kept on globalThis so module reloads do not+ * orphan a Chrome. Kuri kills its Chrome when it is stopped. */++export type KuriState = {+ running: boolean;+ port: number | null;+ pid: number | null;+ startedMs: number | null;+ lastUsedMs: number | null;+ bin: string | null;+ idleMs: number;+};++type Live = {+ child: ChildProcess;+ port: number;+ token: string;+ startedMs: number;+ lastUsedMs: number;+ idleTimer: NodeJS.Timeout | null;+ ready: Promise<void>;+};++const g = globalThis as typeof globalThis & { __graffKuri?: { live: Live | null; hooked: boolean } };+const state = (g.__graffKuri ??= { live: null, hooked: false });++const FIRST_PORT = 8091;+// Kuri answers /health only once its Chrome is up, and a launch that hits+// a stale profile lock retries three times at fifteen seconds each.+const HEALTH_TIMEOUT_MS = 75_000;++/** `KURI_BIN`, the installer's `~/.local/bin/kuri`, a source build, then PATH. */+export function kuriBin(): string | null {+ const home = os.homedir();+ const named = [process.env.KURI_BIN, path.join(home, ".local/bin/kuri"), path.join(home, "kuri/zig-out/bin/kuri")];+ for (const candidate of named) if (candidate && existsSync(candidate)) return candidate;+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {+ if (!dir) continue;+ const candidate = path.join(dir, "kuri");+ if (existsSync(candidate)) return candidate;+ }+ return null;+}++/** Minutes of silence before the browser is stopped; 0 keeps it forever. */+export function idleMs(): number {+ const raw = process.env.GRAFF_BROWSER_IDLE_MINS;+ const mins = raw === undefined || raw === "" ? 20 : Number(raw);+ if (!Number.isFinite(mins) || mins < 0) return 20 * 60_000;+ return Math.min(mins, 7 * 24 * 60) * 60_000;+}++function portFree(port: number): Promise<boolean> {+ return new Promise((resolve) => {+ const probe = net.createServer();+ probe.once("error", () => resolve(false));+ probe.listen(port, "127.0.0.1", () => probe.close(() => resolve(true)));+ });+}++async function freePort(): Promise<number> {+ for (let port = FIRST_PORT; port < FIRST_PORT + 60; port += 1) {+ if (await portFree(port)) return port;+ }+ throw new Error("no free port for the sidecar browser");+}++async function waitHealthy(port: number, token: string, child: ChildProcess): Promise<void> {+ const deadline = Date.now() + HEALTH_TIMEOUT_MS;+ while (Date.now() < deadline) {+ if (child.exitCode !== null) throw new Error(`kuri exited with code ${child.exitCode} before it was healthy`);+ try {+ const res = await fetch(`http://127.0.0.1:${port}/health`, {+ headers: { authorization: `Bearer ${token}` },+ cache: "no-store",+ });+ if (res.ok) return;+ } catch {+ // not listening yet+ }+ await new Promise((r) => setTimeout(r, 250));+ }+ throw new Error("kuri did not become healthy in time");+}++function armIdle(live: Live): void {+ if (live.idleTimer) clearTimeout(live.idleTimer);+ const ms = idleMs();+ if (ms === 0) return;+ live.idleTimer = setTimeout(() => {+ const quiet = Date.now() - live.lastUsedMs;+ if (quiet >= ms) {+ if (state.live === live) stopKuri();+ } else {+ armIdle(live);+ }+ }, Math.max(1_000, ms - (Date.now() - live.lastUsedMs)));+ live.idleTimer.unref();+}++function hookExit(): void {+ if (state.hooked) return;+ state.hooked = true;+ process.once("exit", () => stopKuri());+}++const STATE_DIR = path.join(os.homedir(), ".codegraff", "browser");+const PRIVATE_HOME = path.join(STATE_DIR, "home");+/** Every Chrome the sidecar's Kuri launches carries this in its argv. */+const PROFILE_MARK = path.join(PRIVATE_HOME, ".kuri", "chrome-profile");++/** Chrome renderers that outlived their Kuri (the dev server died before+ * Kuri could wind them down) hold the profile's lock and stall the next+ * launch by a minute. The profile is private to the sidecar, so killing+ * whatever still runs on it is safe. Synchronous: this also runs from the+ * process's exit handler, where nothing asynchronous gets a turn. */+function reapProfileChrome(): void {+ if (process.platform === "win32") return;+ try {+ spawnSync("pkill", ["-f", PROFILE_MARK], { stdio: "ignore", timeout: 2_000 });+ } catch {+ // pkill missing or no match+ }+}++/** The live Kuri, spawning it when there is none. */+export async function ensureKuri(): Promise<{ port: number; token: string }> {+ const live = state.live;+ if (live && live.child.exitCode === null) {+ live.lastUsedMs = Date.now();+ await live.ready;+ return { port: live.port, token: live.token };+ }+ const bin = kuriBin();+ if (!bin) {+ throw new Error(+ "kuri is not installed: run `curl -fsSL https://kuri.trilok.ai/download | sh` or set KURI_BIN to the binary",+ );+ }+ const port = await freePort();+ const token = randomBytes(16).toString("hex");+ // Kuri keeps its Chrome profile at $HOME/.kuri/chrome-profile-headless,+ // one per user, and two Chromes cannot share a profile: a `kuri` the+ // user runs for other agents would lock ours out (and the other way+ // round). A private HOME gives the sidecar its own profile and state.+ mkdirSync(PRIVATE_HOME, { recursive: true });+ reapProfileChrome();+ const child = spawn(bin, [], {+ env: {+ ...process.env,+ HOME: PRIVATE_HOME,+ HOST: "127.0.0.1",+ PORT: String(port),+ HEADLESS: "true",+ STATE_DIR: path.join(STATE_DIR, "state"),+ KURI_API_TOKEN: token,+ KURI_NO_TELEMETRY: "1",+ },+ // Kuri's own log goes to the dev server's terminal like the agents' do.+ stdio: ["ignore", "ignore", "inherit"],+ });+ const next: Live = {+ child,+ port,+ token,+ startedMs: Date.now(),+ lastUsedMs: Date.now(),+ idleTimer: null,+ ready: Promise.resolve(),+ };+ next.ready = waitHealthy(port, token, child);+ child.on("exit", () => {+ if (state.live === next) state.live = null;+ if (next.idleTimer) clearTimeout(next.idleTimer);+ });+ state.live = next;+ hookExit();+ armIdle(next);+ try {+ await next.ready;+ } catch (err) {+ stopKuri();+ throw err;+ }+ return { port, token };+}++export function touchKuri(): void {+ if (state.live) state.live.lastUsedMs = Date.now();+}++/** SIGTERM, then SIGKILL if it lingers. Kuri takes its Chrome down with it+ * when it gets the chance; the profile reap covers the times it does not. */+export function stopKuri(): void {+ const live = state.live;+ if (!live) return;+ state.live = null;+ if (live.idleTimer) clearTimeout(live.idleTimer);+ try {+ live.child.kill("SIGTERM");+ } catch {+ // already gone+ }+ const hard = setTimeout(() => {+ if (live.child.exitCode === null) {+ try {+ live.child.kill("SIGKILL");+ } catch {+ // already gone+ }+ }+ reapProfileChrome();+ }, 3_000);+ hard.unref();+ // The exit handler gets no timers: reap now as well, so a dev server+ // that dies takes the sidecar's Chrome with it.+ reapProfileChrome();+}++export function kuriState(): KuriState {+ const live = state.live && state.live.child.exitCode === null ? state.live : null;+ return {+ running: live !== null,+ port: live?.port ?? null,+ pid: live?.child.pid ?? null,+ startedMs: live?.startedMs ?? null,+ lastUsedMs: live?.lastUsedMs ?? null,+ bin: kuriBin(),+ idleMs: idleMs(),+ };+}++/** The live Kuri's address for a caller that wants to drive the same+ * browser itself (the agent, over curl); null when nothing is running. */+export function kuriAddress(): { port: number; token: string } | null {+ const live = state.live && state.live.child.exitCode === null ? state.live : null;+ return live ? { port: live.port, token: live.token } : null;+}++/** One Kuri HTTP call; spawns the browser on first use. */+export async function kuri(pathAndQuery: string, init?: RequestInit): Promise<Response> {+ const { port, token } = await ensureKuri();+ touchKuri();+ return fetch(`http://127.0.0.1:${port}${pathAndQuery}`, {+ ...init,+ headers: { authorization: `Bearer ${token}`, ...(init?.headers ?? {}) },+ cache: "no-store",+ });+}++export async function kuriJson<T = Record<string, unknown>>(pathAndQuery: string, init?: RequestInit): Promise<T> {+ const res = await kuri(pathAndQuery, init);+ const text = await res.text();+ let body: unknown;+ try {+ body = JSON.parse(text);+ } catch {+ if (!res.ok) throw new Error(`kuri ${res.status}: ${text.slice(0, 200)}`);+ return text as unknown as T;+ }+ const rec = body as { error?: unknown };+ if (!res.ok || (rec && typeof rec === "object" && typeof rec.error === "string")) {+ throw new Error(typeof rec.error === "string" ? rec.error : `kuri ${res.status}`);+ }+ return body as T;+}++export function q(params: Record<string, string | number | boolean | undefined>): string {+ const u = new URLSearchParams();+ for (const [k, v] of Object.entries(params)) if (v !== undefined) u.set(k, String(v));+ const s = u.toString();+ return s ? `?${s}` : "";+}diff --git a/apps/native/lib/browser/url.test.ts b/apps/native/lib/browser/url.test.tsnew file mode 100644index 00000000..75902ef4--- /dev/null+++ b/apps/native/lib/browser/url.test.ts@@ -0,0 +1,22 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { normalizeUrl } from "./url.ts";++describe("normalizeUrl", () => {+ it("keeps a full URL and any explicit scheme", () => {+ assert.equal(normalizeUrl("https://example.com/x?y=1"), "https://example.com/x?y=1");+ assert.equal(normalizeUrl("http://localhost:3000"), "http://localhost:3000");+ assert.equal(normalizeUrl("about:blank"), "about:blank");+ });+ it("gives a bare host https and a local address http", () => {+ assert.equal(normalizeUrl("example.com"), "https://example.com");+ assert.equal(normalizeUrl(" news.ycombinator.com/newest "), "https://news.ycombinator.com/newest");+ assert.equal(normalizeUrl("localhost:3000"), "http://localhost:3000");+ assert.equal(normalizeUrl("127.0.0.1:8080/health"), "http://127.0.0.1:8080/health");+ assert.equal(normalizeUrl("192.168.1.20"), "http://192.168.1.20");+ });+ it("means a blank page when empty", () => {+ assert.equal(normalizeUrl(""), "about:blank");+ assert.equal(normalizeUrl(" "), "about:blank");+ });+});diff --git a/apps/native/lib/browser/url.ts b/apps/native/lib/browser/url.tsnew file mode 100644index 00000000..717c846f--- /dev/null+++ b/apps/native/lib/browser/url.ts@@ -0,0 +1,12 @@+/** What the address bar accepts: a full URL, a bare host, or a local+ * address. A bare host becomes https; localhost and raw addresses stay+ * http, since dev servers rarely speak TLS. Empty means a blank page. */+export function normalizeUrl(raw: string): string {+ const t = raw.trim();+ if (!t) return "about:blank";+ // `localhost:3000` is a host and port, not a scheme: a scheme needs `//`+ // after it, except the few that never carry one.+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(t) || /^(about|data|blob|file|javascript):/i.test(t)) return t;+ const local = /^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|\d+\.\d+\.\d+\.\d+)(:\d+)?(\/|$)/i.test(t);+ return `${local ? "http" : "https"}://${t}`;+}diff --git a/apps/native/lib/icons.tsx b/apps/native/lib/icons.tsxindex 4affb30f..7b840076 100644--- a/apps/native/lib/icons.tsx+++ b/apps/native/lib/icons.tsx@@ -140,6 +140,16 @@ export function IconSidebarLeftOpen(p: IconProps) {);}+/** The sidecar browser. */+export function IconGlobe(p: IconProps) {+ return (+ <Svg {...p}>+ <circle cx="12" cy="12" r="8.5" />+ <path d="M3.5 12h17M12 3.5c2.7 2.7 2.7 14.3 0 17M12 3.5c-2.7 2.7-2.7 14.3 0 17" />+ </Svg>+ );+}+/** Brand mark — graff G instead of the paid popsicle. */export function IconPopsicle2(p: IconProps) {return (diff --git a/apps/native/package.json b/apps/native/package.jsonindex 5bcd6909..3a84a96b 100644--- a/apps/native/package.json+++ b/apps/native/package.json@@ -10,7 +10,7 @@"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000","mock-serve": "node scripts/mock-serve.mjs","lint": "next lint",- "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-history.test.ts lib/workspaces.test.ts"+ "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-history.test.ts lib/workspaces.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts"},"dependencies": {"@streamdown/code": "^1.1.1",diff --git a/plans/2026-09-03-browser-sidecar.md b/plans/2026-09-03-browser-sidecar.mdnew file mode 100644index 00000000..80de0753--- /dev/null+++ b/plans/2026-09-03-browser-sidecar.md@@ -0,0 +1,102 @@+# Browser sidecar with built-in annotations++Branch `feat/browser-sidecar`, off `release/v0.0.285`. Throwaway by design:+everything lives under `apps/native` plus one plan file, nothing touches the+Zig harness, so the branch can be deleted without a trace if the idea does+not earn its keep.++## What it is++A pane beside the transcript that shows a live Chrome tab, one per chat,+driven by [Kuri](https://github.com/justrach/kuri) (managed headless Chrome+over CDP, a single Zig binary). Two modes:++- **Browse.** The pointer, wheel and keyboard are forwarded to the page.+- **Annotate.** A click pins the element under it with a note. Pins are+ drawn over the frame from geometry the page reports, and the next prompt+ carries them ahead of the user's text: element identity (role, name,+ selector, size, position), the note, the page, and — when Kuri's snapshot+ names the same element — the `@eN` ref the agent's own actions take.++The block also tells the agent where the tab is (Kuri's port, the tab id,+the bearer token) and the four calls that matter: snapshot, action, evaluate,+highlight. The agent drives the very tab the user is looking at, and can+highlight an element back at them.++This is the agentation idea moved into the browser: no package in the app+under test, works on any page, and the output is actionable rather than+descriptive because it carries Kuri refs.++## Why the annotation layer is not injected into the page++The first design put an overlay script into every document via Kuri's+`/script/inject` (`Page.addScriptToEvaluateOnNewDocument`) and a+`Runtime.addBinding` channel (`/expose`, `/expose/calls`). Both work, and+the binding survives navigation. Two things argued against it for v1:++- Kuri reads a request head into an 8 KB buffer and takes the script in the+ query string, so an overlay bundle does not fit in one request, and a+ loader stub would need a fetch the page's content security policy may+ block.+- Everything the overlay needs — the element under a point, its accessible+ name, a stable selector, its box — is one `Runtime.evaluate` away, and+ drawing the outline and pins in the pane is trivial.++So hover and click each cost one `/evaluate` (a ~2 KB expression built by+`lib/browser/inspect-script.ts`), and the page is never modified. The+injected overlay stays the right answer for a *headed* Chrome window the+user clicks in directly; that is a later step.++## Lazy loading and resources++- Nothing runs until the pane is opened: `GET /api/browser` (status) and+ the frame endpoint never spawn. `POST open` is the only spawner.+- `lib/browser/kuri-supervisor.ts` starts one Kuri per dev server on the+ first free port from 8091, `HEADLESS=true`, its own profile under+ `~/.codegraff/browser`, a random bearer token, telemetry off. Kuri kills+ its Chrome when it is stopped.+- Idle stop after `GRAFF_BROWSER_IDLE_MINS` (default 20, 0 = never) of no+ requests. Frames count as use, so an open pane keeps it; a closed pane+ lets it go. The dev server's exit stops it too.+- Frames are JPEG (`/screenshot`, quality 55) requested one after another;+ a hidden tab drops to one frame every two seconds rather than stopping,+ so the picture is fresh the moment the tab comes back. (Stopping outright+ was tried first; Chrome's automation tabs report `document.hidden` even+ while visible, and a stopped loop looked like a broken pane.)+- The viewport is set to the pane's size, so frames are 1:1 and small.++## Pieces++| Piece | File |+|---|---|+| Kuri lifecycle, HTTP helper | `apps/native/lib/browser/kuri-supervisor.ts` |+| Element lookup expressions | `apps/native/lib/browser/inspect-script.ts` |+| Pin types, ref matching, prompt block (tested) | `apps/native/lib/browser/annotations.ts` |+| Route: status, frame, open/navigate/input/hover/inspect/snapshot/highlight | `apps/native/app/api/browser/route.ts` |+| Browser-side client | `apps/native/lib/browser-client.ts` |+| The pane | `apps/native/components/site/BrowserPane.tsx` |+| Harness wiring: tab-bar button, sidebar item, pins chip, prompt block | `components/site/GraffHarness.tsx`, `SidebarNav.tsx` |++## Not in v1, in order of value++1. **Agent tools instead of curl.** A stdio MCP shim that proxies to+ `/api/browser` would give the agent `browser_snapshot` / `browser_act` /+ `browser_highlight` without the bearer token in the prompt. Kuri ships a+ `kuri-mcp` binary, but it owns its own Chrome; the shim keeps one tab+ shared between the user and the agent.+2. **Headed mode.** `HEADLESS=false` gives a real window the user can click+ in; the pane becomes optional. That is where the injected overlay earns+ its place (pins made in the window, not the pane).+3. **Screenshot crops per pin** in the prompt block, for models that read+ images (`/screenshot` takes a clip).+4. **Ref stamping in Kuri.** Have `/snapshot` write `data-kuri-ref` on the+ nodes it numbers; then `inspect` reads the ref straight off the element+ instead of matching by accessible name.+5. Per-workspace start URL (a dev server per project) and a "tab is+ loading" indicator from `ready_state`.++## Abandon criteria++Frame polling too heavy on a laptop, or the pane too narrow to be useful at+1:1, or the annotation block not moving the agent's behaviour in practice.+Any of those, and the branch goes; the release branch is untouched.