graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(tui): land the three-lens rendering audit — 18 confirmed bugs
Rach Pradhanec2917ce44b4
diff --git a/TUI/app.zig b/TUI/app.zigindex e31826b9..107fdb7b 100644--- a/TUI/app.zig+++ b/TUI/app.zig@@ -43,6 +43,9 @@ pub const Model = struct {theme_id: theme_mod.Id = .night,/// Set once the user picks a theme; blocks the OSC-11 auto polarity.theme_explicit: bool = false,+ /// Rows of sticky-header chrome at the top of the viewport this frame —+ /// keys.zig must treat them as inert instead of clicking what they occlude.+ sticky_rows: usize = 0,mode: AgentMode = .normal,effort: engine.Effort = .medium,fast: bool = false,diff --git a/TUI/image.zig b/TUI/image.zigindex 908577b2..2cff4a78 100644--- a/TUI/image.zig+++ b/TUI/image.zig@@ -199,7 +199,7 @@ pub fn mouse(self: *Model, ev: key_mod.Mouse) bool {}return false;};- const hist = if (y >= self.prompt_origin) null else @import("scrollback.zig").indexAtVisual(self, y -| self.mid_origin + self.mid_skip, self.last_term_width);+ const hist = if (y >= self.prompt_origin or y < self.mid_origin + self.sticky_rows) null else @import("scrollback.zig").indexAtVisual(self, y -| self.mid_origin + self.mid_skip, self.last_term_width);const path = pathForChip(self, n, hist);show(self, path, n, click);return true;@@ -220,6 +220,7 @@ fn chipAt(self: *const Model, x: usize, y: usize) ?u32 {}if (y >= self.prompt_origin) return null;if (y < self.mid_origin) return null;+ if (y < self.mid_origin + self.sticky_rows) return null; // sticky chrome is inertconst vis = y - self.mid_origin + self.mid_skip;const idx = @import("scrollback.zig").indexAtVisual(self, vis, self.last_term_width) orelse return null;if (self.history.items[idx].kind != .user) return null;diff --git a/TUI/keys.zig b/TUI/keys.zigindex 652993ab..ac19cc62 100644--- a/TUI/keys.zig+++ b/TUI/keys.zig@@ -230,8 +230,13 @@ fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {return .stay;}if (y < self.mid_origin) return .stay;+ // Sticky-header chrome occludes the top content rows — a click there must+ // not toggle whatever is hidden underneath it.+ if (y < self.mid_origin + self.sticky_rows) return .stay;const vis = y - self.mid_origin + self.mid_skip;- const idx = scrollback.indexAtVisual(self, vis, self.last_term_width) orelse lastToolIdx(self);+ // No fallback on a miss: clicking blank space below the transcript used to+ // silently expand the LAST tool run (audit: easiest bug to hit).+ const idx = scrollback.indexAtVisual(self, vis, self.last_term_width);self.focus = .scrollback;if (idx) |i| {self.selected = i;diff --git a/TUI/markdown.zig b/TUI/markdown.zigindex ac66e7df..6402ab51 100644--- a/TUI/markdown.zig+++ b/TUI/markdown.zig@@ -51,6 +51,7 @@ pub fn renderThemed(a: std.mem.Allocator, src: []const u8, th: theme_mod.Theme,try out.appendSlice(line);}try out.appendSlice(theme_mod.reset);+ try out.appendSlice(th.bg); // the no-49 reset keeps codeBg alive — restore the canvasi += 1;continue;}@@ -196,6 +197,7 @@ fn inlineSpans(out: *std.array_list.Managed(u8), line: []const u8, accent: []conif (std.mem.indexOfPos(u8, line, i + 2, "**")) |end| {try out.appendSlice(theme_mod.bold);try out.appendSlice(line[i + 2 .. end]);+ try out.appendSlice("\x1b[22m"); // bold OFF — a 38;2 fg alone cannot clear SGR 1try out.appendSlice(text);i = end + 2;continue;@@ -249,23 +251,14 @@ fn splitCells(line: []const u8, out: [][]const u8) usize {return n;}-fn cellWidth(s: []const u8) usize {- var n: usize = 0;- var i: usize = 0;- while (i < s.len) {- if (s[i] == '`') {- i += 1;- continue;- }- if (s[i] == '*' and i + 1 < s.len and s[i + 1] == '*') {- i += 2;- continue;- }- const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;- i += @min(w, s.len - i);- n += 1;- }- return n;+/// Visible width of a cell AS RENDERED: run it through inlineSpans and count.+/// Guessing at markers went wrong on every unmatched ` or ** (the render kept+/// them, the measure dropped them, the pad math sheared the grid).+fn cellWidth(a: std.mem.Allocator, s: []const u8) usize {+ var scratch = std.array_list.Managed(u8).init(a);+ defer scratch.deinit();+ inlineSpans(&scratch, s, "", "") catch return s.len;+ return theme_mod.visibleLen(scratch.items);}fn emitRule(out: *std.array_list.Managed(u8), muted: []const u8, widths: []const usize, left: []const u8, mid: []const u8, right: []const u8) !void {@@ -298,7 +291,7 @@ fn emitTable(if (n > ncol) ncol = n;var c: usize = 0;while (c < n) : (c += 1) {- const w = @min(cellWidth(cells[c]), @as(usize, 36));+ const w = @min(cellWidth(a, cells[c]), @as(usize, 36));if (w > widths[c]) widths[c] = w;}}@@ -350,7 +343,7 @@ fn emitTable(try scratch.appendSlice(text);try inlineSpans(&scratch, cell, accent, text);}- const vis = cellWidth(cell);+ const vis = cellWidth(a, cell);if (vis > want) {try out.appendSlice(theme_mod.takeCols(scratch.items, if (want > 1) want - 1 else want));if (want > 1) try out.appendSlice("\u{2026}");diff --git a/TUI/nav.zig b/TUI/nav.zigindex 1d145be1..92bbc0a6 100644--- a/TUI/nav.zig+++ b/TUI/nav.zig@@ -69,13 +69,22 @@ pub fn jumpTo(self: *Model, idx: usize) void {const width = if (self.last_term_width == 0) 80 else self.last_term_width;const total = sb.totalVisualLines(self, width);const at = sb.visualOfIndex(self, idx, width) orelse return;- const view_h = if (self.prompt_origin > self.mid_origin) self.prompt_origin - self.mid_origin else 8;+ // prompt_origin - mid_origin includes the image-card rows render subtracts+ // from the transcript, and the sticky header occludes the top two viewport+ // rows — without both corrections /jump parked the target off-screen or+ // exactly under the pinned chrome (audit: the jumped-to turn was ALWAYS+ // hidden, with the PREVIOUS prompt pinned above it).+ const gross = if (self.prompt_origin > self.mid_origin) self.prompt_origin - self.mid_origin else 8;+ const view_h = gross -| self.preview_rows;if (total <= view_h) {self.scroll = 0;return;}const max_scroll = total - view_h;- self.scroll = if (at >= max_scroll) 0 else max_scroll - at;+ // Land the target at the row below the sticky slot (row 2) so it is the+ // first fully visible line; at the extremes fall back to the edges.+ const want = at -| 2;+ self.scroll = if (want >= max_scroll) 0 else max_scroll - want;}fn jumpTurn(self: *Model, dir: i32) void {diff --git a/TUI/render.zig b/TUI/render.zigindex 2c9d911b..81f82a15 100644--- a/TUI/render.zig+++ b/TUI/render.zig@@ -48,7 +48,10 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,const bottom_lines = countLines(bottom.items);const top_lines = countLines(top);- const card_lines = countLines(image_card);+ // countLines counts a trailing '\n' as an extra line but the append below+ // adds no newline of its own — the off-by-one shifted the whole frame up+ // one row and broke composer clicks (prompt_origin pointed past the box).+ const card_lines = if (image_card.len == 0) 0 else countLines(image_card) - @intFromBool(image_card[image_card.len - 1] == '\n');self.preview_rows = card_lines;self.mid_origin = top_lines;self.prompt_origin = if (height > bottom_lines) height - bottom_lines else 0;@@ -65,6 +68,7 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,if (top.len > 0 and top[top.len - 1] != '\n') try out.append('\n');const n = mid_lines.items.len;+ self.sticky_rows = 0;if (n <= view_h) {self.scroll = 0;self.mid_skip = 0;@@ -102,6 +106,7 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,try out.append('\n');try out.append('\n');chrome_rows = 2;+ self.sticky_rows = 2;}}for (mid_lines.items[start + chrome_rows .. start + view_h]) |ln| {diff --git a/TUI/restore.zig b/TUI/restore.zigindex 870a23e2..fd190685 100644--- a/TUI/restore.zig+++ b/TUI/restore.zig@@ -11,7 +11,7 @@ const tty = @import("tty.zig");/// 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[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l";+pub const seq = "\x1b[?2026l\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l";var armed = std.atomic.Value(bool).init(false);var saved: tty.RawState = undefined;diff --git a/TUI/run.zig b/TUI/run.zigindex 3c036dea..ce84b2b2 100644--- a/TUI/run.zig+++ b/TUI/run.zig@@ -88,6 +88,8 @@ pub fn run(var saw_gfx: bool = false;var prev: []u8 = &.{};var prev_rows: usize = 0;+ var prev_cols: usize = 0;+ var prev_theme = m.theme_id;defer if (prev.len != 0) gpa.free(prev);while (m.running and !m.quit_requested) {m.now_ms = @intCast(@divTrunc(@max(@as(i128, 0), Io.Timestamp.now(io, .real).nanoseconds), 1_000_000));@@ -104,7 +106,12 @@ pub fn run(const hash = std.hash.Wyhash.hash(0, frame);if (hash != last_hash) {const has_gfx = std.mem.indexOf(u8, frame, "\x1b_G") != null;- const full = prev.len == 0 or rows != prev_rows or saw_gfx or has_gfx;+ // The theme bg is painted per ROW, not baked into the frame, and+ // blank rows are byte-identical across themes/widths — the diff+ // path skips them, stranding old-bg rows after /theme or the+ // startup OSC-11 polarity flip, and stale columns after a+ // width-only resize. Both must force a full paint.+ const full = prev.len == 0 or rows != prev_rows or cols != prev_cols or m.theme_id != prev_theme or saw_gfx or has_gfx;// Kitty images sit above the cell grid and survive \x1b[K / dirty// paints — delete before every redraw that might have shown one.// ?2026 synchronized output: the terminal buffers everything@@ -119,6 +126,8 @@ pub fn run(if (prev.len != 0) gpa.free(prev);prev = gpa.dupe(u8, frame) catch &.{};prev_rows = rows;+ prev_cols = cols;+ prev_theme = m.theme_id;last_hash = hash;saw_gfx = has_gfx;}@@ -227,7 +236,14 @@ fn paint(w: *Io.Writer, frame: []const u8, rows: usize, cols: usize, prev: []contry w.writeAll(bg);const ln = nthLine(frame, row);try w.writeAll(ln);- try fillRow(w, ln, cols);+ const vis = theme_mod.visibleLen(ln);+ if (vis < cols) {+ try fillRow(w, ln, cols);+ } else {+ // Row is exactly full: the cursor is ON the last column and EL+ // erases it inclusive — that ate the composer's right border.+ continue;+ }try w.writeAll(bg);try w.writeAll("\x1b[K");}diff --git a/TUI/scrollback.zig b/TUI/scrollback.zigindex cb55dd05..a7f4c8c2 100644--- a/TUI/scrollback.zig+++ b/TUI/scrollback.zig@@ -100,6 +100,7 @@ pub fn totalVisualLines(self: *const Model, width: usize) usize {var arena = std.heap.ArenaAllocator.init(self.alloc);defer arena.deinit();const text = render(self, arena.allocator(), width, self.now_ms) catch return 0;+ if (text.len == 0) return 0; // render.zig pops the empty tail; agree with itreturn lineCount(text);}@@ -247,7 +248,7 @@ fn row(self: *const Model, a: std.mem.Allocator, idx: usize, e: app.Entry, widthelsee.text;const body = switch (e.kind) {- .assistant => try @import("markdown.zig").renderThemed(a, raw, th, width),+ .assistant => try @import("markdown.zig").renderThemed(a, raw, th, width -| 4), // the " ● " gutter costs 4 cols.user => try @import("markdown.zig").renderUser(a, raw, th.accent, th.text),else => raw,};@@ -258,10 +259,11 @@ fn row(self: *const Model, a: std.mem.Allocator, idx: usize, e: app.Entry, width}if (e.kind == .pending) {const fg = if (flickerOn(now_ms)) th.accent else th.muted;- const line = try std.fmt.allocPrint(a, "{s}{s}❙{s} {s}{s}", .{ sel, fg, theme_mod.reset, body, theme_mod.reset });+ const line = try std.fmt.allocPrint(a, "{s}{s}❙{s}{s} {s}{s}", .{ sel, fg, theme_mod.reset, th.muted, body, theme_mod.reset });return theme_mod.wrapToWidth(a, line, width);}- const line = try std.fmt.allocPrint(a, "{s}{s}{s}{s} {s}{s}", .{ sel, color, mark, theme_mod.reset, body, theme_mod.reset });+ const body_fg = if (e.kind == .err) th.error_fg else th.text;+ const line = try std.fmt.allocPrint(a, "{s}{s}{s}{s}{s} {s}{s}", .{ sel, color, mark, theme_mod.reset, body_fg, body, theme_mod.reset });return theme_mod.wrapToWidth(a, line, width);}@@ -346,7 +348,7 @@ fn toolCard(a: std.mem.Allocator, th: theme_mod.Theme, start_text: []const u8, dconst sel: []const u8 = if (selected) "› " else " ";const title = try toolTitle(a, start_text);const preview = toolPreview(done_text);- const head = try std.fmt.allocPrint(a, "{s}{s}◆{s} {s}", .{ sel, if (selected) th.accent else th.muted, theme_mod.reset, title });+ const head = try std.fmt.allocPrint(a, "{s}{s}◆{s}{s} {s}", .{ sel, if (selected) th.accent else th.muted, theme_mod.reset, th.text, title });if (preview == null) return theme_mod.wrapToWidth(a, head, width);const body = try std.fmt.allocPrint(a, "{s}{s}│ {s}{s}", .{ sel, th.muted, preview.?, theme_mod.reset });const joined = try std.fmt.allocPrint(a, "{s}\n{s}", .{ try theme_mod.wrapToWidth(a, head, width), try theme_mod.wrapToWidth(a, body, width) });diff --git a/TUI/syntax.zig b/TUI/syntax.zigindex 9a3276ee..63de62bd 100644--- a/TUI/syntax.zig+++ b/TUI/syntax.zig@@ -150,7 +150,7 @@ const langs = [_]*const Lang{ &zig_lang, &rust_lang, &py_lang, &js_lang, &go_lan/// (extension lookup), then the whole info string as a token. Unknown → null/// (the fence still gets the background band, just uncolored text).pub fn resolve(fence_info: []const u8) ?*const Lang {- const info = std.mem.trim(u8, fence_info, " \t");+ const info = std.mem.trim(u8, fence_info, " \t\r"); // CRLF fences must still resolveif (info.len == 0) return null;blk: {var it = std.mem.splitScalar(u8, info, ':');@@ -223,9 +223,13 @@ pub fn highlightLine(out: *std.array_list.Managed(u8), line: []const u8, lang: *var j = i + 1;try emit(out, &cls, .string, line[i .. i + 1], light);while (j < line.len) {- if (line[j] == '\\' and j + 1 < line.len) {- try emit(out, &cls, .escape, line[j .. j + 2], light);- j += 2;+ if (line[j] == '\\') {+ // A trailing backslash (shell continuation) has no pair —+ // consume it alone or the scanner loops forever (P0: froze+ // the whole TUI at 100% CPU on `echo "a \` fences).+ const esc_end = @min(j + 2, line.len);+ try emit(out, &cls, .escape, line[j..esc_end], light);+ j = esc_end;continue;}if (line[j] == quote) break;@@ -345,3 +349,13 @@ test "strings color their escapes separately" {try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;158;206;106m\"a") != null);try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;158;206;106mb") != null);}++test "P0 regression: a trailing backslash inside a string terminates" {+ var out = std.array_list.Managed(u8).init(std.testing.allocator);+ defer out.deinit();+ var st: State = .{};+ try highlightLine(&out, "echo \"hello \\", &sh_lang, &st, false);+ try highlightLine(&out, "s = 'unterminated \\", &py_lang, &st, false);+ try std.testing.expect(out.items.len > 0);+ try std.testing.expect(resolve("zig\r") == &zig_lang);+}diff --git a/TUI/theme.zig b/TUI/theme.zigindex a7f5f699..c1486fd7 100644--- a/TUI/theme.zig+++ b/TUI/theme.zig@@ -144,7 +144,29 @@ pub fn skipEsc(s: []const u8, start: usize) usize {return i;}-/// Columns in `s`, skipping SGR. Assumes 1-col codepoints (no CJK/emoji width).+/// 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.+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+ else => 1,+ };+}++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 };+}++/// Columns in `s`, skipping SGR; CJK/emoji count 2, combining marks 0.pub fn visibleLen(s: []const u8) usize {var n: usize = 0;var i: usize = 0;@@ -153,9 +175,9 @@ pub fn visibleLen(s: []const u8) usize {i = skipEsc(s, i);continue;}- const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;- i += @min(w, s.len - i);- n += 1;+ const c = cpAt(s, i);+ i += c.step;+ n += c.w;}return n;}@@ -163,15 +185,15 @@ pub fn visibleLen(s: []const u8) usize {pub fn takeCols(s: []const u8, max: usize) []const u8 {var n: usize = 0;var i: usize = 0;- while (i < s.len and n < max) {+ while (i < s.len) {if (s[i] == 0x1b) {i = skipEsc(s, i);continue;}- const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;- const step = @min(w, s.len - i);- i += step;- n += 1;+ const c = cpAt(s, i);+ if (n + c.w > max) break; // a wide glyph that would straddle the edge stays out+ i += c.step;+ n += c.w;}return s[0..i];}@@ -216,15 +238,33 @@ 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);}-/// Wrap `s` so no row is wider than `width` columns. SGR is preserved.+/// 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;+ }+ if (active.items.len > 96) active.clearRetainingCapacity(); // bound pathological runs+ active.appendSlice(seq) catch {};+}++/// 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 col: usize = 0;var i: usize = 0;while (i < s.len) {if (s[i] == '\n') {try out.append('\n');+ try out.appendSlice(active.items);col = 0;i += 1;continue;@@ -233,17 +273,18 @@ pub fn wrapToWidth(a: std.mem.Allocator, s: []const u8, width: usize) ![]const uconst start = i;i = skipEsc(s, i);try out.appendSlice(s[start..i]);+ trackSgr(&active, s[start..i]);continue;}- const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;- const step = @min(w, s.len - i);- if (col >= width) {+ const c = cpAt(s, i);+ if (col + c.w > width and col > 0) {try out.append('\n');+ try out.appendSlice(active.items);col = 0;}- try out.appendSlice(s[i .. i + step]);- col += 1;- i += step;+ try out.appendSlice(s[i .. i + c.step]);+ col += c.w;+ i += c.step;}return out.toOwnedSlice();}@@ -252,12 +293,15 @@ pub fn wrapToWidth(a: std.mem.Allocator, s: []const u8, width: usize) ![]const upub 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 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);col = 0;last_sp = null;i += 1;@@ -265,31 +309,28 @@ pub fn wrapPreferWords(a: std.mem.Allocator, s: []const u8, width: usize) ![]con}if (s[i] == 0x1b) {const start = i;- i += 1;- if (i < s.len and s[i] == '[') {- i += 1;- while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) : (i += 1) {}- if (i < s.len) i += 1;- }+ i = skipEsc(s, i); // full skip: hand-rolled CSI-only parsing broke a \n INTO an OSC hyperlinktry out.appendSlice(s[start..i]);+ trackSgr(&active, s[start..i]);continue;}- const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;- const step = @min(w, s.len - i);- if (col + 1 > width) {+ const c = cpAt(s, i);+ if (col + c.w > width) {if (last_sp) |sp| {out.items[sp] = '\n';+ try out.insertSlice(sp + 1, active.items);col = visibleLen(out.items[sp + 1 ..]);last_sp = null;} else {try out.append('\n');+ try out.appendSlice(active.items);col = 0;}}if (s[i] == ' ') last_sp = out.items.len;- try out.appendSlice(s[i .. i + step]);- col += 1;- i += step;+ try out.appendSlice(s[i .. i + c.step]);+ col += c.w;+ i += c.step;}return out.toOwnedSlice();}@@ -323,3 +364,26 @@ test "visibleLen and takeCols treat OSC/APC as invisible" {const cut = takeCols("\x1b]8;;u\x07ab", 1);try std.testing.expectEqualStrings("\x1b]8;;u\x07a", cut);}++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}"));+ try std.testing.expectEqual(@as(usize, 1), visibleLen("e\u{0301}"));+ try std.testing.expectEqualStrings("a", takeCols("a\u{1F680}", 2)); // rocket won't fit in 1 col+}++test "wrap re-emits active SGR on continuation rows" {+ const got = try wrapToWidth(std.testing.allocator, "\x1b[32mabcdefgh\x1b[0m", 4);+ defer std.testing.allocator.free(got);+ var it = std.mem.splitScalar(u8, got, '\n');+ _ = it.next();+ const row2 = it.next().?;+ try std.testing.expect(std.mem.startsWith(u8, row2, "\x1b[32m"));+}++test "wrapPreferWords keeps OSC strings intact" {+ const link = "\x1b]8;;http://example.com/long/url\x07go\x1b]8;;\x07 tail words here";+ const got = try wrapPreferWords(std.testing.allocator, link, 10);+ defer std.testing.allocator.free(got);+ try std.testing.expect(std.mem.indexOf(u8, got, "http://example.com/long/url") != null); // URL unbroken+}