xonecas.io
7814
Ta

tiny-c-agent / files

tiny-c-agent / src / tui / tui.c

44.4 KB
1#include "tui.h"
2
3#include <errno.h>
4#include <limits.h>
5#include <poll.h>
6#include <pthread.h>
7#include <signal.h>
8#include <stdatomic.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12#include <sys/ioctl.h>
13#include <termios.h>
14#include <time.h>
15#include <unistd.h>
16
17#include <yyjson.h>
18
19#include "agent.h"
20#include "catalog.h"
21#include "commands.h"
22#include "complete.h"
23#include "editor.h"
24#include "highlight.h"
25#include "message.h"
26#include "resolve.h"
27#include "session.h"
28#include "stream.h"
29#include "term.h"
30#include "theme.h"
31#include "usage.h"
32#include "util.h"
33
34#define SPINNER_MS 120
35#define MAX_BODY_ROWS 12
36#define ELIDED_HEAD 4
37#define ELIDED_TAIL 4
38
39// The braille patterns in mini-coder's order: frame i is U+2800 + SPINNER[i].
40static const unsigned char SPINNER[] = {
41    0, 1, 2, 3, 4, 5, 6, 7, 64, 65, 66, 67, 68, 69, 70, 71,
42    8, 9, 10, 11, 12, 13, 14, 15, 72, 73, 74, 75, 76, 77, 78, 79,
43    16, 17, 18, 19, 20, 21, 22, 23, 80, 81, 82, 83, 84, 85, 86, 87,
44    24, 25, 26, 27, 28, 29, 30, 31, 88, 89, 90, 91, 92, 93, 94, 95,
45    32, 33, 34, 35, 36, 37, 38, 39, 96, 97, 98, 99, 100, 101, 102, 103,
46    40, 41, 42, 43, 44, 45, 46, 47, 104, 105, 106, 107, 108, 109, 110, 111,
47    48, 49, 50, 51, 52, 53, 54, 55, 112, 113, 114, 115, 116, 117, 118, 119,
48    56, 57, 58, 59, 60, 61, 62, 63, 120, 121, 122, 123, 124, 125, 126, 127,
49    128, 129, 130, 131, 132, 133, 134, 135, 192, 193, 194, 195, 196, 197, 198, 199,
50    136, 137, 138, 139, 140, 141, 142, 143, 200, 201, 202, 203, 204, 205, 206, 207,
51    144, 145, 146, 147, 148, 149, 150, 151, 208, 209, 210, 211, 212, 213, 214, 215,
52    152, 153, 154, 155, 156, 157, 158, 159, 216, 217, 218, 219, 220, 221, 222, 223,
53    160, 161, 162, 163, 164, 165, 166, 167, 224, 225, 226, 227, 228, 229, 230, 231,
54    168, 169, 170, 171, 172, 173, 174, 175, 232, 233, 234, 235, 236, 237, 238, 239,
55    176, 177, 178, 179, 180, 181, 182, 183, 240, 241, 242, 243, 244, 245, 246, 247,
56    184, 185, 186, 187, 188, 189, 190, 191, 248, 249, 250, 251, 252, 253, 254, 255,
57};
58
59static const char *const BODY_PREFIX = " | ";
60static const char *const ERROR_PREFIX = " ! ";
61
62static volatile sig_atomic_t g_exit;
63static volatile sig_atomic_t g_resize;
64
65static void on_signal(int sig) {
66    if (sig == SIGWINCH) g_resize = 1;
67    else g_exit = 1;
68}
69
70// ---- small helpers ---------------------------------------------------------
71
72static bool starts_with(const char *s, const char *prefix) {
73    return strncmp(s, prefix, strlen(prefix)) == 0;
74}
75
76// ---- tui state -------------------------------------------------------------
77
78typedef struct {
79    const tiny_tui_config *c;
80    tiny_model model;
81    tiny_agent agent;
82    tiny_session *session;
83
84    int in_fd;
85    int out_fd;
86    struct termios orig;
87    bool raw;
88    tiny_key_parser *parser;
89
90    int width;
91    int height;
92
93    tiny_editor *editor;
94    tiny_mdstream reply;
95    tiny_tailstream activity;
96    tiny_blist pending_calls;
97
98    tui_buf scroll;
99    bool wrote;
100    bool last_blank;
101    bool separator;
102
103    int live_rows;
104    int live_up;
105
106    // Deadlines for completing a held ESC or escape sequence, in monotonic
107    // seconds. Data arriving before a deadline replaces it.
108    bool esc_pending;
109    bool seq_pending;
110    double esc_deadline;
111    double seq_deadline;
112
113    bool active;
114    volatile bool cancel;
115    _Atomic bool pause_requested;
116    bool paused;
117    bool steering_waiting;
118    char *steering_text;
119    tiny_phase phase;
120    char *detail;
121    char *writing_tool;
122    long ctx_used;
123    long context_window;
124    struct timespec turn_start;
125    int frame;
126    char *streamed;
127    bool closed;
128
129    // A pending command choice: the next submitted line picks one of the
130    // numbered options. `choice_provider` carries the provider just chosen
131    // into the chained model list.
132    bool choice_active;
133    tiny_choose choice_kind;
134    char *choice_provider;
135    tiny_choice choice;
136
137    pthread_mutex_t lock;
138    pthread_cond_t cv;
139    pthread_t worker;
140    bool worker_live;
141} tui;
142
143static double elapsed(const tui *t) {
144    struct timespec now;
145    clock_gettime(CLOCK_MONOTONIC, &now);
146    double s = (double)(now.tv_sec - t->turn_start.tv_sec) +
147               (double)(now.tv_nsec - t->turn_start.tv_nsec) / 1e9;
148    return s < 0 ? 0 : s;
149}
150
151// Monotonic seconds, for key-parser deadlines.
152static double monotonic_now(void) {
153    struct timespec now;
154    clock_gettime(CLOCK_MONOTONIC, &now);
155    return (double)now.tv_sec + (double)now.tv_nsec / 1e9;
156}
157
158// ---- rendering -------------------------------------------------------------
159
160// Wraps plain text, then styles each row. Styling after the break lets a
161// continuation row inherit its source line's style.
162static tiny_strv render_rows(const tiny_body_line *lines, size_t n, int width) {
163    tiny_strv out = {0};
164    for (size_t i = 0; i < n; i++) {
165        char *clean = tiny_sanitize(lines[i].text);
166        char *expanded = tiny_expand_tabs(clean, 4);
167        tiny_strv rows = tiny_wrap_line(expanded, width);
168        free(clean);
169        free(expanded);
170        for (size_t r = 0; r < rows.n; r++) {
171            if (rows.v[r][0] == '\0') {
172                strv_push(&out, rows.v[r]);
173                continue;
174            }
175            tui_buf b;
176            buf_init(&b);
177            const char *bg = lines[i].bg ? lines[i].bg : tiny_normal_bg();
178            sgr_bg(&b, bg);
179            if (lines[i].style) lines[i].style(&b, rows.v[r]);
180            else buf_adds(&b, rows.v[r]);
181            sgr_bg(&b, bg);
182            strv_push(&out, buf_steal(&b));
183            free(rows.v[r]);
184        }
185        free(rows.v);
186    }
187    return out;
188}
189
190// render_rows plus the display-only elision for long tool bodies.
191static tiny_strv body_rows(const tiny_body_line *lines, size_t n, int width) {
192    tiny_strv rows = render_rows(lines, n, width);
193    if (rows.n <= MAX_BODY_ROWS) return rows;
194    size_t hidden = rows.n - ELIDED_HEAD - ELIDED_TAIL;
195    tiny_strv out = {0};
196    for (size_t i = 0; i < ELIDED_HEAD; i++) strv_push(&out, rows.v[i]);
197    tui_buf b;
198    buf_init(&b);
199    char note[64];
200    snprintf(note, sizeof note, "... %zu lines not shown ...", hidden);
201    fg_dim(&b, note);
202    strv_push(&out, buf_steal(&b));
203    for (size_t i = rows.n - ELIDED_TAIL; i < rows.n; i++) strv_push(&out, rows.v[i]);
204    free(rows.v);
205    return out;
206}
207
208static void append_painted(tui_buf *b, const char *row) {
209    sgr_plain(b);
210    buf_adds(b, row);
211    buf_adds(b, "\x1b[K");
212}
213
214// ---- scrollback ------------------------------------------------------------
215
216static void tui_render_locked(tui *t);
217
218static void push(tui *t, const char *row) {
219    bool blank = row[0] == '\0' || (t->separator && t->wrote);
220    t->separator = false;
221    if (blank && t->wrote && !t->last_blank) {
222        append_painted(&t->scroll, "");
223        buf_adds(&t->scroll, "\r\n");
224        t->last_blank = true;
225    }
226    if (row[0] != '\0') {
227        append_painted(&t->scroll, row);
228        buf_adds(&t->scroll, "\r\n");
229        t->wrote = true;
230        t->last_blank = false;
231    }
232}
233
234static void commit_lines(tui *t, const tiny_body_line *lines, size_t n) {
235    tiny_strv rows = render_rows(lines, n, t->width > 0 ? t->width : 1);
236    for (size_t i = 0; i < rows.n; i++) push(t, rows.v[i]);
237    strv_free(&rows);
238}
239
240static void commit_user(tui *t, const char *text) {
241    t->separator = true;
242    tiny_strv parts = tiny_split_lines(text);
243    tiny_body_line *lines = xmalloc(parts.n * sizeof *lines);
244    for (size_t i = 0; i < parts.n; i++)
245        lines[i] = (tiny_body_line){parts.v[i], fg_blue, NULL};
246    free(parts.v);
247    commit_lines(t, lines, parts.n);
248    for (size_t i = 0; i < parts.n; i++) free(lines[i].text);
249    free(lines);
250    t->separator = true;
251}
252
253// ---- tool result projection ------------------------------------------------
254
255static bool edit_header(const char *line) {
256    return starts_with(line, "Index: ") || starts_with(line, "--- ") ||
257           starts_with(line, "+++ ") ||
258           (starts_with(line, "===") && line[3] == '=');
259}
260
261static tiny_body_line diff_line(const char *line) {
262    if (starts_with(line, "@@")) return (tiny_body_line){xstrdup(line), fg_cyan, NULL};
263    if (starts_with(line, "+")) return (tiny_body_line){xstrdup(line), fg_green, tiny_diff_add()};
264    if (starts_with(line, "-")) return (tiny_body_line){xstrdup(line), fg_red, tiny_diff_delete()};
265    if (starts_with(line, "\\ No newline")) return (tiny_body_line){xstrdup(line), fg_dim, NULL};
266    if (starts_with(line, " ")) return (tiny_body_line){xstrdup(line), fg_dim, NULL};
267    return (tiny_body_line){xstrdup(line), NULL, NULL};
268}
269
270// Splits a tool result into its display lines, rewriting the trailing exit code
271// for bash and stripping the repeated diff header for edit.
272static tiny_blist result_lines(const char *name, const char *text, bool is_error) {
273    char *copy = tiny_trim_end(text);
274    tiny_strv raw = tiny_split_lines(copy);
275    size_t n = raw.n;
276
277    tiny_blist out = {0};
278    bool diff = false;
279    size_t start = 0;
280    if (strcmp(name, "bash") == 0 && n > 0) {
281        const char *last = raw.v[n - 1];
282        if (starts_with(last, "exit code: ")) {
283            const char *code = last + strlen("exit code: ");
284            n--;
285            if (is_error) {
286                tui_buf b;
287                buf_init(&b);
288                buf_adds(&b, "exit ");
289                buf_adds(&b, code);
290                char *tmp = buf_steal(&b);
291                bl_push(&out, xstrdup(tmp), fg_red, NULL);
292                free(tmp);
293            }
294        }
295    } else if (strcmp(name, "edit") == 0 && n > 0) {
296        if (starts_with(raw.v[0], "edited ") || starts_with(raw.v[0], "created ")) {
297            start = 1;
298            while (start < n && edit_header(raw.v[start])) start++;
299            diff = true;
300        }
301    }
302    for (size_t i = start; i < n; i++) {
303        if (diff) {
304            tiny_body_line bl = diff_line(raw.v[i]);
305            bl_push(&out, bl.text, bl.style, bl.bg);
306        } else {
307            bl_push(&out, xstrdup(raw.v[i]), NULL, NULL);
308        }
309    }
310    free(copy);
311    strv_free(&raw);
312    return out;
313}
314
315static tiny_blist diff_rows(const tiny_file_diff *diffs, size_t ndiffs) {
316    tiny_blist out = {0};
317    for (size_t d = 0; d < ndiffs; d++) {
318        bl_push(&out, xstrdup(diffs[d].path), fg_cyan, NULL);
319        if (diffs[d].patch) {
320            char *copy = tiny_trim_end(diffs[d].patch);
321            tiny_strv lines = tiny_split_lines(copy);
322            size_t start = 0;
323            while (start < lines.n && edit_header(lines.v[start])) start++;
324            for (size_t i = start; i < lines.n; i++) {
325                tiny_body_line bl = diff_line(lines.v[i]);
326                bl_push(&out, bl.text, bl.style, bl.bg);
327            }
328            strv_free(&lines);
329            free(copy);
330        } else if (diffs[d].note) {
331            bl_push(&out, xstrdup(diffs[d].note), fg_dim, NULL);
332        }
333    }
334    return out;
335}
336
337static void commit_tool_result(tui *t, const char *name, const char *text, bool is_error,
338                               const tiny_file_diff *diffs, size_t ndiffs) {
339    t->separator = true;
340    if (t->pending_calls.n > 0) {
341        tiny_body_line call = t->pending_calls.v[0];
342        memmove(t->pending_calls.v, t->pending_calls.v + 1, (t->pending_calls.n - 1) * sizeof *t->pending_calls.v);
343        t->pending_calls.n--;
344        commit_lines(t, &call, 1);
345        free(call.text);
346    }
347    int width = t->width - (int)strlen(BODY_PREFIX);
348    if (width < 1) width = 1;
349    tiny_blist lines = result_lines(name, text, is_error);
350    tiny_strv rows = (strcmp(name, "edit") == 0) ? render_rows(lines.v, lines.n, width)
351                                                 : body_rows(lines.v, lines.n, width);
352    tui_buf bodychrome;
353    buf_init(&bodychrome);
354    fg_dim(&bodychrome, BODY_PREFIX);
355    tui_buf errchrome;
356    buf_init(&errchrome);
357    fg_red(&errchrome, ERROR_PREFIX);
358    for (size_t i = 0; i < rows.n; i++) {
359        const char *prefix = (is_error && i == rows.n - 1) ? errchrome.data : bodychrome.data;
360        tui_buf row;
361        buf_init(&row);
362        buf_adds(&row, prefix);
363        buf_adds(&row, rows.v[i]);
364        if (row.data) push(t, row.data);
365        buf_free(&row);
366    }
367    strv_free(&rows);
368    buf_free(&bodychrome);
369    buf_free(&errchrome);
370    bl_free(&lines);
371
372    if (diffs && ndiffs > 0) {
373        tiny_blist dlines = diff_rows(diffs, ndiffs);
374        tiny_strv drows = render_rows(dlines.v, dlines.n, width);
375        tui_buf chrome;
376        buf_init(&chrome);
377        fg_dim(&chrome, BODY_PREFIX);
378        for (size_t i = 0; i < drows.n; i++) {
379            tui_buf row;
380            buf_init(&row);
381            buf_adds(&row, chrome.data);
382            buf_adds(&row, drows.v[i]);
383            if (row.data) push(t, row.data);
384            buf_free(&row);
385        }
386        buf_free(&chrome);
387        strv_free(&drows);
388        bl_free(&dlines);
389    }
390    t->separator = true;
391}
392
393static void flush_calls(tui *t) {
394    for (size_t i = 0; i < t->pending_calls.n; i++) {
395        t->separator = true;
396        commit_lines(t, &t->pending_calls.v[i], 1);
397    }
398    bl_free(&t->pending_calls);
399}
400
401// ---- call line -------------------------------------------------------------
402
403static char *call_summary(const char *name, const char *arguments) {
404    yyjson_doc *doc = yyjson_read(arguments ? arguments : "{}", arguments ? strlen(arguments) : 2, 0);
405    const char *key = (strcmp(name, "bash") == 0)  ? "command"
406                      : (strcmp(name, "edit") == 0 || strcmp(name, "read") == 0) ? "path"
407                                                                                 : NULL;
408    const char *value = NULL;
409    if (doc && key) {
410        yyjson_val *v = yyjson_obj_get(yyjson_doc_get_root(doc), key);
411        if (yyjson_is_str(v)) value = yyjson_get_str(v);
412    }
413    tui_buf b;
414    buf_init(&b);
415    if (value) {
416        // Newlines and tabs collapse to a single space.
417        for (const char *p = value; *p; p++) {
418            if (*p == '\n' || *p == '\t') {
419                if (b.len > 0 && b.data[b.len - 1] != ' ') buf_addc(&b, ' ');
420            } else {
421                buf_addc(&b, *p);
422            }
423        }
424    } else {
425        buf_adds(&b, arguments ? arguments : "");
426    }
427    if (doc) yyjson_doc_free(doc);
428    // trim
429    while (b.len > 0 && (b.data[b.len - 1] == ' ')) b.data[--b.len] = '\0';
430    return buf_steal(&b);
431}
432
433// ---- status ----------------------------------------------------------------
434
435static char *status_line(tui *t) {
436    char *usage = tiny_context_usage_line(t->ctx_used, t->context_window, t->model.max_tokens);
437    if (t->paused || t->phase == TINY_PHASE_PAUSING) {
438        tui_buf b;
439        buf_init(&b);
440        fg_dim(&b, "paused - type steering, Enter to submit");
441        buf_adds(&b, " · ");
442        buf_adds(&b, usage);
443        free(usage);
444        return buf_steal(&b);
445    }
446    if (!t->active || t->phase == TINY_PHASE_IDLE) return usage;
447
448    const char *label;
449    char buf[128];
450    switch (t->phase) {
451    case TINY_PHASE_PREPARING: label = "preparing"; break;
452    case TINY_PHASE_WAITING_MODEL: label = "waiting for provider"; break;
453    case TINY_PHASE_STREAMING:
454        if (t->writing_tool) {
455            snprintf(buf, sizeof buf, "writing %s", t->writing_tool);
456            label = buf;
457        } else {
458            label = "streaming";
459        }
460        break;
461    case TINY_PHASE_RUNNING_TOOL:
462        snprintf(buf, sizeof buf, "running %s", t->detail ? t->detail : "tool");
463        label = buf;
464        break;
465    default: label = "idle"; break;
466    }
467    tui_buf phase;
468    buf_init(&phase);
469    char spin[8];
470    int sn = tiny_utf8_encode(0x2800u + SPINNER[t->frame % (int)(sizeof SPINNER / sizeof SPINNER[0])], spin);
471    spin[sn] = '\0';
472    char text[192];
473    snprintf(text, sizeof text, "%s %s · %ds", spin, label, (int)elapsed(t));
474    fg_dim(&phase, text);
475
476    tui_buf out;
477    buf_init(&out);
478    buf_adds(&out, phase.data ? phase.data : "");
479    buf_adds(&out, " · ");
480    buf_adds(&out, usage);
481    buf_free(&phase);
482    free(usage);
483    return buf_steal(&out);
484}
485
486// ---- live region -----------------------------------------------------------
487
488static void live_clear(tui *t, tui_buf *out) {
489    if (t->live_rows == 0) return;
490    if (t->live_up > 0) buf_addf(out, "\x1b[%dB", t->live_up);
491    if (t->live_rows > 1) buf_addf(out, "\x1b[%dA", t->live_rows - 1);
492    buf_adds(out, "\r");
493    sgr_plain(out);
494    buf_adds(out, "\x1b[J");
495    t->live_rows = 0;
496    t->live_up = 0;
497}
498
499static void live_draw(tui *t, tui_buf *out, char **lines, size_t n, int cursor_row, int cursor_col,
500                      const char *above) {
501    live_clear(t, out);
502    buf_adds(out, above);
503    for (size_t i = 0; i < n; i++) {
504        if (i > 0) buf_adds(out, "\r\n");
505        buf_adds(out, lines[i]);
506    }
507    int up = (int)n - 1 - cursor_row;
508    if (up > 0) buf_addf(out, "\x1b[%dA", up);
509    buf_adds(out, "\r");
510    if (cursor_col > 0) buf_addf(out, "\x1b[%dG", cursor_col + 1);
511    t->live_rows = (int)n;
512    t->live_up = up;
513}
514
515static void tui_render_locked(tui *t) {
516    if (t->closed) return;
517    int width = t->width > 0 ? t->width : 80;
518    int height = (t->height > 1 ? t->height - 1 : 1);
519
520    char *status = status_line(t);
521    tiny_strv status_rows = tiny_wrap_line(status, width);
522    free(status);
523
524    tiny_blist infl = tiny_mdstream_pending(&t->reply);
525    if (infl.n == 0) {
526        bl_free(&infl);
527        infl = tiny_tailstream_pending(&t->activity);
528    }
529    tiny_strv rows = render_rows(infl.v, infl.n, width);
530    bl_free(&infl);
531
532    int keep = height - (int)status_rows.n - 1;
533    if (keep < 0) keep = 0;
534    if (keep > (int)rows.n) keep = (int)rows.n;
535    size_t body_start = rows.n - (size_t)keep;
536
537    int ed_max = height - (int)status_rows.n - keep;
538    if (ed_max < 1) ed_max = 1;
539    tiny_editor_view ev = tiny_editor_render(t->editor, width, ed_max);
540
541    size_t total = status_rows.n + (size_t)keep + ev.nrows;
542    char **lines = xmalloc((total ? total : 1) * sizeof *lines);
543    size_t k = 0;
544    for (size_t i = 0; i < (size_t)keep; i++) lines[k++] = rows.v[body_start + i];
545    for (size_t i = 0; i < status_rows.n; i++) lines[k++] = status_rows.v[i];
546    for (size_t i = 0; i < ev.nrows; i++) lines[k++] = ev.rows[i];
547
548    int cursor_row = (int)status_rows.n + keep + ev.cursor_row;
549    if (cursor_row >= (int)total) cursor_row = (int)total - 1;
550
551    // Every row is painted the same way; the live region adds no attributes.
552    for (size_t i = 0; i < total; i++) {
553        tui_buf painted;
554        buf_init(&painted);
555        append_painted(&painted, lines[i]);
556        free(lines[i]);
557        lines[i] = buf_steal(&painted);
558    }
559
560    char *scroll = buf_steal(&t->scroll);
561    bool reanchor = scroll[0] != '\0' && t->live_rows >= t->height - 1;
562    tui_buf above;
563    buf_init(&above);
564    buf_adds(&above, scroll);
565    if (reanchor) buf_adds(&above, "\r\n");
566
567    tui_buf frame;
568    buf_init(&frame);
569    live_draw(t, &frame, lines, total, cursor_row, ev.cursor_col, above.data ? above.data : "");
570    tiny_write_all(t->out_fd, frame.data, frame.len);
571    buf_free(&frame);
572    buf_free(&above);
573    free(scroll);
574
575    for (size_t i = 0; i < total; i++) free(lines[i]);
576    free(lines);
577    // The body rows past the kept tail, the status array, and the editor rows
578    // were all moved into `lines` and freed with it.
579    for (size_t i = 0; i < body_start; i++) free(rows.v[i]);
580    free(rows.v);
581    free(status_rows.v);
582    free(ev.rows);
583}
584
585// ---- events ----------------------------------------------------------------
586
587static void activity_reset(tui *t) {
588    tiny_tailstream_reset(&t->activity);
589}
590
591static void end_turn(tui *t, const char *line) {
592    t->phase = TINY_PHASE_IDLE;
593    free(t->detail);
594    t->detail = NULL;
595    free(t->writing_tool);
596    t->writing_tool = NULL;
597    t->paused = false;
598    activity_reset(t);
599    tiny_blist lines = tiny_mdstream_flush(&t->reply);
600    commit_lines(t, lines.v, lines.n);
601    bl_free(&lines);
602    flush_calls(t);
603    t->separator = true;
604    push(t, line);
605}
606
607// Ends the turn with one styled line.
608static void end_turn_styled(tui *t, tiny_fg_fn style, const char *text) {
609    tui_buf b;
610    buf_init(&b);
611    style(&b, text);
612    char *line = buf_steal(&b);
613    end_turn(t, line);
614    free(line);
615}
616
617// Extracts concatenated assistant text and total tokens from a message JSON.
618static void message_text_usage(const char *json, char **text_out, long *total_out) {
619    *text_out = NULL;
620    *total_out = -1;
621    yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
622    if (!doc) return;
623    yyjson_val *root = yyjson_doc_get_root(doc);
624    tui_buf b;
625    buf_init(&b);
626    yyjson_val *content = yyjson_obj_get(root, "content");
627    if (yyjson_is_arr(content)) {
628        size_t idx, max;
629        yyjson_val *block;
630        yyjson_arr_foreach(content, idx, max, block) {
631            yyjson_val *type = yyjson_obj_get(block, "type");
632            if (yyjson_is_str(type) && strcmp(yyjson_get_str(type), "text") == 0) {
633                yyjson_val *txt = yyjson_obj_get(block, "text");
634                if (yyjson_is_str(txt)) buf_adds(&b, yyjson_get_str(txt));
635            }
636        }
637    }
638    yyjson_val *usage = yyjson_obj_get(root, "usage");
639    if (yyjson_is_obj(usage)) {
640        yyjson_val *total = yyjson_obj_get(usage, "total");
641        if (yyjson_is_int(total)) *total_out = (long)yyjson_get_int(total);
642    }
643    yyjson_doc_free(doc);
644    *text_out = buf_steal(&b);
645}
646
647static void commit_message(tui *t, const char *json) {
648    activity_reset(t);
649    tiny_blist lines = tiny_mdstream_flush(&t->reply);
650    commit_lines(t, lines.v, lines.n);
651    bl_free(&lines);
652
653    char *text;
654    long total;
655    message_text_usage(json, &text, &total);
656    if (total >= 0) t->ctx_used = total;
657
658    // trimEnd for the contains check
659    size_t tl = strlen(text);
660    while (tl > 0 && (text[tl - 1] == '\n' || text[tl - 1] == '\r')) text[--tl] = '\0';
661    if (!tiny_is_blank(text) && !strstr(t->streamed, text)) {
662        tiny_blist fed = tiny_mdstream_feed(&t->reply, text);
663        commit_lines(t, fed.v, fed.n);
664        bl_free(&fed);
665        tiny_blist more = tiny_mdstream_flush(&t->reply);
666        commit_lines(t, more.v, more.n);
667        bl_free(&more);
668    }
669    free(text);
670    if (t->streamed) t->streamed[0] = '\0';
671}
672
673static void on_event(const tiny_event *e, void *user) {
674    tui *t = user;
675    if (t->closed) return;
676    pthread_mutex_lock(&t->lock);
677    switch (e->type) {
678    case TINY_EVENT_PHASE:
679        t->phase = e->u.phase.phase;
680        free(t->detail);
681        t->detail = e->u.phase.detail ? xstrdup(e->u.phase.detail) : NULL;
682        if (e->u.phase.phase == TINY_PHASE_PAUSING) t->paused = true;
683        break;
684    case TINY_EVENT_TEXT: {
685        activity_reset(t);
686        if (t->streamed) {
687            size_t a = strlen(t->streamed), b = strlen(e->u.text.delta);
688            t->streamed = realloc(t->streamed, a + b + 1);
689            if (!t->streamed) abort();
690            memcpy(t->streamed + a, e->u.text.delta, b + 1);
691        }
692        tiny_blist lines = tiny_mdstream_feed(&t->reply, e->u.text.delta);
693        commit_lines(t, lines.v, lines.n);
694        bl_free(&lines);
695        break;
696    }
697    case TINY_EVENT_REASONING: {
698        tiny_blist p = tiny_mdstream_pending(&t->reply);
699        bool empty = (p.n == 0);
700        bl_free(&p);
701        if (empty) tiny_tailstream_feed(&t->activity, e->u.reasoning.delta);
702        break;
703    }
704    case TINY_EVENT_TOOL_CALL_START:
705        free(t->writing_tool);
706        t->writing_tool = e->u.tool_call_start.name ? xstrdup(e->u.tool_call_start.name) : NULL;
707        break;
708    case TINY_EVENT_TOOL_CALL: {
709        free(t->writing_tool);
710        t->writing_tool = NULL;
711        tiny_blist lines = tiny_mdstream_flush(&t->reply);
712        commit_lines(t, lines.v, lines.n);
713        bl_free(&lines);
714        activity_reset(t);
715        tui_buf b;
716        buf_init(&b);
717        tui_buf head;
718        buf_init(&head);
719        char name[128];
720        snprintf(name, sizeof name, "-> %s", e->u.tool_call.name);
721        fg_teal(&head, name);
722        buf_adds(&b, head.data ? head.data : "");
723        buf_free(&head);
724        buf_adds(&b, "  ");
725        char *summary = call_summary(e->u.tool_call.name, e->u.tool_call.arguments);
726        buf_adds(&b, summary);
727        free(summary);
728        bl_push(&t->pending_calls, buf_steal(&b), NULL, NULL);
729        break;
730    }
731    case TINY_EVENT_TOOL_OUTPUT:
732        tiny_tailstream_feed(&t->activity, e->u.tool_output.chunk);
733        break;
734    case TINY_EVENT_TOOL_RESULT:
735        activity_reset(t);
736        commit_tool_result(t, e->u.tool_result.name, e->u.tool_result.text, e->u.tool_result.is_error,
737                           e->u.tool_result.diffs, e->u.tool_result.diffs_len);
738        break;
739    case TINY_EVENT_MESSAGE:
740        commit_message(t, e->u.message.json);
741        break;
742    case TINY_EVENT_ERROR: {
743        tui_buf p;
744        buf_init(&p);
745        buf_adds(&p, "! ");
746        buf_adds(&p, e->u.error.message);
747        end_turn_styled(t, fg_red, p.data ? p.data : "");
748        buf_free(&p);
749        break;
750    }
751    case TINY_EVENT_NO_MODEL:
752        end_turn_styled(t, fg_red, "! no model configured");
753        break;
754    case TINY_EVENT_CANCELLED:
755        end_turn_styled(t, fg_red, "! cancelled");
756        break;
757    case TINY_EVENT_COMPLETE: {
758        char text[64];
759        snprintf(text, sizeof text, "[complete · %ds]", (int)elapsed(t));
760        end_turn_styled(t, fg_dim, text);
761        break;
762    }
763    }
764    tui_render_locked(t);
765    pthread_mutex_unlock(&t->lock);
766}
767
768// ---- interruption callbacks ------------------------------------------------
769
770static bool is_pause_requested(void *user) {
771    tui *t = user;
772    return t->pause_requested;
773}
774
775static void clear_pause(void *user) {
776    tui *t = user;
777    t->pause_requested = false;
778}
779
780static char *request_steering(void *user) {
781    tui *t = user;
782    pthread_mutex_lock(&t->lock);
783    t->paused = true;
784    t->steering_waiting = true;
785    if (t->steering_text) {
786        free(t->steering_text);
787        t->steering_text = NULL;
788    }
789    tui_render_locked(t);
790    while (t->steering_waiting && !t->cancel && !t->closed) {
791        struct timespec ts;
792        clock_gettime(CLOCK_REALTIME, &ts);
793        ts.tv_nsec += 50 * 1000000L;
794        if (ts.tv_nsec >= 1000000000L) {
795            ts.tv_sec++;
796            ts.tv_nsec -= 1000000000L;
797        }
798        pthread_cond_timedwait(&t->cv, &t->lock, &ts);
799    }
800    char *s = t->steering_text;
801    t->steering_text = NULL;
802    t->steering_waiting = false;
803    t->paused = false;
804    tui_render_locked(t);
805    pthread_mutex_unlock(&t->lock);
806    return s ? s : xstrdup("");
807}
808
809// ---- command execution -----------------------------------------------------
810
811// Command callbacks run under the TUI lock, from `submit`.
812static void command_write(void *user, char *line) {
813    tui *t = user;
814    t->separator = true;
815    tiny_body_line bl = {line, NULL, NULL};
816    tiny_strv rows = render_rows(&bl, 1, t->width > 0 ? t->width : 1);
817    for (size_t i = 0; i < rows.n; i++) push(t, rows.v[i]);
818    strv_free(&rows);
819    t->separator = true;
820}
821
822static void command_new_session(void *user) {
823    tui *t = user;
824    if (t->session) tiny_session_close(t->session);
825    char title[256];
826    const char *base = strrchr(t->c->cwd, '/');
827    base = base ? base + 1 : t->c->cwd;
828    snprintf(title, sizeof title, "%s", base[0] ? base : "session");
829    char *err = NULL;
830    t->session = tiny_session_open(t->c->cfg->sessions_dir, t->c->cwd, title, &err);
831    free(err);
832    t->agent.session = t->session;
833    for (size_t i = 0; i < t->agent.messages_len; i++) tiny_message_free(&t->agent.messages[i]);
834    free(t->agent.messages);
835    t->agent.messages = NULL;
836    t->agent.messages_len = 0;
837    t->ctx_used = 0;
838}
839
840// The one-line model banner: "tiny · provider/model · effort".
841static char *model_line(tui *t) {
842    tui_buf b;
843    buf_init(&b);
844    buf_adds(&b, "tiny · ");
845    buf_adds(&b, t->model.provider ? t->model.provider : "no provider");
846    buf_addc(&b, '/');
847    buf_adds(&b, t->model.model ? t->model.model : "no model");
848    if (t->model.effort) {
849        buf_adds(&b, " · ");
850        buf_adds(&b, t->model.effort);
851    }
852    return buf_steal(&b);
853}
854
855static long window_for(const char *provider, const char *model) {
856    if (!provider || !model) return 0;
857    const tiny_model_info *info = tiny_catalog_lookup(tiny_provider_canonical(provider), model);
858    return info ? info->context_limit : 0;
859}
860
861// Switches the running session to a provider/model/effort, persists the change,
862// and repoints the agent's model. A NULL argument leaves that field unchanged.
863static int command_apply(void *user, const char *provider, const char *model,
864                         const char *effort, char **err) {
865    if (err) *err = NULL;
866    tui *t = user;
867    tiny_config *cfg = t->c->cfg;
868
869    const char *new_provider = provider ? provider : cfg->provider;
870    const char *new_model = model ? model : cfg->model;
871    const char *new_effort = effort ? effort : cfg->effort;
872
873    // Validate by resolving against a shallow copy before touching anything.
874    tiny_config probe = *cfg;
875    probe.provider = (char *)new_provider;
876    probe.model = (char *)new_model;
877    probe.effort = (char *)new_effort;
878    tiny_model resolved;
879    if (tiny_resolve_model(&probe, &resolved, err) != 0) return -1;
880
881    if (tiny_config_save(provider, model, effort, err) != 0) return -1;
882
883    if (provider) {
884        free(cfg->provider);
885        cfg->provider = xstrdup(provider);
886    }
887    if (model) {
888        free(cfg->model);
889        cfg->model = xstrdup(model);
890    }
891    if (effort) {
892        free(cfg->effort);
893        cfg->effort = xstrdup(effort);
894    }
895
896    if (tiny_resolve_model(cfg, &t->model, err) != 0) return -1;
897    t->agent.model = t->model;
898    t->context_window = window_for(cfg->provider, cfg->model);
899    t->agent.tools = tiny_tools(t->model.supports_images, &t->agent.tools_len);
900
901    char *line = model_line(t);
902    t->separator = true;
903    command_write(t, line);
904    return 0;
905}
906
907// Releases the pending choice and its options.
908static void free_choice(tui *t) {
909    tiny_choice_free(&t->choice);
910    free(t->choice_provider);
911    t->choice_provider = NULL;
912    t->choice_active = false;
913}
914
915// Commits one red line, for errors the choice flow reports.
916static void command_error(tui *t, const char *msg) {
917    t->separator = true;
918    tiny_body_line bl = {xstrdup(msg), fg_red, NULL};
919    commit_lines(t, &bl, 1);
920    free(bl.text);
921    t->separator = true;
922}
923
924// Presents the options for `what` as a numbered list and arms the choice.
925// `provider` overrides the config provider for a model list.
926static void start_choose(tui *t, tiny_choose what, const char *provider) {
927    free_choice(t);
928    tiny_choice options = tiny_choose_list(t->c->cfg, what, provider);
929    if (options.ids.n == 0) {
930        tiny_choice_free(&options);
931        const char *msg = what == TINY_CHOOSE_MODEL ? "! select a provider first"
932                          : what == TINY_CHOOSE_EFFORT ? "! no configurable effort for this model"
933                                                       : "! no providers configured";
934        command_error(t, msg);
935        return;
936    }
937    t->choice_active = true;
938    t->choice_kind = what;
939    t->choice_provider = provider ? xstrdup(provider) : NULL;
940    t->choice = options;
941
942    // The heading and options are one block, so no blank line separates them.
943    char *title = tiny_choose_title(t->c->cfg, what, provider);
944    tiny_blist lines = {0};
945    bl_push(&lines, title, NULL, NULL);
946    for (size_t i = 0; i < options.labels.n; i++) {
947        tui_buf b;
948        buf_init(&b);
949        buf_addf(&b, "  %zu. ", i + 1);
950        buf_adds(&b, options.labels.v[i]);
951        bl_push(&lines, buf_steal(&b), NULL, NULL);
952    }
953    t->separator = true;
954    commit_lines(t, lines.v, lines.n);
955    bl_free(&lines);
956    t->separator = true;
957}
958
959// Turns the submitted line into the pending choice: a 1-based index, an id, or
960// a label. An invalid line reports and clears the choice.
961static void resolve_choice(tui *t, const char *text) {
962    char *word = tiny_trim(text);
963
964    const char *chosen = NULL;
965    char *end = NULL;
966    long idx = strtol(word, &end, 10);
967    if (word[0] != '\0' && *end == '\0' && idx >= 1 && (size_t)idx <= t->choice.ids.n)
968        chosen = t->choice.ids.v[idx - 1];
969    if (!chosen) {
970        for (size_t i = 0; i < t->choice.ids.n; i++) {
971            if (strcmp(word, t->choice.ids.v[i]) == 0 ||
972                strcmp(word, t->choice.labels.v[i]) == 0) {
973                chosen = t->choice.ids.v[i];
974                break;
975            }
976        }
977    }
978    if (!chosen) {
979        size_t ml = strlen(word) + 32;
980        char *msg = xmalloc(ml);
981        snprintf(msg, ml, "! invalid selection: %s", word);
982        command_error(t, msg);
983        free(msg);
984        free(word);
985        free_choice(t);
986        return;
987    }
988
989    tiny_choose kind = t->choice_kind;
990    char *id = xstrdup(chosen);
991    char *provider = t->choice_provider ? xstrdup(t->choice_provider) : NULL;
992    free(word);
993    free_choice(t);
994
995    if (kind == TINY_CHOOSE_PROVIDER) {
996        start_choose(t, TINY_CHOOSE_MODEL, id);
997        free(id);
998        return;
999    }
1000
1001    char *err = NULL;
1002    int rc = kind == TINY_CHOOSE_MODEL
1003        ? command_apply(t, provider, id, NULL, &err)
1004        : command_apply(t, NULL, NULL, id, &err);
1005    if (rc != 0) {
1006        const char *detail = err ? err : "cannot apply the selection";
1007        size_t ml = strlen(detail) + 4;
1008        char *msg = xmalloc(ml);
1009        snprintf(msg, ml, "! %s", detail);
1010        command_error(t, msg);
1011        free(msg);
1012        free(err);
1013    }
1014    free(provider);
1015    free(id);
1016}
1017
1018static void command_choose(void *user, tiny_choose what) {
1019    start_choose(user, what, NULL);
1020}
1021
1022static void run_command(tui *t, const tiny_command *cmd, const char *args) {
1023    tiny_command_ctx ctx = {
1024        .user = t,
1025        .write = command_write,
1026        .new_session = command_new_session,
1027        .choose = command_choose,
1028        .cfg = t->c->cfg,
1029        .apply = command_apply,
1030    };
1031    cmd->run(&ctx, args);
1032}
1033
1034// ---- turns -----------------------------------------------------------------
1035
1036typedef struct {
1037    tui *t;
1038    char *text;
1039} turn_arg;
1040
1041static void *worker_main(void *arg) {
1042    turn_arg *a = arg;
1043    tui *t = a->t;
1044    char *text = a->text;
1045    free(a);
1046    tiny_agent_turn(&t->agent, text);
1047    free(text);
1048    pthread_mutex_lock(&t->lock);
1049    t->active = false;
1050    t->paused = false;
1051    t->pause_requested = false;
1052    free(t->streamed);
1053    t->streamed = NULL;
1054    tui_render_locked(t);
1055    pthread_mutex_unlock(&t->lock);
1056    return NULL;
1057}
1058
1059// The user message is appended to the transcript and session by the agent turn,
1060// which runs on `worker`. commit_user already displayed it.
1061static void start_turn(tui *t, const char *text) {
1062    t->active = true;
1063    t->cancel = false;
1064    t->pause_requested = false;
1065    t->paused = false;
1066    t->phase = TINY_PHASE_PREPARING;
1067    free(t->detail);
1068    t->detail = NULL;
1069    t->frame = 0;
1070    clock_gettime(CLOCK_MONOTONIC, &t->turn_start);
1071    free(t->streamed);
1072    t->streamed = xstrdup("");
1073
1074    turn_arg *a = xmalloc(sizeof *a);
1075    a->t = t;
1076    a->text = xstrdup(text);
1077    if (pthread_create(&t->worker, NULL, worker_main, a) != 0) {
1078        t->active = false;
1079        free(a->text);
1080        free(a);
1081    } else {
1082        t->worker_live = true;
1083    }
1084    tui_render_locked(t);
1085}
1086
1087// ---- input -----------------------------------------------------------------
1088
1089static void submit(tui *t) {
1090    const char *raw = tiny_editor_text(t->editor);
1091    char *text = xstrdup(raw);
1092    if (t->active) {
1093        if (t->paused && t->steering_waiting) {
1094            free(t->steering_text);
1095            t->steering_text = xstrdup(text);
1096            t->steering_waiting = false;
1097            pthread_cond_broadcast(&t->cv);
1098            tiny_editor_clear(t->editor);
1099            if (!tiny_is_blank(text)) commit_user(t, text);
1100            free(text);
1101            tui_render_locked(t);
1102            return;
1103        }
1104        free(text);
1105        return;
1106    }
1107    if (t->choice_active) {
1108        tiny_editor_clear(t->editor);
1109        resolve_choice(t, text);
1110        free(text);
1111        tui_render_locked(t);
1112        return;
1113    }
1114    if (tiny_is_blank(text)) {
1115        free(text);
1116        return;
1117    }
1118    const char *args = NULL;
1119    const tiny_command *cmd = tiny_find_command(text, &args);
1120    if (cmd) {
1121        tiny_editor_clear(t->editor);
1122        char *argcopy = xstrdup(args);
1123        run_command(t, cmd, argcopy);
1124        free(argcopy);
1125        free(text);
1126        tui_render_locked(t);
1127        return;
1128    }
1129    tiny_editor_clear(t->editor);
1130    commit_user(t, text);
1131    start_turn(t, text);
1132    free(text);
1133}
1134
1135// Tab completion for a path needs the cwd; a wrapper over the editor.
1136typedef struct {
1137    const char *cwd;
1138} complete_ctx;
1139
1140static char *complete_step(const char *word, void *user) {
1141    complete_ctx *c = user;
1142    return tiny_complete_path(word, c->cwd);
1143}
1144
1145static void handle_tab(tui *t) {
1146    const char *draft = tiny_editor_text(t->editor);
1147    char *completed = tiny_complete_command(draft);
1148    if (completed) {
1149        tiny_editor_set_text(t->editor, completed);
1150        free(completed);
1151        return;
1152    }
1153    complete_ctx cc = {t->c->cwd};
1154    tiny_editor_complete_word(t->editor, complete_step, &cc);
1155}
1156
1157static void handle_key(tui *t, const tiny_key *key) {
1158    pthread_mutex_lock(&t->lock);
1159    switch (key->type) {
1160    case TINY_KEY_EOF:
1161        if (!t->active && tiny_editor_text(t->editor)[0] == '\0') t->closed = true;
1162        break;
1163    case TINY_KEY_INTERRUPT:
1164        if (t->active) {
1165            t->cancel = true;
1166            pthread_cond_broadcast(&t->cv);
1167        } else if (t->choice_active) {
1168            free_choice(t);
1169            command_error(t, "! cancelled");
1170        } else if (tiny_editor_text(t->editor)[0] != '\0') {
1171            tiny_editor_clear(t->editor);
1172        }
1173        break;
1174    case TINY_KEY_ESCAPE:
1175        if (t->active && !t->paused) t->pause_requested = true;
1176        break;
1177    case TINY_KEY_TAB:
1178        handle_tab(t);
1179        break;
1180    default: {
1181        tiny_edit_result r = tiny_editor_handle(t->editor, key);
1182        if (r == TINY_EDIT_SUBMIT) submit(t);
1183        break;
1184    }
1185    }
1186    tui_render_locked(t);
1187    pthread_mutex_unlock(&t->lock);
1188}
1189
1190static void handle_key_cb(const tiny_key *key, void *user) {
1191    handle_key(user, key);
1192}
1193
1194// ---- lifecycle -------------------------------------------------------------
1195
1196static void get_size(tui *t) {
1197    struct winsize ws;
1198    if (ioctl(t->out_fd, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) {
1199        t->width = ws.ws_col;
1200        t->height = ws.ws_row > 0 ? ws.ws_row : 24;
1201    } else {
1202        t->width = 80;
1203        t->height = 24;
1204    }
1205}
1206
1207static void terminal_raw(tui *t) {
1208    if (tcgetattr(t->in_fd, &t->orig) != 0) return;
1209    struct termios raw = t->orig;
1210    cfmakeraw(&raw);
1211    if (tcsetattr(t->in_fd, TCSAFLUSH, &raw) == 0) t->raw = true;
1212}
1213
1214static void terminal_restore(tui *t) {
1215    if (t->raw) tcsetattr(t->in_fd, TCSAFLUSH, &t->orig);
1216}
1217
1218// Pushes one styled line into scrollback.
1219static void push_line(tui *t, char *text) {
1220    t->separator = true;
1221    tiny_body_line bl = {text, NULL, NULL};
1222    tiny_strv rows = render_rows(&bl, 1, t->width > 0 ? t->width : 80);
1223    for (size_t i = 0; i < rows.n; i++) push(t, rows.v[i]);
1224    strv_free(&rows);
1225    free(bl.text);
1226    t->separator = true;
1227}
1228
1229static void push_banner(tui *t) {
1230    push_line(t, model_line(t));
1231    const tiny_resources *r = t->c->resources;
1232    if (!r) return;
1233    for (size_t i = 0; i < r->agent_files_len; i++) {
1234        tui_buf b;
1235        buf_init(&b);
1236        buf_adds(&b, "agents · ");
1237        buf_adds(&b, r->agent_files[i].path);
1238        push_line(t, buf_steal(&b));
1239    }
1240    if (r->skills_len > 0) {
1241        tui_buf b;
1242        buf_init(&b);
1243        buf_adds(&b, "skills · ");
1244        for (size_t i = 0; i < r->skills_len; i++) {
1245            if (i > 0) buf_adds(&b, ", ");
1246            buf_adds(&b, r->skills[i].name);
1247        }
1248        push_line(t, buf_steal(&b));
1249    }
1250}
1251
1252int tiny_tui_run(const tiny_tui_config *c) {
1253    tui t;
1254    memset(&t, 0, sizeof t);
1255    t.c = c;
1256    t.in_fd = STDIN_FILENO;
1257    t.out_fd = STDOUT_FILENO;
1258    t.editor = tiny_editor_new();
1259    tiny_mdstream_init(&t.reply);
1260    tiny_tailstream_init(&t.activity);
1261    buf_init(&t.scroll);
1262    pthread_mutex_init(&t.lock, NULL);
1263    pthread_cond_init(&t.cv, NULL);
1264    t.parser = tiny_key_parser_new();
1265
1266    tiny_theme_use(c->cfg->theme);
1267
1268    t.model = c->model;
1269    t.context_window = window_for(c->model.provider, c->model.model);
1270
1271    get_size(&t);
1272
1273    char title[256];
1274    const char *base = strrchr(c->cwd, '/');
1275    base = base ? base + 1 : c->cwd;
1276    snprintf(title, sizeof title, "%s", base[0] ? base : "session");
1277    char *err = NULL;
1278    t.session = tiny_session_open(c->cfg->sessions_dir, c->cwd, title, &err);
1279    if (!t.session) {
1280        fprintf(stderr, "%s\n", err ? err : "session error");
1281        free(err);
1282        tiny_editor_free(t.editor);
1283        return 1;
1284    }
1285
1286    size_t tools_len;
1287    const tiny_tool *tools = tiny_tools(t.model.supports_images, &tools_len);
1288
1289    t.agent = (tiny_agent){
1290        .model = t.model,
1291        .system_prompt = c->resources ? c->resources->system_prompt : "",
1292        .tools = tools,
1293        .tools_len = tools_len,
1294        .session = t.session,
1295        .on_event = on_event,
1296        .user = &t,
1297        .is_pause_requested = is_pause_requested,
1298        .clear_pause = clear_pause,
1299        .request_steering = request_steering,
1300        .cancel = &t.cancel,
1301    };
1302
1303    struct sigaction sa;
1304    memset(&sa, 0, sizeof sa);
1305    sa.sa_handler = on_signal;
1306    sigaction(SIGWINCH, &sa, NULL);
1307    sigaction(SIGINT, &sa, NULL);
1308    sigaction(SIGTERM, &sa, NULL);
1309
1310    terminal_raw(&t);
1311    if (isatty(t.out_fd)) {
1312        const char *enable = "\x1b[?2004h\x1b[>1u\x1b[?u";
1313        tiny_write_all(t.out_fd, enable, strlen(enable));
1314    }
1315
1316    push_banner(&t);
1317    tui_render_locked(&t);
1318
1319    while (!t.closed && !g_exit) {
1320        int timeout = SPINNER_MS;
1321        double now = monotonic_now();
1322        if (t.esc_pending) {
1323            int ms = (int)((t.esc_deadline - now) * 1000.0);
1324            if (ms < timeout) timeout = ms;
1325        }
1326        if (t.seq_pending) {
1327            int ms = (int)((t.seq_deadline - now) * 1000.0);
1328            if (ms < timeout) timeout = ms;
1329        }
1330        if (timeout < 0) timeout = 0;
1331
1332        struct pollfd pfd = {.fd = t.in_fd, .events = POLLIN};
1333        int rc = poll(&pfd, 1, timeout);
1334        if (rc > 0 && (pfd.revents & POLLIN)) {
1335            char buf[4096];
1336            ssize_t n = read(t.in_fd, buf, sizeof buf);
1337            if (n > 0) {
1338                // New data supersedes any held ESC or sequence.
1339                t.esc_pending = false;
1340                t.seq_pending = false;
1341                tiny_key_parser_feed(t.parser, buf, (size_t)n, handle_key_cb, &t);
1342                int pend = tiny_key_parser_pending(t.parser);
1343                if (pend == 1) {
1344                    t.esc_pending = true;
1345                    t.esc_deadline = monotonic_now() + 0.030;
1346                } else if (pend == 2) {
1347                    t.seq_pending = true;
1348                    t.seq_deadline = monotonic_now() + 0.150;
1349                }
1350            } else if (n == 0) {
1351                t.closed = true;
1352            }
1353        }
1354        now = monotonic_now();
1355        if (t.esc_pending && now >= t.esc_deadline) {
1356            t.esc_pending = false;
1357            tiny_key_parser_flush_escape(t.parser, handle_key_cb, &t);
1358        }
1359        if (t.seq_pending && now >= t.seq_deadline) {
1360            t.seq_pending = false;
1361            tiny_key_parser_flush_sequence(t.parser);
1362        }
1363        pthread_mutex_lock(&t.lock);
1364        if (g_resize) {
1365            g_resize = 0;
1366            get_size(&t);
1367            tui_render_locked(&t);
1368        } else if (t.active) {
1369            t.frame++;
1370            tui_render_locked(&t);
1371        }
1372        pthread_mutex_unlock(&t.lock);
1373    }
1374
1375    pthread_mutex_lock(&t.lock);
1376    t.closed = true;
1377    t.cancel = true;
1378    pthread_cond_broadcast(&t.cv);
1379    pthread_mutex_unlock(&t.lock);
1380    if (t.worker_live) pthread_join(t.worker, NULL);
1381
1382    // Flush the live region and any pending scrollback.
1383    pthread_mutex_lock(&t.lock);
1384    tui_buf out;
1385    buf_init(&out);
1386    live_clear(&t, &out);
1387    if (t.scroll.data) buf_adds(&out, t.scroll.data);
1388    tiny_write_all(t.out_fd, out.data, out.len);
1389    buf_free(&out);
1390    buf_init(&t.scroll);
1391    pthread_mutex_unlock(&t.lock);
1392
1393    if (isatty(t.out_fd)) {
1394        const char *disable = "\x1b[<u\x1b[?2004l";
1395        tiny_write_all(t.out_fd, disable, strlen(disable));
1396    }
1397    terminal_restore(&t);
1398
1399    if (t.session) tiny_session_close(t.session);
1400    tiny_agent_free(&t.agent);
1401    tiny_editor_free(t.editor);
1402    tiny_mdstream_free(&t.reply);
1403    tiny_tailstream_free(&t.activity);
1404    bl_free(&t.pending_calls);
1405    free_choice(&t);
1406    free(t.detail);
1407    free(t.writing_tool);
1408    free(t.streamed);
1409    free(t.steering_text);
1410    buf_free(&t.scroll);
1411    tiny_key_parser_free(t.parser);
1412    pthread_mutex_destroy(&t.lock);
1413    pthread_cond_destroy(&t.cv);
1414    return 0;
1415}