graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(native): Codex-class harness — review flow, files pane, live models
justrach933a2b8eac26
diff --git a/apps/native/README.md b/apps/native/README.mdindex b437d920..1f89920d 100644--- a/apps/native/README.md+++ b/apps/native/README.md@@ -56,6 +56,20 @@ the child with `--model`. Approvals (`ask_user` / `session/request_permission`)are not on this path: the child runs `--yolo` so tools execute from thefirst turn.+The model picker is live, not a hardcoded list: `graff/models` (a vendor+JSON-RPC method on the same stdio agent) returns the catalog with+per-provider credential state in the REPL's election order (signed-in+plan, then local, credits, api). The UI shows only authenticated seats+and re-reads `current` after every respawn, so the picker reflects what+graff's fuzzy `--model` resolution actually chose.++The workspace itself is walkable: `/api/fs` (list/read, plus macOS+`open`/`open -R` passthroughs) is sandboxed to the agent's cwd and backs+a files pane — the folder chip in the tab bar or the sidebar's+Workspace item opens it. Tool-row chips and path-looking inline code in+answers (`src/acp.zig`) jump straight to that file; markdown files+render, code shows mono, binaries hand off to Open.+## Run```bashdiff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex 716bd029..dbae84f9 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -1,13 +1,16 @@-import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { spawn, type ChildProcessByStdio } from "node:child_process";import { existsSync } from "node:fs";import path from "node:path";+import type { Readable, Writable } from "node:stream";import { NextRequest } from "next/server";export const runtime = "nodejs";export const dynamic = "force-dynamic";type Slot = {- child: ChildProcessWithoutNullStreams;+ // stderr is "inherit" (null here): the agent's diagnostics land in the dev+ // server's terminal instead of being buffered and lost.+ child: ChildProcessByStdio<Writable, Readable, null>;buf: string;nextId: number;sessionId: string | null;@@ -70,8 +73,11 @@ function writeLine(slot: Slot, obj: unknown) {function readLine(slot: Slot, timeoutMs: number): Promise<string> {return new Promise((resolve, reject) => {- const timer = setTimeout(() => reject(new Error("ACP agent timed out")), timeoutMs);- const onData = () => {+ // The chunk handler itself must be what gets removed — detaching a+ // different function leaks a listener that keeps consuming stdout lines+ // (and re-appending chunks to the shared buffer) for the slot's lifetime.+ const onData = (chunk?: Buffer) => {+ if (chunk) slot.buf += chunk.toString("utf8");const nl = slot.buf.indexOf("\n");if (nl < 0) return;const line = slot.buf.slice(0, nl);@@ -80,10 +86,11 @@ function readLine(slot: Slot, timeoutMs: number): Promise<string> {slot.child.stdout.off("data", onData);resolve(line);};- slot.child.stdout.on("data", (chunk: Buffer) => {- slot.buf += chunk.toString("utf8");- onData();- });+ const timer = setTimeout(() => {+ slot.child.stdout.off("data", onData);+ reject(new Error("ACP agent timed out"));+ }, timeoutMs);+ slot.child.stdout.on("data", onData);onData();});}@@ -121,19 +128,22 @@ async function bootstrap(model?: string, reset = false): Promise<Slot> {}export async function GET() {- try {- const slot = await bootstrap();- return Response.json({ ok: true, sessionId: slot.sessionId });- } catch (err) {+ // Health is a passive probe: report the binary and any live slot without+ // spawning. Spawning here raced the UI's own bootstrap (two agents per+ // page load) — the POST bootstrap path is the only spawner.+ const bin = graffBin();+ const found = path.isAbsolute(bin) ? existsSync(bin) : true;+ if (!found) {return Response.json({ok: false,- detail: err instanceof Error ? err.message : String(err),+ detail: `graff binary not found at ${bin}`,hint: "Build graff (zig build) or set GRAFF_BIN. The native app speaks ACP via `graff acp`.",},{ status: 502 },);}+ return Response.json({ ok: true, sessionId: g.__graffAcp?.sessionId ?? null, cwd: workspace() });}export async function POST(req: NextRequest) {diff --git a/apps/native/app/api/fs/route.ts b/apps/native/app/api/fs/route.tsnew file mode 100644index 00000000..68b8571d--- /dev/null+++ b/apps/native/app/api/fs/route.ts@@ -0,0 +1,112 @@+import { spawn } from "node:child_process";+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import path from "node:path";+import { NextRequest } from "next/server";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++/** Same resolution as /api/acp: the workspace the agent itself runs in. */+function workspaceRoot(): string {+ if (process.env.GRAFF_ACP_CWD) return process.env.GRAFF_ACP_CWD;+ if (process.env.GRAFF_CWD) return process.env.GRAFF_CWD;+ const fromApp = path.resolve(process.cwd(), "../..");+ if (existsSync(path.join(fromApp, "build.zig"))) return fromApp;+ return process.cwd();+}++/** Heavy or generated trees that only bury the folders people navigate to. */+const HIDDEN = new Set([".git", "node_modules", ".next", ".zig-cache", "zig-out", ".DS_Store"]);++const MAX_TEXT = 256 * 1024;++const IMAGE_TYPES: Record<string, string> = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp",+ ".svg": "image/svg+xml",+ ".ico": "image/x-icon",+ ".bmp": "image/bmp",+ ".avif": "image/avif",+};++/** Resolve a user-supplied path INSIDE the workspace or refuse it. */+function resolveInRoot(root: string, rel: string): string | null {+ const target = path.resolve(root, rel || ".");+ if (target !== root && !target.startsWith(root + path.sep)) return null;+ return target;+}++export async function GET(req: NextRequest) {+ const root = workspaceRoot();+ const rel = req.nextUrl.searchParams.get("path") ?? "";+ const target = resolveInRoot(root, rel);+ if (!target) return Response.json({ error: "path escapes the workspace" }, { status: 400 });+ try {+ const stat = statSync(target);+ const relPath = path.relative(root, target);+ if (stat.isDirectory()) {+ const entries = readdirSync(target, { withFileTypes: true })+ .filter((e) => !HIDDEN.has(e.name))+ .map((e) => {+ const dir = e.isDirectory();+ let size = 0;+ if (!dir) {+ try {+ size = statSync(path.join(target, e.name)).size;+ } catch {+ // unstattable (dangling symlink); list it anyway+ }+ }+ return { name: e.name, dir, size };+ })+ .sort((a, b) => (a.dir === b.dir ? a.name.localeCompare(b.name) : a.dir ? -1 : 1));+ return Response.json({ ok: true, root, path: relPath, dir: true, entries });+ }+ // ?raw=1 streams the bytes themselves — how the pane shows images.+ if (req.nextUrl.searchParams.get("raw")) {+ const type = IMAGE_TYPES[path.extname(target).toLowerCase()] ?? "application/octet-stream";+ const bytes = readFileSync(target);+ return new Response(new Uint8Array(bytes), {+ headers: { "content-type": type, "cache-control": "no-store" },+ });+ }+ const buf = readFileSync(target);+ const head = buf.subarray(0, 8192);+ const binary = head.includes(0);+ const truncated = buf.length > MAX_TEXT;+ return Response.json({+ ok: true,+ root,+ path: relPath,+ dir: false,+ size: buf.length,+ binary,+ truncated,+ text: binary ? "" : buf.subarray(0, MAX_TEXT).toString("utf8"),+ });+ } catch (err) {+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 404 });+ }+}++export async function POST(req: NextRequest) {+ const root = workspaceRoot();+ const body = (await req.json()) as { action?: string; path?: string };+ const target = resolveInRoot(root, body.path ?? "");+ if (!target) return Response.json({ error: "path escapes the workspace" }, { status: 400 });+ if (process.platform !== "darwin") {+ return Response.json({ error: "open/reveal is macOS-only here" }, { status: 501 });+ }+ if (body.action === "reveal") {+ spawn("open", ["-R", target], { stdio: "ignore", detached: true }).unref();+ return Response.json({ ok: true });+ }+ if (body.action === "open") {+ spawn("open", [target], { stdio: "ignore", detached: true }).unref();+ return Response.json({ ok: true });+ }+ return Response.json({ error: `unknown action: ${body.action}` }, { status: 400 });+}diff --git a/apps/native/app/api/git/route.ts b/apps/native/app/api/git/route.tsnew file mode 100644index 00000000..06541ab2--- /dev/null+++ b/apps/native/app/api/git/route.ts@@ -0,0 +1,94 @@+import { execFile } from "node:child_process";+import { existsSync } from "node:fs";+import path from "node:path";+import { promisify } from "node:util";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++const run = promisify(execFile);++/** Same resolution as /api/acp: the workspace the agent itself runs in. */+function workspaceRoot(): string {+ if (process.env.GRAFF_ACP_CWD) return process.env.GRAFF_ACP_CWD;+ if (process.env.GRAFF_CWD) return process.env.GRAFF_CWD;+ const fromApp = path.resolve(process.cwd(), "../..");+ if (existsSync(path.join(fromApp, "build.zig"))) return fromApp;+ return process.cwd();+}++async function git(args: string[], cwd: string): Promise<string> {+ const { stdout } = await run("git", args, { cwd, maxBuffer: 8 * 1024 * 1024 });+ return stdout;+}++/** The working tree's uncommitted story, Codex-review shaped: per-file+ * +adds/−dels plus the unified diff, untracked files included. */+export async function GET() {+ const root = workspaceRoot();+ try {+ const [numstat, untrackedRaw] = await Promise.all([+ git(["diff", "--numstat"], root),+ git(["ls-files", "--others", "--exclude-standard"], root),+ ]);+ const files: { path: string; add: number; del: number; untracked: boolean }[] = [];+ for (const line of numstat.split("\n")) {+ if (!line.trim()) continue;+ const [add, del, file] = line.split("\t");+ if (!file) continue;+ files.push({ path: file, add: Number(add) || 0, del: Number(del) || 0, untracked: false });+ }+ const untracked = untrackedRaw.split("\n").filter(Boolean);+ for (const file of untracked) {+ let add = 0;+ try {+ const wc = await git(["diff", "--numstat", "--no-index", "/dev/null", file], root).catch((err) => {+ // git diff --no-index exits 1 when files differ; the diff is still on stdout+ const out = (err as { stdout?: string }).stdout;+ if (typeof out === "string") return out;+ throw err;+ });+ const first = wc.split("\n")[0]?.split("\t")[0];+ add = Number(first) || 0;+ } catch {+ // binary or unreadable; list it with no count+ }+ files.push({ path: file, add, del: 0, untracked: true });+ }+ files.sort((a, b) => a.path.localeCompare(b.path));+ return Response.json({+ ok: true,+ root,+ files,+ totalAdd: files.reduce((n, f) => n + f.add, 0),+ totalDel: files.reduce((n, f) => n + f.del, 0),+ });+ } catch (err) {+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 });+ }+}++/** POST {path} → the unified diff for one file (or its full content when untracked). */+export async function POST(req: Request) {+ const root = workspaceRoot();+ const body = (await req.json()) as { path?: string };+ const file = body.path ?? "";+ const target = path.resolve(root, file);+ if (target !== root && !target.startsWith(root + path.sep)) {+ return Response.json({ error: "path escapes the workspace" }, { status: 400 });+ }+ try {+ let diff = await git(["diff", "--", file], root);+ if (!diff.trim()) {+ // Untracked: diff against /dev/null so new files render as all-adds.+ diff = await git(["diff", "--no-index", "--", "/dev/null", file], root).catch((err) => {+ const out = (err as { stdout?: string }).stdout;+ if (typeof out === "string") return out;+ throw err;+ });+ }+ return Response.json({ ok: true, path: file, diff });+ } catch (err) {+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 });+ }+}diff --git a/apps/native/components/primitives/Markdown.tsx b/apps/native/components/primitives/Markdown.tsxnew file mode 100644index 00000000..46ef46db--- /dev/null+++ b/apps/native/components/primitives/Markdown.tsx@@ -0,0 +1,333 @@+"use client";++import { useCallback, useState, type ReactNode } from "react";++/* ─────────────────────────────────────────────────────────+ * MARKDOWN+ * Renders the assistant's markdown live while it streams:+ * headings, lists, quotes, tables, fenced code (with copy),+ * and inline bold / italic / code / links. Zero deps — the+ * subset agents actually emit, on the Beautiful UI tokens.+ * ───────────────────────────────────────────────────────── */++const INLINE =+ /(`+)([\s\S]+?)\1|\*\*([\s\S]+?)\*\*|__([\s\S]+?)__|\*([^*\n]+)\*|_([^_\n]+)_|~~([\s\S]+?)~~|\[([^\]]*)\]\(([^)\s]+)\)/;++/** `src/acp.zig`, `README.md`, `benchmarks/` — but not `--flags` or phrases. */+const PATHISH = /^(?:[\[email protected]]+\/)+[\[email protected]]*$|^[\w-][\w.-]*\.[a-z0-9]{1,8}$/i;++function inline(text: string, depth = 0, onOpen?: (path: string) => void): ReactNode[] {+ if (depth > 4) return [text];+ const out: ReactNode[] = [];+ let rest = text;+ let key = 0;+ while (rest.length > 0) {+ const m = INLINE.exec(rest);+ if (!m) {+ out.push(rest);+ break;+ }+ if (m.index > 0) out.push(rest.slice(0, m.index));+ if (m[2] !== undefined) {+ const code = m[2];+ // `src/acp.zig:96` and `file.md:7-31` open the file; the line ref is display-only.+ const target = code.replace(/\/$/, "").replace(/:\d+(?:[-–]\d+)?$/, "");+ const pathish = onOpen && PATHISH.test(target);+ out.push(+ <code+ key={key++}+ onClick={pathish ? () => onOpen(target) : undefined}+ title={pathish ? `Open ${code} in the files pane` : undefined}+ className={`rounded-[4px] bg-inset px-1 py-px font-mono text-[0.92em] text-ink shadow-hairline ${+ pathish ? "cursor-pointer underline decoration-line underline-offset-2 transition-colors hover:bg-hover hover:decoration-ink" : ""+ }`}+ >+ {code}+ </code>,+ );+ } else if (m[3] !== undefined || m[4] !== undefined) {+ out.push(+ <strong key={key++} className="font-semibold text-ink">+ {inline(m[3] ?? m[4], depth + 1, onOpen)}+ </strong>,+ );+ } else if (m[5] !== undefined || m[6] !== undefined) {+ out.push(<em key={key++}>{inline(m[5] ?? m[6], depth + 1, onOpen)}</em>);+ } else if (m[7] !== undefined) {+ out.push(+ <s key={key++} className="text-ink-3">+ {inline(m[7], depth + 1, onOpen)}+ </s>,+ );+ } else {+ out.push(+ <a+ key={key++}+ href={m[9]}+ target="_blank"+ rel="noreferrer"+ className="animated-underline text-ink underline decoration-line underline-offset-2 hover:decoration-ink"+ >+ {inline(m[8] || m[9], depth + 1, onOpen)}+ </a>,+ );+ }+ rest = rest.slice(m.index + m[0].length);+ }+ return out;+}++type Block =+ | { kind: "p"; text: string }+ | { kind: "h"; level: number; text: string }+ | { kind: "code"; lang: string; text: string; open: boolean }+ | { kind: "quote"; lines: string[] }+ | { kind: "list"; ordered: boolean; items: { text: string; indent: number }[] }+ | { kind: "table"; header: string[]; rows: string[][] }+ | { kind: "hr" };++const FENCE = /^\s*```+\s*(\S*)\s*$/;+const HEADING = /^(#{1,6})\s+(.*)$/;+const LIST_ITEM = /^(\s*)(?:([-*+])|(\d{1,3})[.)])\s+(.*)$/;+const TABLE_DIVIDER = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)+\|?\s*$/;++function cells(line: string): string[] {+ return line+ .replace(/^\s*\|/, "")+ .replace(/\|\s*$/, "")+ .split("|")+ .map((c) => c.trim());+}++/** Streaming-safe: an unterminated fence renders as an open code block. */+export function parseMarkdown(src: string): Block[] {+ const lines = src.split("\n");+ const blocks: Block[] = [];+ let para: string[] = [];+ const flush = () => {+ if (para.length) blocks.push({ kind: "p", text: para.join("\n") });+ para = [];+ };+ let i = 0;+ while (i < lines.length) {+ const line = lines[i];+ const fence = FENCE.exec(line);+ if (fence) {+ flush();+ const body: string[] = [];+ i += 1;+ let closed = false;+ while (i < lines.length) {+ if (FENCE.test(lines[i]) && !lines[i].trim().slice(3).trim()) {+ closed = true;+ i += 1;+ break;+ }+ body.push(lines[i]);+ i += 1;+ }+ blocks.push({ kind: "code", lang: fence[1] ?? "", text: body.join("\n"), open: !closed });+ continue;+ }+ const heading = HEADING.exec(line);+ if (heading) {+ flush();+ blocks.push({ kind: "h", level: heading[1].length, text: heading[2] });+ i += 1;+ continue;+ }+ if (/^\s*([-*_])\s*\1\s*\1[\s\-*_]*$/.test(line) && line.trim().length >= 3) {+ flush();+ blocks.push({ kind: "hr" });+ i += 1;+ continue;+ }+ if (/^>\s?/.test(line)) {+ flush();+ const quote: string[] = [];+ while (i < lines.length && /^>\s?/.test(lines[i])) {+ quote.push(lines[i].replace(/^>\s?/, ""));+ i += 1;+ }+ blocks.push({ kind: "quote", lines: quote });+ continue;+ }+ const item = LIST_ITEM.exec(line);+ if (item) {+ flush();+ const ordered = item[3] !== undefined;+ const items: { text: string; indent: number }[] = [];+ while (i < lines.length) {+ const m = LIST_ITEM.exec(lines[i]);+ if (!m) break;+ items.push({ text: m[4], indent: Math.min(3, Math.floor(m[1].length / 2)) });+ i += 1;+ }+ blocks.push({ kind: "list", ordered, items });+ continue;+ }+ if (line.includes("|") && i + 1 < lines.length && TABLE_DIVIDER.test(lines[i + 1])) {+ flush();+ const header = cells(line);+ i += 2;+ const rows: string[][] = [];+ while (i < lines.length && lines[i].includes("|")) {+ rows.push(cells(lines[i]));+ i += 1;+ }+ blocks.push({ kind: "table", header, rows });+ continue;+ }+ if (!line.trim()) {+ flush();+ i += 1;+ continue;+ }+ para.push(line);+ i += 1;+ }+ flush();+ return blocks;+}++function CodeFence({ lang, text, open }: { lang: string; text: string; open: boolean }) {+ const [copied, setCopied] = useState(false);+ const copy = useCallback(() => {+ navigator.clipboard.writeText(text).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ });+ }, [text]);+ return (+ <div className="my-3 overflow-hidden rounded-[10px] bg-inset shadow-hairline">+ <div className="flex h-7 items-center justify-between border-b border-line px-2.5">+ <span className="font-mono text-[11px] text-ink-3">{lang || "text"}</span>+ {!open && (+ <button+ type="button"+ aria-label="Copy code"+ onClick={copy}+ className={`flex h-5 items-center gap-1 rounded-[5px] px-1 text-[11px] font-medium transition-colors duration-100 hover:bg-hover ${+ copied ? "text-green" : "text-ink-3 hover:text-ink"+ }`}+ >+ {copied ? "Copied" : "Copy"}+ </button>+ )}+ </div>+ <pre className="overflow-x-auto px-3 py-2.5 font-mono text-[12px] leading-[1.65] whitespace-pre text-ink-2">+ {text}+ {open && <span className="ml-0.5 inline-block h-3 w-[3px] translate-y-0.5 rounded-full bg-accent" />}+ </pre>+ </div>+ );+}++const HEADING_STYLE: Record<number, string> = {+ 1: "mt-4 mb-1.5 text-[16px] font-semibold text-ink",+ 2: "mt-4 mb-1.5 text-[15px] font-semibold text-ink",+ 3: "mt-3.5 mb-1 text-[14px] font-semibold text-ink",+ 4: "mt-3 mb-1 text-[13.5px] font-semibold text-ink",+ 5: "mt-3 mb-1 text-[13px] font-semibold text-ink-2",+ 6: "mt-3 mb-1 text-[13px] font-semibold text-ink-3",+};++export default function Markdown({+ text,+ streaming = false,+ onOpenPath,+}: {+ text: string;+ streaming?: boolean;+ /** Makes path-looking inline code (`src/acp.zig`) a jump into the files pane. */+ onOpenPath?: (path: string) => void;+}) {+ const blocks = parseMarkdown(text);+ const inl = (t: string) => inline(t, 0, onOpenPath);+ return (+ <div className="min-w-0 text-[13.5px] leading-[1.7] text-ink">+ {blocks.map((b, i) => {+ const last = i === blocks.length - 1;+ const caret =+ streaming && last && b.kind !== "code" ? (+ <span className="stream-caret ml-0.5 inline-block h-3 w-0.5 translate-y-0.5 rounded-full bg-ink" />+ ) : null;+ switch (b.kind) {+ case "h":+ return (+ <p key={i} className={HEADING_STYLE[b.level] ?? HEADING_STYLE[4]}>+ {inl(b.text)}+ {caret}+ </p>+ );+ case "code":+ return <CodeFence key={i} lang={b.lang} text={b.text} open={streaming && last && b.open} />;+ case "quote":+ return (+ <blockquote key={i} className="my-2 border-l-2 border-line pl-3 text-ink-2">+ {b.lines.map((l, j) => (+ <p key={j} className="my-0.5">+ {inl(l)}+ </p>+ ))}+ {caret}+ </blockquote>+ );+ case "list":+ return (+ <ul key={i} className="my-2 flex flex-col gap-1">+ {b.items.map((item, j) => (+ <li key={j} className="flex gap-2" style={{ marginLeft: item.indent * 16 }}>+ <span className="mt-[1px] shrink-0 text-ink-3 select-none">+ {b.ordered ? `${j + 1}.` : "•"}+ </span>+ <span className="min-w-0">{inl(item.text)}</span>+ </li>+ ))}+ {caret && <li>{caret}</li>}+ </ul>+ );+ case "table":+ return (+ <div key={i} className="my-3 overflow-x-auto rounded-[10px] shadow-hairline">+ <table className="w-full border-collapse text-[12.5px]">+ <thead>+ <tr className="border-b border-line bg-inset">+ {b.header.map((h, j) => (+ <th key={j} className="px-2.5 py-1.5 text-left font-semibold text-ink">+ {inl(h)}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {b.rows.map((row, j) => (+ <tr key={j} className="border-b border-line last:border-0">+ {row.map((cell, k) => (+ <td key={k} className="px-2.5 py-1.5 align-top text-ink-2">+ {inl(cell)}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+ case "hr":+ return <hr key={i} className="my-3 border-line" />;+ default:+ return (+ <p key={i} className="my-2 whitespace-pre-wrap first:mt-0 last:mb-0">+ {inl(b.text)}+ {caret}+ </p>+ );+ }+ })}+ {streaming && blocks.length === 0 && (+ <span className="stream-caret inline-block h-3 w-0.5 translate-y-0.5 rounded-full bg-ink" />+ )}+ </div>+ );+}diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsxindex 8d41abc5..4305cf86 100644--- a/apps/native/components/primitives/PromptBar.tsx+++ b/apps/native/components/primitives/PromptBar.tsx@@ -182,6 +182,15 @@ export default function PromptBar({const [model, setModel] = useState(() => catalog.find((m) => m.key === modelKey) ?? catalog[0] ?? MODELS[1],);+ /* Live surfaces load their catalog async (graff/models); once it lands, or+ * the owner re-points modelKey, the picked entry must follow — the initial+ * useState snapshot is stale by then. */+ useEffect(() => {+ if (!modelKey) return;+ const found = catalog.find((m) => m.key === modelKey);+ if (found && found.key !== model.key) setModel(found);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [modelKey, models]);const [attachments, setAttachments] = useState<string[]>([]);const [connected, setConnected] = useState(false);const [active, setActive] = useState(0);@@ -194,8 +203,10 @@ export default function PromptBar({const [engaged, setEngaged] = useState(false);const [modelBox, setModelBox] = useState<{ top: number; height: number } | null>(null);const [modelHovered, setModelHovered] = useState<number | null>(null);+ const [modelQuery, setModelQuery] = useState("");const [modelMenuLeft, setModelMenuLeft] = useState(0);const [modelMenuBottom, setModelMenuBottom] = useState(0);+ const [modelMenuMaxH, setModelMenuMaxH] = useState(560);const composerAnchorRef = useRef<HTMLDivElement>(null);const controlsRef = useRef<HTMLDivElement>(null);const inputRef = useRef<HTMLTextAreaElement>(null);@@ -239,12 +250,23 @@ export default function PromptBar({/* same gliding highlight in the model menu — floats to the hovered* row, falling back to the currently-selected model */- const modelIndex = catalog.findIndex((m) => m.key === model.key);+ const modelFilter = modelQuery.trim().toLowerCase();+ const shownModels = modelFilter+ ? catalog.filter(+ (m) => m.name.toLowerCase().includes(modelFilter) || (m.tag ?? "").toLowerCase().includes(modelFilter),+ )+ : catalog;+ const modelIndex = shownModels.findIndex((m) => m.key === model.key);useLayoutEffect(() => {if (!modelOpen) return;const target = modelRowRefs.current[modelHovered ?? modelIndex];- if (target) setModelBox({ top: target.offsetTop, height: target.offsetHeight });- }, [modelOpen, modelHovered, modelIndex]);+ if (target) {+ setModelBox({ top: target.offsetTop, height: target.offsetHeight });+ /* 40+ authenticated models: opening far from the current selection+ * hid it off-screen — bring it into view, but never fight the mouse */+ if (modelHovered === null) target.scrollIntoView({ block: "nearest" });+ }+ }, [modelOpen, modelHovered, modelIndex, modelFilter]);/* The menu is outside the clipped composer, so align it to the model* trigger by measurement instead of pinning it to the far-right edge. */@@ -254,10 +276,16 @@ export default function PromptBar({const triggerRect = modelRef.current.getBoundingClientRect();setModelMenuLeft(Math.max(0, Math.min(triggerRect.left - anchorRect.left, anchorRect.width - 176)));setModelMenuBottom(anchorRect.bottom - triggerRect.top + 8);+ // The menu grows upward from the trigger; without this cap a 40-model+ // list runs past the viewport top and clips its own filter input.+ setModelMenuMaxH(Math.max(220, Math.min(560, triggerRect.top - 20)));}, [modelOpen, wide, model.name]);useEffect(() => {- if (!modelOpen) setModelHovered(null);+ if (!modelOpen) {+ setModelHovered(null);+ setModelQuery("");+ }}, [modelOpen]);/* Build the shader with a pinned hue phase. createShader seeds its@@ -505,44 +533,75 @@ export default function PromptBar({{/* ── model menu ─────────────────────────────────── */}{modelOpen && (<div- onMouseLeave={() => setModelHovered(null)}- className="absolute z-10 w-44 rounded-[10px] bg-surface p-1 shadow-raised"- style={{ left: modelMenuLeft, bottom: modelMenuBottom, animation: "pop-in 180ms cubic-bezier(0.23,1,0.32,1) both", transformOrigin: "bottom left" }}+ className="absolute z-10 flex w-64 flex-col rounded-[10px] bg-surface p-1 shadow-raised"+ style={{ left: modelMenuLeft, bottom: modelMenuBottom, maxHeight: modelMenuMaxH, animation: "pop-in 180ms cubic-bezier(0.23,1,0.32,1) both", transformOrigin: "bottom left" }}>- {/* single gliding highlight — floats to the hovered / selected row */}- <span- aria-hidden- className="pointer-events-none absolute inset-x-1 rounded-[6px] bg-hover"- style={{- top: modelBox?.top ?? 0,- height: modelBox?.height ?? 0,- opacity: modelBox && modelHovered !== null ? 1 : 0,- transition:- "top 220ms cubic-bezier(0.23,1,0.32,1), height 220ms cubic-bezier(0.23,1,0.32,1), opacity 150ms ease",- }}- />- {catalog.map((m, i) => (- <button- key={m.key}- type="button"- ref={(el) => {- modelRowRefs.current[i] = el;+ {/* a real install lists 40+ authenticated seats — filter beats scrolling */}+ {catalog.length > 8 && (+ <input+ autoFocus+ value={modelQuery}+ onChange={(event) => {+ setModelQuery(event.target.value);+ setModelHovered(null);}}- onMouseDown={(event) => event.preventDefault()}- onMouseEnter={() => setModelHovered(i)}- onClick={() => {- selectModel(m);- inputRef.current?.focus();+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ setModelOpen(false);+ inputRef.current?.focus();+ }+ if (event.key === "Enter" && shownModels.length > 0) {+ selectModel(shownModels[0]);+ inputRef.current?.focus();+ }}}- className="relative z-10 flex h-7.5 w-full items-center gap-2 rounded-[6px] px-2 text-left"- >- <span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-ink">{m.name}</span>- <span className="shrink-0 text-[11px] text-ink-3">{m.tag}</span>- <span className={`shrink-0 text-ink ${m.key === model.key ? "" : "invisible"}`}>- <Icon size={13} strokeWidth={2.5}><path d="M20 6L9 17l-5-5" /></Icon>- </span>- </button>- ))}+ placeholder="Filter models…"+ aria-label="Filter models"+ className="mb-1 h-7 shrink-0 rounded-[6px] bg-field px-2 text-[12px] text-ink shadow-hairline outline-none placeholder:text-ink-3"+ />+ )}+ <div+ onMouseLeave={() => setModelHovered(null)}+ className="relative min-h-0 flex-1 overflow-y-auto"+ >+ {/* single gliding highlight — floats to the hovered / selected row */}+ <span+ aria-hidden+ className="pointer-events-none absolute inset-x-0 rounded-[6px] bg-hover"+ style={{+ top: modelBox?.top ?? 0,+ height: modelBox?.height ?? 0,+ opacity: modelBox && modelHovered !== null ? 1 : 0,+ transition:+ "top 220ms cubic-bezier(0.23,1,0.32,1), height 220ms cubic-bezier(0.23,1,0.32,1), opacity 150ms ease",+ }}+ />+ {shownModels.map((m, i) => (+ <button+ key={m.key}+ type="button"+ ref={(el) => {+ modelRowRefs.current[i] = el;+ }}+ onMouseDown={(event) => event.preventDefault()}+ onMouseEnter={() => setModelHovered(i)}+ onClick={() => {+ selectModel(m);+ inputRef.current?.focus();+ }}+ className="relative z-10 flex h-7.5 w-full items-center gap-2 rounded-[6px] px-2 text-left"+ >+ <span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-ink">{m.name}</span>+ <span className="shrink-0 text-[11px] text-ink-3">{m.tag}</span>+ <span className={`shrink-0 text-ink ${m.key === model.key ? "" : "invisible"}`}>+ <Icon size={13} strokeWidth={2.5}><path d="M20 6L9 17l-5-5" /></Icon>+ </span>+ </button>+ ))}+ {shownModels.length === 0 && (+ <div className="px-2 py-2 text-[12px] text-ink-3">No models match “{modelQuery.trim()}”</div>+ )}+ </div></div>)}diff --git a/apps/native/components/primitives/ThinkingState.tsx b/apps/native/components/primitives/ThinkingState.tsxindex 17b4ba4e..13ff247c 100644--- a/apps/native/components/primitives/ThinkingState.tsx+++ b/apps/native/components/primitives/ThinkingState.tsx@@ -32,6 +32,7 @@ type Row = {add?: number;del?: number;href?: string;+ shimmer?: boolean;};const VARIANTS: Record<@@ -97,6 +98,8 @@ export type ThinkingRow = {add?: number;del?: number;href?: string;+ /** A placeholder row ("Waiting on the model…") — spinner + shimmer, not static text. */+ shimmer?: boolean;};export default function ThinkingState({@@ -126,7 +129,9 @@ export default function ThinkingState({rows: rows ?? canned.rows,query: live ? undefined : canned.query,};- const autoExpanded = live ? true : stage >= 1 && stage < 4;+ /* live traces expand while the agent works and settle closed, like the+ * canned sequence; the reader can reopen the header any time */+ const autoExpanded = live ? (workingProp ?? true) : stage >= 1 && stage < 4;const expanded = manualExpanded ?? autoExpanded;const working = workingProp ?? (!live && stage < 3);const visible = live ? v.rows.length : stage < 2 ? 0 : stage === 2 ? Math.min(2, v.rows.length) : v.rows.length;@@ -149,7 +154,9 @@ export default function ThinkingState({key={variant}className="flex w-full max-w-95 flex-col"style={{- minHeight: working || expanded ? 176 : undefined,+ /* the gallery reserves room for its choreography; a live thread must+ * hug its content or every turn ships 176px of dead air */+ minHeight: !live && (working || expanded) ? 176 : undefined,transition: "min-height 400ms cubic-bezier(0.23,1,0.32,1)",}}>@@ -234,9 +241,28 @@ export default function ThinkingState({<span className="size-3 shrink-0 rounded-full border-[1.5px] border-line-strong border-t-ink-2" style={{ animation: "spin 700ms linear infinite" }} />))}+ {row.shimmer ? (+ <>+ <span+ className="size-3 shrink-0 rounded-full border-[1.5px] border-line-strong border-t-ink-2"+ style={{ animation: "spin 700ms linear infinite" }}+ />+ <span+ className="min-w-0 truncate bg-clip-text text-[12.5px] leading-relaxed text-transparent"+ style={{+ backgroundImage: "linear-gradient(90deg, var(--ink-3) 35%, var(--ink) 50%, var(--ink-3) 65%)",+ backgroundSize: "200% 100%",+ animation: "shimmer-text 1.4s linear infinite",+ }}+ >+ {row.primary}+ </span>+ </>+ ) : (<span className={`min-w-0 truncate text-[12.5px] ${variant === "Reasoning" ? "whitespace-normal leading-relaxed text-ink-2" : "font-medium text-ink"} ${variant === "Search" ? "animated-underline" : ""}`}>{row.primary}</span>+ )}{row.secondary && (<span className={`shrink-0 text-[11.5px] text-ink-3 ${row.mono ? "font-mono" : ""}`}>{row.secondary}diff --git a/apps/native/components/primitives/ToolChips.tsx b/apps/native/components/primitives/ToolChips.tsxindex 4799e5a9..1859ee3c 100644--- a/apps/native/components/primitives/ToolChips.tsx+++ b/apps/native/components/primitives/ToolChips.tsx@@ -90,6 +90,10 @@ export type LiveToolRow = {mono?: boolean;detailMono?: boolean;detail: { text: string; tone?: "add" }[];+ /** Workspace file this call touched; makes the chip a jump target. */+ path?: string;+ /** Live call state — running rows get a spinner so the turn visibly moves. */+ status?: "running" | "ok" | "error";};export type LiveDiff = {@@ -102,9 +106,12 @@ export type LiveDiff = {export default function ToolChips({rows: liveRows,diffs: liveDiffs,+ onOpenPath,}: {rows?: LiveToolRow[];diffs?: LiveDiff[];+ /** Open a touched file in the harness's files pane. */+ onOpenPath?: (path: string) => void;} = {}) {const live = liveRows !== undefined;const rows = live ? liveRows : ROWS;@@ -154,7 +161,7 @@ export default function ToolChips({});return (- <div className="min-h-[220px] w-full max-w-80 pb-1">+ <div className={live ? "w-full pb-1" : "min-h-[220px] w-full max-w-80 pb-1"}>{/* collapsed run header */}<buttontype="button"@@ -165,7 +172,22 @@ export default function ToolChips({<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" className="transition-transform duration-200" style={{ transform: open ? "rotate(0deg)" : "rotate(-90deg)" }}><path d="M6 9l6 6 6-6" /></svg>- <span className="tabular-nums">{live ? `${rows.length} tool calls` : "4 tool calls, 2 messages"}</span>+ <span className="tabular-nums">+ {live+ ? (() => {+ // Codex-style activity summary: what happened, not how many calls.+ const counts: Record<string, number> = {};+ for (const row of rows) counts[row.icon] = (counts[row.icon] ?? 0) + 1;+ const parts: string[] = [];+ if (counts.read) parts.push(`Explored ${counts.read} file${counts.read === 1 ? "" : "s"}`);+ if (counts.write) parts.push(`Edited ${counts.write} file${counts.write === 1 ? "" : "s"}`);+ if (counts.run) parts.push(`Ran ${counts.run} command${counts.run === 1 ? "" : "s"}`);+ const other = rows.length - (counts.read ?? 0) - (counts.write ?? 0) - (counts.run ?? 0);+ if (other > 0) parts.push(`${other} other step${other === 1 ? "" : "s"}`);+ return parts.join(" · ") || `${rows.length} tool call${rows.length === 1 ? "" : "s"}`;+ })()+ : "4 tool calls, 2 messages"}+ </span></button>{/* tool call rows */}@@ -185,12 +207,19 @@ export default function ToolChips({className="group/row -mx-[3px] flex h-7 w-[calc(100%+6px)] min-w-0 items-center gap-2 rounded-control px-[3px] text-left transition-colors duration-100 hover:bg-hover-2"><span className="relative flex size-4 shrink-0 items-center justify-center text-ink-3">+ {"status" in row && row.status === "running" ? (+ <span+ className={`size-3 rounded-full border-[1.5px] border-line-strong border-t-ink-2 transition-opacity duration-100 group-hover/row:opacity-0 ${rowOpen ? "opacity-0" : ""}`}+ style={{ animation: "spin 700ms linear infinite" }}+ />+ ) : (<svgwidth="13" height="13" viewBox="0 0 24 24" fill={row.icon === "think" ? "currentColor" : "none"} stroke="currentColor"- className={`transition-opacity duration-100 group-hover/row:opacity-0 ${rowOpen ? "opacity-0" : ""}`}+ className={`transition-opacity duration-100 group-hover/row:opacity-0 ${rowOpen ? "opacity-0" : ""} ${"status" in row && row.status === "error" ? "text-red" : ""}`}>{Icons[row.icon]}</svg>+ )}<svgwidth="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"className={`absolute transition-[opacity,transform] duration-150 group-hover/row:opacity-100 ${rowOpen ? "opacity-100" : "opacity-0"}`}@@ -200,13 +229,26 @@ export default function ToolChips({</svg></span><span className="shrink-0 text-[12.5px] font-medium text-ink">{row.label}</span>- <span- className={`inline-flex h-5.5 min-w-0 flex-1 cursor-pointer items-center truncate rounded-chip bg-field px-1.5- text-[11.5px] text-ink-2 shadow-hairline transition-colors duration-100 hover:bg-hover-2- ${row.mono ? "font-mono" : ""}`}- >- {row.chip}- </span>+ {row.chip ? (+ <span+ onClick={+ onOpenPath && "path" in row && row.path+ ? (event) => {+ event.stopPropagation();+ onOpenPath(row.path!);+ }+ : undefined+ }+ title={onOpenPath && "path" in row && row.path ? `Open ${row.path}` : undefined}+ className={`inline-flex h-5.5 min-w-0 max-w-fit flex-1 cursor-pointer items-center truncate rounded-chip bg-field px-1.5+ text-[11.5px] text-ink-2 shadow-hairline transition-colors duration-100 hover:bg-hover-2+ ${row.mono ? "font-mono" : ""}`}+ >+ {row.chip}+ </span>+ ) : (+ <span className="min-w-0 flex-1" />+ )}</button>{/* expanded detail */}diff --git a/apps/native/components/site/FilesPane.tsx b/apps/native/components/site/FilesPane.tsxnew file mode 100644index 00000000..fde4eb5a--- /dev/null+++ b/apps/native/components/site/FilesPane.tsx@@ -0,0 +1,407 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import Markdown from "@/components/primitives/Markdown";+import {+ formatSize,+ fsOpen,+ fsRawUrl,+ fsReveal,+ fsStat,+ gitChanges,+ gitFileDiff,+ IMAGE_RE,+ type FsDir,+ type FsFile,+ type GitChanges,+} from "@/lib/fs-client";+import { IconCrossSmall, IconFolder } from "@/lib/icons";++/* ─────────────────────────────────────────────────────────+ * FILES PANE+ * The workspace the agent is working in, made walkable:+ * breadcrumbs, folder listing, and a file viewer (markdown+ * rendered, code in mono) with Open / Reveal passthroughs.+ * ───────────────────────────────────────────────────────── */++const FileGlyph = ({ size = 13 }: { size?: number }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />+ <path d="M14 2v6h6" />+ </svg>+);++function ActionButton({ label, active = false, onClick }: { label: string; active?: boolean; onClick: () => void }) {+ return (+ <button+ type="button"+ aria-pressed={active}+ onClick={onClick}+ className={`flex h-6 items-center rounded-[6px] px-1.5 text-[11.5px] font-medium transition-colors duration-100 hover:bg-hover hover:text-ink ${+ active ? "bg-hover text-ink" : "text-ink-3"+ }`}+ >+ {label}+ </button>+ );+}++const TYPE_LABELS: Record<string, string> = {+ zig: "Zig", ts: "TypeScript", tsx: "TypeScript", js: "JavaScript", jsx: "JavaScript",+ json: "JSON", css: "CSS", html: "HTML", sh: "Shell", zsh: "Shell", py: "Python",+ rs: "Rust", go: "Go", swift: "Swift", yml: "YAML", yaml: "YAML", toml: "TOML",+ txt: "Plain text", lock: "Lockfile", mjs: "JavaScript",+};++/** Code-fence chrome for a whole file: type · lines · size header with+ * Copy and a wrap toggle, and a sticky line-number gutter. */+function TextViewer({ file }: { file: FsFile }) {+ const [wrap, setWrap] = useState(false);+ const [copied, setCopied] = useState(false);+ const copy = useCallback(() => {+ navigator.clipboard.writeText(file.text).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ });+ }, [file.text]);+ const lines = file.text.split("\n");+ if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();+ const ext = file.path.split(".").pop()?.toLowerCase() ?? "";+ const kind = TYPE_LABELS[ext] ?? (ext ? ext.toUpperCase() : "Plain text");++ return (+ <div className="overflow-hidden rounded-[10px] bg-inset shadow-hairline">+ <div className="flex h-7 items-center justify-between gap-2 border-b border-line px-2.5">+ <span className="min-w-0 truncate font-mono text-[11px] text-ink-3">+ {kind} · {lines.length.toLocaleString()} {lines.length === 1 ? "line" : "lines"} · {formatSize(file.size)}+ </span>+ <span className="flex shrink-0 items-center">+ <ActionButton label="Wrap" active={wrap} onClick={() => setWrap((w) => !w)} />+ <ActionButton label={copied ? "Copied" : "Copy"} onClick={copy} />+ </span>+ </div>+ <div className="flex overflow-x-auto">+ {!wrap && (+ <pre className="sticky left-0 shrink-0 border-r border-line bg-inset py-2.5 pr-2 pl-2.5 text-right font-mono text-[11.5px] leading-[1.65] text-ink-3/60 select-none">+ {lines.map((_, i) => i + 1).join("\n")}+ </pre>+ )}+ <pre+ className={`min-w-0 flex-1 px-3 py-2.5 font-mono text-[11.5px] leading-[1.65] text-ink-2 ${+ wrap ? "whitespace-pre-wrap break-all" : "whitespace-pre"+ }`}+ >+ {file.text}+ </pre>+ </div>+ {file.truncated && (+ <p className="border-t border-line px-2.5 py-1.5 text-[11px] text-ink-3">+ Showing the first 256 KB of {formatSize(file.size)}.+ </p>+ )}+ </div>+ );+}++/** Unified diff, Codex-review colored: adds green, dels red, hunks muted. */+function DiffView({ text }: { text: string }) {+ const lines = text.split("\n");+ return (+ <div className="px-3 py-3">+ <div className="overflow-x-auto rounded-[10px] bg-inset py-2 shadow-hairline">+ {lines.map((line, i) => {+ if (line.startsWith("diff --git") || line.startsWith("index ") || line.startsWith("new file") || line.startsWith("+++") || line.startsWith("---"))+ return null;+ const tone = line.startsWith("@@")+ ? "bg-hover text-ink-3"+ : line.startsWith("+")+ ? "text-green"+ : line.startsWith("-")+ ? "text-red"+ : "text-ink-2";+ return (+ <div key={i} className={`px-3 font-mono text-[11.5px] leading-[1.6] whitespace-pre ${tone}`}>+ {line || " "}+ </div>+ );+ })}+ {!text.trim() && <p className="px-3 text-[12px] text-ink-3">No diff (binary or unchanged).</p>}+ </div>+ </div>+ );+}++export default function FilesPane({+ requested,+ onClose,+}: {+ /** A path the harness wants shown (e.g. a clicked tool chip), or the+ * changes review when `changes` is set. */+ requested?: { path: string; n: number; changes?: boolean } | null;+ onClose: () => void;+}) {+ const [dir, setDir] = useState<FsDir | null>(null);+ const [file, setFile] = useState<FsFile | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [view, setView] = useState<"files" | "changes">("files");+ const [changes, setChanges] = useState<GitChanges | null>(null);+ const [diff, setDiff] = useState<{ path: string; text: string } | null>(null);++ const loadChanges = useCallback(async () => {+ try {+ setChanges(await gitChanges());+ setError(null);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ }+ }, []);++ const openChangesView = useCallback(() => {+ setView("changes");+ setDiff(null);+ void loadChanges();+ }, [loadChanges]);++ const show = useCallback(async (path: string, keepView = false) => {+ try {+ const res = await fsStat(path);+ setError(null);+ if (!keepView) {+ setView("files");+ setDiff(null);+ }+ if (res.dir) {+ setDir(res);+ setFile(null);+ } else {+ setFile(res);+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ }+ }, []);++ useEffect(() => {+ // Preload the root listing without stealing the view — a Review click+ // can land before this resolves, and changes must win that race.+ void show("", true);+ }, [show]);++ useEffect(() => {+ if (!requested) return;+ if (requested.changes) openChangesView();+ else void show(requested.path);+ }, [requested, show, openChangesView]);++ const openFileDiff = useCallback(async (path: string) => {+ try {+ setDiff({ path, text: await gitFileDiff(path) });+ setError(null);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ }+ }, []);++ const here = file ? file.path : (dir?.path ?? "");+ const crumbs = here ? here.split("/") : [];+ const rootName = dir?.root.split("/").pop() ?? file?.root.split("/").pop() ?? "workspace";+ const isMarkdown = file && /\.(md|mdx|markdown)$/i.test(file.path);+ const isImage = file && IMAGE_RE.test(file.path);++ return (+ <aside+ className="hidden w-[400px] shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page lg:flex"+ style={{ animation: "fade-in 300ms ease both" }}+ >+ {/* header: workspace root + close */}+ <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">+ <IconFolder size={16} />+ </span>+ <span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-ink" title={dir?.root ?? file?.root}>+ {rootName}+ </span>+ <button+ type="button"+ aria-pressed={view === "changes"}+ onClick={() => (view === "changes" ? (setView("files"), setDiff(null)) : openChangesView())}+ className={`flex h-6 items-center gap-1 rounded-[6px] px-1.5 text-[11.5px] font-medium transition-colors duration-100 hover:bg-hover hover:text-ink ${+ view === "changes" ? "bg-hover text-ink" : "text-ink-3"+ }`}+ >+ Changes+ {changes && changes.files.length > 0 && (+ <span className="rounded-full bg-field px-1 font-mono text-[10px] text-ink-2 tabular-nums shadow-hairline">+ {changes.files.length}+ </span>+ )}+ </button>+ <ActionButton label="Reveal" onClick={() => void fsReveal(here)} />+ {view === "files" && file && <ActionButton label="Open" onClick={() => void fsOpen(file.path)} />}+ <button+ type="button"+ aria-label="Close files"+ 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>++ {/* breadcrumbs (files view) / review summary (changes view) */}+ {view === "changes" ? (+ <div className="flex h-9 shrink-0 items-center gap-2 border-b border-line px-3 text-[12px] whitespace-nowrap">+ {diff ? (+ <>+ <button+ type="button"+ onClick={() => setDiff(null)}+ className="rounded px-1 py-0.5 font-medium text-ink-3 transition-colors hover:bg-hover hover:text-ink"+ >+ ‹ Changes+ </button>+ <span className="min-w-0 truncate font-mono text-[11.5px] text-ink">{diff.path}</span>+ </>+ ) : (+ <>+ <span className="font-medium text-ink">Uncommitted changes</span>+ {changes && (+ <span className="font-mono text-[11px] tabular-nums">+ <span className="text-green">+{changes.totalAdd}</span>{" "}+ <span className="text-red">−{changes.totalDel}</span>+ </span>+ )}+ <button+ type="button"+ onClick={() => void loadChanges()}+ className="ml-auto rounded px-1 py-0.5 text-[11.5px] font-medium text-ink-3 transition-colors hover:bg-hover hover:text-ink"+ >+ Refresh+ </button>+ </>+ )}+ </div>+ ) : (+ <div className="flex h-9 shrink-0 items-center gap-1 overflow-x-auto border-b border-line px-3 text-[12px] whitespace-nowrap text-ink-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">+ <button type="button" onClick={() => void show("")} className="rounded px-1 py-0.5 font-medium transition-colors hover:bg-hover hover:text-ink">+ {rootName}+ </button>+ {crumbs.map((seg, i) => (+ <span key={i} className="flex items-center gap-1">+ <span className="text-line-strong">/</span>+ <button+ type="button"+ onClick={() => void show(crumbs.slice(0, i + 1).join("/"))}+ className={`rounded px-1 py-0.5 transition-colors hover:bg-hover hover:text-ink ${i === crumbs.length - 1 ? "font-medium text-ink" : ""}`}+ >+ {seg}+ </button>+ </span>+ ))}+ </div>+ )}++ <div className="min-h-0 flex-1 overflow-y-auto">+ {error && <p className="px-4 py-3 text-[12.5px] text-red">{error}</p>}++ {/* changes review: per-file diff */}+ {!error && view === "changes" && diff && <DiffView key={diff.path} text={diff.text} />}++ {/* changes review: changed-file list */}+ {!error && view === "changes" && !diff && (+ <div className="flex flex-col px-2 py-1.5">+ {(changes?.files ?? []).map((entry) => (+ <button+ key={entry.path}+ type="button"+ onClick={() => void openFileDiff(entry.path)}+ className="flex h-8 items-center gap-2 rounded-[7px] px-2 text-left transition-colors duration-100 hover:bg-hover"+ >+ <span className="flex size-4 shrink-0 items-center justify-center text-ink-3">+ <FileGlyph />+ </span>+ <span className="min-w-0 flex-1 truncate font-mono text-[12px] text-ink">{entry.path}</span>+ {entry.untracked && <span className="shrink-0 text-[10px] font-medium text-accent-ink">new</span>}+ <span className="shrink-0 font-mono text-[10.5px] tabular-nums">+ <span className="text-green">+{entry.add}</span>{" "}+ {entry.del > 0 && <span className="text-red">−{entry.del}</span>}+ </span>+ </button>+ ))}+ {changes && changes.files.length === 0 && (+ <p className="px-2 py-2 text-[12.5px] text-ink-3">Working tree is clean — nothing to review.</p>+ )}+ </div>+ )}++ {/* file viewer */}+ {!error && view === "files" && file && (+ <div className="px-3 py-3">+ {isImage ? (+ <figure>+ <img+ src={fsRawUrl(file.path)}+ alt={file.path}+ className="max-w-full rounded-[10px] bg-inset shadow-hairline"+ style={{ animation: "fade-in 250ms ease both" }}+ />+ <figcaption className="mt-2 text-[11.5px] text-ink-3">{formatSize(file.size)}</figcaption>+ </figure>+ ) : file.binary ? (+ <p className="text-[12.5px] text-ink-3">+ Binary file · {formatSize(file.size)} — use Open to view it.+ </p>+ ) : isMarkdown ? (+ <>+ <Markdown text={file.text} onOpenPath={(p) => void show(p)} />+ {file.truncated && (+ <p className="mt-2 text-[11.5px] text-ink-3">Showing the first 256 KB of {formatSize(file.size)}.</p>+ )}+ </>+ ) : (+ <TextViewer key={file.path} file={file} />+ )}+ </div>+ )}++ {/* folder listing */}+ {!error && view === "files" && !file && dir && (+ <div className="flex flex-col px-2 py-1.5">+ {dir.path && (+ <button+ type="button"+ onClick={() => void show(dir.path.split("/").slice(0, -1).join("/"))}+ className="flex h-8 items-center gap-2 rounded-[7px] px-2 text-left text-[13px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"+ >+ <span className="flex size-4 shrink-0 items-center justify-center">…</span>+ <span>Up one level</span>+ </button>+ )}+ {dir.entries.map((entry) => {+ const target = dir.path ? `${dir.path}/${entry.name}` : entry.name;+ return (+ <button+ key={entry.name}+ type="button"+ onClick={() => void show(target)}+ className="group flex h-8 items-center gap-2 rounded-[7px] px-2 text-left transition-colors duration-100 hover:bg-hover"+ >+ <span className={`flex size-4 shrink-0 items-center justify-center ${entry.dir ? "text-accent-ink" : "text-ink-3"}`}>+ {entry.dir ? <IconFolder size={14} /> : <FileGlyph />}+ </span>+ <span className="min-w-0 flex-1 truncate text-[13px] text-ink">{entry.name}</span>+ {!entry.dir && (+ <span className="shrink-0 font-mono text-[10.5px] text-ink-3 opacity-0 transition-opacity duration-100 group-hover:opacity-100">+ {formatSize(entry.size)}+ </span>+ )}+ </button>+ );+ })}+ {dir.entries.length === 0 && <p className="px-2 py-2 text-[12.5px] text-ink-3">Empty folder</p>}+ </div>+ )}+ </div>+ </aside>+ );+}diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex be3d3d4e..a4ef943b 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -1,9 +1,11 @@"use client";import { useEffect, useRef, useState, type CSSProperties } from "react";-import PromptBar from "@/components/primitives/PromptBar";+import Markdown from "@/components/primitives/Markdown";+import PromptBar, { type PromptModel } from "@/components/primitives/PromptBar";import SidebarNav from "@/components/primitives/SidebarNav";-import StreamingText from "@/components/primitives/StreamingText";+import FilesPane from "@/components/site/FilesPane";+import { IconFolder } from "@/lib/icons";import TaskRows from "@/components/primitives/TaskRows";import ThinkingState from "@/components/primitives/ThinkingState";import ToolChips from "@/components/primitives/ToolChips";@@ -14,6 +16,7 @@ import {cancel,checkHealth,ensureSession,+ fetchModels,prompt,type Health,} from "@/lib/acp-client";@@ -42,12 +45,34 @@ function homeRevealStyle(visible: boolean): CSSProperties {function UserBubble({ text }: { text: string }) {return (<div className="flex justify-end pl-10 sm:pl-24" style={{ animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}>- <div className="rounded-xl bg-field px-3.5 py-2 text-[13px] leading-relaxed text-ink shadow-hairline">{text}</div>+ <div+ className="rounded-xl px-3.5 py-2 text-[13px] leading-relaxed text-ink shadow-hairline"+ style={{ background: "color-mix(in oklab, var(--accent) 12%, var(--surface))" }}+ >+ {text}+ </div></div>);}-function AssistantBody({ turn }: { turn: AssistantTurn }) {+function AssistantBody({+ turn,+ onOpenPath,+ onReview,+}: {+ turn: AssistantTurn;+ onOpenPath?: (path: string) => void;+ /** Open the workspace changes review (the Codex "Changed N files" bar). */+ onReview?: () => void;+}) {+ const thinking = turn.status === "thinking";+ // "Thought for Ns" — measured here, since ACP updates carry no timestamps.+ const startRef = useRef(Date.now());+ const [thoughtSecs, setThoughtSecs] = useState<number | null>(null);+ useEffect(() => {+ if (thinking) return;+ setThoughtSecs((current) => current ?? Math.max(1, Math.round((Date.now() - startRef.current) / 1000)));+ }, [thinking]);const reasoningRows = turn.reasoning? turn.reasoning.split(/\n+/)@@ -63,33 +88,52 @@ function AssistantBody({ turn }: { turn: AssistantTurn }) {mono: tool.icon === "run" || tool.icon === "write" || tool.icon === "read",detailMono: tool.icon === "run" || tool.icon === "write",detail: tool.detail,+ path: tool.path,+ status: tool.status,}));return (<article className="min-w-0" style={{ animation: "fade-up 450ms cubic-bezier(0.23,1,0.32,1) both" }}>- {(turn.status === "thinking" || reasoningRows.length > 0) && (+ {(thinking || reasoningRows.length > 0) && (<ThinkingStatevariant="Reasoning"- rows={reasoningRows.length ? reasoningRows : [{ primary: "Waiting on the model…" }]}+ rows={reasoningRows.length ? reasoningRows : [{ primary: "Waiting on the model…", shimmer: true }]}activeLabel={turn.model ? `Thinking · ${turn.model}` : "Thinking"}- doneLabel={turn.status === "thinking" ? "Thinking" : "Thought"}- working={turn.status === "thinking"}+ doneLabel={thoughtSecs ? `Thought for ${thoughtSecs}s` : "Thought"}+ working={thinking}/>)}{toolRows.length > 0 && (<div className="mt-4">- <ToolChips rows={toolRows} diffs={turn.diffs} />+ <ToolChips rows={toolRows} diffs={turn.diffs} onOpenPath={onOpenPath} /></div>)}- {(turn.text || turn.status === "streaming") && (- <div className="mt-4 max-w-[630px]">- <StreamingText- fill- loop={false}- text={turn.text}- streaming={turn.status === "streaming" || turn.status === "thinking"}- />+ {turn.status === "streaming" && !turn.text ? (+ /* Between the last tool and the first text token nothing streams —+ * a lone caret here read as "stuck". Shimmer like the thinking+ * header, and say which phase the agent is actually in. */+ <div className="mt-4">+ <span+ className="bg-clip-text text-[13px] font-medium whitespace-nowrap text-transparent"+ style={{+ backgroundImage: "linear-gradient(90deg, var(--ink-3) 35%, var(--ink) 50%, var(--ink-3) 65%)",+ backgroundSize: "200% 100%",+ animation: "shimmer-text 1.4s linear infinite",+ }}+ >+ {turn.tools.some((tool) => tool.status === "running") ? "Running tools…" : "Writing…"}+ </span></div>+ ) : (+ turn.text && (+ <div className="mt-4 max-w-[630px]">+ <Markdown+ text={turn.text}+ streaming={turn.status === "streaming" || turn.status === "thinking"}+ onOpenPath={onOpenPath}+ />+ </div>+ ))}{turn.error && (<p className="mt-4 max-w-[620px] text-[13.5px] leading-[1.65] text-red">{turn.error}</p>@@ -100,6 +144,32 @@ function AssistantBody({ turn }: { turn: AssistantTurn }) {{turn.costUsd !== undefined && turn.status === "done" && (<p className="mt-1 font-mono text-[11px] text-ink-3">${turn.costUsd.toFixed(4)}</p>)}+ {turn.status === "done" && turn.diffs.length > 0 && onReview && (+ <button+ type="button"+ onClick={onReview}+ className="mt-4 flex h-9 w-full max-w-[630px] items-center gap-2 rounded-[10px] bg-surface px-3 text-left shadow-btn transition-colors duration-100 hover:bg-hover"+ style={{ animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="shrink-0 text-ink-3" aria-hidden>+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />+ <path d="M14 2v6h6" />+ </svg>+ <span className="text-[12.5px] font-medium text-ink">+ Changed {turn.diffs.length} file{turn.diffs.length === 1 ? "" : "s"}+ </span>+ <span className="font-mono text-[11.5px] tabular-nums">+ <span className="text-green">+{turn.diffs.reduce((n, d) => n + d.add, 0)}</span>{" "}+ <span className="text-red">−{turn.diffs.reduce((n, d) => n + d.del, 0)}</span>+ </span>+ <span className="ml-auto flex items-center gap-0.5 text-[12.5px] font-medium text-ink-2">+ Review+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>+ <path d="M9 18l6-6-6-6" />+ </svg>+ </span>+ </button>+ )}</article>);}@@ -115,11 +185,17 @@ function EmptyState({health,offset,shuffle,+ models,+ modelKey,+ onModelChange,}: {onSend: (text: string) => void;health: Health | null;offset: number;shuffle: () => void;+ models: PromptModel[];+ modelKey?: string;+ onModelChange: (key: string) => void;}) {const shown = [0, 1, 2].map((i) => STARTER_PROMPTS[(offset + i) % STARTER_PROMPTS.length]);const [stage, setStage] = useState(0);@@ -149,7 +225,9 @@ function EmptyState({demo={false}tallplaceholder="Ask graff to read, edit, or review this workspace…"- models={MODELS}+ models={models}+ modelKey={modelKey}+ onModelChange={onModelChange}onSend={onSend}disabled={health !== null && !health.ok}/>@@ -179,9 +257,11 @@ function EmptyState({</button>))}<div className="mt-1 flex items-center gap-5 pl-0.5 text-[13px] text-ink-3">- <span className="flex items-center gap-2 py-1">+ <span className="flex items-center gap-2 py-1" title={health?.cwd}><span className={`size-1.5 rounded-full ${health?.ok ? "bg-green" : "bg-orange"}`} />- {health?.ok ? "Connected over ACP" : "Waiting for graff acp"}+ {health?.ok+ ? `Connected · ${health.cwd ? (health.cwd.split("/").pop() ?? health.cwd) : "over ACP"}`+ : "Waiting for graff acp"}</span><button type="button" onClick={shuffle} className="flex items-center gap-2 py-1 transition-colors duration-150 hover:text-ink">Shuffle suggestions@@ -198,8 +278,14 @@ export default function GraffHarness() {const [offset, setOffset] = useState(0);const [health, setHealth] = useState<Health | null>(null);const [sessionId, setSessionId] = useState<string | null>(null);- const [model, setModelKey] = useState(process.env.NEXT_PUBLIC_GRAFF_MODEL || MODELS[0].key);+ // No hardcoded default: until graff/models answers, the agent's own model+ // resolution decides, and `current` from that call re-points the picker.+ const [models, setModels] = useState<PromptModel[]>(MODELS);+ const [model, setModelKey] = useState<string | null>(process.env.NEXT_PUBLIC_GRAFF_MODEL || null);const [busy, setBusy] = useState(false);+ const [filesOpen, setFilesOpen] = useState(false);+ const [fileRequest, setFileRequest] = useState<{ path: string; n: number; changes?: boolean } | null>(null);+ const fileReqRef = useRef(0);const chatIdRef = useRef(1);const msgIdRef = useRef(0);const sessionRef = useRef<string | null>(null);@@ -209,6 +295,18 @@ export default function GraffHarness() {const active = chatThread.messages.length > 0;const lastAssistant = [...chatThread.messages].reverse().find((m): m is Extract<Msg, { role: "assistant" }> => m.role === "assistant");+ const adoptCatalog = async () => {+ // What did the agent actually resolve? The picker should show graff's+ // answer (fuzzy --model resolution, election-ranked seats), not our guess.+ try {+ const { models: live, current } = await fetchModels();+ if (live.length > 0) setModels(live);+ if (current) setModelKey(current);+ } catch {+ // keep the static fallback; the picker still works+ }+ };+useEffect(() => {let cancelled = false;(async () => {@@ -217,10 +315,11 @@ export default function GraffHarness() {setHealth(h);if (!h.ok) return;try {- const id = await ensureSession(model);+ const id = await ensureSession(model ?? undefined);if (cancelled) return;sessionRef.current = id;setSessionId(id);+ await adoptCatalog();} catch (err) {if (!cancelled) {setHealth({ ok: false, detail: err instanceof Error ? err.message : String(err) });@@ -234,6 +333,28 @@ export default function GraffHarness() {// eslint-disable-next-line react-hooks/exhaustive-deps}, []);+ const openPath = (path: string) => {+ setFilesOpen(true);+ setFileRequest({ path, n: (fileReqRef.current += 1) });+ };++ const openChanges = () => {+ setFilesOpen(true);+ setFileRequest({ path: "", n: (fileReqRef.current += 1), changes: true });+ };++ const changeModel = (key: string) => {+ setModelKey(key);+ sessionRef.current = null;+ void ensureSession(key, true)+ .then((id) => {+ sessionRef.current = id;+ setSessionId(id);+ return adoptCatalog();+ })+ .catch(() => undefined);+ };+const patchAssistant = (chatId: number, msgId: number, next: AssistantTurn) => {setChats((current) =>current.map((c) =>@@ -249,7 +370,7 @@ export default function GraffHarness() {const requireSession = async (reset = false): Promise<string> => {if (!reset && sessionRef.current) return sessionRef.current;- const id = await ensureSession(model, reset);+ const id = await ensureSession(model ?? undefined, reset);sessionRef.current = id;setSessionId(id);setHealth({ ok: true });@@ -272,13 +393,13 @@ export default function GraffHarness() {messages: [...c.messages,{ id: userId, role: "user", text: trimmed },- { id: asstId, role: "assistant", turn: { ...emptyTurn(), model } },+ { id: asstId, role: "assistant", turn: { ...emptyTurn(), model: model ?? undefined } },],},),);setBusy(true);- let turn: AssistantTurn = { ...emptyTurn(), model };+ let turn: AssistantTurn = { ...emptyTurn(), model: model ?? undefined };try {const id = await requireSession();for await (const update of prompt(id, trimmed)) {@@ -342,6 +463,8 @@ export default function GraffHarness() {...chats.filter((c) => c.title).map((c) => ({ id: `chat-${c.id}`, label: c.title as string, prompt: undefined })),];+ const workspaceName = health?.cwd ? (health.cwd.split("/").pop() || health.cwd) : "workspace";+const tabBar = (<div className="flex h-11 shrink-0 items-center gap-1 overflow-x-auto border-b border-line px-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">{chats.map((c) => (@@ -377,6 +500,18 @@ export default function GraffHarness() {</svg></button><div className="ml-auto flex items-center gap-2 pr-1">+ <button+ type="button"+ aria-pressed={filesOpen}+ onClick={() => setFilesOpen((open) => !open)}+ title={health?.cwd ?? "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"+ }`}+ >+ <IconFolder size={14} />+ <span className="max-w-40 truncate font-mono text-[11.5px]">{workspaceName}</span>+ </button><ThemeToggle /></div></div>@@ -393,6 +528,8 @@ export default function GraffHarness() {activeTitle={chatThread.title}onPick={pickRecent}onNewChat={newChat}+ activeNav={filesOpen ? "workspace" : "chats"}+ onNavigate={(key) => setFilesOpen(key === "workspace")}footerLabel={sessionId ? `Session ${sessionId.slice(0, 8)}` : "Connecting…"}onFooterClick={() => undefined}/>@@ -409,7 +546,7 @@ export default function GraffHarness() {message.role === "user" ? (<UserBubble key={message.id} text={message.text} />) : (- <AssistantBody key={message.id} turn={message.turn} />+ <AssistantBody key={message.id} turn={message.turn} onOpenPath={openPath} onReview={openChanges} />),)}</div>@@ -419,31 +556,15 @@ export default function GraffHarness() {<PromptBardemo={false}tall- placeholder={busy ? "Agent is working…" : "Reply"}- models={MODELS}- modelKey={model}- onModelChange={(key) => {- setModelKey(key);- sessionRef.current = null;- void ensureSession(key, true)- .then((id) => {- sessionRef.current = id;- setSessionId(id);- })- .catch(() => undefined);- }}+ placeholder={busy ? "Agent is working…" : "Follow up"}+ models={models}+ modelKey={model ?? undefined}+ onModelChange={changeModel}onSend={send}disabled={busy}+ busy={busy}+ onStop={() => sessionRef.current && void cancel(sessionRef.current)}/>- {busy && (- <button- type="button"- onClick={() => sessionRef.current && void cancel(sessionRef.current)}- className="mt-2 text-[12px] text-ink-3 transition-colors hover:text-ink"- >- Cancel turn- </button>- )}</div></div></div>@@ -454,12 +575,17 @@ export default function GraffHarness() {health={health}offset={offset}shuffle={() => setOffset((current) => (current + 3) % STARTER_PROMPTS.length)}+ models={models}+ modelKey={model ?? undefined}+ onModelChange={changeModel}/></div>)}</section>- {active && paneTodos.length > 0 && (+ {filesOpen && <FilesPane requested={fileRequest} onClose={() => setFilesOpen(false)} />}++ {!filesOpen && 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/desktop/main.zig b/apps/native/desktop/main.zigindex d3397aeb..d0ea9dee 100644--- a/apps/native/desktop/main.zig+++ b/apps/native/desktop/main.zig@@ -94,7 +94,7 @@ fn sendWebViewInit(recv: Id, s: Sel, frame: CGRect, config: Id) Id {fn runMac(url: []const u8) !void {var url_buf: [256]u8 = undefined;- const url_z = try std.fmt.bufPrintZ(&url_buf, "{s}", .{url});+ const url_z = try std.fmt.bufPrintSentinel(&url_buf, "{s}", .{url}, 0);const app = send(cls("NSApplication"), sel("sharedApplication"));sendIntv(app, sel("setActivationPolicy:"), NSApplicationActivationPolicyRegular);diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.tsindex 4a75f6b0..d67cfee8 100644--- a/apps/native/lib/acp-client.ts+++ b/apps/native/lib/acp-client.ts@@ -2,7 +2,7 @@ import { parseRpcLine, type AcpUpdate, type JsonRpcLine } from "./acp";const BASE = "/api/acp";-export type Health = { ok: boolean; detail?: string };+export type Health = { ok: boolean; detail?: string; cwd?: string };async function* ndjson(res: Response): AsyncGenerator<JsonRpcLine> {const body = res.body;@@ -101,7 +101,56 @@ export const STARTER_PROMPTS = [{ id: "todos", label: "What's on the checklist?", prompt: "Read the current todo list and tell me what's open." },] as const;-export const MODELS = [+export type ModelChoice = {+ key: string;+ name: string;+ tag?: string;+ provider?: string;+ context?: number;+ cost?: string;+ current?: boolean;+};++type GraffModelsResult = {+ models?: {+ name: string;+ provider: string;+ context: number;+ authenticated: boolean;+ cost: string;+ current: boolean;+ }[];+ current?: { model: string; provider: string };+};++/** The models THIS install can reach: `graff/models` filtered to providers+ * with live credentials, already in the agent's election order. The same+ * model name can be served by several providers; the highest-ranked seat+ * wins its row (spawn-by-name resolves through graff's own routing anyway). */+export async function fetchModels(): Promise<{ models: ModelChoice[]; current: string | null }> {+ const res = await rpc("graff/models");+ const body = (await res.json()) as { result?: GraffModelsResult; error?: string };+ if (!body.result) throw new Error(body.error ?? "graff/models failed");+ const seen = new Set<string>();+ const models: ModelChoice[] = [];+ for (const m of body.result.models ?? []) {+ if (!m.authenticated || seen.has(m.name)) continue;+ seen.add(m.name);+ models.push({+ key: m.name,+ name: m.name,+ tag: m.cost === "plan" || m.cost === "credits" ? `${m.provider} · ${m.cost}` : m.provider,+ provider: m.provider,+ context: m.context,+ cost: m.cost,+ current: m.current,+ });+ }+ return { models, current: body.result.current?.model ?? null };+}++/** Fallback until `graff/models` answers (or when nothing is authenticated). */+export const MODELS: ModelChoice[] = [{ key: "gpt-5.5", name: "GPT-5.5", tag: "OpenAI" },{ key: "claude-opus-4-8", name: "Opus 4.8", tag: "Anthropic" },{ key: "codex", name: "Codex", tag: "ChatGPT" },diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.tsindex 119b3eb2..63ce1fd5 100644--- a/apps/native/lib/acp.ts+++ b/apps/native/lib/acp.ts@@ -50,6 +50,20 @@ function iconForKind(kind: string | undefined, title: string): ToolIcon {return "think";}+/** `mcp__codedbpro__faster_search` → { server: "codedbpro", tool: "faster_search" } */+function mcpParts(name: string): { server: string; tool: string } | null {+ if (!name.startsWith("mcp__")) return null;+ const rest = name.slice(5);+ const split = rest.indexOf("__");+ if (split < 0) return { server: "", tool: rest };+ return { server: rest.slice(0, split), tool: rest.slice(split + 2) };+}++function humanize(id: string): string {+ const words = id.replace(/[_-]+/g, " ").trim();+ return words ? words[0].toUpperCase() + words.slice(1) : id;+}+function labelForKind(kind: string | undefined, title: string): string {if (kind === "execute") return "Run";if (kind === "edit") return "Edit";@@ -59,6 +73,10 @@ function labelForKind(kind: string | undefined, title: string): string {if (kind === "fetch") return "Fetch";if (kind === "search") return "Search";if (kind === "think") return "Plan";+ const mcp = mcpParts(title);+ if (mcp) return humanize(mcp.tool);+ // Bare engine tools (attempt_completion, todo_write…) read as identifiers.+ if (/^[a-z0-9_]+$/.test(title)) return humanize(title);return title;}@@ -139,7 +157,13 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId: "running": (prev?.status ?? "running");const rawInput = update.rawInput && typeof update.rawInput === "object" ? update.rawInput : {};- const path = typeof rawInput.path === "string" ? rawInput.path : prev?.path;+ // codedbpro-style tools say `file`, catalog tools say `path`.+ const path =+ typeof rawInput.path === "string"+ ? rawInput.path+ : typeof rawInput.file === "string"+ ? rawInput.file+ : prev?.path;const contentItems = "content" in update && Array.isArray(update.content) ? update.content : [];const contentText = contentItems.map((item) => item.content?.text)@@ -151,11 +175,16 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId: fromInput.length? fromInput: (prev?.detail ?? []);+ const mcp = mcpParts(title);+ const label = labelForKind(kind, title);+ // A raw MCP name as chip repeated the label; show the server instead, and+ // no chip at all when it would just echo the label.+ const chip = path ?? (mcp ? mcp.server : title);const row: ToolRow = {id,- name: labelForKind(kind, title),+ name: label,icon: iconForKind(kind, title),- chip: path ?? title,+ chip: chip === label || humanize(chip) === label ? "" : chip,status,detail,path,@@ -171,6 +200,8 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId...turn,tools,todos: todos.length ? todos : turn.todos,+ // Text after a tool bracket is a new message segment, not a continuation.+ pendingBreak: turn.text.length > 0 ? true : turn.pendingBreak,status: turn.status === "ask" ? "ask" : status === "running" || turn.status === "thinking" ? "streaming" : turn.status,};if ((merged.icon === "write" || kind === "edit") && (status === "ok" || status === "error")) {@@ -191,7 +222,7 @@ export function finishAcpTurn(turn: AssistantTurn): AssistantTurn {export function applyAcpUpdate(turn: AssistantTurn, update: AcpUpdate): AssistantTurn {switch (update.sessionUpdate) {case "agent_thought_chunk": {- const text = update.content?.text ?? "";+ const text = (update as { content?: AcpContent }).content?.text ?? "";return {...turn,reasoning: `${turn.reasoning}${text}`,@@ -199,16 +230,19 @@ export function applyAcpUpdate(turn: AssistantTurn, update: AcpUpdate): Assistan};}case "agent_message_chunk": {- const text = update.content?.text ?? "";+ const text = (update as { content?: AcpContent }).content?.text ?? "";+ const needsBreak = turn.pendingBreak && turn.text.length > 0 && !/\s$/.test(turn.text) && !/^\s/.test(text);return {...turn,- text: `${turn.text}${text}`,+ text: `${turn.text}${needsBreak ? "\n\n" : ""}${text}`,+ pendingBreak: false,status: turn.status === "ask" ? "ask" : "streaming",};}case "tool_call":case "tool_call_update":- return upsertTool(turn, update);+ // The catch-all AcpUpdate member defeats literal narrowing here.+ return upsertTool(turn, update as Extract<AcpUpdate, { toolCallId: string }>);default:return turn;}diff --git a/apps/native/lib/fs-client.ts b/apps/native/lib/fs-client.tsnew file mode 100644index 00000000..8243a101--- /dev/null+++ b/apps/native/lib/fs-client.ts@@ -0,0 +1,73 @@+/** Browser side of /api/fs — workspace listing, file reads, open/reveal. */++const BASE = "/api/fs";++export type FsEntry = { name: string; dir: boolean; size: number };++export type FsDir = { root: string; path: string; dir: true; entries: FsEntry[] };++export type FsFile = {+ root: string;+ path: string;+ dir: false;+ size: number;+ binary: boolean;+ truncated: boolean;+ text: string;+};++export async function fsStat(path: string): Promise<FsDir | FsFile> {+ const res = await fetch(`${BASE}?path=${encodeURIComponent(path)}`, { cache: "no-store" });+ const body = (await res.json()) as (FsDir | FsFile) & { error?: string };+ if (!res.ok) throw new Error(body.error ?? `fs ${res.status}`);+ return body;+}++async function act(action: "open" | "reveal", path: string): Promise<void> {+ await fetch(BASE, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ action, path }),+ }).catch(() => {});+}++/** Reveal in Finder. */+export const fsReveal = (path: string) => act("reveal", path);++/** Open with the default app (editor for code, Preview for images…). */+export const fsOpen = (path: string) => act("open", path);++export const IMAGE_RE = /\.(png|jpe?g|gif|webp|svg|ico|bmp|avif)$/i;++/** Byte URL for a workspace file — <img src=…> in the pane. */+export const fsRawUrl = (path: string) => `${BASE}?path=${encodeURIComponent(path)}&raw=1`;++export function formatSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+}++/* ── workspace changes (Codex-style review) ── */++export type GitFile = { path: string; add: number; del: number; untracked: boolean };++export type GitChanges = { root: string; files: GitFile[]; totalAdd: number; totalDel: number };++export async function gitChanges(): Promise<GitChanges> {+ const res = await fetch("/api/git", { cache: "no-store" });+ const body = (await res.json()) as GitChanges & { error?: string };+ if (!res.ok) throw new Error(body.error ?? `git ${res.status}`);+ return body;+}++export async function gitFileDiff(path: string): Promise<string> {+ const res = await fetch("/api/git", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ path }),+ });+ const body = (await res.json()) as { diff?: string; error?: string };+ if (!res.ok) throw new Error(body.error ?? `git ${res.status}`);+ return body.diff ?? "";+}diff --git a/apps/native/lib/graff-events.ts b/apps/native/lib/graff-events.tsindex 7ca7b115..3e5a569b 100644--- a/apps/native/lib/graff-events.ts+++ b/apps/native/lib/graff-events.ts@@ -84,6 +84,9 @@ export type AssistantTurn = {model?: string;provider?: string;costUsd?: number;+ /** A tool bracket landed after streamed text — the next text chunk starts a+ * new paragraph instead of fusing onto the previous sentence. */+ pendingBreak?: boolean;status: TurnStatus;};diff --git a/apps/native/tsconfig.json b/apps/native/tsconfig.jsonindex c51be7a8..900d942c 100644--- a/apps/native/tsconfig.json+++ b/apps/native/tsconfig.json@@ -6,6 +6,7 @@"skipLibCheck": true,"strict": true,"noEmit": true,+ "allowImportingTsExtensions": true,"esModuleInterop": true,"module": "esnext","moduleResolution": "bundler",