Skip to content

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

Python

fix(native): no jitter per ACP chunk, and ArrowUp recalls prompts

justrach40e1e3ecfb7e
diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsx
index 4305cf86..3ae00b63 100644
--- a/apps/native/components/primitives/PromptBar.tsx
+++ b/apps/native/components/primitives/PromptBar.tsx
@@ -2,6 +2,7 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { createShader, playSweep, accentChain, ACCENTS } from "glimm";
+import { entryAt, historyKeyIntent, stepHistory } from "@/lib/prompt-history";
/* The built-in "prism" palette is only cyan→indigo→magenta, so a sweep
* reads as blue/purple. Build a true full-spectrum rainbow instead. */
@@ -157,6 +158,7 @@ export default function PromptBar({
disabled,
busy = false,
onStop,
+ history,
}: {
variant?: string;
/** the self-running walkthrough; turn off when embedding in a real surface */
@@ -172,10 +174,18 @@ export default function PromptBar({
/** A turn is running: the send arrow morphs into a stop square. */
busy?: boolean;
onStop?: () => void;
+ /** Earlier prompts, oldest first. ArrowUp on the first line of the draft
+ * walks back through them like a shell; ArrowDown walks forward again. */
+ history?: readonly string[];
}) {
const pill = variant === "Pill";
const catalog = models && models.length > 0 ? models : MODELS;
const [draft, setDraft] = useState("");
+ /* Recall cursor: -1 is the live draft. Whatever was being typed is kept
+ * aside so ArrowDown past the newest entry hands it back untouched. */
+ const [historyIndex, setHistoryIndex] = useState(-1);
+ const stashRef = useRef("");
+ const caretToEndRef = useRef(false);
const [dismissed, setDismissed] = useState(false);
const [plusOpen, setPlusOpen] = useState(false);
const [modelOpen, setModelOpen] = useState(false);
@@ -405,6 +415,13 @@ export default function PromptBar({
input.style.overflowY = contentHeight > maxHeight ? "auto" : "hidden";
}, [draft, expanded]);
+ /* A recalled prompt lands with the caret at its end, ready to edit or send. */
+ useLayoutEffect(() => {
+ if (!caretToEndRef.current) return;
+ caretToEndRef.current = false;
+ inputRef.current?.setSelectionRange(draft.length, draft.length);
+ }, [draft]);
+
/* clicking anywhere outside the composer closes the open menus */
useEffect(() => {
if (!modelOpen && !plusOpen) return;
@@ -444,9 +461,29 @@ export default function PromptBar({
onSend?.(draft.trim());
setDraft("");
setAttachments([]);
+ setHistoryIndex(-1);
+ stashRef.current = "";
closeMenus();
};
+ /* Shell-style recall. Only from the draft's first line (up) or last line
+ * (down) — in the middle of a multi-line draft the arrows keep moving the
+ * caret — and never while the @ / model menus own the arrow keys. */
+ const recall = (event: React.KeyboardEvent<HTMLTextAreaElement>): boolean => {
+ if (menu || modelOpen || !history || history.length === 0) return false;
+ const caret = event.currentTarget.selectionStart ?? draft.length;
+ const intent = historyKeyIntent(draft, caret, event.key);
+ if (!intent || (intent === "down" && historyIndex < 0)) return false;
+ event.preventDefault();
+ const next = stepHistory(history.length, historyIndex, intent);
+ if (next === historyIndex) return true;
+ if (historyIndex < 0) stashRef.current = draft;
+ setHistoryIndex(next);
+ setDraft(next < 0 ? stashRef.current : (entryAt(history, next) ?? ""));
+ caretToEndRef.current = true;
+ return true;
+ };
+
return (
<div
data-promptbar
@@ -704,6 +741,7 @@ export default function PromptBar({
return;
}
}
+ if (recall(event)) return;
if (event.key === "Escape") {
setDismissed(true);
closeMenus();
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index 25f4404e..88890dda 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 { memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
import Markdown from "@/components/primitives/Markdown";
import PromptBar, { type PromptModel } from "@/components/primitives/PromptBar";
import SidebarNav from "@/components/primitives/SidebarNav";
@@ -25,6 +25,7 @@ import {
} from "@/lib/acp-client";
import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";
import { dateGroup, listSessions, loadSession, relativeTime, type StoredSession } from "@/lib/sessions";
+import { loadHistory, mergeHistory, pushHistory, saveHistory } from "@/lib/prompt-history";
const NAME = "there";
@@ -88,7 +89,10 @@ function homeRevealStyle(visible: boolean): CSSProperties {
};
}
-function UserBubble({ text }: { text: string }) {
+/* Rows are memoized: a chunk landing in the live turn replaces that one
+ * message's `turn`, and every other row keeps its props — without memo the
+ * whole thread re-rendered (and re-parsed its markdown) per ACP update. */
+const UserBubble = memo(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
@@ -99,9 +103,9 @@ function UserBubble({ text }: { text: string }) {
</div>
</div>
);
-}
+});
-function AssistantBody({
+const AssistantBody = memo(function AssistantBody({
turn,
onOpenPath,
onReview,
@@ -114,12 +118,6 @@ function AssistantBody({
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);
- useEffect(() => {
- if (draining) articleRef.current?.scrollIntoView({ block: "end", behavior: "auto" });
- }, [smoothText, draining]);
// "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());
@@ -156,7 +154,7 @@ function AssistantBody({
}));
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={{ animation: "fade-up 450ms cubic-bezier(0.23,1,0.32,1) 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. */}
@@ -238,7 +236,7 @@ function AssistantBody({
)}
</article>
);
-}
+});
type Msg =
| { id: number; role: "user"; text: string }
@@ -252,6 +250,32 @@ function newPageToken(): string {
return Math.random().toString(36).slice(2, 10);
}
+/** One React commit per animation frame, however many ACP chunks land in
+ * it. The stream delivers `agent_message_chunk`s a few characters at a time
+ * and a state update per chunk was a full render each — the thread jittered
+ * under its own re-renders. Only the newest turn matters; the rest is
+ * superseded before anyone could have seen it. */
+function frameCoalescer<T>(apply: (value: T) => void) {
+ let latest: T | undefined;
+ let frame = 0;
+ const flush = () => {
+ frame = 0;
+ if (latest !== undefined) apply(latest);
+ };
+ return {
+ push(value: T) {
+ latest = value;
+ if (!frame) frame = requestAnimationFrame(flush);
+ },
+ /** Drop whatever is queued; the caller commits the final value itself. */
+ cancel() {
+ if (frame) cancelAnimationFrame(frame);
+ frame = 0;
+ latest = undefined;
+ },
+ };
+}
+
/** 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. */
@@ -267,6 +291,7 @@ function EmptyState({
models,
modelKey,
onModelChange,
+ history,
}: {
onSend: (text: string) => void;
health: Health | null;
@@ -275,6 +300,7 @@ function EmptyState({
models: PromptModel[];
modelKey?: string;
onModelChange: (key: string) => void;
+ history: readonly string[];
}) {
const shown = [0, 1, 2].map((i) => STARTER_PROMPTS[(offset + i) % STARTER_PROMPTS.length]);
const [stage, setStage] = useState(0);
@@ -309,6 +335,7 @@ function EmptyState({
onModelChange={onModelChange}
onSend={onSend}
disabled={health !== null && !health.ok}
+ history={history}
/>
{health && !health.ok && (
<p className="mt-3 text-[12.5px] text-orange">
@@ -372,6 +399,12 @@ export default function GraffHarness() {
const [filesOpen, setFilesOpen] = useState(false);
const [fileRequest, setFileRequest] = useState<{ path: string; n: number; changes?: boolean } | null>(null);
const fileReqRef = useRef(0);
+ // Shell-style prompt recall (ArrowUp in the composer), kept per browser so
+ // a new tab or a reload still has the last prompts under the cursor.
+ const [history, setHistory] = useState<string[]>([]);
+ useEffect(() => {
+ setHistory(loadHistory(window.localStorage));
+ }, []);
const chatIdRef = useRef(1);
const msgIdRef = useRef(0);
const scrollRef = useRef<HTMLDivElement>(null);
@@ -393,6 +426,12 @@ export default function GraffHarness() {
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");
+ // A resumed session's prompts came from its file, not this browser; fold
+ // them in so ArrowUp walks the conversation on screen first.
+ const composerHistory = useMemo(
+ () => mergeHistory(history, chatThread.messages.flatMap((m) => (m.role === "user" ? [m.text] : []))),
+ [history, chatThread.messages],
+ );
const adoptCatalog = async (chatId: number) => {
// What did the agent actually resolve? The picker should show graff's
@@ -471,15 +510,16 @@ export default function GraffHarness() {
}
};
- const openPath = (path: string) => {
+ // Stable callbacks: they are props of every memoized row.
+ const openPath = useCallback((path: string) => {
setFilesOpen(true);
setFileRequest({ path, n: (fileReqRef.current += 1) });
- };
+ }, []);
- const openChanges = () => {
+ const openChanges = useCallback(() => {
setFilesOpen(true);
setFileRequest({ path: "", n: (fileReqRef.current += 1), changes: true });
- };
+ }, []);
const changeModel = (key: string) => {
// New tabs inherit the pick; the active tab respawns its agent with it
@@ -528,18 +568,26 @@ export default function GraffHarness() {
),
);
setBusyFor(chatId, true);
+ setHistory((current) => {
+ const next = pushHistory(current, trimmed);
+ saveHistory(window.localStorage, next);
+ return next;
+ });
let turn: AssistantTurn = { ...emptyTurn(), model: chatModel };
const startedAt = Date.now();
+ const frames = frameCoalescer<AssistantTurn>((next) => patchAssistant(chatId, asstId, next));
try {
const id = await requireSession(chatId);
for await (const update of prompt(handleOf(chatId), id, trimmed)) {
turn = applyAcpUpdate(turn, update);
if (turn.thoughtMs === undefined && turn.status !== "thinking") turn = { ...turn, thoughtMs: Date.now() - startedAt };
- patchAssistant(chatId, asstId, turn);
+ frames.push(turn);
}
+ frames.cancel();
turn = finishAcpTurn(turn);
patchAssistant(chatId, asstId, turn);
} catch (err) {
+ frames.cancel();
turn = { ...turn, error: err instanceof Error ? err.message : String(err), status: "error" };
patchAssistant(chatId, asstId, turn);
} finally {
@@ -618,23 +666,49 @@ export default function GraffHarness() {
void openStored(id);
};
- // A new message glides the thread to the bottom; streaming growth (reasoning,
- // text, tool rows) follows instantly and only while the reader is already at
- // the tail. Re-issuing a *smooth* scroll on every chunk restarted the scroll
- // animation each token — the whole thread juddered while the model thought.
+ // A new message glides the thread to the bottom. After that the tail is
+ // followed by a ResizeObserver on the thread body: every growth — a token,
+ // a tool row, a typewriter frame — pins scrollTop instantly, so there is
+ // no smooth scroll to restart per chunk (that restart was the judder), and
+ // only while the reader is at the tail. Scrolling up to read earlier
+ // history releases the pin until they come back down, so a streaming turn
+ // never yanks the view away from them.
const messageCount = chatThread.messages.length;
+ const bodyRef = useRef<HTMLDivElement>(null);
+ const stuckRef = useRef(true);
+ const glideUntilRef = useRef(0);
useEffect(() => {
- if (!active) return;
const el = scrollRef.current;
- if (el) el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
- }, [messageCount, activeId, active]);
+ const body = bodyRef.current;
+ if (!active || !el || !body) return;
+ const onScroll = () => {
+ const fromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
+ if (fromBottom < 48) {
+ stuckRef.current = true;
+ glideUntilRef.current = 0;
+ } else if (performance.now() >= glideUntilRef.current) {
+ // Positions mid-glide are the animation's, not the reader's.
+ stuckRef.current = false;
+ }
+ };
+ el.addEventListener("scroll", onScroll, { passive: true });
+ const observer = new ResizeObserver(() => {
+ if (stuckRef.current && performance.now() >= glideUntilRef.current) el.scrollTop = el.scrollHeight;
+ });
+ observer.observe(body);
+ return () => {
+ el.removeEventListener("scroll", onScroll);
+ observer.disconnect();
+ };
+ }, [active, activeId]);
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;
- }, [active, lastAssistant?.turn.text, lastAssistant?.turn.reasoning, lastAssistant?.turn.tools.length]);
+ stuckRef.current = true;
+ glideUntilRef.current = performance.now() + 900;
+ el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
+ }, [messageCount, activeId, active]);
// The sidebar is graff's session directory, newest first, bucketed by day.
const now = Date.now();
@@ -731,7 +805,7 @@ export default function GraffHarness() {
{active ? (
<div className="flex min-h-0 flex-1 flex-col">
<div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
- <div className="mx-auto flex w-full max-w-[720px] flex-col gap-8 px-4 py-8 sm:px-8">
+ <div ref={bodyRef} className="mx-auto flex w-full max-w-[720px] flex-col gap-8 px-4 py-8 sm:px-8">
{chatThread.messages.map((message) =>
message.role === "user" ? (
<UserBubble key={message.id} text={message.text} />
@@ -752,6 +826,7 @@ export default function GraffHarness() {
onModelChange={changeModel}
onSend={send}
disabled={busy}
+ history={composerHistory}
busy={busy}
onStop={() => {
const live = sessionsRef.current.get(chatThread.id);
@@ -766,6 +841,7 @@ export default function GraffHarness() {
<EmptyState
onSend={send}
health={health}
+ history={composerHistory}
offset={offset}
shuffle={() => setOffset((current) => (current + 3) % STARTER_PROMPTS.length)}
models={models}
diff --git a/apps/native/lib/prompt-history.test.ts b/apps/native/lib/prompt-history.test.ts
new file mode 100644
index 00000000..a9f0a9e6
--- /dev/null
+++ b/apps/native/lib/prompt-history.test.ts
@@ -0,0 +1,83 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ HISTORY_KEY,
+ entryAt,
+ historyKeyIntent,
+ loadHistory,
+ mergeHistory,
+ pushHistory,
+ saveHistory,
+ stepHistory,
+} from "./prompt-history.ts";
+
+test("pushHistory appends, moves a repeat to the newest slot, and caps from the old end", () => {
+ assert.deepEqual(pushHistory([], " hi "), ["hi"]);
+ assert.deepEqual(pushHistory(["a", "b"], "a"), ["b", "a"]);
+ assert.deepEqual(pushHistory(["a", "b"], "b"), ["a", "b"]);
+ assert.deepEqual(pushHistory(["a", "b"], " "), ["a", "b"]);
+ assert.deepEqual(pushHistory(["a", "b", "c"], "d", 3), ["b", "c", "d"]);
+});
+
+test("mergeHistory keeps each prompt once at its most recent position", () => {
+ assert.deepEqual(mergeHistory(["old", "x", "y"], ["x", "z"]), ["old", "y", "x", "z"]);
+ assert.deepEqual(mergeHistory([], []), []);
+ assert.deepEqual(mergeHistory(["a", " ", "a"], []), ["a"]);
+});
+
+test("stepHistory and entryAt walk newest-first and clamp at both ends", () => {
+ const list = ["first", "second", "third"];
+ let i = -1;
+ i = stepHistory(list.length, i, "up");
+ assert.equal(entryAt(list, i), "third");
+ i = stepHistory(list.length, i, "up");
+ assert.equal(entryAt(list, i), "second");
+ i = stepHistory(list.length, i, "up");
+ i = stepHistory(list.length, i, "up");
+ assert.equal(i, 2);
+ assert.equal(entryAt(list, i), "first");
+ i = stepHistory(list.length, i, "down");
+ i = stepHistory(list.length, i, "down");
+ i = stepHistory(list.length, i, "down");
+ assert.equal(i, -1);
+ assert.equal(entryAt(list, i), null);
+ assert.equal(stepHistory(0, -1, "up"), -1);
+});
+
+test("historyKeyIntent only fires from the first line (up) or last line (down)", () => {
+ assert.equal(historyKeyIntent("", 0, "ArrowUp"), "up");
+ assert.equal(historyKeyIntent("one line", 3, "ArrowUp"), "up");
+ assert.equal(historyKeyIntent("one line", 3, "ArrowDown"), "down");
+ assert.equal(historyKeyIntent("two\nlines", 6, "ArrowUp"), null);
+ assert.equal(historyKeyIntent("two\nlines", 6, "ArrowDown"), "down");
+ assert.equal(historyKeyIntent("two\nlines", 1, "ArrowDown"), null);
+ assert.equal(historyKeyIntent("two\nlines", 1, "ArrowUp"), "up");
+ assert.equal(historyKeyIntent("x", 1, "Enter"), null);
+});
+
+test("loadHistory and saveHistory round-trip through a storage-like object and tolerate garbage", () => {
+ const store = new Map<string, string>();
+ const storage = {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => void store.set(key, value),
+ };
+ saveHistory(storage, ["a", "b"]);
+ assert.deepEqual(loadHistory(storage), ["a", "b"]);
+ assert.equal(store.has(HISTORY_KEY), true);
+ store.set(HISTORY_KEY, "not json");
+ assert.deepEqual(loadHistory(storage), []);
+ store.set(HISTORY_KEY, JSON.stringify(["ok", 7, null]));
+ assert.deepEqual(loadHistory(storage), ["ok"]);
+ assert.deepEqual(loadHistory(null), []);
+ assert.doesNotThrow(() => saveHistory(null, ["x"]));
+ assert.doesNotThrow(() =>
+ saveHistory(
+ {
+ setItem: () => {
+ throw new Error("quota");
+ },
+ },
+ ["x"],
+ ),
+ );
+});
diff --git a/apps/native/lib/prompt-history.ts b/apps/native/lib/prompt-history.ts
new file mode 100644
index 00000000..19edf846
--- /dev/null
+++ b/apps/native/lib/prompt-history.ts
@@ -0,0 +1,75 @@
+/** Composer prompt history: ArrowUp / ArrowDown in the prompt bar recall
+ * earlier prompts the way a shell does. Persisted per browser so a fresh tab
+ * (or a reload) still has yesterday's prompts under the cursor. Pure helpers
+ * live here so the key rules are testable without a DOM. */
+
+export const HISTORY_KEY = "graff.native.prompt-history";
+export const HISTORY_MAX = 200;
+
+/** Append `text` as the newest entry. A prompt already in the list moves to
+ * the newest position instead of repeating — stepping through five copies of
+ * "continue" is noise — and the list is capped from the oldest end. */
+export function pushHistory(list: readonly string[], text: string, max = HISTORY_MAX): string[] {
+ const t = text.trim();
+ if (!t) return [...list];
+ const next = [...list.filter((entry) => entry !== t), t];
+ return next.length > max ? next.slice(next.length - max) : next;
+}
+
+/** Persisted history plus the open chat's own prompts (a resumed session's
+ * transcript is not in this browser's storage), newest last, each prompt once
+ * at its most recent position. */
+export function mergeHistory(persisted: readonly string[], chatPrompts: readonly string[]): string[] {
+ const all = [...persisted, ...chatPrompts];
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (let i = all.length - 1; i >= 0; i -= 1) {
+ const t = all[i].trim();
+ if (!t || seen.has(t)) continue;
+ seen.add(t);
+ out.push(t);
+ }
+ return out.reverse();
+}
+
+/** History cursor: -1 is the live draft, 0 the newest prompt, and so on. */
+export function stepHistory(length: number, index: number, dir: "up" | "down"): number {
+ if (dir === "up") return Math.min(length - 1, index + 1);
+ return Math.max(-1, index - 1);
+}
+
+export function entryAt(list: readonly string[], index: number): string | null {
+ if (index < 0 || index >= list.length) return null;
+ return list[list.length - 1 - index];
+}
+
+/** ArrowUp recalls history only from the first line of the draft (or an
+ * empty one); ArrowDown steps forward only from the last line. Anywhere else
+ * the keys move the caret like they do in any textarea. */
+export function historyKeyIntent(draft: string, caret: number, key: string): "up" | "down" | null {
+ if (key === "ArrowUp") return draft.slice(0, caret).includes("\n") ? null : "up";
+ if (key === "ArrowDown") return draft.slice(caret).includes("\n") ? null : "down";
+ return null;
+}
+
+type ReadStore = Pick<Storage, "getItem">;
+type WriteStore = Pick<Storage, "setItem">;
+
+export function loadHistory(storage: ReadStore | null | undefined): string[] {
+ try {
+ const raw = storage?.getItem(HISTORY_KEY);
+ if (!raw) return [];
+ const parsed: unknown = JSON.parse(raw);
+ return Array.isArray(parsed) ? parsed.filter((entry): entry is string => typeof entry === "string") : [];
+ } catch {
+ return [];
+ }
+}
+
+export function saveHistory(storage: WriteStore | null | undefined, list: readonly string[]): void {
+ try {
+ storage?.setItem(HISTORY_KEY, JSON.stringify(list.slice(-HISTORY_MAX)));
+ } catch {
+ // Private mode or a full quota: history is a convenience, never a failure.
+ }
+}
diff --git a/apps/native/package.json b/apps/native/package.json
index 9b139fa4..53d05f11 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -10,7 +10,7 @@
"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000",
"mock-serve": "node scripts/mock-serve.mjs",
"lint": "next lint",
- "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts"
+ "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/prompt-history.test.ts"
},
"dependencies": {
"@streamdown/code": "^1.1.1",