Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396const std = @import("std");const testing = std.testing;
const vaxis = @import("vaxis");const vxfw = vaxis.vxfw;
const protocol = @import("protocol.zig");const editors = @import("editor.zig");const transcripts = @import("transcript.zig");const View = @import("view/root.zig").View;
pub const Event = union(enum) { key_press: vaxis.Key, mouse: vaxis.Mouse, winsize: vaxis.Winsize, paste_start, paste_end, /// A message from the core. The TUI frees it. core: protocol.core.Message, /// The timer of this widget expired. tick: vxfw.Widget,};
/// The one queue the TUI reads: input, core messages and timers all arrive here.pub const Queue = vaxis.Queue(Event, 512);
pub const Action = enum { none, submit, interrupt, clear_prompt, quit, page_up, page_down, insert_newline, toggle_expanded, toggle_thinking, cycle_level, cycle_model,
const TerminalState = struct { working: bool, has_text: bool, };
/// Get the Action for the given key, depending on the current terminal state. pub fn forKey(key: vaxis.Key, state: TerminalState) Action { if (key.matches('c', .{ .ctrl = true })) { if (state.working) { return .interrupt; }
return if (state.has_text) .clear_prompt else .quit; }
if (key.matches('o', .{ .ctrl = true })) { return .toggle_expanded; }
if (key.matches('t', .{ .ctrl = true })) { return .cycle_level; }
if (key.matches('p', .{ .ctrl = true })) { return .cycle_model; }
if (key.matches(vaxis.Key.tab, .{ .shift = true })) { return .toggle_thinking; }
if (key.matches(vaxis.Key.escape, .{})) { return if (state.working) .interrupt else .none; }
if (key.matches(vaxis.Key.enter, .{ .shift = true }) or key.matches(vaxis.Key.enter, .{ .alt = true })) { return .insert_newline; }
if (key.matches(vaxis.Key.enter, .{})) { return .submit; }
if (key.matches(vaxis.Key.page_up, .{})) { return .page_up; }
if (key.matches(vaxis.Key.page_down, .{})) { return .page_down; }
return .none; }};
/// Collects the per-character key events that vaxis delivers between paste_start/// and paste_end, so that a bracketed paste becomes one editor insert.const PasteBuffer = struct { gpa: std.mem.Allocator, text: std.ArrayList(u8) = .empty, active: bool = false,
fn init(gpa: std.mem.Allocator) PasteBuffer { return .{ .gpa = gpa }; }
fn deinit(self: *PasteBuffer) void { self.text.deinit(self.gpa); }
/// Handles paste events. Returns true when the event belongs to a paste and /// the caller must not run the key action table. fn handle(self: *PasteBuffer, event: Event, editor: *editors.Editor) !bool { switch (event) { .paste_start => { self.active = true; self.text.clearRetainingCapacity(); return true; }, .paste_end => { if (!self.active) { return false; } self.active = false; try editor.insertPaste(self.text.items); self.text.clearRetainingCapacity(); return true; }, .key_press => |key| { if (!self.active) { return false; } if (key.text) |text| { try self.text.appendSlice(self.gpa, text); } else if (key.matches(vaxis.Key.enter, .{}) or key.matches('j', .{ .ctrl = true })) { try self.text.append(self.gpa, '\n'); } else if (key.matches(vaxis.Key.tab, .{})) { try self.text.append(self.gpa, '\t'); } return true; }, else => return false, } }};
/// Owns the TUI state: the transcript, the editor, the widgets, the timers and/// the terminal. A test can use the state without `open`, and then nothing/// touches the terminal.pub const Tui = struct { io: std.Io, gpa: std.mem.Allocator, transcript: transcripts.Transcript, editor: editors.Editor, /// Prompts that wait to run, in queue order. queued: std.ArrayList([]const u8) = .empty, view: View, paste: PasteBuffer, timers: Timers, ctx: vxfw.EventContext, /// True when an event changed what the next frame shows. dirty: bool = true, /// Terminal columns, from the last resize. width: u16 = 0, session: ?protocol.core.Session = null, /// Where the TUI sends its requests. `attach` sets it. core: protocol.Sink(protocol.ui.Request) = undefined, attached: bool = false, next_id: protocol.RequestId = 0, /// Requests without a response, in the order the core answers them. pending: std.ArrayList(Pending), pending_buffer: [protocol.inbox_capacity]Pending = undefined, tty_buffer: [4096]u8 = undefined, tty: vaxis.Tty = undefined, vx: vaxis.Vaxis = undefined, /// Its queue is the one queue the TUI reads, also before `open`. loop: vaxis.Loop(Event), signal_resize: bool = false,
/// Allocates the TUI with `gpa`. `deinit` frees it. pub fn init(gpa: std.mem.Allocator, io: std.Io) !*Tui { const self = try gpa.create(Tui); self.* = .{ .io = io, .gpa = gpa, .transcript = .init(gpa), .editor = .init(gpa), .view = .init(gpa, io), .paste = .init(gpa), .timers = .init(gpa, io), .ctx = .{ .io = io, .alloc = gpa, .phase = .capturing, .cmds = .empty, .consume_event = false, .redraw = false, .quit = false, }, .loop = .init(io, undefined, undefined), .pending = .initBuffer(&self.pending_buffer), }; return self; }
const Pending = struct { id: protocol.RequestId, /// The text of a submit, kept until the core answers. prompt: ?[]const u8 = null, };
/// Frees the TUI, its state and the events nobody read. pub fn deinit(self: *Tui) void { self.timers.deinit(); while (self.loop.queue.tryPop() catch null) |event| switch (event) { .core => |unread| unread.deinit(self.gpa), else => {}, }; self.ctx.cmds.deinit(self.gpa); self.paste.deinit(); self.view.deinit(); self.editor.deinit(); for (self.queued.items) |prompt| self.gpa.free(prompt); self.queued.deinit(self.gpa); self.clearPending(); self.transcript.deinit(); if (self.session) |session| { session.deinit(self.gpa); } self.gpa.destroy(self); }
/// Takes over the terminal and starts reading input and the timers. pub fn open(self: *Tui, env_map: *std.process.Environ.Map) !void { self.tty = try vaxis.Tty.init(self.io, &self.tty_buffer); errdefer self.tty.deinit(); self.vx = try vaxis.init(self.io, self.gpa, env_map, .{}); errdefer self.vx.deinit(self.gpa, self.tty.writer());
self.loop.tty = &self.tty; self.loop.vaxis = &self.vx; try self.loop.start(); errdefer self.loop.stop();
const writer = self.tty.writer(); try self.vx.enterAltScreen(writer); try self.vx.setMouseMode(writer, true); try self.vx.setBracketedPaste(writer, true); try self.vx.queryTerminal(writer, .fromSeconds(1)); // A terminal with in-band resize reports sizes itself; others need SIGWINCH. self.signal_resize = !self.vx.state.in_band_resize; if (self.signal_resize) { try self.loop.installResizeHandler(); } errdefer if (self.signal_resize) { self.loop.uninstallResizeHandler(); };
try self.timers.start(&self.loop.queue); }
/// Stops the timers and the input and gives the terminal back. pub fn close(self: *Tui) void { self.timers.stop(); if (self.signal_resize) { self.loop.uninstallResizeHandler(); } self.loop.stop(); self.vx.deinit(self.gpa, self.tty.writer()); self.tty.deinit(); }
/// Where the core sends its messages. Blocks while the queue of unread /// events is full. Refuses messages after `run` returns. pub fn sink(self: *Tui) protocol.Sink(protocol.core.Message) { return .{ .ctx = &self.loop.queue, .sendFn = sendCoreMessage }; }
fn sendCoreMessage(ctx: *anyopaque, message: protocol.core.Message) bool { const queue: *Queue = @ptrCast(@alignCast(ctx)); queue.push(.{ .core = message }) catch |err| { // A provider task that is canceled during the push must still stop. if (err == error.Canceled) { queue.io.recancel(); } return false; }; return true; }
/// Attaches to `core`, then reads input and core messages and draws until /// the user quits, and detaches. Call it after `open`. When it returns, /// `sink` takes no more messages. pub fn run(self: *Tui, core: protocol.Sink(protocol.ui.Request)) !void { // A core that waits for room in the queue could not stop otherwise. defer self.loop.queue.close(error.Closed); try self.attach(core); defer self.detach(); while (true) { // Apply the queued events, then draw once. The limit keeps a flood of // events from delaying the frame forever. var next: ?Event = try self.loop.nextEvent(); var budget: usize = 512; while (next) |event| : (next = if (budget == 0) null else try self.loop.tryEvent()) { budget -= 1; if (!try self.handle(event)) { return; } }
// One redraw when the paste ends instead of one per pasted character. if (self.paste.active or !self.dirty) { continue; }
try self.draw(self.vx.window()); try self.vx.render(self.tty.writer()); } }
/// Applies one event. Returns false when the user quits. A resize needs /// the terminal from `open`. pub fn handle(self: *Tui, event: Event) !bool { if (event != .mouse) { self.dirty = true; } // vaxis sends a bracketed paste as paste_start, one key per character and // paste_end. Collect it so the paste is one insert and never reaches the // key action table, where an Enter inside it would submit the prompt. if (try self.paste.handle(event, &self.editor)) { return true; } switch (event) { .key_press => |key| { const action = Action.forKey(key, .{ .working = self.view.working, .has_text = !self.editor.isEmpty(), }); switch (action) { .quit => return false, .interrupt => if (!self.canRequest() or !self.request(.interrupt, null)) { try self.notify(busy); }, .clear_prompt => self.editor.clear(), .submit => try self.submit(), .insert_newline => try self.editor.newline(), .toggle_expanded => self.transcript.toggleExpanded(), .toggle_thinking => self.transcript.toggleThinking(), .cycle_level => if (!self.canRequest() or !self.request(.cycle_level, null)) { try self.notify(busy); }, .cycle_model => if (!self.canRequest() or !self.request(.cycle_model, null)) { try self.notify(busy); }, .page_up => self.view.pageUp(), .page_down => self.view.pageDown(), .none => try self.editor.handleKey(key, self.width), } }, .mouse => |mouse| switch (mouse.button) { // TODO: make scroll size/rate configurable .wheel_up, .wheel_down => |button| { if (button == .wheel_up) { self.view.scrollUp(3); } else { self.view.scrollDown(3); } self.dirty = true; }, else => try self.click(mouse), }, .winsize => |size| { try self.vx.resize(self.gpa, self.tty.writer(), size); self.width = size.cols; }, .paste_start, .paste_end => {}, .core => |update| switch (update) { .response => |response| try self.receive(response), // The core reports when it picks work up and when it runs out, so // the spinner follows the run and not the submit. .agent_start => if (self.view.setWorking(true)) |tick| { try self.timers.arm(tick); }, .agent_end => _ = self.view.setWorking(false), .prompt_start => { const prompt = self.queued.orderedRemove(0); self.transcript.items.append(self.gpa, .{ .user = prompt }) catch |err| { self.gpa.free(prompt); return err; }; self.view.toBottom(); }, .prompts_returned => |returned| { defer self.gpa.free(returned.text); for (self.queued.items[0..returned.count]) |prompt| self.gpa.free(prompt); self.queued.replaceRangeAssumeCapacity(0, returned.count, &.{}); try self.restore(returned.text); }, .usage => |report| self.view.usage = report, .selection => |selection| try self.select(selection), .text_delta, .thinking_delta, .tool_call, .tool_result, .notice, => self.transcript.apply(update), }, .tick => |widget| { self.ctx.consume_event = false; self.ctx.redraw = true; self.ctx.phase = .at_target; try widget.handleEvent(&self.ctx, .tick); try self.runCommands(); }, } return true; }
fn receive(self: *Tui, response: protocol.core.Response) !void { const sent = self.pending.orderedRemove(0); std.debug.assert(sent.id == response.id); switch (response.result) { .attached => |session| { if (self.session) |old| { old.deinit(self.gpa); } self.session = session; self.view.model = session.model; self.view.level = session.level; self.view.cwd = session.cwd; }, .already_attached => return error.AlreadyAttached, .unknown_model => {}, .queued => self.queued.append(self.gpa, sent.prompt.?) catch |err| { self.gpa.free(sent.prompt.?); return err; }, .refused => { defer self.gpa.free(sent.prompt.?); try self.restore(sent.prompt.?); try self.notify("too many queued prompts; try again later"); }, .ok => {}, } }
/// Asks `core` to send its messages to `sink()`. pub fn attach(self: *Tui, core: protocol.Sink(protocol.ui.Request)) !void { self.core = core; if (!self.request(.{ .attach = self.sink() }, null)) { return error.CoreStopped; } self.attached = true; }
/// Detaches from the core and frees the core messages that arrive until /// the core answers. Other events in the queue are dropped too. pub fn detach(self: *Tui) void { if (!self.attached) { return; } self.attached = false; defer self.clearPending(); const id = self.next_id; if (!self.request(.{ .detach = self.sink() }, null)) { return; } while (self.loop.queue.pop()) |event| switch (event) { .core => |message| { defer message.deinit(self.gpa); if (message == .response and message.response.id == id) { return; } }, else => {}, } else |_| {} }
/// Forgets the requests without a response. A detached core does not answer them. fn clearPending(self: *Tui) void { for (self.pending.items) |sent| { if (sent.prompt) |prompt| { self.gpa.free(prompt); } } self.pending.clearRetainingCapacity(); }
/// Whether a request other than `detach` keeps a slot free for `detach`. fn canRequest(self: *const Tui) bool { return self.pending.items.len < protocol.inbox_capacity - 1; }
/// Sends a request and keeps it, with the text of a submit, until the /// response. Returns false when the core refused it. fn request(self: *Tui, method: protocol.ui.Request.Method, prompt: ?[]const u8) bool { if (!self.core.send(.{ .id = self.next_id, .method = method })) { return false; } self.pending.appendAssumeCapacity(.{ .id = self.next_id, .prompt = prompt }); self.next_id +%= 1; return true; }
fn runCommands(self: *Tui) !void { defer self.ctx.cmds.clearRetainingCapacity(); for (self.ctx.cmds.items) |command| switch (command) { .tick => |next| try self.timers.arm(next), else => {}, }; }
const busy = "the agent is busy; try again";
/// Sends the prompt in the editor to the core, or keeps it in the editor /// and reports why not. fn submit(self: *Tui) !void { if (self.editor.isEmpty()) { return; } if (!self.canRequest()) { return self.notify(busy); } const prompt = try self.editor.expand(); const copy = self.gpa.dupe(u8, prompt) catch |err| { self.gpa.free(prompt); return err; }; if (self.request(.{ .submit = copy }, prompt)) { self.editor.clear(); return; } self.gpa.free(copy); self.gpa.free(prompt); try self.notify(busy); }
/// Shows a new selection in the footer and in the transcript. Takes /// ownership of the model name. fn select(self: *Tui, selection: protocol.core.Selection) !void { const session = if (self.session) |*session| session else { self.gpa.free(selection.model); return; }; self.gpa.free(session.model); session.model = selection.model; session.level = selection.level; self.view.model = selection.model; self.view.level = selection.level;
const text = if (selection.level) |level| try std.fmt.allocPrint(self.gpa, "{s} • {t}", .{ selection.model, level }) else try self.gpa.dupe(u8, selection.model); errdefer self.gpa.free(text); try self.transcript.items.append(self.gpa, .{ .notice = .{ .kind = .info, .text = text } }); }
fn notify(self: *Tui, text: []const u8) !void { const notice = try self.gpa.dupe(u8, text); errdefer self.gpa.free(notice); try self.transcript.items.append(self.gpa, .{ .notice = .{ .kind = .err, .text = notice } }); }
/// Puts returned prompt text before the editor text, a blank line between /// the parts, and leaves out parts that are only whitespace. fn restore(self: *Tui, text: []const u8) !void { if (std.mem.trim(u8, text, &std.ascii.whitespace).len == 0) { return; } if (std.mem.trim(u8, self.editor.slice(), &std.ascii.whitespace).len == 0) { self.editor.clear(); } else { self.editor.cursor = 0; try self.editor.insert("\n\n"); self.editor.cursor = 0; } try self.editor.insert(text); self.editor.cursor = self.editor.text.items.len; }
/// Hands a click to the widget under the pointer. fn click(self: *Tui, mouse: vaxis.Mouse) !void { if (mouse.type != .press or mouse.button != .left) { return; } if (mouse.row < 0 or mouse.col < 0) { return; } var hits: std.ArrayList(vxfw.HitResult) = .empty; defer hits.deinit(self.gpa); try self.view.hitTest(self.gpa, .{ .row = @intCast(mouse.row), .col = @intCast(mouse.col) }, &hits); const target = hits.getLastOrNull() orelse return; self.ctx.consume_event = false; self.ctx.redraw = false; self.ctx.phase = .at_target; try target.widget.handleEvent(&self.ctx, .{ .mouse = mouse }); if (self.ctx.redraw) { self.dirty = true; } try self.runCommands(); }
pub fn draw(self: *Tui, win: vaxis.Window) !void { self.dirty = false; self.view.queued = self.queued.items; try self.view.render(win, &self.transcript, &self.editor); }};
/// Posts a `.tick` event when the deadline of a widget's timer passes. A/// widget has at most one timer: arming it again moves the deadline.const Timers = struct { gpa: std.mem.Allocator, io: std.Io, queue: *Queue = undefined, armed: std.ArrayList(vxfw.Tick) = .empty, mutex: std.Io.Mutex = .init, changed: std.Io.Condition = .init, task: ?std.Io.Future(std.Io.Cancelable!void) = null,
fn init(gpa: std.mem.Allocator, io: std.Io) Timers { return .{ .gpa = gpa, .io = io }; }
fn deinit(self: *Timers) void { self.stop(); self.armed.deinit(self.gpa); }
/// Starts posting ticks to `queue`. fn start(self: *Timers, queue: *Queue) !void { self.queue = queue; self.task = try self.io.concurrent(taskMain, .{self}); }
fn stop(self: *Timers) void { if (self.task) |*task| { task.cancel(self.io) catch {}; } self.task = null; }
fn arm(self: *Timers, tick: vxfw.Tick) !void { self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); for (self.armed.items) |*armed| { if (armed.widget.eql(tick.widget)) { armed.deadline = tick.deadline; break; } } else try self.armed.append(self.gpa, tick); self.changed.signal(self.io); }
fn taskMain(self: *Timers) std.Io.Cancelable!void { try self.mutex.lock(self.io); defer self.mutex.unlock(self.io); while (true) { if (self.armed.items.len == 0) { try self.changed.wait(self.io, &self.mutex); continue; } var first: usize = 0; for (self.armed.items, 0..) |armed, index| { if (armed.deadline.nanoseconds < self.armed.items[first].deadline.nanoseconds) { first = index; } } const due = self.armed.items[first]; if (std.Io.Timestamp.now(self.io, .awake).durationTo(due.deadline).nanoseconds > 0) { // Wakes early when a timer changes; a spurious wakeup only loops. self.changed.waitTimeout(self.io, &self.mutex, .{ .deadline = .{ .raw = due.deadline, .clock = .awake } }) catch |err| switch (err) { error.Canceled => return error.Canceled, error.Timeout => {}, }; continue; } _ = self.armed.swapRemove(first); self.mutex.unlock(self.io); defer self.mutex.lockUncancelable(self.io); self.queue.push(.{ .tick = due.widget }) catch |err| if (err == error.Canceled) { return error.Canceled; }; } }};
test "the key table maps the interrupt and quit keys" { try testing.expectEqual(Action.interrupt, Action.forKey(.{ .codepoint = 'c', .mods = .{ .ctrl = true }, }, .{ .working = true, .has_text = false, }));
try testing.expectEqual(Action.quit, Action.forKey(.{ .codepoint = 'c', .mods = .{ .ctrl = true }, }, .{ .working = false, .has_text = false, }));
try testing.expectEqual(Action.clear_prompt, Action.forKey(.{ .codepoint = 'c', .mods = .{ .ctrl = true }, }, .{ .working = false, .has_text = true, }));
try testing.expectEqual(Action.interrupt, Action.forKey(.{ .codepoint = vaxis.Key.escape }, .{ .working = true, .has_text = false, }));
try testing.expectEqual(Action.none, Action.forKey(.{ .codepoint = vaxis.Key.escape }, .{ .working = false, .has_text = false, }));}
test "ctrl t, ctrl p and shift tab work while the agent is idle or working" { for ([_]bool{ false, true }) |working| { const state: Action.TerminalState = .{ .working = working, .has_text = working }; try testing.expectEqual(Action.cycle_level, Action.forKey(.{ .codepoint = 't', .mods = .{ .ctrl = true } }, state)); try testing.expectEqual(Action.cycle_model, Action.forKey(.{ .codepoint = 'p', .mods = .{ .ctrl = true } }, state)); try testing.expectEqual(Action.toggle_thinking, Action.forKey(.{ .codepoint = vaxis.Key.tab, .mods = .{ .shift = true } }, state)); }}
test "ctrl o toggles the expanded state" { for ([_]bool{ false, true }) |working| { try testing.expectEqual(Action.toggle_expanded, Action.forKey(.{ .codepoint = 'o', .mods = .{ .ctrl = true }, }, .{ .working = working, .has_text = true, })); }}
test "enter submits and shift enter inserts a newline" { try testing.expectEqual(Action.submit, Action.forKey(.{ .codepoint = vaxis.Key.enter }, .{ .working = false, .has_text = false, }));
try testing.expectEqual(Action.submit, Action.forKey(.{ .codepoint = vaxis.Key.enter }, .{ .working = true, .has_text = false, }));
try testing.expectEqual(Action.insert_newline, Action.forKey(.{ .codepoint = vaxis.Key.enter, .mods = .{ .shift = true } }, .{ .working = false, .has_text = false, }));
try testing.expectEqual(Action.page_up, Action.forKey(.{ .codepoint = vaxis.Key.page_up }, .{ .working = false, .has_text = false, }));}
test "a bracketed paste inserts once and never submits" { var paste = PasteBuffer.init(testing.allocator); defer paste.deinit();
var editor = editors.Editor.init(testing.allocator); defer editor.deinit();
// Keys outside a paste belong to the key action table. try testing.expect(!try paste.handle(.{ .key_press = .{ .codepoint = 'x', .text = "x" } }, &editor)); try testing.expectEqualStrings("", editor.slice());
// vaxis sends paste_start, one key per character (a newline is Enter) and paste_end. const events = [_]Event{ .paste_start, .{ .key_press = .{ .codepoint = 'a', .text = "a" } }, .{ .key_press = .{ .codepoint = vaxis.Key.enter } }, .{ .key_press = .{ .codepoint = 'b', .text = "b" } }, .paste_end, }; for (events) |event| try testing.expect(try paste.handle(event, &editor));
try testing.expect(!paste.active); try testing.expectEqualStrings("a\nb", editor.slice());}
test "a paste maps control keys to text and ignores the rest" { var paste = PasteBuffer.init(testing.allocator); defer paste.deinit();
var editor = editors.Editor.init(testing.allocator); defer editor.deinit();
const events = [_]Event{ .paste_start, .{ .key_press = .{ .codepoint = 'a', .text = "a" } }, .{ .key_press = .{ .codepoint = 'j', .mods = .{ .ctrl = true } } }, .{ .key_press = .{ .codepoint = vaxis.Key.tab } }, .{ .key_press = .{ .codepoint = vaxis.Key.left } }, .{ .key_press = .{ .codepoint = 'b', .text = "b" } }, .paste_end, }; for (events) |event| try testing.expect(try paste.handle(event, &editor));
// insertPaste expands tabs, so the tab arrives as four spaces. try testing.expectEqualStrings("a\n b", editor.slice());}
test "a paste of more than ten lines becomes one marker that expands for the agent" { var paste = PasteBuffer.init(testing.allocator); defer paste.deinit();
var editor = editors.Editor.init(testing.allocator); defer editor.deinit();
try testing.expect(try paste.handle(.paste_start, &editor)); var buf: [1]u8 = undefined; for ("abcdefghijkl", 0..) |char, index| { if (index > 0) { try testing.expect(try paste.handle(.{ .key_press = .{ .codepoint = vaxis.Key.enter } }, &editor)); } buf[0] = char; try testing.expect(try paste.handle(.{ .key_press = .{ .codepoint = char, .text = &buf } }, &editor)); } try testing.expect(try paste.handle(.paste_end, &editor));
// A single insert produces the marker; one insert per character would not. try testing.expectEqualStrings("[paste #1 +12 lines]", editor.slice()); try testing.expectEqual(@as(usize, 1), editor.pasteCount());
const taken = try editor.take(); defer testing.allocator.free(taken); try testing.expectEqualStrings("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl", taken);}
/// A widget that re-arms itself, like the spinner does.const RearmingWidget = struct { calls: usize = 0,
fn widget(self: *RearmingWidget) vxfw.Widget { return .{ .userdata = self, .eventHandler = handle, .drawFn = draw }; }
fn handle(ptr: *anyopaque, ctx: *vxfw.EventContext, event: vxfw.Event) anyerror!void { const self: *RearmingWidget = @ptrCast(@alignCast(ptr)); switch (event) { .tick => { self.calls += 1; try ctx.tick(5, self.widget()); }, else => {}, } }
fn draw(ptr: *anyopaque, ctx: vxfw.DrawContext) std.mem.Allocator.Error!vxfw.Surface { const self: *RearmingWidget = @ptrCast(@alignCast(ptr)); return vxfw.Surface.init(ctx.arena, self.widget(), .{ .width = 1, .height = 1 }); }};
fn tickIn(ms: u32, widget: vxfw.Widget) vxfw.Tick { const deadline = std.Io.Timestamp.now(testing.io, .awake).addDuration(.fromMilliseconds(ms)); return .{ .deadline = deadline, .widget = widget };}
const helpers = @import("testing.zig");const Watchdog = helpers.Watchdog(Queue);
/// Started timers that post into their own queue. Do not move it after `init`.const TimerTest = struct { queue: Queue, timers: Timers, watchdog: Watchdog,
fn init(self: *TimerTest) !void { self.queue = .init(testing.io); self.timers = .init(testing.allocator, testing.io); try self.timers.start(&self.queue); self.watchdog = try .start(&self.queue); }
fn deinit(self: *TimerTest) void { self.watchdog.stop(); self.queue.close(error.Closed); self.timers.deinit(); }
fn expectTick(self: *TimerTest, widget: vxfw.Widget) !void { const event = try self.queue.pop(); try testing.expect(event == .tick and event.tick.eql(widget)); }};
test "a timer posts a tick for its widget when its deadline passes" { var widget: RearmingWidget = .{}; var timers: TimerTest = undefined; try timers.init(); defer timers.deinit();
try timers.timers.arm(tickIn(10, widget.widget())); try timers.expectTick(widget.widget());}
test "a fired timer does not fire again" { var first: RearmingWidget = .{}; var second: RearmingWidget = .{}; var timers: TimerTest = undefined; try timers.init(); defer timers.deinit();
try timers.timers.arm(tickIn(0, first.widget())); try timers.expectTick(first.widget()); try timers.timers.arm(tickIn(20, second.widget())); try timers.expectTick(second.widget());}
test "timers fire in deadline order" { var late: RearmingWidget = .{}; var early: RearmingWidget = .{}; var timers: TimerTest = undefined; try timers.init(); defer timers.deinit();
try timers.timers.arm(tickIn(40, late.widget())); try timers.timers.arm(tickIn(0, early.widget())); try timers.expectTick(early.widget()); try timers.expectTick(late.widget());}
test "arming a widget again replaces its deadline" { var moved: RearmingWidget = .{}; var other: RearmingWidget = .{}; var timers: TimerTest = undefined; try timers.init(); defer timers.deinit();
try timers.timers.arm(tickIn(200, moved.widget())); try timers.timers.arm(tickIn(60_000, moved.widget())); try timers.timers.arm(tickIn(400, other.widget())); try timers.expectTick(other.widget());}
const Fixture = @import("view/testing.zig").Fixture;/// Keeps the requests that a TUI sends.const Sent = struct { requests: std.ArrayList(protocol.ui.Request) = .empty,
fn deinit(self: *Sent) void { for (self.requests.items) |request| request.deinit(testing.allocator); self.requests.deinit(testing.allocator); }
fn sink(self: *Sent) protocol.Sink(protocol.ui.Request) { return .{ .ctx = self, .sendFn = send }; }
fn send(ctx: *anyopaque, request: protocol.ui.Request) bool { const self: *Sent = @ptrCast(@alignCast(ctx)); self.requests.append(testing.allocator, request) catch return false; return true; }
fn count(self: *const Sent, tag: std.meta.Tag(protocol.ui.Request.Method)) usize { var total: usize = 0; for (self.requests.items) |request| total += @intFromBool(request.method == tag); return total; }};
/// A TUI without a terminal, attached to a core that it records the requests/// to. Do not move it after `init`.const Harness = struct { sent: Sent, tui: *Tui, /// How many of the sent requests have a response. answered: usize,
fn init(self: *Harness) !void { self.sent = .{}; self.answered = 0; self.tui = try Tui.init(testing.allocator, testing.io); self.tui.width = 80; try self.tui.attach(self.sent.sink()); try self.respond(.{ .attached = .{ .model = try dupe("fake"), .cwd = try dupe("/tmp") } }); }
fn deinit(self: *Harness) void { self.tui.deinit(); self.sent.deinit(); }
fn apply(self: *Harness, message: protocol.core.Message) !void { try testing.expect(try self.tui.handle(.{ .core = message })); }
/// Answers the oldest request without a response. fn respond(self: *Harness, result: protocol.core.Response.Result) !void { const id = self.sent.requests.items[self.answered].id; self.answered += 1; try self.apply(.{ .response = .{ .id = id, .result = result } }); }
fn key(self: *Harness, codepoint: u21) !void { try testing.expect(try self.tui.handle(.{ .key_press = .{ .codepoint = codepoint } })); }
/// Checks the prompts submitted so far. fn expectSubmitted(self: *Harness, prompts: []const []const u8) !void { try testing.expectEqual(prompts.len, self.sent.count(.submit)); var index: usize = 0; for (self.sent.requests.items) |request| switch (request.method) { .submit => |text| { try testing.expectEqualStrings(prompts[index], text); index += 1; }, else => {}, }; }
/// Applies queued events up to and including a tick. fn applyUntilTick(self: *Harness) !void { var watchdog: Watchdog = try .start(&self.tui.loop.queue); defer watchdog.stop(); while (true) { const event = try self.tui.loop.queue.pop(); _ = try self.tui.handle(event); if (event == .tick) { return; } } }};
fn dupe(text: []const u8) ![]const u8 { return testing.allocator.dupe(u8, text);}
fn refuse(_: *anyopaque, _: protocol.ui.Request) bool { return false;}
const refusing: protocol.Sink(protocol.ui.Request) = .{ .ctx = undefined, .sendFn = refuse };
test "a tick runs its widget and arms the timer the widget asks for" { var harness: Harness = undefined; try harness.init(); defer harness.deinit(); try harness.tui.timers.start(&harness.tui.loop.queue);
var widget: RearmingWidget = .{}; try testing.expect(try harness.tui.handle(.{ .tick = widget.widget() })); try testing.expectEqual(@as(usize, 1), widget.calls); try harness.applyUntilTick(); try testing.expectEqual(@as(usize, 2), widget.calls);}
test "a core send that waits for room fails once the queue closes, and deinit frees every event" { var harness: Harness = undefined; try harness.init(); defer harness.deinit(); const queue = &harness.tui.loop.queue; var flood = try testing.io.concurrent(sendUntilRefused, .{harness.tui.sink()}); defer flood.await(testing.io); // What `run` does when it returns. defer queue.close(error.Closed); const deadline = std.Io.Timestamp.now(testing.io, .awake).addDuration(.fromSeconds(10)); while (!try queue.isFull()) { try testing.expect(deadline.untilNow(testing.io, .awake).nanoseconds < 0); try testing.io.sleep(.fromMilliseconds(1), .awake); }}
fn sendUntilRefused(sink: protocol.Sink(protocol.core.Message)) void { while (true) { const text = dupe("x") catch return; if (!sink.send(.{ .text_delta = text })) { return testing.allocator.free(text); } }}
test "agent_start arms the spinner timer" { var harness: Harness = undefined; try harness.init(); defer harness.deinit(); try harness.tui.timers.start(&harness.tui.loop.queue);
try harness.apply(.agent_start); try harness.applyUntilTick(); try testing.expect(harness.tui.view.working);}
test "ctrl t and ctrl p ask the core for the next level and the next model" { var harness: Harness = undefined; try harness.init(); defer harness.deinit();
try testing.expect(try harness.tui.handle(.{ .key_press = .{ .codepoint = 't', .mods = .{ .ctrl = true } } })); try testing.expectEqual(@as(usize, 1), harness.sent.count(.cycle_level)); try harness.respond(.ok); try testing.expect(try harness.tui.handle(.{ .key_press = .{ .codepoint = 'p', .mods = .{ .ctrl = true } } })); try testing.expectEqual(@as(usize, 1), harness.sent.count(.cycle_model)); try harness.respond(.ok); try testing.expectEqual(@as(usize, 0), harness.tui.transcript.items.items.len);}
test "a new selection shows in the footer and as a notice" { var harness: Harness = undefined; try harness.init(); defer harness.deinit(); const tui = harness.tui; try testing.expectEqualStrings("fake", tui.view.model); try testing.expectEqual(null, tui.view.level);
try harness.apply(.{ .selection = .{ .model = try dupe("kimi"), .level = .high } }); try testing.expectEqualStrings("kimi", tui.view.model); try testing.expectEqual(protocol.core.Level.high, tui.view.level.?); const first = tui.transcript.items.items[0].notice; try testing.expectEqual(protocol.core.Notice.Kind.info, first.kind); try testing.expectEqualStrings("kimi • high", first.text);
try harness.apply(.{ .selection = .{ .model = try dupe("plain"), .level = null } }); try testing.expectEqualStrings("plain", tui.view.model); try testing.expectEqual(null, tui.view.level); try testing.expectEqualStrings("plain", tui.transcript.items.items[1].notice.text);}
test "shift tab hides and shows thinking" { var harness: Harness = undefined; try harness.init(); defer harness.deinit(); const tui = harness.tui; const shift_tab: Event = .{ .key_press = .{ .codepoint = vaxis.Key.tab, .mods = .{ .shift = true } } };
try testing.expect(tui.transcript.show_thinking); try testing.expect(try tui.handle(shift_tab)); try testing.expect(!tui.transcript.show_thinking); try testing.expect(try tui.handle(shift_tab)); try testing.expect(tui.transcript.show_thinking); try testing.expect(tui.editor.isEmpty());}
test "a usage report reaches the footer and the next one replaces it" { var harness: Harness = undefined; try harness.init(); defer harness.deinit(); const tui = harness.tui; try testing.expectEqual(null, tui.view.usage);
var report: protocol.core.UsageReport = .{ .request = .{ .input = 5 }, .request_cost = null, .session = .{ .input = 5 }, .session_cost = null, .context_tokens = 5, .context_window = 0, }; try harness.apply(.{ .usage = report }); try testing.expectEqual(@as(u64, 5), tui.view.usage.?.session.input); report.session.input = 9; try harness.apply(.{ .usage = report }); try testing.expectEqual(@as(u64, 9), tui.view.usage.?.session.input);}
test "a prompt submitted during a run waits dim below the transcript and then runs" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); var harness: Harness = undefined; try harness.init(); defer harness.deinit(); const tui = harness.tui;
try tui.editor.insert("first"); try harness.key(vaxis.Key.enter); try harness.respond(.queued); try harness.apply(.agent_start); try harness.apply(.prompt_start); try harness.apply(.{ .text_delta = try dupe("one") }); try tui.editor.insert("second"); try harness.key(vaxis.Key.enter); try testing.expectEqual(@as(usize, 0), tui.queued.items.len); try harness.respond(.queued);
try harness.expectSubmitted(&.{ "first", "second" }); try testing.expect(tui.editor.isEmpty()); try testing.expectEqual(@as(usize, 1), tui.queued.items.len); try testing.expectEqualStrings("second", tui.queued.items[0]); try testing.expectEqualStrings("first", tui.transcript.items.items[0].user); try testing.expectEqual(@as(usize, 2), tui.transcript.items.items.len);
var screen: Fixture = undefined; try screen.init(10, 40); defer screen.deinit(); try tui.draw(screen.win); var line: u16 = 0; while (!std.mem.startsWith(u8, try screen.row(line, arena_state.allocator()), "second")) line += 1; try testing.expect(screen.style(0, line).dim); try testing.expectEqualStrings("one", std.mem.trimEnd(u8, try screen.row(line - 1, arena_state.allocator()), " "));
try harness.apply(.prompt_start); try harness.apply(.{ .text_delta = try dupe("two") }); try harness.apply(.agent_end); try testing.expectEqual(@as(usize, 0), tui.queued.items.len); try testing.expectEqualStrings("second", tui.transcript.items.items[2].user);}
test "a prompt that the core has no room for goes back to the editor with a notice" { var harness: Harness = undefined; try harness.init(); defer harness.deinit(); const tui = harness.tui;
tui.core = refusing; try tui.editor.insert("go"); try harness.key(vaxis.Key.enter); try testing.expectEqualStrings("go", tui.editor.slice()); try testing.expectEqualStrings("the agent is busy; try again", tui.transcript.items.items[0].notice.text);
tui.core = harness.sent.sink(); try harness.key(vaxis.Key.enter); try testing.expect(tui.editor.isEmpty()); try tui.editor.insert("draft"); try harness.respond(.refused); try testing.expectEqualStrings("go\n\ndraft", tui.editor.slice()); try testing.expectEqualStrings("too many queued prompts; try again later", tui.transcript.items.items[1].notice.text); try testing.expectEqual(@as(usize, 0), tui.queued.items.len);}
test "an interrupt puts the returned prompts before the draft in the editor" { var harness: Harness = undefined; try harness.init(); defer harness.deinit(); const tui = harness.tui;
try harness.apply(.agent_start); for ([_][]const u8{ "second", " ", "third" }) |prompt| { try tui.editor.insert(prompt); try harness.key(vaxis.Key.enter); try harness.respond(.queued); } try tui.editor.insert("draft"); try harness.key(vaxis.Key.escape); try testing.expectEqual(@as(usize, 1), harness.sent.count(.interrupt)); try harness.respond(.ok); try harness.apply(.{ .prompts_returned = .{ .count = 3, .text = try dupe("second\n\nthird") } });
try testing.expectEqualStrings("second\n\nthird\n\ndraft", tui.editor.slice()); try testing.expectEqual(@as(usize, 0), tui.queued.items.len);
tui.core = refusing; try harness.key(vaxis.Key.escape); try testing.expectEqualStrings("the agent is busy; try again", tui.transcript.items.items[0].notice.text);}
test "the footer shows the model and the working directory from the attach response" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); var harness: Harness = undefined; try harness.init(); defer harness.deinit();
var screen: Fixture = undefined; try screen.init(6, 40); defer screen.deinit(); try harness.tui.draw(screen.win); try testing.expectEqualStrings("fake · /tmp", std.mem.trimEnd(u8, try screen.row(5, arena_state.allocator()), " "));}
test "an attach that finds another UI attached ends the TUI" { var sent: Sent = .{}; defer sent.deinit(); const tui = try Tui.init(testing.allocator, testing.io); defer tui.deinit();
try tui.attach(sent.sink());
const id = sent.requests.items[0].id; try testing.expectError(error.AlreadyAttached, tui.handle(.{ .core = .{ .response = .{ .id = id, .result = .already_attached } } }));}
test "a TUI with inbox_capacity - 1 unanswered requests keeps the prompt and refuses an interrupt, and detach still fits" { var harness: Harness = undefined; try harness.init(); defer harness.deinit(); const tui = harness.tui; try harness.apply(.agent_start);
for (0..protocol.inbox_capacity - 1) |_| { try tui.editor.insert("p"); try harness.key(vaxis.Key.enter); } try tui.editor.insert("last"); try harness.key(vaxis.Key.enter); try harness.key(vaxis.Key.escape);
try testing.expectEqualStrings("last", tui.editor.slice()); try testing.expectEqual(protocol.inbox_capacity - 1, harness.sent.count(.submit)); try testing.expectEqual(0, harness.sent.count(.interrupt)); try testing.expectEqualStrings("the agent is busy; try again", tui.transcript.items.items[0].notice.text); try testing.expectEqualStrings("the agent is busy; try again", tui.transcript.items.items[1].notice.text);
try tui.loop.queue.push(.{ .core = .{ .response = .{ .id = tui.next_id, .result = .ok } } }); tui.detach(); try testing.expectEqual(1, harness.sent.count(.detach));}
test "detach frees the core messages that arrive before its response" { var harness: Harness = undefined; try harness.init(); defer harness.deinit(); const tui = harness.tui;
try tui.loop.queue.push(.{ .core = .{ .text_delta = try dupe("late") } }); try tui.loop.queue.push(.{ .core = .{ .response = .{ .id = tui.next_id, .result = .ok } } }); try tui.loop.queue.push(.{ .core = .{ .text_delta = try dupe("after") } }); tui.detach();
try testing.expectEqual(1, harness.sent.count(.detach)); try testing.expectEqual(@as(usize, 0), tui.transcript.items.items.len); const left = try tui.loop.queue.pop(); try testing.expectEqualStrings("after", left.core.text_delta); left.core.deinit(testing.allocator);}
test "returned prompts replace a draft that is only whitespace" { var harness: Harness = undefined; try harness.init(); defer harness.deinit(); const tui = harness.tui;
try tui.editor.insert(" \n"); try tui.restore("a"); try testing.expectEqualStrings("a", tui.editor.slice()); try tui.restore(""); try testing.expectEqualStrings("a", tui.editor.slice());}
fn appendTool(tui: *Tui) !void { try tui.transcript.items.append(testing.allocator, .{ .tool = .{ .id = try testing.allocator.dupe(u8, "call"), .state = .ok, .call = try .init(testing.allocator, &.{.{ .text = "bash" }}), .collapsed = try .init(testing.allocator, &.{.{ .text = "exit 0" }}), .expanded = try .init(testing.allocator, &.{.{ .text = "out" }}), } });}
test "a click expands the tool block under the pointer and motion needs no redraw" { const tui = try Tui.init(testing.allocator, testing.io); defer tui.deinit(); try appendTool(tui); var screen: Fixture = undefined; try screen.init(12, 40); defer screen.deinit(); try tui.draw(screen.win);
try testing.expect(try tui.handle(.{ .mouse = .{ .col = 2, .row = 1, .button = .none, .mods = .{}, .type = .motion } })); try testing.expect(!tui.dirty); try testing.expect(!tui.transcript.items.items[0].tool.open);
try testing.expect(try tui.handle(.{ .mouse = .{ .col = 2, .row = 1, .button = .left, .mods = .{}, .type = .press } })); try testing.expect(tui.dirty); try testing.expect(tui.transcript.items.items[0].tool.open);}
test "the wheel scrolls the transcript" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const tui = try Tui.init(testing.allocator, testing.io); defer tui.deinit(); const lines = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15"; try tui.transcript.items.append(testing.allocator, .{ .assistant = .fromOwnedSlice(try testing.allocator.dupe(u8, lines)) }); var screen: Fixture = undefined; try screen.init(12, 40); defer screen.deinit(); // The transcript shows eight rows above the prompt. try tui.draw(screen.win); try testing.expect(std.mem.startsWith(u8, try screen.row(0, arena), "8 "));
try testing.expect(try tui.handle(.{ .mouse = .{ .col = 2, .row = 1, .button = .wheel_up, .mods = .{}, .type = .press } })); try testing.expect(tui.dirty); try tui.draw(screen.win); try testing.expect(std.mem.startsWith(u8, try screen.row(0, arena), "5 "));
try testing.expect(try tui.handle(.{ .mouse = .{ .col = 2, .row = 1, .button = .wheel_down, .mods = .{}, .type = .press } })); try tui.draw(screen.win); try testing.expect(std.mem.startsWith(u8, try screen.row(0, arena), "8 "));}