Skip to content

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

Python

fix(tui): close the six findings from the ec2917c verification pass

Rach Pradhan7616c5ecda25
diff --git a/TUI/chrome.zig b/TUI/chrome.zig
index 78e9c32c..269ce855 100644
--- a/TUI/chrome.zig
+++ b/TUI/chrome.zig
@@ -424,3 +424,31 @@ test "prompt box wraps a long draft onto several rows" {
try std.testing.expect(std.mem.count(u8, box, "│") >= 6);
try std.testing.expect(std.mem.indexOf(u8, box, "can we make") != null);
}
+
+test "the composer's right border holds its column for ambiguous and wide glyphs" {
+ // rowInner pads from visibleLen, so a mis-measured glyph moves the wall.
+ // ✓/⚙ draw one cell (they used to claim two, pulling the border in); emoji
+ // and CJK draw two and must not push it out.
+ const drafts = [_][]const u8{
+ "✓ done ⚙ running ✗ failed ❯ next",
+ "🚀 ship it 🚀🚀 and keep typing until this wraps onto another row 🚀",
+ "你好世界你好世界你好世界你好世界你好世界你好世界你好世界你好世界",
+ "mixed ✓ 🚀 漢字 tail",
+ };
+ for (drafts) |draft| {
+ for ([_]usize{ 40, 41, 57, 80 }) |w| {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.input.setValue(draft);
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const box = try promptBox(&m, arena.allocator(), w);
+ var it = std.mem.splitScalar(u8, box, '\n');
+ while (it.next()) |ln| {
+ if (ln.len == 0) continue;
+ try std.testing.expectEqual(w, theme_mod.visibleLen(ln));
+ }
+ }
+ }
+}
diff --git a/TUI/markdown.zig b/TUI/markdown.zig
index 6402ab51..67bcecb9 100644
--- a/TUI/markdown.zig
+++ b/TUI/markdown.zig
@@ -25,13 +25,24 @@ pub fn renderThemed(a: std.mem.Allocator, src: []const u8, th: theme_mod.Theme,
var lang: ?*const syntax.Lang = null;
var lex: syntax.State = .{};
var first = true;
+ // The previous line ended inside the code band, so codeBg is still the
+ // active canvas and the next line that is NOT band content has to reclaim
+ // it. Restoring on the fence line's own tail instead ended the band at the
+ // last code glyph: run.zig pads the rest of the row from wherever the line
+ // left the background, so the band has to stay open until the row ends.
+ var band = false;
var i: usize = 0;
while (i < lines.items.len) {
const line = lines.items[i];
if (!first) try out.append('\n');
first = false;
const t = std.mem.trimStart(u8, line, " ");
- if (std.mem.startsWith(u8, t, "```")) {
+ const marker = std.mem.startsWith(u8, t, "```");
+ if (band and !(in_fence and !marker)) {
+ try out.appendSlice(th.bg); // leave the band before anything paints
+ band = false;
+ }
+ if (marker) {
in_fence = !in_fence;
if (in_fence) {
lang = syntax.resolve(t[3..]);
@@ -50,8 +61,8 @@ pub fn renderThemed(a: std.mem.Allocator, src: []const u8, th: theme_mod.Theme,
try out.appendSlice(th.text);
try out.appendSlice(line);
}
- try out.appendSlice(theme_mod.reset);
- try out.appendSlice(th.bg); // the no-49 reset keeps codeBg alive — restore the canvas
+ try out.appendSlice(theme_mod.reset); // fg/weight only: the band survives to the row end
+ band = true;
i += 1;
continue;
}
@@ -378,6 +389,88 @@ test "render paints headers, code, bold, and bullets" {
try std.testing.expect(std.mem.indexOf(u8, text, theme_mod.emerald) != null);
}
+test "the code band stays open to the row end and is released on the next line" {
+ const th = theme_mod.of(.night);
+ const code_bg = syntax.codeBg(false);
+ const out = try renderThemed(std.testing.allocator, "intro\n```\nabc\ndef\n```\nafter", th, 40);
+ defer std.testing.allocator.free(out);
+ var it = std.mem.splitScalar(u8, out, '\n');
+ var rows: usize = 0;
+ var was_band = false;
+ var band_rows: usize = 0;
+ while (it.next()) |ln| : (rows += 1) {
+ const band = std.mem.indexOf(u8, ln, code_bg) != null;
+ if (band) {
+ // run.zig pads a row from whatever background the line left active,
+ // so a band row must NOT hand the canvas back before it ends.
+ try std.testing.expect(std.mem.indexOf(u8, ln, th.bg) == null);
+ band_rows += 1;
+ } else if (was_band) {
+ // The first row off the band reclaims the theme canvas up front.
+ try std.testing.expect(std.mem.startsWith(u8, ln, th.bg));
+ }
+ was_band = band;
+ }
+ try std.testing.expectEqual(@as(usize, 2), band_rows); // abc, def
+ // intro, opening separator, abc, def, closing separator, after
+ try std.testing.expectEqual(@as(usize, 6), rows);
+}
+
+test "a wrapped fence line carries its band onto every continuation row" {
+ const th = theme_mod.of(.night);
+ const bg = syntax.codeBg(false);
+ const src =
+ \\```zig
+ \\const message = try std.fmt.allocPrint(gpa, "hello {s} world", .{name});
+ \\```
+ ;
+ const body = try renderThemed(std.testing.allocator, src, th, 36);
+ defer std.testing.allocator.free(body);
+ const wrapped = try theme_mod.wrapToWidth(std.testing.allocator, body, 36);
+ defer std.testing.allocator.free(wrapped);
+ var it = std.mem.splitScalar(u8, wrapped, '\n');
+ var code_rows: usize = 0;
+ while (it.next()) |ln| {
+ if (theme_mod.visibleLen(ln) == 0) continue; // fence separators
+ code_rows += 1;
+ // A syntax-coloured line spends an SGR per token; the old byte-capped
+ // tracker had dropped the background long before the wrap point.
+ try std.testing.expect(std.mem.indexOf(u8, ln, bg) != null);
+ }
+ try std.testing.expect(code_rows > 1); // it really did wrap
+}
+
+test "no code background leaks past a closed fence or off the last fence row" {
+ const th = theme_mod.of(.night);
+ const code_bg = syntax.codeBg(false);
+ const closed = try renderThemed(std.testing.allocator, "```\nx\n```\ntail", th, 40);
+ defer std.testing.allocator.free(closed);
+ // The band ends with the fence, the next row takes the canvas back, and no
+ // later row re-opens codeBg.
+ var it = std.mem.splitScalar(u8, closed, '\n');
+ var seen_band = false;
+ var restored = false;
+ while (it.next()) |ln| {
+ const band = std.mem.indexOf(u8, ln, code_bg) != null;
+ if (band) {
+ try std.testing.expect(!restored); // never re-opened
+ seen_band = true;
+ continue;
+ }
+ if (seen_band and !restored) {
+ try std.testing.expect(std.mem.startsWith(u8, ln, th.bg));
+ restored = true;
+ }
+ }
+ try std.testing.expect(seen_band and restored);
+ // A message that ends mid-fence keeps its band (that row IS code) and adds
+ // no stray row after it for the theme bg to land on.
+ const open = try renderThemed(std.testing.allocator, "```\nx", th, 40);
+ defer std.testing.allocator.free(open);
+ try std.testing.expect(std.mem.indexOf(u8, open, th.bg) == null);
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, open, "\n"));
+}
+
test "renderUser chips @[path] and paints slash commands" {
const text = try renderUser(std.testing.allocator, "@[/tmp/a.png] /goal look at this", theme_mod.emerald, theme_mod.zinc200);
defer std.testing.allocator.free(text);
diff --git a/TUI/render.zig b/TUI/render.zig
index 81f82a15..09df275b 100644
--- a/TUI/render.zig
+++ b/TUI/render.zig
@@ -27,7 +27,10 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
try chrome.overlay(self, a, width)
else
"";
- const mid = if (self.overlay != .none and self.overlay != .image)
+ // The image overlay is a card ABOVE the composer, so `mid` stays the
+ // transcript; every other overlay replaces it with its own body.
+ const overlay_body = self.overlay != .none and self.overlay != .image;
+ const mid = if (overlay_body)
try chrome.overlay(self, a, width)
else if (self.screen == .welcome and self.userTurnCount() == 0)
try welcome.render(self, a, width)
@@ -90,7 +93,10 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
// two top content lines instead of shifting them, so the row↔line map
// for everything below is unchanged and the bottom line stays put.
var chrome_rows: usize = 0;
- if (view_h >= 5) {
+ // Only the transcript gets a pinned prompt. On an overlay screen `mid`
+ // is the overlay's own body, and a long one (/help, /models) scrolls
+ // too — ungated, this pinned a user prompt over its first two rows.
+ if (!overlay_body and view_h >= 5) {
if (scrollback.stickyUserAbove(self, start, width)) |utext| {
const th = self.theme();
var head = std.array_list.Managed(u8).init(a);
@@ -259,6 +265,34 @@ test "debug overlay keeps the observability HUD and adds layout" {
try std.testing.expect(std.mem.indexOf(u8, text, "pending") != null);
}
+test "the sticky header never pins a prompt over an overlay" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.user, "SECRETPROMPT about widgets");
+ var i: usize = 0;
+ while (i < 40) : (i += 1) try m.push(.assistant, "filler assistant prose to make the transcript long");
+ // It engages on the transcript...
+ const transcript = try render(&m, std.testing.allocator, 80, 24, 0);
+ std.testing.allocator.free(transcript);
+ try std.testing.expectEqual(@as(usize, 2), m.sticky_rows);
+ // ...and stands down once `mid` is an overlay body long enough to scroll:
+ // ungated, the pin ate the overlay's own first two rows.
+ m.openOverlay(.help);
+ const overlay_frame = try render(&m, std.testing.allocator, 80, 24, 0);
+ defer std.testing.allocator.free(overlay_frame);
+ try std.testing.expectEqual(@as(usize, 0), m.sticky_rows);
+ try std.testing.expect(std.mem.indexOf(u8, overlay_frame, "SECRETPROMPT") == null);
+ // The image overlay is a card, not a body: the transcript keeps its pin.
+ m.closeOverlay();
+ m.preview_path = "/tmp/shot.png";
+ m.preview_n = 1;
+ m.openOverlay(.image);
+ const card_frame = try render(&m, std.testing.allocator, 80, 24, 0);
+ defer std.testing.allocator.free(card_frame);
+ try std.testing.expectEqual(@as(usize, 2), m.sticky_rows);
+}
+
test "sticky header pins the last scrolled-past user prompt with a blank separator" {
var m: Model = undefined;
m.setup(std.testing.allocator);
diff --git a/TUI/run.zig b/TUI/run.zig
index ce84b2b2..0e54616e 100644
--- a/TUI/run.zig
+++ b/TUI/run.zig
@@ -294,6 +294,39 @@ test "run loop enables click+hover tracking and bracketed paste" {
try std.testing.expect(std.mem.indexOf(u8, src, "a=d,d=A") != null);
}
+fn paintToBuf(a: std.mem.Allocator, frame: []const u8, rows: usize, cols: usize, prev: []const u8) ![]u8 {
+ var aw = Io.Writer.Allocating.init(a);
+ errdefer aw.deinit();
+ try paint(&aw.writer, frame, rows, cols, prev, "\x1b[48;2;20;20;20m");
+ return aw.toOwnedSlice();
+}
+
+test "paint keeps a full row's last glyph but still erases every shorter row" {
+ const a = std.testing.allocator;
+ // Row 0 is exactly 10 columns: ESC[K sits ON the last cell and would eat
+ // the composer's right border, so a full row gets neither pad nor erase.
+ // Row 1 is short and must get both.
+ const out = try paintToBuf(a, "╭────────╮\nshort", 2, 10, "XXXXXXXXXX\nold row!!");
+ defer a.free(out);
+ const border = std.mem.indexOf(u8, out, "╭────────╮").?;
+ const short = std.mem.indexOf(u8, out, "short").?;
+ const erase = std.mem.indexOfPos(u8, out, border, "\x1b[K");
+ try std.testing.expect(erase != null and erase.? > short);
+ try std.testing.expect(std.mem.indexOfPos(u8, out, short, " ") != null);
+}
+
+test "paint erases a row whose glyphs are ambiguous width" {
+ const a = std.testing.allocator;
+ // " ✓ bash finished ok" draws 20 cells. When visibleLen claimed 21 it
+ // measured full at cols=21, so paint skipped the pad AND the erase and the
+ // 21st cell kept the previous frame. Both must still happen.
+ const frame = " \u{2713} bash finished ok";
+ try std.testing.expectEqual(@as(usize, 20), theme_mod.visibleLen(frame));
+ const out = try paintToBuf(a, frame, 1, 21, "RESIDUE RESIDUE RESIDU");
+ defer a.free(out);
+ try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[K") != null);
+}
+
test "rowChanged only flags the line that actually moved" {
const prev = "top\nmiddle\nbottom";
const next = "top\nmiddle\nBOTTOM";
diff --git a/TUI/theme.zig b/TUI/theme.zig
index c1486fd7..647666d5 100644
--- a/TUI/theme.zig
+++ b/TUI/theme.zig
@@ -144,26 +144,53 @@ pub fn skipEsc(s: []const u8, start: usize) usize {
return i;
}
-/// Terminal column width of one codepoint: 2 for East Asian Wide/Fullwidth
-/// and emoji presentation, 0 for combining marks and zero-width joiners, 1
-/// otherwise. Coarse ranges, but every box border and pad in the TUI keys on
-/// this — counting 🚀 as one column pushed the composer's right wall two
-/// cells past its corners.
+/// Terminal column width of one codepoint: 2 for East Asian Wide/Fullwidth and
+/// for emoji whose DEFAULT presentation is emoji, 0 for combining marks and
+/// zero-width joiners, 1 otherwise. Every box border and pad in the TUI keys on
+/// this — counting 🚀 as one column pushed the composer's right wall two cells
+/// past its corners.
+///
+/// The symbol blocks are enumerated, never taken wholesale. U+2600..U+27BF and
+/// U+2B00..U+2BFF are mostly East-Asian-Ambiguous glyphs that terminals draw in
+/// ONE cell, and the TUI paints five of them itself (⚙ ✓ ✗ ❙ ❯). Claiming two
+/// columns for those under-padded every chrome row by one and — because
+/// run.zig skips the pad AND the erase once a row measures full — stranded the
+/// previous frame's last cell. Only Emoji_Presentation=Yes is wide here; the
+/// text-presentation symbols reach two columns via a VS16 selector (see cpAt).
pub fn charWidth(cp: u21) u2 {
return switch (cp) {
0x0300...0x036F, 0x1AB0...0x1AFF, 0x1DC0...0x1DFF, 0x20D0...0x20FF, 0xFE20...0xFE2F => 0, // combining
0x200B...0x200D, 0xFE0E...0xFE0F, 0x2060 => 0, // zero-width + variation selectors
0x1100...0x115F, 0x2E80...0x303E, 0x3041...0x33FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xA000...0xA4CF, 0xAC00...0xD7A3, 0xF900...0xFAFF, 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6 => 2, // East Asian Wide
- 0x1F300...0x1FAFF, 0x2600...0x27BF, 0x2B00...0x2BFF, 0x20000...0x3FFFD => 2, // emoji + supplementary ideographs
+ 0x1F300...0x1FAFF, 0x20000...0x3FFFD => 2, // emoji planes + supplementary ideographs
+ // Emoji_Presentation=Yes inside the BMP symbol blocks.
+ 0x231A...0x231B, 0x23E9...0x23EC, 0x23F0, 0x23F3, 0x25FD...0x25FE => 2,
+ 0x2614...0x2615, 0x2648...0x2653, 0x267F, 0x2693, 0x26A1 => 2,
+ 0x26AA...0x26AB, 0x26BD...0x26BE, 0x26C4...0x26C5, 0x26CE, 0x26D4 => 2,
+ 0x26EA, 0x26F2...0x26F3, 0x26F5, 0x26FA, 0x26FD => 2,
+ 0x2705, 0x270A...0x270B, 0x2728, 0x274C, 0x274E => 2,
+ 0x2753...0x2755, 0x2757, 0x2795...0x2797, 0x27B0, 0x27BF => 2,
+ 0x2B1B...0x2B1C, 0x2B50, 0x2B55 => 2,
else => 1,
};
}
+/// Width and byte length of the codepoint at `i`, honouring a trailing VS16:
+/// `✓\u{FE0F}` asks for emoji presentation and does take two cells, while a
+/// bare `✓` takes one. The selector itself stays zero-width, so the pair still
+/// measures two in total.
fn cpAt(s: []const u8, i: usize) struct { w: u2, step: usize } {
const len = std.unicode.utf8ByteSequenceLength(s[i]) catch return .{ .w = 1, .step = 1 };
const step = @min(@as(usize, len), s.len - i);
const cp = std.unicode.utf8Decode(s[i .. i + step]) catch return .{ .w = 1, .step = step };
- return .{ .w = charWidth(cp), .step = step };
+ const w = charWidth(cp);
+ if (w == 1 and emojiPresentationNext(s, i + step)) return .{ .w = 2, .step = step };
+ return .{ .w = w, .step = step };
+}
+
+fn emojiPresentationNext(s: []const u8, at: usize) bool {
+ if (at + 3 > s.len) return false;
+ return std.mem.eql(u8, s[at .. at + 3], "\u{FE0F}");
}
/// Columns in `s`, skipping SGR; CJK/emoji count 2, combining marks 0.
@@ -238,33 +265,130 @@ test "day uses the Codegraff light palette; dark themes match their tokens" {
try std.testing.expectEqualStrings("\x1b[38;2;155;126;206m", of(.oscura).accent);
}
-/// Active-SGR tracker for the wrappers: remember styling since the last full
-/// reset so an inserted line break can re-open it — the diff painter repaints
-/// rows independently, so a continuation row with no SGR of its own renders
-/// in whatever style the previous paint left behind.
-fn trackSgr(active: *std.array_list.Managed(u8), seq: []const u8) void {
- if (seq.len < 3 or seq[1] != '[' or seq[seq.len - 1] != 'm') return;
- if (std.mem.eql(u8, seq, "\x1b[0m") or std.mem.eql(u8, seq, "\x1b[m")) {
- active.clearRetainingCapacity();
- return;
+/// Active-SGR tracker for the wrappers: remember styling since the last reset
+/// so an inserted line break can re-open it — the diff painter repaints rows
+/// independently, so a continuation row with no SGR of its own renders in
+/// whatever style the previous paint left behind.
+///
+/// State is kept PER CATEGORY, last writer wins. Concatenating the raw
+/// sequences instead grew without bound, so it needed a byte cap — and the cap
+/// CLEARED the tracker rather than trimming it. The background is set first on
+/// a code fence, so it was always the first casualty: a syntax-highlighted line
+/// carries a colour per token, and by the wrap point the band was long gone and
+/// the continuation row painted on the plain canvas.
+pub const Sgr = struct {
+ fg: Slot = .{},
+ bg: Slot = .{},
+ weight: Slot = .{},
+ italic: Slot = .{},
+ underline: Slot = .{},
+
+ /// Longest parameter list a slot holds: "48;2;255;255;255".
+ const Slot = struct {
+ buf: [20]u8 = undefined,
+ len: u8 = 0,
+
+ fn set(s: *Slot, p: []const u8) void {
+ if (p.len == 0 or p.len > s.buf.len) return;
+ @memcpy(s.buf[0..p.len], p);
+ s.len = @intCast(p.len);
+ }
+ fn drop(s: *Slot) void {
+ s.len = 0;
+ }
+ fn params(s: *const Slot) []const u8 {
+ return s.buf[0..s.len];
+ }
+ };
+
+ /// Five slots at "\x1b[" + 16 params + "m" apiece, rounded up.
+ pub const max_render = 5 * 20;
+
+ pub fn clear(self: *Sgr) void {
+ self.* = .{};
}
- if (active.items.len > 96) active.clearRetainingCapacity(); // bound pathological runs
- active.appendSlice(seq) catch {};
-}
+
+ /// Re-emit the active state into `buf`. Background first so a continuation
+ /// row establishes its canvas before anything paints on it.
+ pub fn render(self: *const Sgr, buf: *[max_render]u8) []const u8 {
+ var n: usize = 0;
+ const order = [_]*const Slot{ &self.bg, &self.fg, &self.weight, &self.italic, &self.underline };
+ for (order) |slot| {
+ const p = slot.params();
+ if (p.len == 0) continue;
+ buf[n] = 0x1b;
+ buf[n + 1] = '[';
+ n += 2;
+ @memcpy(buf[n .. n + p.len], p);
+ n += p.len;
+ buf[n] = 'm';
+ n += 1;
+ }
+ return buf[0..n];
+ }
+
+ /// Fold one escape sequence into the state. Non-SGR escapes (OSC links,
+ /// kitty graphics, ESC[K) are ignored: they carry no style.
+ pub fn note(self: *Sgr, seq: []const u8) void {
+ if (seq.len < 3 or seq[1] != '[' or seq[seq.len - 1] != 'm') return;
+ const body = seq[2 .. seq.len - 1];
+ if (body.len == 0) { // "\x1b[m" is "\x1b[0m"
+ self.clear();
+ return;
+ }
+ var parts: [16][]const u8 = undefined;
+ var n: usize = 0;
+ var it = std.mem.splitScalar(u8, body, ';');
+ while (it.next()) |p| {
+ if (n == parts.len) return; // pathological: leave the state alone
+ parts[n] = p;
+ n += 1;
+ }
+ var i: usize = 0;
+ while (i < n) : (i += 1) {
+ const code = std.fmt.parseInt(u16, parts[i], 10) catch continue;
+ switch (code) {
+ 0 => self.clear(),
+ 1, 2 => self.weight.set(parts[i]),
+ 3 => self.italic.set(parts[i]),
+ 4 => self.underline.set(parts[i]),
+ 22 => self.weight.drop(),
+ 23 => self.italic.drop(),
+ 24 => self.underline.drop(),
+ 39 => self.fg.drop(),
+ 49 => self.bg.drop(),
+ 30...37, 90...97 => self.fg.set(parts[i]),
+ 40...47, 100...107 => self.bg.set(parts[i]),
+ 38, 48 => {
+ // 38/48 own the parameters that follow: ";5;n" or ";2;r;g;b".
+ const want: usize = if (i + 1 < n and std.mem.eql(u8, parts[i + 1], "5")) 2 else 4;
+ if (i + want >= n) return;
+ const start = @intFromPtr(parts[i].ptr) - @intFromPtr(body.ptr);
+ const last = parts[i + want];
+ const end = @intFromPtr(last.ptr) - @intFromPtr(body.ptr) + last.len;
+ const slot = if (code == 38) &self.fg else &self.bg;
+ slot.set(body[start..end]);
+ i += want;
+ },
+ else => {},
+ }
+ }
+ }
+};
/// Wrap `s` so no row is wider than `width` columns. SGR is preserved AND
/// re-emitted on continuation rows; wide glyphs never straddle the edge.
pub fn wrapToWidth(a: std.mem.Allocator, s: []const u8, width: usize) ![]const u8 {
if (width == 0) return a.dupe(u8, s);
var out = std.array_list.Managed(u8).init(a);
- var active = std.array_list.Managed(u8).init(a);
- defer active.deinit();
+ var active: Sgr = .{};
+ var sgr_buf: [Sgr.max_render]u8 = undefined;
var col: usize = 0;
var i: usize = 0;
while (i < s.len) {
if (s[i] == '\n') {
try out.append('\n');
- try out.appendSlice(active.items);
+ try out.appendSlice(active.render(&sgr_buf));
col = 0;
i += 1;
continue;
@@ -273,13 +397,13 @@ pub fn wrapToWidth(a: std.mem.Allocator, s: []const u8, width: usize) ![]const u
const start = i;
i = skipEsc(s, i);
try out.appendSlice(s[start..i]);
- trackSgr(&active, s[start..i]);
+ active.note(s[start..i]);
continue;
}
const c = cpAt(s, i);
if (col + c.w > width and col > 0) {
try out.append('\n');
- try out.appendSlice(active.items);
+ try out.appendSlice(active.render(&sgr_buf));
col = 0;
}
try out.appendSlice(s[i .. i + c.step]);
@@ -293,15 +417,15 @@ pub fn wrapToWidth(a: std.mem.Allocator, s: []const u8, width: usize) ![]const u
pub fn wrapPreferWords(a: std.mem.Allocator, s: []const u8, width: usize) ![]const u8 {
if (width == 0) return a.dupe(u8, s);
var out = std.array_list.Managed(u8).init(a);
- var active = std.array_list.Managed(u8).init(a);
- defer active.deinit();
+ var active: Sgr = .{};
+ var sgr_buf: [Sgr.max_render]u8 = undefined;
var col: usize = 0;
var last_sp: ?usize = null;
var i: usize = 0;
while (i < s.len) {
if (s[i] == '\n') {
try out.append('\n');
- try out.appendSlice(active.items);
+ try out.appendSlice(active.render(&sgr_buf));
col = 0;
last_sp = null;
i += 1;
@@ -311,19 +435,21 @@ pub fn wrapPreferWords(a: std.mem.Allocator, s: []const u8, width: usize) ![]con
const start = i;
i = skipEsc(s, i); // full skip: hand-rolled CSI-only parsing broke a \n INTO an OSC hyperlink
try out.appendSlice(s[start..i]);
- trackSgr(&active, s[start..i]);
+ active.note(s[start..i]);
continue;
}
const c = cpAt(s, i);
- if (col + c.w > width) {
+ // `col > 0` matches wrapToWidth: a glyph wider than the whole width has
+ // nowhere to go, and breaking before it only opened with a blank row.
+ if (col + c.w > width and col > 0) {
if (last_sp) |sp| {
out.items[sp] = '\n';
- try out.insertSlice(sp + 1, active.items);
+ try out.insertSlice(sp + 1, active.render(&sgr_buf));
col = visibleLen(out.items[sp + 1 ..]);
last_sp = null;
} else {
try out.append('\n');
- try out.appendSlice(active.items);
+ try out.appendSlice(active.render(&sgr_buf));
col = 0;
}
}
@@ -365,6 +491,71 @@ test "visibleLen and takeCols treat OSC/APC as invisible" {
try std.testing.expectEqualStrings("\x1b]8;;u\x07a", cut);
}
+test "charWidth: the TUI's own glyphs measure one cell" {
+ // ⚙ ✓ ✗ ❙ ❯ are painted by scrollback/render themselves and are ambiguous
+ // width: terminals give them one cell. A blanket 2600..27BF range called
+ // them two, which under-padded every chrome row and — once a row measured
+ // full — cost it both the pad and the erase-to-EOL in run.zig.
+ for ([_]u21{ '⚙', '✓', '✗', '❙', '❯', '⊘', '●', '◆', '·', '›', '…', '│', '╭', '─', '▏', '↳', '→' }) |cp| {
+ try std.testing.expectEqual(@as(u2, 1), charWidth(cp));
+ }
+ // Real emoji and CJK stay two.
+ for ([_]u21{ '🚀', '✅', '❌', '⭐', '⌚', '你', '한' }) |cp| {
+ try std.testing.expectEqual(@as(u2, 2), charWidth(cp));
+ }
+ try std.testing.expectEqual(@as(usize, 20), visibleLen(" \u{2713} bash finished ok"));
+}
+
+test "charWidth: a VS16 selector promotes a text-presentation symbol" {
+ try std.testing.expectEqual(@as(usize, 1), visibleLen("\u{2713}"));
+ try std.testing.expectEqual(@as(usize, 2), visibleLen("\u{2713}\u{FE0F}"));
+ try std.testing.expectEqual(@as(usize, 1), visibleLen("\u{2713}\u{FE0E}")); // VS15 stays text
+ try std.testing.expectEqualStrings("", takeCols("\u{2713}\u{FE0F}", 1)); // never half a cell
+}
+
+test "Sgr keeps the background through a colour-heavy line" {
+ // One bg then six token colours: concatenating these passed 96 bytes, and
+ // the cap CLEARED the tracker, so the continuation row of a wrapped code
+ // fence lost its band. Per-slot tracking cannot lose the oldest slot.
+ const s = "\x1b[48;2;28;28;28m" ++
+ "\x1b[38;2;101;101;101m\x1b[38;2;102;102;102m\x1b[38;2;103;103;103m" ++
+ "\x1b[38;2;104;104;104m\x1b[38;2;105;105;105m\x1b[38;2;106;106;106m" ++
+ "ABCDEFGHIJ";
+ const got = try wrapToWidth(std.testing.allocator, s, 4);
+ defer std.testing.allocator.free(got);
+ var it = std.mem.splitScalar(u8, got, '\n');
+ var n: usize = 0;
+ while (it.next()) |ln| : (n += 1) {
+ if (n == 0) continue;
+ try std.testing.expect(std.mem.startsWith(u8, ln, "\x1b[48;2;28;28;28m"));
+ try std.testing.expect(std.mem.indexOf(u8, ln, "\x1b[38;2;106;106;106m") != null);
+ }
+ try std.testing.expect(n > 1);
+}
+
+test "Sgr: each reset code drops only its own slot" {
+ var st: Sgr = .{};
+ var buf: [Sgr.max_render]u8 = undefined;
+ st.note("\x1b[48;2;1;2;3m");
+ st.note("\x1b[38;5;9m");
+ st.note("\x1b[1m");
+ try std.testing.expectEqualStrings("\x1b[48;2;1;2;3m\x1b[38;5;9m\x1b[1m", st.render(&buf));
+ st.note(reset); // 39;22;23;24 — fg and weight go, the background stays
+ try std.testing.expectEqualStrings("\x1b[48;2;1;2;3m", st.render(&buf));
+ st.note("\x1b[31m");
+ try std.testing.expectEqualStrings("\x1b[48;2;1;2;3m\x1b[31m", st.render(&buf));
+ st.note("\x1b[0m");
+ try std.testing.expectEqualStrings("", st.render(&buf));
+ st.note("\x1b[K"); // not SGR: ignored
+ try std.testing.expectEqualStrings("", st.render(&buf));
+}
+
+test "wrapPreferWords does not open with a blank row for an oversized glyph" {
+ const got = try wrapPreferWords(std.testing.allocator, "\u{1F680}ab", 1);
+ defer std.testing.allocator.free(got);
+ try std.testing.expect(got[0] != '\n');
+}
+
test "wide glyphs: 2 columns, never straddling a wrap or a takeCols edge" {
try std.testing.expectEqual(@as(usize, 2), visibleLen("\u{1F680}"));
try std.testing.expectEqual(@as(usize, 4), visibleLen("\u{4F60}\u{597D}"));
diff --git a/scripts/eval/tier1_test_binary.py b/scripts/eval/tier1_test_binary.py
index ad8d7a50..62537986 100644
--- a/scripts/eval/tier1_test_binary.py
+++ b/scripts/eval/tier1_test_binary.py
@@ -52,25 +52,65 @@ class ArtifactError(Exception):
"""No usable test artifact, or one that would not say how many tests it holds."""
+def _names_in(path: pathlib.Path) -> list[str]:
+ try:
+ text = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ return []
+ # The source carries Zig escapes; the binary carries the resolved bytes.
+ # Unescape so a name containing a quote still matches.
+ return [
+ m.group(1).replace('\\"', '"').replace("\\\\", "\\")
+ for m in TEST_NAME.finditer(text)
+ ]
+
+
def declared_tests() -> dict[str, str]:
"""Every `test "name"` in src/*.zig, mapped to the file that declares it."""
out: dict[str, str] = {}
for path in sorted(SRC.glob("*.zig")):
- for match in TEST_NAME.finditer(path.read_text(encoding="utf-8")):
- # The source carries Zig escapes; the binary carries the resolved
- # bytes. Unescape so a name containing a quote still matches.
- name = match.group(1).replace('\\"', '"').replace("\\\\", "\\")
+ for name in _names_in(path):
out[name] = path.name
return out
+def foreign_tests(declared: dict[str, str]) -> set[str]:
+ """Test names that belong to a DIFFERENT test root than src/.
+
+ The name set alone cannot tell the src floor build (a filter matching
+ nothing, so zero declared names survive) apart from a `zig build tui-test`
+ artifact, which also holds zero src names - and being newer, the TUI binary
+ won the tie and reported its 138 tests as the floor. Tier 1 then measured
+ 9 invariants against a 138 floor and called a green suite red.
+
+ Any name declared outside src/ is proof the artifact is not the src root,
+ whatever the filters were, so it settles that tie the other way.
+ """
+ out: set[str] = set()
+ for path in sorted(ROOT.rglob("*.zig")):
+ rel = path.relative_to(ROOT)
+ if rel.parts[0] in ("src", "vendor", ".zig-cache", "zig-out"):
+ continue
+ out.update(_names_in(path))
+ return out - set(declared)
+
+
class Selection:
"""One candidate artifact, scored against the build we asked for."""
- def __init__(self, path: pathlib.Path, present: set[str], expected: set[str]):
+ def __init__(
+ self,
+ path: pathlib.Path,
+ present: set[str],
+ expected: set[str],
+ foreign: set[str] | None = None,
+ ):
self.path = path
self.present = present
self.expected = expected
+ # Names from another test root found in this binary: nonzero means the
+ # artifact is not a build of src/ at all.
+ self.foreign = foreign or set()
self.considered = 1
self.was_newest = True
@@ -102,13 +142,17 @@ def select(filters: list[str], declared: dict[str, str] | None = None) -> Select
Zig's filters are substring matches on the test name, so the set of declared
names a filtered build keeps is computable from the source alone. Rank every
- candidate by how far it is from that set - missing names first, then names it
- should not have - and the full build wins the unfiltered question even when a
- filtered build is newer.
+ candidate by how far it is from that set - missing names first, then names
+ from a foreign test root, then names it should not have - and the full build
+ wins the unfiltered question even when a filtered build is newer.
+
+ The foreign term is what keeps a `zig build tui-test` artifact out of the
+ answer when `expected` is empty and every candidate ties at zero missing.
"""
if declared is None:
declared = declared_tests()
expected = {n for n in declared if not filters or any(f in n for f in filters)}
+ outsiders = foreign_tests(declared)
ranked: list[Selection] = []
# candidates() is newest first and sort() below is stable, so ties stay in
@@ -116,14 +160,15 @@ def select(filters: list[str], declared: dict[str, str] | None = None) -> Select
for path in candidates():
blob = path.read_bytes()
present = {n for n in declared if n.encode("utf-8") in blob}
- ranked.append(Selection(path, present, expected))
+ alien = {n for n in outsiders if n.encode("utf-8") in blob}
+ ranked.append(Selection(path, present, expected, alien))
if not ranked:
raise ArtifactError(
"no compiled test binary under .zig-cache/o - run `zig build test` first"
)
newest = ranked[0].path
- ranked.sort(key=lambda s: (len(s.missing), len(s.extra)))
+ ranked.sort(key=lambda s: (len(s.missing), len(s.foreign), len(s.extra)))
best = ranked[0]
best.considered = len(ranked)
best.was_newest = best.path == newest