Skip to content

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

Python

Merge branch 'perf/tui-event-pacing' into ui/tui-hover-affordance

Rach Pradhanf6fe9fb143d3
diff --cc TUI/keys.zig
index 1b76e83f,a72d1e01..2a8068ea
--- a/TUI/keys.zig
+++ b/TUI/keys.zig
@@@ -215,17 -215,20 +215,31 @@@ fn scrollbackKey(self: *Model, k: Key)
return .stay;
}
+ /// Apply `notches` of wheel scroll. One report and a whole coalesced momentum
+ /// run go through the SAME door (pacing.zig folds consecutive reports into one
+ /// delta), so a storm can never mean something a single report does not.
+ pub fn wheelScroll(self: *Model, notches: i32) Effect {
+ if (notches == 0) return .stay;
+ // The band is anchored to screen rows, so scrolling it would slide it onto
+ // other content — drop it and scroll.
+ selection.clear(self);
++ // An open picker or the completion menu owns the wheel: one notch is one
++ // ITEM there, never a scroll of the transcript underneath. A coalesced run
++ // steps once per notch, so a flick lands where the same notches typed
++ // slowly would.
++ const overlays = @import("overlays.zig");
++ const up = notches > 0;
++ if (overlays.wheel(self, up)) {
++ var left: u32 = @as(u32, @intCast(@abs(notches))) -| 1;
++ while (left > 0) : (left -= 1) _ = overlays.wheel(self, up);
++ return .stay;
++ }
+ scrollBy(self, notches *| @import("pacing.zig").lines_per_notch);
+ return .stay;
+ }
+
fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {
- if (ev.btn == 64 or ev.btn == 65) {
- // The band is anchored to screen rows, so scrolling it would slide it
- // onto other content — drop it and scroll.
- selection.clear(self);
- // An open picker or the completion menu owns the wheel: one notch is
- // one ITEM there, never a scroll of the transcript underneath.
- if (@import("overlays.zig").wheel(self, ev.btn == 64)) return .stay;
- scrollBy(self, if (ev.btn == 64) 3 else -3);
- return .stay;
- }
+ if (@import("pacing.zig").wheelNotch(.{ .mouse = ev })) |n| return wheelScroll(self, n);
// A drag or its release belongs to the selection; a press only ANCHORS one
// and falls through, so a plain click keeps its meaning (#529).
if (selection.mouse(self, ev)) return .stay;
diff --cc TUI/root.zig
index 87ec20a4,67153438..4a167a43
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@@ -81,8 -76,8 +81,9 @@@ test
_ = @import("overlays.zig");
_ = run_mod;
_ = @import("paint.zig");
+ _ = @import("scrollpaint.zig");
_ = @import("run_stall.zig");
+ _ = @import("pacing.zig");
_ = @import("traj.zig");
}
diff --cc TUI/run.zig
index 0b9d708e,de6cd99b..2b751a07
--- a/TUI/run.zig
+++ b/TUI/run.zig
@@@ -85,14 -89,11 +89,17 @@@ pub fn run
w.writeAll(enable_seq) catch {};
w.writeAll("\x1b]11;?\x07") catch {}; // background query -> auto light/dark (key.zig bg_report)
w.flush() catch {};
+ // Nothing may write to the real terminal around the frame painter: park
+ // fd 2 on .graff/tui-stderr.log so std.debug.print from any thread (a
+ // subagent's status card, a worker line) cannot scroll the alt screen and
+ // bleed stale rows through the diff paint. Every exit path unparks it.
+ restore_mod.muteStderr();
+ // Registered BEFORE the restore below, so LIFO puts the line on the normal
+ // screen after the alt screen is gone. No-op unless GRAFF_TUI_PAINT_STATS.
+ defer pacing.report(w);
traj.open(io);
defer {
+ restore_mod.unmuteStderr();
w.writeAll(restore_mod.seq) catch {};
w.flush() catch {};
}
@@@ -133,57 -140,75 +146,83 @@@
// Background engine ops (/compact, !cmd, @-file list) land here too —
// the same poll that keeps a turn from freezing the loop (#533).
bgop.finish(&m);
- const cols = @max(tty.cols(), @as(usize, 40));
- const rows = @max(tty.rows(), @as(usize, 12));
- const frame = render_mod.render(&m, gpa, cols, rows, m.now_ms) catch "tui: render error";
- defer gpa.free(frame);
- const hash = std.hash.Wyhash.hash(0, frame);
- // The diff painter trusts `prev` to be what is on screen. Two things
- // can make that a lie without changing a single byte of the frame: a
- // resize the loop never sees (SIGWINCH between tty.cols() and the
- // paint, or one that ends on the dimensions it started from — the
- // terminal still reflowed), and any async writer over the same tty (a
- // kitty image delete redrawing late). Neither moves the hash, so
- // neither would ever be repaired. A resize EVENT forces the full
- // clear-and-lay-down; the heartbeat forces a cheaper every-row rewrite
- // of the frame we already believe is up, which under ?2026 is
- // byte-identical output into a synchronized swap — visually a no-op.
- const resized = restore_mod.takeResized();
- const heal = resized or m.now_ms -| last_heal_ms >= heal_interval_ms;
- if (hash != last_hash or heal) {
- const has_gfx = std.mem.indexOf(u8, frame, "\x1b_G") != null;
- // The theme bg is painted per ROW, not baked into the frame, and
- // blank rows are byte-identical across themes/widths — the diff
- // path skips them, stranding old-bg rows after /theme or the
- // startup OSC-11 polarity flip, and stale columns after a
- // width-only resize. Both must force a full paint.
- const full = prev.len == 0 or rows != prev_rows or cols != prev_cols or m.theme_id != prev_theme or saw_gfx or has_gfx or resized;
- // Kitty images sit above the cell grid and survive \x1b[K / dirty
- // paints — delete before every redraw that might have shown one.
- // ?2026 synchronized output: the terminal buffers everything
- // between begin/end and swaps atomically, so a diff paint can
- // never show a half-updated frame (grok-build does the same).
- // Terminals without it ignore the pair — strictly no worse.
- // Scrolling the transcript moves CELLS, not the kitty images that
- // sit above the cell grid — and the self-heal exists precisely to
- // rewrite rows a scroll would skip. Both take the whole-screen
- // paths, so neither may reach the scroll fast path; `full` already
- // folds in graphics, resize and theme.
- const hint = if (full or heal) null else m.paint_hint;
- w.writeAll("\x1b[?2026h") catch {};
- if (saw_gfx or has_gfx) w.writeAll("\x1b_Ga=d,d=A,q=2\x1b\\") catch {};
- paint_mod.paint(w, frame, rows, cols, if (full) &.{} else prev, m.theme().bg, heal, hint) catch {};
- w.writeAll("\x1b[?2026l") catch {};
- w.flush() catch {};
- if (prev.len != 0) gpa.free(prev);
- prev = gpa.dupe(u8, frame) catch &.{};
- prev_rows = rows;
- prev_cols = cols;
- prev_theme = m.theme_id;
- last_hash = hash;
- saw_gfx = has_gfx;
- // Only a paint that rewrote EVERY row resets the heartbeat.
- if (full or heal) last_heal_ms = m.now_ms;
+ pacing.ticks += 1;
+ // At most ONE composed frame per tick, and while input keeps arriving,
+ // at most one per frame budget (pacing.zig). The storm signal is a
+ // backlog OR a stream still landing inside the storm window — a check
+ // for queued bytes alone misses momentum entirely, because on a loop
+ // this fast every report is read the instant it arrives and finds the
+ // queue empty behind it. Quiet, the frame is composed on the spot, so a
+ // single flick pays nothing. A skipped tick falls straight through to
+ // the drain below, so the frame that does land shows the LATEST scroll
- // position — the intermediate ones are never painted at all.
++ // position — the intermediate ones are never painted at all. A hover
++ // sweep is the same shape as a momentum flick and rides the same lane.
+ const more_pending = tty.poll(0);
+ const painted = pacing.shouldPaint(m.now_ms, last_frame_ms, last_input_ms, more_pending);
+ if (!painted) {
+ pacing.frames_skipped += 1;
+ } else {
+ last_frame_ms = m.now_ms;
+ pacing.frames += 1;
+ frame_blk: {
+ const cols = @max(tty.cols(), @as(usize, 40));
+ const rows = @max(tty.rows(), @as(usize, 12));
+ const frame = render_mod.render(&m, gpa, cols, rows, m.now_ms) catch break :frame_blk;
+ defer gpa.free(frame);
+ const hash = std.hash.Wyhash.hash(0, frame);
+ // The diff painter trusts `prev` to be what is on screen. Two
+ // things can make that a lie without changing a single byte of
+ // the frame: a resize the loop never sees (SIGWINCH between
+ // tty.cols() and the paint, or one that ends on the dimensions
+ // it started from — the terminal still reflowed), and any async
+ // writer over the same tty (a kitty image delete redrawing
+ // late). Neither moves the hash, so neither would ever be
+ // repaired. A resize EVENT forces the full clear-and-lay-down;
+ // the heartbeat forces a cheaper every-row rewrite of the frame
+ // we already believe is up, which under ?2026 is byte-identical
+ // output into a synchronized swap — visually a no-op.
+ const resized = restore_mod.takeResized();
+ const heal = resized or m.now_ms -| last_heal_ms >= heal_interval_ms;
+ if (hash != last_hash or heal) {
+ const has_gfx = std.mem.indexOf(u8, frame, "\x1b_G") != null;
+ // The theme bg is painted per ROW, not baked into the
+ // frame, and blank rows are byte-identical across
+ // themes/widths — the diff path skips them, stranding
+ // old-bg rows after /theme or the startup OSC-11 polarity
+ // flip, and stale columns after a width-only resize. Both
+ // must force a full paint.
+ const full = prev.len == 0 or rows != prev_rows or cols != prev_cols or m.theme_id != prev_theme or saw_gfx or has_gfx or resized;
+ // Kitty images sit above the cell grid and survive \x1b[K /
+ // dirty paints — delete before every redraw that might have
+ // shown one. ?2026 synchronized output: the terminal
+ // buffers everything between begin/end and swaps
+ // atomically, so a diff paint can never show a half-updated
+ // frame (grok-build does the same). Terminals without it
+ // ignore the pair — strictly no worse.
++ // Scrolling the transcript moves CELLS, not the kitty
++ // images that sit above the cell grid — and the self-heal
++ // exists precisely to rewrite rows a scroll would skip.
++ // Both take the whole-screen paths, so neither may reach
++ // the scroll fast path; `full` already folds in graphics,
++ // resize and theme.
++ const hint = if (full or heal) null else m.paint_hint;
+ w.writeAll("\x1b[?2026h") catch {};
+ if (saw_gfx or has_gfx) w.writeAll("\x1b_Ga=d,d=A,q=2\x1b\\") catch {};
- paint_mod.paint(w, frame, rows, cols, if (full) &.{} else prev, m.theme().bg, heal) catch {};
++ paint_mod.paint(w, frame, rows, cols, if (full) &.{} else prev, m.theme().bg, heal, hint) catch {};
+ w.writeAll("\x1b[?2026l") catch {};
+ w.flush() catch {};
+ pacing.paints += 1;
+ if (prev.len != 0) gpa.free(prev);
+ prev = gpa.dupe(u8, frame) catch &.{};
+ prev_rows = rows;
+ prev_cols = cols;
+ prev_theme = m.theme_id;
+ last_hash = hash;
+ saw_gfx = has_gfx;
+ // Only a paint that rewrote EVERY row resets the heartbeat.
+ if (full or heal) last_heal_ms = m.now_ms;
+ }
+ }
}
// Short wait while an unfinished escape sequence is pending: if
diff --cc TUI/scrollback_tests.zig
index 795e76d6,ede4694a..3dd4cd45
--- a/TUI/scrollback_tests.zig
+++ b/TUI/scrollback_tests.zig
@@@ -150,72 -91,3 +150,70 @@@ test "a failed call is marked, a refuse
try std.testing.expect(std.mem.indexOf(u8, text, "⊘ write") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "refused by plan mode") != null);
}
+
+test "an edit result that is a unified diff renders banded, not quoted (#diff)" {
+ const diff = @import("diff.zig");
- const theme_mod = @import("theme.zig");
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ const patch = "@@ -1,2 +1,2 @@\n const keep = 0;\n-const old = 1;\n+const new = 2;";
+ try m.pushTool(.{ .name = "edit_file", .detail = "TUI/run.zig" });
+ try m.pushTool(.{ .name = "edit_file", .detail = patch, .done = true });
+ m.toggleToolGroup(0);
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const th = m.theme();
+ const text = try scrollback.render(&m, arena.allocator(), 80, 0);
+ try std.testing.expect(std.mem.indexOf(u8, text, diff.addBg(false)) != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, diff.delBg(false)) != null);
+ // Banded, so the quoted-body rail is not used for this card.
+ try std.testing.expect(std.mem.indexOf(u8, text, "│ @@") == null);
+ var it = std.mem.splitScalar(u8, text, '\n');
+ while (it.next()) |ln| {
+ if (std.mem.indexOf(u8, ln, diff.delBg(false)) == null) continue;
+ // Every banded row closes: the card's own rows and the transcript
+ // under it must not inherit the wash.
+ try std.testing.expect(std.mem.endsWith(u8, ln, theme_mod.reset));
+ try std.testing.expect(std.mem.indexOf(u8, ln, th.bg) != null);
+ }
+ // A plain result is untouched — still the quoted body. It needs its own
+ // run, or the toggle below folds the diff card with it.
+ try m.push(.assistant, "and then");
+ try m.pushTool(.{ .name = "bash", .detail = "ls" });
+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
+ m.toggleToolGroup(3);
+ const plain = try scrollback.render(&m, arena.allocator(), 80, 0);
+ try std.testing.expect(std.mem.indexOf(u8, plain, "│ ok") != null);
+}
+
+test "end to end: a wrapped diff keeps its band and bleeds onto nothing (#diff)" {
+ // The whole pipeline — markdown → row() → theme.wrapToWidth — at a width
+ // that forces the deletion to fold. wrapToWidth re-opens whatever SGR is
+ // active at a break, so a band left open at EOL is what used to paint the
+ // equal line (and the prose) under a long deletion.
+ const diff = @import("diff.zig");
- const theme_mod = @import("theme.zig");
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.assistant, "here is the patch\n```diff\n@@ -1,2 +1,2 @@\n-const message = try std.fmt.allocPrint(gpa, \"a very long deleted line\", .{});\n const equal = 1;\n```\ntail prose");
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const text = try scrollback.render(&m, arena.allocator(), 40, 0);
+ var it = std.mem.splitScalar(u8, text, '\n');
+ var del_rows: usize = 0;
+ var folds: usize = 0;
+ while (it.next()) |ln| {
+ try std.testing.expect(theme_mod.visibleLen(ln) <= 40);
+ if (std.mem.indexOf(u8, ln, diff.delBg(false)) != null) {
+ del_rows += 1;
+ folds += @intFromBool(std.mem.indexOf(u8, ln, diff.gutter) != null);
+ try std.testing.expect(std.mem.endsWith(u8, ln, theme_mod.reset));
+ continue;
+ }
+ // Nothing else in the transcript wears the deletion wash.
+ try std.testing.expect(std.mem.indexOf(u8, ln, "const equal") == null or
+ std.mem.indexOf(u8, ln, diff.delBg(false)) == null);
+ }
+ try std.testing.expect(del_rows > 1); // the deletion really did fold
+ try std.testing.expectEqual(del_rows - 1, folds); // every fold is marked
+}
diff --cc scripts/eval-tier1.sh
index 1645c160,07848e1a..e32cf2ff
--- a/scripts/eval-tier1.sh
+++ b/scripts/eval-tier1.sh
@@@ -271,26 -256,14 +271,34 @@@ if wanted tuiguard; the
if python3 scripts/test-tui-resize-anchor.py zig-out/bin/graff; then :; else
record_fail tuiguard
fi
+ # grok-build's one-column rule for ANIMATED chrome: watches the live blink
+ # on a background op's pending row and fails if the label beside it moves a
+ # column, or if a frame is not East-Asian-Narrow. TUI/glyphs.zig holds the
+ # same law for the frame sets; this is the pixels.
+ if python3 scripts/test-tui-chrome-width.py zig-out/bin/graff; then :; else
+ record_fail tuiguard
+ fi
+ # Streaming markdown: the answer arrives as 1-3 codepoint deltas whose
+ # boundaries land mid-escape, mid-fence and mid-marker. Both the live tail
+ # and the settled row must be free of the model's own CR/SGR bytes.
+ if python3 scripts/test-tui-stream-markdown.py zig-out/bin/graff; then :; else
+ record_fail tuiguard
+ fi
+ # A wheel notch must be a scroll region + SU, not a screen rewrite — and a
+ # storm of them must still leave the screen equal to a forced full repaint.
+ # With the hint refused the probe fails on the FIRST notch (verified), so
+ # this is a gate on both halves, not a smoke test.
+ if python3 scripts/test-tui-scroll-paint.py zig-out/bin/graff; then :; else
+ record_fail tuiguard
+ fi
+ # Trackpad momentum must be COALESCED and BUDGETED, not queued. Drives 500
+ # SGR wheel reports twice — all at once, then spread over ~1s the way
+ # momentum really arrives — and reads the loop's own paint counters back.
+ # With the frame budget removed the paced storm paints 503 times instead of
+ # ~105, so this is a real gate, not a smoke test.
+ if python3 scripts/test-tui-event-pacing.py zig-out/bin/graff; then :; else
+ record_fail tuiguard
+ fi
fi
fi