graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(native): browser annotations that work — instant local hover and pin, scroll in both modes, pins follow the page, Ask graff; Kuri self-heal
justrach8ed9e5deb2f4
diff --git a/apps/native/README.md b/apps/native/README.mdindex 1608e72f..f5d7d8f8 100644--- a/apps/native/README.md+++ b/apps/native/README.md@@ -113,13 +113,17 @@ sees no requests for `GRAFF_BROWSER_IDLE_MINS` (default 20, `0` = never) isstopped 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.+- **Annotate** pins the element under a click, instantly: the page's+ pinnable elements (boxes, names, selectors, Kuri refs) are fetched as+ one map and hit-tested in the pane, so hover and click never wait on+ the network; the map refreshes after a scroll and every few seconds.+ A note is optional. Pins keep page coordinates and follow the page as+ it scrolls; scrolling works in both modes. Nothing is injected, so any+ page works. Pins go behind 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. **Ask graff** in the pane sends them right away.The design and what is deliberately left out are in`plans/2026-09-03-browser-sidecar.md`. The sidebar footer names the tab's graffdiff --git a/apps/native/app/api/browser/route.ts b/apps/native/app/api/browser/route.tsindex 60782686..e920dbc4 100644--- a/apps/native/app/api/browser/route.ts+++ b/apps/native/app/api/browser/route.ts@@ -1,6 +1,6 @@import { NextRequest } from "next/server";import { matchRef, parseSnapshotRefs, type PinElement } from "@/lib/browser/annotations";-import { hoverExpression, inspectExpression } from "@/lib/browser/inspect-script";+import { hoverExpression, inspectExpression, mapExpression } from "@/lib/browser/inspect-script";import { ensureKuri, kuriAddress, kuriJson, kuriState, q, stopKuri } from "@/lib/browser/kuri-supervisor";import { normalizeUrl } from "@/lib/browser/url";@@ -13,10 +13,34 @@ export const dynamic = "force-dynamic";* 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 };+/** `url` is the last address the tab was known to show: if Kuri dies, the+ * chat's tab is recreated there on the next request. */+type Tab = { id: string; width: number; height: number; url?: string };-const g = globalThis as typeof globalThis & { __graffBrowserTabs?: Map<string, Tab> };+const g = globalThis as typeof globalThis & {+ __graffBrowserTabs?: Map<string, Tab>;+ __graffBrowserChains?: Map<string, Promise<void>>;+};const tabs = (g.__graffBrowserTabs ??= new Map<string, Tab>());+const chains = (g.__graffBrowserChains ??= new Map<string, Promise<void>>());++/** One request at a time per chat. Kuri handles each HTTP connection on+ * its own thread, and two of them driving the same tab's CDP client at+ * once (a frame and an element map, say) segfaulted it in+ * `CdpClient.send`. Different chats, different tabs, still overlap. */+function serial<T>(key: string, fn: () => Promise<T>): Promise<T> {+ const prev = chains.get(key) ?? Promise.resolve();+ const run = prev.catch(() => undefined).then(fn);+ const settled: Promise<void> = run.then(+ () => undefined,+ () => undefined,+ );+ chains.set(key, settled);+ void settled.then(() => {+ if (chains.get(key) === settled) chains.delete(key);+ });+ return run;+}const DEFAULT_CHAT = "default";const DEFAULT_SIZE = { width: 960, height: 640 };@@ -58,8 +82,23 @@ async function ensureTab(chat: string, size?: { width: number; height: number })return tab;}+/** The chat's tab, brought back if Kuri (and the tab with it) went away:+ * a fresh Kuri, a fresh tab at the same size, back on the last address. */+async function reviveTab(chat: string): Promise<Tab | null> {+ const have = tabs.get(chat);+ if (!have) return null;+ if (kuriAddress() && (await tabAlive(have.id))) return have;+ const fresh = await ensureTab(chat, { width: have.width, height: have.height });+ if (have.url && have.url !== "about:blank") {+ await kuriJson(`/navigate${q({ tab_id: fresh.id, url: have.url })}`).catch(() => undefined);+ fresh.url = have.url;+ }+ return fresh;+}+async function pageInfo(tab: Tab): Promise<PageInfo> {const info = await kuriJson<KuriPageInfo>(`/page/info${q({ tab_id: tab.id })}`);+ if (info.url) tab.url = info.url;return {tabId: tab.id,url: info.url ?? "",@@ -96,8 +135,8 @@ export async function GET(req: NextRequest) {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 shot = await serial(chat, () =>+ 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 });@@ -124,6 +163,10 @@ export async function POST(req: NextRequest) {const chat = typeof body.chat === "string" && body.chat ? body.chat : DEFAULT_CHAT;const method = body.method ?? "";const params = body.params ?? {};+ return serial(chat, () => handle(chat, method, params));+}++async function handle(chat: string, method: string, params: Record<string, unknown>): Promise<Response> {try {if (method === "stop") {tabs.clear();@@ -150,8 +193,9 @@ export async function POST(req: NextRequest) {}// 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 });+ // One that was opened and lost its Kuri gets it back here.+ const tab = await reviveTab(chat);+ if (!tab) 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 ?? "")) })}`);@@ -236,6 +280,24 @@ export async function POST(req: NextRequest) {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 "map": {+ // Everything pinnable on screen, each with Kuri's ref when the+ // accessibility snapshot names the same element. One evaluate plus+ // one snapshot; the pane hit-tests the result locally.+ type MapEl = PinElement & { i: number };+ type Map = { url: string; title: string; vw: number; vh: number; scrollX: number; scrollY: number; els: MapEl[] };+ const map = await evaluate<Map>(tab, mapExpression());+ if (!map) return Response.json(null);+ let rows: ReturnType<typeof parseSnapshotRefs> = [];+ try {+ const snapshot = await kuriJson<string>(`/snapshot${q({ tab_id: tab.id, filter: "interactive", format: "compact" })}`);+ if (typeof snapshot === "string") rows = parseSnapshotRefs(snapshot);+ } catch {+ // mid-navigation: no refs this round+ }+ const els = map.els.map((el) => ({ ...el, ref: el.role ? matchRef(rows, el) : null }));+ return Response.json({ ...map, els });+ }case "highlight": {const target = typeof params.ref === "string" ? { ref: params.ref } : { selector: String(params.selector ?? "") };await kuriJson(`/highlight${q({ tab_id: tab.id, ...target })}`);diff --git a/apps/native/components/site/BrowserPane.tsx b/apps/native/components/site/BrowserPane.tsxindex fd22677a..266abddc 100644--- a/apps/native/components/site/BrowserPane.tsx+++ b/apps/native/components/site/BrowserPane.tsx@@ -10,16 +10,17 @@ import {type WheelEvent as ReactWheelEvent,} from "react";import {- browserHover,browserInput,- browserInspect,+ browserMap,browserNav,browserNavigate,browserOpen,browserStatus,browserViewport,frameUrl,- type InspectHit,+ hitTest,+ type ElementMap,+ type MapElement,type PageInfo,} from "@/lib/browser-client";import type { BrowserPin, PinRect } from "@/lib/browser/annotations";@@ -28,10 +29,12 @@ 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.+ * this chat. Browse mode forwards the pointer, wheel and keyboard. Annotate+ * mode pins the element under a click, instantly: the page's pinnable+ * elements are fetched as one map (boxes, names, selectors, Kuri refs) and+ * hit-tested here, so hover and click never wait on the network. Pins are+ * kept in page coordinates and follow the page as it scrolls. Nothing is+ * injected into the page, so any site works.* ───────────────────────────────────────────────────────── */type Mode = "browse" | "annotate";@@ -39,8 +42,9 @@ 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 MAP_REFRESH_MS = 2500;+const MAP_SETTLE_MS = 350;const PIN_STYLE = "flex size-5 items-center justify-center rounded-full bg-accent text-[10.5px] font-semibold text-white shadow-btn";@@ -71,10 +75,34 @@ function BarButton({ label, onClick, disabled, children }: { label: string; onCl);}+function elementLabel(el: { role: string; tag: string; name: string }): string {+ return `${el.role || el.tag}${el.name ? ` “${el.name}”` : ""}`;+}++/** Where a pin's marker sits now: its click point, moved by however far the+ * page has scrolled since it was placed. Null when it is off screen. */+function markerAt(pin: BrowserPin, map: ElementMap | null): { x: number; y: number } | null {+ if (!pin.doc) return pin.point;+ const scrollX = map?.scrollX ?? 0;+ const scrollY = map?.scrollY ?? 0;+ const x = pin.doc.x + (pin.point.x - pin.element.rect.x) - scrollX;+ const y = pin.doc.y + (pin.point.y - pin.element.rect.y) - scrollY;+ const vw = map?.vw ?? Infinity;+ const vh = map?.vh ?? Infinity;+ if (x < 0 || y < 0 || x > vw || y > vh) return null;+ return { x, y };+}++function pinBox(pin: BrowserPin, map: ElementMap | null): PinRect {+ if (!pin.doc) return pin.element.rect;+ return { x: pin.doc.x - (map?.scrollX ?? 0), y: pin.doc.y - (map?.scrollY ?? 0), w: pin.doc.w, h: pin.doc.h };+}+export default function BrowserPane({chat,pins,onPinsChange,+ onAsk,onClose,initialUrl,}: {@@ -82,6 +110,8 @@ export default function BrowserPane({chat: string;pins: BrowserPin[];onPinsChange: (next: BrowserPin[]) => void;+ /** Send the pins to the agent now, with a default request. */+ onAsk?: () => void;onClose: () => void;initialUrl?: string;}) {@@ -91,17 +121,20 @@ export default function BrowserPane({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 [map, setMap] = useState<ElementMap | null>(null);+ const [hoverEl, setHoverEl] = useState<MapElement | null>(null);+ const [editing, setEditing] = useState<number | null>(null);const frameRef = useRef<HTMLDivElement>(null);const imgRef = useRef<HTMLImageElement>(null);const urlRef = useRef<HTMLInputElement>(null);- const commentRef = useRef<HTMLInputElement>(null);+ const noteRef = useRef<HTMLInputElement>(null);const lastMove = useRef(0);- const lastHover = useRef(0);+ const mapSeq = useRef(0);+ const settleTimer = useRef(0);const infoRef = useRef<PageInfo | null>(null);infoRef.current = info;+ const mapRef = useRef<ElementMap | null>(null);+ mapRef.current = map;const paneSize = useCallback(() => {const el = frameRef.current;@@ -182,6 +215,35 @@ export default function BrowserPane({};}, [chat, tabId]);+ // The element map: what is pinnable on screen, and the scroll offset the+ // pins are placed against. Refreshed on a timer, after a scroll settles,+ // and whenever the page's address changes.+ const refreshMap = useCallback(async () => {+ if (!infoRef.current) return;+ const n = (mapSeq.current += 1);+ try {+ const next = await browserMap(chat);+ if (n !== mapSeq.current || !next) return;+ setMap(next);+ setHoverEl((cur) => (cur ? (next.els.find((el) => el.selector === cur.selector) ?? null) : null));+ } catch {+ // a page mid-navigation has no map; the last one stands until the next tick+ }+ }, [chat]);++ const pageUrl = info?.url ?? null;+ useEffect(() => {+ if (!tabId) return;+ void refreshMap();+ const timer = window.setInterval(() => void refreshMap(), MAP_REFRESH_MS);+ return () => window.clearInterval(timer);+ }, [tabId, pageUrl, refreshMap]);++ const scheduleMapRefresh = useCallback(() => {+ window.clearTimeout(settleTimer.current);+ settleTimer.current = window.setTimeout(() => void refreshMap(), MAP_SETTLE_MS);+ }, [refreshMap]);+// The viewport follows the pane, so the picture is 1:1 and stays crisp.useEffect(() => {const el = frameRef.current;@@ -195,6 +257,7 @@ export default function BrowserPane({if (!cur || (width === cur.width && height === cur.height)) return;void browserViewport(chat, width, height).then((v) => setInfo((c) => (c ? { ...c, ...v } : c)))+ .then(() => refreshMap()).catch(() => undefined);}, 300);});@@ -203,7 +266,7 @@ export default function BrowserPane({observer.disconnect();window.clearTimeout(timer);};- }, [chat, tabId, paneSize]);+ }, [chat, tabId, paneSize, refreshMap]);// Title and address follow the page (links clicked inside it, redirects).useEffect(() => {@@ -219,6 +282,10 @@ export default function BrowserPane({return () => window.clearInterval(timer);}, [chat, tabId]);+ useEffect(() => {+ if (editing !== null) window.setTimeout(() => noteRef.current?.focus(), 0);+ }, [editing]);+/** Frame pixels → the page's CSS pixels. */const toPage = (e: { clientX: number; clientY: number }) => {const img = imgRef.current;@@ -229,21 +296,24 @@ export default function BrowserPane({return { x: ((e.clientX - r.left) / r.width) * cur.width, y: ((e.clientY - r.top) / r.height) * cur.height };};+ const updatePin = (id: number, patch: Partial<BrowserPin>) => onPinsChange(pins.map((p) => (p.id === id ? { ...p, ...patch } : p)));+ const removePin = (id: number) => {+ onPinsChange(pins.filter((p) => p.id !== id));+ if (editing === id) setEditing(null);+ };+const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {const p = toPage(e);if (!p || busy) return;- const now = performance.now();if (mode === "browse") {+ const now = performance.now();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 hit = hitTest(mapRef.current, p.x, p.y);+ setHoverEl((cur) => (cur === hit || (cur && hit && cur.i === hit.i) ? cur : hit));};const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {@@ -264,53 +334,48 @@ export default function BrowserPane({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));+ // One click pins. The note is optional and can be typed right away.+ const m = mapRef.current;+ const hit = hitTest(m, p.x, p.y);+ if (!m || !hit) {+ setEditing(null);+ return;+ }+ const { i: _i, ref, ...element } = hit;+ const pin: BrowserPin = {+ id: Date.now(),+ comment: "",+ url: m.url,+ title: m.title,+ ref,+ element,+ point: { x: p.x, y: p.y },+ doc: { x: element.rect.x + m.scrollX, y: element.rect.y + m.scrollY, w: element.rect.w, h: element.rect.h },+ };+ onPinsChange([...pins, pin]);+ setEditing(pin.id);};const onWheel = (e: ReactWheelEvent<HTMLDivElement>) => {- if (mode !== "browse" || busy) return;+ if (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);+ scheduleMapRefresh();};const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {- if (mode !== "browse" || busy || e.metaKey || e.ctrlKey || e.altKey) return;if (e.target !== frameRef.current) return;+ if (mode === "annotate") {+ if (e.key === "Escape") setEditing(null);+ return;+ }+ if (busy || e.metaKey || e.ctrlKey || e.altKey) 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);@@ -319,6 +384,8 @@ export default function BrowserPane({const pageW = info?.width ?? 1;const pageH = info?.height ?? 1;const samePage = (p: BrowserPin) => !info || p.url === info.url;+ const editingPin = editing !== null ? (pins.find((p) => p.id === editing) ?? null) : null;+ const editingAt = editingPin ? markerAt(editingPin, map) : null;return (<aside@@ -340,8 +407,9 @@ export default function BrowserPane({aria-pressed={mode === m}onClick={() => {setMode(m);- setHover(null);- setDraft(null);+ setHoverEl(null);+ setEditing(null);+ if (m === "annotate") void refreshMap();}}className={`h-6 rounded-[6px] px-2 capitalize transition-colors ${mode === m ? "bg-surface text-ink shadow-hairline" : "text-ink-3 hover:text-ink"}`}>@@ -393,101 +461,122 @@ export default function BrowserPane({ref={frameRef}tabIndex={0}role="application"- aria-label={mode === "browse" ? "Page, keyboard and pointer forwarded" : "Page, click an element to annotate it"}+ aria-label={mode === "browse" ? "Page, keyboard and pointer forwarded" : "Page, click an element to pin it"}onPointerMove={onPointerMove}onPointerDown={onPointerDown}onPointerUp={onPointerUp}- onPointerLeave={() => setHover(null)}+ onPointerLeave={() => setHoverEl(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" }}+ style={{ cursor: mode === "annotate" ? (hoverEl ? "pointer" : "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" && (+ {hoverEl && mode === "annotate" && (<divclassName="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)",+ left: pct(hoverEl.rect.x, pageW),+ top: pct(hoverEl.rect.y, pageH),+ width: pct(hoverEl.rect.w, pageW),+ height: pct(hoverEl.rect.h, pageH),+ boxShadow: "0 0 0 2px var(--accent), 0 0 0 9999px color-mix(in oklab, var(--accent) 8%, 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>+ <span className="absolute -top-5 left-0 max-w-full truncate rounded-[4px] bg-accent px-1 text-[10px] font-medium whitespace-nowrap text-white">+ {hoverEl.ref ? `@${hoverEl.ref} · ` : ""}+ {elementLabel(hoverEl)}+ </span></div>)}+ {pins.filter(samePage).map((pin) => {+ const box = pinBox(pin, map);+ return (+ <div+ key={`box-${pin.id}`}+ className="absolute rounded-[3px]"+ style={{+ left: pct(box.x, pageW),+ top: pct(box.y, pageH),+ width: pct(box.w, pageW),+ height: pct(box.h, pageH),+ boxShadow: editing === pin.id ? "0 0 0 2px var(--accent)" : "0 0 0 1.5px color-mix(in oklab, var(--accent) 70%, transparent)",+ }}+ />+ );+ })}</div>- {draft && (+ <div className="pointer-events-none absolute inset-0">+ {pins.filter(samePage).map((pin) => {+ const at = markerAt(pin, map);+ if (!at) return null;+ return (+ <button+ key={pin.id}+ type="button"+ title={pin.comment || elementLabel(pin.element)}+ onPointerDown={(e) => e.stopPropagation()}+ onPointerUp={(e) => {+ e.stopPropagation();+ setEditing(pin.id);+ }}+ className="pointer-events-auto absolute"+ style={{ left: pct(at.x, pageW), top: pct(at.y, pageH), transform: "translate(-50%, -50%)" }}+ >+ <span className={`${PIN_STYLE} ${editing === pin.id ? "ring-2 ring-white" : ""}`}>{pins.indexOf(pin) + 1}</span>+ </button>+ );+ })}+ </div>+ {editingPin && editingAt && (<formclassName="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))`,+ left: `min(calc(${pct(editingAt.x, pageW)} + 14px), calc(100% - 290px))`,+ top: `min(calc(${pct(editingAt.y, pageH)} + 14px), calc(100% - 110px))`,animation: "pop-in 160ms cubic-bezier(0.23,1,0.32,1) both",}}onSubmit={(e) => {e.preventDefault();- commitPin();+ setEditing(null);}}onPointerDown={(e) => e.stopPropagation()}onPointerUp={(e) => e.stopPropagation()}onPointerMove={(e) => e.stopPropagation()}+ onWheel={(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 className="truncate text-[11.5px] text-ink-3" title={editingPin.element.selector}>+ <span className="mr-1 font-semibold text-ink">#{pins.indexOf(editingPin) + 1}</span>+ {editingPin.ref ? <span className="mr-1 font-mono text-accent-ink">@{editingPin.ref}</span> : null}+ {elementLabel(editingPin.element)}</div><input- ref={commentRef}- value={comment}- onChange={(e) => setComment(e.target.value)}+ ref={noteRef}+ value={editingPin.comment}+ onChange={(e) => updatePin(editingPin.id, { comment: e.target.value })}onKeyDown={(e) => {e.stopPropagation();- if (e.key === "Escape") {- setDraft(null);- setHover(null);- }+ if (e.key === "Escape") setEditing(null);}}- placeholder="What should change here?"- aria-label="Annotation"+ placeholder="What should change here? (optional)"+ aria-label="Note for this pin"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">+ <div className="flex items-center gap-1"><buttontype="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"+ onClick={() => removePin(editingPin.id)}+ className="h-6 rounded-full px-2 text-[11.5px] font-medium text-red hover:bg-hover">- Cancel+ Remove</button>+ <span className="flex-1" /><button type="submit" className="h-6 rounded-full bg-ink px-2.5 text-[11.5px] font-medium text-canvas hover:opacity-90">- Pin+ Done</button></div></form>@@ -510,26 +599,54 @@ export default function BrowserPane({)}</div>- <div className="max-h-44 shrink-0 overflow-y-auto border-t border-line">+ <div className="max-h-48 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."+ ? "Click any element to pin it. Add a note if you like. 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">+ <div className="flex items-center gap-2 px-1.5 pb-1">+ <span className="min-w-0 flex-1 truncate text-[11.5px] text-ink-3">+ {pins.length} pin{pins.length === 1 ? "" : "s"} · sent with your next message+ </span>+ {onAsk && (+ <button+ type="button"+ onClick={onAsk}+ className="h-6 shrink-0 rounded-full bg-ink px-2.5 text-[11.5px] font-medium text-canvas hover:opacity-90"+ >+ Ask graff+ </button>+ )}+ <button+ type="button"+ onClick={() => {+ onPinsChange([]);+ setEditing(null);+ }}+ className="h-6 shrink-0 rounded-full px-2 text-[11.5px] font-medium text-ink-3 hover:bg-hover hover:text-ink"+ >+ Clear+ </button>+ </div>{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>+ <div+ key={pin.id}+ className={`group flex min-h-8 items-center gap-2 rounded-[7px] px-1.5 py-1 ${editing === pin.id ? "bg-hover" : "hover:bg-hover"}`}+ >+ <button type="button" onClick={() => setEditing(pin.id)} className="flex min-w-0 flex-1 items-center gap-2 text-left">+ <span className={`${PIN_STYLE} shrink-0`}>{i + 1}</span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[12px] text-ink">{pin.comment || <span className="text-ink-3">no note</span>}</span>+ <span className="block truncate font-mono text-[10.5px] text-ink-3" title={pin.element.selector}>+ {pin.ref ? `@${pin.ref} · ` : ""}+ {elementLabel(pin.element)}+ </span>+ </span>+ </button><buttontype="button"aria-label="Remove pin"@@ -540,13 +657,6 @@ export default function BrowserPane({</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>diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex 35d78eaa..bef44df3 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -790,6 +790,7 @@ export default function GraffHarness() {chat={handleOf(chatThread.id)}pins={pinsByChat[chatThread.id] ?? []}onPinsChange={(next) => setPins(chatThread.id, next)}+ onAsk={() => void send("Make the changes I pinned in the browser.")}onClose={() => setBrowserOpen(false)}/>)}diff --git a/apps/native/lib/browser-client.ts b/apps/native/lib/browser-client.tsindex f1ec5af8..a801186d 100644--- a/apps/native/lib/browser-client.ts+++ b/apps/native/lib/browser-client.ts@@ -14,6 +14,38 @@ export type InspectHit = { element: PinElement; ref: string | null; url: string;export type HoverHit = { rect: PinElement["rect"]; tag: string };+/** One pinnable element on screen, as the page reported it. */+export type MapElement = PinElement & { i: number; ref: string | null };++/** The page's pinnable elements at one moment, with the scroll offset they+ * were measured at, so pins can be placed in page coordinates. */+export type ElementMap = {+ url: string;+ title: string;+ vw: number;+ vh: number;+ scrollX: number;+ scrollY: number;+ els: MapElement[];+};++/** The smallest mapped element under a viewport point, or null. */+export function hitTest(map: ElementMap | null, x: number, y: number): MapElement | null {+ if (!map) return null;+ let best: MapElement | null = null;+ let bestArea = Infinity;+ for (const el of map.els) {+ const r = el.rect;+ if (x < r.x || y < r.y || x > r.x + r.w || y > r.y + r.h) continue;+ const area = r.w * r.h;+ if (area < bestArea) {+ best = el;+ bestArea = area;+ }+ }+ return best;+}+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 }@@ -63,6 +95,7 @@ export const browserHover = (chat: string, x: number, y: number) => browserCall<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 browserMap = (chat: string) => browserCall<ElementMap | null>(chat, "map");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.ts b/apps/native/lib/browser/annotations.tsindex 47415df3..4afe34fd 100644--- a/apps/native/lib/browser/annotations.ts+++ b/apps/native/lib/browser/annotations.ts@@ -26,6 +26,9 @@ export type BrowserPin = {element: PinElement;/** Viewport point of the click, CSS pixels. */point: { x: number; y: number };+ /** The element's box in page coordinates (viewport box plus the scroll+ * offset at pin time), so the marker follows the page when it scrolls. */+ doc?: PinRect;};export type SnapshotRow = { role: string; name: string; ref: string };diff --git a/apps/native/lib/browser/inspect-script.ts b/apps/native/lib/browser/inspect-script.tsindex 6d0e5f3d..8c480416 100644--- a/apps/native/lib/browser/inspect-script.ts+++ b/apps/native/lib/browser/inspect-script.ts@@ -66,6 +66,81 @@ export function inspectExpression(x: number, y: number): string {return compact(SOURCE).replace("__X__", String(Math.round(x))).replace("__Y__", String(Math.round(y)));}+/** Every element worth pinning that is on screen right now, in one call:+ * interactive things and anything with its own text, with the box, a+ * stable selector and an accessible name for each. The pane hit-tests this+ * locally, so hover and click cost nothing, and refreshes it after a+ * scroll or a navigation. `textContent` rather than `innerText`: the+ * latter forces layout per element and the page can have thousands. */+const MAP_SOURCE = String.raw`(function () {+ var vw = innerWidth, vh = innerHeight;+ 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 SKIP = /^(SCRIPT|STYLE|NOSCRIPT|SVG|PATH|BR|HTML|HEAD|META|LINK|TEMPLATE|IFRAME)$/;+ var INTERACTIVE = /^(A|BUTTON|INPUT|SELECT|TEXTAREA|SUMMARY|LABEL|IMG|VIDEO)$/;+ var roleOf = function (el) {+ var tag = el.tagName;+ var role = el.getAttribute("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";+ }+ return role;+ };+ var nameOf = function (el) {+ var attr = function (n) { return el.getAttribute(n) || ""; };+ var labelled = el.labels && el.labels.length ? squash(el.labels[0].textContent) : "";+ return squash(attr("aria-label") || labelled || attr("alt") || attr("title") || attr("placeholder") || attr("value") || 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 selectorOf = function (el) {+ 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 parts.join(" > ");+ };+ var out = [];+ var all = document.body ? document.body.getElementsByTagName("*") : [];+ for (var i = 0; i < all.length && out.length < 600; i++) {+ var el = all[i];+ var tag = el.tagName;+ if (SKIP.test(tag)) continue;+ var r = el.getBoundingClientRect();+ if (r.width < 6 || r.height < 6) continue;+ if (r.bottom < 0 || r.right < 0 || r.top > vh || r.left > vw) continue;+ var interactive = INTERACTIVE.test(tag) || el.hasAttribute("role") || el.hasAttribute("onclick") || el.hasAttribute("tabindex") || el.hasAttribute("contenteditable");+ var hasText = false;+ for (var c = el.firstChild; c; c = c.nextSibling) { if (c.nodeType === 3 && c.nodeValue.trim()) { hasText = true; break; } }+ if (!interactive && !hasText) continue;+ out.push({ i: out.length, tag: tag.toLowerCase(), role: roleOf(el), name: nameOf(el), text: squash(el.textContent).slice(0, 120),+ selector: selectorOf(el), href: el.href ? String(el.href) : null, rect: { x: r.left, y: r.top, w: r.width, h: r.height } });+ }+ return { url: location.href, title: document.title, vw: vw, vh: vh, scrollX: scrollX, scrollY: scrollY, els: out };+})()`;++export function mapExpression(): string {+ return compact(MAP_SOURCE);+}+/** 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);diff --git a/apps/native/lib/browser/kuri-supervisor.ts b/apps/native/lib/browser/kuri-supervisor.tsindex 936b3ec8..8ce6dea7 100644--- a/apps/native/lib/browser/kuri-supervisor.ts+++ b/apps/native/lib/browser/kuri-supervisor.ts@@ -31,8 +31,9 @@ type Live = {ready: Promise<void>;};-const g = globalThis as typeof globalThis & { __graffKuri?: { live: Live | null; hooked: boolean } };-const state = (g.__graffKuri ??= { live: null, hooked: false });+type State = { live: Live | null; hooked: boolean; spawning: Promise<{ port: number; token: string }> | null };+const g = globalThis as typeof globalThis & { __graffKuri?: State };+const state: State = (g.__graffKuri ??= { live: null, hooked: false, spawning: null });const FIRST_PORT = 8091;// Kuri answers /health only once its Chrome is up, and a launch that hits@@ -133,7 +134,8 @@ function reapProfileChrome(): void {}}-/** The live Kuri, spawning it when there is none. */+/** The live Kuri, spawning it when there is none. Two chats asking at once+ * (both panes open on a dead browser) share one spawn. */export async function ensureKuri(): Promise<{ port: number; token: string }> {const live = state.live;if (live && live.child.exitCode === null) {@@ -141,6 +143,17 @@ export async function ensureKuri(): Promise<{ port: number; token: string }> {await live.ready;return { port: live.port, token: live.token };}+ if (state.spawning) return state.spawning;+ const spawning = spawnKuri();+ state.spawning = spawning;+ try {+ return await spawning;+ } finally {+ if (state.spawning === spawning) state.spawning = null;+ }+}++async function spawnKuri(): Promise<{ port: number; token: string }> {const bin = kuriBin();if (!bin) {throw new Error(@@ -179,9 +192,15 @@ export async function ensureKuri(): Promise<{ port: number; token: string }> {ready: Promise.resolve(),};next.ready = waitHealthy(port, token, child);- child.on("exit", () => {- if (state.live === next) state.live = null;+ child.on("exit", (code, signal) => {+ const mine = state.live === next;+ if (mine) state.live = null;if (next.idleTimer) clearTimeout(next.idleTimer);+ // A Kuri that died on its own (not our stop) leaves its Chrome behind.+ if (mine) {+ console.error(`[browser] kuri exited unexpectedly (code=${code ?? "?"} signal=${signal ?? "none"}); the next request respawns it`);+ reapProfileChrome();+ }});state.live = next;hookExit();diff --git a/plans/2026-09-03-browser-sidecar.md b/plans/2026-09-03-browser-sidecar.mdindex 80de0753..91232ef3 100644--- a/plans/2026-09-03-browser-sidecar.md+++ b/plans/2026-09-03-browser-sidecar.md@@ -42,10 +42,19 @@ the binding survives navigation. Two things argued against it for v1:name, a stable selector, its box — is one `Runtime.evaluate` away, anddrawing 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.+So the page is never modified. The first cut evaluated one expression per+hover and per click; that made the outline lag the pointer and a click+feel dead for a round trip, and it did not survive the first real try.+Annotate now fetches an *element map* — every interactive or text-bearing+element on screen with its box, name, selector and Kuri ref, one+`/evaluate` plus one `/snapshot`, about 50 ms for a Hacker News page —+and hit-tests it in the pane. Hover and pin are local and instant; the+map refreshes 350 ms after a scroll settles, every 2.5 s, and on+navigation. Pins are stored in page coordinates against the map's scroll+offset, so they stay on their element when the page scrolls, and the+wheel is forwarded in both modes. 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