graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(native,tui): stream tools with the answer, not as a wall on top
Rach Pradhan0fb41c06d982
diff --git a/TUI/foldhdr.zig b/TUI/foldhdr.zigindex f5b83590..a4484dea 100644--- a/TUI/foldhdr.zig+++ b/TUI/foldhdr.zig@@ -32,7 +32,7 @@ pub const gutter_cols: usize = 2;// ── families ────────────────────────────────────────────────────────────────-pub const Family = enum { read, write, edit, bash, search, web, task, todo, mcp, other, mixed };+pub const Family = enum { read, write, edit, bash, search, web, task, todo, mcp, lookup, other, mixed };const Verb = struct {/// In flight.@@ -54,6 +54,7 @@ fn verbOf(f: Family) Verb {.edit => .{ .present = "Editing", .past = "Edited", .noun = "file" },.bash => .{ .present = "Running", .past = "Ran", .noun = "command", .solo_tool = true },.search => .{ .present = "Searching", .past = "Searched", .noun = "pattern" },+ .lookup => .{ .present = "Looking up", .past = "Looked up", .noun = "item" },.web => .{ .present = "Fetching", .past = "Fetched", .noun = "page" },.task => .{ .present = "Scouting", .past = "Scouted", .noun = "scout" },.todo => .{ .present = "Updating", .past = "Updated", .noun = "todo" },@@ -121,7 +122,8 @@ pub fn familyOf(name: []const u8) Family {if (eqAny(leaf, &.{ "webfetch", "web_fetch", "web_search", "fetch", "browse" })) return .web;if (eqAny(leaf, &.{ "task", "subagent", "workflow", "agent_output", "dispatch_agent" })) return .task;if (std.mem.startsWith(u8, leaf, "todo")) return .todo;- if (eqAny(leaf, &.{ "grep", "glob", "search", "find", "ls", "list_dir", "codedb" })) return .search;+ if (eqAny(leaf, &.{ "codedb" })) return .lookup;+ if (eqAny(leaf, &.{ "grep", "glob", "search", "find", "ls", "list_dir" })) return .search;if (has(leaf, "search") or has(leaf, "grep") or has(leaf, "glob") or has(leaf, "find")) return .search;if (has(leaf, "web")) return .web;if (isMcp(name)) return .mcp;@@ -271,6 +273,21 @@ test "a homogeneous run reads present-progressive live and past tense settled" {try testing.expectEqualStrings("Read 3 files", try phrase(a, oneRun(&m)));}+test "codedb is a lookup, not a search-for-patterns" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ var arena = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ try m.pushTool(.{ .name = "codedb", .detail = "context how auth works" });+ try testing.expectEqualStrings("Looking up 1 item\u{2026}", try phrase(a, oneRun(&m)));+ try m.pushTool(.{ .name = "codedb", .detail = "ok", .done = true });+ try m.pushTool(.{ .name = "codedb", .detail = "around Agent" });+ try m.pushTool(.{ .name = "codedb", .detail = "ok", .done = true });+ try testing.expectEqualStrings("Looked up 2 items", try phrase(a, oneRun(&m)));+}+test "a single call names its tool where that is how it reads" {var m: Model = undefined;m.setup(testing.allocator);@@ -345,6 +362,7 @@ test "familyOf reads the name, and an MCP leaf classifies like a first-party tootry testing.expectEqual(Family.bash, familyOf("bash"));try testing.expectEqual(Family.search, familyOf("grep"));try testing.expectEqual(Family.search, familyOf("glob"));+ try testing.expectEqual(Family.lookup, familyOf("codedb"));try testing.expectEqual(Family.search, familyOf("mcp__codedbpro__faster_search"));try testing.expectEqual(Family.read, familyOf("mcp__codedbpro__read"));try testing.expectEqual(Family.web, familyOf("webfetch"));diff --git a/TUI/layout_cache.zig b/TUI/layout_cache.zigindex 07f4362e..f824e73f 100644--- a/TUI/layout_cache.zig+++ b/TUI/layout_cache.zig@@ -108,6 +108,10 @@ pub fn ensure(m: *Model, width: usize) *Cache {w.users += 1;w.user_text = e.text;}+ if (e.kind == .pending and scrollback.liveHasBytes(m)) {+ i = end;+ continue;+ }w.place(i, end, e.kind == .pending, false);i = end;}@@ -202,7 +206,7 @@ fn liveText(m: *Model, a: std.mem.Allocator, start: usize, end: usize, width: usconst raw_bash = job.raw.len.load(.acquire) > 0;const src = if (raw_bash) &job.raw else &job.stream;const live = src.snapshot(a) orelse return "";- return theme_mod.paint(a, m.theme().muted, try scrollback.liveTail(m, a, live, raw_bash, width));+ return scrollback.liveAnswer(m, a, live, raw_bash, width, m.now_ms);}fn steerText(m: *Model, a: std.mem.Allocator) ![]const u8 {diff --git a/TUI/scrollback.zig b/TUI/scrollback.zigindex de366e41..7eb5436c 100644--- a/TUI/scrollback.zig+++ b/TUI/scrollback.zig@@ -27,6 +27,12 @@ pub fn render(self: *const Model, a: std.mem.Allocator, width: usize, now_ms: u6i = run.end;continue;}+ // Once tokens are on the wire the pending "Thinking" row is a second+ // spinner sitting on the answer. Skip it; liveAnswer() is the reply.+ if (e.kind == .pending and liveHasBytes(self)) {+ i += 1;+ continue;+ }if (!first) try out.append('\n');first = false;const selected = self.focus == .scrollback and i == self.selected;@@ -40,7 +46,7 @@ pub fn render(self: *const Model, a: std.mem.Allocator, width: usize, now_ms: u6if (src.snapshot(a)) |live| {if (!first) try out.append('\n');first = false;- try out.appendSlice(try theme_mod.paint(a, self.theme().muted, try liveTail(self, a, live, raw_bash, width)));+ try out.appendSlice(try liveAnswer(self, a, live, raw_bash, width, now_ms));}if (self.steer_queue.items.len > 0) {if (!first) try out.append('\n');@@ -67,6 +73,10 @@ pub fn indexAtVisual(self: *const Model, visual_row: usize, width: usize) ?usizei = run.end;continue;}+ if (self.history.items[i].kind == .pending and liveHasBytes(self)) {+ i += 1;+ continue;+ }const s = row(self, a, userNo(self, i), self.history.items[i], width, self.now_ms, false) catch "";const lines = lineCount(s);if (visual_row >= v and visual_row < v + lines) return i;@@ -100,6 +110,10 @@ pub fn visualOfIndex(self: *const Model, idx: usize, width: usize) ?usize {i = run.end;continue;}+ if (self.history.items[i].kind == .pending and liveHasBytes(self)) {+ i += 1;+ continue;+ }if (i == idx) return v;v += lineCount(row(self, a, userNo(self, i), self.history.items[i], width, self.now_ms, false) catch "");i += 1;@@ -126,6 +140,10 @@ pub fn stickyUserAbove(self: *const Model, top_line: usize, width: usize) ?[]coni = run.end;continue;}+ if (e.kind == .pending and liveHasBytes(self)) {+ i += 1;+ continue;+ }if (e.kind == .user and v < top_line) best = e.text;v += lineCount(row(self, a, userNo(self, i), e, width, self.now_ms, false) catch "");i += 1;@@ -339,13 +357,31 @@ pub fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {return @import("markdown.zig").sanitize(a, s) catch s;}+/// True once the engine has put tokens (or raw bash) on the wire. The+/// pending "Thinking" row is then redundant — liveAnswer is the reply.+pub fn liveHasBytes(self: *const Model) bool {+ const job = self.pending orelse return false;+ if (self.cancel_requested) return false;+ return job.stream.len.load(.acquire) > 0 or job.raw.len.load(.acquire) > 0;+}+/// Live prose uses the same renderer as a settled assistant row. Raw bash/// stays sanitized-only — those bytes are a terminal, not markdown.pub fn liveTail(self: *const Model, a: std.mem.Allocator, live: []const u8, raw_bash: bool, width: usize) ![]const u8 {const clean = strip(a, live);if (raw_bash) return tail(a, clean, width, 4);const painted = @import("markdown.zig").renderThemed(a, clean, self.theme(), width -| 4) catch clean;- return tail(a, painted, width, 8);+ return tail(a, painted, width, 48);+}++/// The growing answer: assistant chrome + themed markdown, not a muted+/// 8-line clip under Thinking. finishJob then swaps this for the settled row.+pub fn liveAnswer(self: *const Model, a: std.mem.Allocator, live: []const u8, raw_bash: bool, width: usize, now_ms: u64) ![]const u8 {+ const clean = strip(a, live);+ if (clean.len == 0) return "";+ if (raw_bash) return theme_mod.paint(a, self.theme().muted, try tail(a, clean, width, 4));+ const fake: app.Entry = .{ .kind = .assistant, .text = clean };+ return row(self, a, 0, fake, width, now_ms, false);}pub fn tail(a: std.mem.Allocator, s: []const u8, width: usize, max_lines: usize) ![]const u8 {diff --git a/apps/native/components/primitives/Markdown.tsx b/apps/native/components/primitives/Markdown.tsxindex 46ef46db..083562de 100644--- a/apps/native/components/primitives/Markdown.tsx+++ b/apps/native/components/primitives/Markdown.tsx@@ -82,7 +82,7 @@ type Block =| { 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: "list"; ordered: boolean; items: { text: string; indent: number; n?: number }[] }| { kind: "table"; header: string[]; rows: string[][] }| { kind: "hr" };@@ -156,11 +156,16 @@ export function parseMarkdown(src: string): Block[] {if (item) {flush();const ordered = item[3] !== undefined;- const items: { text: string; indent: number }[] = [];+ const items: { text: string; indent: number; n?: 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)) });+ if ((m[3] !== undefined) !== ordered) break;+ items.push({+ text: m[4],+ indent: Math.min(3, Math.floor(m[1].length / 2)),+ n: m[3] !== undefined ? Number(m[3]) : undefined,+ });i += 1;}blocks.push({ kind: "list", ordered, items });@@ -250,7 +255,7 @@ export default function Markdown({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" />+ <span className="stream-caret is-streaming ml-0.5 inline-block h-3 w-0.5 translate-y-0.5 rounded-full bg-ink" />) : null;switch (b.kind) {case "h":@@ -279,7 +284,7 @@ export default function Markdown({{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}.` : "•"}+ {b.ordered ? `${item.n ?? j + 1}.` : "•"}</span><span className="min-w-0">{inl(item.text)}</span></li>@@ -326,7 +331,7 @@ export default function Markdown({}})}{streaming && blocks.length === 0 && (- <span className="stream-caret inline-block h-3 w-0.5 translate-y-0.5 rounded-full bg-ink" />+ <span className="stream-caret is-streaming inline-block h-3 w-0.5 translate-y-0.5 rounded-full bg-ink" />)}</div>);diff --git a/apps/native/components/primitives/ThinkingState.tsx b/apps/native/components/primitives/ThinkingState.tsxindex 67f3e771..56a8f10f 100644--- a/apps/native/components/primitives/ThinkingState.tsx+++ b/apps/native/components/primitives/ThinkingState.tsx@@ -296,7 +296,7 @@ export default function ThinkingState({</>);const rowClass = "flex min-h-7 w-full items-center gap-2 rounded-[6px] px-1.5 py-0.5 text-left";- const key = live ? i : row.primary;+ const key = `${i}:${row.primary}`;const animation =i >= firstNewRow? { animation: `fade-up 320ms cubic-bezier(0.23,1,0.32,1) ${live ? 0 : i * 120}ms both` }diff --git a/apps/native/components/primitives/ToolChips.tsx b/apps/native/components/primitives/ToolChips.tsxindex 15ea4bbb..0522418a 100644--- a/apps/native/components/primitives/ToolChips.tsx+++ b/apps/native/components/primitives/ToolChips.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { createPortal } from "react-dom";/* ─────────────────────────────────────────────────────────@@ -130,6 +130,7 @@ export default function ToolChips({: DIFF_LINES;const [step, setStep] = useState(0);const [open, setOpen] = useState(true);+ const userToggled = useRef(false);/* tick once a second while any live row runs, so its timer counts up */const [, setClock] = useState(0);const anyRunning = live && rows.some((r) => "status" in r && r.status === "running");@@ -138,6 +139,15 @@ export default function ToolChips({const t = setInterval(() => setClock((c) => c + 1), 1000);return () => clearInterval(t);}, [anyRunning]);+ /* A batch of reads should not be a wall sitting on the answer. Expand+ * while something is running so the live call is visible; fold the rest+ * into the summary once they settle — unless the reader opened it. */+ useEffect(() => {+ if (!live || userToggled.current) return;+ if (anyRunning) setOpen(true);+ else if (rows.length > 1) setOpen(false);+ }, [live, anyRunning, rows.length]);+ const showHeader = !live || rows.length > 1;const [openRows, setOpenRows] = useState<Set<string>>(new Set());/* Rendered in a body portal so animated/translated reply wrappers cannot* redefine the fixed-position coordinate system. */@@ -170,20 +180,24 @@ export default function ToolChips({return () => clearTimeout(t);}, [step, total, live]);- const toggleRow = (label: string) =>+ const toggleRow = (id: string) =>setOpenRows((current) => {const next = new Set(current);- next.has(label) ? next.delete(label) : next.add(label);+ next.has(id) ? next.delete(id) : next.add(id);return next;});return (<div className={live ? "w-full pb-1" : "min-h-[220px] w-full max-w-80 pb-1"}>{/* collapsed run header */}+ {showHeader && (<buttontype="button"aria-expanded={open}- onClick={() => setOpen((current) => !current)}+ onClick={() => {+ userToggled.current = true;+ setOpen((current) => !current);+ }}className="-mx-1.5 flex w-fit items-center gap-1.5 rounded-control px-1.5 py-1 text-[12.5px] text-ink-2 transition-colors duration-100 hover:bg-hover-2"><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)" }}>@@ -192,35 +206,38 @@ export default function ToolChips({<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"}`);+ if (counts.read) parts.push(`Explored ${counts.read}`);+ if (counts.write) parts.push(`Edited ${counts.write}`);+ if (counts.run) parts.push(`Ran ${counts.run}`);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"}`;+ if (other > 0) parts.push(`${other} other`);+ const liveN = rows.filter((r) => "status" in r && r.status === "running").length;+ if (liveN) parts.push(liveN === 1 ? "running" : `${liveN} running`);+ return parts.join(" · ") || `${rows.length} steps`;})(): "4 tool calls, 2 messages"}</span></button>+ )}{/* tool call rows */}- <div className="grid transition-[grid-template-rows,opacity] duration-300" style={{ gridTemplateRows: open ? "1fr" : "0fr", opacity: open ? 1 : 0 }}>+ <div className="grid transition-[grid-template-rows,opacity] duration-300" style={{ gridTemplateRows: !showHeader || open ? "1fr" : "0fr", opacity: !showHeader || open ? 1 : 0 }}>{/* -mx-1 + px-1.5 keeps content at the same x while giving therow hover pills room inside this overflow-hidden clip box */}<div className="-mx-1 overflow-hidden px-1.5 pb-1"><div className="mt-1.5 flex flex-col gap-1">- {(live ? rows : rows.slice(0, step)).map((row) => {- const rowOpen = openRows.has(row.label);+ {(live ? rows : rows.slice(0, step)).map((row, i) => {+ const rowKey = "id" in row && row.id ? row.id : `${row.label}-${i}`;+ const rowOpen = openRows.has(rowKey);return (- <div key={"id" in row && row.id ? row.id : row.label} style={{ animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}>+ <div key={rowKey} style={live ? undefined : { animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}><buttontype="button"aria-expanded={rowOpen}- onClick={() => toggleRow(row.label)}+ onClick={() => toggleRow(rowKey)}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">@@ -245,26 +262,28 @@ export default function ToolChips({<path d="M6 9l6 6 6-6" /></svg></span>- <span className="shrink-0 text-[12.5px] font-medium text-ink">{row.label}</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="shrink-0 text-[11.5px] text-ink-3">{row.label}</span>+ <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}` : row.chip}+ className={`inline-flex h-5.5 min-w-0 max-w-fit flex-1 items-center truncate rounded-chip bg-field px-1.5+ text-[12px] text-ink shadow-hairline transition-colors duration-100 hover:bg-hover-2+ ${row.mono ? "font-mono" : ""} ${onOpenPath && "path" in row && row.path ? "cursor-pointer" : ""}`}+ >+ {row.chip}+ </span>+ </>) : (- <span className="min-w-0 flex-1" />+ <span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-ink">{row.label}</span>)}{"status" in row && (() => {const label =@@ -286,9 +305,9 @@ export default function ToolChips({><div className="min-h-0 overflow-hidden"><div className="mt-0.5 mb-1 ml-2 flex flex-col gap-0.5 border-l border-line py-0.5 pl-3.5">- {row.detail.map((line) => (+ {row.detail.map((line, lineIdx) => (<span- key={line.text}+ key={`${lineIdx}:${line.text}`}className={`truncate text-[11.5px] leading-[1.6] ${row.detailMono ? "font-mono" : ""} ${line.tone === "add" ? "text-green" : "text-ink-2"}`}>{line.text}diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex 25f4404e..de8d2a7e 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useRef, useState, type CSSProperties } from "react";+import { useEffect, useRef, useState, type CSSProperties, type RefObject } from "react";import Markdown from "@/components/primitives/Markdown";import PromptBar, { type PromptModel } from "@/components/primitives/PromptBar";import SidebarNav from "@/components/primitives/SidebarNav";@@ -23,7 +23,7 @@ import {prompt,type Health,} from "@/lib/acp-client";-import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";+import { applyAcpUpdate, emptyTurn, finishAcpTurn, turnBlocks, type AssistantTurn } from "@/lib/acp";import { dateGroup, listSessions, loadSession, relativeTime, type StoredSession } from "@/lib/sessions";const NAME = "there";@@ -40,7 +40,9 @@ function greeting(): string {* readable base rate with gentle backlog catch-up (capped so a one-shot* final answer still visibly types out), and the drain keeps playing after* the turn's result lands — done-state chrome waits for the last word.- * Mounted mid-history it starts caught-up, so old messages never replay. */+ * Mounted mid-history it starts caught-up, so old messages never replay.+ * Catch-up lands on whitespace so markdown chips/lists don't reflow every+ * mid-token character — that wrap-jitter stacked with scrollIntoView. */function useSmoothStream(target: string): string {const [shown, setShown] = useState(target);const shownRef = useRef(target);@@ -54,13 +56,21 @@ function useSmoothStream(target: string): string {let raf = 0;let last = performance.now();const tick = (now: number) => {- const dt = Math.min(now - last, 100);+ const dt = Math.min(now - last, 80);last = now;- const behind = target.length - shownRef.current.length;+ const have = shownRef.current.length;+ const behind = target.length - have;if (behind <= 0) return;- const rate = Math.min(160 + behind * 1.2, 2400); // chars/second- const step = Math.max(1, Math.round((rate * dt) / 1000));- shownRef.current = target.slice(0, shownRef.current.length + step);+ const rate = Math.min(180 + behind * 1.4, 2800);+ let next = have + Math.max(1, Math.round((rate * dt) / 1000));+ if (next < target.length) {+ const rest = target.slice(next, next + 24);+ const cut = rest.search(/[\s\n]/);+ if (cut > 0) next += cut + 1;+ } else {+ next = target.length;+ }+ shownRef.current = target.slice(0, next);setShown(shownRef.current);if (shownRef.current.length < target.length) raf = requestAnimationFrame(tick);};@@ -70,6 +80,15 @@ function useSmoothStream(target: string): string {return shown;}+/** Pin the thread scroller to its tail without scrollIntoView. WKWebView+ * treats block:end on a tall article as a viewport realignment every frame+ * — the whole reply judders while the typewriter runs. */+function pinScrollerTail(el: HTMLElement | null): void {+ if (!el) return;+ const fromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;+ if (fromBottom < 240) el.scrollTop = el.scrollHeight;+}+const HOME_REVEAL = {offsetY: 23,blur: 17,@@ -105,21 +124,26 @@ function AssistantBody({turn,onOpenPath,onReview,+ scroller,}: {turn: AssistantTurn;onOpenPath?: (path: string) => void;/** Open the workspace changes review (the Codex "Changed N files" bar). */onReview?: () => void;+ scroller?: RefObject<HTMLDivElement | null>;}) {const thinking = turn.status === "thinking";- const smoothText = useSmoothStream(turn.text);- const draining = smoothText.length < turn.text.length;- // Follow the typewriter tail — the parent's scroll effect tracks the wire- // text, which goes quiet while the reveal is still playing out.- const articleRef = useRef<HTMLElement>(null);+ const blocks = turnBlocks(turn.text, turn.tools);+ const lastText = [...blocks].reverse().find((b) => b.kind === "text");+ const lastTextBody = lastText?.kind === "text" ? lastText.text : "";+ const smoothText = useSmoothStream(lastTextBody);+ const draining = smoothText.length < lastTextBody.length;+ // Follow the typewriter tail — the parent's pin tracks the wire text,+ // which goes quiet while the reveal is still playing out. Pin the+ // overflow scroller directly; do not scrollIntoView (WKWebView jitter).useEffect(() => {- if (draining) articleRef.current?.scrollIntoView({ block: "end", behavior: "auto" });- }, [smoothText, draining]);+ if (draining) pinScrollerTail(scroller?.current ?? null);+ }, [smoothText, draining, scroller]);// "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());@@ -141,22 +165,30 @@ function AssistantBody({.filter(Boolean).map((primary) => ({ primary })): [];- const toolRows = turn.tools.map((tool) => ({- id: tool.id,- icon: tool.icon,- label: tool.name,- chip: tool.chip,- 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,- startedAt: tool.startedAt,- elapsedMs: tool.elapsedMs,- }));+ const toChipRows = (tools: typeof turn.tools) =>+ tools.map((tool) => ({+ id: tool.id,+ icon: tool.icon,+ label: tool.name,+ chip: tool.chip,+ 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,+ startedAt: tool.startedAt,+ elapsedMs: tool.elapsedMs,+ }));++ const lastTextIndex = blocks.reduce((acc, b, i) => (b.kind === "text" ? i : acc), -1);+ const lastBlock = blocks[blocks.length - 1];+ const waitingOnTools =+ turn.status === "streaming" &&+ !lastTextBody &&+ (lastBlock?.kind === "tools" || blocks.length === 0);return (- <article ref={articleRef} className="min-w-0" style={{ animation: "fade-up 450ms cubic-bezier(0.23,1,0.32,1) both" }}>+ <article className="min-w-0" style={{ overflowAnchor: "none", animation: "fade-in 280ms ease both" }}>{/* Keep the header once the model has actually thought (streamed* reasoning, or a think long enough to notice): unmounting it when the* think ends made the answer jump up into the space it left. */}@@ -169,15 +201,26 @@ function AssistantBody({working={thinking}/>)}- {toolRows.length > 0 && (- <div className="mt-4">- <ToolChips rows={toolRows} diffs={turn.diffs} onOpenPath={onOpenPath} />- </div>+ {blocks.map((block, i) =>+ block.kind === "tools" ? (+ <div key={`tools-${block.tools[0]?.id ?? i}`} className="mt-3">+ <ToolChips+ rows={toChipRows(block.tools)}+ diffs={i === blocks.length - 1 || (i === blocks.length - 2 && lastBlock?.kind === "text") ? turn.diffs : []}+ onOpenPath={onOpenPath}+ />+ </div>+ ) : (+ <div key={`text-${i}`} className="mt-3 max-w-[630px]">+ <Markdown+ text={i === lastTextIndex ? smoothText : block.text}+ streaming={i === lastTextIndex && (draining || turn.status === "streaming" || turn.status === "thinking")}+ onOpenPath={onOpenPath}+ />+ </div>+ ),)}- {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. */+ {waitingOnTools && (<div className="mt-4"><spanclassName="bg-clip-text text-[13px] font-medium whitespace-nowrap text-transparent"@@ -190,16 +233,6 @@ function AssistantBody({{turn.tools.some((tool) => tool.status === "running") ? "Running tools…" : "Writing…"}</span></div>- ) : (- turn.text && (- <div className="mt-4 max-w-[630px]">- <Markdown- text={smoothText}- streaming={draining || 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>@@ -626,14 +659,11 @@ export default function GraffHarness() {useEffect(() => {if (!active) return;const el = scrollRef.current;- if (el) el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });+ if (el) el.scrollTop = el.scrollHeight;}, [messageCount, activeId, active]);useEffect(() => {if (!active) return;- const el = scrollRef.current;- if (!el) return;- const fromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;- if (fromBottom < 160) el.scrollTop = el.scrollHeight;+ pinScrollerTail(scrollRef.current);}, [active, lastAssistant?.turn.text, lastAssistant?.turn.reasoning, lastAssistant?.turn.tools.length]);// The sidebar is graff's session directory, newest first, bucketed by day.@@ -736,7 +766,7 @@ export default function GraffHarness() {message.role === "user" ? (<UserBubble key={message.id} text={message.text} />) : (- <AssistantBody key={message.id} turn={message.turn} onOpenPath={openPath} onReview={openChanges} />+ <AssistantBody key={message.id} turn={message.turn} onOpenPath={openPath} onReview={openChanges} scroller={scrollRef} />),)}</div>diff --git a/apps/native/lib/acp.test.ts b/apps/native/lib/acp.test.tsindex ec5396f1..cb71ec53 100644--- a/apps/native/lib/acp.test.ts+++ b/apps/native/lib/acp.test.ts@@ -1,6 +1,6 @@import { describe, it } from "node:test";import assert from "node:assert/strict";-import { applyAcpUpdate, emptyTurn, finishAcpTurn, parseRpcLine } from "./acp.ts";+import { applyAcpUpdate, emptyTurn, finishAcpTurn, parseRpcLine, turnBlocks } from "./acp.ts";describe("parseRpcLine", () => {it("skips blanks and noise", () => {@@ -88,6 +88,34 @@ describe("applyAcpUpdate", () => {assert.equal(turn.todos[1]?.status, "in_progress");});+ it("interleaves tools at the text cursor they landed on", () => {+ let turn = emptyTurn();+ turn = applyAcpUpdate(turn, {+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text: "Hello" },+ });+ turn = applyAcpUpdate(turn, {+ sessionUpdate: "tool_call",+ toolCallId: "c1",+ title: "codedb",+ kind: "read",+ status: "pending",+ rawInput: { command: "context how does auth work" },+ });+ assert.equal(turn.tools[0]?.atChars, 5);+ assert.equal(turn.tools[0]?.name, "Codedb");+ assert.equal(turn.tools[0]?.chip, "context how does auth work");+ turn = applyAcpUpdate(turn, {+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text: " more" },+ });+ const blocks = turnBlocks(turn.text, turn.tools);+ assert.equal(blocks[0]?.kind, "text");+ if (blocks[0]?.kind === "text") assert.equal(blocks[0].text, "Hello");+ assert.equal(blocks[1]?.kind, "tools");+ assert.equal(blocks[2]?.kind, "text");+ });+it("finishAcpTurn settles running chips", () => {let turn = emptyTurn();turn = applyAcpUpdate(turn, {diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.tsindex 705a6695..e43b8411 100644--- a/apps/native/lib/acp.ts+++ b/apps/native/lib/acp.ts@@ -65,6 +65,10 @@ function humanize(id: string): string {}function labelForKind(kind: string | undefined, title: string): string {+ const mcp = mcpParts(title);+ if (mcp) return humanize(mcp.tool);+ // Bare engine tools (codedb, todo_write…) beat a generic kind of "read".+ if (/^[a-z][a-z0-9_]*$/.test(title)) return humanize(title);if (kind === "execute") return "Run";if (kind === "edit") return "Edit";if (kind === "delete") return "Delete";@@ -73,10 +77,6 @@ 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;}@@ -177,18 +177,21 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId: (prev?.detail ?? []);const mcp = mcpParts(title);const label = labelForKind(kind, title);+ const command = typeof rawInput.command === "string" ? firstLine(rawInput.command) : undefined;// 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);+ // no chip at all when it would just echo the label. codedb's query lives+ // in `command` — without it every call rendered as a blank "Read".+ const chipRaw = path ?? command ?? (mcp ? mcp.server : title);const row: ToolRow = {id,name: label,icon: iconForKind(kind, title),- chip: chip === label || humanize(chip) === label ? "" : chip,+ chip: chipRaw === label || humanize(chipRaw) === label ? "" : chipRaw,status,detail,path,startedAt: prev?.startedAt ?? Date.now(),+ atChars: prev?.atChars ?? turn.text.length,};const tools = turn.tools.slice();const merged: ToolRow = idx >= 0@@ -223,6 +226,34 @@ export function finishAcpTurn(turn: AssistantTurn): AssistantTurn {};}+export type TurnBlock = { kind: "text"; text: string } | { kind: "tools"; tools: ToolRow[] };++/** Split a turn into the order the user should see it: text, then the tools+ * that landed at that cursor, then the next text. Tools without `atChars`+ * (old sessions) stay in a single group at the top. */+export function turnBlocks(text: string, tools: ToolRow[]): TurnBlock[] {+ if (tools.length === 0) return text ? [{ kind: "text", text }] : [];+ const blocks: TurnBlock[] = [];+ let cursor = 0;+ let i = 0;+ while (i < tools.length) {+ const mark = tools[i].atChars ?? 0;+ const at = Math.min(Math.max(mark, 0), text.length);+ if (at > cursor) {+ blocks.push({ kind: "text", text: text.slice(cursor, at) });+ cursor = at;+ }+ const group: ToolRow[] = [];+ while (i < tools.length && (tools[i].atChars ?? 0) === mark) {+ group.push(tools[i]);+ i += 1;+ }+ blocks.push({ kind: "tools", tools: group });+ }+ if (cursor < text.length) blocks.push({ kind: "text", text: text.slice(cursor) });+ return blocks;+}+export function applyAcpUpdate(turn: AssistantTurn, update: AcpUpdate): AssistantTurn {switch (update.sessionUpdate) {case "agent_thought_chunk": {diff --git a/apps/native/lib/graff-events.ts b/apps/native/lib/graff-events.tsindex 1363660e..4b9d9c57 100644--- a/apps/native/lib/graff-events.ts+++ b/apps/native/lib/graff-events.ts@@ -53,6 +53,8 @@ export type ToolRow = {/** Wall-clock bracket, measured client-side — rows tick while running. */startedAt?: number;elapsedMs?: number;+ /** `turn.text.length` when this call started — where it sits in the stream. */+ atChars?: number;};export type DiffChip = {@@ -145,6 +147,7 @@ function upsertTool(turn: AssistantTurn, name: string, input: Record<string, unkstatus: "running",detail: summarizeInput(name, input),path: typeof input.path === "string" ? input.path : undefined,+ atChars: turn.text.length,};return { ...turn, tools: [...turn.tools, row], status: turn.status === "ask" ? "ask" : "streaming" };}