graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(tui): /context and /session-info read the engine's meters
Rach Pradhancad59324cdb9
diff --git a/TUI/app.zig b/TUI/app.zigindex a76e9c4b..45be06e5 100644--- a/TUI/app.zig+++ b/TUI/app.zig@@ -95,8 +95,10 @@ pub const Model = struct {scroll: usize = 0,selected: usize = 0,turns: usize = 0,- chars_in: usize = 0,- chars_out: usize = 0,+ /// The engine's last reported meters (#551). Null until a turn has run —+ /// there is nothing honest to say about a context nobody has measured.+ /// Its strings are owned here; setStatus and deinit are the only writers.+ status: ?engine.Status = null,last_term_width: usize = 80,last_term_height: usize = 24,/// Screen row (0-based) where scrollback/welcome starts — for mouse hits.@@ -164,6 +166,7 @@ pub const Model = struct {self.images.deinit();if (self.goal) |g| self.alloc.free(g);if (self.session_name) |s| self.alloc.free(s);+ self.dropStatus();if (self.model_override) |m| {// The global points into this buffer; drop it before the free so a// late reader cannot follow a dangling slice.@@ -257,13 +260,44 @@ pub const Model = struct {for (self.history.items) |e| self.freeEntry(e);self.history.clearRetainingCapacity();self.turns = 0;- self.chars_in = 0;- self.chars_out = 0;+ // The meters describe a conversation that no longer exists. Compaction+ // replays through here too and re-reports its own on the next turn.+ self.dropStatus();self.selected = 0;self.scroll = 0;self.screen = .welcome;}+ /// Adopt the engine's meters. The event's copy dies with the drain that+ /// delivered it, so the two strings are re-owned here.+ pub fn setStatus(self: *Model, st: engine.Status) void {+ const model = self.alloc.dupe(u8, st.model) catch return;+ const provider = self.alloc.dupe(u8, st.provider_id) catch {+ self.alloc.free(model);+ return;+ };+ self.dropStatus();+ var owned = st;+ owned.model = model;+ owned.provider_id = provider;+ self.status = owned;+ }++ pub fn dropStatus(self: *Model) void {+ const st = self.status orelse return;+ self.alloc.free(st.model);+ self.alloc.free(st.provider_id);+ self.status = null;+ }++ /// Percent of the model's context window in use, or null while nothing has+ /// been measured — a "0%" drawn before the first response is a lie.+ pub fn contextPercent(self: *const Model) ?u64 {+ const st = self.status orelse return null;+ if (!st.has_context) return null;+ return st.percent();+ }+/// /new, /clear, Ctrl+N twice: start over. Distinct from clearHistory,/// which the compaction replay also uses — that one REPLACES the visible/// transcript for a conversation the engine has just rewritten and mustdiff --git a/TUI/chrome.zig b/TUI/chrome.zigindex f7c81f4c..00006a16 100644--- a/TUI/chrome.zig+++ b/TUI/chrome.zig@@ -58,7 +58,15 @@ pub fn promptBox(self: *const Model, a: std.mem.Allocator, width: usize) ![]constry out.append('\n');}const model = if (engine.g_model_name.len > 0) engine.g_model_name else "offline";- const label = try std.fmt.allocPrint(a, " {s} ({s}) · {s} ", .{ model, @tagName(self.effort), self.modeSlug() });+ // The context share comes from the engine's meter and appears only once a+ // turn has reported usage — a "0%" before the first response would be the+ // char-counter's old habit of showing a number it had not measured (#551).+ var pct_buf: [16]u8 = undefined;+ const pct: []const u8 = if (self.contextPercent()) |p|+ (std.fmt.bufPrint(&pct_buf, " · {d}%", .{p}) catch "")+ else+ "";+ const label = try std.fmt.allocPrint(a, " {s} ({s}) · {s}{s} ", .{ model, @tagName(self.effort), self.modeSlug(), pct });try out.appendSlice(try footer(a, border, th.muted, label, inner));return out.items;}diff --git a/TUI/dispatch.zig b/TUI/dispatch.zigindex 53350c18..41739111 100644--- a/TUI/dispatch.zig+++ b/TUI/dispatch.zig@@ -7,6 +7,7 @@ const app = @import("app.zig");const bgop = @import("bgop.zig");const catalog = @import("catalog.zig");const engine = @import("engine.zig");+const meters = @import("meters.zig");const theme_mod = @import("theme.zig");const turn = @import("turn.zig");const Model = app.Model;@@ -35,7 +36,6 @@ pub fn applyLine(self: *Model, raw: []const u8) Effect {if (payload.ptr != line.ptr) self.alloc.free(payload);if (self.chat) {self.turns += 1;- self.chars_in += line.len;turn.startJob(self);return .stay;}@@ -155,7 +155,7 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {self.session_name = if (arg.len > 0) (self.alloc.dupe(u8, arg) catch null) else null;self.pushFmt(.system, "session: {s}", .{self.session_name orelse "untitled"}) catch {};} else if (std.mem.eql(u8, canon, "/session-info")) {- self.pushFmt(.system, "{s} · {s} · {d} turn(s) · ~{d} in / ~{d} out · {s}", .{ self.modeLabel(), engine.g_model_name, self.turns, self.chars_in, self.chars_out, engine.g_cwd }) catch {};+ meters.sessionInfo(self);} else if (std.mem.eql(u8, canon, "/debug")) {self.openOverlay(.debug);} else if (std.mem.eql(u8, canon, "/usage")) {@@ -167,7 +167,7 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {self.push(.system, "usage unavailable (no session sink)") catch {};}} else if (std.mem.eql(u8, canon, "/context")) {- self.pushFmt(.system, "context: {d} chars sent, {d} received this session", .{ self.chars_in, self.chars_out }) catch {};+ meters.contextInfo(self);} else if (std.mem.eql(u8, canon, "/history")) {recallPrev(self);} else if (std.mem.eql(u8, canon, "/image")) {@@ -375,8 +375,6 @@ test "/usage is not a char-count view" {var m: Model = undefined;m.setup(std.testing.allocator);defer m.deinit();- m.chars_in = 99;- m.chars_out = 88;_ = applyLine(&m, "/usage");const text = m.history.items[m.history.items.len - 1].text;try std.testing.expect(std.mem.indexOf(u8, text, "chars sent") == null);@@ -447,7 +445,6 @@ test "/usage with a session HUD is the cost line, not chars" {var m: Model = undefined;m.setup(std.testing.allocator);defer m.deinit();- m.chars_in = 99;_ = applyLine(&m, "/cost");const text = m.history.items[m.history.items.len - 1].text;try std.testing.expect(std.mem.indexOf(u8, text, "api call(s)") != null);diff --git a/TUI/engine.zig b/TUI/engine.zigindex e1f54c5a..c1bacd6a 100644--- a/TUI/engine.zig+++ b/TUI/engine.zig@@ -8,6 +8,8 @@ const events_mod = @import("events.zig");pub const Event = events_mod.Event;pub const EventQueue = events_mod.Queue;pub const ToolEvent = events_mod.Tool;+pub const Status = events_mod.Status;+pub const Cost = events_mod.Cost;pub const Effort = enum { low, medium, high, xhigh, max, ultra };diff --git a/TUI/events.zig b/TUI/events.zigindex 86d58cdb..35aaffdc 100644--- a/TUI/events.zig+++ b/TUI/events.zig@@ -35,6 +35,45 @@ pub const Tool = struct {denied: bool = false,};+/// What the cost meter can say. Three of the four are STATES, not numbers, so+/// a pre-formatted string would have had to invent figures for them.+pub const Cost = union(enum) {+ /// --no-cost: the segment does not exist.+ hidden,+ /// Flat-rate provider: spend is not per-turn.+ subscription,+ /// No price-table row for this model.+ unpriced,+ usd: f64,+};++/// The engine's view of the session after a turn (engine_events.PromptStatus).+/// The TUI used to answer /context and /session-info from characters it had+/// counted itself, which measured the transcript rather than the request and+/// went further wrong every time the engine compacted or a tool result landed.+pub const Status = struct {+ model: []const u8,+ provider_id: []const u8 = "",+ /// Context figures are meaningful only once a response has reported usage.+ has_context: bool = false,+ tokens: u64 = 0,+ window: u64 = 0,+ compact_at: u64 = 0,+ cache_read: u64 = 0,+ cost: Cost = .hidden,+ fast: bool = false,+ fallback: bool = false,+ plan: bool = false,+ strict: bool = false,+ ultracode: bool = false,++ /// Percent of the window in use, 0 when nothing has been measured.+ pub fn percent(self: Status) u64 {+ if (!self.has_context or self.window == 0) return 0;+ return @min((self.tokens *| 100) / self.window, 100);+ }+};+pub const Event = union(enum) {/// A tool call cleared the gates and is running (ToolInvocation).tool_started: Tool,@@ -47,6 +86,10 @@ pub const Event = union(enum) {notice: []const u8,/// The active provider failed over mid-turn (provider_fallback).model_changed: []const u8,+ /// The engine's own context/cost meters (prompt_ready). The TUI renders+ /// /context, /session-info and the footer from THIS, instead of counting+ /// characters and calling the result a context meter.+ status: Status,};/// Lock-guarded SPSC-shaped hand-off: the turn thread (and the parallel tool@@ -141,9 +184,20 @@ fn dupeEvent(gpa: std.mem.Allocator, ev: Event) ?Event {.tool_rejected => |t| .{ .tool_rejected = dupeTool(gpa, t) orelse return null },.notice => |s| .{ .notice = gpa.dupe(u8, s) catch return null },.model_changed => |s| .{ .model_changed = gpa.dupe(u8, s) catch return null },+ .status => |st| .{ .status = dupeStatus(gpa, st) orelse return null },};}+fn dupeStatus(gpa: std.mem.Allocator, st: Status) ?Status {+ var out = st;+ out.model = gpa.dupe(u8, st.model) catch return null;+ out.provider_id = gpa.dupe(u8, st.provider_id) catch {+ gpa.free(out.model);+ return null;+ };+ return out;+}+fn freeEvent(gpa: std.mem.Allocator, ev: Event) void {switch (ev) {.tool_started, .tool_finished, .tool_rejected => |t| {@@ -151,6 +205,10 @@ fn freeEvent(gpa: std.mem.Allocator, ev: Event) void {gpa.free(t.detail);},.notice, .model_changed => |s| gpa.free(s),+ .status => |st| {+ gpa.free(st.model);+ gpa.free(st.provider_id);+ },}}diff --git a/TUI/meters.zig b/TUI/meters.zignew file mode 100644index 00000000..17645f11--- /dev/null+++ b/TUI/meters.zig@@ -0,0 +1,135 @@+//! The readouts backed by the ENGINE's meters (#551): /context and+//! /session-info.+//!+//! Both used to be answered from `chars_in`/`chars_out`, two counters the TUI+//! incremented with the length of the text it had drawn. That is not a context+//! window and never was: it missed the system prompt, the tool catalog and+//! every tool result, it counted characters where the provider counts tokens,+//! and it only grew — a compaction that halved the real context left the+//! "context" line climbing. The engine already computes ContextMeter and+//! CostMeter for its own status line; those now arrive as a typed event and+//! this file renders them.+//!+//! Split out of dispatch.zig for the 600-line cap.++const std = @import("std");++const app = @import("app.zig");+const engine = @import("engine.zig");+const Model = app.Model;++/// `/context`.+pub fn contextInfo(self: *Model) void {+ const st = self.status orelse {+ self.push(.system, "context: not measured yet — the meter fills in once a turn reports usage") catch {};+ return;+ };+ if (!st.has_context) {+ self.pushFmt(.system, "context: {s} has not reported usage yet", .{st.model}) catch {};+ return;+ }+ self.pushFmt(.system, "context: {d} / {d} tokens ({d}%) · compacts at {d} · {d} cached", .{+ st.tokens,+ st.window,+ st.percent(),+ st.compact_at,+ st.cache_read,+ }) catch {};+}++/// `/session-info` — mode, model and turn count from the Model; context and+/// spend from the engine.+pub fn sessionInfo(self: *Model) void {+ var buf: [64]u8 = undefined;+ const ctx: []const u8 = if (self.contextPercent()) |p|+ (std.fmt.bufPrint(&buf, "{d}% context", .{p}) catch "context ?")+ else+ "context not measured";+ const spend: []const u8 = if (self.status) |st| switch (st.cost) {+ .hidden => "",+ .subscription => " · subscription",+ .unpriced => " · unpriced",+ .usd => " · see /cost",+ } else "";+ self.pushFmt(.system, "{s} · {s} · {d} turn(s) · {s}{s} · {s}", .{+ self.modeLabel(),+ engine.g_model_name,+ self.turns,+ ctx,+ spend,+ engine.g_cwd,+ }) catch {};+}++const testing = std.testing;++test "/context reports the engine's tokens, never a character count (#551)" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();++ // Before any turn there is nothing measured, and the line says so rather+ // than printing a 0 that reads like an empty context.+ contextInfo(&m);+ try testing.expect(std.mem.indexOf(u8, m.history.items[0].text, "not measured") != null);++ m.setStatus(.{+ .model = "sonnet",+ .provider_id = "anthropic",+ .has_context = true,+ .tokens = 12_345,+ .window = 200_000,+ .compact_at = 160_000,+ .cache_read = 2048,+ .cost = .{ .usd = 0.42 },+ });+ contextInfo(&m);+ const line = m.history.items[m.history.items.len - 1].text;+ try testing.expect(std.mem.indexOf(u8, line, "12345") != null);+ try testing.expect(std.mem.indexOf(u8, line, "200000") != null);+ try testing.expect(std.mem.indexOf(u8, line, "6%") != null);+ try testing.expect(std.mem.indexOf(u8, line, "160000") != null);+ try testing.expect(std.mem.indexOf(u8, line, "2048") != null);+ try testing.expect(std.mem.indexOf(u8, line, "chars") == null);+}++test "/session-info shows context share, not characters" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ m.turns = 3;++ sessionInfo(&m);+ try testing.expect(std.mem.indexOf(u8, m.history.items[0].text, "context not measured") != null);++ m.setStatus(.{+ .model = "gpt-5.6",+ .provider_id = "codex",+ .has_context = true,+ .tokens = 100_000,+ .window = 200_000,+ .cost = .subscription,+ });+ sessionInfo(&m);+ const line = m.history.items[m.history.items.len - 1].text;+ try testing.expect(std.mem.indexOf(u8, line, "3 turn(s)") != null);+ try testing.expect(std.mem.indexOf(u8, line, "50% context") != null);+ try testing.expect(std.mem.indexOf(u8, line, "subscription") != null);+ try testing.expect(std.mem.indexOf(u8, line, " in / ") == null);+}++test "a status the engine has not measured yields no percent anywhere" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ try testing.expect(m.contextPercent() == null);+ // A turn ran but the provider reported no usage: still nothing to show.+ m.setStatus(.{ .model = "local", .provider_id = "lmstudio" });+ try testing.expect(m.contextPercent() == null);+ // Measured: the share is the engine's, capped at 100.+ m.setStatus(.{ .model = "local", .provider_id = "lmstudio", .has_context = true, .tokens = 500, .window = 400 });+ try testing.expectEqual(@as(u64, 100), m.contextPercent().?);+ // Replacing the status frees the old strings — the leak checker owns this+ // assertion, but the identity is worth stating.+ try testing.expectEqualStrings("local", m.status.?.model);+}diff --git a/TUI/root.zig b/TUI/root.zigindex 8f660ba9..3349e7a1 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -20,6 +20,7 @@ pub const StreamBuf = engine.StreamBuf;pub const Event = engine.Event;pub const EventQueue = engine.EventQueue;pub const ToolEvent = engine.ToolEvent;+pub const Status = engine.Status;pub const TurnFn = engine.TurnFn;pub const ModelFn = engine.ModelFn;pub const CancelFn = engine.CancelFn;@@ -45,6 +46,7 @@ test {_ = catalog;_ = app;_ = @import("dispatch.zig");+ _ = @import("meters.zig");_ = @import("key.zig");_ = @import("key_orphan.zig");_ = @import("key_tests.zig");diff --git a/TUI/turn.zig b/TUI/turn.zigindex 574d4190..4729771d 100644--- a/TUI/turn.zig+++ b/TUI/turn.zig@@ -78,7 +78,6 @@ pub fn finishJob(self: *Model) void {drainEvents(self);_ = removePendingRows(self);if (job.result) |r| {- self.chars_out += r.len;self.push(.assistant, r) catch {};self.alloc.free(r);} else if (self.cancel_requested) {@@ -220,6 +219,8 @@ fn applyEvent(self: *Model, ev: engine.Event) void {// A mid-turn failover changes what the status bar must say. The event's// copy dies with this drain, so the Model takes ownership of the name// the global points at.+ // The engine's meters, measured against the request it actually sent.+ .status => |st| self.setStatus(st),.model_changed => |s| if (self.alloc.dupe(u8, s)) |owned| {if (self.model_override) |old| self.alloc.free(old);self.model_override = owned;diff --git a/src/repl_glue.zig b/src/repl_glue.zigindex 8d1abeb0..64bac1ff 100644--- a/src/repl_glue.zig+++ b/src/repl_glue.zig@@ -58,6 +58,13 @@ pub const ReplCtx = struct {/// built from the transcript it passes in, which is what `graff repl`'s/// scripted path still does.convo: ?*repl_convo.Conversation = null,+ /// The context meter, carried between turns (#551). A chat frontend builds+ /// a fresh Agent per turn, so leaving these on it reset the meter every+ /// turn — and with them the pre-send compaction gate, which reads exactly+ /// these numbers to decide when the window is nearly full.+ last_context_tokens: u64 = 0,+ context_local_tokens: u64 = 0,+ last_cache_read: u64 = 0,};/// The engine-owned conversation, in repl_convo.zig (move+alias, #123).diff --git a/src/repl_turn.zig b/src/repl_turn.zigindex 9aad4834..6b36933c 100644--- a/src/repl_turn.zig+++ b/src/repl_turn.zig@@ -102,6 +102,10 @@ pub fn turnAgent(.ultracode_mode = params.ultracode,.show_thinking = params.thinking,.strict = Policy.from(params).strict,+ // Session meters, not per-turn ones: see ReplCtx.+ .last_context_tokens = c.last_context_tokens,+ .context_local_tokens = c.context_local_tokens,+ .last_cache_read = c.last_cache_read,};try prompts.setSystemPrompts(&agent, sys, arena);return agent;@@ -170,7 +174,15 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tuc.provider = agent.provider;c.fallback_active = agent.fallback_active;c.fallback_blocked = agent.fallback_blocked;+ c.last_context_tokens = agent.last_context_tokens;+ c.context_local_tokens = agent.context_local_tokens;+ c.last_cache_read = agent.last_cache_read;returnHistory(c, &agent);+ // The engine's own status line, as a typed event (#551): the frontend+ // renders /context, /session-info and its footer from THIS rather than+ // from characters it counted. Emitted on every exit path, including the+ // early ends, because a stalled turn still moved the meters.+ agent.prompt() catch {};}const final = providers.runTurnWithFallback(&agent, &c.keys, arena, &sink.writer) catch |err| switch (err) {// A mid-stream stall (#134): the repl turn IS live (stream_quiet=false),diff --git a/src/tui_sink.zig b/src/tui_sink.zigindex 8349592f..e6c3a495 100644--- a/src/tui_sink.zig+++ b/src/tui_sink.zig@@ -177,10 +177,29 @@ fn emit(ctx: *anyopaque, ev: engine_sink.Stamped) void {.session_saved,.run_finished,=> {},- // The pre-turn status line. The TUI draws its own chrome from its own- // Model, so adopting this needs the context/cost meters to move into- // that Model first — a later slice of #551, not a silent drop here.- .prompt_ready => {},+ // The engine's own meters. The TUI kept character counters and called+ // them a context meter; these are the real numbers, and they are the+ // only ones that know about compaction, cached tokens and cost.+ .prompt_ready => |st| b.queue.push(.{ .status = .{+ .model = st.model,+ .provider_id = st.provider_id,+ .has_context = st.context != null,+ .tokens = if (st.context) |meter| meter.tokens else 0,+ .window = if (st.context) |meter| meter.window else 0,+ .compact_at = if (st.context) |meter| meter.compact_at else 0,+ .cache_read = st.cache_read,+ .cost = switch (st.cost) {+ .hidden => .hidden,+ .subscription => .subscription,+ .unpriced => .unpriced,+ .usd => |v| .{ .usd = v },+ },+ .fast = st.fast,+ .fallback = st.fallback,+ .plan = st.plan,+ .strict = st.strict,+ .ultracode = st.ultracode,+ } }),}}@@ -266,6 +285,62 @@ test "a refusal and a failover reach the frontend instead of being dropped" {try std.testing.expectEqualStrings("sonnet", evs[2].model_changed);}+test "the engine's meters reach the frontend instead of being dropped (#551)" {+ var qbuf: tui.EventQueue = .{};+ qbuf.attach(std.testing.allocator);+ defer qbuf.deinit();+ var sbuf: [8]u8 = undefined;+ var stream: repl.StreamBuf = .{ .buf = &sbuf };+ var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };+ forBridge(&bridge).emit(undefined, .{ .prompt_ready = .{+ .model = "gpt-5.6",+ .provider_id = "codex",+ .cwd = "~/src/graff",+ .privacy_label = "Privacy:Aggregate",+ .privacy = .aggregate,+ .effort = .high,+ .context = .{ .tokens = 12_345, .window = 200_000, .compact_at = 160_000 },+ .cache_read = 2048,+ .cost = .subscription,+ .plan = true,+ } });+ const evs = qbuf.drain();+ defer qbuf.free(evs);+ try std.testing.expectEqual(@as(usize, 1), evs.len);+ const st = evs[0].status;+ try std.testing.expectEqualStrings("gpt-5.6", st.model);+ try std.testing.expectEqualStrings("codex", st.provider_id);+ try std.testing.expect(st.has_context);+ try std.testing.expectEqual(@as(u64, 12_345), st.tokens);+ try std.testing.expectEqual(@as(u64, 160_000), st.compact_at);+ try std.testing.expectEqual(@as(u64, 2048), st.cache_read);+ try std.testing.expectEqual(@as(u64, 6), st.percent());+ try std.testing.expect(st.cost == .subscription);+ try std.testing.expect(st.plan);+}++test "a status with no usage yet says so rather than reporting a zero context" {+ var qbuf: tui.EventQueue = .{};+ qbuf.attach(std.testing.allocator);+ defer qbuf.deinit();+ var sbuf: [8]u8 = undefined;+ var stream: repl.StreamBuf = .{ .buf = &sbuf };+ var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };+ forBridge(&bridge).emit(undefined, .{ .prompt_ready = .{+ .model = "local",+ .provider_id = "lmstudio",+ .cwd = ".",+ .privacy_label = "",+ .privacy = .local,+ .cost = .unpriced,+ } });+ const evs = qbuf.drain();+ defer qbuf.free(evs);+ try std.testing.expect(!evs[0].status.has_context);+ try std.testing.expectEqual(@as(u64, 0), evs[0].status.percent());+ try std.testing.expect(evs[0].status.cost == .unpriced);+}+test "a capped preview never ends mid-character" {// 80 bytes of ASCII then a 3-byte glyph straddling the cap.var buf: [128]u8 = undefined;