Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(native): one agent per tab, and graff's session history in the sidebar

justrach0718d594465e
diff --git a/apps/native/README.md b/apps/native/README.md
index 1f89920d..84f85e36 100644
--- a/apps/native/README.md
+++ b/apps/native/README.md
@@ -40,9 +40,12 @@ browser → Next.js /api/acp → graff acp --yolo (stdio JSON-RPC)
(this app) session/update → thought / tools / text
```
-The Next.js route owns one `graff acp` child. The browser never speaks
-stdio; it POSTs ACP methods and reads an NDJSON stream of the same
-JSON-RPC lines the agent wrote.
+The Next.js route owns one `graff acp` child **per chat tab** (the agent
+holds a single live session per process and has no `session/load`, so a
+tab's conversation memory is its child). The browser never speaks stdio; it
+POSTs ACP methods with its `<page>:<chat>` handle and reads an NDJSON
+stream of the same JSON-RPC lines the agent wrote. Closing a tab or leaving
+the page reaps its agents; tabs run turns concurrently.
| ACP `sessionUpdate` | primitive |
| --- | --- |
@@ -63,6 +66,14 @@ 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.
+History is graff's own: every tab's agent autosaves to
+`.graff/sessions/<name>.session.json` in the workspace (`--resume <name>`),
+and the sidebar lists that directory — grouped by day, searchable — via
+`/api/sessions`, which peeks each file's header rather than parsing it.
+Opening a past session renders its saved transcript at once and spawns the
+tab's agent with `--resume`, so a follow-up continues the conversation with
+the model's memory intact.
+
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
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index dbae84f9..d2cc494d 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -15,9 +15,23 @@ type Slot = {
nextId: number;
sessionId: string | null;
model: string | null;
+ /** graff session name (`--resume`): the file this agent autosaves to. */
+ resume: string | null;
};
-const g = globalThis as typeof globalThis & { __graffAcp?: Slot };
+// One `graff acp` child per chat tab. The agent holds exactly one live
+// session per process (`session/load` is not implemented), so a tab's
+// conversation memory *is* its child: when every tab shared one child, each
+// new tab respawned it and silently erased the others' context. Keys are the
+// browser's `<page>:<chat>` handles, so a reloaded page never adopts a stale
+// child's history; `dispose`/`dispose-page` reap children on tab close and
+// page unload. Kept on globalThis so dev-server module reloads don't orphan
+// running agents.
+const g = globalThis as typeof globalThis & { __graffAcpSlots?: Map<string, Slot> };
+const slots = (g.__graffAcpSlots ??= new Map<string, Slot>());
+const DEFAULT_CHAT = "default";
+// Session names become a CLI argument and a filename under .graff/sessions.
+const SESSION_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
function graffBin(): string {
if (process.env.GRAFF_BIN) return process.env.GRAFF_BIN;
@@ -42,28 +56,54 @@ function yolo(): boolean {
return true;
}
-function killSlot() {
- const slot = g.__graffAcp;
+// A closed tab's agent gets stdin EOF first: `graff acp` leaves its read loop
+// on EOF and writes the session's exit save on the way out, which a SIGTERM
+// would skip. The signal is the fallback for an agent that does not wind down.
+const EXIT_GRACE_MS = 5_000;
+
+function killSlot(chat: string) {
+ const slot = slots.get(chat);
if (!slot) return;
- slot.child.kill("SIGTERM");
- g.__graffAcp = undefined;
+ slots.delete(chat);
+ try {
+ slot.child.stdin.end();
+ } catch {
+ // already closed
+ }
+ const timer = setTimeout(() => {
+ try {
+ slot.child.kill("SIGTERM");
+ } catch {
+ // already gone
+ }
+ }, EXIT_GRACE_MS);
+ timer.unref();
+ slot.child.once("exit", () => clearTimeout(timer));
+}
+
+function killPage(page: string) {
+ const prefix = `${page}:`;
+ for (const chat of [...slots.keys()]) {
+ if (chat.startsWith(prefix)) killSlot(chat);
+ }
}
-function spawnAgent(model?: string): Slot {
- killSlot();
+function spawnAgent(chat: string, model?: string, resume?: string): Slot {
+ killSlot(chat);
const args = ["acp"];
if (yolo()) args.push("--yolo");
if (model) args.push("--model", model);
+ if (resume) args.push("--resume", resume);
const child = spawn(graffBin(), args, {
stdio: ["pipe", "pipe", "inherit"],
cwd: workspace(),
env: process.env,
});
- const slot: Slot = { child, buf: "", nextId: 1, sessionId: null, model: model ?? null };
+ const slot: Slot = { child, buf: "", nextId: 1, sessionId: null, model: model ?? null, resume: resume ?? null };
child.on("exit", () => {
- if (g.__graffAcp === slot) g.__graffAcp = undefined;
+ if (slots.get(chat) === slot) slots.delete(chat);
});
- g.__graffAcp = slot;
+ slots.set(chat, slot);
return slot;
}
@@ -113,11 +153,12 @@ async function rpc(slot: Slot, method: string, params?: unknown): Promise<unknow
}
}
-async function bootstrap(model?: string, reset = false): Promise<Slot> {
- if (!reset && g.__graffAcp && (!model || g.__graffAcp.model === model) && g.__graffAcp.sessionId) {
- return g.__graffAcp;
+async function bootstrap(chat: string, model?: string, reset = false, resume?: string): Promise<Slot> {
+ const live = slots.get(chat);
+ if (!reset && live && (!model || live.model === model) && (!resume || live.resume === resume) && live.sessionId) {
+ return live;
}
- const slot = spawnAgent(model);
+ const slot = spawnAgent(chat, model, resume);
await rpc(slot, "initialize", { protocolVersion: 1, clientCapabilities: { fs: {} } });
const created = (await rpc(slot, "session/new", { cwd: workspace() })) as {
sessionId?: string;
@@ -128,9 +169,9 @@ async function bootstrap(model?: string, reset = false): Promise<Slot> {
}
export async function GET() {
- // 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.
+ // Health is a passive probe: report the binary and the live agent count
+ // 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) {
@@ -143,21 +184,35 @@ export async function GET() {
{ status: 502 },
);
}
- return Response.json({ ok: true, sessionId: g.__graffAcp?.sessionId ?? null, cwd: workspace() });
+ return Response.json({ ok: true, sessions: slots.size, cwd: workspace() });
}
export async function POST(req: NextRequest) {
- const body = (await req.json()) as { method?: string; params?: Record<string, unknown>; stream?: boolean };
+ const body = (await req.json()) as {
+ chat?: string;
+ method?: string;
+ params?: Record<string, unknown>;
+ stream?: boolean;
+ };
const method = body.method ?? "";
+ const chat = typeof body.chat === "string" && body.chat ? body.chat : DEFAULT_CHAT;
+ const model = typeof body.params?.model === "string" ? body.params.model : undefined;
try {
+ if (method === "dispose") {
+ killSlot(chat);
+ return Response.json({ ok: true });
+ }
+ if (method === "dispose-page") {
+ if (typeof body.params?.page === "string" && body.params.page) killPage(body.params.page);
+ return Response.json({ ok: true });
+ }
if (method === "bootstrap") {
- const slot = await bootstrap(
- typeof body.params?.model === "string" ? body.params.model : undefined,
- body.params?.reset === true,
- );
+ const resume =
+ typeof body.params?.resume === "string" && SESSION_NAME_RE.test(body.params.resume) ? body.params.resume : undefined;
+ const slot = await bootstrap(chat, model, body.params?.reset === true, resume);
return Response.json({ sessionId: slot.sessionId });
}
- const slot = await bootstrap(typeof body.params?.model === "string" ? body.params.model : undefined);
+ const slot = await bootstrap(chat, model);
if (method === "session/cancel") {
writeLine(slot, { jsonrpc: "2.0", method: "session/cancel", params: body.params });
return Response.json({ ok: true });
diff --git a/apps/native/app/api/sessions/route.ts b/apps/native/app/api/sessions/route.ts
new file mode 100644
index 00000000..80e3e4de
--- /dev/null
+++ b/apps/native/app/api/sessions/route.ts
@@ -0,0 +1,123 @@
+import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, 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();
+}
+
+// graff autosaves every conversation to `<cwd>/.graff/sessions/<name>.session.json`
+// (src/session_index.zig owns the layout). The header — provider, model, title,
+// updated_ms — is written before the (possibly multi-MB) messages array, so the
+// list peeks the prefix instead of parsing whole files.
+const SESSIONS_DIR = ".graff/sessions";
+const EXT = ".session.json";
+const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+const PEEK_BYTES = 64 * 1024;
+const MAX_FULL_BYTES = 16 * 1024 * 1024;
+
+type Header = { title?: unknown; updated_ms?: unknown; model?: unknown; provider?: unknown };
+
+export type StoredSessionRow = {
+ name: string;
+ title: string | null;
+ updatedMs: number;
+ model: string | null;
+ provider: string | null;
+ size: number;
+};
+
+function str(v: unknown): string | null {
+ return typeof v === "string" && v.length > 0 ? v : null;
+}
+
+function peekHeader(file: string, size: number): Header | null {
+ const fd = openSync(file, "r");
+ try {
+ const want = Math.min(size, PEEK_BYTES);
+ const buf = Buffer.alloc(want);
+ const n = readSync(fd, buf, 0, want, 0);
+ const text = buf.toString("utf8", 0, n);
+ // Quotes inside string values are escaped in the file, so the raw needle
+ // only matches the real top-level key.
+ const idx = text.indexOf('"messages":');
+ if (idx < 0) return null;
+ let head = text.slice(0, idx).trimEnd();
+ if (head.endsWith(",")) head = head.slice(0, -1);
+ return JSON.parse(`${head}}`) as Header;
+ } catch {
+ return null;
+ } finally {
+ closeSync(fd);
+ }
+}
+
+function rowFor(dir: string, entry: string): StoredSessionRow | null {
+ const name = entry.slice(0, -EXT.length);
+ if (!NAME_RE.test(name)) return null;
+ const file = path.join(dir, entry);
+ let size = 0;
+ let mtimeMs = 0;
+ try {
+ const st = statSync(file);
+ if (!st.isFile()) return null;
+ size = st.size;
+ mtimeMs = st.mtimeMs;
+ } catch {
+ return null;
+ }
+ const header = size > 0 ? peekHeader(file, size) : null;
+ const updated = typeof header?.updated_ms === "number" && header.updated_ms > 0 ? header.updated_ms : Math.round(mtimeMs);
+ return {
+ name,
+ title: str(header?.title),
+ updatedMs: updated,
+ model: str(header?.model),
+ provider: str(header?.provider),
+ size,
+ };
+}
+
+export async function GET(req: NextRequest) {
+ const root = workspaceRoot();
+ const dir = path.join(root, SESSIONS_DIR);
+ const name = req.nextUrl.searchParams.get("name");
+ if (name !== null) {
+ if (!NAME_RE.test(name)) return Response.json({ error: "bad session name" }, { status: 400 });
+ const file = path.join(dir, `${name}${EXT}`);
+ if (!existsSync(file)) return Response.json({ error: "no such session" }, { status: 404 });
+ const st = statSync(file);
+ if (st.size > MAX_FULL_BYTES) return Response.json({ error: "session too large to open" }, { status: 413 });
+ try {
+ const parsed = JSON.parse(readFileSync(file, "utf8")) as Header & { messages?: unknown };
+ return Response.json({
+ name,
+ title: str(parsed.title),
+ model: str(parsed.model),
+ provider: str(parsed.provider),
+ updatedMs: typeof parsed.updated_ms === "number" ? parsed.updated_ms : Math.round(st.mtimeMs),
+ size: st.size,
+ messages: Array.isArray(parsed.messages) ? parsed.messages : [],
+ });
+ } catch (err) {
+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 502 });
+ }
+ }
+ if (!existsSync(dir)) return Response.json({ cwd: root, sessions: [] });
+ const rows: StoredSessionRow[] = [];
+ for (const entry of readdirSync(dir)) {
+ if (!entry.endsWith(EXT)) continue;
+ const row = rowFor(dir, entry);
+ if (row) rows.push(row);
+ }
+ rows.sort((a, b) => b.updatedMs - a.updatedMs);
+ return Response.json({ cwd: root, sessions: rows });
+}
diff --git a/apps/native/components/primitives/SidebarNav.tsx b/apps/native/components/primitives/SidebarNav.tsx
index 5653aea0..ddcf2116 100644
--- a/apps/native/components/primitives/SidebarNav.tsx
+++ b/apps/native/components/primitives/SidebarNav.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
+import { Fragment, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { createPortal } from "react-dom";
import {
IconArrowBoxLeft,
@@ -37,6 +37,10 @@ export type SidebarRecent = {
id: string;
label: string;
prompt?: string;
+ /** Section header shown above the first row of each run of equal groups. */
+ group?: string;
+ /** Tooltip detail (model, age) — the row itself stays a single line. */
+ hint?: string;
};
const DEFAULT_RECENTS: SidebarRecent[] = [
@@ -48,6 +52,8 @@ const DEFAULT_RECENTS: SidebarRecent[] = [
type SidebarNavProps = {
activeTitle?: string | null;
+ /** When set, rows highlight by id instead of by label (titles can repeat). */
+ activeId?: string | null;
className?: string;
fill?: boolean;
onNewChat?: () => void;
@@ -200,6 +206,7 @@ function WorkspaceMenu({
export default function SidebarNav({
activeTitle,
+ activeId,
className = "",
fill = false,
onNewChat,
@@ -403,14 +410,20 @@ export default function SidebarNav({
</div>
<GlideGroup>
- {visibleRecents.map((item) => {
- const active = item.label === selectedTitle;
+ {visibleRecents.map((item, index) => {
+ const active = activeId !== undefined ? item.id === activeId : item.label === selectedTitle;
+ const header = item.group && item.group !== visibleRecents[index - 1]?.group ? item.group : null;
return (
+ <Fragment key={item.id}>
+ {header && (
+ <div className={`sidebar-copy mx-2 px-2 pb-1 text-[11px] font-medium tracking-wide text-ink-3 ${index === 0 ? "" : "mt-3"}`}>
+ {header}
+ </div>
+ )}
<button
- key={item.id}
data-row
type="button"
- title={item.label}
+ title={item.hint ? `${item.label} — ${item.hint}` : item.label}
onClick={() => {
selectNav("chats");
if (activeTitle === undefined) setDemoActiveTitle(item.label);
@@ -424,6 +437,7 @@ export default function SidebarNav({
{item.label}
</span>
</button>
+ </Fragment>
);
})}
{query && visibleRecents.length === 0 && (
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index a5acbbaa..a5d51c29 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -14,13 +14,17 @@ import {
MODELS,
STARTER_PROMPTS,
cancel,
+ chatHandle,
checkHealth,
+ disposePage,
+ disposeSession,
ensureSession,
fetchModels,
prompt,
type Health,
} from "@/lib/acp-client";
import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";
+import { dateGroup, listSessions, loadSession, relativeTime, type StoredSession } from "@/lib/sessions";
const NAME = "there";
@@ -116,13 +120,20 @@ function AssistantBody({
useEffect(() => {
if (draining) articleRef.current?.scrollIntoView({ block: "end", behavior: "auto" });
}, [smoothText, draining]);
- // "Thought for Ns" — measured here, since ACP updates carry no timestamps.
+ // "Thought for Ns": the harness stamps `thoughtMs` on the turn as it streams
+ // (ACP updates carry no timestamps); a live turn without one yet is timed here.
const startRef = useRef(Date.now());
- const [thoughtSecs, setThoughtSecs] = useState<number | null>(null);
+ const [thoughtSecs, setThoughtSecs] = useState<number | null>(
+ turn.thoughtMs !== undefined ? Math.max(1, Math.round(turn.thoughtMs / 1000)) : null,
+ );
useEffect(() => {
if (thinking) return;
- setThoughtSecs((current) => current ?? Math.max(1, Math.round((Date.now() - startRef.current) / 1000)));
- }, [thinking]);
+ setThoughtSecs((current) => {
+ if (current !== null) return current;
+ const ms = turn.thoughtMs ?? Date.now() - startRef.current;
+ return Math.max(1, Math.round(ms / 1000));
+ });
+ }, [thinking, turn.thoughtMs]);
const reasoningRows = turn.reasoning
? turn.reasoning
.split(/\n+/)
@@ -230,7 +241,20 @@ type Msg =
| { id: number; role: "user"; text: string }
| { id: number; role: "assistant"; turn: AssistantTurn };
-type Chat = { id: number; title: string | null; messages: Msg[] };
+/** `model` is what this tab's own agent was spawned with; the harness-level
+ * model is only the default a new tab inherits. */
+type Chat = { id: number; title: string | null; messages: Msg[]; model?: string; session?: string };
+
+function newPageToken(): string {
+ return Math.random().toString(36).slice(2, 10);
+}
+
+/** A fresh tab's graff session name. Not `session-…`: that prefix is what the
+ * REPL's auto-title renames, and a tab needs a name that stays put so the
+ * sidebar row and the running agent keep pointing at the same file. */
+function newSessionName(): string {
+ return `native-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
+}
function EmptyState({
onSend,
@@ -329,36 +353,70 @@ export default function GraffHarness() {
const [activeId, setActiveId] = useState(1);
const [offset, setOffset] = useState(0);
const [health, setHealth] = useState<Health | null>(null);
- const [sessionId, setSessionId] = useState<string | null>(null);
+ // Every tab owns a `graff acp` child (the agent keeps one session per
+ // process), so sessions, busy state and the spawned model are all per chat.
+ const pageRef = useRef<string>(newPageToken());
+ const sessionsRef = useRef(new Map<number, string>());
+ // chat id → graff session name (the `--resume` target / sidebar identity).
+ const sessionNamesRef = useRef(new Map<number, string>());
+ const [sessionIds, setSessionIds] = useState<Record<number, string>>({});
+ const [stored, setStored] = useState<StoredSession[]>([]);
+ const [busyIds, setBusyIds] = useState<ReadonlySet<number>>(() => new Set());
// 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);
const scrollRef = useRef<HTMLDivElement>(null);
const chatThread = chats.find((c) => c.id === activeId) ?? chats[0];
const active = chatThread.messages.length > 0;
+ const busy = busyIds.has(chatThread.id);
+ const chatModel = chatThread.model ?? model ?? undefined;
+ const sessionId = sessionIds[chatThread.id] ?? null;
+ const handleOf = (chatId: number) => chatHandle(pageRef.current, chatId);
+ const setBusyFor = (chatId: number, on: boolean) =>
+ setBusyIds((current) => {
+ if (current.has(chatId) === on) return current;
+ const next = new Set(current);
+ if (on) next.add(chatId);
+ else next.delete(chatId);
+ return next;
+ });
+ const setChatModel = (chatId: number, key: string) =>
+ setChats((current) => current.map((c) => (c.id === chatId ? { ...c, model: key } : c)));
const lastAssistant = [...chatThread.messages].reverse().find((m): m is Extract<Msg, { role: "assistant" }> => m.role === "assistant");
- const adoptCatalog = async () => {
+ const adoptCatalog = async (chatId: number) => {
// 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();
+ const { models: live, current } = await fetchModels(handleOf(chatId));
if (live.length > 0) setModels(live);
- if (current) setModelKey(current);
+ if (current) {
+ setChatModel(chatId, current);
+ setModelKey((fallback) => fallback ?? current);
+ }
} catch {
// keep the static fallback; the picker still works
}
};
+ const requireSession = async (chatId: number, reset = false, key?: string): Promise<string> => {
+ const live = sessionsRef.current.get(chatId);
+ if (!reset && live) return live;
+ const spawnModel = key ?? chats.find((c) => c.id === chatId)?.model ?? model ?? undefined;
+ const id = await ensureSession(handleOf(chatId), spawnModel, reset, sessionNamesRef.current.get(chatId));
+ sessionsRef.current.set(chatId, id);
+ setSessionIds((current) => ({ ...current, [chatId]: id }));
+ setHealth({ ok: true });
+ return id;
+ };
+
useEffect(() => {
let cancelled = false;
(async () => {
@@ -367,24 +425,49 @@ export default function GraffHarness() {
setHealth(h);
if (!h.ok) return;
try {
- const id = await ensureSession(model ?? undefined);
+ const session = newSessionName();
+ sessionNamesRef.current.set(1, session);
+ setChats((current) => current.map((c) => (c.id === 1 ? { ...c, session } : c)));
+ await requireSession(1);
if (cancelled) return;
- sessionRef.current = id;
- setSessionId(id);
- await adoptCatalog();
+ await adoptCatalog(1);
} catch (err) {
if (!cancelled) {
setHealth({ ok: false, detail: err instanceof Error ? err.message : String(err) });
}
}
})();
+ void refreshStored();
+ // Reap this page's agents when it goes away — without this every reload
+ // leaves a `graff acp` (and its MCP children) running under the dev server.
+ const page = pageRef.current;
+ const reap = () => disposePage(page);
+ window.addEventListener("pagehide", reap);
return () => {
cancelled = true;
+ window.removeEventListener("pagehide", reap);
};
- // ACP session is created once per mount; model changes respawn the agent.
+ // The first tab's agent is spawned once per mount; later tabs spawn their
+ // own on creation, and a model change respawns only the active tab's.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ /** Re-read graff's session directory; tabs adopt the titles graff saved. */
+ const refreshStored = async () => {
+ try {
+ const list = await listSessions();
+ setStored(list);
+ setChats((current) =>
+ current.map((c) => {
+ const saved = c.session ? list.find((s) => s.name === c.session) : undefined;
+ return saved?.title && saved.title !== c.title ? { ...c, title: saved.title } : c;
+ }),
+ );
+ } catch {
+ // the sidebar keeps its last list
+ }
+ };
+
const openPath = (path: string) => {
setFilesOpen(true);
setFileRequest({ path, n: (fileReqRef.current += 1) });
@@ -396,14 +479,13 @@ export default function GraffHarness() {
};
const changeModel = (key: string) => {
+ // New tabs inherit the pick; the active tab respawns its agent with it
+ // (a fresh context — the agent cannot swap models mid-session).
+ const chatId = chatThread.id;
setModelKey(key);
- sessionRef.current = null;
- void ensureSession(key, true)
- .then((id) => {
- sessionRef.current = id;
- setSessionId(id);
- return adoptCatalog();
- })
+ setChatModel(chatId, key);
+ void requireSession(chatId, true, key)
+ .then(() => adoptCatalog(chatId))
.catch(() => undefined);
};
@@ -420,24 +502,16 @@ export default function GraffHarness() {
);
};
- const requireSession = async (reset = false): Promise<string> => {
- if (!reset && sessionRef.current) return sessionRef.current;
- const id = await ensureSession(model ?? undefined, reset);
- sessionRef.current = id;
- setSessionId(id);
- setHealth({ ok: true });
- return id;
- };
-
const send = async (text: string) => {
const trimmed = text.trim();
- if (!trimmed || busy) return;
+ const chatId = chatThread.id;
+ if (!trimmed || busyIds.has(chatId)) return;
const userId = (msgIdRef.current += 1);
const asstId = (msgIdRef.current += 1);
const title = chatThread.title ?? (trimmed.length > 30 ? `${trimmed.slice(0, 30).trimEnd()}…` : trimmed);
setChats((current) =>
current.map((c) =>
- c.id !== chatThread.id
+ c.id !== chatId
? c
: {
...c,
@@ -445,63 +519,100 @@ export default function GraffHarness() {
messages: [
...c.messages,
{ id: userId, role: "user", text: trimmed },
- { id: asstId, role: "assistant", turn: { ...emptyTurn(), model: model ?? undefined } },
+ { id: asstId, role: "assistant", turn: { ...emptyTurn(), model: chatModel } },
],
},
),
);
- setBusy(true);
- let turn: AssistantTurn = { ...emptyTurn(), model: model ?? undefined };
+ setBusyFor(chatId, true);
+ let turn: AssistantTurn = { ...emptyTurn(), model: chatModel };
+ const startedAt = Date.now();
try {
- const id = await requireSession();
- for await (const update of prompt(id, trimmed)) {
+ const id = await requireSession(chatId);
+ for await (const update of prompt(handleOf(chatId), id, trimmed)) {
turn = applyAcpUpdate(turn, update);
- patchAssistant(chatThread.id, asstId, turn);
+ if (turn.thoughtMs === undefined && turn.status !== "thinking") turn = { ...turn, thoughtMs: Date.now() - startedAt };
+ patchAssistant(chatId, asstId, turn);
}
turn = finishAcpTurn(turn);
- patchAssistant(chatThread.id, asstId, turn);
+ patchAssistant(chatId, asstId, turn);
} catch (err) {
turn = { ...turn, error: err instanceof Error ? err.message : String(err), status: "error" };
- patchAssistant(chatThread.id, asstId, turn);
+ patchAssistant(chatId, asstId, turn);
} finally {
- setBusy(false);
+ setBusyFor(chatId, false);
+ // graff autosaves the turn in the background; look once now for the
+ // title, and again after the write has had time to land.
+ void refreshStored();
+ setTimeout(() => void refreshStored(), 2500);
}
};
- const newChat = () => {
+ const openChat = (id: number) => {
+ const session = newSessionName();
+ sessionNamesRef.current.set(id, session);
+ setChats((current) => [...current, { id, title: null, messages: [], model: model ?? undefined, session }]);
+ setActiveId(id);
+ setFilesOpen(false);
+ // Spawn eagerly so the first send is not stuck behind agent + MCP boot.
+ void requireSession(id).catch(() => undefined);
+ };
+
+ /** Open a saved graff session: its transcript renders from the file at once,
+ * and the tab's agent starts with `--resume` so a follow-up remembers it. */
+ const openStored = async (name: string) => {
+ const existing = chats.find((c) => c.session === name);
+ if (existing) {
+ setActiveId(existing.id);
+ setFilesOpen(false);
+ return;
+ }
+ let loaded: Awaited<ReturnType<typeof loadSession>>;
+ try {
+ loaded = await loadSession(name);
+ } catch (err) {
+ setHealth({ ok: true, detail: err instanceof Error ? err.message : String(err) });
+ return;
+ }
const id = (chatIdRef.current += 1);
- setChats((current) => [...current, { id, title: null, messages: [] }]);
+ const messages: Msg[] = loaded.messages.map((m) => ({ id: (msgIdRef.current += 1), ...m }));
+ sessionNamesRef.current.set(id, name);
+ setChats((current) => [
+ ...current,
+ { id, title: loaded.meta.title ?? name, messages, model: loaded.meta.model ?? undefined, session: name },
+ ]);
setActiveId(id);
- sessionRef.current = null;
- void requireSession(true).catch(() => undefined);
+ setFilesOpen(false);
+ void requireSession(id, false, loaded.meta.model ?? undefined).catch(() => undefined);
+ };
+
+ const newChat = () => openChat((chatIdRef.current += 1));
+
+ const dropChat = (id: number) => {
+ sessionsRef.current.delete(id);
+ sessionNamesRef.current.delete(id);
+ setSessionIds((current) => {
+ const { [id]: _gone, ...rest } = current;
+ return rest;
+ });
+ setBusyFor(id, false);
+ void disposeSession(handleOf(id));
};
const closeChat = (id: number) => {
+ dropChat(id);
const remaining = chats.filter((c) => c.id !== id);
if (remaining.length === 0) {
- const nid = (chatIdRef.current += 1);
- setChats([{ id: nid, title: null, messages: [] }]);
- setActiveId(nid);
+ setChats([]);
+ openChat((chatIdRef.current += 1));
return;
}
setChats(remaining);
if (id === activeId) setActiveId(remaining[remaining.length - 1].id);
};
- const pickRecent = (_id: string, label: string, prompt?: string) => {
- const existing = chats.find((c) => c.title === label);
- if (existing) {
- setActiveId(existing.id);
- return;
- }
- if (chatThread.messages.length === 0) {
- void send(prompt ?? label);
- return;
- }
- const id = (chatIdRef.current += 1);
- setChats((current) => [...current, { id, title: null, messages: [] }]);
- setActiveId(id);
- queueMicrotask(() => void send(prompt ?? label));
+ const pickRecent = (id: string) => {
+ void openStored(id);
};
useEffect(() => {
@@ -510,10 +621,14 @@ export default function GraffHarness() {
if (el) el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
}, [chatThread.messages, active, lastAssistant?.turn.text, lastAssistant?.turn.tools.length]);
- const recents = [
- ...STARTER_PROMPTS.map((p) => ({ id: p.id, label: p.label, prompt: p.prompt })),
- ...chats.filter((c) => c.title).map((c) => ({ id: `chat-${c.id}`, label: c.title as string, prompt: undefined })),
- ];
+ // The sidebar is graff's session directory, newest first, bucketed by day.
+ const now = Date.now();
+ const recents = stored.map((s) => ({
+ id: s.name,
+ label: s.title ?? s.name,
+ group: dateGroup(s.updatedMs, now),
+ hint: [s.model, relativeTime(s.updatedMs, now)].filter(Boolean).join(" · "),
+ }));
const workspaceName = health?.cwd ? (health.cwd.split("/").pop() || health.cwd) : "workspace";
@@ -526,7 +641,7 @@ export default function GraffHarness() {
c.id === activeId ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"
}`}
>
- {busy && c.id === activeId && (
+ {busyIds.has(c.id) && (
<span
className="mr-1 size-1.5 shrink-0 animate-pulse rounded-full"
style={{ background: "var(--accent)" }}
@@ -585,6 +700,7 @@ export default function GraffHarness() {
className="hidden lg:flex"
recents={recents}
activeTitle={chatThread.title}
+ activeId={chatThread.session ?? null}
onPick={pickRecent}
onNewChat={newChat}
activeNav={filesOpen ? "workspace" : "chats"}
@@ -617,12 +733,15 @@ export default function GraffHarness() {
tall
placeholder={busy ? "Agent is working…" : "Follow up"}
models={models}
- modelKey={model ?? undefined}
+ modelKey={chatModel}
onModelChange={changeModel}
onSend={send}
disabled={busy}
busy={busy}
- onStop={() => sessionRef.current && void cancel(sessionRef.current)}
+ onStop={() => {
+ const live = sessionsRef.current.get(chatThread.id);
+ if (live) void cancel(handleOf(chatThread.id), live);
+ }}
/>
</div>
</div>
@@ -635,7 +754,7 @@ export default function GraffHarness() {
offset={offset}
shuffle={() => setOffset((current) => (current + 3) % STARTER_PROMPTS.length)}
models={models}
- modelKey={model ?? undefined}
+ modelKey={chatModel}
onModelChange={changeModel}
/>
</div>
diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.ts
index d67cfee8..02bc9e3f 100644
--- a/apps/native/lib/acp-client.ts
+++ b/apps/native/lib/acp-client.ts
@@ -4,6 +4,15 @@ const BASE = "/api/acp";
export type Health = { ok: boolean; detail?: string; cwd?: string };
+/** Server-side key for a chat tab's own `graff acp` child: `<page>:<chat>`.
+ * The page half is minted per load so a reload never inherits the previous
+ * page's still-running agents (and their conversation history). */
+export type ChatHandle = string;
+
+export function chatHandle(page: string, chatId: number): ChatHandle {
+ return `${page}:${chatId}`;
+}
+
async function* ndjson(res: Response): AsyncGenerator<JsonRpcLine> {
const body = res.body;
if (!body) throw new Error("ACP bridge had no body");
@@ -30,11 +39,11 @@ async function* ndjson(res: Response): AsyncGenerator<JsonRpcLine> {
}
}
-async function rpc(method: string, params?: unknown, stream = false): Promise<Response> {
+async function rpc(chat: ChatHandle, method: string, params?: unknown, stream = false): Promise<Response> {
const res = await fetch(BASE, {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ method, params, stream }),
+ body: JSON.stringify({ chat, method, params, stream }),
cache: "no-store",
});
if (!res.ok) {
@@ -54,18 +63,21 @@ export async function checkHealth(): Promise<Health> {
}
}
-export async function ensureSession(model?: string, reset = false): Promise<string> {
- const res = await rpc("bootstrap", { model, reset });
+/** `resume` names the graff session file the tab's agent autosaves to (and
+ * restores from, when it already exists) — `graff acp --resume <name>`. */
+export async function ensureSession(chat: ChatHandle, model?: string, reset = false, resume?: string): Promise<string> {
+ const res = await rpc(chat, "bootstrap", { model, reset, resume });
const body = (await res.json()) as { sessionId?: string; error?: string };
if (!body.sessionId) throw new Error(body.error ?? "ACP session/new failed");
return body.sessionId;
}
export async function* prompt(
+ chat: ChatHandle,
sessionId: string,
text: string,
): AsyncGenerator<AcpUpdate> {
- const res = await rpc("session/prompt", {
+ const res = await rpc(chat, "session/prompt", {
sessionId,
prompt: [{ type: "text", text }],
}, true);
@@ -86,11 +98,36 @@ export async function* prompt(
if (!terminal) throw new Error("ACP stream ended before session/prompt returned");
}
-export async function cancel(sessionId: string): Promise<void> {
+export async function cancel(chat: ChatHandle, sessionId: string): Promise<void> {
await fetch(BASE, {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ method: "session/cancel", params: { sessionId } }),
+ body: JSON.stringify({ chat, method: "session/cancel", params: { sessionId } }),
+ }).catch(() => {});
+}
+
+/** Kill a closed tab's agent. `keepalive` so a close-then-navigate still lands. */
+export async function disposeSession(chat: ChatHandle): Promise<void> {
+ await fetch(BASE, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ chat, method: "dispose" }),
+ keepalive: true,
+ }).catch(() => {});
+}
+
+/** Reap every agent this page spawned. Fired from `pagehide`, where only a
+ * beacon is guaranteed to leave the tab; falls back to a keepalive fetch. */
+export function disposePage(page: string): void {
+ const payload = JSON.stringify({ method: "dispose-page", params: { page } });
+ if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
+ if (navigator.sendBeacon(BASE, new Blob([payload], { type: "application/json" }))) return;
+ }
+ void fetch(BASE, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: payload,
+ keepalive: true,
}).catch(() => {});
}
@@ -127,8 +164,8 @@ type GraffModelsResult = {
* 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");
+export async function fetchModels(chat: ChatHandle): Promise<{ models: ModelChoice[]; current: string | null }> {
+ const res = await rpc(chat, "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>();
diff --git a/apps/native/lib/graff-events.ts b/apps/native/lib/graff-events.ts
index 6482a9d2..1363660e 100644
--- a/apps/native/lib/graff-events.ts
+++ b/apps/native/lib/graff-events.ts
@@ -87,6 +87,10 @@ export type AssistantTurn = {
model?: string;
provider?: string;
costUsd?: number;
+ /** How long the model thought before its first tool/text, measured by the
+ * harness while the turn streamed — kept on the turn so a remount (tab
+ * switch) shows the real figure instead of re-timing from mount. */
+ thoughtMs?: 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;
@@ -104,7 +108,7 @@ export function emptyTurn(): AssistantTurn {
};
}
-function iconFor(name: string): ToolIcon {
+export function iconFor(name: string): ToolIcon {
if (name === "bash" || name === "bash_output" || name === "bash_kill") return "run";
if (name === "write_file" || name === "edit_file") return "write";
if (name === "read_file" || name === "codedb" || name === "webfetch" || name === "skill") return "read";
@@ -112,7 +116,7 @@ function iconFor(name: string): ToolIcon {
return "think";
}
-function chipFor(name: string, input: Record<string, unknown>): string {
+export function chipFor(name: string, input: Record<string, unknown>): string {
const path = typeof input.path === "string" ? input.path : undefined;
const command = typeof input.command === "string" ? input.command : undefined;
if (path) return path;
@@ -145,7 +149,7 @@ function upsertTool(turn: AssistantTurn, name: string, input: Record<string, unk
return { ...turn, tools: [...turn.tools, row], status: turn.status === "ask" ? "ask" : "streaming" };
}
-function summarizeInput(name: string, input: Record<string, unknown>): { text: string; tone?: "add" }[] {
+export function summarizeInput(name: string, input: Record<string, unknown>): { text: string; tone?: "add" }[] {
if (name === "edit_file") {
const oldS = typeof input.old_string === "string" ? input.old_string : "";
const newS = typeof input.new_string === "string" ? input.new_string : "";
@@ -169,7 +173,7 @@ function summarizeInput(name: string, input: Record<string, unknown>): { text: s
}
}
-function firstLine(s: string): string {
+export function firstLine(s: string): string {
const line = s.split("\n")[0] ?? s;
return line.length > 80 ? `${line.slice(0, 79)}…` : line;
}
diff --git a/apps/native/lib/sessions.test.ts b/apps/native/lib/sessions.test.ts
new file mode 100644
index 00000000..0682e6eb
--- /dev/null
+++ b/apps/native/lib/sessions.test.ts
@@ -0,0 +1,89 @@
+import { describe, it } from "node:test";
+import assert from "node:assert/strict";
+import { dateGroup, transcriptFromMessages } from "./sessions.ts";
+
+describe("transcriptFromMessages", () => {
+ it("folds assistant + tool messages into one turn per user message", () => {
+ const raw = [
+ { role: "user", content: "write a haiku file" },
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ { id: "c1", type: "function", function: { name: "write_file", arguments: '{"path":"demo.md","content":"a\\nb\\nc"}' } },
+ ],
+ },
+ { role: "tool", tool_call_id: "c1", content: "wrote 6 bytes to demo.md" },
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [{ id: "c2", type: "function", function: { name: "attempt_completion", arguments: '{"result":"Created demo.md."}' } }],
+ },
+ { role: "tool", tool_call_id: "c2", content: "completion recorded" },
+ { role: "user", content: "thanks" },
+ { role: "assistant", content: "You're welcome." },
+ ];
+ const out = transcriptFromMessages(raw, "glm-5.3-flash");
+ assert.equal(out.length, 4);
+ assert.deepEqual(out[0], { role: "user", text: "write a haiku file" });
+ const first = out[1];
+ assert.equal(first.role, "assistant");
+ if (first.role !== "assistant") return;
+ assert.equal(first.turn.status, "done");
+ assert.equal(first.turn.model, "glm-5.3-flash");
+ assert.equal(first.turn.text, "Created demo.md.");
+ assert.equal(first.turn.tools.length, 1);
+ const row = first.turn.tools[0];
+ assert.equal(row.name, "Write file");
+ assert.equal(row.icon, "write");
+ assert.equal(row.path, "demo.md");
+ assert.equal(row.status, "ok");
+ assert.deepEqual(row.detail.map((d) => d.text), ["3 lines", "wrote 6 bytes to demo.md"]);
+ assert.deepEqual(out[2], { role: "user", text: "thanks" });
+ const last = out[3];
+ if (last.role !== "assistant") return;
+ assert.equal(last.turn.text, "You're welcome.");
+ });
+
+ it("marks failed tool results, keeps todos, and survives junk", () => {
+ const raw = [
+ { role: "user", content: [{ type: "text", text: "plan it" }] },
+ {
+ role: "assistant",
+ content: "On it.",
+ tool_calls: [
+ { id: "t1", type: "function", function: { name: "todo_write", arguments: '{"todos":[{"content":"step one","status":"in_progress"}]}' } },
+ { id: "b1", type: "function", function: { name: "bash", arguments: '{"command":"false"}' } },
+ { id: "x1", type: "function", function: { name: "mcp__codedbpro__read", arguments: "not json" } },
+ ],
+ },
+ { role: "tool", tool_call_id: "b1", content: "Error: exit 1" },
+ "garbage",
+ null,
+ { role: "user", content: "" },
+ ];
+ const out = transcriptFromMessages(raw);
+ assert.equal(out.length, 2);
+ const turn = out[1];
+ if (turn.role !== "assistant") return;
+ assert.equal(turn.turn.text, "On it.");
+ assert.deepEqual(turn.turn.todos, [{ id: "todo-0", content: "step one", status: "in_progress" }]);
+ const bash = turn.turn.tools.find((t) => t.id === "b1");
+ assert.equal(bash?.status, "error");
+ assert.equal(bash?.icon, "run");
+ const mcp = turn.turn.tools.find((t) => t.id === "x1");
+ assert.equal(mcp?.name, "Read");
+ });
+});
+
+describe("dateGroup", () => {
+ it("buckets by calendar day relative to now", () => {
+ const now = new Date(2026, 7, 30, 15, 0, 0).getTime();
+ const day = 86_400_000;
+ assert.equal(dateGroup(now - 3_600_000, now), "Today");
+ assert.equal(dateGroup(now - day, now), "Yesterday");
+ assert.equal(dateGroup(now - 3 * day, now), "Previous 7 days");
+ assert.equal(dateGroup(now - 20 * day, now), "Previous 30 days");
+ assert.match(dateGroup(now - 90 * day, now), /2026/);
+ });
+});
diff --git a/apps/native/lib/sessions.ts b/apps/native/lib/sessions.ts
new file mode 100644
index 00000000..f1c1a3d3
--- /dev/null
+++ b/apps/native/lib/sessions.ts
@@ -0,0 +1,194 @@
+import {
+ chipFor,
+ emptyTurn,
+ firstLine,
+ iconFor,
+ summarizeInput,
+ type AssistantTurn,
+ type TodoItem,
+ type ToolRow,
+} from "./graff-events.ts";
+
+/** A conversation graff autosaved under `.graff/sessions/<name>.session.json`. */
+export type StoredSession = {
+ name: string;
+ title: string | null;
+ updatedMs: number;
+ model: string | null;
+ provider: string | null;
+ size: number;
+};
+
+export type TranscriptMsg =
+ | { role: "user"; text: string }
+ | { role: "assistant"; turn: AssistantTurn };
+
+const BASE = "/api/sessions";
+
+export async function listSessions(): Promise<StoredSession[]> {
+ const res = await fetch(BASE, { cache: "no-store" });
+ if (!res.ok) throw new Error(`sessions → ${res.status}`);
+ const body = (await res.json()) as { sessions?: StoredSession[] };
+ return body.sessions ?? [];
+}
+
+export async function loadSession(name: string): Promise<{ meta: StoredSession; messages: TranscriptMsg[] }> {
+ const res = await fetch(`${BASE}?name=${encodeURIComponent(name)}`, { cache: "no-store" });
+ if (!res.ok) {
+ const detail = await res.text().catch(() => "");
+ throw new Error(`session ${name} → ${res.status}: ${detail.slice(0, 200)}`);
+ }
+ const body = (await res.json()) as StoredSession & { messages?: unknown[] };
+ const { messages, ...meta } = body;
+ return { meta, messages: transcriptFromMessages(messages ?? [], meta.model ?? undefined) };
+}
+
+/** Sidebar bucket for a session's last activity, newest buckets first. */
+export function dateGroup(ms: number, now = Date.now()): string {
+ const today = new Date(now);
+ const startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime();
+ const day = 86_400_000;
+ if (ms >= startOfToday) return "Today";
+ if (ms >= startOfToday - day) return "Yesterday";
+ if (ms >= startOfToday - 7 * day) return "Previous 7 days";
+ if (ms >= startOfToday - 30 * day) return "Previous 30 days";
+ return new Date(ms).toLocaleString(undefined, { month: "long", year: "numeric" });
+}
+
+export function relativeTime(ms: number, now = Date.now()): string {
+ const delta = Math.max(0, now - ms);
+ const min = Math.round(delta / 60_000);
+ if (min < 1) return "just now";
+ if (min < 60) return `${min}m ago`;
+ const hours = Math.round(min / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.round(hours / 24);
+ if (days < 30) return `${days}d ago`;
+ return new Date(ms).toLocaleDateString();
+}
+
+type RawCall = { id?: unknown; function?: { name?: unknown; arguments?: unknown } };
+type RawMsg = { role?: unknown; content?: unknown; tool_calls?: unknown; tool_call_id?: unknown };
+
+function textOf(content: unknown): string {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content
+ .map((part) => (part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : ""))
+ .filter(Boolean)
+ .join("\n");
+}
+
+function humanize(id: string): string {
+ const words = id.replace(/[_-]+/g, " ").trim();
+ return words ? words[0].toUpperCase() + words.slice(1) : id;
+}
+
+/** `mcp__codedbpro__faster_search` → "Faster search"; `write_file` → "Write file". */
+function labelFor(name: string): string {
+ if (name.startsWith("mcp__")) {
+ const rest = name.slice(5);
+ const split = rest.indexOf("__");
+ return humanize(split < 0 ? rest : rest.slice(split + 2));
+ }
+ return humanize(name);
+}
+
+function todosOf(input: Record<string, unknown>): TodoItem[] {
+ const raw = input.todos;
+ if (!Array.isArray(raw)) return [];
+ return raw.flatMap((item, i) => {
+ if (!item || typeof item !== "object") return [];
+ const rec = item as Record<string, unknown>;
+ const content = typeof rec.content === "string" ? rec.content : "";
+ if (!content) return [];
+ const status = rec.status === "completed" || rec.status === "in_progress" ? rec.status : "pending";
+ return [{ id: typeof rec.id === "string" ? rec.id : `todo-${i}`, content, status }];
+ });
+}
+
+function appendText(turn: AssistantTurn, text: string): void {
+ const t = text.trim();
+ if (!t) return;
+ turn.text = turn.text ? `${turn.text}\n\n${t}` : t;
+}
+
+/**
+ * Rebuild the harness's turn shapes from a saved session's provider-native
+ * message array (user / assistant+tool_calls / tool). Consecutive assistant
+ * and tool messages fold into one turn until the next user message, the way
+ * the live ACP stream renders a turn; `attempt_completion` is the engine's
+ * final-answer tool, so its `result` becomes prose instead of a tool row.
+ */
+export function transcriptFromMessages(raw: unknown[], model?: string): TranscriptMsg[] {
+ const out: TranscriptMsg[] = [];
+ let turn: AssistantTurn | null = null;
+ const flush = () => {
+ if (turn) out.push({ role: "assistant", turn: { ...turn, status: "done" } });
+ turn = null;
+ };
+ const current = (): AssistantTurn => (turn ??= { ...emptyTurn(), model, status: "done" });
+
+ for (const item of raw) {
+ if (!item || typeof item !== "object") continue;
+ const msg = item as RawMsg;
+ if (msg.role === "user") {
+ const text = textOf(msg.content).trim();
+ if (!text) continue;
+ flush();
+ out.push({ role: "user", text });
+ continue;
+ }
+ if (msg.role === "assistant") {
+ const t = current();
+ appendText(t, textOf(msg.content));
+ const calls = Array.isArray(msg.tool_calls) ? (msg.tool_calls as RawCall[]) : [];
+ for (const call of calls) {
+ const name = typeof call.function?.name === "string" ? call.function.name : "tool";
+ let input: Record<string, unknown> = {};
+ try {
+ const parsed: unknown = JSON.parse(typeof call.function?.arguments === "string" ? call.function.arguments : "{}");
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) input = parsed as Record<string, unknown>;
+ } catch {
+ // malformed arguments still get a row, just without detail
+ }
+ if (name === "attempt_completion") {
+ if (typeof input.result === "string") appendText(t, input.result);
+ continue;
+ }
+ if (name === "todo_write") {
+ const todos = todosOf(input);
+ if (todos.length) t.todos = todos;
+ }
+ const label = labelFor(name);
+ const chip = chipFor(name, input);
+ const path = typeof input.path === "string" ? input.path : typeof input.file === "string" ? input.file : undefined;
+ const row: ToolRow = {
+ id: typeof call.id === "string" ? call.id : `${name}:${t.tools.length}`,
+ name: label,
+ icon: iconFor(name),
+ chip: chip === name ? "" : chip,
+ status: "ok",
+ detail: summarizeInput(name, input),
+ path,
+ };
+ t.tools = [...t.tools, row];
+ }
+ continue;
+ }
+ if (msg.role === "tool") {
+ const t = current();
+ const idx = t.tools.findIndex((row) => row.id === msg.tool_call_id);
+ if (idx < 0) continue;
+ const text = textOf(msg.content).trim();
+ const failed = /^(error|failed|denied)\b/i.test(text);
+ t.tools = t.tools.map((row, i) =>
+ i === idx
+ ? { ...row, status: failed ? "error" : row.status, detail: text ? [...row.detail, { text: firstLine(text) }] : row.detail }
+ : row,
+ );
+ }
+ }
+ flush();
+ return out;
+}
diff --git a/apps/native/package.json b/apps/native/package.json
index b4514e7a..f0569552 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -10,7 +10,7 @@
"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000",
"mock-serve": "node scripts/mock-serve.mjs",
"lint": "next lint",
- "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts"
+ "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts"
},
"dependencies": {
"glimm": "^0.3.0",