graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Make usage summaries readable and retain message bubbles while editing
justrach2ea501badb4a
diff --git a/apps/native/app/visual-tests/usage/fixture.tsx b/apps/native/app/visual-tests/usage/fixture.tsxnew file mode 100644index 00000000..432b6d3f--- /dev/null+++ b/apps/native/app/visual-tests/usage/fixture.tsx@@ -0,0 +1,29 @@+"use client";+import { useState } from "react";+import ChatTranscript from "@/components/site/ChatTranscript";+import { emptyTurn } from "@/lib/acp";+import type { Msg } from "@/components/site/harness-types";++// Synthetic usage: never put real session/account data in a public fixture.+const report = `session usage+ api calls: 12 (12 subscription, flat-rate)+ tokens: 12400 in (8000 cached) + 640 out+ cost: $0.0000 (API-key calls with a known price only)+codex plan+ plan: sample+ 5h: 65% remaining (35% used), resets in a few hours+xai / grok+ xAI weekly plan remaining is not a public API`;+const original = "Could we make this output easier to read?\n\nKeep the useful numbers together, with the plan limits underneath. I'd like the message to keep its rounded shape while I edit it, too.";+export default function Fixture() {+ const [text, setText] = useState(original);+ const messages: Msg[] = [+ { id: 1, role: "user", text: "/usage" },+ { id: 2, role: "assistant", turn: { ...emptyTurn(), text: report, status: "done" } },+ { id: 3, role: "user", text },+ ];+ return <main className="mx-auto flex h-screen max-w-[760px] flex-col bg-surface text-ink">+ <ChatTranscript messages={messages} register={() => {}} following={false} onOpenPath={() => {}} onReview={() => {}}+ onEditPrompt={(_, next) => setText(next)} />+ </main>;+}diff --git a/apps/native/app/visual-tests/usage/page.tsx b/apps/native/app/visual-tests/usage/page.tsxnew file mode 100644index 00000000..4db8c32b--- /dev/null+++ b/apps/native/app/visual-tests/usage/page.tsx@@ -0,0 +1,7 @@+import { notFound } from "next/navigation";+import Fixture from "./fixture";+export const dynamic = "force-dynamic";+export default function Page() {+ if (process.env.GRAFF_VISUAL_TESTS !== "1") notFound();+ return <Fixture />;+}diff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsxindex 9592c191..3a5806fd 100644--- a/apps/native/components/site/ChatBubbles.tsx+++ b/apps/native/components/site/ChatBubbles.tsx@@ -9,6 +9,8 @@ import TurnActivity from "./TurnActivity";import HtmlArtifact from "./HtmlArtifact";import McpAppResult from "./McpAppResult";import SnapshotView from "./SnapshotView";+import UsageSummary from "./UsageSummary";+import motion from "./transcript-motion.module.css";import { markerName, splitImageMarkers } from "@/lib/attachments";import { pinScrollerTail } from "@/lib/follow-scroll";import { IconArrowUp, IconCrossSmall, IconEditBig } from "@/lib/icons";@@ -66,6 +68,21 @@ export const UserBubble = memo(function UserBubble({ text, onEdit }: { text: strconst words = parts.filter((_, index) => index % 2 === 0).join("");const [editing, setEditing] = useState(false);const [draft, setDraft] = useState(words);+ const bubble = useRef<HTMLDivElement>(null);+ const editor = useRef<HTMLTextAreaElement>(null);+ const [editWidth, setEditWidth] = useState<number>();+ useLayoutEffect(() => {+ if (!editing || !editor.current) return;+ const input = editor.current;+ const resize = () => {+ input.style.height = "0px";+ input.style.height = `${input.scrollHeight}px`;+ };+ resize();+ const observer = new ResizeObserver(resize);+ if (bubble.current) observer.observe(bubble.current);+ return () => observer.disconnect();+ }, [editing, draft]);const save = () => {const next = draft.trim();setEditing(false);@@ -79,31 +96,31 @@ export const UserBubble = memo(function UserBubble({ text, onEdit }: { text: str{images.map((part, index) => <PastedImage key={`${index}-${part}`} name={markerName(part)} />)}</div>}{words.trim() && <div className="flex max-w-full items-end gap-1">- {onEdit && !editing && <button type="button" data-edit-prompt aria-label="Edit prompt" onClick={() => { setDraft(words); setEditing(true); }}- className="mb-0.5 flex size-6 shrink-0 items-center justify-center rounded-[6px] text-ink-3 opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-hover-2 hover:text-ink group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:none)]:opacity-100">+ {onEdit && !editing && <button type="button" data-edit-prompt aria-label="Edit prompt" onClick={() => { setEditWidth(bubble.current?.getBoundingClientRect().width); setDraft(words); setEditing(true); }}+ className="mb-0.5 flex size-6 shrink-0 items-center justify-center rounded-full text-ink-3 opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-hover-2 hover:text-ink group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:none)]:opacity-100"><IconEditBig size={13} /></button>}- {editing ? <div className="relative min-w-[14rem] max-w-full">- <textarea data-edit-prompt-draft value={draft} autoFocus rows={Math.min(8, Math.max(2, draft.split("\n").length))}+ <div ref={bubble} data-message-bubble data-editing={editing}+ className="min-w-0 max-w-full whitespace-pre-wrap break-words rounded-card px-3.5 py-2 text-[13px] leading-relaxed text-ink shadow-hairline [overflow-wrap:anywhere] focus-within:ring-1 focus-within:ring-[color-mix(in_oklab,var(--accent)_25%,transparent)]"+ style={{ background: "color-mix(in oklab, var(--accent) 12%, var(--surface))", width: editing && editWidth ? Math.max(140, editWidth) : undefined }}>+ {editing ? <>+ <textarea ref={editor} data-edit-prompt-draft aria-label="Edit prompt" value={draft} autoFocus rows={1}onChange={e => setDraft(e.target.value)}- onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); save(); } if (e.key === "Escape") setEditing(false); }}- className="min-w-0 w-full resize-y rounded-xl px-3.5 pb-9 pt-2.5 text-[13px] leading-relaxed text-ink shadow-hairline outline-none ring-1 ring-transparent transition-[box-shadow,ring-color] duration-150 focus:ring-[color-mix(in_oklab,var(--accent)_40%,transparent)]"- style={{ background: "color-mix(in oklab, var(--accent) 12%, var(--surface))" }} />- <div className="absolute bottom-1.5 right-1.5 flex items-center gap-0.5">+ onKeyDown={e => { if (e.nativeEvent.isComposing) return; if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); save(); } if (e.key === "Escape") setEditing(false); }}+ className="block min-w-0 w-full resize-none overflow-hidden border-0 bg-transparent p-0 text-[13px] leading-relaxed text-ink outline-none" />+ <div className={`${motion.reveal} mt-2 flex items-center justify-end gap-1`}><button type="button" aria-label="Cancel" onClick={() => setEditing(false)}- className="flex size-6 items-center justify-center rounded-[6px] text-ink-3 transition-[background-color,color] duration-150 hover:bg-hover-2 hover:text-ink">+ className="flex size-7 items-center justify-center rounded-full text-ink-3 transition-[background-color,color] duration-150 hover:bg-hover-2 hover:text-ink"><IconCrossSmall size={13} /></button><button type="button" aria-label="Send again" onClick={save} disabled={!draft.trim()}- className="flex size-6 items-center justify-center rounded-[8px] transition-[opacity,transform] duration-150 enabled:active:scale-[0.94] disabled:opacity-30"+ className="flex size-7 items-center justify-center rounded-full transition-[opacity,transform] duration-150 enabled:active:scale-[0.94] disabled:opacity-30"style={{ background: "var(--ink)", color: "var(--surface)" }}><IconArrowUp size={14} /></button></div>- </div> : <div- className="min-w-0 max-w-full whitespace-pre-wrap break-words rounded-xl px-3.5 py-2 text-[13px] leading-relaxed text-ink shadow-hairline [overflow-wrap:anywhere]"- style={{ background: "color-mix(in oklab, var(--accent) 12%, var(--surface))" }}- >{words}</div>}+ </> : words}+ </div></div>}</div></div>@@ -119,6 +136,7 @@ export const AssistantBody = memo(function AssistantBody({following,reasoningLabel,snapshot,+ usage = false,}: {turn: AssistantTurn;onOpenPath?: (path: string) => void;@@ -128,6 +146,7 @@ export const AssistantBody = memo(function AssistantBody({following: boolean;reasoningLabel?: string;snapshot?: boolean;+ usage?: boolean;}) {const thinking = turn.status === "thinking";const live = thinking || turn.status === "streaming";@@ -177,8 +196,8 @@ export const AssistantBody = memo(function AssistantBody({</div>) : (<div key={`text-${i}`} className="mt-3 max-w-[630px]">- <StreamingMarkdown text={block.text} live={i === lastTextIndex && live}- onOpenPath={onOpenPath} scroller={scroller} following={i === lastTextIndex && following} />+ {usage ? <UsageSummary text={block.text} /> : <StreamingMarkdown text={block.text} live={i === lastTextIndex && live}+ onOpenPath={onOpenPath} scroller={scroller} following={i === lastTextIndex && following} />}</div>),)}diff --git a/apps/native/components/site/ChatTranscript.tsx b/apps/native/components/site/ChatTranscript.tsxindex 204317f9..25e2b71a 100644--- a/apps/native/components/site/ChatTranscript.tsx+++ b/apps/native/components/site/ChatTranscript.tsx@@ -68,6 +68,7 @@ export default memo(function ChatTranscript({ messages, register, following, onOonEditPrompt(n, next);}} />: <AssistantBody key={message.id} turn={message.turn} onOpenPath={onOpenPath} onReview={onReview} onAnswer={onAnswer}+ usage={(() => { const previous = messages[start + index - 1]; return previous?.role === "user" && /^\/(usage|cost)$/.test(previous.text.trim()); })()}scroller={scroller} following={following && start + index === messages.length - 1} snapshot={snapshot} />)}</div></div>;diff --git a/apps/native/components/site/SessionNotice.tsx b/apps/native/components/site/SessionNotice.tsxindex c825d200..6e51ff0d 100644--- a/apps/native/components/site/SessionNotice.tsx+++ b/apps/native/components/site/SessionNotice.tsx@@ -1,7 +1,9 @@+import motion from "./transcript-motion.module.css";+/** Engine-generated context has its own identity, even when its wire role is user. */export default function SessionNotice({ text }: { text: string }) {return <details data-session-notice className="min-w-0 rounded-lg border border-line px-3 py-2 text-[12.5px] leading-relaxed text-ink-2"><summary className="cursor-pointer select-none">Session notification</summary>- <p className="mt-2 whitespace-pre-wrap [overflow-wrap:anywhere]">{text}</p>+ <p className={`${motion.reveal} mt-2 whitespace-pre-wrap [overflow-wrap:anywhere]`}>{text}</p></details>;}diff --git a/apps/native/components/site/SnapshotView.tsx b/apps/native/components/site/SnapshotView.tsxindex 963dda1f..a576e0c9 100644--- a/apps/native/components/site/SnapshotView.tsx+++ b/apps/native/components/site/SnapshotView.tsx@@ -2,6 +2,7 @@import {useState, useEffect, useRef} from "react";import {validAppId} from "@/lib/mcp-apps";+import motion from "./transcript-motion.module.css";/** One saved HTML snapshot shown inside the transcript. The two kinds differ* only in where the bytes came from and what they may do; neither is ever@@ -48,7 +49,7 @@ export default function SnapshotView({kind, id}: {kind: SnapshotKind; id: string{visible? <div className="pointer-events-none absolute right-1 top-1 z-10 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100"><span className="pointer-events-auto">{toggle}</span></div>: toggle}- {visible && <div className="w-full bg-transparent" style={{height: "min(70vh, 32rem)"}}>{iframe}</div>}+ {visible && <div className={`${motion.reveal} w-full bg-transparent`} style={{height: "min(70vh, 32rem)"}}>{iframe}</div>}</section>;}return <section ref={host} className="my-3 overflow-hidden rounded-lg border border-ink/10" aria-label={label}>diff --git a/apps/native/components/site/UsageSummary.tsx b/apps/native/components/site/UsageSummary.tsxnew file mode 100644index 00000000..44d9086b--- /dev/null+++ b/apps/native/components/site/UsageSummary.tsx@@ -0,0 +1,37 @@+"use client";++import { parseUsageSummary } from "@/lib/usage-summary";+import motion from "./transcript-motion.module.css";++export default function UsageSummary({ text }: { text: string }) {+ const summary = parseUsageSummary(text);+ if (!summary) return <p className="whitespace-pre-wrap text-[13px] leading-relaxed text-ink-2">{text}</p>;+ return <section aria-label="Session usage" className={`${motion.reveal} space-y-5 text-[13px] text-ink`}>+ <h3 className="font-medium">Session usage</h3>+ {summary.metrics.length > 0 && <dl className="grid grid-cols-2 gap-x-6 gap-y-4">+ {summary.metrics.map(metric => <div key={metric.label} className="min-w-0">+ <dt className="text-[12px] text-ink-3">{metric.label}</dt>+ <dd className="mt-1 text-[20px] font-medium leading-tight tabular-nums tracking-tight">{metric.value}</dd>+ {metric.note && <dd className="mt-1 text-[11px] leading-relaxed text-ink-3">{metric.note}</dd>}+ </div>)}+ </dl>}+ {summary.notes.map(note => <p key={note} className="text-[12px] text-ink-3">{note}</p>)}+ {summary.plans.map(plan => <section key={plan.name} aria-label={`${plan.name} plan`} className="space-y-3 border-t border-line pt-4">+ <h4 className="flex items-center gap-2 font-medium">{plan.name}+ {plan.plan && <span className="rounded-full bg-hover px-2 py-0.5 text-[11px] font-normal text-ink-2">{plan.plan}</span>}+ </h4>+ {plan.windows.map(window => <div key={window.label} className="space-y-1.5">+ <div className="flex items-baseline justify-between gap-3 text-[12px]">+ <span className="text-ink-2">{window.label === "5h" ? "5-hour window" : window.label === "weekly" ? "Weekly" : window.label}</span>+ <span className="tabular-nums">{window.remaining}% remaining</span>+ </div>+ <div role="meter" aria-label={`${plan.name} ${window.label} remaining`} aria-valuemin={0} aria-valuemax={100}+ aria-valuenow={Math.min(100, Math.max(0, window.remaining))} className="h-1.5 overflow-hidden rounded-full bg-hover">+ <div className={`${motion.resize} h-full rounded-full bg-accent`} style={{width: `${Math.min(100, Math.max(0, window.remaining))}%`}} />+ </div>+ <p className="text-[11px] text-ink-3">{window.used}% used{window.reset ? ` · Resets in ${window.reset}` : ""}</p>+ </div>)}+ {plan.notes.map(note => <p key={note} className="text-[12px] leading-relaxed text-ink-3">{note}</p>)}+ </section>)}+ </section>;+}diff --git a/apps/native/components/site/transcript-motion.module.css b/apps/native/components/site/transcript-motion.module.cssnew file mode 100644index 00000000..301cfcd8--- /dev/null+++ b/apps/native/components/site/transcript-motion.module.css@@ -0,0 +1,19 @@+/* Card-resize and panel-reveal patterns from transitions.dev, tuned to the+ desktop's existing easing. No runtime dependency or looping animation. */+.resize {+ transition: width 180ms var(--ease-out-strong, ease-out), height 180ms var(--ease-out-strong, ease-out);+}++.reveal {+ animation: transcript-reveal 180ms var(--ease-out-strong, ease-out) both;+}++@keyframes transcript-reveal {+ from { opacity: 0; transform: translateY(3px); }+ to { opacity: 1; transform: translateY(0); }+}++@media (prefers-reduced-motion: reduce) {+ .resize { transition: none !important; }+ .reveal { animation: none !important; }+}diff --git a/apps/native/lib/usage-summary.test.ts b/apps/native/lib/usage-summary.test.tsnew file mode 100644index 00000000..92b75d04--- /dev/null+++ b/apps/native/lib/usage-summary.test.ts@@ -0,0 +1,31 @@+import { describe, expect, test } from "bun:test";+import { parseUsageSummary } from "./usage-summary";++describe("usage summary", () => {+ test("keeps cache and billing caveats alongside readable numbers and plan windows", () => {+ const result = parseUsageSummary(`session usage+ api calls: 12 (12 subscription, flat-rate)+ tokens: 12400 in (8000 cached) + 640 out+ cost: $0.0000 (API-key calls with a known price only)+codex plan+ plan: sample+ 5h: 65% remaining (35% used), resets in a few hours+xai / grok+ xAI weekly plan remaining is not a public API`)!;+ expect(result.metrics.map(metric => metric.value)).toEqual(["12", "12,400", "640", "$0.0000"]);+ expect(result.metrics[1].note).toBe("8,000 cached");+ expect(result.metrics[3].note).toBe("API-key calls with a known price only");+ expect(result.plans[0].windows[0]).toEqual({ label: "5h", remaining: 65, used: 35, reset: "a few hours" });+ expect(result.plans[1].notes).toEqual(["xAI weekly plan remaining is not a public API"]);+ });+ test("empty sessions can still show plan limits and unknown lines are not lost", () => {+ const result = parseUsageSummary("no API calls yet this session\ncodex plan\n weekly: 0% remaining (100% used)\n Usage unavailable")!;+ expect(result.metrics).toHaveLength(0);+ expect(result.notes).toEqual(["No API calls yet this session."]);+ expect(result.plans[0].notes).toEqual(["Usage unavailable"]);+ });+ test("does not reinterpret ordinary assistant text or empty output", () => {+ expect(parseUsageSummary("Here is your session usage")).toBeNull();+ expect(parseUsageSummary(" \n ")).toBeNull();+ });+});diff --git a/apps/native/lib/usage-summary.ts b/apps/native/lib/usage-summary.tsnew file mode 100644index 00000000..7fa3d01e--- /dev/null+++ b/apps/native/lib/usage-summary.ts@@ -0,0 +1,41 @@+export type UsageMetric = { label: string; value: string; note?: string };+export type UsageWindow = { label: string; remaining: number; used: number; reset?: string };+export type UsagePlan = { name: string; plan?: string; windows: UsageWindow[]; notes: string[] };+export type UsageSummary = { metrics: UsageMetric[]; plans: UsagePlan[]; notes: string[] };++const number = (value: string) => Number(value).toLocaleString("en-US");++/** Only used for /usage and /cost replies; unknown lines remain visible. */+export function parseUsageSummary(text: string): UsageSummary | null {+ const lines = text.trim().split(/\r?\n/).map(line => line.trim()).filter(Boolean);+ if (lines[0] !== "session usage" && lines[0] !== "no API calls yet this session") return null;+ const result: UsageSummary = { metrics: [], plans: [], notes: [] };+ let plan: UsagePlan | undefined;+ if (lines[0].startsWith("no API")) result.notes.push("No API calls yet this session.");+ for (const line of lines.slice(1)) {+ if (line === "codex plan" || line === "xai / grok") {+ plan = { name: line === "codex plan" ? "Codex" : "xAI / Grok", windows: [], notes: [] };+ result.plans.push(plan);+ continue;+ }+ if (plan) {+ const tier = /^plan:\s+(.+)$/.exec(line);+ const window = /^(.+?):\s+(\d+)% remaining \((\d+)% used\)(?:, resets in (.+))?$/.exec(line);+ if (tier) plan.plan = tier[1];+ else if (window) plan.windows.push({ label: window[1], remaining: Number(window[2]), used: Number(window[3]), reset: window[4] });+ else plan.notes.push(line);+ continue;+ }+ const calls = /^api calls:\s+(\d+)(.*)$/.exec(line);+ const tokens = /^tokens:\s+(\d+) in \((\d+) cached\) \+ (\d+) out$/.exec(line);+ const cost = /^cost:\s+(\$[\d.]+)(?:\s+\((.*)\))?$/.exec(line);+ if (calls) result.metrics.push({ label: "API calls", value: number(calls[1]), note: calls[2].replace(/[()]/g, "").trim() });+ else if (tokens) result.metrics.push(+ { label: "Input tokens", value: number(tokens[1]), note: `${number(tokens[2])} cached` },+ { label: "Output tokens", value: number(tokens[3]) },+ );+ else if (cost) result.metrics.push({ label: "API cost", value: cost[1], note: cost[2] });+ else result.notes.push(line);+ }+ return result;+}