Skip to content

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

Python

fix(merge): line-cap splits + restore xAI WS eligibility (#502)

Rach Pradhancd4879337e25
diff --git a/TUI/key.zig b/TUI/key.zig
index 7d9464b4..a0ee5461 100644
--- a/TUI/key.zig
+++ b/TUI/key.zig
@@ -4,7 +4,7 @@ const std = @import("std");
/// Super/alt currently held, from kitty modifier-key events (Ghostty Cmd+Delete
/// often arrives as a bare DEL after Super-down).
-var held: u32 = 0;
+pub var held: u32 = 0;
pub const Key = union(enum) {
char: u8,
@@ -430,242 +430,3 @@ fn leadingInt(s: []const u8) u32 {
}
return n;
}
-
-test "next: letters, enter, ctrl-c, arrows, kitty ctrl-p" {
- var i: usize = 0;
- try std.testing.expectEqual(Key{ .char = 'a' }, next("a", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.enter, next("\r", &i).?);
- i = 0;
- try std.testing.expectEqual(Key{ .ctrl = 'c' }, next("\x03", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.up, next("\x1b[A", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.shift_tab, next("\x1b[Z", &i).?);
- i = 0;
- try std.testing.expectEqual(Key{ .ctrl = 'p' }, next("\x1b[112;5u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key{ .char = '/' }, next("/", &i).?);
- i = 0;
- const click = next("\x1b[<0;12;8M", &i).?;
- try std.testing.expect(click == .mouse);
- try std.testing.expectEqual(@as(u8, 0), click.mouse.btn);
- try std.testing.expectEqual(@as(u16, 12), click.mouse.x);
- try std.testing.expectEqual(@as(u16, 8), click.mouse.y);
- try std.testing.expect(click.mouse.down);
- i = 0;
- try std.testing.expectEqual(Key.paste_start, next("\x1b[200~", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.paste_end, next("\x1b[201~", &i).?);
- i = 0;
- try std.testing.expect(next("\x1b[20", &i) == null);
- try std.testing.expectEqual(@as(usize, 0), i);
- i = 0;
- try std.testing.expectEqual(Key{ .char = 0xc3 }, next("\xc3\xa9", &i).?);
- try std.testing.expectEqual(Key{ .char = 0xa9 }, next("\xc3\xa9", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.delete_to_start, next("\x1b[127;9u", &i).?);
- held = 0;
- i = 0;
- try std.testing.expectEqual(Key.delete_word, next("\x1b\x7f", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.prev_turn, next("\x1b[1;2D", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.next_turn, next("\x1b[1;2C", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.word_left, next("\x1b[1;3D", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.home, next("\x1b[1;9D", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.shift_enter, next("\x1b[13;2u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.shift_enter, next("\x1b\r", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.delete_to_start, next("\x1b[27;9;127~", &i).?);
- i = 0;
- held = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[57444;1:1u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.delete_to_start, next("\x7f", &i).?);
- held = 0;
-}
-
-test "lone trailing ESC stays pending, not an instant Escape" {
- var i: usize = 0;
- try std.testing.expect(next("\x1b", &i) == null);
- try std.testing.expectEqual(@as(usize, 0), i);
-}
-
-test "ESC ESC delivers an Escape and leaves the second pending" {
- var i: usize = 0;
- try std.testing.expectEqual(Key.escape, next("\x1b\x1b", &i).?);
- try std.testing.expectEqual(@as(usize, 1), i);
- try std.testing.expect(next("\x1b\x1b", &i) == null);
- try std.testing.expectEqual(@as(usize, 1), i);
-}
-
-test "kitty release events never fire keys" {
- var i: usize = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[1;1:3A", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[3;1:3~", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[5;1:3~", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[97;1:3u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.up, next("\x1b[1;1:2A", &i).?); // repeat acts
-}
-
-test "right-side modifiers follow the real kitty table, never Escape" {
- held = 0;
- var i: usize = 0;
- // Right-Shift (57447) and Right-Ctrl (57448) must not latch held bits.
- try std.testing.expectEqual(Key.ignore, next("\x1b[57447;1:1u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[57448;1:1u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);
- // Right-Alt (57449) latches alt; its release clears it.
- i = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:1u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.delete_word, next("\x7f", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:3u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);
- held = 0;
-}
-
-test "unknown keys and replies are inert, never Escape" {
- var i: usize = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[57376u", &i).?); // F13
- i = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[17~", &i).?); // F6
- i = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[2~", &i).?); // Insert
- i = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b[?1;2c", &i).?); // DA reply
-}
-
-test "kitty functional arrows and keypad map; a stale super latch resyncs" {
- held = 8; // pretend we missed the Super release
- var i: usize = 0;
- try std.testing.expectEqual(Key.up, next("\x1b[57352u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key{ .char = 'a' }, next("\x1b[97;1u", &i).?);
- try std.testing.expectEqual(@as(u32, 0), held);
- i = 0;
- try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.enter, next("\x1b[57414u", &i).?); // KP_ENTER
- held = 0;
-}
-
-test "SS3 application keys and unbound alt-chords" {
- var i: usize = 0;
- try std.testing.expectEqual(Key.up, next("\x1bOA", &i).?);
- i = 0;
- try std.testing.expectEqual(Key.f1, next("\x1bOP", &i).?);
- i = 0;
- // Split SS3 stays pending.
- try std.testing.expect(next("\x1bO", &i) == null);
- try std.testing.expectEqual(@as(usize, 0), i);
- i = 0;
- // Unbound Alt+p swallows both bytes — no phantom Escape, no stray 'p'.
- try std.testing.expectEqual(Key.ignore, next("\x1bp", &i).?);
- try std.testing.expectEqual(@as(usize, 2), i);
- try std.testing.expect(next("\x1bp", &i) == null);
-}
-
-test "X10 mouse fallback consumes its payload instead of typing it" {
- var i: usize = 0;
- const ev = next("\x1b[M\x20\x2c\x28", &i).?;
- try std.testing.expect(ev == .mouse);
- try std.testing.expectEqual(@as(u8, 0), ev.mouse.btn);
- try std.testing.expectEqual(@as(u16, 12), ev.mouse.x);
- try std.testing.expectEqual(@as(u16, 8), ev.mouse.y);
- try std.testing.expect(ev.mouse.down);
- try std.testing.expectEqual(@as(usize, 6), i);
- i = 0;
- // Split short — wait for the rest.
- try std.testing.expect(next("\x1b[M\x20", &i) == null);
- try std.testing.expectEqual(@as(usize, 0), i);
-}
-
-test "non-ASCII CSI-u codepoints type text instead of Escape" {
- var i: usize = 0;
- try std.testing.expectEqual(Key{ .codepoint = 0xe9 }, next("\x1b[233;1u", &i).?);
- held = 0;
-}
-
-test "OSC and APC replies on stdin are consumed, never typed" {
- var i: usize = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b]11;rgb:14/14/14\x07", &i).?);
- try std.testing.expectEqual(@as(usize, 18), i);
- i = 0;
- try std.testing.expectEqual(Key.ignore, next("\x1b_Gi=1;OK\x1b\\", &i).?);
- try std.testing.expectEqual(@as(usize, 11), i);
- i = 0;
- // Unterminated reply stays pending until the rest arrives.
- try std.testing.expect(next("\x1b]11;rgb:14", &i) == null);
- try std.testing.expectEqual(@as(usize, 0), i);
-}
-
-test "orphan SGR mouse is never inserted as letters" {
- var i: usize = 0;
- const k = next("39;33;23M", &i).?;
- try std.testing.expect(k == .mouse);
- try std.testing.expectEqual(@as(u8, 39), k.mouse.btn);
- try std.testing.expectEqual(@as(u16, 33), k.mouse.x);
- try std.testing.expectEqual(@as(usize, 9), i);
- i = 0;
- const k2 = next("<64;4;8Mhi", &i).?;
- try std.testing.expect(k2 == .mouse);
- try std.testing.expectEqual(@as(u8, 64), k2.mouse.btn);
- try std.testing.expectEqual(Key{ .char = 'h' }, next("<64;4;8Mhi", &i).?);
-}
-
-test "SGR mouse flood does not leak digits" {
- const seq = "\x1b[<39;33;23M\x1b[<39;26;20M\x1b[<39;25;19M";
- var i: usize = 0;
- var n: usize = 0;
- while (next(seq, &i)) |k| {
- try std.testing.expect(k == .mouse);
- n += 1;
- }
- try std.testing.expectEqual(@as(usize, 3), n);
- try std.testing.expectEqual(seq.len, i);
-}
-
-test "orphan kitty CSI-u is ignore, never letters or Escape" {
- var i: usize = 0;
- const seq = "3u7444;9u7441;10u";
- var n: usize = 0;
- while (next(seq, &i)) |k| {
- try std.testing.expect(k == .ignore);
- n += 1;
- }
- try std.testing.expectEqual(@as(usize, 3), n);
- try std.testing.expectEqual(seq.len, i);
- i = 0;
- try std.testing.expectEqual(Key{ .char = 'h' }, next("hi", &i).?);
-}
-
-test "Shift+9 is open-paren, Shift+0 is close-paren" {
- var i: usize = 0;
- try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57;2u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key{ .char = ')' }, next("\x1b[48;2u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57:40;2u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57;2;40u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key{ .char = '!' }, next("\x1b[49;2u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key{ .char = 'A' }, next("\x1b[97;2u", &i).?);
- i = 0;
- try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[27;2;57~", &i).?);
-}
diff --git a/TUI/key_tests.zig b/TUI/key_tests.zig
new file mode 100644
index 00000000..b4878ca7
--- /dev/null
+++ b/TUI/key_tests.zig
@@ -0,0 +1,245 @@
+//! key.zig's test battery, parked here under the 600-line ceiling.
+
+const std = @import("std");
+const key = @import("key.zig");
+const Key = key.Key;
+const next = key.next;
+
+test "next: letters, enter, ctrl-c, arrows, kitty ctrl-p" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key{ .char = 'a' }, next("a", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.enter, next("\r", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key{ .ctrl = 'c' }, next("\x03", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.up, next("\x1b[A", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.shift_tab, next("\x1b[Z", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key{ .ctrl = 'p' }, next("\x1b[112;5u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key{ .char = '/' }, next("/", &i).?);
+ i = 0;
+ const click = next("\x1b[<0;12;8M", &i).?;
+ try std.testing.expect(click == .mouse);
+ try std.testing.expectEqual(@as(u8, 0), click.mouse.btn);
+ try std.testing.expectEqual(@as(u16, 12), click.mouse.x);
+ try std.testing.expectEqual(@as(u16, 8), click.mouse.y);
+ try std.testing.expect(click.mouse.down);
+ i = 0;
+ try std.testing.expectEqual(Key.paste_start, next("\x1b[200~", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.paste_end, next("\x1b[201~", &i).?);
+ i = 0;
+ try std.testing.expect(next("\x1b[20", &i) == null);
+ try std.testing.expectEqual(@as(usize, 0), i);
+ i = 0;
+ try std.testing.expectEqual(Key{ .char = 0xc3 }, next("\xc3\xa9", &i).?);
+ try std.testing.expectEqual(Key{ .char = 0xa9 }, next("\xc3\xa9", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.delete_to_start, next("\x1b[127;9u", &i).?);
+ key.held = 0;
+ i = 0;
+ try std.testing.expectEqual(Key.delete_word, next("\x1b\x7f", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.prev_turn, next("\x1b[1;2D", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.next_turn, next("\x1b[1;2C", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.word_left, next("\x1b[1;3D", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.home, next("\x1b[1;9D", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.shift_enter, next("\x1b[13;2u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.shift_enter, next("\x1b\r", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.delete_to_start, next("\x1b[27;9;127~", &i).?);
+ i = 0;
+ key.held = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[57444;1:1u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.delete_to_start, next("\x7f", &i).?);
+ key.held = 0;
+}
+
+test "lone trailing ESC stays pending, not an instant Escape" {
+ var i: usize = 0;
+ try std.testing.expect(next("\x1b", &i) == null);
+ try std.testing.expectEqual(@as(usize, 0), i);
+}
+
+test "ESC ESC delivers an Escape and leaves the second pending" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.escape, next("\x1b\x1b", &i).?);
+ try std.testing.expectEqual(@as(usize, 1), i);
+ try std.testing.expect(next("\x1b\x1b", &i) == null);
+ try std.testing.expectEqual(@as(usize, 1), i);
+}
+
+test "kitty release events never fire keys" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[1;1:3A", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[3;1:3~", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[5;1:3~", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[97;1:3u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.up, next("\x1b[1;1:2A", &i).?); // repeat acts
+}
+
+test "right-side modifiers follow the real kitty table, never Escape" {
+ key.held = 0;
+ var i: usize = 0;
+ // Right-Shift (57447) and Right-Ctrl (57448) must not latch key.held bits.
+ try std.testing.expectEqual(Key.ignore, next("\x1b[57447;1:1u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[57448;1:1u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);
+ // Right-Alt (57449) latches alt; its release clears it.
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:1u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.delete_word, next("\x7f", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:3u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);
+ key.held = 0;
+}
+
+test "unknown keys and replies are inert, never Escape" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[57376u", &i).?); // F13
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[17~", &i).?); // F6
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[2~", &i).?); // Insert
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b[?1;2c", &i).?); // DA reply
+}
+
+test "kitty functional arrows and keypad map; a stale super latch resyncs" {
+ key.held = 8; // pretend we missed the Super release
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.up, next("\x1b[57352u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key{ .char = 'a' }, next("\x1b[97;1u", &i).?);
+ try std.testing.expectEqual(@as(u32, 0), key.held);
+ i = 0;
+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.enter, next("\x1b[57414u", &i).?); // KP_ENTER
+ key.held = 0;
+}
+
+test "SS3 application keys and unbound alt-chords" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.up, next("\x1bOA", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key.f1, next("\x1bOP", &i).?);
+ i = 0;
+ // Split SS3 stays pending.
+ try std.testing.expect(next("\x1bO", &i) == null);
+ try std.testing.expectEqual(@as(usize, 0), i);
+ i = 0;
+ // Unbound Alt+p swallows both bytes — no phantom Escape, no stray 'p'.
+ try std.testing.expectEqual(Key.ignore, next("\x1bp", &i).?);
+ try std.testing.expectEqual(@as(usize, 2), i);
+ try std.testing.expect(next("\x1bp", &i) == null);
+}
+
+test "X10 mouse fallback consumes its payload instead of typing it" {
+ var i: usize = 0;
+ const ev = next("\x1b[M\x20\x2c\x28", &i).?;
+ try std.testing.expect(ev == .mouse);
+ try std.testing.expectEqual(@as(u8, 0), ev.mouse.btn);
+ try std.testing.expectEqual(@as(u16, 12), ev.mouse.x);
+ try std.testing.expectEqual(@as(u16, 8), ev.mouse.y);
+ try std.testing.expect(ev.mouse.down);
+ try std.testing.expectEqual(@as(usize, 6), i);
+ i = 0;
+ // Split short — wait for the rest.
+ try std.testing.expect(next("\x1b[M\x20", &i) == null);
+ try std.testing.expectEqual(@as(usize, 0), i);
+}
+
+test "non-ASCII CSI-u codepoints type text instead of Escape" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key{ .codepoint = 0xe9 }, next("\x1b[233;1u", &i).?);
+ key.held = 0;
+}
+
+test "OSC and APC replies on stdin are consumed, never typed" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b]11;rgb:14/14/14\x07", &i).?);
+ try std.testing.expectEqual(@as(usize, 18), i);
+ i = 0;
+ try std.testing.expectEqual(Key.ignore, next("\x1b_Gi=1;OK\x1b\\", &i).?);
+ try std.testing.expectEqual(@as(usize, 11), i);
+ i = 0;
+ // Unterminated reply stays pending until the rest arrives.
+ try std.testing.expect(next("\x1b]11;rgb:14", &i) == null);
+ try std.testing.expectEqual(@as(usize, 0), i);
+}
+
+test "orphan SGR mouse is never inserted as letters" {
+ var i: usize = 0;
+ const k = next("39;33;23M", &i).?;
+ try std.testing.expect(k == .mouse);
+ try std.testing.expectEqual(@as(u8, 39), k.mouse.btn);
+ try std.testing.expectEqual(@as(u16, 33), k.mouse.x);
+ try std.testing.expectEqual(@as(usize, 9), i);
+ i = 0;
+ const k2 = next("<64;4;8Mhi", &i).?;
+ try std.testing.expect(k2 == .mouse);
+ try std.testing.expectEqual(@as(u8, 64), k2.mouse.btn);
+ try std.testing.expectEqual(Key{ .char = 'h' }, next("<64;4;8Mhi", &i).?);
+}
+
+test "SGR mouse flood does not leak digits" {
+ const seq = "\x1b[<39;33;23M\x1b[<39;26;20M\x1b[<39;25;19M";
+ var i: usize = 0;
+ var n: usize = 0;
+ while (next(seq, &i)) |k| {
+ try std.testing.expect(k == .mouse);
+ n += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 3), n);
+ try std.testing.expectEqual(seq.len, i);
+}
+
+test "orphan kitty CSI-u is ignore, never letters or Escape" {
+ var i: usize = 0;
+ const seq = "3u7444;9u7441;10u";
+ var n: usize = 0;
+ while (next(seq, &i)) |k| {
+ try std.testing.expect(k == .ignore);
+ n += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 3), n);
+ try std.testing.expectEqual(seq.len, i);
+ i = 0;
+ try std.testing.expectEqual(Key{ .char = 'h' }, next("hi", &i).?);
+}
+
+test "Shift+9 is open-paren, Shift+0 is close-paren" {
+ var i: usize = 0;
+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57;2u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key{ .char = ')' }, next("\x1b[48;2u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57:40;2u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57;2;40u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key{ .char = '!' }, next("\x1b[49;2u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key{ .char = 'A' }, next("\x1b[97;2u", &i).?);
+ i = 0;
+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[27;2;57~", &i).?);
+}
diff --git a/TUI/keys.zig b/TUI/keys.zig
index 2ddc967b..b558c052 100644
--- a/TUI/keys.zig
+++ b/TUI/keys.zig
@@ -231,8 +231,6 @@ fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {
return .stay;
}
-
-
fn slashOpen(self: *const Model) bool {
const v = self.input.getValue();
return self.focus == .prompt and v.len > 0 and v[0] == '/';
diff --git a/TUI/root.zig b/TUI/root.zig
index e33fdf2c..76f3e706 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -34,6 +34,7 @@ test {
_ = app;
_ = @import("dispatch.zig");
_ = @import("key.zig");
+ _ = @import("key_tests.zig");
_ = @import("input.zig");
_ = @import("keys.zig");
_ = @import("nav.zig");
diff --git a/src/additional_tests.zig b/src/additional_tests.zig
index 55e30732..f92f92e2 100644
--- a/src/additional_tests.zig
+++ b/src/additional_tests.zig
@@ -2,4 +2,5 @@ test {
_ = @import("readline_history.zig");
_ = @import("codedbpro_paths.zig");
_ = @import("agent_request_body_responses.zig");
+ _ = @import("agent_server_compact_tests.zig");
}
diff --git a/src/agent_server_compact.zig b/src/agent_server_compact.zig
index 86656e66..f83c425a 100644
--- a/src/agent_server_compact.zig
+++ b/src/agent_server_compact.zig
@@ -124,7 +124,7 @@ pub fn writeContextManagement(self: *const Agent, s: anytype) !void {
try writeContextManagementBody(s, threshold);
}
-fn writeContextManagementBody(s: anytype, threshold: u64) !void {
+pub fn writeContextManagementBody(s: anytype, threshold: u64) !void {
try s.objectField("context_management");
try s.beginArray();
try s.beginObject();
@@ -136,12 +136,12 @@ fn writeContextManagementBody(s: anytype, threshold: u64) !void {
try s.endArray();
}
-const ManualRoute = enum { local, standalone, in_stream };
+pub const ManualRoute = enum { local, standalone, in_stream };
/// Only first-party OpenAI Responses providers get server-side manual compact:
/// direct API traffic uses `/responses/compact`; ChatGPT/Codex forces the
/// supported in-stream directive. Every other provider stays on local summary.
-fn manualRoute(p: Provider) ManualRoute {
+pub fn manualRoute(p: Provider) ManualRoute {
if (p.kind != .responses) return .local;
if (std.mem.eql(u8, p.id, "openai")) return .standalone;
if (std.mem.eql(u8, p.id, "codex")) return .in_stream;
@@ -152,12 +152,12 @@ pub fn manualServerEligible(p: Provider) bool {
return manualRoute(p) != .local;
}
-fn compactEndpoint(arena: std.mem.Allocator, responses_url: []const u8) ![]const u8 {
+pub fn compactEndpoint(arena: std.mem.Allocator, responses_url: []const u8) ![]const u8 {
if (!std.mem.endsWith(u8, responses_url, "/responses")) return error.UnsupportedServerCompaction;
return std.fmt.allocPrint(arena, "{s}/compact", .{responses_url});
}
-fn compactBody(self: *const Agent) ![]u8 {
+pub fn compactBody(self: *const Agent) ![]u8 {
var aw: Io.Writer.Allocating = .init(self.gpa);
errdefer aw.deinit();
var s: std.json.Stringify = .{ .writer = &aw.writer };
@@ -184,7 +184,7 @@ fn installItems(self: *Agent, items: []const std.json.Value) !void {
session_prunes +|= 1; // manual compaction is not an A/B treatment exposure
}
-fn installCompactedOutput(self: *Agent, response: std.json.Value) !usize {
+pub fn installCompactedOutput(self: *Agent, response: std.json.Value) !usize {
if (response != .object) return error.InvalidCompactionResponse;
const output = response.object.get("output") orelse return error.InvalidCompactionResponse;
if (output != .array or output.array.items.len == 0) return error.InvalidCompactionResponse;
@@ -192,7 +192,7 @@ fn installCompactedOutput(self: *Agent, response: std.json.Value) !usize {
return output.array.items.len;
}
-fn installInStreamCompaction(self: *Agent, response: std.json.ObjectMap) !usize {
+pub fn installInStreamCompaction(self: *Agent, response: std.json.ObjectMap) !usize {
if (response.get("incomplete")) |v| {
if (v == .bool and v.bool) return error.IncompleteCompactionResponse;
}
@@ -311,7 +311,7 @@ pub fn pruneToLatestBlob(self: *Agent) bool {
return pruneIf(self, enabled(self.provider));
}
-fn pruneIf(self: *Agent, server_arm: bool) bool {
+pub fn pruneIf(self: *Agent, server_arm: bool) bool {
if (!server_arm or self.provider.kind != .responses) return false;
const items = self.messages.items;
var blob_idx: ?usize = null;
@@ -370,7 +370,7 @@ pub fn autocompactResumed(self: *Agent) void {
autocompactIf(self, 0, enabled(self.provider));
}
-fn autocompactIf(self: *Agent, recovery_meter: u64, server_arm: bool) void {
+pub fn autocompactIf(self: *Agent, recovery_meter: u64, server_arm: bool) void {
// #502: an explicit-compact provider (xAI) gets first-party compaction —
// one POST folds the whole history into an opaque blob, no summary model
// call. Any failure falls through to the client policy so a broken
@@ -468,276 +468,3 @@ pub fn installCompactionItem(self: *Agent, resp: []const u8) bool {
}
const test_support = @import("agent_compact_test_support.zig");
-
-fn testAgent(a: std.mem.Allocator, kind: Provider.Kind) Agent {
- var agent = test_support.subAgent(a, false);
- agent.provider.kind = kind;
- agent.gpa = a;
- agent.out = null;
- agent.label = "t";
- agent.goal_note_fp = 0;
- agent.history_rewrites = 0;
- agent.messages = std.json.Array.init(a);
- return agent;
-}
-
-fn item(a: std.mem.Allocator, typ: []const u8, call_id: ?[]const u8) !std.json.Value {
- var obj: std.json.ObjectMap = .empty;
- try obj.put(a, "type", .{ .string = typ });
- if (call_id) |c| try obj.put(a, "call_id", .{ .string = c });
- return .{ .object = obj };
-}
-
-test "manual server compaction routes direct OpenAI and Codex only" {
- var p: Provider = .{ .id = "openai", .kind = .responses, .auth = .bearer, .url = "https://api.openai.com/v1/responses", .api_key = "k", .model = "m", .context = 272_000 };
- try std.testing.expectEqual(ManualRoute.standalone, manualRoute(p));
- p.id = "codex";
- try std.testing.expectEqual(ManualRoute.in_stream, manualRoute(p));
- try std.testing.expect(manualServerEligible(p));
- p.id = "openai-compatible-router";
- try std.testing.expectEqual(ManualRoute.local, manualRoute(p));
- p.id = "openai";
- p.kind = .openai;
- try std.testing.expect(!manualServerEligible(p));
- p.kind = .anthropic;
- try std.testing.expect(!manualServerEligible(p));
-}
-
-test "manual compact endpoint appends compact and rejects non-Responses URLs" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- try std.testing.expectEqualStrings("http://127.0.0.1:8765/responses/compact", try compactEndpoint(a, "http://127.0.0.1:8765/responses"));
- try std.testing.expectError(error.UnsupportedServerCompaction, compactEndpoint(a, "http://127.0.0.1:8765/chat/completions"));
-}
-
-test "manual compact body sends model, canonical Responses input, and instructions" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var agent = testAgent(a, .responses);
- agent.provider.model = "gpt-test";
- agent.sys_normal = "system-test";
- try agent.messages.append(try item(a, "message", null));
- const body = try compactBody(&agent);
- defer a.free(body);
- const parsed = try std.json.parseFromSliceLeaky(std.json.Value, a, body, .{});
- try std.testing.expectEqualStrings("gpt-test", parsed.object.get("model").?.string);
- try std.testing.expectEqualStrings("system-test", parsed.object.get("instructions").?.string);
- try std.testing.expectEqual(@as(usize, 1), parsed.object.get("input").?.array.items.len);
-}
-
-test "installCompactedOutput transactionally replaces history and resets meters" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var agent = testAgent(a, .responses);
- try agent.messages.append(try item(a, "message", null));
- agent.last_context_tokens = 99;
- agent.context_local_tokens = 88;
- agent.goal_note_fp = 77;
- const invalid = std.json.Value{ .object = .empty };
- try std.testing.expectError(error.InvalidCompactionResponse, installCompactedOutput(&agent, invalid));
- try std.testing.expectError(error.InvalidCompactionResponse, installInStreamCompaction(&agent, .empty));
- try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
-
- var output = std.json.Array.init(a);
- try output.append(try item(a, "message", null));
- var obj: std.json.ObjectMap = .empty;
- try obj.put(a, "output", .{ .array = output });
- try std.testing.expectError(error.MissingCompactionItem, installInStreamCompaction(&agent, obj));
- try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
- try output.append(try item(a, "compaction", null));
- try output.append(try item(a, "message", null));
- try obj.put(a, "output", .{ .array = output });
- try std.testing.expectEqual(@as(usize, 3), try installCompactedOutput(&agent, .{ .object = obj }));
- try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);
- try std.testing.expectEqual(@as(usize, 1), try installInStreamCompaction(&agent, obj));
- try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
- try std.testing.expectEqualStrings("compaction", agent.messages.items[0].object.get("type").?.string);
- try std.testing.expectEqual(@as(u64, 0), agent.last_context_tokens);
- try std.testing.expectEqual(@as(u64, 0), agent.context_local_tokens);
- try std.testing.expectEqual(@as(u64, 0), agent.goal_note_fp);
- try std.testing.expectEqual(@as(u64, 2), agent.history_rewrites);
-}
-
-test "enabled: responses-only; unassigned defaults to client; override wins" {
- var p: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "m", .context = 272_000 };
- try std.testing.expect(!enabled(p)); // no assignment in tests → client arm
- p.kind = .anthropic;
- try std.testing.expect(!enabled(p));
- p.kind = .openai;
- try std.testing.expect(!enabled(p));
- p.kind = .responses;
- g_server_compact_override = true;
- try std.testing.expect(enabled(p));
- g_server_compact_override = false;
- try std.testing.expect(!enabled(p));
- g_server_compact_override = null;
-}
-
-test "armForId: deterministic bucketing of the install id" {
- const id: [32]u8 = "0123456789abcdef0123456789abcdef".*;
- try std.testing.expectEqual(armForId(&id), armForId(&id));
- const other: [32]u8 = "ffffffffffffffffffffffffffffffff".*;
- _ = armForId(&other); // both buckets are reachable outcomes; no crash, pure
-}
-
-test "writeContextManagement: automatic threshold and forced Codex pass stay OpenAI-only" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var agent = testAgent(a, .responses);
- var aw: @import("std").Io.Writer.Allocating = .init(a);
- var s: std.json.Stringify = .{ .writer = &aw.writer };
- try s.beginObject();
- try writeContextManagementBody(&s, 80_000);
- try s.endObject();
- try std.testing.expect(std.mem.indexOf(u8, aw.written(), "\"compact_threshold\":80000") != null);
- agent.provider.id = "codex";
- agent.server_compaction_request = true;
- var aw2: @import("std").Io.Writer.Allocating = .init(a);
- var s2: std.json.Stringify = .{ .writer = &aw2.writer };
- try s2.beginObject();
- try writeContextManagement(&agent, &s2);
- try s2.endObject();
- try std.testing.expect(std.mem.indexOf(u8, aw2.written(), "\"compact_threshold\":1000") != null);
- agent.provider.id = "openai-compatible-router";
- var aw3: @import("std").Io.Writer.Allocating = .init(a);
- var s3: std.json.Stringify = .{ .writer = &aw3.writer };
- try s3.beginObject();
- try writeContextManagement(&agent, &s3);
- try s3.endObject();
- try std.testing.expectEqualStrings("{}", aw3.written());
-}
-
-test "pruneToLatestBlob: no blob or blob-first leaves history untouched" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var agent = testAgent(a, .responses);
- try agent.messages.append(try item(a, "message", null));
- try std.testing.expect(!pruneIf(&agent, true));
- try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
- // blob already at the head: nothing to prune
- var agent2 = testAgent(a, .responses);
- try agent2.messages.append(try item(a, "compaction", null));
- try agent2.messages.append(try item(a, "message", null));
- try std.testing.expect(!pruneIf(&agent2, true));
- try std.testing.expectEqual(@as(usize, 2), agent2.messages.items.len);
- try std.testing.expectEqual(@as(u32, 0), agent2.history_rewrites);
-}
-
-test "pruneToLatestBlob: prunes to the newest blob and resets the meters" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var agent = testAgent(a, .responses);
- try agent.messages.append(try item(a, "message", null)); // pruned
- try agent.messages.append(try item(a, "compaction", null)); // older blob — superseded
- try agent.messages.append(try item(a, "message", null)); // pruned
- try agent.messages.append(try item(a, "compaction", null)); // newest blob
- try agent.messages.append(try item(a, "function_call", "c1")); // pair survives intact
- try agent.messages.append(try item(a, "function_call_output", "c1"));
- agent.last_context_tokens = 200_000;
- agent.context_local_tokens = 190_000;
- try std.testing.expect(pruneIf(&agent, true));
- try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);
- try std.testing.expectEqualStrings("compaction", agent.messages.items[0].object.get("type").?.string);
- try std.testing.expectEqual(@as(u32, 1), agent.history_rewrites);
- try std.testing.expectEqual(@as(u64, 0), agent.last_context_tokens);
- try std.testing.expectEqual(@as(u64, 0), agent.context_local_tokens);
-}
-
-test "pruneToLatestBlob: an orphaned tool output refuses the prune" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var agent = testAgent(a, .responses);
- try agent.messages.append(try item(a, "function_call", "c1")); // pruned by the cut
- try agent.messages.append(try item(a, "compaction", null));
- try agent.messages.append(try item(a, "function_call_output", "c1")); // orphan if pruned
- try std.testing.expect(!pruneIf(&agent, true));
- try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);
-}
-
-test "pruneIf: never fires off the server arm or off responses" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var agent = testAgent(a, .anthropic);
- try agent.messages.append(try item(a, "message", null));
- try agent.messages.append(try item(a, "compaction", null));
- try std.testing.expect(!pruneIf(&agent, true));
- try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);
-}
-
-test "autocompact: responses providers hold at the ordinary threshold without a blob" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var agent = testAgent(a, .responses); // context 100_000
- try agent.messages.append(try item(a, "message", null));
- // Over the 80% compactAt line but under the 95% wall, no blob: the server
- // owns compaction now, so history must survive untouched (legacy policy
- // would have run a summary here).
- autocompactIf(&agent, 85_000, true);
- try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
- try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);
-}
-
-test "installCompactionItem restarts history from the blob and resets the meters (#502)" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var agent = testAgent(a, .responses);
- agent.arena = a;
- try agent.messages.append(try item(a, "message", null));
- try agent.messages.append(try item(a, "function_call", "c1"));
- try agent.messages.append(try item(a, "function_call_output", "c1"));
- agent.last_context_tokens = 400_000;
- const resp =
- \\{"id":"cmp_1","object":"response.compaction","output":[{"type":"compaction","id":"cmp_1","encrypted_content":"BLOB"}],
- \\ "usage":{"input_tokens":9000,"output_tokens":400,"dropped_message_count":3}}
- ;
- try std.testing.expect(installCompactionItem(&agent, resp));
- try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
- try std.testing.expectEqualStrings("compaction", agent.messages.items[0].object.get("type").?.string);
- try std.testing.expectEqualStrings("BLOB", agent.messages.items[0].object.get("encrypted_content").?.string);
- try std.testing.expectEqual(@as(u64, 0), agent.last_context_tokens);
- try std.testing.expectEqual(@as(u32, 1), agent.history_rewrites);
-}
-
-test "installCompactionItem refuses malformed responses and leaves history intact (#502)" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var agent = testAgent(a, .responses);
- agent.arena = a;
- try agent.messages.append(try item(a, "message", null));
- for ([_][]const u8{
- "not json",
- "{\"output\":[]}",
- "{\"output\":[{\"type\":\"message\"}]}",
- "{\"output\":[{\"type\":\"compaction\"}]}", // no encrypted_content
- }) |bad| {
- try std.testing.expect(!installCompactionItem(&agent, bad));
- try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
- try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);
- }
-}
-
-test "explicitCompact anti-thrash: a fresh blob head with little growth refuses (#502)" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var agent = testAgent(a, .responses);
- agent.arena = a;
- agent.provider.id = "xai"; // serverCompactUrl fires for xai + .responses
- try agent.messages.append(try item(a, "compaction", null));
- try agent.messages.append(try item(a, "message", null));
- // Guard trips BEFORE any network I/O — false, history untouched.
- try std.testing.expect(!explicitCompact(&agent));
- try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);
- try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);
-}
diff --git a/src/agent_server_compact_tests.zig b/src/agent_server_compact_tests.zig
new file mode 100644
index 00000000..2db43e22
--- /dev/null
+++ b/src/agent_server_compact_tests.zig
@@ -0,0 +1,304 @@
+//! White-box tests for agent_server_compact.zig, parked here under the
+//! 600-line ceiling (same pattern as router_catalog_tests.zig).
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const main_mod = @import("main.zig");
+const Agent = @import("agent.zig").Agent;
+const Provider = @import("provider.zig").Provider;
+const asc = @import("agent_server_compact.zig");
+const enabled = asc.enabled;
+const noteExposure = asc.noteExposure;
+const noteClientSummary = asc.noteClientSummary;
+const writeContextManagement = asc.writeContextManagement;
+const writeContextManagementBody = asc.writeContextManagementBody;
+const manualRoute = asc.manualRoute;
+const manualServerEligible = asc.manualServerEligible;
+const compactEndpoint = asc.compactEndpoint;
+const compactBody = asc.compactBody;
+const installCompactedOutput = asc.installCompactedOutput;
+const installInStreamCompaction = asc.installInStreamCompaction;
+const manualCompact = asc.manualCompact;
+const pruneToLatestBlob = asc.pruneToLatestBlob;
+const pruneIf = asc.pruneIf;
+const autocompact = asc.autocompact;
+const autocompactIf = asc.autocompactIf;
+const explicitCompact = asc.explicitCompact;
+const installCompactionItem = asc.installCompactionItem;
+const armForId = asc.armForId;
+const ManualRoute = asc.ManualRoute;
+const test_support = @import("agent_compact_test_support.zig");
+
+fn testAgent(a: std.mem.Allocator, kind: Provider.Kind) Agent {
+ var agent = test_support.subAgent(a, false);
+ agent.provider.kind = kind;
+ agent.gpa = a;
+ agent.out = null;
+ agent.label = "t";
+ agent.goal_note_fp = 0;
+ agent.history_rewrites = 0;
+ agent.messages = std.json.Array.init(a);
+ return agent;
+}
+
+fn item(a: std.mem.Allocator, typ: []const u8, call_id: ?[]const u8) !std.json.Value {
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(a, "type", .{ .string = typ });
+ if (call_id) |c| try obj.put(a, "call_id", .{ .string = c });
+ return .{ .object = obj };
+}
+
+test "manual server compaction routes direct OpenAI and Codex only" {
+ var p: Provider = .{ .id = "openai", .kind = .responses, .auth = .bearer, .url = "https://api.openai.com/v1/responses", .api_key = "k", .model = "m", .context = 272_000 };
+ try std.testing.expectEqual(ManualRoute.standalone, manualRoute(p));
+ p.id = "codex";
+ try std.testing.expectEqual(ManualRoute.in_stream, manualRoute(p));
+ try std.testing.expect(manualServerEligible(p));
+ p.id = "openai-compatible-router";
+ try std.testing.expectEqual(ManualRoute.local, manualRoute(p));
+ p.id = "openai";
+ p.kind = .openai;
+ try std.testing.expect(!manualServerEligible(p));
+ p.kind = .anthropic;
+ try std.testing.expect(!manualServerEligible(p));
+}
+
+test "manual compact endpoint appends compact and rejects non-Responses URLs" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ try std.testing.expectEqualStrings("http://127.0.0.1:8765/responses/compact", try compactEndpoint(a, "http://127.0.0.1:8765/responses"));
+ try std.testing.expectError(error.UnsupportedServerCompaction, compactEndpoint(a, "http://127.0.0.1:8765/chat/completions"));
+}
+
+test "manual compact body sends model, canonical Responses input, and instructions" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses);
+ agent.provider.model = "gpt-test";
+ agent.sys_normal = "system-test";
+ try agent.messages.append(try item(a, "message", null));
+ const body = try compactBody(&agent);
+ defer a.free(body);
+ const parsed = try std.json.parseFromSliceLeaky(std.json.Value, a, body, .{});
+ try std.testing.expectEqualStrings("gpt-test", parsed.object.get("model").?.string);
+ try std.testing.expectEqualStrings("system-test", parsed.object.get("instructions").?.string);
+ try std.testing.expectEqual(@as(usize, 1), parsed.object.get("input").?.array.items.len);
+}
+
+test "installCompactedOutput transactionally replaces history and resets meters" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses);
+ try agent.messages.append(try item(a, "message", null));
+ agent.last_context_tokens = 99;
+ agent.context_local_tokens = 88;
+ agent.goal_note_fp = 77;
+ const invalid = std.json.Value{ .object = .empty };
+ try std.testing.expectError(error.InvalidCompactionResponse, installCompactedOutput(&agent, invalid));
+ try std.testing.expectError(error.InvalidCompactionResponse, installInStreamCompaction(&agent, .empty));
+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
+
+ var output = std.json.Array.init(a);
+ try output.append(try item(a, "message", null));
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(a, "output", .{ .array = output });
+ try std.testing.expectError(error.MissingCompactionItem, installInStreamCompaction(&agent, obj));
+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
+ try output.append(try item(a, "compaction", null));
+ try output.append(try item(a, "message", null));
+ try obj.put(a, "output", .{ .array = output });
+ try std.testing.expectEqual(@as(usize, 3), try installCompactedOutput(&agent, .{ .object = obj }));
+ try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);
+ try std.testing.expectEqual(@as(usize, 1), try installInStreamCompaction(&agent, obj));
+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
+ try std.testing.expectEqualStrings("compaction", agent.messages.items[0].object.get("type").?.string);
+ try std.testing.expectEqual(@as(u64, 0), agent.last_context_tokens);
+ try std.testing.expectEqual(@as(u64, 0), agent.context_local_tokens);
+ try std.testing.expectEqual(@as(u64, 0), agent.goal_note_fp);
+ try std.testing.expectEqual(@as(u64, 2), agent.history_rewrites);
+}
+
+test "enabled: responses-only; unassigned defaults to client; override wins" {
+ var p: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "m", .context = 272_000 };
+ try std.testing.expect(!enabled(p)); // no assignment in tests → client arm
+ p.kind = .anthropic;
+ try std.testing.expect(!enabled(p));
+ p.kind = .openai;
+ try std.testing.expect(!enabled(p));
+ p.kind = .responses;
+ asc.g_server_compact_override = true;
+ try std.testing.expect(enabled(p));
+ asc.g_server_compact_override = false;
+ try std.testing.expect(!enabled(p));
+ asc.g_server_compact_override = null;
+}
+
+test "armForId: deterministic bucketing of the install id" {
+ const id: [32]u8 = "0123456789abcdef0123456789abcdef".*;
+ try std.testing.expectEqual(armForId(&id), armForId(&id));
+ const other: [32]u8 = "ffffffffffffffffffffffffffffffff".*;
+ _ = armForId(&other); // both buckets are reachable outcomes; no crash, pure
+}
+
+test "writeContextManagement: automatic threshold and forced Codex pass stay OpenAI-only" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses);
+ var aw: @import("std").Io.Writer.Allocating = .init(a);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.beginObject();
+ try writeContextManagementBody(&s, 80_000);
+ try s.endObject();
+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "\"compact_threshold\":80000") != null);
+ agent.provider.id = "codex";
+ agent.server_compaction_request = true;
+ var aw2: @import("std").Io.Writer.Allocating = .init(a);
+ var s2: std.json.Stringify = .{ .writer = &aw2.writer };
+ try s2.beginObject();
+ try writeContextManagement(&agent, &s2);
+ try s2.endObject();
+ try std.testing.expect(std.mem.indexOf(u8, aw2.written(), "\"compact_threshold\":1000") != null);
+ agent.provider.id = "openai-compatible-router";
+ var aw3: @import("std").Io.Writer.Allocating = .init(a);
+ var s3: std.json.Stringify = .{ .writer = &aw3.writer };
+ try s3.beginObject();
+ try writeContextManagement(&agent, &s3);
+ try s3.endObject();
+ try std.testing.expectEqualStrings("{}", aw3.written());
+}
+
+test "pruneToLatestBlob: no blob or blob-first leaves history untouched" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses);
+ try agent.messages.append(try item(a, "message", null));
+ try std.testing.expect(!pruneIf(&agent, true));
+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
+ // blob already at the head: nothing to prune
+ var agent2 = testAgent(a, .responses);
+ try agent2.messages.append(try item(a, "compaction", null));
+ try agent2.messages.append(try item(a, "message", null));
+ try std.testing.expect(!pruneIf(&agent2, true));
+ try std.testing.expectEqual(@as(usize, 2), agent2.messages.items.len);
+ try std.testing.expectEqual(@as(u32, 0), agent2.history_rewrites);
+}
+
+test "pruneToLatestBlob: prunes to the newest blob and resets the meters" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses);
+ try agent.messages.append(try item(a, "message", null)); // pruned
+ try agent.messages.append(try item(a, "compaction", null)); // older blob — superseded
+ try agent.messages.append(try item(a, "message", null)); // pruned
+ try agent.messages.append(try item(a, "compaction", null)); // newest blob
+ try agent.messages.append(try item(a, "function_call", "c1")); // pair survives intact
+ try agent.messages.append(try item(a, "function_call_output", "c1"));
+ agent.last_context_tokens = 200_000;
+ agent.context_local_tokens = 190_000;
+ try std.testing.expect(pruneIf(&agent, true));
+ try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);
+ try std.testing.expectEqualStrings("compaction", agent.messages.items[0].object.get("type").?.string);
+ try std.testing.expectEqual(@as(u32, 1), agent.history_rewrites);
+ try std.testing.expectEqual(@as(u64, 0), agent.last_context_tokens);
+ try std.testing.expectEqual(@as(u64, 0), agent.context_local_tokens);
+}
+
+test "pruneToLatestBlob: an orphaned tool output refuses the prune" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses);
+ try agent.messages.append(try item(a, "function_call", "c1")); // pruned by the cut
+ try agent.messages.append(try item(a, "compaction", null));
+ try agent.messages.append(try item(a, "function_call_output", "c1")); // orphan if pruned
+ try std.testing.expect(!pruneIf(&agent, true));
+ try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);
+}
+
+test "pruneIf: never fires off the server arm or off responses" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .anthropic);
+ try agent.messages.append(try item(a, "message", null));
+ try agent.messages.append(try item(a, "compaction", null));
+ try std.testing.expect(!pruneIf(&agent, true));
+ try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);
+}
+
+test "autocompact: responses providers hold at the ordinary threshold without a blob" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses); // context 100_000
+ try agent.messages.append(try item(a, "message", null));
+ // Over the 80% compactAt line but under the 95% wall, no blob: the server
+ // owns compaction now, so history must survive untouched (legacy policy
+ // would have run a summary here).
+ autocompactIf(&agent, 85_000, true);
+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
+ try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);
+}
+
+test "installCompactionItem restarts history from the blob and resets the meters (#502)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses);
+ agent.arena = a;
+ try agent.messages.append(try item(a, "message", null));
+ try agent.messages.append(try item(a, "function_call", "c1"));
+ try agent.messages.append(try item(a, "function_call_output", "c1"));
+ agent.last_context_tokens = 400_000;
+ const resp =
+ \\{"id":"cmp_1","object":"response.compaction","output":[{"type":"compaction","id":"cmp_1","encrypted_content":"BLOB"}],
+ \\ "usage":{"input_tokens":9000,"output_tokens":400,"dropped_message_count":3}}
+ ;
+ try std.testing.expect(installCompactionItem(&agent, resp));
+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
+ try std.testing.expectEqualStrings("compaction", agent.messages.items[0].object.get("type").?.string);
+ try std.testing.expectEqualStrings("BLOB", agent.messages.items[0].object.get("encrypted_content").?.string);
+ try std.testing.expectEqual(@as(u64, 0), agent.last_context_tokens);
+ try std.testing.expectEqual(@as(u32, 1), agent.history_rewrites);
+}
+
+test "installCompactionItem refuses malformed responses and leaves history intact (#502)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses);
+ agent.arena = a;
+ try agent.messages.append(try item(a, "message", null));
+ for ([_][]const u8{
+ "not json",
+ "{\"output\":[]}",
+ "{\"output\":[{\"type\":\"message\"}]}",
+ "{\"output\":[{\"type\":\"compaction\"}]}", // no encrypted_content
+ }) |bad| {
+ try std.testing.expect(!installCompactionItem(&agent, bad));
+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
+ try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);
+ }
+}
+
+test "explicitCompact anti-thrash: a fresh blob head with little growth refuses (#502)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses);
+ agent.arena = a;
+ agent.provider.id = "xai"; // serverCompactUrl fires for xai + .responses
+ try agent.messages.append(try item(a, "compaction", null));
+ try agent.messages.append(try item(a, "message", null));
+ // Guard trips BEFORE any network I/O — false, history untouched.
+ try std.testing.expect(!explicitCompact(&agent));
+ try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);
+ try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);
+}
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
index 6cbf35a5..96b97102 100644
--- a/src/agent_ws.zig
+++ b/src/agent_ws.zig
@@ -46,19 +46,18 @@ const watchdogError = http.watchdogError;
const signal = @import("agent_ws_signal.zig");
pub const frameHasOutputText = signal.frameHasOutputText;
pub const TokenSignal = signal.TokenSignal;
-
const isStreamEnd = @import("agent_stream.zig").isStreamEnd;
-
const escPressed = Agent.escPressed;
const rawNonblockStdin = Agent.rawNonblockStdin;
const drainSteerStdin = Agent.drainSteerStdin;
-/// Codex ws applies to root Responses turns when enabled and not already fallen
-/// back this session. Subagents/quiet turns keep the non-streaming SSE path.
+/// WS applies to root Responses turns when enabled and not already fallen back
+/// this session; subagents/quiet turns keep SSE. Only providers with a real WS
+/// endpoint qualify — Platform OpenAI is Responses-kind but has no WS server.
pub fn wsEligible(self: *Agent) bool {
- return main_mod.g_codex_ws and !self.ws_off and !self.sub and
- self.provider.kind == .responses and std.mem.eql(u8, self.provider.id, "codex") and
- self.out != null and !self.stream_quiet;
+ const has_ws = std.mem.eql(u8, self.provider.id, "codex") or std.mem.eql(u8, self.provider.id, "xai");
+ return main_mod.g_codex_ws and !self.ws_off and !self.sub and has_ws and
+ self.provider.kind == .responses and self.out != null and !self.stream_quiet;
}
/// (#codex-ws) Client-side idle limit on the held codex WS, opencode's
diff --git a/src/mcp_lifecycle.zig b/src/mcp_lifecycle.zig
index 3a7e236b..d70f240a 100644
--- a/src/mcp_lifecycle.zig
+++ b/src/mcp_lifecycle.zig
@@ -209,7 +209,6 @@ fn expectDecision(body: []const u8, status: u16, want: std.meta.Tag(Decision)) !
try std.testing.expectEqual(want, std.meta.activeTag(got));
}
-
test "Auto: server/discover listing 2026-07-28 is modern_list" {
try expectDecision(
\\{"jsonrpc":"2.0","id":1,"result":{"supportedVersions":["2026-07-28","2025-11-25"]}}