Skip to content

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

Python

Scroll the transcript instead of repainting the screen for it

Rach Pradhana7040c8bab6f
diff --git a/TUI/app.zig b/TUI/app.zig
index edbd4c6c..6c18fac5 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -46,6 +46,21 @@ pub const Entry = struct {
pub const Effect = enum { stay, quit, background };
+/// The rows of a composed frame that a scroll actually MOVES: content only, no
+/// chrome. `off` is the transcript line the first of them shows, so comparing
+/// two consecutive frames' bands says whether the viewport merely slid — which
+/// is the one thing a row-against-row diff can never see (perf/tui-scroll-paint).
+/// `live` is false whenever there is nothing scrollable: the welcome pane, a
+/// transcript shorter than the viewport.
+pub const Band = struct {
+ live: bool = false,
+ /// First screen row of the band, 0-based.
+ top: usize = 0,
+ len: usize = 0,
+ /// Index, in the composed mid-lines, of the line on `top`.
+ off: usize = 0,
+};
+
pub const ESC_MS: u64 = 800;
pub const Model = struct {
@@ -107,6 +122,12 @@ pub const Model = struct {
prompt_origin: usize = 20,
/// How many mid-lines were clipped above the viewport.
mid_skip: usize = 0,
+ /// The scrollable band of the frame just composed, and the painter hint
+ /// derived from how it moved since the frame before it. Presentation state
+ /// for the diff painter's scroll fast path: render.zig is the only writer,
+ /// paint.zig the only reader, and both treat it as a claim to verify.
+ band: Band = .{},
+ paint_hint: ?@import("scrollpaint.zig").Hint = null,
now_ms: u64 = 0,
hist_idx: ?usize = null,
/// Newline-joined paths for the @-file picker, loaded once per session.
diff --git a/TUI/paint.zig b/TUI/paint.zig
index 9936faf3..ae0d5750 100644
--- a/TUI/paint.zig
+++ b/TUI/paint.zig
@@ -26,6 +26,7 @@
const std = @import("std");
const Io = std.Io;
+const scrollpaint = @import("scrollpaint.zig");
const theme_mod = @import("theme.zig");
/// Rewrite only rows that changed, so a drag-select on older transcript
@@ -39,6 +40,14 @@ const theme_mod = @import("theme.zig");
/// under synchronized output (?2026) it is visually a no-op —
/// but it is also the only thing that can repair a screen some
/// other writer, or a terminal-side reflow, has disturbed.
+/// `hint` set -> the composer believes the viewport merely SLID. Row i is
+/// then the wrong thing to compare row i against, and every
+/// row of the band reads as changed; scrollpaint.zig checks
+/// the claim against both frames and, when it holds, has the
+/// terminal do the sliding. It never writes on a refusal, so
+/// falling through here is always safe. The self-heal MUST
+/// bypass it: its whole job is to rewrite rows that are
+/// already correct, which is precisely what a scroll skips.
pub fn paint(
w: *Io.Writer,
frame: []const u8,
@@ -47,6 +56,7 @@ pub fn paint(
prev: []const u8,
bg: []const u8,
force: bool,
+ hint: ?scrollpaint.Hint,
) !void {
if (prev.len == 0) {
try w.writeAll(bg);
@@ -60,6 +70,11 @@ pub fn paint(
try w.flush();
return;
}
+ if (!force) {
+ if (hint) |h| {
+ if (try scrollpaint.tryPaint(w, frame, rows, cols, prev, bg, h)) return;
+ }
+ }
var row: usize = 0;
while (row < rows) : (row += 1) {
if (!force and !rowChanged(prev, frame, row)) continue;
@@ -72,7 +87,7 @@ pub fn paint(
/// One row, cursor already at its first column. See the file header: the
/// prologue makes the row's style self-contained, and the two shapes below are
/// the entire residue story.
-fn paintRow(w: *Io.Writer, ln: []const u8, cols: usize, bg: []const u8) !void {
+pub fn paintRow(w: *Io.Writer, ln: []const u8, cols: usize, bg: []const u8) !void {
try w.writeAll(row_prologue);
try w.writeAll(bg);
const vis = theme_mod.visibleLen(ln);
@@ -126,7 +141,7 @@ fn paintToBuf(a: std.mem.Allocator, frame: []const u8, rows: usize, cols: usize,
fn paintForced(a: std.mem.Allocator, frame: []const u8, rows: usize, cols: usize, prev: []const u8, force: bool) ![]u8 {
var aw = Io.Writer.Allocating.init(a);
errdefer aw.deinit();
- try paint(&aw.writer, frame, rows, cols, prev, test_bg, force);
+ try paint(&aw.writer, frame, rows, cols, prev, test_bg, force, null);
return aw.toOwnedSlice();
}
diff --git a/TUI/render.zig b/TUI/render.zig
index 9610947f..dbc8b598 100644
--- a/TUI/render.zig
+++ b/TUI/render.zig
@@ -9,6 +9,7 @@ const app = @import("app.zig");
const chrome = @import("chrome.zig");
const engine = @import("engine.zig");
const scrollback = @import("scrollback.zig");
+const scrollpaint = @import("scrollpaint.zig");
const selection = @import("selection.zig");
const theme_mod = @import("theme.zig");
const welcome = @import("welcome.zig");
@@ -29,6 +30,11 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
self.last_term_width = width;
self.last_term_height = height;
self.now_ms = now_ms;
+ // Where the scrollable band was last time, so the painter can be told the
+ // viewport SLID rather than left to conclude every row changed. Presentation
+ // state, and only ever a hint: paint.zig verifies it against the bytes.
+ const prev_band = self.band;
+ self.band = .{};
@import("turn.zig").drainEvents(self);
var arena_state = std.heap.ArenaAllocator.init(gpa);
@@ -156,18 +162,49 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
try out.appendSlice(ln);
try out.append('\n');
}
+ // The band is the part of the frame a wheel event MOVES: content rows
+ // only. The sticky header occludes the top of the viewport, so it is
+ // chrome that happens to sit inside it, and the composer, status bar
+ // and image card are below the end.
+ self.band = .{
+ .live = true,
+ .top = self.mid_origin + chrome_rows,
+ .len = view_h - chrome_rows,
+ .off = start + chrome_rows,
+ };
}
if (image_card.len > 0) {
try out.appendSlice(image_card);
if (image_card[image_card.len - 1] != '\n') try out.append('\n');
}
try out.appendSlice(bottom_block);
+ self.paint_hint = scrollHint(self, prev_band);
// Selection is a post-pass over the finished frame: the row builders stay
// unaware of it, and the band lands on screen rows exactly as the mouse
// reported them (#529).
return gpa.dupe(u8, try selection.paint(self, a, out.items, width));
}
+/// The delta the scrollable band moved by between the last frame and this one,
+/// when that is the ONLY thing that happened to it — the painter's scroll fast
+/// path. Null is always safe: it just means the ordinary row diff.
+fn scrollHint(self: *const Model, prev: app.Band) ?scrollpaint.Hint {
+ const cur = self.band;
+ if (!cur.live or !prev.live) return null;
+ // Geometry moved, so screen row N is not the same slot it was: a resize, an
+ // image card appearing, the sticky header engaging, an overlay opening.
+ if (cur.top != prev.top or cur.len != prev.len) return null;
+ if (cur.off == prev.off) return null;
+ // The drag-selection band is anchored to SCREEN rows (#529), so its
+ // inverse video does not travel with the content a hardware scroll moves.
+ // The wheel drops the band for exactly this reason; keyboard scrolling
+ // keeps it, and that case has to keep repainting.
+ if (self.sel.active or self.sel.pressed) return null;
+ const d = @as(isize, @intCast(cur.off)) - @as(isize, @intCast(prev.off));
+ if (@abs(d) >= cur.len) return null;
+ return .{ .top = cur.top, .len = cur.len, .delta = d };
+}
+
fn countLines(s: []const u8) usize {
if (s.len == 0) return 0;
return std.mem.count(u8, s, "\n") + 1;
@@ -388,6 +425,64 @@ test "debug overlay keeps the observability HUD and adds layout" {
try std.testing.expect(std.mem.indexOf(u8, text, "pending") != null);
}
+test "a wheel notch reports a scroll hint; anything else about the frame refuses one" {
+ const keys = @import("keys.zig");
+ const a = std.testing.allocator;
+ var m: Model = undefined;
+ m.setup(a);
+ defer m.deinit();
+ try m.push(.user, "how do I frobnicate the widget?");
+ var i: usize = 0;
+ while (i < 60) : (i += 1)
+ try m.pushFmt(.assistant, "explanation line {d}, long enough to fill the transcript", .{i});
+
+ // A first frame has nothing to compare against, and an idle one has not moved.
+ for (0..2) |_| {
+ a.free(try render(&m, a, 80, 24, 0));
+ try std.testing.expect(m.paint_hint == null);
+ }
+
+ // One wheel notch. The band slides by exactly the three content lines
+ // keys.zig moved the viewport, and keeps its geometry — which is the whole
+ // claim paint.zig acts on. `top` clears the sticky header: those rows are
+ // chrome occluding the viewport, and a hardware scroll must not move them.
+ _ = keys.handle(&m, .{ .mouse = .{ .btn = 64, .x = 1, .y = 5, .down = true } });
+ a.free(try render(&m, a, 80, 24, 0));
+ const h = m.paint_hint orelse return error.NoScrollHint;
+ try std.testing.expectEqual(@as(isize, -3), h.delta);
+ try std.testing.expectEqual(m.mid_origin + m.sticky_rows, h.top);
+ try std.testing.expectEqual(@as(usize, 2), m.sticky_rows);
+ try std.testing.expect(h.len >= 2 and h.top + h.len <= 24);
+
+ // A resize on the same frame as a scroll: every row below rewraps, so the
+ // band is not the same band and nothing about it may be claimed to slide.
+ keys.scrollBy(&m, 3);
+ a.free(try render(&m, a, 79, 24, 0));
+ try std.testing.expect(m.paint_hint == null);
+
+ // A live drag-selection band is anchored to SCREEN rows, so its inverse
+ // video does not travel with the content a hardware scroll would move.
+ a.free(try render(&m, a, 79, 24, 0));
+ m.sel.active = true;
+ keys.scrollBy(&m, 3);
+ a.free(try render(&m, a, 79, 24, 0));
+ try std.testing.expect(m.paint_hint == null);
+ m.sel.active = false;
+
+ // Scrolling all the way to the top clamps: the viewport stops moving, and
+ // a band that did not move is not a scroll.
+ m.scroll = 1_000_000;
+ a.free(try render(&m, a, 79, 24, 0));
+ a.free(try render(&m, a, 79, 24, 0));
+ try std.testing.expect(m.paint_hint == null);
+
+ // An overlay replaces the whole viewport — no band at all, so no hint even
+ // though the frame changed completely.
+ m.openOverlay(.help);
+ a.free(try render(&m, a, 79, 24, 0));
+ try std.testing.expect(m.paint_hint == null);
+}
+
test "the sticky header never pins a prompt over an overlay" {
var m: Model = undefined;
m.setup(std.testing.allocator);
diff --git a/TUI/restore.zig b/TUI/restore.zig
index f9a6fed3..9f5b9064 100644
--- a/TUI/restore.zig
+++ b/TUI/restore.zig
@@ -8,11 +8,17 @@ const std = @import("std");
const builtin = @import("builtin");
const tty = @import("tty.zig");
-/// Inverse of run.zig's enable string: modifyOtherKeys off, kitty pop,
-/// autowrap on, mouse off (1006/1003/1000), bracketed paste off, cursor
-/// visible. The alt-screen exit stays last so everything lands on the
-/// primary screen.
-pub const seq = "\x1b[?2026l\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l";
+/// Inverse of run.zig's enable string: synchronized update closed, scroll
+/// margins dropped, modifyOtherKeys off, kitty pop, autowrap on, mouse off
+/// (1006/1003/1000), bracketed paste off, cursor visible. The alt-screen exit
+/// stays last so everything lands on the primary screen.
+///
+/// The first two are not inverses of anything in the enable string — they undo
+/// state a paint sets and clears WITHIN itself (scrollpaint.zig brackets a
+/// DECSTBM region exactly as run.zig brackets ?2026). A crash lands between the
+/// two halves often enough to matter, and margins left set turn every later
+/// newline in the user's shell into a scroll inside a window that is gone.
+pub const seq = "\x1b[?2026l\x1b[r\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l";
/// Every signal that ends the process with the terminal still ours. The first
/// `first_fault` are the polite ones (a human or an init system asking us to
diff --git a/TUI/root.zig b/TUI/root.zig
index 453e6273..cbdf2d60 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -76,6 +76,7 @@ test {
_ = @import("overlays.zig");
_ = run_mod;
_ = @import("paint.zig");
+ _ = @import("scrollpaint.zig");
_ = @import("run_stall.zig");
_ = @import("traj.zig");
}
diff --git a/TUI/run.zig b/TUI/run.zig
index 916f346b..4b0c47cd 100644
--- a/TUI/run.zig
+++ b/TUI/run.zig
@@ -158,9 +158,15 @@ pub fn run(
// 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 {};
if (prev.len != 0) gpa.free(prev);
@@ -308,7 +314,7 @@ pub fn run(
const rows = @max(tty.rows(), @as(usize, 12));
if (render_mod.render(&m, gpa, cols, rows, m.now_ms)) |frame| {
defer gpa.free(frame);
- paint_mod.paint(w, frame, rows, cols, &.{}, m.theme().bg, true) catch {};
+ paint_mod.paint(w, frame, rows, cols, &.{}, m.theme().bg, true, null) catch {};
w.flush() catch {};
} else |_| {}
const start = m.now_ms;
@@ -431,4 +437,9 @@ test "the loop self-heals: a resize EVENT and a periodic sweep force a repaint"
// to run even when the frame hash has not moved.
try std.testing.expect(std.mem.indexOf(u8, src, "hash != last_hash or heal") != null);
try std.testing.expect(heal_interval_ms > 0);
+ // ...and the self-heal must never be served by the scroll fast path, whose
+ // whole point is to SKIP rows that are already correct — which is exactly
+ // the set of rows a heal exists to rewrite. Same for `full`, which folds in
+ // kitty graphics (pixels do not move when cells scroll), resize and theme.
+ try std.testing.expect(std.mem.indexOf(u8, src, "if (full or heal) null else m.paint_hint") != null);
}
diff --git a/TUI/scrollpaint.zig b/TUI/scrollpaint.zig
new file mode 100644
index 00000000..9dc74092
--- /dev/null
+++ b/TUI/scrollpaint.zig
@@ -0,0 +1,462 @@
+//! Scroll-aware painting: the fast path out of the diff painter.
+//!
+//! The diff painter compares screen row i to the PREVIOUS frame's row i. That
+//! is exactly right for a token arriving or a spinner ticking, and exactly
+//! wrong for a wheel event: sliding the transcript by one line makes every row
+//! of the viewport differ from the row above it, so a one-line scroll repaints
+//! the entire screen. At 3 lines per wheel notch and a notch every few
+//! milliseconds that is the whole frame, over and over, down the pty.
+//!
+//! A terminal can do the sliding itself. Set a scroll region over the band
+//! that actually moved (DECSTBM), emit SU/SD, drop the region, and only the
+//! rows the scroll EXPOSED need bytes — plus whatever chrome legitimately
+//! changed, which the ordinary row diff still handles.
+//!
+//! The danger is emitting a hardware scroll when the screen did not, in fact,
+//! merely scroll. So this module never trusts the hint on its own: render.zig
+//! reports the delta it believes the band moved by, and `plan` VERIFIES it
+//! against the bytes of both frames — every row that would survive the shift
+//! must already hold what the new frame wants there. Anything else in the band
+//! (a fold toggling, a tool row finishing, a rewrap, a live token, an image
+//! card resizing the viewport) breaks that equality and the caller falls back
+//! to the full diff. Cases the verification cannot see — a self-heal repaint,
+//! a resize, kitty images on screen, a live selection band anchored to SCREEN
+//! rows rather than to content — are refused before we get here.
+
+const std = @import("std");
+const Io = std.Io;
+
+const paint = @import("paint.zig");
+
+/// What render.zig believes the last two frames did to the scrollable band.
+/// `delta` counts CONTENT lines: positive means the viewport moved further
+/// down the transcript, so the band's content slides UP the screen (SU).
+pub const Hint = struct {
+ /// First screen row of the band, 0-based. Sticky header rows are chrome
+ /// and sit ABOVE this; the composer and status bar sit below the end.
+ top: usize,
+ len: usize,
+ delta: isize,
+};
+
+/// Terminals taller than this fall back to the diff path rather than grow the
+/// stack. Nothing in the TUI is fast enough to care at that size anyway.
+const max_rows = 256;
+
+const Plan = struct {
+ /// Band rows the scroll exposes, as absolute screen rows.
+ first_exposed: usize,
+ count: usize,
+ up: bool,
+};
+
+/// Frame lines indexed once. The diff painter's nthLine rescans from byte 0
+/// for every row, which is O(rows x frame) per paint; the verification below
+/// touches every row, so it does the split once instead.
+const Lines = struct {
+ buf: [max_rows][]const u8 = undefined,
+ n: usize = 0,
+
+ fn index(s: []const u8, rows: usize) Lines {
+ var l: Lines = .{};
+ var it = std.mem.splitScalar(u8, s, '\n');
+ while (it.next()) |ln| {
+ if (l.n >= rows or l.n >= max_rows) break;
+ l.buf[l.n] = ln;
+ l.n += 1;
+ }
+ return l;
+ }
+
+ fn at(self: *const Lines, i: usize) []const u8 {
+ return if (i < self.n) self.buf[i] else "";
+ }
+};
+
+/// Everything about a hint that can be judged from the hint alone, so the two
+/// line indexes below are never built for a frame that cannot use them.
+fn viable(rows: usize, h: Hint) bool {
+ if (h.delta == 0 or h.len < 2 or rows > max_rows) return false;
+ if (h.top + h.len > rows) return false;
+ // A scroll that clears the whole band exposes every row of it: the region
+ // dance would be pure overhead on top of the same repaint.
+ return @abs(h.delta) < h.len;
+}
+
+/// Decide, writing nothing. Returns the exposed-row plan when a hardware
+/// scroll is provably equivalent to repainting the band, and null otherwise —
+/// a null here is never a correctness risk, only a missed optimisation.
+fn plan(rows: usize, h: Hint, cur: *const Lines, old: *const Lines) ?Plan {
+ if (!viable(rows, h)) return null;
+ const mag: usize = @abs(h.delta);
+ const up = h.delta > 0;
+ const kept = h.len - mag;
+ var j: usize = 0;
+ while (j < kept) : (j += 1) {
+ const dst = if (up) j else j + mag;
+ const src = if (up) j + mag else j;
+ if (!std.mem.eql(u8, cur.at(h.top + dst), old.at(h.top + src))) return null;
+ }
+ return .{
+ .first_exposed = h.top + (if (up) kept else 0),
+ .count = mag,
+ .up = up,
+ };
+}
+
+/// Paint `frame` over `prev` as a scroll plus its exposed rows. Returns false
+/// WITHOUT writing a byte when the hint does not hold up, so the caller can
+/// fall through to the ordinary diff.
+pub fn tryPaint(
+ w: *Io.Writer,
+ frame: []const u8,
+ rows: usize,
+ cols: usize,
+ prev: []const u8,
+ bg: []const u8,
+ h: Hint,
+) !bool {
+ if (!viable(rows, h)) return false;
+ const cur = Lines.index(frame, rows);
+ const old = Lines.index(prev, rows);
+ const p = plan(rows, h, &cur, &old) orelse return false;
+
+ // The rows the scroll opens up are filled with the ACTIVE background, not
+ // the theme's, so establish it before the region moves. (Under ?2026 the
+ // whole thing swaps atomically, but a terminal without it would flash.)
+ try w.writeAll(paint.row_prologue);
+ try w.writeAll(bg);
+ // DECSTBM is 1-based and inclusive. It also homes the cursor, which costs
+ // nothing here: every row painted below addresses itself with CUP.
+ try w.print("\x1b[{d};{d}r", .{ h.top + 1, h.top + h.len });
+ if (p.up) try w.print("\x1b[{d}S", .{p.count}) else try w.print("\x1b[{d}T", .{p.count});
+ // Drop the region immediately. Left set, an LF anywhere later — a panic
+ // message, the restore sequence — would scroll inside it instead of the
+ // screen, and the margins survive the alt-screen exit.
+ try w.writeAll("\x1b[r");
+
+ var e: usize = 0;
+ while (e < p.count) : (e += 1) {
+ const r = p.first_exposed + e;
+ try w.print("\x1b[{d};1H", .{r + 1});
+ try paint.paintRow(w, cur.at(r), cols, bg);
+ }
+ // The band moved; nothing else did. Chrome that changed for its own
+ // reasons — the sticky header now pinning a different prompt, a scroll
+ // indicator, the composer — is still an ordinary row diff.
+ var r: usize = 0;
+ while (r < rows) : (r += 1) {
+ if (r >= h.top and r < h.top + h.len) continue;
+ if (std.mem.eql(u8, cur.at(r), old.at(r))) continue;
+ try w.print("\x1b[{d};1H", .{r + 1});
+ try paint.paintRow(w, cur.at(r), cols, bg);
+ }
+ try w.flush();
+ return true;
+}
+
+// ------------------------------------------------------------------ tests
+
+const test_bg = "\x1b[48;2;20;20;20m";
+
+fn emit(a: std.mem.Allocator, frame: []const u8, rows: usize, cols: usize, prev: []const u8, h: Hint) !?[]u8 {
+ var aw = Io.Writer.Allocating.init(a);
+ errdefer aw.deinit();
+ if (!try tryPaint(&aw.writer, frame, rows, cols, prev, test_bg, h)) {
+ aw.deinit();
+ return null;
+ }
+ return try aw.toOwnedSlice();
+}
+
+/// A frame with two chrome rows on top, a scrollable band, and two chrome rows
+/// at the bottom. `off` is the content offset of the band's first row.
+fn frameAt(a: std.mem.Allocator, off: usize, rows: usize, band_top: usize, band_len: usize, chrome: []const u8) ![]const u8 {
+ var out = std.array_list.Managed(u8).init(a);
+ var r: usize = 0;
+ while (r < rows) : (r += 1) {
+ if (r > 0) try out.append('\n');
+ const line = if (r >= band_top and r < band_top + band_len)
+ try std.fmt.allocPrint(a, "content line {d} of the transcript", .{off + r - band_top})
+ else
+ try std.fmt.allocPrint(a, "{s} chrome row {d}", .{ chrome, r });
+ try out.appendSlice(line);
+ }
+ return out.items;
+}
+
+test "a one-line scroll costs one SU and the rows it exposed, not the screen" {
+ const a = std.testing.allocator;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const ar = arena.allocator();
+ const rows: usize = 24;
+ const cols: usize = 80;
+ const top: usize = 3; // top bar + sticky header + separator
+ const len: usize = 18;
+ const before = try frameAt(ar, 100, rows, top, len, "same");
+ const after = try frameAt(ar, 101, rows, top, len, "same");
+ const scrolled = (try emit(ar, after, rows, cols, before, .{ .top = top, .len = len, .delta = 1 })).?;
+ // Exactly one scroll, in the right direction, over the right region.
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, scrolled, "\x1b[1S"));
+ try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, scrolled, "\x1b[1T"));
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, scrolled, "\x1b[4;21r"));
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, scrolled, "\x1b[r"));
+ // ...and exactly one row of cells: the one the scroll exposed at the bottom.
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, scrolled, "\x1b[21;1H"));
+ // ...and that is the ONLY row addressed at all: the other 23 kept their cells.
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, scrolled, ";1H"));
+ // The budget. A full repaint of the same frame is the thing this replaces.
+ var aw = Io.Writer.Allocating.init(ar);
+ try paint.paint(&aw.writer, after, rows, cols, before, test_bg, true, null);
+ const full = aw.written();
+ try std.testing.expect(full.len > 1000); // sanity: a real 80x24 repaint
+ if (scrolled.len * 4 >= full.len) {
+ std.debug.print("scroll paint {d} bytes vs full repaint {d}\n", .{ scrolled.len, full.len });
+ return error.ScrollPaintTooExpensive;
+ }
+}
+
+test "scrolling the other way is a single SD over the same region" {
+ const a = std.testing.allocator;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const ar = arena.allocator();
+ const before = try frameAt(ar, 100, 24, 3, 18, "same");
+ const after = try frameAt(ar, 97, 24, 3, 18, "same");
+ const out = (try emit(ar, after, 24, 80, before, .{ .top = 3, .len = 18, .delta = -3 })).?;
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, out, "\x1b[3T"));
+ try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, out, "S"));
+ // Three rows exposed, and they are the TOP three of the band.
+ for ([_][]const u8{ "\x1b[4;1H", "\x1b[5;1H", "\x1b[6;1H" }) |cup| {
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, out, cup));
+ }
+ try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[7;1H") == null);
+}
+
+test "chrome that changed on the same frame is still repainted" {
+ const a = std.testing.allocator;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const ar = arena.allocator();
+ // The sticky header now pins a different prompt and the status bar moved:
+ // both live OUTSIDE the band, so the scroll cannot carry them.
+ const before = try frameAt(ar, 100, 24, 3, 18, "old");
+ const after = try frameAt(ar, 101, 24, 3, 18, "new");
+ const out = (try emit(ar, after, 24, 80, before, .{ .top = 3, .len = 18, .delta = 1 })).?;
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, out, "\x1b[1S"));
+ for ([_][]const u8{ "\x1b[1;1H", "\x1b[2;1H", "\x1b[3;1H", "\x1b[22;1H", "\x1b[23;1H", "\x1b[24;1H" }) |cup| {
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, out, cup));
+ }
+ try std.testing.expect(std.mem.indexOf(u8, out, "new chrome row 0") != null);
+}
+
+test "a hint the frames do not bear out is refused without writing a byte" {
+ const a = std.testing.allocator;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const ar = arena.allocator();
+ const before = try frameAt(ar, 100, 24, 3, 18, "same");
+ const after = try frameAt(ar, 101, 24, 3, 18, "same");
+ // Wrong magnitude, wrong direction, a band the frame never moved, a delta
+ // that clears the band, a band running off the screen: all refused.
+ for ([_]Hint{
+ .{ .top = 3, .len = 18, .delta = 2 },
+ .{ .top = 3, .len = 18, .delta = -1 },
+ .{ .top = 3, .len = 18, .delta = 18 },
+ .{ .top = 3, .len = 18, .delta = 0 },
+ .{ .top = 3, .len = 30, .delta = 1 },
+ .{ .top = 2, .len = 18, .delta = 1 },
+ }) |h| {
+ try std.testing.expect((try emit(ar, after, 24, 80, before, h)) == null);
+ }
+ // A fold toggling inside the band on the same frame as the scroll: the
+ // rows that "survive" no longer match, so the scroll is off the table.
+ var folded = std.array_list.Managed(u8).init(ar);
+ var it = std.mem.splitScalar(u8, after, '\n');
+ var r: usize = 0;
+ while (it.next()) |ln| : (r += 1) {
+ if (r > 0) try folded.append('\n');
+ try folded.appendSlice(if (r == 9) "the tool run just expanded" else ln);
+ }
+ try std.testing.expect((try emit(ar, folded.items, 24, 80, before, .{ .top = 3, .len = 18, .delta = 1 })) == null);
+}
+
+test "a selection band dropped by the same wheel notch blocks the scroll" {
+ const a = std.testing.allocator;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const ar = arena.allocator();
+ // The wheel CLEARS the drag band and scrolls in one event (keys.zig): the
+ // band is anchored to screen rows, so it cannot ride the scroll. render.zig
+ // refuses the hint while a band is live, but the frame AFTER it clears is
+ // an ordinary frame with an ordinary hint — and the screen it is painted
+ // over still has inverse video on rows the scroll would carry. Bytes catch
+ // it: an SGR-only difference is a difference.
+ const clean_prev = try frameAt(ar, 100, 24, 3, 18, "same");
+ var banded = std.array_list.Managed(u8).init(ar);
+ var it = std.mem.splitScalar(u8, clean_prev, '\n');
+ var r: usize = 0;
+ while (it.next()) |ln| : (r += 1) {
+ if (r > 0) try banded.append('\n');
+ if (r >= 6 and r <= 8) try banded.appendSlice("\x1b[7m");
+ try banded.appendSlice(ln);
+ if (r >= 6 and r <= 8) try banded.appendSlice("\x1b[27m");
+ }
+ const after = try frameAt(ar, 101, 24, 3, 18, "same");
+ const h: Hint = .{ .top = 3, .len = 18, .delta = 1 };
+ // Over the CLEAN screen the scroll is fine; over the banded one it is not.
+ try std.testing.expect((try emit(ar, after, 24, 80, clean_prev, h)) != null);
+ try std.testing.expect((try emit(ar, after, 24, 80, banded.items, h)) == null);
+}
+
+/// A terminal that also knows DECSTBM / SU / SD — the two sequences the diff
+/// painter's own screen model never had to understand.
+const Screen = struct {
+ rows: usize,
+ cols: usize,
+ cells: []u8,
+ row: usize = 0,
+ col: usize = 0,
+ top: usize = 0,
+ bot: usize,
+
+ fn init(a: std.mem.Allocator, rows: usize, cols: usize) !Screen {
+ const cells = try a.alloc(u8, rows * cols);
+ @memset(cells, ' ');
+ return .{ .rows = rows, .cols = cols, .cells = cells, .bot = rows - 1 };
+ }
+
+ fn at(self: *Screen, r: usize, c: usize) *u8 {
+ return &self.cells[r * self.cols + c];
+ }
+
+ fn rowSlice(self: *Screen, r: usize) []u8 {
+ return self.cells[r * self.cols ..][0..self.cols];
+ }
+
+ fn scroll(self: *Screen, n: usize, up: bool) void {
+ var k: usize = 0;
+ while (k < n) : (k += 1) {
+ if (up) {
+ var r = self.top;
+ while (r < self.bot) : (r += 1) @memcpy(self.rowSlice(r), self.rowSlice(r + 1));
+ @memset(self.rowSlice(self.bot), ' ');
+ } else {
+ var r = self.bot;
+ while (r > self.top) : (r -= 1) @memcpy(self.rowSlice(r), self.rowSlice(r - 1));
+ @memset(self.rowSlice(self.top), ' ');
+ }
+ }
+ }
+
+ fn feed(self: *Screen, s: []const u8) void {
+ var i: usize = 0;
+ while (i < s.len) {
+ if (s[i] == 0x1b) {
+ const e = @import("theme.zig").skipEsc(s, i);
+ self.control(s[i..e]);
+ i = e;
+ continue;
+ }
+ if (s[i] == '\r') {
+ self.col = 0;
+ } else if (s[i] == '\n') {
+ self.row += 1;
+ } else if (self.row < self.rows and self.col < self.cols) {
+ self.at(self.row, self.col).* = s[i];
+ self.col += 1;
+ }
+ i += 1;
+ }
+ }
+
+ fn control(self: *Screen, seq: []const u8) void {
+ if (seq.len < 3 or seq[1] != '[') return;
+ const final = seq[seq.len - 1];
+ const body = seq[2 .. seq.len - 1];
+ var it = std.mem.splitScalar(u8, body, ';');
+ const p0 = std.fmt.parseInt(usize, it.first(), 10) catch 0;
+ switch (final) {
+ 'H' => {
+ self.row = if (p0 > 0) p0 - 1 else 0;
+ self.col = 0;
+ },
+ 'J' => if (std.mem.eql(u8, body, "2")) {
+ @memset(self.cells, ' ');
+ self.row = 0;
+ self.col = 0;
+ },
+ 'K' => if (self.row < self.rows) {
+ var c = self.col;
+ while (c < self.cols) : (c += 1) self.at(self.row, c).* = ' ';
+ },
+ 'r' => {
+ const p1 = std.fmt.parseInt(usize, it.next() orelse "", 10) catch 0;
+ self.top = if (p0 > 0) p0 - 1 else 0;
+ self.bot = if (p1 > 0 and p1 <= self.rows) p1 - 1 else self.rows - 1;
+ self.row = self.top;
+ self.col = 0;
+ },
+ 'S' => self.scroll(@max(p0, 1), true),
+ 'T' => self.scroll(@max(p0, 1), false),
+ else => {},
+ }
+ }
+};
+
+test "a scroll storm leaves the screen exactly where a full repaint would" {
+ const a = std.testing.allocator;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const ar = arena.allocator();
+ const rows: usize = 24;
+ const cols: usize = 80;
+ const top: usize = 3;
+ const len: usize = 18;
+ var screen = try Screen.init(ar, rows, cols);
+ var off: usize = 200;
+ var cur = try frameAt(ar, off, rows, top, len, "same");
+ // Lay the first frame down in full, then scroll it around.
+ {
+ var aw = Io.Writer.Allocating.init(ar);
+ try paint.paint(&aw.writer, cur, rows, cols, "", test_bg, false, null);
+ screen.feed(aw.written());
+ }
+ var took: usize = 0;
+ for ([_]isize{ 3, 3, 3, -1, -3, 7, -7, 1, 1, 1, 1, -17, 17, 2, -2 }) |d| {
+ const next_off: usize = @intCast(@as(isize, @intCast(off)) + d);
+ const next = try frameAt(ar, next_off, rows, top, len, "same");
+ const out = try emit(ar, next, rows, cols, cur, .{ .top = top, .len = len, .delta = d });
+ if (out) |bytes| {
+ screen.feed(bytes);
+ took += 1;
+ } else {
+ // The fallback the caller would take.
+ var aw = Io.Writer.Allocating.init(ar);
+ try paint.paint(&aw.writer, next, rows, cols, cur, test_bg, false, null);
+ screen.feed(aw.written());
+ }
+ off = next_off;
+ cur = next;
+ }
+ // Most of the storm really did take the scroll path...
+ try std.testing.expect(took >= 10);
+ // ...and a forced full repaint of the final frame changes nothing at all.
+ var truth = try Screen.init(ar, rows, cols);
+ {
+ var aw = Io.Writer.Allocating.init(ar);
+ try paint.paint(&aw.writer, cur, rows, cols, "", test_bg, false, null);
+ truth.feed(aw.written());
+ }
+ var r: usize = 0;
+ while (r < rows) : (r += 1) {
+ if (std.mem.eql(u8, screen.rowSlice(r), truth.rowSlice(r))) continue;
+ std.debug.print("row {d}:\n screen {s}\n truth {s}\n", .{ r, screen.rowSlice(r), truth.rowSlice(r) });
+ return error.ScrollStormLeftResidue;
+ }
+ // And the scroll region is back to the whole screen, so nothing later
+ // scrolls inside a stale margin.
+ try std.testing.expectEqual(@as(usize, 0), screen.top);
+ try std.testing.expectEqual(rows - 1, screen.bot);
+}
diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.sh
index 47da7768..bc21db09 100644
--- a/scripts/eval-tier1.sh
+++ b/scripts/eval-tier1.sh
@@ -256,6 +256,13 @@ if wanted tuiguard; then
if python3 scripts/test-tui-resize-anchor.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
fi
fi
diff --git a/scripts/test-tui-scroll-paint.py b/scripts/test-tui-scroll-paint.py
new file mode 100644
index 00000000..f23ea075
--- /dev/null
+++ b/scripts/test-tui-scroll-paint.py
@@ -0,0 +1,404 @@
+#!/usr/bin/env python3
+"""Live proof: scrolling the transcript is a terminal-side SCROLL, and it lies
+about nothing.
+
+The diff painter compares screen row i to the previous frame's row i, so a
+one-line scroll makes EVERY row differ and the whole screen is rewritten per
+wheel notch. TUI/scrollpaint.zig instead sets a scroll region over the band that
+moved, emits SU/SD, and repaints only the rows the scroll exposed. That is a
+correctness risk exactly where it is a performance win: if the region, the
+direction or the exposed rows are off by one, the screen quietly stops matching
+the frame and NOTHING says so — the next paint diffs against a model of the
+screen that is no longer true.
+
+So this probe drives the real binary under a pty and checks both halves:
+
+ A. cheap one wheel notch must cost a small fraction of a full repaint, and
+ must contain a scroll-region + SU/SD rather than a screenful of
+ rows. Reported as bytes, measured live.
+ B. honest after a storm of wheel notches in both directions (plus keyboard
+ scrolling, a fold toggle mid-storm and a page jump), the modelled
+ screen — replayed through a terminal that understands DECSTBM /
+ SU / SD — must equal a FORCED FULL REPAINT of the same frame, cell
+ for cell. Any cell where they differ is a cell the scroll path
+ moved somewhere the composer did not.
+ C. tidy the scroll region must not be left set. A margin that outlives the
+ paint turns every later LF into a scroll inside it.
+
+Usage: python3 scripts/test-tui-scroll-paint.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
+import unicodedata
+
+# 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
+TAIL = "SCROLLTAILOMEGA"
+# One wheel notch is 3 lines out of a ~24-row band: comfortably under a quarter
+# of a full repaint even with the sticky header and status bar changing too.
+BUDGET = 0.25
+
+WHEEL_UP = b"\x1b[<64;40;10M"
+WHEEL_DOWN = b"\x1b[<65;40;10M"
+
+
+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 and the TUI clamps to its floor.
+ resize(fd, rows, cols)
+ return pid, fd
+
+
+def fresh_ws():
+ ws = tempfile.mkdtemp(prefix="tui-scroll-")
+ 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, 2.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 cell_width(ch):
+ if unicodedata.combining(ch) or ch in "​‌‍︎️⁠":
+ return 0
+ if unicodedata.east_asian_width(ch) in ("W", "F"):
+ return 2
+ if ord(ch) >= 0x1F300:
+ return 2
+ return 1
+
+
+CSI = re.compile(r"\x1b\[([0-9;?<>]*)([@-~])")
+
+
+class Screen:
+ """The subset of a terminal the painter can get wrong, plus the two
+ sequences the scroll path adds: DECSTBM margins and SU/SD. Autowrap is off,
+ as run.zig sets it (?7l)."""
+
+ def __init__(self, rows, cols):
+ self.rows, self.cols = rows, cols
+ self.cells = [[" "] * cols for _ in range(rows)]
+ self.r = self.c = 0
+ self.top, self.bot = 0, rows - 1
+ self.margins_seen = 0
+ self.scrolls = 0
+
+ def put(self, ch, w):
+ if self.r >= self.rows:
+ return
+ c = min(self.c, self.cols - 1)
+ self.cells[self.r][c] = ch
+ if w == 2 and c + 1 < self.cols:
+ self.cells[self.r][c + 1] = ""
+ self.c = min(c + w, self.cols)
+
+ def erase_to_eol(self):
+ if self.r >= self.rows:
+ return
+ for c in range(min(self.c, self.cols - 1), self.cols):
+ self.cells[self.r][c] = " "
+
+ def clear(self):
+ self.cells = [[" "] * self.cols for _ in range(self.rows)]
+ self.r = self.c = 0
+
+ def scroll(self, n, up):
+ self.scrolls += 1
+ blank = [" "] * self.cols
+ for _ in range(n):
+ if up:
+ for r in range(self.top, self.bot):
+ self.cells[r] = self.cells[r + 1]
+ self.cells[self.bot] = list(blank)
+ else:
+ for r in range(self.bot, self.top, -1):
+ self.cells[r] = self.cells[r - 1]
+ self.cells[self.top] = list(blank)
+
+ def feed(self, data):
+ s = data.decode("utf-8", errors="replace")
+ i = 0
+ while i < len(s):
+ ch = s[i]
+ if ch == "\x1b":
+ i = self.escape(s, i)
+ continue
+ if ch == "\r":
+ self.c = 0
+ i += 1
+ continue
+ if ch == "\n":
+ # Inside the margins an LF at the bottom scrolls; the painter
+ # only ever emits LF on the full lay-down, with no margins set.
+ self.r += 1
+ i += 1
+ continue
+ w = cell_width(ch)
+ if w:
+ self.put(ch, w)
+ i += 1
+ return self
+
+ def escape(self, s, i):
+ rest = s[i:]
+ m = CSI.match(rest)
+ if m:
+ self.csi(m.group(1), m.group(2))
+ return i + m.end()
+ if len(rest) > 1 and rest[1] in "]P_^X":
+ bel = rest.find("\x07")
+ st = rest.find("\x1b\\")
+ ends = [e for e in (bel + 1 if bel >= 0 else -1, st + 2 if st >= 0 else -1) if e > 0]
+ return i + (min(ends) if ends else len(rest))
+ return i + 2
+
+ def csi(self, params, final):
+ if params.startswith(("?", "<", ">")):
+ return
+ parts = params.split(";")
+
+ def num(k, dflt):
+ return int(parts[k]) if len(parts) > k and parts[k].isdigit() else dflt
+
+ if final == "H":
+ self.r, self.c = max(num(0, 1) - 1, 0), max(num(1, 1) - 1, 0)
+ elif final == "J" and params in ("2", "3"):
+ self.clear()
+ elif final == "K" and params in ("", "0"):
+ self.erase_to_eol()
+ elif final == "r":
+ self.top = max(num(0, 1) - 1, 0)
+ self.bot = min(num(1, self.rows) - 1, self.rows - 1)
+ if params:
+ self.margins_seen += 1
+ self.r, self.c = self.top, 0
+ elif final == "S":
+ self.scroll(max(num(0, 1), 1), True)
+ elif final == "T":
+ self.scroll(max(num(0, 1), 1), False)
+
+ def text_rows(self):
+ return ["".join(row).rstrip() for row in self.cells]
+
+ def diff(self, other):
+ for r, (a, b) in enumerate(zip(self.text_rows(), other.text_rows())):
+ if a != b:
+ return f"row {r}: screen has {a!r} but the frame is {b!r}"
+ return None
+
+
+def paints(stream):
+ """One entry per PAINT. run.zig wraps each in the ?2026 synchronized-update
+ bracket, which is the only way to tell one paint from the next in a stream
+ that also carries the 3-second self-heal — and a heal landing inside the
+ window would otherwise be billed to the wheel notch being measured."""
+ return re.findall(rb"\x1b\[\?2026h(.*?)\x1b\[\?2026l", stream, re.S)
+
+
+def ground_truth(fd, rows, cols):
+ """A forced full repaint, replayed onto a fresh screen: what the terminal
+ WOULD show if it were redrawn from nothing right now. A resize invalidates
+ run.zig's diff baseline, so the paint that follows one is a whole frame."""
+ resize(fd, rows - 1, cols)
+ drain(fd, 0.5)
+ resize(fd, rows, cols)
+ stream = drain(fd, 1.5)
+ full = [p for p in paints(stream) if b"\x1b[2J\x1b[H" in p]
+ if not full:
+ return None, 0
+ truth = Screen(rows, cols)
+ truth.clear()
+ return truth.feed(full[-1]), len(full[-1])
+
+
+def fill(fd):
+ """Transcript content with no model call: `!` lines run in-session, so the
+ text on screen is known exactly and nothing streams while we scroll."""
+ for tag in range(8):
+ body = "filler line %d-%d padded out so the transcript is far longer than the viewport"
+ lines = "".join((body % (tag, k)) + r"\n" for k in range(4))
+ os.write(fd, (r"!printf '" + lines + r"'" + "\r").encode())
+ drain(fd, 1.2)
+ os.write(fd, (r"!printf '" + TAIL + r"\n'" + "\r").encode())
+ return drain(fd, 2.5)
+
+
+def check_a_cheap(fd, screen):
+ truth, full_bytes = ground_truth(fd, ROWS, COLS)
+ if truth is None:
+ return "A: no full repaint came back to size the budget against", None
+ screen.feed(b"")
+ # Off the bottom first, so the notch measured below is a plain slide with
+ # transcript on both sides of it rather than a clamp at the tail.
+ for _ in range(4):
+ os.write(fd, WHEEL_UP)
+ screen.feed(drain(fd, 0.35))
+ os.write(fd, WHEEL_UP)
+ stream = drain(fd, 0.8)
+ screen.feed(stream)
+ # The notch's OWN paint, not whatever else the 0.8s window caught.
+ scrolled = [p for p in paints(stream) if re.search(rb"\x1b\[\d+[ST]", p)]
+ if not scrolled:
+ return "A: a wheel notch emitted no SU/SD — the fast path never fired", None
+ one = scrolled[-1]
+ if not re.search(rb"\x1b\[\d+;\d+r", one):
+ return "A: the scroll was emitted with no DECSTBM region around it", None
+ if len(one) >= full_bytes * BUDGET:
+ return (
+ f"A: a wheel notch cost {len(one)} bytes against a {full_bytes}-byte full repaint "
+ f"(budget {BUDGET:.0%})"
+ ), None
+ return None, (len(one), full_bytes)
+
+
+def check_b_honest(fd, screen):
+ storm = (
+ [WHEEL_UP] * 9
+ + [WHEEL_DOWN] * 4
+ + [b"\x0b"] * 3 # Ctrl+K: keyboard scroll, one line at a time
+ + [WHEEL_UP] * 6
+ + [b"\x1b[5~"] # PageUp: a jump far larger than the band
+ + [WHEEL_DOWN] * 5
+ + [WHEEL_UP] * 2
+ + [b"\x1b[6~"] # PageDown back
+ + [WHEEL_DOWN] * 8
+ + [WHEEL_UP] * 3
+ )
+ for ev in storm:
+ os.write(fd, ev)
+ screen.feed(drain(fd, 0.18))
+ screen.feed(drain(fd, 0.8))
+ if screen.scrolls == 0:
+ return "B: the storm never took the scroll path at all"
+ truth, _ = ground_truth(fd, ROWS, COLS)
+ if truth is None:
+ return "B: no full repaint came back to compare against"
+ screen.feed(b"")
+ d = screen.diff(truth)
+ return d and f"B: after a scroll storm of {screen.scrolls} scrolls, {d}"
+
+
+def check_c_tidy(screen):
+ if (screen.top, screen.bot) != (0, ROWS - 1):
+ return f"C: the scroll region was left at rows {screen.top}-{screen.bot}"
+ if screen.margins_seen == 0:
+ return "C: no DECSTBM was ever set, so nothing was proven about resetting it"
+ return None
+
+
+def run():
+ ws, env = fresh_ws()
+ pid, fd = spawn(ws, env)
+ try:
+ screen = Screen(ROWS, COLS)
+ screen.feed(boot(fd))
+ out = fill(fd)
+ screen.feed(out)
+ if TAIL.encode() not in out:
+ return f"the transcript never showed {TAIL} (no `!` output)"
+ err, nums = check_a_cheap(fd, screen)
+ if err:
+ return err
+ print(f" one wheel notch: {nums[0]} bytes vs {nums[1]} for a full repaint "
+ f"({nums[0] / nums[1]:.1%})")
+ err = check_b_honest(fd, screen)
+ if err:
+ return err
+ print(f" storm: {screen.scrolls} hardware scrolls, screen == frame")
+ return check_c_tidy(screen)
+ finally:
+ reap(pid, fd)
+
+
+def main():
+ if not os.path.exists(BIN):
+ print(f"tui-scroll-paint: {BIN} not built — skipping")
+ return 0
+ try:
+ import pty # noqa: F401
+ except ImportError:
+ print("tui-scroll-paint: no pty support here — skipping")
+ return 0
+ try:
+ err = run()
+ except OSError as e:
+ if getattr(e, "errno", None) == 5:
+ err = "pty EIO — the graff process died mid-check"
+ else:
+ print(f"tui-scroll-paint: pty unavailable ({e}) — skipping")
+ return 0
+ if err:
+ print(f" ✗ scroll-paint: {err}")
+ return 1
+ print(" ✓ scroll-paint: a wheel notch is a scroll region + SU, and a storm of them leaves the screen == the frame")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/spec/kernels/terminal_modes.json b/spec/kernels/terminal_modes.json
index 1710265a..0f575ee7 100644
--- a/spec/kernels/terminal_modes.json
+++ b/spec/kernels/terminal_modes.json
@@ -1,7 +1,7 @@
{
"kernel": "terminal_modes",
"graff_enable": "\u001b[?1049h\u001b[?25l\u001b[?2004h\u001b[?1000h\u001b[?1003h\u001b[?1006h\u001b[?7l\u001b[>11u\u001b[>4;2m",
- "graff_restore": "\u001b[?2026l\u001b[>4;0m\u001b[<u\u001b[?7h\u001b[?1006l\u001b[?1003l\u001b[?1000l\u001b[?2004l\u001b[?25h\u001b[?1049l",
+ "graff_restore": "\u001b[?2026l\u001b[r\u001b[>4;0m\u001b[<u\u001b[?7h\u001b[?1006l\u001b[?1003l\u001b[?1000l\u001b[?2004l\u001b[?25h\u001b[?1049l",
"cells": [
{
"name": "empty",
@@ -27,7 +27,7 @@
},
{
"name": "graff-lifecycle",
- "stream": "\u001b[?1049h\u001b[?25l\u001b[?2004h\u001b[?1000h\u001b[?1003h\u001b[?1006h\u001b[?7l\u001b[>11u\u001b[>4;2m\u001b[?2026l\u001b[>4;0m\u001b[<u\u001b[?7h\u001b[?1006l\u001b[?1003l\u001b[?1000l\u001b[?2004l\u001b[?25h\u001b[?1049l",
+ "stream": "\u001b[?1049h\u001b[?25l\u001b[?2004h\u001b[?1000h\u001b[?1003h\u001b[?1006h\u001b[?7l\u001b[>11u\u001b[>4;2m\u001b[?2026l\u001b[r\u001b[>4;0m\u001b[<u\u001b[?7h\u001b[?1006l\u001b[?1003l\u001b[?1000l\u001b[?2004l\u001b[?25h\u001b[?1049l",
"deviations": [],
"depth": 0,
"balanced": true
diff --git a/spec/ref/terminal_modes.py b/spec/ref/terminal_modes.py
index 7218aa30..3ad5a3a3 100644
--- a/spec/ref/terminal_modes.py
+++ b/spec/ref/terminal_modes.py
@@ -18,7 +18,7 @@ KITTY_POP_RE = re.compile(r"\x1b\[<[0-9;]*u")
# The Zig conformance test parses the live constants and diffs them against
# the fixture copy of these, so drift in either direction trips.
GRAFF_ENABLE = "\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1b[?1006h\x1b[?7l\x1b[>11u\x1b[>4;2m"
-GRAFF_RESTORE = "\x1b[?2026l\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l"
+GRAFF_RESTORE = "\x1b[?2026l\x1b[r\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l"
def parse_ops(stream: str) -> list[tuple[str, int]]: