Skip to content
pi-c Documentation
Login

Documentation

/* pic's terminal UI: the event loop, transcript, footer and commands.
 *
 * Output model: everything finished is committed once to the terminal's
 * scrollback (render.h); the live area at the bottom holds the reply being
 * streamed, a running tool call, the status line, queued messages, the
 * editor and the footer. A reply that fails mid-stream is only ever in the
 * live area, so dropping it leaves no trace. Requests run as a child
 * `pic --json ... ask` (stdin /dev/null, events on its stdout, notices on its
 * stderr); Esc sends it SIGINT, which pic turns into a clean cancel. */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#include "sqlite3.h"
#include "tui/editor.h"
#include "tui/fuzzy.h"
#include "tui/render.h"
#include "tui/term.h"
#include "tui/tui.h"
#include "tui/width.h"

#define DIM "\x1b[2m"
#define BOLD "\x1b[1m"
#define CYAN "\x1b[36m"
#define GREEN "\x1b[32m"
#define RED "\x1b[31m"
#define YELLOW "\x1b[33m"
#define RESET "\x1b[0m"
#define TOOL_PREVIEW_LINES 6
#define MAX_QUEUED 16

typedef struct {
    char *buf;
    size_t len, cap;
} text;

static int text_add(text *t, const char *s, size_t n) {
    if (t->len + n + 1 > t->cap) {
        size_t cap = t->cap ? t->cap : 256;
        char *grown;
        while (cap < t->len + n + 1) {
            cap *= 2;
        }
        if (!(grown = realloc(t->buf, cap))) {
            return -1;
        }
        t->buf = grown;
        t->cap = cap;
    }
    memcpy(t->buf + t->len, s, n);
    t->len += n;
    t->buf[t->len] = '\0';
    return 0;
}

static void text_clear(text *t) {
    t->len = 0;
    if (t->buf) {
        t->buf[0] = '\0';
    }
}

/* A child pic process: a request (events) or a short command (output). */
typedef struct {
    pid_t pid;
    int out, err; /* read ends; -1 once closed */
    text outbuf, errbuf;
} child;

typedef struct {
    const pic_tui_options *o;
    char model[160], conversation[64], name[128];
    long window;
    sqlite3 *db; /* in-memory, for reading JSON */
    sqlite3_stmt *get;
    tui_render *r;
    tui_editor *ed;
    tui_keys *keys;
    int cols, rows;
    /* the running request */
    child run;
    int working, interrupted, seen_end;
    text stream;          /* assistant text being streamed */
    text thinking;        /* its thinking, shown dimmed while it streams */
    size_t stream_off;    /* bytes of it already committed: always whole lines */
    int stream_fence;     /* inside a ``` block at stream_off */
    long stop_at;         /* the request was interrupted at this time (ms), 0: not */
    int stop_level;       /* signals sent so far: 1 SIGINT, 2 SIGTERM, 3 SIGKILL */
    char status[256];     /* retry / compaction notices */
    char tool[512];       /* the running tool call's header */
    int spin;
    /* tokens over this session of the UI */
    long long in, out, cache_read, cache_write, context;
    int expand_tools;
    char *queue[MAX_QUEUED];
    int nqueue;
    int ctrl_c_armed; /* a second Ctrl-C quits */
    /* /resume picker */
    char **pick_ids, **pick_rows;
    int npick, pick_at, picking;
    /* the model picker */
    char **mp_models, **mp_names, **mp_search;
    long *mp_window;
    size_t *mp_order, mp_n;
    int nmodels, mp_open, mp_sel;
    char mp_filter[128], default_model[160];
    child refresh; /* the background catalog refresh */
    int refreshing;
    /* the slash menu */
    int menu_sel;
    char menu_dismissed[512];
    char *last_reply; /* for /copy */
    int quit;
} app;

static volatile sig_atomic_t resized;
static volatile pid_t child_pid; /* the running request, for on_stop */
static int wake_pipe[2] = {-1, -1};

static long now_ms(void) {
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return (long)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}

static void on_winch(int sig) {
    (void)sig;
    resized = 1;
    if (wake_pipe[1] >= 0) {
        ssize_t n = write(wake_pipe[1], "w", 1);
        (void)n;
    }
}

/* Terminated, hung up or crashed: the terminal is put back, and a running
 * request is cancelled (pic finishes the cancel on its own; it ignores a
 * reader that went away). */
static void on_stop(int sig) {
    if (child_pid > 0) {
        (void)kill(child_pid, SIGINT);
    }
    tui_term_restore();
    (void)signal(sig, SIG_DFL);
    (void)raise(sig);
}

/* ---- JSON (through SQLite) -------------------------------------------- */

/* json_extract(doc, path) as a malloc'd string, or NULL. */
static char *jget(app *a, const char *doc, const char *path) {
    char *out = NULL;
    sqlite3_bind_text(a->get, 1, doc, -1, SQLITE_STATIC);
    sqlite3_bind_text(a->get, 2, path, -1, SQLITE_STATIC);
    if (sqlite3_step(a->get) == SQLITE_ROW && sqlite3_column_type(a->get, 0) != SQLITE_NULL) {
        const char *t = (const char *)sqlite3_column_text(a->get, 0);
        out = t ? strdup(t) : NULL;
    }
    sqlite3_reset(a->get);
    sqlite3_clear_bindings(a->get);
    return out;
}

static long long jnum(app *a, const char *doc, const char *path) {
    char *s = jget(a, doc, path);
    long long v = s ? strtoll(s, NULL, 10) : 0;
    free(s);
    return v;
}

/* ---- committing output ------------------------------------------------ */

static void commit_lines(app *a, tui_lines *l) {
    (void)tui_render_commit(a->r, (const char *const *)l->lines, l->n);
    tui_lines_clear(l);
}

/* Commits text wrapped to the width, each line prefixed with PREFIX (a
 * style, or ""). */
static void commit_text(app *a, const char *prefix, const char *s) {
    tui_lines l = {NULL, 0, 0}, out = {NULL, 0, 0};
    size_t cols = a->cols > 2 ? (size_t)a->cols : 2;
    if (tui_wrap(s, strlen(s), cols, &l) != 0) {
        return;
    }
    for (size_t i = 0; i < l.n; i++) {
        text t = {NULL, 0, 0};
        (void)text_add(&t, prefix, strlen(prefix));
        (void)text_add(&t, l.lines[i], strlen(l.lines[i]));
        if (*prefix) {
            (void)text_add(&t, RESET, strlen(RESET));
        }
        (void)tui_lines_add(&out, t.buf ? t.buf : "", t.len);
        free(t.buf);
    }
    tui_lines_clear(&l);
    commit_lines(a, &out);
}

static void notice(app *a, const char *style, const char *fmt, ...) {
    char msg[1024];
    va_list ap;
    va_start(ap, fmt);
    (void)vsnprintf(msg, sizeof msg, fmt, ap);
    va_end(ap);
    commit_text(a, style, msg);
}

/* Light markdown for one logical line: headings bold, fences and code dim
 * cyan, `code` cyan, **bold** bold, "- " bullets as "• ". */
static void md_line(const char *line, int *fence, text *out) {
    const char *p = line;
    if (strncmp(line, "```", 3) == 0) {
        *fence = !*fence;
        (void)text_add(out, DIM, strlen(DIM));
        (void)text_add(out, line, strlen(line));
        (void)text_add(out, RESET, strlen(RESET));
        return;
    }
    if (*fence) {
        (void)text_add(out, CYAN, strlen(CYAN));
        (void)text_add(out, line, strlen(line));
        (void)text_add(out, RESET, strlen(RESET));
        return;
    }
    if (*p == '#') {
        while (*p == '#') {
            p++;
        }
        while (*p == ' ') {
            p++;
        }
        (void)text_add(out, BOLD, strlen(BOLD));
        (void)text_add(out, p, strlen(p));
        (void)text_add(out, RESET, strlen(RESET));
        return;
    }
    {
        size_t lead = strspn(p, " ");
        if ((p[lead] == '-' || p[lead] == '*') && p[lead + 1] == ' ') {
            (void)text_add(out, p, lead);
            (void)text_add(out, "\xe2\x80\xa2 ", 4);
            p += lead + 2;
        }
    }
    for (int code = 0, bold = 0; *p; p++) {
        if (*p == '`') {
            code = !code;
            (void)text_add(out, code ? CYAN : RESET, strlen(code ? CYAN : RESET));
            if (!code && bold) {
                (void)text_add(out, BOLD, strlen(BOLD));
            }
        } else if (!code && p[0] == '*' && p[1] == '*') {
            bold = !bold;
            (void)text_add(out, bold ? BOLD : RESET, strlen(bold ? BOLD : RESET));
            p++;
        } else {
            (void)text_add(out, p, 1);
        }
        if (!p[1] && (code || bold)) {
            (void)text_add(out, RESET, strlen(RESET));
        }
    }
}

/* The uncommitted part of the streamed reply as styled, wrapped lines. */
static void stream_lines(app *a, tui_lines *out) {
    int fence = a->stream_fence;
    const char *s = a->stream.buf ? a->stream.buf + a->stream_off : "";
    size_t cols = a->cols > 1 ? (size_t)a->cols : 1;
    while (*s) {
        size_t n = strcspn(s, "\n");
        char *line = strndup(s, n);
        text styled = {NULL, 0, 0};
        if (line) {
            md_line(line, &fence, &styled);
            (void)tui_wrap(styled.buf ? styled.buf : "", styled.len, cols, out);
        }
        free(line);
        free(styled.buf);
        s += n;
        if (*s == '\n') {
            s++;
            if (!*s) {
                (void)tui_lines_add(out, "", 0);
            }
        }
    }
}

/* Commits the first uncommitted logical line of the reply (a finished one:
 * it ends in a newline). 0 when there is none yet. */
static int commit_head_line(app *a) {
    const char *s = a->stream.buf ? a->stream.buf + a->stream_off : "", *nl = strchr(s, '\n');
    char *line;
    text styled = {NULL, 0, 0};
    tui_lines l = {NULL, 0, 0};
    if (!nl) {
        return 0;
    }
    line = strndup(s, (size_t)(nl - s));
    if (line) {
        md_line(line, &a->stream_fence, &styled);
        (void)tui_wrap(styled.buf ? styled.buf : "", styled.len, a->cols > 1 ? (size_t)a->cols : 1, &l);
        commit_lines(a, &l);
    }
    free(line);
    free(styled.buf);
    a->stream_off += (size_t)(nl - s) + 1;
    return 1;
}

/* Commits what is left of the streamed reply and starts the next one. */
static void commit_stream(app *a) {
    tui_lines l = {NULL, 0, 0};
    if (a->stream.len) { /* kept for /copy */
        free(a->last_reply);
        a->last_reply = strdup(a->stream.buf);
    }
    stream_lines(a, &l);
    if (l.n) {
        commit_lines(a, &l);
    }
    tui_lines_clear(&l);
    text_clear(&a->stream);
    text_clear(&a->thinking);
    a->stream_off = 0;
    a->stream_fence = 0;
}

/* ---- the live area ---------------------------------------------------- */

static void fmt_tokens(long long n, char *out, size_t cap) {
    if (n >= 1000000) {
        (void)snprintf(out, cap, "%.1fM", (double)n / 1e6);
    } else if (n >= 1000) {
        (void)snprintf(out, cap, "%.1fk", (double)n / 1e3);
    } else {
        (void)snprintf(out, cap, "%lld", n);
    }
}

static void add_fit(tui_lines *l, const char *style, const char *s, int cols) {
    text t = {NULL, 0, 0};
    size_t fit = tui_fit(s, strlen(s), cols > 0 ? (size_t)cols : 1);
    (void)text_add(&t, style, strlen(style));
    (void)text_add(&t, s, fit);
    (void)text_add(&t, RESET, strlen(RESET));
    (void)tui_lines_add(l, t.buf, t.len);
    free(t.buf);
}

static void picker_lines(app *a, tui_lines *tail);
static void submit(app *a, char *msg);
static void pump_refresh(app *a);
static void models_free(app *a);
static void menu_lines(app *a, tui_lines *tail);

static void draw(app *a) {
    static const char *const frames[] = {"\xe2\xa0\x8b", "\xe2\xa0\x99", "\xe2\xa0\xb9", "\xe2\xa0\xb8", "\xe2\xa0\xbc",
                                         "\xe2\xa0\xb4", "\xe2\xa0\xa6", "\xe2\xa0\xa7", "\xe2\xa0\x87", "\xe2\xa0\x8f"};
    tui_lines live = {NULL, 0, 0}, tail = {NULL, 0, 0};
    int crow = -1, ccol = 0, budget;
    char line[1024], a1[16], a2[16], a3[16], a4[16];
    const char *home = getenv("HOME");
    const char *ws = a->o->workspace;
    /* Below the reply: status, queue, editor and its menu (or a picker), footer. */
    if (a->mp_open) {
        picker_lines(a, &tail);
    } else if (a->picking) {
        add_fit(&tail, BOLD, "Resume a conversation (up/down, enter, esc):", a->cols);
        for (int i = 0; i < a->npick && i < 12; i++) {
            int at = a->pick_at < 12 ? i : a->pick_at - 11 + i;
            if (at >= a->npick) {
                break;
            }
            (void)snprintf(line, sizeof line, "%s %s", at == a->pick_at ? ">" : " ", a->pick_rows[at]);
            add_fit(&tail, at == a->pick_at ? CYAN : "", line, a->cols);
        }
    } else {
        if (a->working) {
            (void)snprintf(line, sizeof line, "%s %s", frames[a->spin % 10],
                           a->interrupted ? "Stopping\xe2\x80\xa6" : a->status[0] ? a->status : "Working\xe2\x80\xa6 (esc to interrupt)");
            add_fit(&tail, a->status[0] ? YELLOW : DIM, line, a->cols);
        } else if (a->status[0]) {
            add_fit(&tail, YELLOW, a->status, a->cols);
        }
        for (int i = 0; i < a->nqueue; i++) {
            (void)snprintf(line, sizeof line, "queued: %s", a->queue[i]);
            add_fit(&tail, DIM, line, a->cols);
        }
        {
            size_t before = tail.n;
            int er = 0, ec = 0;
            if (tui_editor_render(a->ed, a->cols > 2 ? (size_t)a->cols : 2, &tail, &er, &ec) == 0) {
                crow = (int)before + er;
                ccol = ec;
            }
        }
        menu_lines(a, &tail);
    }
    /* footer: where, which conversation; tokens, context, model */
    if (home && *home && strncmp(ws, home, strlen(home)) == 0 && (ws[strlen(home)] == '/' || !ws[strlen(home)])) {
        (void)snprintf(line, sizeof line, "~%s  %s", ws + strlen(home),
                       a->name[0] ? a->name : a->conversation[0] ? a->conversation : "new conversation");
    } else {
        (void)snprintf(line, sizeof line, "%s  %s", ws, a->name[0] ? a->name : a->conversation[0] ? a->conversation : "new conversation");
    }
    add_fit(&tail, DIM, line, a->cols);
    fmt_tokens(a->in, a1, sizeof a1);
    fmt_tokens(a->out, a2, sizeof a2);
    fmt_tokens(a->context, a3, sizeof a3);
    fmt_tokens(a->window, a4, sizeof a4);
    if (a->window > 0) {
        (void)snprintf(line, sizeof line, "\xe2\x86\x91%s \xe2\x86\x93%s  %.1f%%/%s  %s%s", a1, a2,
                       100.0 * (double)a->context / (double)a->window, a4, a->model,
                       a->expand_tools ? "  (tool output expanded)" : "");
    } else {
        (void)snprintf(line, sizeof line, "\xe2\x86\x91%s \xe2\x86\x93%s  %s  %s%s", a1, a2, a3, a->model,
                       a->expand_tools ? "  (tool output expanded)" : "");
    }
    add_fit(&tail, DIM, line, a->cols);
    /* Above: the reply being written. When it no longer fits, its finished
     * lines (ending in a newline) go to the scrollback for good. */
    budget = a->rows - 1 - (int)tail.n - 1;
    if (budget < 2) {
        budget = 2;
    }
    if (a->stream.len || a->thinking.len || a->tool[0]) {
        tui_lines s = {NULL, 0, 0};
        if (a->stream.len) {
            stream_lines(a, &s);
            while ((int)s.n > budget && commit_head_line(a)) {
                tui_lines_clear(&s);
                stream_lines(a, &s);
            }
        } else if (a->thinking.len) {
            const char *t = a->thinking.buf, *last = strrchr(t, '\n');
            add_fit(&s, DIM, last && last[1] ? last + 1 : t, a->cols);
        }
        for (size_t i = 0; i < s.n; i++) {
            (void)tui_lines_add(&live, s.lines[i], strlen(s.lines[i]));
        }
        tui_lines_clear(&s);
        if (a->tool[0]) {
            add_fit(&live, CYAN, a->tool, a->cols);
        }
        (void)tui_lines_add(&live, "", 0);
    }
    if (crow >= 0) {
        crow += (int)live.n;
    }
    for (size_t i = 0; i < tail.n; i++) {
        (void)tui_lines_add(&live, tail.lines[i], strlen(tail.lines[i]));
    }
    (void)tui_render_draw(a->r, (const char *const *)live.lines, live.n, crow, ccol, a->rows);
    tui_lines_clear(&live);
    tui_lines_clear(&tail);
}

/* ---- child processes -------------------------------------------------- */

/* argv for this pic with the journal, workspace and model, then ARGS. */
static int spawn(app *a, child *c, const char *const *args) {
    const char *argv[32];
    char exec_s[16], window_s[24];
    int n = 0, out[2], err[2];
    argv[n++] = a->o->self;
    argv[n++] = "--db";
    argv[n++] = a->o->db;
    argv[n++] = "--workspace";
    argv[n++] = a->o->workspace;
    argv[n++] = "--model";
    argv[n++] = a->model;
    (void)snprintf(exec_s, sizeof exec_s, "%d", a->o->exec_seconds);
    argv[n++] = "--exec-timeout";
    argv[n++] = exec_s;
    if (a->o->context_window >= 0) {
        (void)snprintf(window_s, sizeof window_s, "%ld", a->o->context_window);
        argv[n++] = "--context-window";
        argv[n++] = window_s;
    }
    for (; *args && n < 31; args++) {
        argv[n++] = *args;
    }
    argv[n] = NULL;
    memset(c, 0, sizeof *c);
    c->out = c->err = -1;
    if (pipe(out) != 0) {
        return -1;
    }
    if (pipe(err) != 0) {
        close(out[0]);
        close(out[1]);
        return -1;
    }
    /* Our ends must not leak into later children. */
    (void)fcntl(out[0], F_SETFD, FD_CLOEXEC);
    (void)fcntl(err[0], F_SETFD, FD_CLOEXEC);
    c->pid = fork();
    if (c->pid == 0) {
        int null = open("/dev/null", O_RDONLY);
        /* Its own session: no controlling terminal, so nothing it runs can
         * read the keyboard from under the interface. */
        (void)setsid();
        if (null >= 0) {
            (void)dup2(null, STDIN_FILENO);
        }
        (void)dup2(out[1], STDOUT_FILENO);
        (void)dup2(err[1], STDERR_FILENO);
        close(out[0]);
        close(out[1]);
        close(err[0]);
        close(err[1]);
        (void)signal(SIGINT, SIG_DFL);
        (void)signal(SIGPIPE, SIG_DFL);
        execv(a->o->self, (char *const *)(void *)argv);
        _exit(127);
    }
    close(out[1]);
    close(err[1]);
    if (c->pid < 0) {
        close(out[0]);
        close(err[0]);
        return -1;
    }
    c->out = out[0];
    c->err = err[0];
    (void)fcntl(c->out, F_SETFL, fcntl(c->out, F_GETFL) | O_NONBLOCK);
    (void)fcntl(c->err, F_SETFL, fcntl(c->err, F_GETFL) | O_NONBLOCK);
    return 0;
}

/* Reads what is available; 1 when both pipes are closed. */
static int drain(child *c) {
    int fds[2] = {c->out, c->err};
    text *bufs[2] = {&c->outbuf, &c->errbuf};
    for (int i = 0; i < 2; i++) {
        char buf[8192];
        ssize_t n;
        while (fds[i] >= 0 && (n = read(fds[i], buf, sizeof buf)) != 0) {
            if (n < 0) {
                if (errno == EINTR) {
                    continue;
                }
                break; /* EAGAIN: later */
            }
            (void)text_add(bufs[i], buf, (size_t)n);
        }
        if (fds[i] >= 0 && n == 0) {
            close(fds[i]);
            fds[i] = -1;
        }
    }
    c->out = fds[0];
    c->err = fds[1];
    return c->out < 0 && c->err < 0;
}

/* Runs pic with ARGS to the end; its stdout in *out (malloc'd). The exit
 * status, or -1. Stderr lines are shown as notices. */
static int run_sync(app *a, const char *const *args, char **out) {
    child c;
    int status = 0;
    *out = NULL;
    if (spawn(a, &c, args) != 0) {
        return -1;
    }
    while (!drain(&c)) {
        struct pollfd p[2] = {{c.out, POLLIN, 0}, {c.err, POLLIN, 0}};
        (void)poll(p, 2, 100);
    }
    while (waitpid(c.pid, &status, 0) < 0 && errno == EINTR) {
    }
    if (c.errbuf.len) {
        notice(a, RED, "%.*s", (int)strcspn(c.errbuf.buf, "\n"), c.errbuf.buf);
    }
    free(c.errbuf.buf);
    *out = c.outbuf.buf ? c.outbuf.buf : strdup("");
    return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}

/* ---- requests and their events ----------------------------------------- */

static void start_request(app *a, const char *msg) {
    const char *args[6];
    int n = 0;
    args[n++] = "--json";
    args[n++] = "ask";
    if (a->conversation[0]) {
        args[n++] = "--session";
        args[n++] = a->conversation;
    }
    args[n++] = msg;
    args[n] = NULL;
    notice(a, BOLD, "> %s", msg);
    if (spawn(a, &a->run, args) != 0) {
        notice(a, RED, "pic: could not start the request: %s", strerror(errno));
        return;
    }
    child_pid = a->run.pid;
    a->working = 1;
    a->interrupted = a->seen_end = 0;
    a->status[0] = a->tool[0] = '\0';
}

static void show_tool_end(app *a, const char *ev) {
    char *name = jget(a, ev, "$.toolName"), *result = jget(a, ev, "$.result.content[0].text");
    int err = (int)jnum(a, ev, "$.isError");
    const char *r = result ? result : "";
    size_t lines = 0;
    text preview = {NULL, 0, 0};
    for (const char *p = r; *p; p++) {
        lines += *p == '\n';
    }
    lines += *r && r[strlen(r) - 1] != '\n';
    notice(a, err ? RED : GREEN, "%s %s", err ? "\xe2\x9c\x97" : "\xe2\x9c\x93", a->tool[0] ? a->tool : name ? name : "tool");
    if (a->expand_tools || lines <= TOOL_PREVIEW_LINES) {
        (void)text_add(&preview, r, strlen(r));
    } else {
        const char *p = r;
        for (int i = 0; i < TOOL_PREVIEW_LINES && *p; i++) {
            size_t n = strcspn(p, "\n");
            (void)text_add(&preview, p, n + (p[n] == '\n'));
            p += n + (p[n] == '\n');
        }
        {
            char more[96];
            (void)snprintf(more, sizeof more, "\xe2\x80\xa6 +%zu lines (ctrl+o expands later results)",
                           lines - TOOL_PREVIEW_LINES);
            (void)text_add(&preview, more, strlen(more));
        }
    }
    if (preview.len) {
        commit_text(a, DIM, preview.buf);
    }
    free(preview.buf);
    free(name);
    free(result);
    a->tool[0] = '\0';
}

static void on_event(app *a, const char *ev) {
    char *type = jget(a, ev, "$.type");
    if (!type) {
        return;
    }
    if (strcmp(type, "agent_start") == 0) {
        char *conv = jget(a, ev, "$.conversation"), *model = jget(a, ev, "$.model");
        if (conv) {
            (void)snprintf(a->conversation, sizeof a->conversation, "%s", conv);
        }
        if (model && *model) {
            (void)snprintf(a->model, sizeof a->model, "%s", model);
        }
        a->window = jnum(a, ev, "$.contextWindow");
        free(conv);
        free(model);
    } else if (strcmp(type, "message_update") == 0) {
        char *kind = jget(a, ev, "$.assistantMessageEvent.type"), *delta = jget(a, ev, "$.assistantMessageEvent.delta");
        if (kind && delta && strcmp(kind, "text_delta") == 0) {
            (void)text_add(&a->stream, delta, strlen(delta));
        } else if (kind && delta && strcmp(kind, "thinking_delta") == 0) {
            (void)text_add(&a->thinking, delta, strlen(delta));
        }
        free(kind);
        free(delta);
    } else if (strcmp(type, "message_end") == 0) {
        char *role = jget(a, ev, "$.message.role"), *stop = jget(a, ev, "$.message.stopReason");
        if (role && strcmp(role, "assistant") == 0) {
            if (stop && strcmp(stop, "error") == 0) {
                char *err = jget(a, ev, "$.message.errorMessage");
                /* The partial reply is dropped. A long one may have had finished
                 * lines committed already; say so rather than leave them unexplained. */
                if (a->stream_off > 0) {
                    notice(a, YELLOW, "(the reply above was cut off; it is requested again)");
                }
                text_clear(&a->stream);
                text_clear(&a->thinking);
                a->stream_off = 0;
                a->stream_fence = 0;
                (void)snprintf(a->status, sizeof a->status, "reply failed: %s", err ? err : "error");
                free(err);
            } else {
                long long in = jnum(a, ev, "$.message.usage.input"), out = jnum(a, ev, "$.message.usage.output"),
                          cr = jnum(a, ev, "$.message.usage.cacheRead"), cw = jnum(a, ev, "$.message.usage.cacheWrite");
                a->in += in;
                a->out += out;
                a->cache_read += cr;
                a->cache_write += cw;
                if (in + cr + cw + out > 0) {
                    a->context = in + cr + cw + out;
                }
                commit_stream(a);
                a->status[0] = '\0';
            }
        }
        free(role);
        free(stop);
    } else if (strcmp(type, "auto_retry_start") == 0) {
        char *err = jget(a, ev, "$.errorMessage");
        (void)snprintf(a->status, sizeof a->status, "Retrying (%lld/%lld): %s", jnum(a, ev, "$.attempt"),
                       jnum(a, ev, "$.maxAttempts"), err ? err : "");
        free(err);
    } else if (strcmp(type, "tool_execution_start") == 0) {
        char *name = jget(a, ev, "$.toolName"), *cmd = jget(a, ev, "$.args.command"), *path = jget(a, ev, "$.args.path");
        commit_stream(a);
        (void)snprintf(a->tool, sizeof a->tool, "%s %s", name ? name : "tool", cmd ? cmd : path ? path : "");
        free(name);
        free(cmd);
        free(path);
    } else if (strcmp(type, "tool_execution_end") == 0) {
        show_tool_end(a, ev);
    } else if (strcmp(type, "compaction_start") == 0) {
        (void)snprintf(a->status, sizeof a->status, "Compacting the conversation\xe2\x80\xa6");
    } else if (strcmp(type, "compaction_end") == 0) {
        char *err = jget(a, ev, "$.errorMessage");
        if (err) {
            notice(a, RED, "compaction failed: %s", err);
        } else {
            notice(a, DIM, "\xe2\x94\x80 compacted %lld tokens of history into a summary \xe2\x94\x80",
                   jnum(a, ev, "$.result.tokensBefore"));
        }
        a->status[0] = '\0';
        free(err);
    } else if (strcmp(type, "agent_end") == 0) {
        char *status = jget(a, ev, "$.status"), *err = jget(a, ev, "$.errorMessage");
        commit_stream(a);
        a->seen_end = 1;
        if (status && strcmp(status, "failed") == 0) {
            notice(a, RED, err && strcmp(err, "cancelled") == 0 ? "request cancelled" : "request failed: %s", err ? err : "");
        }
        a->status[0] = '\0';
        free(status);
        free(err);
    }
    free(type);
}

static void command(app *a, char *line);

/* Handles complete event lines; at the end of the child, settles the run. */
static void pump(app *a) {
    int done = drain(&a->run);
    char *s = a->run.outbuf.buf;
    size_t used = 0;
    while (s && used < a->run.outbuf.len) {
        char *nl = memchr(s + used, '\n', a->run.outbuf.len - used);
        if (!nl) {
            break;
        }
        *nl = '\0';
        on_event(a, s + used);
        used = (size_t)(nl - s) + 1;
    }
    if (used) {
        memmove(s, s + used, a->run.outbuf.len - used);
        a->run.outbuf.len -= used;
        s[a->run.outbuf.len] = '\0';
    }
    /* Settled when the child has exited (not at end of output: a command it
     * started in the background may hold the pipes open). Then read what is
     * left and stop listening. */
    {
        int status = 0;
        pid_t w = waitpid(a->run.pid, &status, WNOHANG);
        (void)done;
        if (w != a->run.pid) {
            if (a->stop_at && now_ms() - a->stop_at > 3000 * a->stop_level && a->stop_level < 3) {
                /* Not stopping on SIGINT: SIGTERM, then SIGKILL (the journal recovers). */
                a->stop_level++;
                (void)kill(a->run.pid, a->stop_level == 2 ? SIGTERM : SIGKILL);
            }
            return;
        }
        (void)drain(&a->run);
        if (a->run.outbuf.len) {
            (void)text_add(&a->run.outbuf, "\n", 1);
            for (char *line = a->run.outbuf.buf, *nl; line && *line; line = nl + 1) {
                nl = strchr(line, '\n');
                *nl = '\0';
                on_event(a, line);
            }
        }
        if (a->run.out >= 0) {
            close(a->run.out);
        }
        if (a->run.err >= 0) {
            close(a->run.err);
        }
        child_pid = 0;
        a->stop_at = 0;
        a->stop_level = 0;
        commit_stream(a);
        if (!a->seen_end) {
            if (a->run.errbuf.len) {
                notice(a, RED, "%s", a->run.errbuf.buf);
            }
            if (WIFSIGNALED(status)) {
                notice(a, RED, "the request stopped (signal %d)", WTERMSIG(status));
            } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
                notice(a, RED, "the request failed (exit %d)", WEXITSTATUS(status));
            }
        }
        free(a->run.outbuf.buf);
        free(a->run.errbuf.buf);
        memset(&a->run, 0, sizeof a->run);
        a->run.out = a->run.err = -1;
        a->working = 0;
        a->tool[0] = '\0';
        a->status[0] = '\0';
        while (a->nqueue && !a->working && !a->quit) { /* queued commands, then the next message */
            char *next = a->queue[0];
            memmove(a->queue, a->queue + 1, (size_t)(a->nqueue - 1) * sizeof *a->queue);
            a->nqueue--;
            if (next[0] == '/') {
                command(a, next);
            } else {
                start_request(a, next);
            }
            free(next);
        }
    }
}

/* ---- commands ---------------------------------------------------------- */

static void show_history(app *a) {
    const char *args[] = {"log", "--json", a->conversation, NULL};
    char *out = NULL;
    if (run_sync(a, args, &out) == 0) {
        for (char *line = out, *nl; line && *line; line = nl ? nl + 1 : NULL) {
            char *kind, *t;
            nl = strchr(line, '\n');
            if (nl) {
                *nl = '\0';
            }
            kind = jget(a, line, "$.kind");
            t = jget(a, line, "$.text");
            if (kind && strcmp(kind, "user") == 0) {
                notice(a, BOLD, "> %s", t ? t : "");
            } else if (kind && (strcmp(kind, "assistant") == 0 || strcmp(kind, "answer") == 0) && t && *t) {
                text_clear(&a->stream);
                (void)text_add(&a->stream, t, strlen(t));
                commit_stream(a);
            } else if (kind && strcmp(kind, "tool_result") == 0) {
                char *tool = jget(a, line, "$.tool");
                notice(a, DIM, "  %s: %.*s", tool ? tool : "tool", (int)strcspn(t ? t : "", "\n"), t ? t : "");
                free(tool);
            } else if (kind && strcmp(kind, "compaction") == 0) {
                notice(a, DIM, "\xe2\x94\x80 compacted history \xe2\x94\x80");
            }
            free(kind);
            free(t);
        }
    }
    free(out);
}

static void pick_free(app *a) {
    for (int i = 0; i < a->npick; i++) {
        free(a->pick_ids[i]);
        free(a->pick_rows[i]);
    }
    free(a->pick_ids);
    free(a->pick_rows);
    a->pick_ids = a->pick_rows = NULL;
    a->npick = a->pick_at = a->picking = 0;
}

static void open_picker(app *a) {
    const char *args[] = {"sessions", "--json", NULL};
    char *out = NULL;
    pick_free(a);
    if (run_sync(a, args, &out) == 0) {
        for (char *line = out, *nl; line && *line; line = nl ? nl + 1 : NULL) {
            char *id, *name, *first, row[512], **ids, **rows;
            nl = strchr(line, '\n');
            if (nl) {
                *nl = '\0';
            }
            id = jget(a, line, "$.id");
            name = jget(a, line, "$.name");
            first = jget(a, line, "$.first");
            ids = realloc(a->pick_ids, (size_t)(a->npick + 1) * sizeof *ids);
            if (ids) {
                a->pick_ids = ids;
            }
            rows = realloc(a->pick_rows, (size_t)(a->npick + 1) * sizeof *rows);
            if (rows) {
                a->pick_rows = rows;
            }
            if (id && ids && rows) {
                (void)snprintf(row, sizeof row, "%s  %-16s %lld requests  %s", id, name ? name : "-",
                               jnum(a, line, "$.requests"), first ? first : "");
                for (char *c = row; *c; c++) {
                    *c = *c == '\n' ? ' ' : *c;
                }
                a->pick_ids[a->npick] = id;
                a->pick_rows[a->npick] = strdup(row);
                a->npick++;
                id = NULL;
            }
            free(id);
            free(name);
            free(first);
        }
    }
    free(out);
    if (a->npick == 0) {
        notice(a, DIM, "no conversations yet");
        return;
    }
    a->picking = 1;
}

static void resume(app *a, const char *id) {
    const char *args[] = {"sessions", "--json", NULL};
    char *out = NULL;
    (void)snprintf(a->conversation, sizeof a->conversation, "%s", id);
    a->name[0] = '\0';
    if (run_sync(a, args, &out) == 0) {
        for (char *line = out, *nl; line && *line; line = nl ? nl + 1 : NULL) {
            char *lid, *name;
            nl = strchr(line, '\n');
            if (nl) {
                *nl = '\0';
            }
            lid = jget(a, line, "$.id");
            name = jget(a, line, "$.name");
            if (lid && strcmp(lid, id) == 0 && name) {
                (void)snprintf(a->name, sizeof a->name, "%s", name);
            }
            free(lid);
            free(name);
        }
    }
    free(out);
    notice(a, DIM, "\xe2\x94\x80 continuing %s \xe2\x94\x80", id);
    show_history(a);
}

/* ---- the model picker (Pi's, see model-selector.ts) ---------------------- */

static void models_free(app *a) {
    for (int i = 0; i < a->nmodels; i++) {
        free(a->mp_models[i]);
        free(a->mp_names[i]);
        free(a->mp_search[i]);
    }
    free(a->mp_models);
    free(a->mp_names);
    free(a->mp_search);
    free(a->mp_window);
    free(a->mp_order);
    a->mp_models = a->mp_names = a->mp_search = NULL;
    a->mp_window = NULL;
    a->mp_order = NULL;
    a->nmodels = 0;
    a->mp_n = 0;
}

/* Rank for Pi's order: the current model, then the default, then the rest. */
static int model_rank(const app *a, const char *m) {
    return strcmp(m, a->model) == 0 ? 0 : strcmp(m, a->default_model) == 0 ? 1 : 2;
}

/* The models of providers with a key (pic models --json), in Pi's order:
 * current, default, then by provider (stable). */
static void load_models(app *a) {
    const char *args[] = {"models", "--json", NULL};
    char *out = NULL;
    int cap = 0;
    models_free(a);
    if (run_sync(a, args, &out) != 0 || !out) {
        free(out);
        return;
    }
    for (char *line = out, *nl; *line; line = nl + 1) {
        char *m, *name, *provider, *id;
        nl = strchr(line, '\n');
        if (!nl) {
            break;
        }
        *nl = '\0';
        if (a->nmodels == cap) {
            int c = cap ? cap * 2 : 128;
            char **m1 = realloc(a->mp_models, (size_t)c * sizeof *m1), **m2, **m3;
            long *w;
            if (m1) {
                a->mp_models = m1;
            }
            m2 = realloc(a->mp_names, (size_t)c * sizeof *m2);
            if (m2) {
                a->mp_names = m2;
            }
            m3 = realloc(a->mp_search, (size_t)c * sizeof *m3);
            if (m3) {
                a->mp_search = m3;
            }
            w = realloc(a->mp_window, (size_t)c * sizeof *w);
            if (w) {
                a->mp_window = w;
            }
            if (!m1 || !m2 || !m3 || !w) {
                break;
            }
            cap = c;
        }
        m = jget(a, line, "$.model");
        name = jget(a, line, "$.name");
        provider = jget(a, line, "$.provider");
        id = jget(a, line, "$.id");
        if (m && name && provider && id) {
            char search[1024];
            (void)snprintf(search, sizeof search, "%s %s %s %s", id, provider, m, name);
            a->mp_models[a->nmodels] = m;
            a->mp_names[a->nmodels] = name;
            a->mp_search[a->nmodels] = strdup(search);
            a->mp_window[a->nmodels] = jnum(a, line, "$.contextWindow");
            a->nmodels++;
            m = name = NULL;
        }
        free(m);
        free(name);
        free(provider);
        free(id);
    }
    free(out);
    /* Stable insertion sort by rank (the list is already by provider). */
    for (int i = 1; i < a->nmodels; i++) {
        for (int j = i; j > 0 && model_rank(a, a->mp_models[j]) < model_rank(a, a->mp_models[j - 1]); j--) {
            char *t;
            long w;
            t = a->mp_models[j], a->mp_models[j] = a->mp_models[j - 1], a->mp_models[j - 1] = t;
            t = a->mp_names[j], a->mp_names[j] = a->mp_names[j - 1], a->mp_names[j - 1] = t;
            t = a->mp_search[j], a->mp_search[j] = a->mp_search[j - 1], a->mp_search[j - 1] = t;
            w = a->mp_window[j], a->mp_window[j] = a->mp_window[j - 1], a->mp_window[j - 1] = w;
        }
    }
    a->mp_order = malloc(((size_t)a->nmodels + 1) * sizeof *a->mp_order);
}

static void filter_models(app *a) {
    a->mp_n = a->mp_order ? tui_fuzzy_filter(a->mp_filter, (const char *const *)a->mp_search, (size_t)a->nmodels, a->mp_order) : 0;
    a->mp_sel = 0;
}

static void use_model(app *a, int i, int save) {
    (void)snprintf(a->model, sizeof a->model, "%s", a->mp_models[i]);
    a->window = a->mp_window[i];
    if (save) {
        const char *args[] = {"models", "--default", a->model, NULL};
        char *out = NULL;
        if (run_sync(a, args, &out) == 0) {
            (void)snprintf(a->default_model, sizeof a->default_model, "%s", a->model);
            notice(a, DIM, "model %s, saved as the default", a->model);
        }
        free(out);
    } else {
        notice(a, DIM, "model %s", a->model);
    }
}

/* Opens the picker; a fresher catalog is fetched in the background, as Pi
 * does when its selector opens. */
static void open_models(app *a, const char *filter) {
    load_models(a);
    (void)snprintf(a->mp_filter, sizeof a->mp_filter, "%s", filter ? filter : "");
    filter_models(a);
    a->mp_open = 1;
    if (!a->refreshing) {
        const char *args[] = {"models", "--refresh", "--json", NULL};
        if (spawn(a, &a->refresh, args) == 0) {
            a->refreshing = 1;
        }
    }
}

/* The background catalog refresh: when it ends, the open picker reloads. */
static void pump_refresh(app *a) {
    int status;
    (void)drain(&a->refresh);
    if (waitpid(a->refresh.pid, &status, WNOHANG) != a->refresh.pid) {
        return;
    }
    (void)drain(&a->refresh);
    if (a->refresh.out >= 0) {
        close(a->refresh.out);
    }
    if (a->refresh.err >= 0) {
        close(a->refresh.err);
    }
    free(a->refresh.outbuf.buf);
    free(a->refresh.errbuf.buf);
    memset(&a->refresh, 0, sizeof a->refresh);
    a->refresh.out = a->refresh.err = -1;
    a->refreshing = 0;
    if (a->mp_open) {
        char *selected = a->mp_n ? strdup(a->mp_models[a->mp_order[a->mp_sel]]) : NULL;
        load_models(a);
        filter_models(a);
        for (size_t i = 0; selected && i < a->mp_n; i++) {
            if (strcmp(a->mp_models[a->mp_order[i]], selected) == 0) {
                a->mp_sel = (int)i;
            }
        }
        free(selected);
    }
}

static void picker_lines(app *a, tui_lines *tail) {
    char line[1024];
    int first = a->mp_sel < 10 ? 0 : a->mp_sel - 9;
    add_fit(tail, BOLD, "Select a model  (type to filter \xc2\xb7 enter: use \xc2\xb7 ctrl+s: use and save as default \xc2\xb7 esc)", a->cols);
    (void)snprintf(line, sizeof line, "> %s", a->mp_filter);
    add_fit(tail, "", line, a->cols);
    for (int r = 0; r < 10 && first + r < (int)a->mp_n; r++) {
        int i = (int)a->mp_order[first + r];
        const char *m = a->mp_models[i], *slash = strchr(m, '/');
        char provider[64];
        int sel = first + r == a->mp_sel;
        (void)snprintf(provider, sizeof provider, "%.*s", slash ? (int)(slash - m) : 0, m);
        (void)snprintf(line, sizeof line, "%s %s %s%s%s%s [%s]%s", sel ? "\xe2\x86\x92" : " ",
                       strcmp(m, a->model) == 0 ? "\xe2\x9c\x93" : " ", slash ? slash + 1 : m,
                       strcmp(a->mp_names[i], slash ? slash + 1 : m) != 0 ? " (" : "",
                       strcmp(a->mp_names[i], slash ? slash + 1 : m) != 0 ? a->mp_names[i] : "",
                       strcmp(a->mp_names[i], slash ? slash + 1 : m) != 0 ? ")" : "", provider,
                       strcmp(m, a->default_model) == 0 ? " \xc2\xb7 default" : "");
        add_fit(tail, sel ? CYAN : "", line, a->cols);
    }
    if (a->mp_n == 0) {
        add_fit(tail, DIM, a->nmodels ? "  no model matches" : "  no models: no provider has a key (pic models --all lists them)", a->cols);
    } else {
        (void)snprintf(line, sizeof line, "  (%d/%zu)%s", a->mp_sel + 1, a->mp_n,
                       a->refreshing ? "  refreshing the catalog\xe2\x80\xa6" : "");
        add_fit(tail, DIM, line, a->cols);
    }
    add_fit(tail, DIM, "Only models from providers with a key are shown (pic models --all lists every one).", a->cols);
}

static void picker_key(app *a, const tui_key *k) {
    size_t len = strlen(a->mp_filter);
    switch (k->kind) {
    case TUI_KEY_UP:
        a->mp_sel = a->mp_n ? (a->mp_sel + (int)a->mp_n - 1) % (int)a->mp_n : 0;
        break;
    case TUI_KEY_DOWN:
        a->mp_sel = a->mp_n ? (a->mp_sel + 1) % (int)a->mp_n : 0;
        break;
    case TUI_KEY_PAGEUP:
        a->mp_sel = a->mp_sel > 10 ? a->mp_sel - 10 : 0;
        break;
    case TUI_KEY_PAGEDOWN:
        a->mp_sel = a->mp_n ? (a->mp_sel + 10 < (int)a->mp_n ? a->mp_sel + 10 : (int)a->mp_n - 1) : 0;
        break;
    case TUI_KEY_ENTER:
    case TUI_KEY_CTRL_S:
        if (a->mp_n) {
            use_model(a, (int)a->mp_order[a->mp_sel], k->kind == TUI_KEY_CTRL_S);
        }
        a->mp_open = 0;
        break;
    case TUI_KEY_ESC:
    case TUI_KEY_CTRL_C:
        a->mp_open = 0;
        break;
    case TUI_KEY_BACKSPACE:
        while (len > 0 && ((unsigned char)a->mp_filter[len - 1] & 0xC0) == 0x80) {
            len--;
        }
        if (len > 0) {
            a->mp_filter[len - 1] = '\0';
        }
        filter_models(a);
        break;
    case TUI_KEY_CHAR:
        if (len + strlen(k->text) < sizeof a->mp_filter) {
            memcpy(a->mp_filter + len, k->text, strlen(k->text) + 1);
        }
        filter_models(a);
        break;
    default:
        break;
    }
}

/* Ctrl+P: the next model with a key, in the picker's order (Pi cycles its
 * available models when no scope is set). */
static void cycle_model(app *a) {
    int at = 0;
    load_models(a);
    if (a->nmodels < 2) {
        notice(a, DIM, "only one model available");
        return;
    }
    for (int i = 0; i < a->nmodels; i++) {
        if (strcmp(a->mp_models[i], a->model) == 0) {
            at = i;
        }
    }
    use_model(a, (at + 1) % a->nmodels, 0);
}

/* ---- slash commands ------------------------------------------------------ */

static const struct {
    const char *name, *hint, *what;
} commands[] = {
    {"model", "[provider/model]", "select a model"},
    {"new", "", "start a new conversation"},
    {"resume", "[ID]", "resume another conversation"},
    {"name", "NAME", "name this conversation"},
    {"session", "", "show this conversation's info and stats"},
    {"fork", "[ENTRY]", "branch this conversation (from ENTRY, see /log)"},
    {"clone", "", "duplicate this conversation at its current point"},
    {"compact", "[FOCUS]", "summarize the history before the next message"},
    {"copy", "", "copy the last reply"},
    {"export", "[DIR]", "write this conversation as a Pi session file"},
    {"hotkeys", "", "show keyboard shortcuts"},
    {"quit", "", "quit pic"},
};
#define NCOMMANDS (sizeof commands / sizeof commands[0])
#define MENU_ROWS 5

/* The menu for what is typed: commands while the first word is typed after
 * "/", model names after "/model ". Fills labels (display) and values (what
 * is inserted); returns how many, and whether they are commands. */
static size_t menu_items(app *a, char labels[][256], char values[][256], size_t cap, int *is_command) {
    const char *t = tui_editor_text(a->ed), *s = t;
    size_t cur = tui_editor_cursor(a->ed), n = 0, order[NCOMMANDS];
    while (*s == ' ') {
        s++;
    }
    *is_command = 0;
    if (*s != '/' || memchr(t, '\n', cur) || cur < (size_t)(s - t) + 1 || strcmp(t, a->menu_dismissed) == 0) {
        return 0;
    }
    if (!strpbrk(s, " \t")) {
        const char *names[NCOMMANDS];
        char query[128];
        (void)snprintf(query, sizeof query, "%s", s + 1);
        for (size_t i = 0; i < NCOMMANDS; i++) {
            names[i] = commands[i].name;
        }
        n = tui_fuzzy_filter(query, names, NCOMMANDS, order);
        for (size_t i = 0; i < n && i < cap; i++) {
            const char *hint = commands[order[i]].hint;
            (void)snprintf(labels[i], 256, "/%-9s %s%s%s", commands[order[i]].name, hint, *hint ? " \xe2\x80\x94 " : "",
                           commands[order[i]].what);
            (void)snprintf(values[i], 256, "/%s", commands[order[i]].name);
        }
        *is_command = 1;
        return n < cap ? n : cap;
    }
    if (strncmp(s, "/model ", 7) == 0) {
        const char *q = s + 7;
        size_t *ord;
        while (*q == ' ') {
            q++;
        }
        if (!a->nmodels) {
            load_models(a);
        }
        ord = malloc(((size_t)a->nmodels + 1) * sizeof *ord);
        if (!ord) {
            return 0;
        }
        {
            const char **texts = malloc(((size_t)a->nmodels + 1) * sizeof *texts);
            if (texts) {
                for (int i = 0; i < a->nmodels; i++) {
                    texts[i] = a->mp_models[i];
                }
                n = tui_fuzzy_filter(q, texts, (size_t)a->nmodels, ord);
                free(texts);
            }
        }
        for (size_t i = 0; i < n && i < cap; i++) {
            const char *m = a->mp_models[ord[i]], *slash = strchr(m, '/');
            (void)snprintf(labels[i], 256, "%s  [%.*s]", slash ? slash + 1 : m, slash ? (int)(slash - m) : 0, m);
            (void)snprintf(values[i], 256, "/model %s", m);
        }
        free(ord);
        return n < cap ? n : cap;
    }
    return 0;
}

static void menu_lines(app *a, tui_lines *tail) {
    char labels[MENU_ROWS][256], values[MENU_ROWS][256];
    int is_command;
    size_t n = menu_items(a, labels, values, MENU_ROWS, &is_command);
    if (a->menu_sel >= (int)n) {
        a->menu_sel = 0;
    }
    for (size_t i = 0; i < n; i++) {
        add_fit(tail, (int)i == a->menu_sel ? CYAN : DIM, labels[i], a->cols);
    }
}

/* Keys the menu takes while it shows: up/down choose, tab completes, enter
 * completes and (for a command) runs it, esc hides it. 1 when taken. */
static int menu_key(app *a, const tui_key *k) {
    char labels[MENU_ROWS][256], values[MENU_ROWS][256];
    int is_command;
    size_t n;
    if (k->kind != TUI_KEY_UP && k->kind != TUI_KEY_DOWN && k->kind != TUI_KEY_TAB && k->kind != TUI_KEY_ENTER &&
        k->kind != TUI_KEY_ESC) {
        return 0;
    }
    n = menu_items(a, labels, values, MENU_ROWS, &is_command);
    if (n == 0) {
        return 0;
    }
    if (a->menu_sel >= (int)n) {
        a->menu_sel = 0;
    }
    switch (k->kind) {
    case TUI_KEY_UP:
        a->menu_sel = (a->menu_sel + (int)n - 1) % (int)n;
        return 1;
    case TUI_KEY_DOWN:
        a->menu_sel = (a->menu_sel + 1) % (int)n;
        return 1;
    case TUI_KEY_ESC:
        (void)snprintf(a->menu_dismissed, sizeof a->menu_dismissed, "%s", tui_editor_text(a->ed));
        return 1;
    case TUI_KEY_TAB: {
        char v[260];
        (void)snprintf(v, sizeof v, "%s ", values[a->menu_sel]);
        tui_editor_set(a->ed, is_command ? v : values[a->menu_sel]);
        a->menu_sel = 0;
        return 1;
    }
    default: /* ENTER */
        if (is_command) {
            char *v = strdup(values[a->menu_sel]);
            tui_editor_clear(a->ed);
            a->menu_sel = 0;
            if (v) {
                submit(a, v);
            }
            free(v);
        } else {
            tui_editor_set(a->ed, values[a->menu_sel]);
            /* the argument is in place; the next Enter runs it, as in Pi */
            (void)snprintf(a->menu_dismissed, sizeof a->menu_dismissed, "%s", tui_editor_text(a->ed));
            a->menu_sel = 0;
        }
        return 1;
    }
}

/* Copies TEXT: OSC 52 (works over ssh, in most terminals) and, where there
 * is one, the system's own clipboard command. */
static void copy_text(app *a, const char *t) {
    static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    size_t n = strlen(t);
    text osc = {NULL, 0, 0};
    (void)text_add(&osc, "\x1b]52;c;", 7);
    for (size_t i = 0; i < n; i += 3) {
        unsigned v = (unsigned)(unsigned char)t[i] << 16 | (i + 1 < n ? (unsigned)(unsigned char)t[i + 1] << 8 : 0) |
                     (i + 2 < n ? (unsigned char)t[i + 2] : 0);
        char q[4] = {b64[v >> 18 & 63], b64[v >> 12 & 63], i + 1 < n ? b64[v >> 6 & 63] : '=', i + 2 < n ? b64[v & 63] : '='};
        (void)text_add(&osc, q, 4);
    }
    (void)text_add(&osc, "\x07", 1);
    if (osc.buf) {
        ssize_t w = write(STDOUT_FILENO, osc.buf, osc.len);
        (void)w;
    }
    free(osc.buf);
    {
        const char *tool = access("/usr/bin/pbcopy", X_OK) == 0 ? "/usr/bin/pbcopy" : NULL;
        if (tool) {
            int p[2];
            pid_t pid = -1;
            if (pipe(p) == 0 && (pid = fork()) == 0) {
                (void)dup2(p[0], STDIN_FILENO);
                close(p[0]);
                close(p[1]);
                execl(tool, tool, (char *)NULL);
                _exit(127);
            } else if (pid > 0) {
                ssize_t w;
                close(p[0]);
                w = write(p[1], t, n);
                (void)w;
                close(p[1]);
                (void)waitpid(pid, NULL, 0);
            }
        }
    }
    notice(a, DIM, "copied the last reply (%zu characters)", n);
}

static const char hotkeys[] =
    "Enter  send (while a reply runs: queue it)      Ctrl+J / Alt+Enter  new line\n"
    "Esc    interrupt the reply (again: stop it harder; restores queued messages)\n"
    "Ctrl+L model picker      Ctrl+P  next model      Ctrl+O  expand later tool output\n"
    "Ctrl+C clear the editor (twice: quit)            Ctrl+D  quit on an empty editor\n"
    "Up/Down history          Tab  complete a /command or a model name";

static void command(app *a, char *line) {
    char *arg = line + strcspn(line, " \t");
    char *out = NULL;
    if (*arg) {
        *arg++ = '\0';
        arg += strspn(arg, " \t");
    }
    if (strcmp(line, "/quit") == 0 || strcmp(line, "/exit") == 0) {
        a->quit = 1;
    } else if (strcmp(line, "/help") == 0 || strcmp(line, "/hotkeys") == 0) {
        notice(a, DIM, "%s", hotkeys);
        if (strcmp(line, "/help") == 0) {
            text t = {NULL, 0, 0};
            for (size_t i = 0; i < NCOMMANDS; i++) {
                char row[256];
                (void)snprintf(row, sizeof row, "/%-9s %-18s %s\n", commands[i].name, commands[i].hint, commands[i].what);
                (void)text_add(&t, row, strlen(row));
            }
            if (t.buf) {
                notice(a, DIM, "%s", t.buf);
            }
            free(t.buf);
        }
    } else if (strcmp(line, "/new") == 0) {
        a->conversation[0] = a->name[0] = '\0';
        a->in = a->out = a->context = 0;
        notice(a, DIM, "\xe2\x94\x80 new conversation \xe2\x94\x80");
    } else if (strcmp(line, "/resume") == 0) {
        if (*arg) {
            resume(a, arg);
        } else {
            open_picker(a);
        }
    } else if (strcmp(line, "/model") == 0) {
        /* An exact provider/model or bare id switches; otherwise the picker
         * opens with what was typed as its filter (Pi's /model ARG). */
        int found = -1;
        if (*arg) {
            load_models(a);
            for (int i = 0; i < a->nmodels && found < 0; i++) {
                const char *m = a->mp_models[i], *slash = strchr(m, '/');
                if (strcasecmp(m, arg) == 0 || (slash && strcasecmp(slash + 1, arg) == 0)) {
                    found = i;
                }
            }
        }
        if (found >= 0) {
            use_model(a, found, 0);
        } else {
            open_models(a, arg);
        }
    } else if (strcmp(line, "/copy") == 0) {
        if (a->last_reply && *a->last_reply) {
            copy_text(a, a->last_reply);
        } else {
            notice(a, DIM, "no reply to copy yet");
        }
    } else if (!a->conversation[0]) {
        if (strcmp(line, "/name") == 0 || strcmp(line, "/fork") == 0 || strcmp(line, "/compact") == 0 ||
            strcmp(line, "/session") == 0 || strcmp(line, "/clone") == 0 || strcmp(line, "/export") == 0) {
            notice(a, RED, "%s needs a conversation: send a message first", line);
        } else {
            notice(a, RED, "unknown command %s (/help lists them)", line);
        }
    } else if (strcmp(line, "/name") == 0 && *arg) {
        const char *args[] = {"name", a->conversation, arg, NULL};
        if (run_sync(a, args, &out) == 0) {
            (void)snprintf(a->name, sizeof a->name, "%s", arg);
            notice(a, DIM, "named %s", arg);
        }
    } else if (strcmp(line, "/fork") == 0 || strcmp(line, "/clone") == 0) {
        int at = strcmp(line, "/fork") == 0 && *arg;
        const char *args[] = {"fork", a->conversation, at ? "--at" : NULL, at ? arg : NULL, NULL};
        if (run_sync(a, args, &out) == 0 && out) {
            out[strcspn(out, "\n")] = '\0';
            notice(a, DIM, "\xe2\x94\x80 %s: now in %s \xe2\x94\x80", strcmp(line, "/clone") == 0 ? "cloned" : "forked", out);
            (void)snprintf(a->conversation, sizeof a->conversation, "%s", out);
            a->name[0] = '\0';
        }
    } else if (strcmp(line, "/compact") == 0) {
        const char *args[] = {"compact", a->conversation, *arg ? arg : NULL, NULL};
        if (run_sync(a, args, &out) == 0) {
            notice(a, DIM, "the history is summarized before the next message");
        }
    } else if (strcmp(line, "/export") == 0) {
        const char *args[] = {"export", "--pi", *arg ? arg : NULL, NULL};
        if (run_sync(a, args, &out) == 0) {
            notice(a, DIM, "written to %s as Pi session files (one per conversation)", *arg ? arg : "~/.pic/sessions");
        }
    } else if (strcmp(line, "/session") == 0) {
        char a1[16], a2[16], a3[16], a4[16], a5[16];
        fmt_tokens(a->in, a1, sizeof a1);
        fmt_tokens(a->out, a2, sizeof a2);
        fmt_tokens(a->cache_read, a3, sizeof a3);
        fmt_tokens(a->cache_write, a4, sizeof a4);
        fmt_tokens(a->context, a5, sizeof a5);
        notice(a, DIM,
               "conversation %s%s%s%s\nmodel        %s\ntokens       in %s, out %s, cache read %s, cache write %s "
               "(this window)\ncontext      %s of %ld\njournal      %s\nPi file      ~/.pic/sessions/ (written after each "
               "request)",
               a->conversation, a->name[0] ? " (" : "", a->name, a->name[0] ? ")" : "", a->model, a1, a2, a3, a4, a5,
               a->window, a->o->db);
    } else if (strcmp(line, "/name") == 0) {
        notice(a, RED, "/name needs a NAME");
    } else {
        notice(a, RED, "unknown command %s (/help lists them)", line);
    }
    free(out);
}

static void submit(app *a, char *msg) {
    /* While a reply runs, messages and commands queue (commands need the
     * journal, which the running request holds). */
    if (msg[0] == '/' && !a->working) {
        command(a, msg);
    } else if (a->working) {
        if (a->nqueue < MAX_QUEUED) {
            a->queue[a->nqueue++] = strdup(msg);
        }
    } else {
        start_request(a, msg);
    }
}

/* ---- keys -------------------------------------------------------------- */

static void on_key(app *a, tui_key *k) {
    if (a->mp_open) {
        picker_key(a, k);
        return;
    }
    if (a->picking) {
        if (k->kind == TUI_KEY_UP && a->pick_at > 0) {
            a->pick_at--;
        } else if (k->kind == TUI_KEY_DOWN && a->pick_at + 1 < a->npick) {
            a->pick_at++;
        } else if (k->kind == TUI_KEY_ENTER) {
            char *id = strdup(a->pick_ids[a->pick_at]);
            pick_free(a);
            if (id) {
                resume(a, id);
            }
            free(id);
        } else if (k->kind == TUI_KEY_ESC || k->kind == TUI_KEY_CTRL_C) {
            pick_free(a);
        }
        return;
    }
    if (k->kind != TUI_KEY_CTRL_C) {
        a->ctrl_c_armed = 0;
    }
    if (menu_key(a, k)) {
        return;
    }
    switch (k->kind) {
    case TUI_KEY_CTRL_C:
        if (!tui_editor_empty(a->ed)) {
            tui_editor_clear(a->ed);
        } else if (a->ctrl_c_armed) {
            a->quit = 1;
        } else {
            a->ctrl_c_armed = 1;
            (void)snprintf(a->status, sizeof a->status, "press ctrl+c again to quit");
        }
        return;
    case TUI_KEY_CTRL_D:
        if (tui_editor_empty(a->ed)) {
            a->quit = 1;
        }
        return;
    case TUI_KEY_ESC:
        if (a->working && !a->interrupted) {
            a->interrupted = 1;
            a->stop_at = now_ms();
            a->stop_level = 1;
            (void)kill(a->run.pid, SIGINT);
        } else if (a->working && a->stop_level < 3) { /* Esc again: stop it harder */
            a->stop_level++;
            (void)kill(a->run.pid, a->stop_level == 2 ? SIGTERM : SIGKILL);
        }
        if (a->nqueue) { /* queued messages come back to the editor, as Pi does */
            text t = {NULL, 0, 0};
            for (int i = 0; i < a->nqueue; i++) {
                (void)text_add(&t, a->queue[i], strlen(a->queue[i]));
                if (i + 1 < a->nqueue) {
                    (void)text_add(&t, "\n", 1);
                }
                free(a->queue[i]);
            }
            a->nqueue = 0;
            tui_editor_set(a->ed, t.buf ? t.buf : "");
            free(t.buf);
        }
        return;
    case TUI_KEY_CTRL_L: /* Pi's model picker key */
        if (!a->working) {
            open_models(a, NULL);
        }
        return;
    case TUI_KEY_CTRL_P:
        if (!a->working) {
            cycle_model(a);
        }
        return;
    case TUI_KEY_CTRL_O:
        a->expand_tools = !a->expand_tools;
        return;
    default:
        break;
    }
    if (tui_editor_key(a->ed, k) == TUI_EDIT_SUBMIT) {
        char *msg = tui_editor_take(a->ed);
        if (msg) {
            if (a->status[0] && !a->working) {
                a->status[0] = '\0';
            }
            submit(a, msg);
        }
        free(msg);
    }
}

/* ---- main loop -------------------------------------------------------- */

int pic_tui_main(const pic_tui_options *o) {
    app a;
    int rc = 0;
    memset(&a, 0, sizeof a);
    a.o = o;
    a.run.out = a.run.err = -1;
    (void)snprintf(a.model, sizeof a.model, "%s", o->model);
    (void)snprintf(a.default_model, sizeof a.default_model, "%s", o->default_model ? o->default_model : o->model);
    a.refresh.out = a.refresh.err = -1;
    if (sqlite3_open(":memory:", &a.db) != SQLITE_OK ||
        sqlite3_prepare_v2(a.db, "SELECT json_extract(?1, ?2) WHERE json_valid(?1)", -1, &a.get, NULL) != SQLITE_OK ||
        !(a.r = tui_render_new(STDOUT_FILENO)) || !(a.ed = tui_editor_new()) || !(a.keys = tui_keys_new()) ||
        pipe(wake_pipe) != 0 || tui_term_raw(STDIN_FILENO) != 0) {
        fprintf(stderr, "pic: cannot start the terminal interface\n");
        rc = 1;
        goto done;
    }
    (void)fcntl(wake_pipe[0], F_SETFL, fcntl(wake_pipe[0], F_GETFL) | O_NONBLOCK);
    (void)fcntl(wake_pipe[0], F_SETFD, FD_CLOEXEC);
    (void)fcntl(wake_pipe[1], F_SETFD, FD_CLOEXEC);
    (void)atexit(tui_term_restore);
    (void)signal(SIGSEGV, on_stop);
    (void)signal(SIGABRT, on_stop);
    (void)signal(SIGBUS, on_stop);
    (void)signal(SIGWINCH, on_winch);
    (void)signal(SIGTERM, on_stop);
    (void)signal(SIGHUP, on_stop);
    (void)signal(SIGQUIT, on_stop);
    (void)signal(SIGPIPE, SIG_IGN);
    (void)signal(SIGINT, SIG_IGN); /* raw mode sends Ctrl+C as a key; a stray SIGINT is ignored */
    tui_term_size(STDOUT_FILENO, &a.cols, &a.rows);
    notice(&a, BOLD, "pic %s", a.model);
    notice(&a, DIM, "%s  \xe2\x80\x94  /help for keys and commands", o->workspace);
    if (o->resume) {
        const char *args[] = {"sessions", "--json", NULL};
        char *out = NULL;
        if (strcmp(o->resume, "latest") == 0) {
            if (run_sync(&a, args, &out) == 0 && out && *out) {
                char *nl = strchr(out, '\n'), *id;
                if (nl) {
                    *nl = '\0';
                }
                id = jget(&a, out, "$.id");
                if (id) {
                    resume(&a, id);
                }
                free(id);
            }
            free(out);
        } else {
            resume(&a, o->resume);
        }
    }
    while (!a.quit) {
        struct pollfd p[4];
        int n = 0, timeout = -1;
        tui_key k;
        if (resized) {
            resized = 0;
            tui_term_size(STDOUT_FILENO, &a.cols, &a.rows);
            tui_render_invalidate(a.r);
        }
        draw(&a);
        p[n++] = (struct pollfd){STDIN_FILENO, POLLIN, 0};
        p[n++] = (struct pollfd){wake_pipe[0], POLLIN, 0};
        if (a.run.out >= 0) {
            p[n++] = (struct pollfd){a.run.out, POLLIN, 0};
        }
        if (a.run.err >= 0) {
            p[n++] = (struct pollfd){a.run.err, POLLIN, 0};
        }
        if (a.refreshing && a.refresh.out >= 0) {
            p[n++] = (struct pollfd){a.refresh.out, POLLIN, 0};
        }
        if (a.refreshing && timeout < 0) {
            timeout = 250; /* notice the refresh ending */
        }
        if (a.working) {
            timeout = 80; /* the spinner */
        }
        if (tui_keys_waiting(a.keys)) {
            timeout = 50; /* a lone Esc, or the start of a sequence */
        }
        if (poll(p, (nfds_t)n, timeout) < 0 && errno != EINTR) {
            rc = 1;
            break;
        }
        a.spin++;
        if (p[1].revents) {
            char buf[64];
            while (read(wake_pipe[0], buf, sizeof buf) > 0) {
            }
        }
        if (p[0].revents & POLLIN) {
            char buf[4096];
            ssize_t got = read(STDIN_FILENO, buf, sizeof buf);
            if (got == 0) {
                break; /* the terminal went away */
            }
            if (got > 0) {
                tui_keys_feed(a.keys, buf, (size_t)got);
            }
        } else if (tui_keys_waiting(a.keys)) {
            tui_keys_flush(a.keys);
        }
        while (tui_keys_next(a.keys, &k)) {
            on_key(&a, &k);
            free(k.paste);
        }
        if (a.working && a.run.pid > 0) {
            pump(&a);
        }
        if (a.refreshing) {
            pump_refresh(&a);
        }
    }
    if (a.working && a.run.pid > 0) { /* quitting mid-reply: cancel it, firmly if it must be */
        long t0 = now_ms();
        int level = 1;
        (void)kill(a.run.pid, SIGINT);
        while (waitpid(a.run.pid, NULL, WNOHANG) == 0) {
            struct pollfd p[2] = {{a.run.out, POLLIN, 0}, {a.run.err, POLLIN, 0}};
            (void)poll(p, 2, 100);
            (void)drain(&a.run);
            if (now_ms() - t0 > 3000 * level && level < 3) {
                level++;
                (void)kill(a.run.pid, level == 2 ? SIGTERM : SIGKILL);
            }
        }
        child_pid = 0;
        free(a.run.outbuf.buf);
        free(a.run.errbuf.buf);
    }
    if (a.refreshing && a.refresh.pid > 0) {
        (void)kill(a.refresh.pid, SIGTERM);
        (void)waitpid(a.refresh.pid, NULL, 0);
        free(a.refresh.outbuf.buf);
        free(a.refresh.errbuf.buf);
    }
    (void)tui_render_finish(a.r);
done:
    tui_term_restore();
    pick_free(&a);
    models_free(&a);
    free(a.last_reply);
    for (int i = 0; i < a.nqueue; i++) {
        free(a.queue[i]);
    }
    free(a.stream.buf);
    free(a.thinking.buf);
    if (a.keys) {
        tui_keys_free(a.keys);
    }
    if (a.ed) {
        tui_editor_free(a.ed);
    }
    if (a.r) {
        tui_render_free(a.r);
    }
    sqlite3_finalize(a.get);
    sqlite3_close(a.db);
    if (a.conversation[0] && rc == 0) {
        printf("pic: conversation %s (pic chat --session %s, or pic tui -c)\n", a.conversation, a.conversation);
    }
    return rc;
}