Skip to content

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

Python

fix(tui): engine-backed /compact, steady thinking, split-sequence hardening, and the #516-#523 audit batch

Rach Pradhaneaf6e2d0c45c
diff --git a/TUI/catalog.zig b/TUI/catalog.zig
index 9ecb9bde..71cde7b1 100644
--- a/TUI/catalog.zig
+++ b/TUI/catalog.zig
@@ -12,7 +12,7 @@ pub const Item = struct {
pub const items = [_]Item{
.{ .name = "/new", .desc = "Start a fresh session", .aliases = &.{"/clear"} },
.{ .name = "/home", .desc = "Return to the welcome screen", .aliases = &.{"/welcome"} },
- .{ .name = "/compact", .desc = "Compress conversation history" },
+ .{ .name = "/compact", .desc = "Engine-compact model-visible history" },
.{ .name = "/context", .desc = "Show context-window use" },
.{ .name = "/session-info", .desc = "Session details", .aliases = &.{ "/status", "/info" } },
.{ .name = "/usage", .desc = "Token usage and cost", .aliases = &.{"/cost"} },
diff --git a/TUI/chrome.zig b/TUI/chrome.zig
index b2b4a117..52334452 100644
--- a/TUI/chrome.zig
+++ b/TUI/chrome.zig
@@ -145,10 +145,13 @@ pub fn slashMenu(self: *const Model, a: std.mem.Allocator, width: usize) ![]cons
if (n == 0) return "";
const th = self.theme();
var out = std.array_list.Managed(u8).init(a);
+ // Clamped selection + a window that follows it, so the highlighted row is
+ // always visible and always the row Enter fires (#522).
const show = @min(n, @as(usize, 8));
- const sel = if (n == 0) 0 else self.slash_sel % n;
- var i: usize = 0;
- while (i < show) : (i += 1) {
+ const sel = @min(self.slash_sel, n - 1);
+ const first = if (sel >= show) sel + 1 - show else 0;
+ var i: usize = first;
+ while (i < first + show) : (i += 1) {
const it = catalog.items[idx[i]];
const mark: []const u8 = if (i == sel) "› " else " ";
const line = try std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, it.name, it.desc });
diff --git a/TUI/dispatch.zig b/TUI/dispatch.zig
index e25bf04a..d66aae7f 100644
--- a/TUI/dispatch.zig
+++ b/TUI/dispatch.zig
@@ -46,6 +46,15 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {
const item = catalog.lookup(cmd);
const canon = if (item) |it| it.name else cmd;
+ // #521: history-destroying commands must not run under a live job — the
+ // steer guard in promptKey only covers plain text, and the slash menu,
+ // palette, and steer drain all land here.
+ const destroys = std.mem.eql(u8, canon, "/new") or std.mem.eql(u8, canon, "/compact") or std.mem.eql(u8, canon, "/rewind");
+ if (self.pending != null and destroys) {
+ self.push(.system, "a turn is still running — press Esc to cancel it first") catch {};
+ return .stay;
+ }
+
if (std.mem.eql(u8, canon, "/quit")) {
self.quit_requested = true;
return .quit;
@@ -241,18 +250,45 @@ pub fn rewind(self: *Model) void {
}
pub fn compact(self: *Model) void {
- const keep = 6;
- const n = self.history.items.len;
- if (n <= keep) {
- self.push(.system, "nothing to compact") catch {};
+ const f = engine.g_compact_fn orelse {
+ self.push(.system, "compaction needs a live session") catch {};
+ return;
+ };
+ var turns = std.array_list.Managed(engine.Turn).init(self.alloc);
+ defer {
+ for (turns.items) |t| self.alloc.free(t.text);
+ turns.deinit();
+ }
+ for (self.history.items) |e| {
+ const role: ?engine.Turn.Role = switch (e.kind) {
+ .user => .user,
+ .assistant => .assistant,
+ else => null,
+ };
+ if (role) |r| {
+ const t = self.alloc.dupe(u8, e.text) catch continue;
+ turns.append(.{ .role = r, .text = t }) catch self.alloc.free(t);
+ }
+ }
+ var out: engine.CompactOut = .{};
+ const ok = f(engine.g_turn_ctx, self.alloc, turns.items, &out);
+ defer {
+ if (out.note.len > 0) self.alloc.free(out.note);
+ for (out.turns) |t| self.alloc.free(t.text);
+ if (out.turns.len > 0) self.alloc.free(out.turns);
+ }
+ if (!ok) {
+ self.push(.system, if (out.note.len > 0) out.note else "compaction failed, history unchanged") catch {};
return;
}
- const drop_to = n - keep;
- var k: usize = 0;
- while (k < drop_to) : (k += 1) self.alloc.free(self.history.items[k].text);
- std.mem.copyForwards(app.Entry, self.history.items[0..], self.history.items[drop_to..]);
- self.history.shrinkRetainingCapacity(n - drop_to);
- self.push(.system, "compacted — kept recent turns") catch {};
+ self.clearHistory();
+ if (out.note.len > 0) self.push(.system, out.note) catch {};
+ for (out.turns) |t| {
+ self.push(switch (t.role) {
+ .user => .user,
+ .assistant => .assistant,
+ }, t.text) catch {};
+ }
}
pub fn recallPrev(self: *Model) void {
@@ -545,3 +581,7 @@ test "lastLines caps ! output to the tail" {
try std.testing.expectEqualStrings("c\nd", lastLines("a\nb\nc\nd", 2));
try std.testing.expectEqualStrings("a\nb", lastLines("a\nb", 5));
}
+
+test {
+ _ = @import("dispatch_tests.zig"); // overflow tests (600-line cap)
+}
diff --git a/TUI/dispatch_tests.zig b/TUI/dispatch_tests.zig
new file mode 100644
index 00000000..b0dde112
--- /dev/null
+++ b/TUI/dispatch_tests.zig
@@ -0,0 +1,59 @@
+//! dispatch.zig tests that outgrew the 600-line source cap.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const dispatch = @import("dispatch.zig");
+const engine = @import("engine.zig");
+const Model = app.Model;
+
+test "/new /compact /rewind are blocked while a job is pending (#521)" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.user, "hi");
+ const job = try std.testing.allocator.create(engine.Job);
+ job.* = .{
+ .threaded = false,
+ .gpa = std.testing.allocator,
+ .history = try std.testing.allocator.alloc(engine.Turn, 0),
+ .params = .{},
+ .stream = .{},
+ };
+ m.pending = job;
+ _ = dispatch.runCommand(&m, "/new");
+ try std.testing.expect(m.pending != null);
+ try std.testing.expectEqualStrings("hi", m.history.items[0].text);
+ try std.testing.expect(std.mem.indexOf(u8, m.history.items[1].text, "still running") != null);
+ _ = dispatch.runCommand(&m, "/rewind");
+ _ = dispatch.runCommand(&m, "/compact");
+ try std.testing.expectEqualStrings("hi", m.history.items[0].text);
+}
+
+test "/compact never crops locally; engine stub rewrites history" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.user, "alpha");
+ try m.push(.assistant, "beta");
+ try m.push(.user, "gamma");
+ _ = dispatch.applyLine(&m, "/compact");
+ try std.testing.expectEqual(@as(usize, 4), m.history.items.len); // 3 + notice
+ try std.testing.expect(std.mem.indexOf(u8, m.history.items[3].text, "live session") != null);
+
+ engine.g_compact_fn = struct {
+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const engine.Turn, out: *engine.CompactOut) bool {
+ out.note = gpa.dupe(u8, "history compacted to a 12-char summary") catch "";
+ const turns = gpa.alloc(engine.Turn, 1) catch return false;
+ turns[0] = .{ .role = .user, .text = gpa.dupe(u8, "Context: earlier work") catch "" };
+ out.turns = turns;
+ return true;
+ }
+ }.f;
+ defer engine.g_compact_fn = null;
+ _ = dispatch.applyLine(&m, "/compact");
+ try std.testing.expectEqual(@as(usize, 2), m.history.items.len);
+ try std.testing.expectEqual(app.EntryKind.system, m.history.items[0].kind);
+ try std.testing.expectEqual(app.EntryKind.user, m.history.items[1].kind);
+ try std.testing.expectEqualStrings("Context: earlier work", m.history.items[1].text);
+}
diff --git a/TUI/engine.zig b/TUI/engine.zig
index 46d4fecd..30cb56ec 100644
--- a/TUI/engine.zig
+++ b/TUI/engine.zig
@@ -52,6 +52,13 @@ pub const BashFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, cmd
pub const FilesFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;
/// Copy text to the system clipboard; true on success.
pub const CopyFn = *const fn (turn_ctx: ?*anyopaque, text: []const u8) bool;
+/// Engine-owned history compaction. Fills `out` with gpa-owned note + turns
+/// (caller frees). Returns false when history is unchanged.
+pub const CompactOut = struct {
+ note: []const u8 = "",
+ turns: []Turn = &.{},
+};
+pub const CompactFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, out: *CompactOut) bool;
pub const Job = struct {
thread: std.Thread = undefined,
@@ -76,6 +83,7 @@ pub var g_paste_fn: ?PasteFn = null;
pub var g_bash_fn: ?BashFn = null;
pub var g_files_fn: ?FilesFn = null;
pub var g_copy_fn: ?CopyFn = null;
+pub var g_compact_fn: ?CompactFn = null;
pub var g_model_name: []const u8 = "";
pub var g_models: []const u8 = "";
pub var g_cwd: []const u8 = ".";
diff --git a/TUI/key.zig b/TUI/key.zig
index 42048767..fdeb381b 100644
--- a/TUI/key.zig
+++ b/TUI/key.zig
@@ -119,6 +119,11 @@ fn escapeSeq(bytes: []const u8, i: *usize) ?Key {
/// OSC/DCS/APC/PM/SOS reply on stdin (e.g. a color query answer) — consume
/// through BEL or ST so the payload is never typed into the prompt.
+/// Longest stdin reply we ever solicit (OSC 10/11 color answers are ~25
+/// bytes; kitty acks are shorter). Anything bigger behind an unterminated
+/// introducer is typed text, not a reply (#516).
+const max_reply_pending = 128;
+
fn stringSeq(bytes: []const u8, i: *usize) ?Key {
var j = i.* + 1;
while (j < bytes.len) : (j += 1) {
@@ -135,6 +140,18 @@ fn stringSeq(bytes: []const u8, i: *usize) ?Key {
}
break; // ST split across reads — wait for the backslash
}
+ if (bytes[j] == 0x0d or bytes[j] == 0x0a) {
+ // Replies never carry CR/LF: this is typed text behind an
+ // Alt+]/P/X/^/_ chord. Swallow only the introducer — like any
+ // unbound alt-chord — so the text reparses instead of the
+ // keyboard wedging until it is destroyed (#516).
+ i.* += 1;
+ return .ignore;
+ }
+ }
+ if (bytes.len - i.* > max_reply_pending) {
+ i.* += 1; // over any real reply's size — same chord recovery (#516)
+ return .ignore;
}
i.* -= 1; // rewind to the ESC; the terminator is still in flight
return null;
@@ -522,3 +539,23 @@ test "OSC and APC replies on stdin are consumed, never typed" {
try std.testing.expect(next("\x1b]11;rgb:14", &i) == null);
try std.testing.expectEqual(@as(usize, 0), i);
}
+
+test "typed text behind an Alt+] chord recovers instead of wedging (#516)" {
+ // CR proves it is not a reply: the introducer is swallowed as a chord
+ // and the sentence reparses as ordinary keys, Enter included.
+ var i: usize = 0;
+ const bytes = "\x1b]fix it\r";
+ try std.testing.expectEqual(Key.ignore, next(bytes, &i).?);
+ try std.testing.expectEqual(Key{ .char = 'f' }, next(bytes, &i).?);
+ var last: Key = .ignore;
+ while (next(bytes, &i)) |k| last = k;
+ try std.testing.expectEqual(Key.enter, last);
+ // Longer than any real reply — recover even without CR/LF.
+ var big: [140]u8 = undefined;
+ big[0] = 0x1b;
+ big[1] = 'P';
+ @memset(big[2..], 'a');
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next(&big, &i).?);
+ try std.testing.expectEqual(Key{ .char = 'a' }, next(&big, &i).?);
+}
diff --git a/TUI/keys.zig b/TUI/keys.zig
index 2ddc967b..3b6e57e0 100644
--- a/TUI/keys.zig
+++ b/TUI/keys.zig
@@ -191,15 +191,6 @@ fn scrollbackKey(self: *Model, k: Key) Effect {
return .stay;
}
-fn lastToolIdx(self: *const Model) ?usize {
- var i = self.history.items.len;
- while (i > 0) {
- i -= 1;
- if (self.history.items[i].kind == .tool) return i;
- }
- return null;
-}
-
fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {
if (ev.btn == 64) {
scrollBy(self, 3);
@@ -222,17 +213,15 @@ fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {
}
if (y < self.mid_origin) return .stay;
const vis = y - self.mid_origin + self.mid_skip;
- const idx = scrollback.indexAtVisual(self, vis, self.last_term_width) orelse lastToolIdx(self);
self.focus = .scrollback;
- if (idx) |i| {
- self.selected = i;
- if (self.history.items[i].kind == .tool) self.toggleToolGroup(i);
- }
+ // A click on blank padding maps to no entry — it must not select or
+ // toggle anything (#519).
+ const i = scrollback.indexAtVisual(self, vis, self.last_term_width) orelse return .stay;
+ self.selected = i;
+ if (self.history.items[i].kind == .tool) self.toggleToolGroup(i);
return .stay;
}
-
-
fn slashOpen(self: *const Model) bool {
const v = self.input.getValue();
return self.focus == .prompt and v.len > 0 and v[0] == '/';
@@ -240,7 +229,11 @@ fn slashOpen(self: *const Model) bool {
fn slashKey(self: *Model, k: Key) bool {
if (k == .down) {
- self.slash_sel += 1;
+ // Clamp to the filtered list so the highlight and the Enter target
+ // can never diverge onto an invisible command (#522).
+ var idx: [catalog.items.len]usize = undefined;
+ const n = catalog.filter(self.input.getValue(), &idx);
+ if (n > 0 and self.slash_sel + 1 < n) self.slash_sel += 1;
return true;
}
if (k == .up) {
@@ -440,6 +433,41 @@ test "Cmd+Delete and Ctrl+U kill the draft, not the viewport" {
try std.testing.expect(m.follow);
}
+test "click on blank padding selects and toggles nothing (#519)" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.user, "hi");
+ try m.push(.tool, "⚙ bash");
+ try m.push(.tool, "✓ bash");
+ m.last_term_height = 24;
+ m.last_term_width = 80;
+ m.mid_origin = 0;
+ m.mid_skip = 0;
+ m.prompt_origin = 20;
+ try std.testing.expect(m.history.items[1].folded);
+ _ = handle(&m, .{ .mouse = .{ .btn = 0, .x = 2, .y = 15, .down = true } });
+ try std.testing.expect(m.history.items[1].folded);
+ try std.testing.expectEqual(app.Focus.scrollback, m.focus);
+}
+
+test "slash selection clamps to the filtered list and stays visible (#522)" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.input.setValue("/");
+ var idx: [catalog.items.len]usize = undefined;
+ const n = catalog.filter("/", &idx);
+ try std.testing.expect(n > 8); // the bug needs more commands than visible rows
+ var presses: usize = 0;
+ while (presses < n + 10) : (presses += 1) _ = handle(&m, .down);
+ try std.testing.expectEqual(n - 1, m.slash_sel);
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const menu = try @import("chrome.zig").slashMenu(&m, arena.allocator(), 80);
+ try std.testing.expect(std.mem.indexOf(u8, menu, "› ") != null);
+}
+
test "click on a folded tool row expands it" {
var m: Model = undefined;
m.setup(std.testing.allocator);
diff --git a/TUI/root.zig b/TUI/root.zig
index 70ce760d..aae43aca 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -20,6 +20,8 @@ pub const StreamBuf = engine.StreamBuf;
pub const TurnFn = engine.TurnFn;
pub const ModelFn = engine.ModelFn;
pub const CancelFn = engine.CancelFn;
+pub const CompactOut = engine.CompactOut;
+pub const CompactFn = engine.CompactFn;
pub const RunOpts = run_mod.RunOpts;
pub const run = run_mod.run;
pub const theme = @import("theme.zig");
diff --git a/TUI/run.zig b/TUI/run.zig
index 24ee32e5..83e2741f 100644
--- a/TUI/run.zig
+++ b/TUI/run.zig
@@ -35,6 +35,7 @@ pub const RunOpts = struct {
bash_fn: ?engine.BashFn = null,
files_fn: ?engine.FilesFn = null,
copy_fn: ?engine.CopyFn = null,
+ compact_fn: ?engine.CompactFn = null,
};
pub fn run(
@@ -53,6 +54,7 @@ pub fn run(
engine.g_bash_fn = opts.bash_fn;
engine.g_files_fn = opts.files_fn;
engine.g_copy_fn = opts.copy_fn;
+ engine.g_compact_fn = opts.compact_fn;
engine.g_model_name = opts.model_name;
engine.g_models = opts.models;
engine.g_cwd = opts.cwd;
@@ -119,15 +121,29 @@ pub fn run(
if (!tty.poll(wait)) {
if (pending_len > 0) {
esc_stall += 1;
- if (esc_stall >= 2) {
- if (inbuf[0] == 0x1b and keys.handle(&m, .escape) == .quit) m.running = false;
- pending_len = 0;
- esc_stall = 0;
+ switch (stallVerdict(inbuf[0..pending_len], esc_stall)) {
+ .wait => {},
+ .escape_key => {
+ if (keys.handle(&m, .escape) == .quit) m.running = false;
+ pending_len = 0;
+ esc_stall = 0;
+ },
+ .drop => {
+ pending_len = 0;
+ esc_stall = 0;
+ },
}
}
continue;
}
esc_stall = 0;
+ if (pending_len == inbuf.len) {
+ // A stuck head has filled the whole buffer: that is a parser
+ // wedge, not a dead tty. Drop it rather than letting the
+ // zero-length read below masquerade as a hangup and kill the
+ // TUI mid-session (#517).
+ pending_len = 0;
+ }
const got = tty.readStdin(inbuf[pending_len..]);
if (got == 0) {
// poll says readable but read gives nothing: hangup or transient
@@ -163,6 +179,20 @@ pub fn run(
}
}
+/// What to do with input bytes stuck mid-sequence after quiet polls (~25ms
+/// each). Exactly one pending ESC byte is the Escape key after the #94 grace.
+/// A longer prefix is a truncated CSI/OSC split by link latency (ssh/tmux):
+/// delivering Escape cancelled live turns and typing the late tail sprayed
+/// "2;39M"-style debris into the transcript — wait for the tail instead, and
+/// only silently drop once it is clearly never coming.
+pub const StallVerdict = enum { wait, escape_key, drop };
+
+pub fn stallVerdict(pending: []const u8, stalls: u8) StallVerdict {
+ if (pending.len == 0) return .wait;
+ if (pending.len == 1 and pending[0] == 0x1b) return if (stalls >= 2) .escape_key else .wait;
+ return if (stalls >= 20) .drop else .wait;
+}
+
fn parkToShell(io: Io, w: *Io.Writer, raw: *tty.RawState) void {
w.writeAll(restore_mod.seq) catch {};
w.flush() catch {};
@@ -253,6 +283,20 @@ test "run loop enables click tracking and bracketed paste" {
try std.testing.expect(std.mem.indexOf(u8, src, &kitty_on) != null);
try std.testing.expect(std.mem.indexOf(u8, src, &wrap_off) != null);
try std.testing.expect(std.mem.indexOf(u8, src, "a=d,d=A") != null);
+ // #517: a buffer-filling parser wedge must be cleared before the read,
+ // or the zero-length read reads as a hangup and kills the TUI.
+ try std.testing.expect(std.mem.indexOf(u8, src, "pending_len == inbuf.len") != null);
+}
+
+test "a truncated CSI never becomes Escape or typed debris; a lone ESC still does (#94)" {
+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 1));
+ try std.testing.expectEqual(StallVerdict.escape_key, stallVerdict("\x1b", 2));
+ // Split SGR mouse / kitty CSI-u: never Escape, wait for the tail...
+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[<65;2;3", 2));
+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[5744", 19));
+ // ...and silently drop once it is clearly lost, so it is never typed.
+ try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[<65;2;3", 20));
+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("", 5));
}
test "rowChanged only flags the line that actually moved" {
diff --git a/TUI/scrollback.zig b/TUI/scrollback.zig
index 1958d928..4c580b06 100644
--- a/TUI/scrollback.zig
+++ b/TUI/scrollback.zig
@@ -166,21 +166,19 @@ fn summary(self: *const Model, a: std.mem.Allocator, start: usize, end: usize, s
if (isSearch(t)) searches += 1 else calls += 1;
}
const sel: []const u8 = if (selected) "› " else " ";
- const live = if (self.pending != null)
- try std.fmt.allocPrint(a, "{s}❙{s} ", .{ if (flickerOn(self.now_ms)) th.accent else th.muted, theme_mod.reset })
- else
- "";
+ // No live bar here: liveness belongs to the pending row alone. A bar on
+ // every summary made the whole transcript pulse and shift while thinking.
var out = std.array_list.Managed(u8).init(a);
if (calls > 0) {
const label = if (mcp_n == calls + searches)
- try std.fmt.allocPrint(a, "{s}{s}◆ Called {d} MCP tool{s}", .{ sel, live, calls, if (calls == 1) "" else "s" })
+ try std.fmt.allocPrint(a, "{s}◆ Called {d} MCP tool{s}", .{ sel, calls, if (calls == 1) "" else "s" })
else
- try std.fmt.allocPrint(a, "{s}{s}◆ Called {d} tool{s}", .{ sel, live, calls, if (calls == 1) "" else "s" });
+ try std.fmt.allocPrint(a, "{s}◆ Called {d} tool{s}", .{ sel, calls, if (calls == 1) "" else "s" });
try out.appendSlice(try theme_mod.paint(a, if (selected) th.accent else th.muted, label));
}
if (searches > 0) {
if (out.items.len > 0) try out.append('\n');
- const label = try std.fmt.allocPrint(a, "{s}{s}◆ Searched {d} MCP tool{s}", .{ sel, live, searches, if (searches == 1) "" else "s" });
+ const label = try std.fmt.allocPrint(a, "{s}◆ Searched {d} MCP tool{s}", .{ sel, searches, if (searches == 1) "" else "s" });
try out.appendSlice(try theme_mod.paint(a, if (selected) th.accent else th.muted, label));
}
return out.items;
@@ -221,8 +219,8 @@ fn row(self: *const Model, a: std.mem.Allocator, idx: usize, e: app.Entry, width
return theme_mod.wrapToWidth(a, line, 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 });
+ // Steady bar; the animated dots in the label carry the motion.
+ const line = try std.fmt.allocPrint(a, "{s}{s}❙{s} {s}{s}", .{ sel, th.accent, theme_mod.reset, 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 });
@@ -317,10 +315,6 @@ fn toolCard(a: std.mem.Allocator, th: theme_mod.Theme, start_text: []const u8, d
return joined;
}
-fn flickerOn(now_ms: u64) bool {
- return (now_ms / 140) % 2 == 0;
-}
-
fn thinkingGlyph(now_ms: u64) []const u8 {
_ = now_ms;
return "❙";
@@ -375,7 +369,42 @@ test "thinking animation is a word, not a lone spinner" {
try std.testing.expect(std.mem.startsWith(u8, thinkingLabel(0), "thinking"));
try std.testing.expect(!std.mem.eql(u8, thinkingLabel(0), thinkingLabel(320)));
try std.testing.expectEqualStrings("❙", thinkingGlyph(0));
- try std.testing.expect(flickerOn(0) != flickerOn(140));
+}
+
+test "a live turn never pulses or shifts historical rows" {
+ const engine = @import("engine.zig");
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.user, "hi");
+ try m.push(.tool, "⚙ bash");
+ try m.push(.tool, "✓ bash");
+ try m.push(.assistant, "done");
+ try m.push(.pending, "");
+ var sbuf: [16]u8 = undefined;
+ var none: [0]engine.Turn = .{};
+ var job: engine.Job = .{
+ .gpa = std.testing.allocator,
+ .history = &none,
+ .params = .{},
+ .stream = .{ .buf = &sbuf },
+ };
+ m.pending = &job;
+ defer m.pending = null;
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const t0 = try render(&m, arena.allocator(), 80, 0);
+ const t140 = try render(&m, arena.allocator(), 80, 140);
+ var it = std.mem.splitScalar(u8, t0, '\n');
+ var saw_summary = false;
+ while (it.next()) |ln| {
+ if (std.mem.indexOf(u8, ln, "Called") != null) {
+ saw_summary = true;
+ try std.testing.expect(std.mem.indexOf(u8, ln, "❙") == null);
+ }
+ }
+ try std.testing.expect(saw_summary);
+ try std.testing.expectEqualStrings(t0, t140);
}
test "prettyTool strips mcp prefix" {
diff --git a/TUI/theme.zig b/TUI/theme.zig
index 1640e37e..d78f9bbb 100644
--- a/TUI/theme.zig
+++ b/TUI/theme.zig
@@ -1,6 +1,7 @@
//! Theme slots as fixed SGR string literals (never padded rgb buffers).
const std = @import("std");
+const width_mod = @import("width.zig");
pub const Id = enum {
night,
@@ -125,7 +126,7 @@ pub fn skipEsc(s: []const u8, start: usize) usize {
return i;
}
-/// Columns in `s`, skipping SGR. Assumes 1-col codepoints (no CJK/emoji width).
+/// Columns in `s`, skipping SGR. CJK/emoji count 2, combining marks 0 (#518).
pub fn visibleLen(s: []const u8) usize {
var n: usize = 0;
var i: usize = 0;
@@ -134,9 +135,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 g = width_mod.glyph(s, i);
+ i += g.step;
+ n += g.cols;
}
return n;
}
@@ -149,10 +150,10 @@ pub fn takeCols(s: []const u8, max: usize) []const u8 {
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 g = width_mod.glyph(s, i);
+ if (n + g.cols > max) break; // a wide glyph never straddles the cut
+ i += g.step;
+ n += g.cols;
}
return s[0..i];
}
@@ -216,15 +217,14 @@ pub fn wrapToWidth(a: std.mem.Allocator, s: []const u8, width: usize) ![]const u
try out.appendSlice(s[start..i]);
continue;
}
- const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;
- const step = @min(w, s.len - i);
- if (col >= width) {
+ const g = width_mod.glyph(s, i);
+ if (col + g.cols > width and col > 0) {
try out.append('\n');
col = 0;
}
- try out.appendSlice(s[i .. i + step]);
- col += 1;
- i += step;
+ try out.appendSlice(s[i .. i + g.step]);
+ col += g.cols;
+ i += g.step;
}
return out.toOwnedSlice();
}
@@ -245,6 +245,19 @@ test "wrapToWidth splits a long line and keeps SGR" {
}
}
+test "visibleLen/wrapToWidth count CJK and emoji as two columns (#518)" {
+ try std.testing.expectEqual(@as(usize, 4), visibleLen("日本"));
+ try std.testing.expectEqual(@as(usize, 7), visibleLen("ab 🐉 c"));
+ try std.testing.expectEqualStrings("日", takeCols("日本", 3));
+ const got = try wrapToWidth(std.testing.allocator, "日本語のテキスト", 6);
+ defer std.testing.allocator.free(got);
+ try std.testing.expect(std.mem.count(u8, got, "\n") >= 1);
+ var it = std.mem.splitScalar(u8, got, '\n');
+ while (it.next()) |ln| {
+ try std.testing.expect(visibleLen(ln) <= 6);
+ }
+}
+
test "visibleLen and takeCols treat OSC/APC as invisible" {
try std.testing.expectEqual(@as(usize, 4), visibleLen("\x1b]8;;http://x\x07link\x1b]8;;\x07"));
try std.testing.expectEqual(@as(usize, 2), visibleLen("\x1b_Ga=d,d=A\x1b\\ok"));
diff --git a/TUI/tty.zig b/TUI/tty.zig
index 4eb8728c..995143f7 100644
--- a/TUI/tty.zig
+++ b/TUI/tty.zig
@@ -14,6 +14,8 @@ pub fn enterRaw() ?RawState {
raw.lflag.ICANON = false;
raw.lflag.ECHO = false;
raw.lflag.ISIG = false;
+ raw.lflag.IEXTEN = false; // ^V (0x16) reaches us, not the tty's lnext (#523)
+ raw.iflag.IXON = false; // ^S/^Q are keys, not XOFF/XON flow control (#523)
raw.cc[@intFromEnum(std.posix.V.MIN)] = 0;
raw.cc[@intFromEnum(std.posix.V.TIME)] = 0;
std.posix.tcsetattr(fd, .NOW, raw) catch return null;
@@ -37,6 +39,12 @@ pub fn readStdin(buf: []u8) usize {
return std.posix.read(std.posix.STDIN_FILENO, buf) catch 0;
}
+test "raw mode surrenders ^V and ^S to the app, not the line discipline (#523)" {
+ const src = @embedFile("tty.zig");
+ try std.testing.expect(std.mem.indexOf(u8, src, "IEXTEN = false") != null);
+ try std.testing.expect(std.mem.indexOf(u8, src, "IXON = false") != null);
+}
+
pub fn cols() usize {
if (builtin.os.tag == .windows) return 80;
var wsz: std.posix.winsize = undefined;
diff --git a/TUI/turn.zig b/TUI/turn.zig
index ca8ed2b2..55a6bc3b 100644
--- a/TUI/turn.zig
+++ b/TUI/turn.zig
@@ -57,11 +57,7 @@ pub fn finishJob(self: *Model) void {
if (!job.done.load(.acquire)) return;
if (job.threaded) job.thread.join();
- const n = self.history.items.len;
- if (n > 0 and self.history.items[n - 1].kind == .pending) {
- self.alloc.free(self.history.items[n - 1].text);
- self.history.shrinkRetainingCapacity(n - 1);
- }
+ _ = removePendingRows(self);
// The live stream carries ⚙/✓/✗ lines; the result is only the final
// answer. Keep the tool rows so they don't vanish with the pending entry.
if (job.stream.snapshot(self.alloc)) |live| {
@@ -127,14 +123,26 @@ pub fn harvestLiveTools(self: *Model) void {
const job = self.pending orelse return;
const live = job.stream.snapshot(self.alloc) orelse return;
defer self.alloc.free(live);
- var held: ?app.Entry = null;
- const n = self.history.items.len;
- if (n > 0 and self.history.items[n - 1].kind == .pending) {
- held = self.history.items[n - 1];
- self.history.shrinkRetainingCapacity(n - 1);
- }
+ const had_pending = removePendingRows(self);
persistToolLines(self, live);
- if (held) |e| self.history.append(e) catch {};
+ if (had_pending) self.push(.pending, "") catch {};
+}
+
+/// Remove every .pending row wherever it sits. Steering pushes "↳ queued"
+/// rows after the pending entry, so "pending is last" is not an invariant —
+/// assuming it stranded a permanent thinking row in the transcript (#520).
+fn removePendingRows(self: *Model) bool {
+ var had = false;
+ var i: usize = self.history.items.len;
+ while (i > 0) {
+ i -= 1;
+ if (self.history.items[i].kind == .pending) {
+ self.alloc.free(self.history.items[i].text);
+ _ = self.history.orderedRemove(i);
+ had = true;
+ }
+ }
+ return had;
}
fn persistToolLines(self: *Model, stream: []const u8) void {
@@ -274,3 +282,25 @@ test "Ctrl+C during a turn cancels once then quits" {
try std.testing.expect(m.pending != null);
try std.testing.expectEqual(@import("app.zig").Effect.quit, keys.handle(&m, .{ .ctrl = 'c' }));
}
+
+test "finishJob strips a pending row buried under steer echoes (#520)" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.user, "hi");
+ try m.push(.pending, "");
+ try m.push(.system, "↳ queued (1 waiting)");
+ const job = try std.testing.allocator.create(engine.Job);
+ job.* = .{
+ .threaded = false,
+ .gpa = std.testing.allocator,
+ .history = try std.testing.allocator.alloc(engine.Turn, 0),
+ .params = .{},
+ .stream = .{},
+ };
+ job.done.store(true, .release);
+ m.pending = job;
+ finishJob(&m);
+ try std.testing.expect(m.pending == null);
+ for (m.history.items) |e| try std.testing.expect(e.kind != .pending);
+}
diff --git a/TUI/width.zig b/TUI/width.zig
new file mode 100644
index 00000000..7a7cb3a1
--- /dev/null
+++ b/TUI/width.zig
@@ -0,0 +1,50 @@
+//! Display-column math (wcwidth-style) for the fullscreen TUI (#518).
+//! Same table as src/repl_markdown.zig codepointWidth — the REPL build can't
+//! import the tui module, so the table lives twice; change both together.
+
+const std = @import("std");
+
+/// Display columns for one codepoint: 0 for combining / zero-width marks,
+/// 2 for East-Asian wide + emoji, 1 otherwise.
+pub fn codepointWidth(cp: u21) usize {
+ if (cp < 0x300) return 1; // ASCII + Latin-1 (control bytes stay 1)
+ if ((cp >= 0x300 and cp <= 0x36F) or // combining diacritical marks
+ (cp >= 0x200B and cp <= 0x200F) or // ZWSP..RLM
+ (cp >= 0xFE00 and cp <= 0xFE0F) or // variation selectors
+ cp == 0xFEFF) return 0; // BOM / ZWNBSP
+ if ((cp >= 0x1100 and cp <= 0x115F) or // Hangul Jamo
+ (cp >= 0x2E80 and cp <= 0x303E) or // CJK radicals .. symbols
+ (cp >= 0x3041 and cp <= 0x33FF) or // kana .. CJK compat
+ (cp >= 0x3400 and cp <= 0x4DBF) or // CJK ext A
+ (cp >= 0x4E00 and cp <= 0x9FFF) or // CJK unified
+ (cp >= 0xA000 and cp <= 0xA4CF) or // Yi
+ (cp >= 0xAC00 and cp <= 0xD7A3) or // Hangul syllables
+ (cp >= 0xF900 and cp <= 0xFAFF) or // CJK compat ideographs
+ (cp >= 0xFE30 and cp <= 0xFE4F) or // CJK compat forms
+ (cp >= 0xFF00 and cp <= 0xFF60) or // fullwidth forms
+ (cp >= 0xFFE0 and cp <= 0xFFE6) or // fullwidth signs
+ (cp >= 0x1F000 and cp <= 0x1F02F) or // mahjong tiles
+ (cp >= 0x1F0A0 and cp <= 0x1F0FF) or // playing cards
+ (cp >= 0x1F100 and cp <= 0x1F1FF) or // enclosed alphanumeric / regional
+ (cp >= 0x1F300 and cp <= 0x1FAFF) or // emoji & pictographs
+ (cp >= 0x20000 and cp <= 0x3FFFD)) return 2; // CJK ext B+
+ return 1;
+}
+
+pub const Glyph = struct { step: usize, cols: usize };
+
+/// One UTF-8 codepoint at s[i]: its byte length and display columns.
+/// Invalid bytes advance 1 byte / 1 column so malformed input cannot loop.
+pub fn glyph(s: []const u8, i: usize) Glyph {
+ const len = std.unicode.utf8ByteSequenceLength(s[i]) catch return .{ .step = 1, .cols = 1 };
+ const end = @min(i + len, s.len);
+ const cols = if (std.unicode.utf8Decode(s[i..end])) |cp| codepointWidth(cp) else |_| 1;
+ return .{ .step = end - i, .cols = cols };
+}
+
+test "codepointWidth: ASCII 1, CJK/emoji 2, combining 0" {
+ try std.testing.expectEqual(@as(usize, 1), codepointWidth('a'));
+ try std.testing.expectEqual(@as(usize, 2), codepointWidth('日'));
+ try std.testing.expectEqual(@as(usize, 2), codepointWidth(0x1F409)); // 🐉
+ try std.testing.expectEqual(@as(usize, 0), codepointWidth(0x0301)); // combining acute
+}
diff --git a/src/repl_compact.zig b/src/repl_compact.zig
new file mode 100644
index 00000000..8432a3f5
--- /dev/null
+++ b/src/repl_compact.zig
@@ -0,0 +1,117 @@
+//! TUI /compact glue — run Agent.compact() on a throwaway quiet agent built
+//! from the same history the next turn would send, then hand back the
+//! rewritten turns. Split from repl_glue.zig for the 600-line cap.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
+const approvals_mod = @import("approvals.zig");
+const Approvals = approvals_mod.Approvals;
+const messages_mod = @import("messages.zig");
+const textMessage = messages_mod.textMessage;
+const prompts = @import("prompts.zig");
+const repl = @import("repl.zig");
+const repl_glue = @import("repl_glue.zig");
+const ReplCtx = repl_glue.ReplCtx;
+
+pub const CompactOut = struct {
+ note: []const u8 = "",
+ turns: []repl.Turn = &.{},
+};
+
+pub fn replCompactCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Turn, out: *CompactOut) bool {
+ const c: *ReplCtx = @ptrCast(@alignCast(ctx_ptr orelse {
+ out.note = gpa.dupe(u8, "compaction needs a live session") catch "";
+ return false;
+ }));
+ if (history.len == 0) {
+ out.note = gpa.dupe(u8, "nothing to compact") catch "";
+ return false;
+ }
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var discard_buf: [256]u8 = undefined;
+ var discarding: Io.Writer.Discarding = .init(&discard_buf);
+ var approvals: Approvals = .{ .yolo = true };
+ var agent: Agent = .{
+ .gpa = gpa,
+ .arena = arena,
+ .io = c.io,
+ .client = c.client,
+ .provider = c.provider,
+ .messages = std.json.Array.init(arena),
+ .sub = false,
+ .label = "repl",
+ .out = &discarding.writer,
+ .in = null,
+ .stream_quiet = true,
+ .registry = c.registry,
+ .tracer = c.tracer,
+ .run_budget = c.run_budget,
+ .approvals = &approvals,
+ .tools_anthropic = c.tools_anthropic,
+ .tools_openai = c.tools_openai,
+ .tools_responses = c.tools_responses,
+ .fallback_allow = c.fallback_allow,
+ .fallback_active = c.fallback_active,
+ .fallback_blocked = c.fallback_blocked,
+ };
+ prompts.setSystemPrompts(&agent, c.sys_normal, arena) catch {
+ out.note = gpa.dupe(u8, "compaction failed: could not build prompts") catch "";
+ return false;
+ };
+ defer agent.tools_used.deinit(gpa);
+ for (history) |t| {
+ const role = switch (t.role) {
+ .user => "user",
+ .assistant => "assistant",
+ };
+ agent.messages.append(textMessage(arena, role, t.text) catch {
+ out.note = gpa.dupe(u8, "compaction failed: out of memory") catch "";
+ return false;
+ }) catch {
+ out.note = gpa.dupe(u8, "compaction failed: out of memory") catch "";
+ return false;
+ };
+ }
+ const n = agent.compact() catch |err| {
+ out.note = (switch (err) {
+ error.EmptySummary => gpa.dupe(u8, "compaction failed: empty summary, history unchanged"),
+ error.IncompleteSummary => gpa.dupe(u8, "compaction failed: incomplete summary, history unchanged"),
+ error.ApiError => gpa.dupe(u8, "compaction failed: provider error, history unchanged"),
+ else => gpa.dupe(u8, "compaction failed, history unchanged"),
+ }) catch "";
+ return false;
+ };
+ if (n == 0) {
+ out.note = gpa.dupe(u8, "nothing to compact") catch "";
+ return false;
+ }
+ var turns = std.array_list.Managed(repl.Turn).init(gpa);
+ errdefer {
+ for (turns.items) |t| gpa.free(t.text);
+ turns.deinit();
+ }
+ for (agent.messages.items) |m| {
+ if (m != .object) continue;
+ const role_v = m.object.get("role") orelse continue;
+ if (role_v != .string) continue;
+ const role: repl.Turn.Role = if (std.mem.eql(u8, role_v.string, "user"))
+ .user
+ else if (std.mem.eql(u8, role_v.string, "assistant"))
+ .assistant
+ else
+ continue;
+ const c_v = m.object.get("content") orelse continue;
+ if (c_v != .string) continue;
+ const text = gpa.dupe(u8, c_v.string) catch continue;
+ turns.append(.{ .role = role, .text = text }) catch gpa.free(text);
+ }
+ out.turns = turns.toOwnedSlice() catch &.{};
+ out.note = std.fmt.allocPrint(gpa, "history compacted to a {d}-char summary", .{n}) catch "";
+ return true;
+}
diff --git a/src/tui_launch.zig b/src/tui_launch.zig
index d141ef4f..4c7e5ed3 100644
--- a/src/tui_launch.zig
+++ b/src/tui_launch.zig
@@ -108,6 +108,7 @@ pub fn run(
.bash_fn = bashCb,
.files_fn = filesCb,
.copy_fn = copyCb,
+ .compact_fn = compactCb,
});
}
@@ -171,6 +172,42 @@ fn modelCb(ctx: ?*anyopaque, gpa: Allocator, name: []const u8) ?[]const u8 {
return nm;
}
+fn compactCb(ctx: ?*anyopaque, gpa: Allocator, history: []const tui.Turn, out: *tui.CompactOut) bool {
+ var turns = std.array_list.Managed(repl.Turn).init(gpa);
+ defer {
+ for (turns.items) |t| gpa.free(t.text);
+ turns.deinit();
+ }
+ for (history) |t| {
+ const text = gpa.dupe(u8, t.text) catch continue;
+ turns.append(.{ .role = switch (t.role) {
+ .user => .user,
+ .assistant => .assistant,
+ }, .text = text }) catch gpa.free(text);
+ }
+ var raw: @import("repl_compact.zig").CompactOut = .{};
+ const ok = @import("repl_compact.zig").replCompactCb(ctx, gpa, turns.items, &raw);
+ out.note = raw.note;
+ if (raw.turns.len == 0) {
+ out.turns = &.{};
+ return ok;
+ }
+ const converted = gpa.alloc(tui.Turn, raw.turns.len) catch {
+ for (raw.turns) |t| gpa.free(t.text);
+ gpa.free(raw.turns);
+ return ok;
+ };
+ for (raw.turns, 0..) |t, i| {
+ converted[i] = .{ .role = switch (t.role) {
+ .user => .user,
+ .assistant => .assistant,
+ }, .text = t.text };
+ }
+ gpa.free(raw.turns);
+ out.turns = converted;
+ return ok;
+}
+
fn cancelCb(ctx: ?*anyopaque) void {
repl_glue.replCancelCb(ctx);
}