Skip to content

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

Python

fix(tui): make the markdown pipeline safe for streamed deltas

Rach Pradhane570d2706a00
diff --git a/TUI/engine.zig b/TUI/engine.zig
index c1bacd6a..e3e34514 100644
--- a/TUI/engine.zig
+++ b/TUI/engine.zig
@@ -47,11 +47,31 @@ pub const StreamBuf = struct {
pub fn appendBytes(self: *StreamBuf, bytes: []const u8) void {
const cur = self.len.load(.monotonic);
if (cur >= self.buf.len) return;
- const n = @min(bytes.len, self.buf.len - cur);
+ var n = @min(bytes.len, self.buf.len - cur);
+ // Overflow drops the tail for good, so a clip must not land INSIDE a
+ // codepoint: the missing bytes never arrive and the live row would
+ // paint replacement garbage that persists for the rest of the turn.
+ if (n < bytes.len) n = utf8Floor(bytes, n);
+ if (n == 0) return;
@memcpy(self.buf[cur .. cur + n], bytes[0..n]);
self.len.store(cur + n, .release);
}
+ /// Largest k <= n where `s[0..k]` ends on a whole UTF-8 codepoint.
+ fn utf8Floor(s: []const u8, n: usize) usize {
+ if (n == 0 or n >= s.len) return n;
+ var k = n;
+ while (k > 0) : (k -= 1) {
+ const b = s[k - 1];
+ if (b < 0x80) return k; // ASCII byte ends a codepoint
+ if (b >= 0xc0) { // lead byte: does its whole sequence fit?
+ const len = std.unicode.utf8ByteSequenceLength(b) catch return k - 1;
+ return if (k - 1 + len <= n) n else k - 1;
+ }
+ }
+ return 0; // all continuation bytes: nothing whole to keep
+ }
+
pub fn snapshot(self: *StreamBuf, gpa: std.mem.Allocator) ?[]u8 {
const n = self.len.load(.acquire);
if (n == 0) return null;
@@ -191,3 +211,21 @@ test "StreamBuf: append then snapshot, overflow is silent" {
s.appendBytes(" world!!!!");
try std.testing.expectEqual(@as(usize, 8), s.len.load(.acquire));
}
+
+test "StreamBuf: an overflow clip lands on a codepoint boundary" {
+ // The dropped tail never arrives, so a clip inside 🚀 would leave the live
+ // row painting replacement garbage for the rest of the turn.
+ var buf: [8]u8 = undefined;
+ var s: StreamBuf = .{ .buf = &buf };
+ s.appendBytes("ab");
+ s.appendBytes("🚀🚀"); // 8 bytes: only the first fits whole
+ const snap = s.snapshot(std.testing.allocator).?;
+ defer std.testing.allocator.free(snap);
+ try std.testing.expect(std.unicode.utf8ValidateSlice(snap));
+ try std.testing.expectEqualStrings("ab🚀", snap);
+ // A chunk that cannot contribute even one whole glyph writes nothing.
+ var tiny: [2]u8 = undefined;
+ var t: StreamBuf = .{ .buf = &tiny };
+ t.appendBytes("日");
+ try std.testing.expectEqual(@as(usize, 0), t.len.load(.acquire));
+}
diff --git a/TUI/markdown.zig b/TUI/markdown.zig
index 67bcecb9..18871cd2 100644
--- a/TUI/markdown.zig
+++ b/TUI/markdown.zig
@@ -9,15 +9,78 @@ pub fn render(a: std.mem.Allocator, src: []const u8, accent: []const u8) ![]cons
return renderTinted(a, src, accent, theme_mod.zinc400, theme_mod.zinc200);
}
+// ── Streaming contract ──────────────────────────────────────────────────────
+// Every renderer here is a PURE function of the accumulated message text: the
+// pager re-renders the whole entry each frame, so a document that arrived in
+// deltas lands on exactly the bytes a one-shot render produces. The only thing
+// a chunk boundary can hand us is a partial TAIL, and `sanitize` is what makes
+// that tail harmless — see markdown_stream_tests.zig for the pinned invariant.
+
+/// Is there anything in `src` a frame cannot carry? Model text goes to the
+/// terminal verbatim, so a C0 control (CR rewinds the row, BEL rings, ESC
+/// paints) or a byte sequence that is not valid UTF-8 (a delta split a glyph)
+/// has to be filtered first. The scan is the fast path: clean prose renders
+/// with no copy at all.
+fn needsClean(src: []const u8) bool {
+ for (src) |b| {
+ if (b < 0x20) {
+ if (b != '\n' and b != '\t') return true;
+ } else if (b == 0x7f) return true;
+ }
+ return !std.unicode.utf8ValidateSlice(src);
+}
+
+/// Drop what `needsClean` found: whole escape sequences (never just the ESC,
+/// or the parameter bytes would land as literal text), C0/DEL other than
+/// newline and tab, and any byte that is not part of a complete UTF-8
+/// codepoint. A glyph the delta cut in half is HELD BACK rather than painted
+/// as U+FFFD — the next delta completes it and the frame settles.
+pub fn sanitize(a: std.mem.Allocator, src: []const u8) ![]const u8 {
+ var out = std.array_list.Managed(u8).init(a);
+ errdefer out.deinit();
+ var i: usize = 0;
+ while (i < src.len) {
+ const b = src[i];
+ if (b == 0x1b) {
+ i = theme_mod.skipEsc(src, i); // a truncated sequence eats the rest
+ continue;
+ }
+ if (b < 0x20 or b == 0x7f) {
+ if (b == '\n' or b == '\t') try out.append(b);
+ i += 1;
+ continue;
+ }
+ if (b < 0x80) {
+ try out.append(b);
+ i += 1;
+ continue;
+ }
+ const len = std.unicode.utf8ByteSequenceLength(b) catch {
+ i += 1;
+ continue;
+ };
+ if (i + len > src.len) break; // the tail of a split glyph: wait for it
+ _ = std.unicode.utf8Decode(src[i .. i + len]) catch {
+ i += 1;
+ continue;
+ };
+ try out.appendSlice(src[i .. i + len]);
+ i += len;
+ }
+ return out.toOwnedSlice();
+}
+
/// Theme-aware render: grok-style code fences — markers hidden behind a blank
/// separator row, a full-width background band (clear-to-EOL under the code
/// bg), and token colors from syntax.zig in the theme's polarity. Everything
/// else matches renderTinted.
pub fn renderThemed(a: std.mem.Allocator, src: []const u8, th: theme_mod.Theme, width: usize) ![]const u8 {
const light = th.id == .day;
+ const clean = if (needsClean(src)) try sanitize(a, src) else src;
+ defer if (clean.ptr != src.ptr) a.free(clean);
var lines = std.array_list.Managed([]const u8).init(a);
defer lines.deinit();
- var split = std.mem.splitScalar(u8, src, '\n');
+ var split = std.mem.splitScalar(u8, clean, '\n');
while (split.next()) |line| try lines.append(line);
var out = std.array_list.Managed(u8).init(a);
@@ -96,9 +159,11 @@ pub fn renderThemed(a: std.mem.Allocator, src: []const u8, th: theme_mod.Theme,
}
pub fn renderTinted(a: std.mem.Allocator, src: []const u8, accent: []const u8, muted: []const u8, text: []const u8) ![]const u8 {
+ const clean = if (needsClean(src)) try sanitize(a, src) else src;
+ defer if (clean.ptr != src.ptr) a.free(clean);
var lines = std.array_list.Managed([]const u8).init(a);
defer lines.deinit();
- var split = std.mem.splitScalar(u8, src, '\n');
+ var split = std.mem.splitScalar(u8, clean, '\n');
while (split.next()) |line| try lines.append(line);
var out = std.array_list.Managed(u8).init(a);
@@ -158,13 +223,15 @@ pub fn renderTinted(a: std.mem.Allocator, src: []const u8, accent: []const u8, m
/// User-row display: `@[path]` → `[Image #n]`, `/cmd` in accent.
pub fn renderUser(a: std.mem.Allocator, src: []const u8, accent: []const u8, text: []const u8) ![]const u8 {
+ const clean = if (needsClean(src)) try sanitize(a, src) else src;
+ defer if (clean.ptr != src.ptr) a.free(clean);
var out = std.array_list.Managed(u8).init(a);
try out.appendSlice(text);
var img_n: u32 = 0;
var i: usize = 0;
- while (i < src.len) {
- if (std.mem.startsWith(u8, src[i..], "@[")) {
- if (std.mem.indexOfScalarPos(u8, src, i + 2, ']')) |close| {
+ while (i < clean.len) {
+ if (std.mem.startsWith(u8, clean[i..], "@[")) {
+ if (std.mem.indexOfScalarPos(u8, clean, i + 2, ']')) |close| {
img_n += 1;
var chip: [24]u8 = undefined;
const label = std.fmt.bufPrint(&chip, "[Image #{d}]", .{img_n}) catch "[Image]";
@@ -172,22 +239,22 @@ pub fn renderUser(a: std.mem.Allocator, src: []const u8, accent: []const u8, tex
try out.appendSlice(label);
try out.appendSlice(text);
i = close + 1;
- if (i < src.len and src[i] == ' ') i += 1;
+ if (i < clean.len and clean[i] == ' ') i += 1;
continue;
}
}
- if (src[i] == '/' and (i == 0 or isBreak(src[i - 1]))) {
+ if (clean[i] == '/' and (i == 0 or isBreak(clean[i - 1]))) {
var j = i + 1;
- while (j < src.len and (std.ascii.isAlphanumeric(src[j]) or src[j] == '-')) j += 1;
+ while (j < clean.len and (std.ascii.isAlphanumeric(clean[j]) or clean[j] == '-')) j += 1;
if (j > i + 1) {
try out.appendSlice(accent);
- try out.appendSlice(src[i..j]);
+ try out.appendSlice(clean[i..j]);
try out.appendSlice(text);
i = j;
continue;
}
}
- try out.append(src[i]);
+ try out.append(clean[i]);
i += 1;
}
return out.toOwnedSlice();
diff --git a/TUI/scrollback.zig b/TUI/scrollback.zig
index 1186e025..76b10d57 100644
--- a/TUI/scrollback.zig
+++ b/TUI/scrollback.zig
@@ -395,18 +395,11 @@ fn firstLine(s: []const u8) []const u8 {
return s;
}
+/// The live tail is raw model bytes: escapes, C0 controls (a CR would rewind
+/// the row) and the half glyph a delta boundary left behind all have to go
+/// before it reaches a frame. Same filter the finished message gets.
fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {
- var out = std.array_list.Managed(u8).init(a);
- var i: usize = 0;
- while (i < s.len) {
- if (s[i] == 0x1b) {
- i = theme_mod.skipEsc(s, i);
- continue;
- }
- out.append(s[i]) catch {};
- i += 1;
- }
- return out.items;
+ return @import("markdown.zig").sanitize(a, s) catch s;
}
fn tail(a: std.mem.Allocator, s: []const u8, width: usize, max_lines: usize) ![]const u8 {
diff --git a/src/repl_types.zig b/src/repl_types.zig
index d1c14e3c..41eae720 100644
--- a/src/repl_types.zig
+++ b/src/repl_types.zig
@@ -49,10 +49,30 @@ pub const StreamBuf = struct {
pub fn appendBytes(self: *StreamBuf, bytes: []const u8) void {
const cur = self.len.load(.monotonic);
if (cur >= self.buf.len) return;
- const n = @min(bytes.len, self.buf.len - cur);
+ var n = @min(bytes.len, self.buf.len - cur);
+ // The dropped tail never comes back, so a clip must not land INSIDE a
+ // codepoint or the live preview keeps half a glyph for the whole turn.
+ // Mirrors TUI/engine.zig's StreamBuf — tui_launch.liveStream overlays
+ // one struct on the other, so their semantics have to match too.
+ if (n < bytes.len) n = utf8Floor(bytes, n);
+ if (n == 0) return;
@memcpy(self.buf[cur .. cur + n], bytes[0..n]);
self.len.store(cur + n, .release);
}
+ /// Largest k <= n where `s[0..k]` ends on a whole UTF-8 codepoint.
+ fn utf8Floor(s: []const u8, n: usize) usize {
+ if (n == 0 or n >= s.len) return n;
+ var k = n;
+ while (k > 0) : (k -= 1) {
+ const b = s[k - 1];
+ if (b < 0x80) return k;
+ if (b >= 0xc0) {
+ const len = std.unicode.utf8ByteSequenceLength(b) catch return k - 1;
+ return if (k - 1 + len <= n) n else k - 1;
+ }
+ }
+ return 0;
+ }
pub fn snapshot(self: *StreamBuf, gpa: std.mem.Allocator) ?[]u8 {
const n = self.len.load(.acquire);
if (n == 0) return null;