graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Hold a logical scroll anchor across a width rewrap
Rach Pradhan5538a0b270a7
diff --git a/TUI/anchor.zig b/TUI/anchor.zignew file mode 100644index 00000000..de3223e5--- /dev/null+++ b/TUI/anchor.zig@@ -0,0 +1,280 @@+//! Logical scroll anchor across a width rewrap.+//!+//! `Model.scroll` is a distance from the BOTTOM of the transcript in visual+//! rows, so a width change — which rewraps every line under the viewport —+//! keeps the number and loses the content: the row that was on top becomes a+//! different row of a different entry, and the transcript jumps under the+//! user's eyes. grok-build fixes this by holding a LOGICAL position across the+//! rebuild instead of a row count, and so do we: before the rewrap, record+//! which history entry owned the top visible line and how far into that+//! entry's block the line sat; after it, put that same logical line back on+//! top. Presentation only — nothing here is engine state.++const std = @import("std");++const app = @import("app.zig");+const scrollback = @import("scrollback.zig");+const Model = app.Model;++/// Where the viewport was parked, in transcript terms rather than screen rows:+/// the history entry whose block the top visible line belonged to, plus that+/// line's ordinal WITHIN the block. Both survive a rewrap; a row index cannot.+pub const Anchor = struct { idx: usize, ordinal: usize };++/// The anchor for the top visible transcript line of the frame last painted at+/// `width`. Null when there is nothing to hold: an empty transcript, or a user+/// who is tailing — follow mode is already an anchor, and a better one (the+/// bottom), so a rewrap must not drag the viewport off it.+pub fn capture(self: *const Model, width: usize) ?Anchor {+ if (self.follow or width == 0 or self.history.items.len == 0) return null;+ const top = self.mid_skip;+ const idx = scrollback.indexAtVisual(self, top, width) orelse return null;+ const base = scrollback.visualOfIndex(self, idx, width) orelse return null;+ return .{ .idx = idx, .ordinal = top -| base };+}++/// The transcript row that shows the anchored logical line at `width`. A block+/// that rewrapped SHORTER clamps to its own last line, so the anchor stays+/// inside the entry it was taken from instead of sliding into the next one.+pub fn rowAt(self: *const Model, anc: Anchor, width: usize) usize {+ const base = scrollback.visualOfIndex(self, anc.idx, width) orelse return 0;+ const span = blockSpan(self, anc.idx, width, base);+ if (span == 0) return base;+ return base + @min(anc.ordinal, span - 1);+}++/// How many visual rows entry `idx`'s block occupies at `width`. Measured as+/// the gap to the next block rather than by re-rendering the entry, so a+/// collapsed or expanded tool RUN — which the row math treats as one unit —+/// is measured the same way the viewport lays it out.+fn blockSpan(self: *const Model, idx: usize, width: usize, base: usize) usize {+ const nxt = nextBlock(self, idx);+ if (nxt >= self.history.items.len) return scrollback.totalVisualLines(self, width) -| base;+ const nb = scrollback.visualOfIndex(self, nxt, width) orelse return 1;+ return nb -| base;+}++fn nextBlock(self: *const Model, idx: usize) usize {+ if (idx < self.history.items.len and self.history.items[idx].kind == .tool)+ return self.toolRun(idx).end;+ return idx + 1;+}++// ---------------------------------------------------------------------------++const render_mod = @import("render.zig");+const testing = std.testing;++/// Park the viewport so entry `idx`'s first row is the top visible line, using+/// only what a real frame leaves on the Model: after a render with scroll = 0+/// and follow off, `mid_skip` IS max_scroll. Fails loudly when the entry sits+/// too near the end to ever BE a top line — a silently mis-parked viewport+/// would make every assertion below vacuous.+fn park(m: *Model, width: usize, height: usize, idx: usize) !usize {+ m.follow = false;+ // Sync `last_term_width` FIRST so neither probe below is itself a rewrap —+ // parking is setup, not the behaviour under test.+ const sync = try render_mod.render(m, testing.allocator, width, height, 0);+ testing.allocator.free(sync);+ m.scroll = 0;+ const probe = try render_mod.render(m, testing.allocator, width, height, 0);+ testing.allocator.free(probe);+ const max_scroll = m.mid_skip;+ const want = scrollback.visualOfIndex(m, idx, width) orelse return error.NoSuchEntry;+ if (want > max_scroll) return error.EntryCannotBeTopLine;+ m.scroll = max_scroll - want;+ const frame = try render_mod.render(m, testing.allocator, width, height, 0);+ testing.allocator.free(frame);+ try testing.expectEqual(want, m.mid_skip);+ return want;+}++fn rewrap(m: *Model, width: usize, height: usize) ![]const u8 {+ return render_mod.render(m, testing.allocator, width, height, 0);+}++// `**` is avoided on purpose: this zig fmt mangles it. Ten words a line,+// seven lines — long enough that the entry spans several rows at 100 cols.+const wrapme = " wrapme wrapme wrapme wrapme wrapme wrapme wrapme wrapme wrapme wrapme";+const wrap_tail = wrapme ++ wrapme ++ wrapme ++ wrapme ++ wrapme ++ wrapme ++ wrapme;++fn fill(m: *Model, n: usize) !void {+ var i: usize = 0;+ while (i < n) : (i += 1) {+ try m.push(.assistant, "a long explanation line that fills the scrollback with content and wraps at every narrow width we test");+ }+}++test "a width rewrap keeps the anchored entry on the top row" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ try fill(&m, 30);+ try m.push(.user, "MARKERONE");+ try fill(&m, 30);++ const idx: usize = 30;+ _ = try park(&m, 100, 24, idx);+ try testing.expectEqual(idx, scrollback.indexAtVisual(&m, m.mid_skip, 100).?);++ // Every one of these widths rewraps the filler above the marker into a+ // different number of rows. Row-count scrolling drifts further on each+ // step; the logical anchor must not move at all. There is transcript to+ // spare above and below at every width here, so no edge clamp applies.+ for ([_]usize{ 72, 55, 41, 120, 64, 100 }) |w| {+ const frame = try rewrap(&m, w, 24);+ defer testing.allocator.free(frame);+ try testing.expectEqual(idx, scrollback.indexAtVisual(&m, m.mid_skip, w).?);+ try testing.expect(std.mem.indexOf(u8, frame, "MARKERONE") != null);+ }+}++test "an anchor inside a wrapped entry stays inside that entry" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ try fill(&m, 25);+ try m.push(.assistant, "WRAPME" ++ wrap_tail);+ try fill(&m, 25);++ const idx: usize = 25;+ const base = try park(&m, 100, 24, idx);+ // Park three rows INTO the long entry: the anchor now carries an ordinal.+ m.scroll -= 3;+ const at = try rewrap(&m, 100, 24);+ testing.allocator.free(at);+ try testing.expectEqual(base + 3, m.mid_skip);++ for ([_]usize{ 60, 44, 90, 40 }) |w| {+ const frame = try rewrap(&m, w, 24);+ defer testing.allocator.free(frame);+ // The row on top still belongs to the same logical entry — the ordinal+ // clamps into the rewrapped block rather than spilling past its end.+ try testing.expectEqual(idx, scrollback.indexAtVisual(&m, m.mid_skip, w).?);+ // Its head word is three rows above the viewport by construction; what+ // must be on screen is the block's own body.+ try testing.expect(std.mem.indexOf(u8, frame, "wrapme") != null);+ }+}++test "the top edge clamps: entry 0 stays pinned to row 0 when it widens" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ try m.push(.user, "FIRSTENTRY");+ try fill(&m, 24);++ _ = try park(&m, 50, 24, 0);+ try testing.expectEqual(@as(usize, 0), m.mid_skip);+ // Widening shortens the transcript; the anchor is row 0, so the viewport+ // must stay at the top rather than being flung to the bottom.+ for ([_]usize{ 80, 110, 46 }) |w| {+ const frame = try rewrap(&m, w, 24);+ defer testing.allocator.free(frame);+ try testing.expectEqual(@as(usize, 0), m.mid_skip);+ try testing.expect(std.mem.indexOf(u8, frame, "FIRSTENTRY") != null);+ }+}++test "the bottom edge clamps: a widened rewrap still shows the anchor" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ try fill(&m, 20);+ try m.push(.user, "TAILMARK");+ try fill(&m, 8);++ const idx: usize = 20;+ _ = try park(&m, 42, 24, idx);+ // Widening collapses the whole transcript into far fewer rows, so the+ // anchored row can no longer BE the top line: max_scroll saturates and the+ // viewport parks at the bottom. The anchor must still be on screen — the+ // failure this guards against is scrolling past it entirely.+ const frame = try rewrap(&m, 120, 24);+ defer testing.allocator.free(frame);+ try testing.expectEqual(@as(usize, 0), m.scroll);+ try testing.expect(std.mem.indexOf(u8, frame, "TAILMARK") != null);+ try testing.expect(scrollback.indexAtVisual(&m, m.mid_skip, 120).? <= idx);+}++test "a vertical-only resize keeps bottom-follow and never anchors" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ try fill(&m, 30);+ try m.push(.assistant, "TAILROW");++ for ([_]usize{ 24, 12, 40, 18 }) |h| {+ const frame = try rewrap(&m, 80, h);+ defer testing.allocator.free(frame);+ try testing.expect(m.follow);+ try testing.expectEqual(@as(usize, 0), m.scroll);+ try testing.expect(std.mem.indexOf(u8, frame, "TAILROW") != null);+ }+ // Height-only changes leave a SCROLLED viewport's distance-from-bottom+ // alone: nothing rewrapped, so there is nothing to re-anchor.+ _ = try park(&m, 80, 24, 8);+ const kept = m.scroll;+ const frame = try rewrap(&m, 80, 20);+ defer testing.allocator.free(frame);+ try testing.expectEqual(kept, m.scroll);+}++test "capture declines when the user is tailing or the transcript is empty" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ try testing.expect(capture(&m, 80) == null);+ try fill(&m, 4);+ m.follow = true;+ try testing.expect(capture(&m, 80) == null);+ m.follow = false;+ try testing.expect(capture(&m, 80) != null);+}++test "a collapsed tool run anchors as one block" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ try fill(&m, 25);+ try m.pushTool(.{ .name = "bash", .detail = "printf hello" });+ try m.pushTool(.{ .name = "bash", .detail = "hello", .done = true });+ try fill(&m, 25);++ const idx: usize = 25;+ _ = try park(&m, 100, 24, idx);+ try testing.expectEqual(idx, scrollback.indexAtVisual(&m, m.mid_skip, 100).?);+ for ([_]usize{ 62, 48, 96 }) |w| {+ const frame = try rewrap(&m, w, 24);+ defer testing.allocator.free(frame);+ // indexAtVisual maps anywhere in the run to its start — the anchored+ // block is the run, and the run is still what the top row shows.+ try testing.expectEqual(idx, scrollback.indexAtVisual(&m, m.mid_skip, w).?);+ try testing.expect(std.mem.indexOf(u8, frame, "Called") != null);+ }+}++test "without the anchor a width rewrap moves the top line" {+ // The bug this module exists for, pinned as a fact about the OLD policy:+ // holding `scroll` (a distance from the bottom) across a rewrap lands on a+ // different entry. If a future change makes plain row-count scrolling+ // width-stable on its own, this test says so out loud.+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ try fill(&m, 30);+ try m.push(.user, "MARKERONE");+ try fill(&m, 30);++ const idx: usize = 30;+ _ = try park(&m, 100, 24, idx);+ const kept = m.scroll;+ // Rewrap with the anchor bypassed: same width change, scroll restored to+ // exactly what the old code would have carried over.+ const frame = try rewrap(&m, 44, 24);+ testing.allocator.free(frame);+ m.scroll = kept;+ const naive = try rewrap(&m, 44, 24);+ defer testing.allocator.free(naive);+ try testing.expect(scrollback.indexAtVisual(&m, m.mid_skip, 44).? != idx);+}diff --git a/TUI/render.zig b/TUI/render.zigindex 8086592c..a347ddb8 100644--- a/TUI/render.zig+++ b/TUI/render.zig@@ -4,6 +4,7 @@const std = @import("std");+const anchor = @import("anchor.zig");const app = @import("app.zig");const chrome = @import("chrome.zig");const engine = @import("engine.zig");@@ -14,6 +15,17 @@ const welcome = @import("welcome.zig");const Model = app.Model;pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize, now_ms: u64) ![]const u8 {+ // A horizontal resize rewraps everything under the viewport, so the row+ // count in `scroll` stops meaning what it meant. Take a LOGICAL anchor off+ // the frame we last painted — read at the OLD width, before it is+ // overwritten — and restore the viewport onto it below. Only the+ // transcript is anchored this way: an overlay body scrolls too, but its+ // rows are not history entries.+ const rewrap: ?anchor.Anchor = if (width != self.last_term_width and+ (self.overlay == .none or self.overlay == .image))+ anchor.capture(self, self.last_term_width)+ else+ null;self.last_term_width = width;self.last_term_height = height;self.now_ms = now_ms;@@ -89,6 +101,10 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,} else {const max_scroll = n - view_h;if (self.follow) self.scroll = 0;+ // Put the anchored logical line back on the top row. Saturating: when+ // the rewrap pushed it past the last possible top line the viewport+ // parks at the bottom, which still shows it.+ if (rewrap) |anc| self.scroll = max_scroll -| anchor.rowAt(self, anc, width);if (self.scroll > max_scroll) self.scroll = max_scroll;const start = max_scroll - self.scroll;self.mid_skip = start;diff --git a/TUI/root.zig b/TUI/root.zigindex 3349e7a1..05e0c28a 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -69,6 +69,7 @@ test {_ = @import("effort.zig");_ = @import("sim.zig");_ = @import("render.zig");+ _ = @import("anchor.zig");_ = @import("tty.zig");_ = @import("restore.zig");_ = @import("files.zig");diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex 9ca8730d..5ae0e768 100644--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -242,6 +242,13 @@ if wanted tuiguard; thenif python3 scripts/test-tui-typed-events.py zig-out/bin/graff; then :; elserecord_fail tuiguardfi+ # The viewport must not jump when the terminal changes width: drives+ # TIOCSWINSZ across five widths mid-scroll and reads the screen back. With+ # the logical scroll anchor removed the marker leaves the screen on the+ # FIRST width change, so this is a real gate, not a smoke test.+ if python3 scripts/test-tui-resize-anchor.py zig-out/bin/graff; then :; else+ record_fail tuiguard+ fififidiff --git a/scripts/test-tui-resize-anchor.py b/scripts/test-tui-resize-anchor.pynew file mode 100644index 00000000..a73e834f--- /dev/null+++ b/scripts/test-tui-resize-anchor.py@@ -0,0 +1,252 @@+#!/usr/bin/env python3+"""Live proof: a horizontal resize must not move the transcript under the user.++grok-build holds a LOGICAL scroll anchor across a width rebuild — the entry the+top visible line belongs to, plus that line's ordinal inside the entry — so a+rewrap puts the same content back on top instead of the same ROW NUMBER. This+probe drives the real binary under a pty and proves it end to end:++ 1. boots `graff tui --yolo` in a scratch cwd with an EMPTY MCP config,+ 2. fills the transcript from `!printf` lines only (no model call, so the text+ on screen is known exactly), with one unique marker in the middle,+ 3. vertical sweep FIRST, while the user is tailing: the transcript must keep+ following the bottom, so the last line stays on screen at every height,+ 4. scrolls up (Ctrl+K) until the marker sits near the top of the viewport,+ 5. drives TIOCSWINSZ across five widths and asserts the marker is still on+ screen and has barely moved. Without an anchor, `scroll` is a distance+ from the bottom of a transcript whose row count just changed, so the+ marker slides away and off screen.++Usage: python3 scripts/test-tui-resize-anchor.py [path/to/graff]+ (default zig-out/bin/graff). Exit 0 = pass; skips (exit 0) with no pty.+"""+import os+import re+import sys+import tempfile+import time++# Absolutized BEFORE the fork: the child chdirs into its scratch workspace.+BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")+BOOT_MAX = 15.0+ROWS, COLS = 30, 100+# Printed through a printf FORMAT so the echoed command line never contains the+# marker itself — otherwise the sticky header (which pins the last prompt) would+# satisfy "the marker is on screen" without the transcript being anywhere near.+MARK = "ANCHORMARKKILO"+MARK_CMD = r"!printf 'ANCHOR%sKILO\n' MARK"+TAIL = "TAILROWOMEGA"+# Rewrapping the entries above the anchor can only shift a near-top line by the+# few rows those entries themselves gain or lose; the failure this guards+# against moves it by tens of rows or off screen entirely.+DRIFT = 4+++def drain(fd, seconds):+ # select-gated: a quiet pty blocks on read, and a blocking read here would+ # hang the probe on exactly the wedged states it exists to catch.+ import select+ out = b""+ end = time.time() + seconds+ while time.time() < end:+ r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))+ if not r:+ continue+ try:+ chunk = os.read(fd, 65536)+ except OSError:+ break+ if not chunk:+ break+ out += chunk+ return out+++def boot(fd):+ out = b""+ end = time.time() + BOOT_MAX+ while time.time() < end:+ out += drain(fd, 0.3)+ if b"\x1b[?1049h" in out:+ return out + drain(fd, 1.5)+ return out+++def resize(fd, rows, cols):+ import fcntl+ import struct+ import termios+ fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))+++def spawn(cwd, env_extra, rows=ROWS, cols=COLS):+ import pty+ pid, fd = pty.fork()+ if pid == 0:+ os.chdir(cwd)+ os.environ.update(env_extra)+ os.execv(BIN, [BIN, "tui", "--yolo"])+ # A pty forked without a size reports 0x0; the TUI would clamp to its 40x12+ # floor and every row index below would be measured against the wrong frame.+ resize(fd, rows, cols)+ return pid, fd+++def fresh_ws():+ ws = tempfile.mkdtemp(prefix="tui-anchor-")+ empty = os.path.join(ws, "empty-mcp.json")+ with open(empty, "w") as f:+ f.write('{"mcpServers": {}}')+ return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}+++def reap(pid, fd):+ import signal+ try:+ os.write(fd, b"\x11") # Ctrl+Q+ drain(fd, 3.0)+ except OSError:+ pass+ for sig in (signal.SIGTERM, signal.SIGKILL):+ try:+ os.kill(pid, sig)+ except OSError:+ pass+ try:+ os.waitpid(pid, 0)+ except OSError:+ pass+++def parse(stream):+ """Screen rows, in order, out of the last FULL repaint in `stream`.++ Between repaints the TUI rewrites only the rows that changed, addressing+ each with CSI row;1H — stripping those out of a diff stream gives row+ indices that are plausible and wrong. Any resize invalidates run.zig's diff+ baseline, so what follows one is a whole frame, top row first.+ """+ frame = stream.rsplit(b"\x1b[2J\x1b[H", 1)+ if len(frame) < 2:+ return None+ text = re.sub(rb"\x1b\][^\x07\x1b]*(\x07|\x1b\\)", b"", frame[1])+ text = re.sub(rb"\x1b\[[0-9;?<>]*[a-zA-Z]", b"", text)+ return [ln.decode(errors="replace") for ln in text.split(b"\r\n")]+++def frame_at(fd, rows, cols, settle=1.2):+ resize(fd, rows, cols)+ return parse(drain(fd, settle))+++def reread(fd):+ """A full frame at the current width, via a HEIGHT-only jiggle.++ Vertical resizes never take the anchor path, so reading the screen this way+ cannot itself perturb what the width sweep is about to measure.+ """+ resize(fd, ROWS - 1, COLS)+ drain(fd, 0.4)+ return frame_at(fd, ROWS, COLS)+++def find(rows, needle):+ # The sticky header pins the last user prompt at the top of the viewport;+ # a hit there is chrome, not the transcript.+ for i, ln in enumerate(rows or []):+ if needle in ln and "❯" not in ln:+ return i+ return None+++def run():+ ws, env = fresh_ws()+ pid, fd = spawn(ws, env)+ try:+ boot(fd)+ # Transcript content with no model call: `!` lines run in-session. Long+ # lines so every width below genuinely rewraps them.+ def block(tag):+ body = "filler line %s-%d padded out so that it rewraps at every width this probe drives"+ lines = "".join((body % (tag, k)) + r"\n" for k in range(3))+ os.write(fd, (r"!printf '" + lines + r"'" + "\r").encode())+ drain(fd, 1.5)++ for i in range(3):+ block(f"A{i}")+ os.write(fd, (MARK_CMD + "\r").encode())+ drain(fd, 1.5)+ # Enough transcript AFTER the marker that it starts off the top of the+ # viewport: the parking loop below then walks it in from the top edge,+ # which is the only way to put it near the anchored row from outside.+ for i in range(5):+ block(f"B{i}")+ os.write(fd, (r"!printf '" + TAIL + r"\n'" + "\r").encode())+ out = drain(fd, 2.5)+ if TAIL.encode() not in out:+ return "the transcript never showed the tail row (no `!` output)"++ # --- vertical only, while tailing: bottom-follow must hold -----------+ # Every step must CHANGE the height: an identical winsize is not a+ # resize, so no full repaint follows it and there is nothing to read.+ for h in (18, 34, 22, ROWS):+ rows = frame_at(fd, h, COLS)+ if rows is None:+ return f"no full repaint at height {h}"+ if find(rows, TAIL) is None:+ return f"a vertical resize to {h} rows dropped the tail row: follow broke"++ # --- park the marker near the top of the viewport ---------------------+ top = None+ for _ in range(30):+ os.write(fd, b"\x0b") # Ctrl+K: scroll one line towards older text+ drain(fd, 0.25)+ at = find(reread(fd), MARK)+ if at is not None:+ # It has just cleared the top edge. Two more lines put it clear+ # of the sticky header, which OCCLUDES the top two content rows+ # — a marker parked under the pin is invisible, not misplaced.+ os.write(fd, b"\x0b\x0b")+ drain(fd, 0.3)+ top = find(reread(fd), MARK)+ break+ if top is None:+ return f"scrolling never brought {MARK} into the upper viewport"++ # --- the width sweep --------------------------------------------------+ seen = [(COLS, top)]+ for w in (76, 58, 44, 92, COLS):+ rows = frame_at(fd, ROWS, w)+ if rows is None:+ return f"no full repaint at width {w}"+ at = find(rows, MARK)+ if at is None:+ return f"width {w} scrolled {MARK} off screen (anchor lost); seen={seen}"+ if abs(at - top) > DRIFT:+ return f"width {w} moved {MARK} from row {top} to {at}; seen={seen}"+ seen.append((w, at))+ print(f" widths/rows: {seen}")+ return None+ finally:+ reap(pid, fd)+++def main():+ if not os.path.exists(BIN):+ print(f"tui-resize-anchor: {BIN} not built — skipping")+ return 0+ try:+ import pty # noqa: F401+ except ImportError:+ print("tui-resize-anchor: no pty support here — skipping")+ return 0+ err = run()+ if err:+ print(f" ✗ resize-anchor: {err}")+ return 1+ print(" ✓ resize-anchor: the marker held its place across five widths")+ return 0+++if __name__ == "__main__":+ sys.exit(main())