xonecas.io
79113
Ma

mini-coding-agent / files

mini-coding-agent / src / tui / tui.zig

48.9 KB
1const std = @import("std");
2const platform = @import("../platform.zig");
3const time = @import("../time.zig");
4const config = @import("../config.zig");
5const session_mod = @import("../session.zig");
6const message_mod = @import("../message.zig");
7const agent = @import("../agent.zig");
8const models_mod = @import("../models.zig");
9const tools_index = @import("../tools.zig");
10const render = @import("render.zig");
11const styles = @import("styles.zig");
12const term = @import("term.zig");
13const input = @import("input.zig");
14const editor_mod = @import("editor.zig");
15const stream = @import("stream.zig");
16const complete = @import("complete.zig");
17const commands = @import("commands.zig");
18const usage_mod = @import("usage.zig");
19const diff_view = @import("diff_view.zig");
20const tool_view = @import("tool_view.zig");
21const image_view = @import("image.zig");
22const picker_mod = @import("picker.zig");
23const screen = @import("screen.zig");
24const history = @import("history.zig");
25const status = @import("status.zig");
26const strings = @import("../text.zig");
27
28const SPINNER = "⠀⠁⠂⠃⠄⠅⠆⠇⡀⡁⡂⡃⡄⡅⡆⡇⠈⠉⠊⠋⠌⠍⠎⠏⡈⡉⡊⡋⡌⡍⡎⡏⠐⠑⠒⠓⠔⠕⠖⠗⡐⡑⡒⡓⡔⡕⡖⡗⠘⠙⠚⠛⠜⠝⠞⠟⡘⡙⡚⡛⡜⡝⡞⡟⠠⠡⠢⠣⠤⠥⠦⠧⡠⡡⡢⡣⡤⡥⡦⡧⠨⠩⠪⠫⠬⠭⠮⠯⡨⡩⡪⡫⡬⡭⡮⡯⠰⠱⠲⠳⠴⠵⠶⠷⡰⡱⡲⡳⡴⡵⡶⡷⠸⠹⠺⠻⠼⠽⠾⠿⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⣀⣁⣂⣃⣄⣅⣆⣇⢈⢉⢊⢋⢌⢍⢎⢏⣈⣉⣊⣋⣌⣍⣎⣏⢐⢑⢒⢓⢔⢕⢖⢗⣐⣑⣒⣓⣔⣕⣖⣗⢘⢙⢚⢛⢜⢝⢞⢟⣘⣙⣚⣛⣜⣝⣞⣟⢠⢡⢢⢣⢤⢥⢦⢧⣠⣡⣢⣣⣤⣥⣦⣧⢨⢩⢪⢫⢬⢭⢮⢯⣨⣩⣪⣫⣬⣭⣮⣯⢰⢱⢲⢳⢴⢵⢶⢷⣰⣱⣲⣳⣴⣵⣶⣷⢸⢹⢺⢻⢼⢽⢾⢿⣸⣹⣺⣻⣼⣽⣾⣿";
29const SPINNER_MS = 120;
30const BODY_PREFIX = " │ ";
31const ERROR_PREFIX = " ! ";
32
33const PendingCall = tool_view.PendingCall;
34const Picker = picker_mod.Picker;
35
36const Command = commands.Command;
37
38var resize_flag = std.atomic.Value(bool).init(false);
39var exit_flag = std.atomic.Value(bool).init(false);
40var exit_signal = std.atomic.Value(u32).init(0);
41
42fn onWinch(_: std.posix.SIG) callconv(.c) void {
43    resize_flag.store(true, .seq_cst);
44}
45
46fn onExitSignal(sig: std.posix.SIG) callconv(.c) void {
47    term.restore();
48    exit_signal.store(@backingInt(sig), .seq_cst);
49    exit_flag.store(true, .seq_cst);
50}
51
52const Tui = struct {
53    opts: *agent.Options,
54    cfg: *const config.Config,
55    history: history.Store = undefined,
56    tool_names: []const config.ToolName,
57    term: term.Terminal = .{},
58    editor: editor_mod.Editor,
59    live: screen.LiveRegion = .{},
60    messages: std.ArrayList(message_mod.Message) = .empty,
61    backing: std.mem.Allocator = undefined,
62    arena: std.heap.ArenaAllocator,
63    a: std.mem.Allocator,
64    scratch: std.heap.ArenaAllocator,
65    s: std.mem.Allocator,
66    sarena: std.heap.ArenaAllocator,
67    sa: std.mem.Allocator,
68    calls: std.heap.ArenaAllocator,
69    ca: std.mem.Allocator = undefined,
70    image_seq: u32 = 0,
71
72    input_bytes: std.ArrayList(u8) = .empty,
73    input_batch: std.ArrayList(u8) = .empty,
74    keys: std.ArrayList(input.Key) = .empty,
75    parser: input.Parser = .{},
76    stdin_closed: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
77    eof_sent: bool = false,
78    key_mutex: std.Io.Mutex = .init,
79    messages_mutex: std.Io.Mutex = .init,
80    events: std.ArrayList(agent.Event) = .empty,
81    batch: std.ArrayList(agent.Event) = .empty,
82    event_mutex: std.Io.Mutex = .init,
83    qarena: std.heap.ArenaAllocator,
84    q: std.mem.Allocator,
85
86    phase: agent.Phase = .idle,
87    detail: ?[]const u8 = null,
88    retrying: ?[]const u8 = null,
89    writing_tool: ?[]const u8 = null,
90    writing_bytes: usize = 0,
91    stream_kind: enum { none, reasoning, text, tool } = .none,
92    text_bytes: usize = 0,
93    reasoning_bytes: usize = 0,
94    active: bool = false,
95    paused: bool = false,
96    retry: bool = false,
97    pause_requested: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
98    aborting: bool = false,
99    turn_done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
100    steering_text: []const u8 = "",
101    steering_ready: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
102    abort: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
103
104    scrollback: screen.Scrollback = .{},
105
106    reply: stream.MarkdownStream,
107    pending_calls: std.ArrayList(PendingCall) = .empty,
108    tool_block: bool = false,
109    streamed: std.ArrayList(u8) = .empty,
110    turn_start: i64 = 0,
111    turn_msgs: usize = 0,
112    ctx_msgs: usize = std.math.maxInt(usize),
113    ctx_used: u64 = 0,
114    ctx_cache: message_mod.Usage = .{},
115    frame: usize = 0,
116    dirty: bool = true,
117    closed: bool = false,
118    last_frame_ms: i64 = 0,
119    last_input_ms: i64 = 0,
120    command_active: bool = false,
121
122    picker_arena: std.heap.ArenaAllocator,
123    picker_m: std.mem.Allocator = undefined,
124
125    hist_index: ?usize = null,
126    hist_saved: []const u8 = "",
127
128    picker: ?Picker = null,
129
130    model_thread: ?std.Thread = null,
131    model_abort: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
132    model_ready: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
133    model_ok: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
134    model_entries: []const models_mod.Entry = &.{},
135    model_provider: []const u8 = "",
136    model_arena: std.heap.ArenaAllocator,
137    model_m: std.mem.Allocator = undefined,
138
139    fn init(a: std.mem.Allocator, opts: *agent.Options, cfg: *const config.Config, tool_names: []const config.ToolName) Tui {
140        return .{
141            .opts = opts,
142            .cfg = cfg,
143            .tool_names = tool_names,
144            .editor = undefined,
145            .backing = a,
146            .arena = std.heap.ArenaAllocator.init(a),
147            .a = undefined,
148            .scratch = std.heap.ArenaAllocator.init(a),
149            .s = undefined,
150            .sarena = std.heap.ArenaAllocator.init(a),
151            .sa = undefined,
152            .calls = std.heap.ArenaAllocator.init(a),
153            .qarena = std.heap.ArenaAllocator.init(a),
154            .q = undefined,
155            .model_arena = std.heap.ArenaAllocator.init(a),
156            .picker_arena = std.heap.ArenaAllocator.init(a),
157            .reply = undefined,
158        };
159    }
160
161    fn bindAllocators(self: *Tui) void {
162        self.a = self.arena.allocator();
163        self.s = self.scratch.allocator();
164        self.sa = self.sarena.allocator();
165        self.ca = self.calls.allocator();
166        self.q = self.qarena.allocator();
167        self.model_m = self.model_arena.allocator();
168        self.picker_m = self.picker_arena.allocator();
169        self.editor = editor_mod.Editor.init(self.backing);
170        self.editor.bind();
171        self.editor.s = self.s;
172        self.reply = stream.MarkdownStream.init(self.backing);
173        self.reply.bind();
174        self.scrollback.a = self.a;
175        self.scrollback.scratch = self.sa;
176    }
177
178    fn resetScratch(self: *Tui) void {
179        _ = self.scratch.reset(.retain_capacity);
180        self.s = self.scratch.allocator();
181        self.editor.s = self.s;
182    }
183
184    fn push(self: *Tui, line: []const u8) void {
185        self.scrollback.push(line);
186        self.dirty = true;
187    }
188
189    fn commitLines(self: *Tui, lines: []const render.BodyLine) void {
190        if (lines.len == 0) return;
191        if (self.tool_block) self.scrollback.separator = true;
192        self.tool_block = false;
193        self.scrollback.commitLines(lines);
194        self.dirty = true;
195    }
196
197    fn note(self: *Tui, line: []const u8) void {
198        self.tool_block = false;
199        self.scrollback.note(line);
200        self.dirty = true;
201    }
202
203    fn fail(self: *Tui, comptime fmt: []const u8, args: anytype) void {
204        self.note(styles.err(self.s, std.fmt.allocPrint(self.s, fmt, args) catch "! error"));
205    }
206
207    fn commitUser(self: *Tui, text: []const u8) void {
208        self.tool_block = false;
209        self.scrollback.commitUser(text);
210        self.dirty = true;
211    }
212
213    fn pushBanner(self: *Tui) void {
214        self.scrollback.separator = true;
215        const a = self.s;
216        var parts: std.ArrayList([]const u8) = .empty;
217        parts.append(a, styles.accent(a, "mini-coding-agent")) catch {};
218        if (self.opts.model) |m| {
219            parts.append(a, std.fmt.allocPrint(a, "{s}/{s}", .{ m.provider, m.id }) catch m.id) catch {};
220            if (m.effort.len > 0) parts.append(a, m.effort) catch {};
221        } else {
222            parts.append(a, "no model configured") catch {};
223        }
224        self.push(styles.join(a, parts.items));
225        const loaded = self.opts.loaded;
226        var resources: std.ArrayList([]const u8) = .empty;
227        if (loaded.agent_files > 0)
228            resources.append(a, styles.comment(a, strings.plural(a, loaded.agent_files, "agent file", "agent files"))) catch {};
229        if (loaded.skills > 0)
230            resources.append(a, styles.comment(a, strings.plural(a, loaded.skills, "skill", "skills"))) catch {};
231        if (resources.items.len > 0) self.push(styles.join(a, resources.items));
232        self.scrollback.separator = true;
233    }
234
235    fn statusLine(self: *Tui) []const u8 {
236        const model = self.opts.model orelse return styles.comment(self.s, "no model configured");
237        self.messages_mutex.lockUncancelable(platform.io);
238        const count = self.messages.items.len;
239        if (count != self.ctx_msgs) {
240            self.ctx_used = usage_mod.estimateContextTokens(self.messages.items, self.opts.system_prompt, self.opts.tools_json);
241            self.ctx_cache = usage_mod.lastUsage(self.messages.items);
242            self.ctx_msgs = count;
243        }
244        const used = self.ctx_used;
245        const cache = self.ctx_cache;
246        self.messages_mutex.unlock(platform.io);
247        const info = std.fmt.allocPrint(self.s, "{s}{s}{s}", .{
248            usage_mod.contextUsageLine(self.s, used, model),
249            styles.sep(self.s),
250            usage_mod.cacheLine(self.s, cache),
251        }) catch "ctx";
252        const sep = styles.sep(self.s);
253        if (self.paused or self.phase == .pausing) {
254            return std.fmt.allocPrint(self.s, "{s}{s}{s}", .{ styles.comment(self.s, "paused - type steering, Enter to submit"), sep, info }) catch info;
255        }
256        if (self.active and self.pause_requested.load(.seq_cst)) {
257            return std.fmt.allocPrint(self.s, "{s}{s}{s}", .{ styles.comment(self.s, "pausing - waiting for the step boundary"), sep, info }) catch info;
258        }
259        if (self.retry) {
260            return std.fmt.allocPrint(self.s, "{s}{s}{s}", .{ styles.err(self.s, "failed - Enter to retry"), sep, info }) catch info;
261        }
262        if (!self.active or self.phase == .idle) return info;
263        var elapsed_buf: [32]u8 = undefined;
264        const elapsed = time.humanize(&elapsed_buf, time.nowMs() - self.turn_start);
265        return std.fmt.allocPrint(self.s, "{s} {s}{s}{s}{s}{s}", .{
266            styles.accent(self.s, spinnerChar(self.frame)),
267            self.stateLabel(),
268            sep,
269            styles.comment(self.s, elapsed),
270            sep,
271            info,
272        }) catch info;
273    }
274
275    fn stateLabel(self: *Tui) []const u8 {
276        const a = self.s;
277        if (self.retrying) |text| return styles.styledWith(a, styles.roles.warn, text);
278        var text: []const u8 = "idle";
279        var role: ?styles.Style = null;
280        var bytes: usize = 0;
281        switch (self.phase) {
282            .preparing => text = "preparing",
283            .waiting_model => text = "waiting for provider",
284            .snapshotting => {
285                text = "snapshotting";
286                role = styles.roles.warn;
287            },
288            .running_tool => {
289                text = std.fmt.allocPrint(a, "running tool call {s}", .{self.detail orelse "tool"}) catch "running tool call";
290                role = styles.roles.prompt;
291            },
292            .streaming => switch (self.stream_kind) {
293                .tool => {
294                    text = std.fmt.allocPrint(a, "writing tool call {s}", .{self.writing_tool orelse "tool"}) catch "writing tool call";
295                    role = styles.roles.prompt;
296                    bytes = self.writing_bytes;
297                },
298                .reasoning => {
299                    text = "reasoning";
300                    role = styles.roles.prompt;
301                    bytes = self.reasoning_bytes;
302                },
303                .text => {
304                    text = "writing response";
305                    role = styles.roles.prompt;
306                    bytes = self.text_bytes;
307                },
308                .none => text = "streaming",
309            },
310            else => {},
311        }
312        var out: std.ArrayList(u8) = .empty;
313        out.appendSlice(a, if (role) |r| styles.styledWith(a, r, text) else styles.comment(a, text)) catch {};
314        if (bytes > 0) {
315            const n = usage_mod.formatTokens(a, (bytes + 3) / 4);
316            out.appendSlice(a, styles.sep(a)) catch {};
317            out.appendSlice(a, styles.comment(a, std.fmt.allocPrint(a, "~{s} tok", .{n}) catch "")) catch {};
318        }
319        const queued = self.pending_calls.items.len -| @intFromBool(self.phase == .running_tool);
320        if (queued > 0) {
321            out.appendSlice(a, styles.sep(a)) catch {};
322            out.appendSlice(a, styles.comment(a, std.fmt.allocPrint(a, "{d} queued", .{queued}) catch "")) catch {};
323        }
324        return out.items;
325    }
326
327    fn spinnerChar(frame: usize) []const u8 {
328        var idx = frame % 256;
329        var i: usize = 0;
330        while (i < SPINNER.len) {
331            const n = std.unicode.utf8ByteSequenceLength(SPINNER[i]) catch 1;
332            if (idx == 0) return SPINNER[i .. i + n];
333            idx -= 1;
334            i += n;
335        }
336        return " ";
337    }
338
339    fn draw(self: *Tui) void {
340        if (self.closed) return;
341        self.resetScratch();
342        const width = @max(self.term.width(), 1);
343        const height = @max(self.term.height() - 1, 1);
344        const status_line = self.statusLine();
345        const status_rows = render.physicalRows(status_line, width);
346        const editor_budget = height -| status_rows;
347        const ed = self.editor.layout(width, @max(editor_budget, 1));
348
349        var lines: std.ArrayList([]const u8) = .empty;
350        lines.append(self.s, status_line) catch {};
351        var caret_line: usize = 0;
352        var caret_col: usize = 0;
353        if (self.picker) |*p| {
354            const prefix = std.fmt.allocPrint(self.s, "{s} › ", .{p.title}) catch "";
355            lines.append(self.s, std.fmt.allocPrint(self.s, "{s}{s}", .{
356                styles.styledWith(self.s, styles.over(.{ .bold = true }, styles.roles.prompt), prefix),
357                render.sanitize(self.s, p.query.items),
358            }) catch "> ") catch {};
359            caret_line = 1;
360            caret_col = render.displayWidth(prefix) + render.displayWidth(p.query.items);
361            if (p.matches.items.len == 0) {
362                lines.append(self.s, styles.comment(self.s, "  no matches")) catch {};
363            } else {
364                const budget = @max(height -| 2, 1);
365                const first = if (p.sel >= budget) p.sel + 1 - budget else 0;
366                const last = @min(p.matches.items.len, first + budget);
367                for (p.matches.items[first..last], first..) |idx, i| {
368                    const row = std.fmt.allocPrint(self.s, "{s}{s}", .{
369                        if (i == p.sel) "❯ " else "  ",
370                        render.sanitize(self.s, p.labels[idx]),
371                    }) catch p.labels[idx];
372                    lines.append(self.s, if (i == p.sel)
373                        styles.styledWith(self.s, styles.over(.{ .bold = true }, styles.roles.prompt), row)
374                    else
375                        styles.comment(self.s, row)) catch {};
376                }
377            }
378        } else {
379            for (ed.rows) |r| lines.append(self.s, r) catch {};
380            caret_line = 1 + ed.cursor_row;
381            caret_col = ed.cursor_col;
382        }
383
384        const frame_text = self.live.draw(self.s, width, lines.items, caret_line, caret_col, self.scrollback.buf.items);
385        self.term.write(frame_text);
386        self.scrollback.clear();
387        _ = self.sarena.reset(.retain_capacity);
388        self.sa = self.sarena.allocator();
389    }
390
391    fn keepName(self: *Tui, slot: *?[]const u8, value: ?[]const u8) void {
392        if (slot.*) |old| self.backing.free(old);
393        slot.* = if (value) |v| self.backing.dupe(u8, v) catch null else null;
394    }
395
396    fn handleAgentEvent(self: *Tui, event: agent.Event) void {
397        if (self.closed) return;
398        if (self.aborting) return;
399        self.resetScratch();
400        if (std.meta.activeTag(event) != .retry) self.keepName(&self.retrying, null);
401        switch (event) {
402            .retry => |r| {
403                const text = std.fmt.allocPrint(self.s, "retrying {d}/{d} in {d}s · {s}", .{
404                    r.attempt, r.total, @divFloor(r.delay_ms + 999, 1000), r.reason,
405                }) catch "";
406                self.keepName(&self.retrying, text);
407                status.report("working", null, r.reason);
408            },
409            .phase => |p| {
410                self.phase = p.phase;
411                self.keepName(&self.detail, p.detail);
412                if (p.phase == .pausing) self.paused = true;
413                if (p.phase == .waiting_model) {
414                    self.stream_kind = .none;
415                    self.text_bytes = 0;
416                    self.reasoning_bytes = 0;
417                }
418                status.report(switch (p.phase) {
419                    .preparing, .waiting_model, .streaming, .snapshotting, .running_tool => "working",
420                    .pausing => "blocked",
421                    .idle => "idle",
422                }, if (p.phase == .pausing) "question" else null, if (p.phase == .pausing) "paused - type steering to continue" else null);
423                if (p.phase == .pausing) status.notify("mini: paused, waiting for steering");
424            },
425            .text => |delta| {
426                self.stream_kind = .text;
427                self.text_bytes += delta.len;
428                self.streamed.appendSlice(self.a, delta) catch {};
429                self.commitLines(self.reply.feed(self.s, delta));
430            },
431            .reasoning => |delta| {
432                self.stream_kind = .reasoning;
433                self.reasoning_bytes += delta.len;
434            },
435            .tool_call => |tc| {
436                self.stream_kind = .none;
437                self.keepName(&self.writing_tool, null);
438                self.commitLines(self.reply.flush(self.s));
439                const summary = tool_view.callSummary(self.ca, tc.name, tc.arguments);
440                const display = if (std.mem.eql(u8, tc.name, "read") or std.mem.eql(u8, tc.name, "edit"))
441                    tool_view.relativize(self.opts.session.cwd, summary)
442                else
443                    summary;
444                self.pending_calls.append(self.a, .{
445                    .name = self.ca.dupe(u8, tc.name) catch "",
446                    .summary = display,
447                }) catch {};
448            },
449            .tool_call_start => |name| {
450                self.stream_kind = .tool;
451                self.keepName(&self.writing_tool, name);
452                self.writing_bytes = 0;
453            },
454            .tool_args => |n| self.writing_bytes = n,
455            .tool_output => {},
456            .message => |am| self.commitMessage(am),
457            .tool_result => |tr| self.commitToolResult(tr.name, tr.text, tr.is_error, tr.diffs, tr.body, tr.images),
458            .err => |m| {
459                status.report("error", null, m);
460                status.notify("mini: turn failed");
461                self.retry = true;
462                self.endTurn(styles.err(self.s, std.fmt.allocPrint(self.s, "! {s}", .{m}) catch "! error"));
463            },
464            .no_model => {
465                status.report("error", null, "no model configured");
466                self.endTurn(styles.err(self.s, "! no model configured"));
467            },
468            .cancelled => {
469                status.report("idle", null, null);
470                self.endTurn(styles.err(self.s, "! cancelled"));
471            },
472            .complete => {
473                status.report("done", null, null);
474                status.notify("mini: turn complete");
475                self.endTurn(styles.comment(self.s, self.doneLine()));
476            },
477        }
478        self.dirty = true;
479    }
480
481    fn doneLine(self: *Tui) []const u8 {
482        var elapsed_buf: [32]u8 = undefined;
483        const secs = time.humanize(&elapsed_buf, time.nowMs() - self.turn_start);
484        self.messages_mutex.lockUncancelable(platform.io);
485        const u = usage_mod.turnUsage(self.messages.items, self.turn_msgs);
486        self.messages_mutex.unlock(platform.io);
487        const prompt = u.input + u.cache_read + u.cache_write;
488        return std.fmt.allocPrint(self.s, "done · {s} · {s} in · {s} out", .{
489            secs,
490            usage_mod.formatTokens(self.s, prompt),
491            usage_mod.formatTokens(self.s, u.output),
492        }) catch "done";
493    }
494
495    fn endTurn(self: *Tui, line: []const u8) void {
496        self.phase = .idle;
497        self.keepName(&self.detail, null);
498        self.keepName(&self.writing_tool, null);
499        self.paused = false;
500        self.stream_kind = .none;
501        self.commitLines(self.reply.flush(self.s));
502        self.flushCalls();
503        self.note(line);
504    }
505
506    fn commitMessage(self: *Tui, am: *message_mod.AssistantMessage) void {
507        self.commitLines(self.reply.flush(self.s));
508        defer self.streamed.clearRetainingCapacity();
509        const text = am.text(self.s) catch return;
510        const trimmed = std.mem.trim(u8, text, " \t\r\n");
511        if (trimmed.len > 0 and std.mem.indexOf(u8, self.streamed.items, trimmed) == null) {
512            self.commitLines(self.reply.feed(self.s, trimmed));
513            self.commitLines(self.reply.flush(self.s));
514        }
515    }
516
517    fn beginToolBlock(self: *Tui) void {
518        if (!self.tool_block) self.scrollback.separator = true;
519        self.tool_block = true;
520    }
521
522    fn renderCall(self: *Tui, call: *PendingCall, meta: ?[]const u8) void {
523        self.beginToolBlock();
524        self.push(tool_view.callLine(self.s, call.name, call.summary, meta, @max(self.term.width(), 1)));
525    }
526
527    fn commitToolResult(self: *Tui, name: []const u8, text: []const u8, is_error: bool, diffs: []const tools_index.FileDiff, body: ?[]const u8, images: []const message_mod.ImageContent) void {
528        const shown = render.stripAnsi(self.s, text);
529        const has_head = self.pending_calls.items.len > 0;
530        const meta: ?[]const u8 = if (!is_error and has_head) body else null;
531        if (has_head) {
532            var call = self.pending_calls.orderedRemove(0);
533            self.renderCall(&call, meta);
534        } else {
535            self.beginToolBlock();
536        }
537        if (self.cfg.show_images) self.commitImages(images);
538        if (meta == null) {
539            const width = @max(self.term.width() - BODY_PREFIX.len, 1);
540            const is_bash = std.mem.eql(u8, name, "bash");
541            const bash_exit: ?[]const u8 = if (is_bash) tool_view.exitLine(self.s, shown) else null;
542            const result = tool_view.resultLines(self.s, name, shown, self.cfg.max_diff_lines);
543            const rows = if (std.mem.eql(u8, name, "edit")) render.plainRows(self.s, result.lines, styles.roles.output) else render.bodyRows(self.s, result.lines, width, styles.roles.output);
544            const mark_error = is_error and bash_exit == null;
545            for (rows, 0..) |row, i| {
546                const prefix = if (mark_error and i == rows.len - 1) styles.err(self.s, ERROR_PREFIX) else styles.comment(self.s, BODY_PREFIX);
547                self.push(std.fmt.allocPrint(self.s, "{s}{s}", .{ prefix, row }) catch row);
548            }
549            if (bash_exit) |status_line| self.push(status_line);
550            if (result.footer) |footer| self.push(footer);
551        }
552        for (diffs) |d| {
553            self.push(tool_view.diffHead(self.s, d.path));
554            const r = diff_view.diffBody(self.s, d, self.cfg.max_diff_lines);
555            for (render.plainRows(self.s, r.lines, styles.roles.output)) |row| {
556                self.push(std.fmt.allocPrint(self.s, "{s}{s}", .{ styles.comment(self.s, BODY_PREFIX), row }) catch row);
557            }
558            if (tool_view.diffFooter(self.s, r)) |footer| self.push(footer);
559        }
560    }
561
562    fn commitImages(self: *Tui, images: []const message_mod.ImageContent) void {
563        if (images.len == 0) return;
564        const width = @max(self.term.width(), 1);
565        const max_rows = @max(self.term.height() -| 2, 1);
566        const cell = self.term.cell();
567        const salt: u8 = @truncate(@as(u64, @bitCast(time.nowMs())));
568        for (images) |image| {
569            self.image_seq +%= 1;
570            const id = image_view.imageId(salt, self.image_seq);
571            if (image_view.block(self.s, id, image, width, max_rows, cell[0], cell[1])) |bytes| {
572                self.scrollback.pushRaw(bytes);
573            }
574        }
575    }
576
577    fn flushCalls(self: *Tui) void {
578        for (self.pending_calls.items) |*call| self.renderCall(call, null);
579        self.pending_calls.clearRetainingCapacity();
580        self.resetCalls();
581    }
582
583    fn resetCalls(self: *Tui) void {
584        _ = self.calls.reset(.retain_capacity);
585        self.ca = self.calls.allocator();
586    }
587
588    fn resetHistory(self: *Tui) void {
589        if (self.hist_index == null) return;
590        self.backing.free(self.hist_saved);
591        self.hist_saved = "";
592        self.hist_index = null;
593    }
594
595    fn historyWalk(self: *Tui, delta: isize) void {
596        const n = self.history.entries.items.len;
597        if (n == 0) return;
598        if (self.hist_index == null) {
599            self.hist_saved = self.backing.dupe(u8, self.editor.contents()) catch return;
600            self.hist_index = n;
601        }
602        const idx = @as(isize, @intCast(self.hist_index.?)) + delta;
603        if (idx < 0) return;
604        if (idx >= @as(isize, @intCast(n))) {
605            self.editor.setText(self.hist_saved);
606            self.resetHistory();
607            self.dirty = true;
608            return;
609        }
610        self.hist_index = @intCast(idx);
611        self.editor.setText(self.history.entries.items[@intCast(idx)]);
612        self.dirty = true;
613    }
614
615    fn openHistorySearch(self: *Tui) void {
616        self.resetHistory();
617        self.startPicker(.history, "history");
618        const p = &(self.picker orelse return);
619        const entries = self.history.entries.items;
620        const ids = self.picker_m.alloc([]const u8, entries.len) catch return;
621        const labels = self.picker_m.alloc([]const u8, entries.len) catch return;
622        for (entries, 0..) |e, i| {
623            ids[i] = e;
624            labels[i] = e[0 .. std.mem.indexOfScalar(u8, e, '\n') orelse e.len];
625        }
626        p.ids = ids;
627        p.labels = labels;
628        p.draft = self.picker_m.dupe(u8, self.editor.contents()) catch "";
629        self.editor.clear();
630        p.refresh(self.picker_m);
631        self.dirty = true;
632    }
633
634    fn handleKey(self: *Tui, key: input.Key) void {
635        self.resetScratch();
636        if (self.picker != null) {
637            self.pickerKey(key);
638            return;
639        }
640        if (key == .reverse_search) {
641            self.openHistorySearch();
642            return;
643        }
644        if (key == .history_prev) {
645            self.historyWalk(-1);
646            return;
647        }
648        if (key == .history_next) {
649            self.historyWalk(1);
650            return;
651        }
652        if (key == .eof) {
653            if (!self.active and !self.command_active and self.editor.contents().len == 0) self.exit();
654            return;
655        }
656        if (key == .interrupt) {
657            if (self.active) {
658                self.abort.store(true, .seq_cst);
659                self.steering_ready.store(true, .seq_cst);
660                self.steering_text = "";
661                if (!self.aborting) {
662                    self.aborting = true;
663                    status.report("idle", null, null);
664                    self.endTurn(styles.err(self.s, "! cancelled"));
665                }
666                self.dirty = true;
667            } else if (self.command_active) {
668                self.command_active = false;
669                self.closePicker();
670                self.model_abort.store(true, .seq_cst);
671                self.dirty = true;
672            } else if (self.editor.contents().len != 0) {
673                self.editor.clear();
674                self.dirty = true;
675            }
676            return;
677        }
678        if (key == .escape) {
679            if (self.active and !self.paused) {
680                self.pause_requested.store(true, .seq_cst);
681                self.dirty = true;
682            }
683            return;
684        }
685        if (key == .tab) {
686            if (commands.completeCommand(self.editor.contents())) |text| {
687                self.editor.setText(text);
688            } else {
689                _ = self.editor.completeWord(complete.completePath);
690            }
691            self.dirty = true;
692            return;
693        }
694        const result = self.editor.handle(key);
695        if (result == .submit) {
696            self.submit();
697        } else if (result == .changed) {
698            self.resetHistory();
699            self.dirty = true;
700        }
701    }
702
703    fn submit(self: *Tui) void {
704        self.resetHistory();
705        const text = self.a.dupe(u8, self.editor.contents()) catch return;
706        if (self.active) {
707            if (self.paused) {
708                self.editor.clear();
709                if (text.len > 0) self.commitUser(text);
710                self.steering_text = text;
711                self.steering_ready.store(true, .seq_cst);
712                self.dirty = true;
713            }
714            return;
715        }
716        if (self.command_active) return;
717        if (std.mem.trim(u8, text, " \t\r\n").len == 0) {
718            self.retryTurn();
719            return;
720        }
721        if (commands.findCommand(text)) |found| {
722            self.editor.clear();
723            self.runCommand(found);
724            self.dirty = true;
725            return;
726        }
727        self.editor.clear();
728        const message = message_mod.Message{ .user = .{ .content = self.a.dupe(u8, text) catch text, .timestamp = time.nowMs() } };
729        self.messages_mutex.lockUncancelable(platform.io);
730        self.messages.append(platform.gpa, message) catch {
731            self.messages_mutex.unlock(platform.io);
732            self.fail("! out of memory", .{});
733            return;
734        };
735        self.messages_mutex.unlock(platform.io);
736        self.opts.session.appendMessage(platform.gpa, message) catch |e| {
737            self.fail("! {s}", .{@errorName(e)});
738            return;
739        };
740        self.commitUser(text);
741        self.history.add(text);
742        self.startTurn();
743    }
744
745    fn retryTurn(self: *Tui) void {
746        if (!self.retry or self.active) return;
747        self.note(styles.comment(self.s, "retrying"));
748        self.startTurn();
749    }
750
751    fn startTurn(self: *Tui) void {
752        self.active = true;
753        self.retry = false;
754        self.abort.store(false, .seq_cst);
755        self.pause_requested.store(false, .seq_cst);
756        self.turn_done.store(false, .seq_cst);
757        self.phase = .preparing;
758        self.keepName(&self.detail, null);
759        self.keepName(&self.retrying, null);
760        self.turn_start = time.nowMs();
761        self.messages_mutex.lockUncancelable(platform.io);
762        self.turn_msgs = self.messages.items.len;
763        self.messages_mutex.unlock(platform.io);
764        self.frame = 0;
765        self.event_mutex.lockUncancelable(platform.io);
766        self.events.clearRetainingCapacity();
767        _ = self.qarena.reset(.retain_capacity);
768        self.q = self.qarena.allocator();
769        self.event_mutex.unlock(platform.io);
770        const t = std.Thread.spawn(.{}, turnThread, .{self}) catch return;
771        t.detach();
772        self.dirty = true;
773    }
774
775    fn runCommand(self: *Tui, command: Command) void {
776        switch (command) {
777            .help => self.showHelp(),
778            .new => {
779                self.newSession();
780                self.push("");
781                self.pushBanner();
782                self.note(styles.comment(self.s, "new session"));
783            },
784            .provider => self.startProviderSelect(),
785            .model => {
786                const m = self.opts.model orelse return self.fail("! no model configured", .{});
787                self.startModelFetch(m.provider);
788            },
789            .thinking => self.startThinkingSelect(),
790        }
791    }
792
793    fn startThinkingSelect(self: *Tui) void {
794        const m = self.opts.model orelse return self.fail("! no model configured", .{});
795        const levels = models_mod.supportedLevels(self.a, self.cfg, m.provider, m.id);
796        self.openPicker(.thinking, "thinking", levels, levels);
797    }
798
799    fn showHelp(self: *Tui) void {
800        const keys = [_][2][]const u8{
801            .{ "Enter", "submit; on an empty draft after a failure, retry it" },
802            .{ "Shift+Enter", "newline (Ctrl+J also works)" },
803            .{ "Shift+Up/Down", "walk input history (Ctrl+R to search)" },
804            .{ "Esc", "pause the turn at the next step boundary" },
805            .{ "Ctrl+C", "cancel the turn" },
806            .{ "Ctrl+D", "exit on an empty draft" },
807            .{ "Tab", "complete command or path" },
808        };
809        var width: usize = 0;
810        for (Command.all) |c| width = @max(width, c.wire().len + 1);
811        for (keys) |row| width = @max(width, row[0].len);
812        self.note("commands");
813        for (Command.all) |c| {
814            self.push(commands.helpRow(self.s, std.fmt.allocPrint(self.s, "/{s}", .{c.wire()}) catch c.wire(), c.summary(), width));
815        }
816        self.push("");
817        self.push("keybindings");
818        for (keys) |row| self.push(commands.helpRow(self.s, row[0], row[1], width));
819    }
820
821    fn newSession(self: *Tui) void {
822        self.opts.session.close();
823        const cwd = std.process.currentPathAlloc(platform.io, self.backing) catch ".";
824        self.opts.session.* = session_mod.Session.init(self.backing, self.cfg.sessions_dir, cwd);
825        self.messages_mutex.lockUncancelable(platform.io);
826        self.messages.clearRetainingCapacity();
827        self.messages_mutex.unlock(platform.io);
828        self.pending_calls.clearRetainingCapacity();
829        self.streamed.clearRetainingCapacity();
830        self.reply.reset();
831        self.keepName(&self.detail, null);
832        self.keepName(&self.writing_tool, null);
833        self.steering_text = "";
834        self.retry = false;
835        self.phase = .idle;
836        self.stream_kind = .none;
837        self.resetCalls();
838        self.dirty = true;
839    }
840
841    fn startProviderSelect(self: *Tui) void {
842        const entries = models_mod.providers(self.a, self.cfg);
843        var ids: std.ArrayList([]const u8) = .empty;
844        var names: std.ArrayList([]const u8) = .empty;
845        for (entries) |p| {
846            if (!p.ready) continue;
847            ids.append(self.a, p.id) catch {};
848            names.append(self.a, p.name) catch {};
849        }
850        if (ids.items.len == 0) {
851            self.fail("! no authenticated providers", .{});
852            return;
853        }
854        self.openPicker(.provider, "provider", ids.items, names.items);
855    }
856
857    fn startModelFetch(self: *Tui, provider_id: []const u8) void {
858        if (self.model_thread) |t| {
859            self.model_abort.store(true, .seq_cst);
860            t.join();
861            self.model_thread = null;
862        }
863        _ = self.model_arena.reset(.retain_capacity);
864        self.model_m = self.model_arena.allocator();
865        self.model_provider = provider_id;
866        self.model_entries = &.{};
867        self.model_abort.store(false, .seq_cst);
868        self.model_ok.store(false, .seq_cst);
869        self.model_ready.store(false, .seq_cst);
870        self.model_thread = std.Thread.spawn(.{}, modelFetchThread, .{self}) catch {
871            self.fail("! cannot query models", .{});
872            return;
873        };
874        self.command_active = true;
875        self.note(styles.comment(self.s, "querying models..."));
876        self.dirty = true;
877    }
878
879    fn modelFetchThread(self: *Tui) void {
880        if (models_mod.listing(self.model_m, self.cfg, self.model_provider, &self.model_abort)) |entries| {
881            self.model_entries = entries;
882            self.model_ok.store(true, .seq_cst);
883        } else |_| {
884            self.model_ok.store(false, .seq_cst);
885        }
886        self.model_ready.store(true, .release);
887    }
888
889    fn openModelsPrompt(self: *Tui) void {
890        if (self.model_entries.len == 0) {
891            self.command_active = false;
892            self.fail("! no models for provider", .{});
893            return;
894        }
895        var ids: std.ArrayList([]const u8) = .empty;
896        var names: std.ArrayList([]const u8) = .empty;
897        for (self.model_entries) |e| {
898            ids.append(self.a, e.id) catch {};
899            names.append(self.a, e.name) catch {};
900        }
901        self.openPicker(.model, "model", ids.items, names.items);
902        if (self.picker) |*p| p.provider = self.model_provider;
903    }
904
905    fn openPicker(self: *Tui, kind: picker_mod.Kind, title: []const u8, ids: []const []const u8, labels: []const []const u8) void {
906        self.startPicker(kind, title);
907        if (self.picker) |*p| {
908            p.ids = ids;
909            p.labels = labels;
910            p.refresh(self.picker_m);
911        }
912        self.dirty = true;
913    }
914
915    fn startPicker(self: *Tui, kind: picker_mod.Kind, title: []const u8) void {
916        _ = self.picker_arena.reset(.retain_capacity);
917        self.picker_m = self.picker_arena.allocator();
918        self.picker = .{ .kind = kind, .title = title };
919        self.command_active = true;
920    }
921
922    fn closePicker(self: *Tui) void {
923        self.picker = null;
924    }
925
926    fn pickerKey(self: *Tui, key: input.Key) void {
927        const p = &(self.picker orelse return);
928        switch (p.key(self.picker_m, key)) {
929            .ignore => return,
930            .update => {},
931            .accept => self.pickerAccept(),
932            .cancel => {
933                const draft = p.draft;
934                const restore = p.kind == .history;
935                self.closePicker();
936                self.command_active = false;
937                if (restore) self.editor.setText(draft);
938            },
939        }
940        self.dirty = true;
941    }
942
943    fn pickerAccept(self: *Tui) void {
944        const p = self.picker orelse return;
945        const id = p.current() orelse return;
946        const kind = p.kind;
947        const provider_id = p.provider;
948        self.closePicker();
949        self.command_active = false;
950        switch (kind) {
951            .provider => self.startModelFetch(id),
952            .model => {
953                var err: ?[]const u8 = null;
954                const m = models_mod.resolveNamed(self.a, self.cfg, provider_id, id, &err) orelse return;
955                const ptr = self.a.create(models_mod.Model) catch return;
956                ptr.* = m;
957                self.select(ptr);
958                config.save(self.a, self.cfg, .{ .provider = provider_id, .model = id }) catch {};
959                self.startThinkingSelect();
960            },
961            .thinking => {
962                const m = self.opts.model orelse return;
963                const updated = self.a.create(models_mod.Model) catch return;
964                updated.* = m.*;
965                updated.effort = models_mod.clampNamed(self.a, self.cfg, m.provider, m.id, id);
966                self.select(updated);
967                config.save(self.a, self.cfg, .{ .thinking_effort = id }) catch {};
968            },
969            .history => self.editor.setText(id),
970        }
971    }
972
973    fn select(self: *Tui, m: *const models_mod.Model) void {
974        self.opts.model = m;
975        self.opts.supports_images = m.supports_images;
976        self.opts.tools_json = tools_index.json(self.a, self.tool_names, self.opts.supports_images, self.opts.session.cwd);
977        self.pushBanner();
978        self.dirty = true;
979    }
980
981    fn isPauseRequested(ctx: *anyopaque) bool {
982        const self: *Tui = @ptrCast(@alignCast(ctx));
983        return self.pause_requested.load(.seq_cst);
984    }
985    fn clearPause(ctx: *anyopaque) void {
986        const self: *Tui = @ptrCast(@alignCast(ctx));
987        self.pause_requested.store(false, .seq_cst);
988    }
989    fn requestSteering(ctx: *anyopaque) []const u8 {
990        const self: *Tui = @ptrCast(@alignCast(ctx));
991        if (self.abort.load(.seq_cst)) return "";
992        self.paused = true;
993        self.dirty = true;
994        while (!self.steering_ready.load(.seq_cst)) {
995            if (self.abort.load(.seq_cst)) {
996                self.paused = false;
997                self.steering_ready.store(false, .seq_cst);
998                return "";
999            }
1000            std.Io.sleep(platform.io, .{ .nanoseconds = 10 * std.time.ns_per_ms }, .boot) catch {};
1001        }
1002        self.steering_ready.store(false, .seq_cst);
1003        self.paused = false;
1004        self.dirty = true;
1005        return self.steering_text;
1006    }
1007
1008    fn exit(self: *Tui) void {
1009        if (self.closed) return;
1010        self.closed = true;
1011        self.abort.store(true, .seq_cst);
1012        self.steering_ready.store(true, .seq_cst);
1013        self.model_abort.store(true, .seq_cst);
1014        if (self.model_thread) |t| {
1015            t.join();
1016            self.model_thread = null;
1017        }
1018        const width = @max(self.term.width(), 1);
1019        self.term.write(self.live.erase(self.a, width));
1020        self.term.write(self.scrollback.buf.items);
1021        self.term.stop();
1022        if (self.opts.session.file != null) {
1023            if (self.opts.session.id) |id|
1024                platform.writeOut(styles.comment(self.a, std.fmt.allocPrint(self.a, "resume with: mini --resume {s}\n", .{id}) catch ""));
1025        }
1026        self.opts.session.close();
1027        status.release();
1028    }
1029};
1030
1031fn inputThread(self: *Tui) void {
1032    var buf: [4096]u8 = undefined;
1033    const stdin = std.Io.File.stdin();
1034    while (!self.closed) {
1035        const n = stdin.readStreaming(platform.io, &.{buf[0..]}) catch break;
1036        if (n == 0) break;
1037        self.key_mutex.lockUncancelable(platform.io);
1038        self.input_bytes.appendSlice(platform.gpa, buf[0..n]) catch {};
1039        self.key_mutex.unlock(platform.io);
1040    }
1041    self.stdin_closed.store(true, .seq_cst);
1042}
1043
1044fn turnThread(self: *Tui) void {
1045    var o = self.opts.*;
1046    o.cancel = &self.abort;
1047    o.messages_mutex = &self.messages_mutex;
1048    agent.runTurn(o, &self.messages, .{
1049        .ctx = self,
1050        .is_pause_requested = Tui.isPauseRequested,
1051        .clear_pause = Tui.clearPause,
1052        .request_steering = Tui.requestSteering,
1053    }, .{ .ctx = self, .on_event = eventTrampoline });
1054    self.turn_done.store(true, .seq_cst);
1055}
1056
1057fn copyEvent(a: std.mem.Allocator, e: agent.Event, with_images: bool) agent.Event {
1058    return switch (e) {
1059        .phase => |p| .{ .phase = .{ .phase = p.phase, .detail = if (p.detail) |d| a.dupe(u8, d) catch "" else null } },
1060        .retry => |r| .{ .retry = .{
1061            .attempt = r.attempt,
1062            .total = r.total,
1063            .delay_ms = r.delay_ms,
1064            .reason = a.dupe(u8, r.reason) catch "",
1065        } },
1066        .text => |s| .{ .text = a.dupe(u8, s) catch "" },
1067        .reasoning => |s| .{ .reasoning = a.dupe(u8, s) catch "" },
1068        .tool_call_start => |s| .{ .tool_call_start = a.dupe(u8, s) catch "" },
1069        .tool_output => |s| .{ .tool_output = a.dupe(u8, s) catch "" },
1070        .err => |s| .{ .err = a.dupe(u8, s) catch "" },
1071        .tool_call => |tc| .{ .tool_call = .{
1072            .name = a.dupe(u8, tc.name) catch "",
1073            .arguments = a.dupe(u8, tc.arguments) catch "",
1074        } },
1075        .tool_result => |tr| blk: {
1076            var diffs: []const tools_index.FileDiff = &.{};
1077            if (a.alloc(tools_index.FileDiff, tr.diffs.len)) |buf| {
1078                for (tr.diffs, 0..) |d, i| buf[i] = .{
1079                    .path = a.dupe(u8, d.path) catch "",
1080                    .patch = if (d.patch) |p| a.dupe(u8, p) catch "" else null,
1081                    .note = if (d.note) |n| a.dupe(u8, n) catch "" else null,
1082                };
1083                diffs = buf;
1084            } else |_| {}
1085            var images: []const message_mod.ImageContent = &.{};
1086            if (with_images) {
1087                if (a.alloc(message_mod.ImageContent, tr.images.len)) |buf| {
1088                    for (tr.images, 0..) |img, i| buf[i] = .{
1089                        .data = a.dupe(u8, img.data) catch "",
1090                        .mime_type = a.dupe(u8, img.mime_type) catch "",
1091                    };
1092                    images = buf;
1093                } else |_| {}
1094            }
1095            break :blk .{ .tool_result = .{
1096                .name = a.dupe(u8, tr.name) catch "",
1097                .text = a.dupe(u8, tr.text) catch "",
1098                .is_error = tr.is_error,
1099                .diffs = diffs,
1100                .body = if (tr.body) |b| a.dupe(u8, b) catch "" else null,
1101                .images = images,
1102            } };
1103        },
1104        else => e,
1105    };
1106}
1107
1108fn eventTrampoline(ctx: *anyopaque, event: agent.Event) void {
1109    const self: *Tui = @ptrCast(@alignCast(ctx));
1110    switch (event) {
1111        .tool_output => return,
1112        else => {},
1113    }
1114    self.event_mutex.lockUncancelable(platform.io);
1115    self.events.append(platform.gpa, copyEvent(self.q, event, self.cfg.show_images)) catch {};
1116    self.event_mutex.unlock(platform.io);
1117}
1118
1119pub fn run(opts: agent.Options, cfg: *const config.Config, tool_names: []const config.ToolName, resumed: []const message_mod.Message) !void {
1120    const gpa = platform.gpa;
1121    const opts_ptr = try gpa.create(agent.Options);
1122    opts_ptr.* = opts;
1123    const self = try gpa.create(Tui);
1124    self.* = Tui.init(gpa, opts_ptr, cfg, tool_names);
1125    self.bindAllocators();
1126    self.history = history.Store.init(gpa, config.historyPath(gpa), cfg.history_size);
1127    status.init(cfg);
1128    styles.applyScheme(cfg.colorscheme);
1129
1130    self.term.start();
1131    defer self.term.stop();
1132    platform.onSignal(.WINCH, onWinch);
1133    for ([_]std.posix.SIG{ .TERM, .INT, .HUP, .QUIT }) |sig| platform.onSignal(sig, onExitSignal);
1134
1135    status.report("idle", null, null);
1136    self.pushBanner();
1137    if (resumed.len > 0) {
1138        self.messages.appendSlice(gpa, resumed) catch {};
1139        self.note(styles.comment(self.s, std.fmt.allocPrint(self.s, "resumed {s} · {d} messages", .{
1140            opts_ptr.session.id orelse "",
1141            resumed.len,
1142        }) catch "resumed"));
1143    }
1144    self.draw();
1145
1146    const stdin_thread = std.Thread.spawn(.{}, inputThread, .{self}) catch return;
1147    stdin_thread.detach();
1148
1149    while (!self.closed) {
1150        self.key_mutex.lockUncancelable(platform.io);
1151        std.mem.swap(std.ArrayList(u8), &self.input_bytes, &self.input_batch);
1152        self.key_mutex.unlock(platform.io);
1153        self.keys.clearRetainingCapacity();
1154        const keys = &self.keys;
1155        if (self.input_batch.items.len > 0) {
1156            self.parser.feed(platform.gpa, self.input_batch.items, keys);
1157            self.last_input_ms = time.nowMs();
1158        }
1159        self.input_batch.clearRetainingCapacity();
1160        const now_early = time.nowMs();
1161        switch (self.parser.pending()) {
1162            .escape => if (now_early - self.last_input_ms > 30) self.parser.flushEscape(platform.gpa, keys),
1163            .sequence => if (now_early - self.last_input_ms > 150) self.parser.flushSequence(),
1164            .none => {},
1165        }
1166        if (self.stdin_closed.load(.seq_cst) and !self.eof_sent) {
1167            keys.append(platform.gpa, .eof) catch {};
1168            self.eof_sent = true;
1169        }
1170        for (keys.items) |k| self.handleKey(k);
1171
1172        self.event_mutex.lockUncancelable(platform.io);
1173        std.mem.swap(std.ArrayList(agent.Event), &self.events, &self.batch);
1174        self.event_mutex.unlock(platform.io);
1175        for (self.batch.items) |e| self.handleAgentEvent(e);
1176        self.event_mutex.lockUncancelable(platform.io);
1177        self.batch.clearRetainingCapacity();
1178        if (self.events.items.len == 0) {
1179            _ = self.qarena.reset(.retain_capacity);
1180            self.q = self.qarena.allocator();
1181        }
1182        self.event_mutex.unlock(platform.io);
1183
1184        if (self.model_thread) |t| {
1185            if (self.model_ready.load(.acquire)) {
1186                t.join();
1187                self.model_thread = null;
1188                if (self.command_active) {
1189                    if (self.model_ok.load(.seq_cst)) {
1190                        self.openModelsPrompt();
1191                    } else {
1192                        self.command_active = false;
1193                        self.fail("! cannot load models", .{});
1194                    }
1195                }
1196                self.dirty = true;
1197            }
1198        }
1199
1200        if (self.turn_done.load(.seq_cst) and self.active) {
1201            self.active = false;
1202            self.paused = false;
1203            self.aborting = false;
1204            self.phase = .idle;
1205            self.dirty = true;
1206        }
1207
1208        if (resize_flag.swap(false, .seq_cst)) {
1209            self.term.refreshSize();
1210            self.dirty = true;
1211        }
1212        if (exit_flag.swap(false, .seq_cst)) self.exit();
1213
1214        const now = time.nowMs();
1215        if (self.active and now - self.last_frame_ms >= SPINNER_MS) {
1216            self.frame += 1;
1217            self.last_frame_ms = now;
1218            self.dirty = true;
1219        }
1220
1221        if (self.dirty) {
1222            self.draw();
1223            self.dirty = false;
1224        }
1225        std.Io.sleep(platform.io, .{ .nanoseconds = 8 * std.time.ns_per_ms }, .boot) catch {};
1226    }
1227    const sig = exit_signal.load(.seq_cst);
1228    if (sig != 0) platform.reRaise(@fromBackingInt(@intCast(sig)));
1229}