graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Show remaining context beside composer controls
justrachc9fd99a01e3b
diff --git a/apps/native/components/primitives/ContextMeter.tsx b/apps/native/components/primitives/ContextMeter.tsxnew file mode 100644index 00000000..1bdbe788--- /dev/null+++ b/apps/native/components/primitives/ContextMeter.tsx@@ -0,0 +1,31 @@+import { useId, useState } from "react";+import { createPortal } from "react-dom";+import { contextRemaining, type ContextMeter as Reading } from "@/lib/context-meter";++export default function ContextMeter({ reading }: { reading?: Reading }) {+ const id = useId(), remaining = contextRemaining(reading);+ const [anchor, setAnchor] = useState<{right:number;bottom:number} | null>(null);+ const show = (element: HTMLButtonElement) => {+ const rect = element.getBoundingClientRect();+ setAnchor({right:Math.max(8, Math.min(window.innerWidth - 232, window.innerWidth - rect.right)),bottom:window.innerHeight-rect.top+8});+ };+ const label = remaining === undefined ? "Context remaining unknown" : `Approximately ${remaining}% context remaining`;+ return <button type="button" role={remaining === undefined ? "img" : "meter"} aria-label={remaining === undefined ? label : "Context remaining"} aria-valuemin={0} aria-valuemax={100}+ aria-valuenow={remaining} aria-valuetext={label} aria-describedby={id}+ onMouseEnter={event=>show(event.currentTarget)} onFocus={event=>show(event.currentTarget)}+ onMouseLeave={event=>{if(document.activeElement!==event.currentTarget)setAnchor(null);}}+ onBlur={()=>setAnchor(null)} onKeyDown={event=>{if(event.key==='Escape'){setAnchor(null);event.stopPropagation();}}}+ className="group relative ml-auto flex size-7 shrink-0 items-center justify-center rounded-lg text-ink-3 outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-accent">+ <svg aria-hidden="true" width="18" height="18" viewBox="0 0 20 20" fill="none">+ <circle cx="10" cy="10" r="7" stroke="currentColor" strokeWidth="2" opacity="0.2" />+ <circle cx="10" cy="10" r="7" pathLength="100" stroke="currentColor" strokeWidth="2" strokeLinecap="round"+ strokeDasharray={remaining === undefined ? "2 6" : `${remaining} 100`} transform="rotate(-90 10 10)"+ className={remaining !== undefined && remaining <= 10 ? "text-red" : ""} />+ </svg>+ {anchor && createPortal(<span id={id} role="tooltip" style={anchor} className="pointer-events-none fixed z-[100] w-56 rounded-lg border border-line bg-page p-3 text-left text-xs leading-5 text-ink shadow-lg">+ {label}+ <span className="block text-ink-3">{remaining === undefined ? "Available after the harness reports usage." :+ `Last reported: ${reading!.used.toLocaleString()} of ${reading!.window.toLocaleString()} tokens. May change during a turn or after compaction.`}</span>+ </span>,document.body)}+ </button>;+}diff --git a/apps/native/components/primitives/ModelEffortButtons.tsx b/apps/native/components/primitives/ModelEffortButtons.tsxindex 153b5d71..f7630c30 100644--- a/apps/native/components/primitives/ModelEffortButtons.tsx+++ b/apps/native/components/primitives/ModelEffortButtons.tsx@@ -3,6 +3,7 @@ import { useEffect, useRef, useState, type RefObject } from "react";import { createPortal } from "react-dom";import type { ModelChoice } from "@/lib/acp-client";import styles from "./EffortPicker.module.css";+import ContextMeter from "./ContextMeter";const labels: Record<string, string> = { low: "Light", medium: "Medium", high: "High", xhigh: "Extra high", max: "Max", ultra: "Ultra" };function Bolt({ filled = false }: { filled?: boolean }) {return <svg aria-hidden="true" width="20" height="20" viewBox="0 0 24 24" fill={filled ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="m13.3 2-9 12h7L10.7 22l9-12h-7L13.3 2Z" /></svg>;@@ -10,9 +11,10 @@ function Bolt({ filled = false }: { filled?: boolean }) {function Chevron() {return <svg aria-hidden="true" width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="m4 6 4 4 4-4" /></svg>;}-export default function ModelEffortButtons({ model, buttonRef, modelOpen, openModel, wide, pill, onCommand, busy }: {+export default function ModelEffortButtons({ model, buttonRef, modelOpen, openModel, wide, pill, onCommand, busy, contextMeter, showContextMeter }: {model: ModelChoice; buttonRef: RefObject<HTMLButtonElement | null>; modelOpen: boolean; openModel(): void;wide: boolean; pill: boolean; onCommand?: (text: string) => Promise<void>; busy?: boolean;+ contextMeter?: import("@/lib/context-meter").ContextMeter; showContextMeter?: boolean;}) {const [open, setOpen] = useState(false);const [saving, setSaving] = useState(false);@@ -62,6 +64,7 @@ export default function ModelEffortButtons({ model, buttonRef, modelOpen, openMo</button>{levels.length > 0 && <button ref={effortButton} type="button" aria-label="Select effort" aria-expanded={open} onClick={show}className="flex h-7 shrink-0 items-center gap-1.5 rounded-full px-2 text-xs text-ink-3 hover:bg-hover">{labels[model.effort ?? ""] ?? "Effort"}<Chevron /></button>}+ {showContextMeter && <ContextMeter reading={contextMeter} />}{open && createPortal(<div ref={panel} role="dialog" aria-label="Reasoning effort" style={position}className="motion-surface fixed z-[100] w-80 max-w-[calc(100vw-24px)] rounded-[22px] border border-line bg-page px-4 pb-4 pt-3 text-ink shadow-[0_8px_24px_-8px_rgb(0_0_0/18%)]"><div className="flex items-center justify-between gap-3">diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsxindex 80f8fbd9..56009820 100644--- a/apps/native/components/primitives/PromptBar.tsx+++ b/apps/native/components/primitives/PromptBar.tsx@@ -46,6 +46,7 @@ export default function PromptBar({onStop,history,root,+ contextMeter,}: {variant?: string;/** the self-running walkthrough; turn off when embedding in a real surface */@@ -72,6 +73,7 @@ export default function PromptBar({/** The workspace this composer sends into. The @ picker searches it, and a* picked file is mentioned by its path relative to it. */root?: string;+ contextMeter?: import("@/lib/context-meter").ContextMeter;}) {const pill = variant === "Pill";const catalog = models && models.length > 0 ? models : MODELS;@@ -502,6 +504,7 @@ export default function PromptBar({/><ModelEffortButtons model={model} buttonRef={modelRef} modelOpen={modelOpen} wide={wide} pill={pill} busy={busy}+ contextMeter={contextMeter} showContextMeter={!demo}onCommand={onSetting} openModel={() => { setPlusOpen(false); setModelOpen(current => !current); }} />{/* Keep cancellation available while a follow-up is being drafted. */}diff --git a/apps/native/components/site/ChatColumn.tsx b/apps/native/components/site/ChatColumn.tsxindex 82bd734f..6ba40eec 100644--- a/apps/native/components/site/ChatColumn.tsx+++ b/apps/native/components/site/ChatColumn.tsx@@ -21,6 +21,8 @@ export default function ChatColumn({ thread, compact, following, register, onOpehealth: Health | null; onOpenProject: () => void; onProjects: () => void; onConversations: () => void;onRefresh: (loaded: Awaited<ReturnType<typeof loadSession>>) => void; onContinue: () => void;}) {+ const measured = thread.messages.findLast(message => message.role === "assistant" && message.turn.contextMeter);+ const contextMeter = measured?.role === "assistant" ? measured.turn.contextMeter : undefined;if (!thread.messages.length && !thread.snapshot) return <div className="min-h-0 flex-1 overflow-y-auto"><EmptyState compact={compact} onOpenProject={onOpenProject} onProjects={onProjects}onContinue={onConversations} onReview={onReview} onSend={prompt.onSend} onSetting={prompt.onSetting}@@ -43,7 +45,7 @@ export default function ChatColumn({ thread, compact, following, register, onOpe</button></div>}<PromptQueue {...queue} />- <PromptBar {...prompt} tall={!compact} placeholder={prompt.busy ? "Queue a follow-up…" : "Follow up"} />+ <PromptBar {...prompt} contextMeter={contextMeter} tall={!compact} placeholder={prompt.busy ? "Queue a follow-up…" : "Follow up"} /></>}</div></div>diff --git a/apps/native/electron/frontend-runtime.cjs b/apps/native/electron/frontend-runtime.cjsindex 80404bc8..c85b47c9 100644--- a/apps/native/electron/frontend-runtime.cjs+++ b/apps/native/electron/frontend-runtime.cjs@@ -239,6 +239,25 @@ app.whenReady().then(async () => {fs.cpSync(path.join(workspace, '.graff'), path.join(output, 'harness-evidence'), {recursive:true});fs.writeFileSync(path.join(output, 'follow-up-finished.png'), (await wc.capturePage()).toPNG());report.passed.push('typed follow-up, real saved history, finished status and frozen elapsed time');+ if (process.env.GRAFF_CONTEXT_METER_TEST) {+ await until(()=>js(`!!document.querySelector('[role="meter"][aria-label="Context remaining"]')`),'live context meter');+ await click('[aria-label="Context remaining"]');+ await until(()=>js(`!!document.querySelector('[role="tooltip"]')`),'context tooltip mounted');+ const reading=await js(`(()=>{const e=document.querySelector('[role="meter"][aria-label="Context remaining"]');return {remaining:Number(e.getAttribute('aria-valuenow')),label:e.getAttribute('aria-valuetext'),detail:document.getElementById(e.getAttribute('aria-describedby')).textContent};})()`);+ const match=reading.detail.match(/Last reported: ([\d,]+) of ([\d,]+) tokens/);+ assert.ok(match,'Tooltip must show the actual harness occupancy and window');+ const used=Number(match[1].replaceAll(',','')), window=Number(match[2].replaceAll(',',''));+ assert.ok(used>0 && window>0);+ assert.equal(reading.remaining,Math.round(Math.max(0,1-used/window)*100));+ const persisted=saved.map(name=>JSON.parse(fs.readFileSync(path.join(workspace,'.graff/sessions',name),'utf8')));+ assert.ok(persisted.some(session=>session.context_tokens===used),'Ring occupancy must match the real saved harness context');+ await js(`new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))`);+ await click('[aria-label="Context remaining"]');+ await until(()=>js(`getComputedStyle(document.querySelector('[role="tooltip"]')).display!=='none'`),'context details visible');+ fs.writeFileSync(path.join(output,'context-meter.png'),(await wc.capturePage()).toPNG());+ fs.writeFileSync(path.join(output,'context-meter.json'),JSON.stringify({...reading,used,window},null,2));+ report.passed.push('actual harness context reading reaches the composer ring and keyboard-accessible tooltip');+ }if (process.env.GRAFF_TITLE_RESULT_TEST) return require('./title-result-frontend.cjs').verify({win,output,workspace,send,click,until,report});if (process.env.GRAFF_CLI_TEST) {await require('./cli-frontend.cjs').runCliFrontend({ app, win, temp, workspace, output, until, report, projects });diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.tsindex 9a47b750..483e2fd7 100644--- a/apps/native/lib/acp.ts+++ b/apps/native/lib/acp.ts@@ -1,4 +1,5 @@import { htmlArtifactId } from "./html-artifacts";+import { parseContextMeter } from "./context-meter";import { boundToolDetail } from "./tool-detail";import { stripCiteMarkup } from "./cite-markup";import { mcpAppId, viewSnapshotId } from "./mcp-apps";@@ -270,6 +271,7 @@ export function turnBlocks(text: string, tools: ToolRow[]): TurnBlock[] {export function applyAcpUpdate(turn: AssistantTurn, update: AcpUpdate): AssistantTurn {turn = { ...turn, lastUpdateAt: Date.now(), activityKind: update.sessionUpdate, connected: true };switch (update.sessionUpdate) {+ case "gui_context_meter": return { ...turn, contextMeter: parseContextMeter(update) };case "gui_turn_end": return { ...turn, stopReason: typeof update.stopReason === "string" ? update.stopReason : "end_turn" };case "agent_thought_chunk": {const text = stripCiteMarkup((update as { content?: AcpContent }).content?.text ?? "");diff --git a/apps/native/lib/context-meter.test.ts b/apps/native/lib/context-meter.test.tsnew file mode 100644index 00000000..42e9dc38--- /dev/null+++ b/apps/native/lib/context-meter.test.ts@@ -0,0 +1,20 @@+import { expect, test } from "bun:test";+import { applyAcpUpdate, emptyTurn } from "./acp";+import { contextRemaining, parseContextMeter } from "./context-meter";++test("the ACP occupancy update drives remaining context, including compaction and over-cap readings", () => {+ let turn = applyAcpUpdate(emptyTurn(), { sessionUpdate: "gui_context_meter", used: 800, window: 1000 });+ expect(contextRemaining(turn.contextMeter)).toBe(20);+ turn = applyAcpUpdate(turn, { sessionUpdate: "gui_context_meter", used: 200, window: 1000 });+ expect(contextRemaining(turn.contextMeter)).toBe(80);+ expect(contextRemaining({ used: 1200, window: 1000 })).toBe(0);+ expect(contextRemaining({ used: 0, window: 1000 })).toBe(100);+});++test("missing or invalid usage cannot imply a full context window", () => {+ for (const value of [undefined, null, {}, {used:-1,window:1000}, {used:0,window:0},+ {used:Infinity,window:1000}, {used:1,window:NaN}, {used:"1",window:1000}]) {+ expect(parseContextMeter(value)).toBeUndefined();+ }+ expect(contextRemaining()).toBeUndefined();+});diff --git a/apps/native/lib/context-meter.ts b/apps/native/lib/context-meter.tsnew file mode 100644index 00000000..41c00f9f--- /dev/null+++ b/apps/native/lib/context-meter.ts@@ -0,0 +1,11 @@+export type ContextMeter = { used: number; window: number };+export function parseContextMeter(value: unknown): ContextMeter | undefined {+ const m = value as Partial<ContextMeter> | null;+ return m && typeof m.used === "number" && Number.isFinite(m.used) && m.used >= 0 &&+ typeof m.window === "number" && Number.isFinite(m.window) && m.window > 0+ ? { used: m.used, window: m.window } : undefined;+}+export function contextRemaining(meter?: ContextMeter): number | undefined {+ const m = parseContextMeter(meter);+ return m ? Math.round(Math.max(0, Math.min(1, 1 - m.used / m.window)) * 100) : undefined;+}diff --git a/apps/native/lib/graff-events.ts b/apps/native/lib/graff-events.tsindex 1b2b4014..86762810 100644--- a/apps/native/lib/graff-events.ts+++ b/apps/native/lib/graff-events.ts@@ -85,6 +85,7 @@ export type AskPrompt = {export type TurnStatus = "thinking" | "streaming" | "ask" | "done" | "error" | "snapshot";export type AssistantTurn = {+ contextMeter?: import("./context-meter").ContextMeter;endedAt?: number;startedAt?: number;lastUpdateAt?: number;diff --git a/apps/native/package.json b/apps/native/package.jsonindex dc69d5a2..f167e85c 100644--- a/apps/native/package.json+++ b/apps/native/package.json@@ -51,7 +51,8 @@"test:packaged-html": "bun scripts/test-packaged-html.mjs","test:workspace-history": "GRAFF_WORKSPACE_HISTORY_TEST=1 bun scripts/test-frontend.mjs","test:narrow-navigation": "GRAFF_NARROW_NAV_TEST=1 bun scripts/test-frontend.mjs",- "test:packaged-titles": "bun scripts/test-packaged-titles.mjs"+ "test:packaged-titles": "bun scripts/test-packaged-titles.mjs",+ "test:context-meter": "GRAFF_CONTEXT_METER_TEST=1 bun scripts/test-frontend.mjs"},"dependencies": {"@streamdown/code": "^1.1.1",diff --git a/docs/adr/0128-gui-context-meter-uses-harness-occupancy.md b/docs/adr/0128-gui-context-meter-uses-harness-occupancy.mdnew file mode 100644index 00000000..eea84049--- /dev/null+++ b/docs/adr/0128-gui-context-meter-uses-harness-occupancy.md@@ -0,0 +1,20 @@+# 0128. GUI context meter uses harness occupancy++Status: accepted++## Decision++The composer displays approximate remaining context from the harness occupancy+and effective window reported through ACP. It never infers occupancy from total+billed tokens, cache hits, or a model catalog default. The reading is explicitly+last reported; missing or invalid data stays unknown. Slash commands refresh the+reading so compaction and model changes do not leave their previous value shown.++The ring stays compact, with token detail available on hover or focus. Over-cap+readings clamp remaining capacity to zero. Saved snapshots are not live meters.++## Validation++Protocol and reducer tests cover occupancy delivery, compaction, missing values+and over-cap readings. The production GUI fixture compares the displayed reading+with the real saved harness context and checks the visible detail panel.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex d79e9758..cf9f10c2 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -144,6 +144,8 @@ record only when you need the evidence or the edge cases.| [0127](0127-title-generation-is-an-explicit-result.md) | GUI titles require one explicit result and successful process exit; diagnostics never become chat names. |+| [0128](0128-gui-context-meter-uses-harness-occupancy.md) | The GUI context ring uses last-reported harness occupancy; missing usage stays unknown. |+## When to write oneWrite an ADR when a decision is load-bearing and non-obvious: it was reacheddiff --git a/src/acp_engine.zig b/src/acp_engine.zigindex 46afef16..6448add4 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -101,12 +101,20 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)const reply = slash(d.ctx, arena, text) catch |err| return turnError(d, w, req, err);if (reply) |plain| {if (plain.len > 0) try writeSessionUpdate(w, sid, plain);+ try emitMeter(d, w, sid);return respond(w, req, .{ .stopReason = "end_turn" });}}if (d.after_user) |after| after(d.ctx, arena, text);const final = d.turn(d.ctx, arena, text) catch |err| return turnError(d, w, req, err);if (final.len > 0) try writeSessionUpdate(w, sid, final);+ try emitMeter(d, w, sid);+ const extra = if (extra_cancelled) |f| f() else false;+ const stop: []const u8 = if (cancel_flag.load(.acquire) or extra) "cancelled" else "end_turn";+ try respond(w, req, .{ .stopReason = stop });+}++fn emitMeter(d: *Dispatch, w: *Io.Writer, sid: []const u8) !void {if (d.meter) |meter| {// Report live occupancy independently of the model catalog.const m = meter(d.ctx);@@ -119,9 +127,27 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)},});}- const extra = if (extra_cancelled) |f| f() else false;- const stop: []const u8 = if (cancel_flag.load(.acquire) or extra) "cancelled" else "end_turn";- try respond(w, req, .{ .stopReason = stop });+}++test "slash commands refresh occupancy before their terminal response" {+ const Fixture = struct {+ fn slash(_: *anyopaque, _: Allocator, _: []const u8) anyerror!?[]const u8 {+ return "compacted";+ }+ fn meter(_: *anyopaque) Meter {+ return .{ .used = 20, .window = 100 };+ }+ };+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ var buffer: [2048]u8 = undefined;+ var writer: Io.Writer = .fixed(&buffer);+ var dispatch: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .slash = Fixture.slash, .meter = Fixture.meter };+ try handleLine(&dispatch, arena.allocator(), &writer, "{\"id\":1,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"/compact\"}]}}");+ const output = writer.buffered();+ const meter_pos = std.mem.indexOf(u8, output, "\"used\":20,\"window\":100") orelse return error.MissingMeter;+ const end_pos = std.mem.indexOf(u8, output, "stopReason") orelse return error.MissingResponse;+ try std.testing.expect(meter_pos < end_pos);}fn respondInitialize(w: *Io.Writer, req: proto.Request) !void {