Skip to content
pi-c Artifact [aca2a2d618]
Login

Artifact [aca2a2d618]

Artifact aca2a2d618a4e5abaa7d4dabf8c5374a79b29de3a88505947fccc11393d6071b:


/* 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 <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <limits.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/wait.h>
#include <unistd.h>

#include "models.h"
#include "pic.h"
#include "platform.h"
#include "prompts.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"
#include "userdb.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;
    pic_prompts tpl; /* prompt templates: /name ARGS goes to the request as typed */
    /* the slash menu */
    int menu_sel;
    char menu_dismissed[512];
    char *last_reply; /* for /copy */
    int quit;
    /* the thinking level: "" means the saved default (see effective_level) */
    char think_level[16];
    char lvl_for[160];                       /* the model lvls was worked out for */
    const char *lvls[PIC_THINKING_LEVELS];   /* its supported levels, lowest first */
    int nlvl;
    char level[16];                          /* the level requests use ('' when the model has none) */
    int hide_thinking;
    /* an overlay: /settings, /scoped-models, /thinking, /tree, /trust, /share */
    int ov;
    char ov_title[160], ov_hint[200], ov_filter[128];
    char **ov_label, **ov_id;
    unsigned char *ov_on;
    size_t *ov_order, ov_m;
    int ov_n, ov_sel;
    char *ov_data; /* /share: the page waiting for a yes */
} app;

enum { OV_NONE, OV_SETTINGS, OV_SCOPED, OV_THINKING, OV_TREE, OV_TRUST, OV_SHARE };

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) { return (long)(pic_platform_get()->mono_ns() / 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);
}

/* ---- the thinking level ------------------------------------------------- */

/* Pi's clampThinkingLevel over the model's supported levels: WANT if
 * supported, else the nearest supported level above it, else below. */
static const char *clamp_level(const app *a, const char *want) {
    int w = pic_thinking_index(want);
    if (a->nlvl == 0) {
        return "";
    }
    for (int d = 0; w >= 0 && d < PIC_THINKING_LEVELS; d++) {
        for (int i = 0; i < a->nlvl; i++) {
            if (pic_thinking_index(a->lvls[i]) == w + d) {
                return a->lvls[i];
            }
        }
    }
    for (int d = 1; w >= 0 && d < PIC_THINKING_LEVELS; d++) {
        for (int i = 0; i < a->nlvl; i++) {
            if (pic_thinking_index(a->lvls[i]) == w - d) {
                return a->lvls[i];
            }
        }
    }
    return a->lvls[a->nlvl - 1];
}

/* The level a request will use, as pic ask works it out (the session's,
 * else the model's saved one, else the default, else medium), clamped to what
 * the model supports; the levels themselves are cached per model. */
static void refresh_level(app *a) {
    pic_model m;
    char err[PIC_ERR_CAP], key[320], *saved = NULL;
    (void)snprintf(a->lvl_for, sizeof a->lvl_for, "%s", a->model);
    a->nlvl = pic_model_resolve(a->model, &m, err, sizeof err) == 0 ? pic_model_thinking_levels(&m, a->lvls) : 0;
    a->level[0] = '\0';
    if (a->nlvl == 0) {
        return;
    }
    if (a->think_level[0]) {
        (void)snprintf(a->level, sizeof a->level, "%s", clamp_level(a, a->think_level));
        return;
    }
    (void)snprintf(key, sizeof key, "thinkingLevel:%s", a->model);
    saved = pic_setting(key);
    if (pic_thinking_index(saved) < 0) {
        free(saved);
        saved = pic_setting("defaultThinkingLevel");
    }
    (void)snprintf(a->level, sizeof a->level, "%s", clamp_level(a, pic_thinking_index(saved) >= 0 ? saved : "medium"));
    free(saved);
}

static void ensure_level(app *a) {
    if (strcmp(a->lvl_for, a->model) != 0 || !a->lvl_for[0]) {
        refresh_level(a);
    }
}

static void set_level(app *a, const char *level) {
    (void)snprintf(a->think_level, sizeof a->think_level, "%s", level);
    refresh_level(a);
    notice(a, DIM, "thinking level: %s", a->level);
}

/* Shift+Tab: the next level the model supports, wrapping (Pi's cycleThinkingLevel). */
static void cycle_level(app *a) {
    int at = 0;
    ensure_level(a);
    if (a->nlvl <= 1) {
        notice(a, DIM, "%s does not support thinking levels", a->model);
        return;
    }
    for (int i = 0; i < a->nlvl; i++) {
        at = strcmp(a->lvls[i], a->level) == 0 ? i : at;
    }
    set_level(a, a->lvls[(at + 1) % a->nlvl]);
}

static void picker_lines(app *a, tui_lines *tail);
static void overlay_lines(app *a, tui_lines *tail);
static void overlay_key(app *a, const tui_key *k);
static void ov_free(app *a);
static void submit(app *a, char *msg);
static const pic_prompt *template_for(const app *a, const char *line);
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], mdl[320];
    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->ov) {
        overlay_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);
    ensure_level(a);
    (void)snprintf(mdl, sizeof mdl, "%s%s%s", a->model, a->nlvl > 1 ? "  \xe2\x80\xa2 " : "", a->nlvl > 1 ? a->level : "");
    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, mdl,
                       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, mdl,
                       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[34];
    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;
    }
    ensure_level(a);
    if (a->think_level[0] && a->level[0]) { /* the session's choice, clamped to this model */
        argv[n++] = "--thinking";
        argv[n++] = a->level;
    }
    for (; *args && n < 33; 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 && !a->hide_thinking && 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] == '/' && !template_for(a, next)) {
                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;
    }
}

/* ---- overlays: lists that take the keys until chosen or closed ------------- */

static void ov_free(app *a) {
    for (int i = 0; i < a->ov_n; i++) {
        free(a->ov_label[i]);
        free(a->ov_id[i]);
    }
    free(a->ov_label);
    free(a->ov_id);
    free(a->ov_on);
    free(a->ov_order);
    free(a->ov_data);
    a->ov_label = a->ov_id = NULL;
    a->ov_on = NULL;
    a->ov_order = NULL;
    a->ov_data = NULL;
    a->ov_n = a->ov_sel = a->ov = 0;
    a->ov_m = 0;
    a->ov_filter[0] = '\0';
}

static void ov_open(app *a, int kind, const char *title, const char *hint) {
    ov_free(a);
    a->ov = kind;
    (void)snprintf(a->ov_title, sizeof a->ov_title, "%s", title);
    (void)snprintf(a->ov_hint, sizeof a->ov_hint, "%s", hint);
}

static void ov_add(app *a, const char *label, const char *id, int on) {
    char **l = realloc(a->ov_label, ((size_t)a->ov_n + 1) * sizeof *l), **d;
    unsigned char *o;
    if (l) {
        a->ov_label = l;
    }
    d = realloc(a->ov_id, ((size_t)a->ov_n + 1) * sizeof *d);
    if (d) {
        a->ov_id = d;
    }
    o = realloc(a->ov_on, (size_t)a->ov_n + 1);
    if (o) {
        a->ov_on = o;
    }
    if (!l || !d || !o) {
        return;
    }
    a->ov_label[a->ov_n] = strdup(label);
    a->ov_id[a->ov_n] = strdup(id);
    a->ov_on[a->ov_n] = (unsigned char)(on != 0);
    a->ov_n++;
}

static int ov_filterable(const app *a) { return a->ov == OV_SCOPED || a->ov == OV_TREE; }

/* The rows that match the filter, best first (all, in order, with none). */
static void ov_refilter(app *a) {
    free(a->ov_order);
    a->ov_order = malloc(((size_t)a->ov_n + 1) * sizeof *a->ov_order);
    a->ov_m = a->ov_order ? tui_fuzzy_filter(a->ov_filter, (const char *const *)a->ov_label, (size_t)a->ov_n, a->ov_order) : 0;
    a->ov_sel = a->ov_m && (size_t)a->ov_sel < a->ov_m ? a->ov_sel : 0;
}

/* The workspace as trust keys it: its real path. */
static const char *trust_path(const app *a, char *out) {
    return realpath(a->o->workspace, out) ? out : a->o->workspace;
}

typedef struct {
    char **p;
    size_t n;
} patterns;

static int add_pattern(void *ctx, const char *pattern) {
    patterns *l = ctx;
    char **g = realloc(l->p, (l->n + 1) * sizeof *g);
    if (g) {
        l->p = g;
        l->p[l->n++] = strdup(pattern);
    }
    return 0;
}

static void patterns_free(patterns *l) {
    for (size_t i = 0; i < l->n; i++) {
        free(l->p[i]);
    }
    free(l->p);
}

/* Whether PATTERN (a model, or with * and ?) names MODEL ("provider/id"); a
 * bare id matches in any provider. Case does not matter. */
static int scope_matches(const char *pattern, const char *model) {
    char p[256], m[256];
    const char *slash = strchr(model, '/');
    size_t i;
    for (i = 0; pattern[i] && i + 1 < sizeof p; i++) {
        p[i] = (char)tolower((unsigned char)pattern[i]);
    }
    p[i] = '\0';
    for (i = 0; model[i] && i + 1 < sizeof m; i++) {
        m[i] = (char)tolower((unsigned char)model[i]);
    }
    m[i] = '\0';
    return fnmatch(p, m, 0) == 0 || (slash && !strchr(p, '/') && fnmatch(p, m + (slash - model) + 1, 0) == 0);
}

static int count_pattern(void *ctx, const char *pattern) {
    (void)pattern;
    ++*(int *)ctx;
    return 0;
}

static void settings_open(app *a, int sel) {
    char label[320], *v;
    int scoped = 0;
    ov_open(a, OV_SETTINGS, "Settings  (up/down \xc2\xb7 enter: change \xc2\xb7 esc: close)",
            "Kept in ~/.pic/pic.sqlite; a new request picks them up.");
    (void)snprintf(label, sizeof label, "%-26s %s", "Default model", a->default_model);
    ov_add(a, label, "defaultModel", 0);
    v = pic_setting("defaultThinkingLevel");
    (void)snprintf(label, sizeof label, "%-26s %s", "Default thinking level", pic_thinking_index(v) >= 0 ? v : "medium");
    free(v);
    ov_add(a, label, "defaultThinkingLevel", 0);
    v = pic_setting("piSessionFiles");
    (void)snprintf(label, sizeof label, "%-26s %s", "Pi session files", v && strcmp(v, "1") == 0 ? "on" : "off");
    free(v);
    ov_add(a, label, "piSessionFiles", 0);
    (void)snprintf(label, sizeof label, "%-26s %s", "Hide thinking", a->hide_thinking ? "on" : "off");
    ov_add(a, label, "hideThinking", 0);
    (void)pic_scoped_each(count_pattern, &scoped);
    if (scoped) {
        (void)snprintf(label, sizeof label, "%-26s %d patterns", "Scoped models (Ctrl+P)", scoped);
    } else {
        (void)snprintf(label, sizeof label, "%-26s every model with a key", "Scoped models (Ctrl+P)");
    }
    ov_add(a, label, "scopedModels", 0);
    ov_refilter(a);
    a->ov_sel = sel;
}

static void scoped_open(app *a) {
    patterns pl = {NULL, 0};
    load_models(a);
    ov_open(a, OV_SCOPED, "Scoped models for Ctrl+P  (type to filter \xc2\xb7 enter: toggle \xc2\xb7 ctrl+s: save \xc2\xb7 esc)",
            "With none chosen, Ctrl+P cycles every model that has a key.");
    (void)pic_scoped_each(add_pattern, &pl);
    for (int i = 0; i < a->nmodels; i++) {
        const char *m = a->mp_models[i], *slash = strchr(m, '/');
        char label[320], provider[64];
        int on = 0;
        for (size_t j = 0; j < pl.n; j++) {
            on |= scope_matches(pl.p[j], m);
        }
        (void)snprintf(provider, sizeof provider, "%.*s", slash ? (int)(slash - m) : 0, m);
        (void)snprintf(label, sizeof label, "%s  [%s]", slash ? slash + 1 : m, provider);
        ov_add(a, label, m, on);
    }
    patterns_free(&pl);
    ov_refilter(a);
}

static void scoped_save(app *a) {
    const char **list = malloc(((size_t)a->ov_n + 1) * sizeof *list);
    size_t n = 0;
    for (int i = 0; list && i < a->ov_n; i++) {
        if (a->ov_on[i]) {
            list[n++] = a->ov_id[i];
        }
    }
    /* Everything or nothing chosen is no scope at all. */
    if (list && pic_scoped_set(list, n == (size_t)a->ov_n ? 0 : n) == 0) {
        if (n == 0 || n == (size_t)a->ov_n) {
            notice(a, DIM, "no scope: Ctrl+P cycles every model with a key");
        } else {
            notice(a, DIM, "Ctrl+P cycles %zu models", n);
        }
    } else {
        notice(a, RED, "could not save the scoped models");
    }
    free(list);
    ov_free(a);
}

static void thinking_open(app *a) {
    ensure_level(a);
    if (a->nlvl <= 1) {
        notice(a, DIM, "%s does not support thinking levels", a->model);
        return;
    }
    ov_open(a, OV_THINKING, "Thinking level  (up/down \xc2\xb7 enter: use \xc2\xb7 esc)", "For this session; /settings sets the default.");
    for (int i = 0; i < a->nlvl; i++) {
        ov_add(a, a->lvls[i], a->lvls[i], strcmp(a->lvls[i], a->level) == 0);
    }
    ov_refilter(a);
    for (int i = 0; i < a->nlvl; i++) {
        a->ov_sel = a->ov_on[i] ? i : a->ov_sel;
    }
}

static void tree_open(app *a) {
    const char *args[] = {"tree", "--json", a->conversation, NULL};
    char *out = NULL;
    int active = 0;
    if (run_sync(a, args, &out) != 0 || !out || !*out) {
        free(out);
        notice(a, DIM, "no conversation tree yet");
        return;
    }
    ov_open(a, OV_TREE, "Conversation tree  (type to filter \xc2\xb7 enter: continue from there \xc2\xb7 esc)",
            "\xe2\x80\xa2 is the path you are on; indented rows are branches; [id] is a conversation that ends there.");
    for (char *line = out, *nl; *line; line = nl ? nl + 1 : line + strlen(line)) {
        char *end, *indent, *act, *text, *sessions, label[512], id[160];
        int n;
        nl = strchr(line, '\n');
        if (nl) {
            *nl = '\0';
        }
        end = jget(a, line, "$.end");
        indent = jget(a, line, "$.indent");
        act = jget(a, line, "$.active");
        text = jget(a, line, "$.text");
        sessions = jget(a, line, "$.sessions");
        if (end && text) {
            int depth = indent ? atoi(indent) : 0;
            size_t first = strcspn(text, "\n");
            n = snprintf(label, sizeof label, "%*s%s %.*s", depth * 2 > 20 ? 20 : depth * 2, "",
                         act && strcmp(act, "1") == 0 ? "\xe2\x80\xa2" : " ", (int)(first > 100 ? 100 : first), text);
            if (sessions && n > 0 && (size_t)n < sizeof label) {
                (void)snprintf(label + n, sizeof label - (size_t)n, "  [%s]", sessions);
            }
            (void)snprintf(id, sizeof id, "%s %s", end, sessions ? sessions : "");
            ov_add(a, label, id, 0);
            if (act && strcmp(act, "1") == 0) {
                active = a->ov_n - 1;
            }
        }
        free(end);
        free(indent);
        free(act);
        free(text);
        free(sessions);
        if (!nl) {
            break;
        }
    }
    free(out);
    ov_refilter(a);
    a->ov_sel = active < (int)a->ov_m ? active : 0;
}

/* Enter on a request: continue from the end of it, in the conversation that
 * already ends there, or in a new fork of this one (Pi's /tree switches the
 * leaf; pic's conversations are paths, so the fork is the new leaf). */
static void tree_enter(app *a) {
    char *id = strdup(a->ov_id[a->ov_order[a->ov_sel]]), *space;
    const char *args[5];
    char *out = NULL;
    ov_free(a);
    if (!id) {
        return;
    }
    space = strchr(id, ' ');
    *space = '\0';
    if (space[1]) {
        char *sess = strdup(space + 1), *comma = strchr(sess, ',');
        if (comma) {
            *comma = '\0';
        }
        if (strcmp(sess, a->conversation) == 0) {
            notice(a, DIM, "already on %s", sess);
        } else {
            resume(a, sess);
        }
        free(sess);
    } else {
        args[0] = "fork";
        args[1] = a->conversation;
        args[2] = "--at";
        args[3] = id;
        args[4] = NULL;
        if (run_sync(a, args, &out) == 0 && out) {
            out[strcspn(out, "\n")] = '\0';
            notice(a, DIM, "\xe2\x94\x80 branched: now in %s \xe2\x94\x80", out);
            resume(a, out);
        }
        free(out);
    }
    free(id);
}

static void trust_open(app *a) {
    char real[PATH_MAX], hint[PATH_MAX + 64];
    int saved = pic_trust_get(trust_path(a, real));
    (void)snprintf(hint, sizeof hint, "%s \xe2\x80\x94 saved decision: %s", real, saved < 0 ? "none" : saved ? "trusted" : "untrusted");
    ov_open(a, OV_TRUST, "Workspace trust  (up/down \xc2\xb7 enter: save \xc2\xb7 esc)", hint);
    ov_add(a, "Trust this workspace", "yes", saved == 1);
    ov_add(a, "Do not trust this workspace", "no", saved == 0);
    ov_refilter(a);
    a->ov_sel = saved == 0;
}

static void trust_save(app *a, int trusted) {
    char real[PATH_MAX];
    if (pic_trust_set(trust_path(a, real), trusted) == 0) {
        notice(a, DIM, "saved trust decision: %s (%s)", trusted ? "trusted" : "untrusted", real);
    } else {
        notice(a, RED, "could not save the trust decision");
    }
}

/* Pipes INPUT to the command ARGV (found on PATH); its stdout in *out. 0 when
 * it ran and exited 0. */
static int run_piped(const char *const *argv, const char *input, char **out) {
    int in[2], o[2];
    pid_t pid;
    text got = {NULL, 0, 0};
    size_t sent = 0, total = strlen(input);
    int status = 0;
    *out = NULL;
    if (pipe(in) != 0) {
        return -1;
    }
    if (pipe(o) != 0) {
        close(in[0]);
        close(in[1]);
        return -1;
    }
    pid = fork();
    if (pid == 0) {
        int null = open("/dev/null", O_WRONLY);
        (void)dup2(in[0], STDIN_FILENO);
        (void)dup2(o[1], STDOUT_FILENO);
        if (null >= 0) {
            (void)dup2(null, STDERR_FILENO);
        }
        close(in[0]);
        close(in[1]);
        close(o[0]);
        close(o[1]);
        (void)signal(SIGPIPE, SIG_DFL);
        execvp(argv[0], (char *const *)(void *)(uintptr_t)argv);
        _exit(127);
    }
    close(in[0]);
    close(o[1]);
    if (pid < 0) {
        close(in[1]);
        close(o[0]);
        return -1;
    }
    (void)fcntl(in[1], F_SETFL, fcntl(in[1], F_GETFL) | O_NONBLOCK);
    for (int in_open = 1, out_open = 1; in_open || out_open;) {
        struct pollfd p[2] = {{in_open ? in[1] : -1, POLLOUT, 0}, {out_open ? o[0] : -1, POLLIN, 0}};
        (void)poll(p, 2, 200);
        if (in_open && (p[0].revents & (POLLOUT | POLLERR | POLLHUP))) {
            ssize_t w = sent < total ? write(in[1], input + sent, total - sent) : 0;
            if (w > 0) {
                sent += (size_t)w;
            }
            if (sent >= total || (w < 0 && errno != EAGAIN && errno != EINTR)) {
                close(in[1]);
                in_open = 0;
            }
        }
        if (out_open && (p[1].revents & (POLLIN | POLLHUP | POLLERR))) {
            char b[4096];
            ssize_t r = read(o[0], b, sizeof b);
            if (r > 0) {
                (void)text_add(&got, b, (size_t)r);
            } else if (r == 0 || (errno != EAGAIN && errno != EINTR)) {
                close(o[0]);
                out_open = 0;
            }
        }
    }
    while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {
    }
    *out = got.buf ? got.buf : strdup("");
    return WIFEXITED(status) && WEXITSTATUS(status) == 0 ? 0 : -1;
}

/* /share: the page goes to a secret gist, after a yes. */
static void share_confirm(app *a) {
    const char *args[] = {"export", "--html", a->conversation, "-", NULL};
    char *html = NULL;
    if (run_sync(a, args, &html) != 0 || !html || !*html) {
        free(html);
        notice(a, RED, "could not build the page to share");
        return;
    }
    ov_open(a, OV_SHARE, "Share this conversation as a secret GitHub gist?  (y/N)",
            "The whole conversation leaves this machine, as one HTML page, through the gh command. Nothing is sent unless you say yes.");
    ov_add(a, "No, keep it here", "no", 0);
    ov_add(a, "Yes, create the gist", "yes", 0);
    ov_refilter(a);
    a->ov_data = html;
}

static void share_run(app *a) {
    const char *argv[] = {"gh", "gist", "create", "-", NULL};
    char *html = a->ov_data, *out = NULL;
    a->ov_data = NULL;
    ov_free(a);
    if (run_piped(argv, html, &out) == 0 && out && *out) {
        out[strcspn(out, "\n")] = '\0';
        notice(a, DIM, "shared as a secret gist (only people with the link can open it): %s", out);
    } else {
        notice(a, RED, "gh could not create the gist (is gh installed and logged in?)");
    }
    free(out);
    free(html);
}

/* Enter on the chosen row. */
static void ov_enter(app *a) {
    int row = a->ov_m ? (int)a->ov_order[a->ov_sel] : -1, sel = a->ov_sel;
    char id[200];
    if (row < 0) {
        return;
    }
    (void)snprintf(id, sizeof id, "%s", a->ov_id[row]);
    switch (a->ov) {
    case OV_SETTINGS:
        if (strcmp(id, "defaultModel") == 0) {
            ov_free(a);
            notice(a, DIM, "pick a model; ctrl+s in the picker saves it as the default");
            open_models(a, NULL);
            return;
        } else if (strcmp(id, "defaultThinkingLevel") == 0) {
            char *v = pic_setting("defaultThinkingLevel");
            int at = pic_thinking_index(v) >= 0 ? pic_thinking_index(v) : pic_thinking_index("medium");
            free(v);
            (void)pic_setting_set("defaultThinkingLevel", pic_thinking_names[(at + 1) % PIC_THINKING_LEVELS]);
        } else if (strcmp(id, "piSessionFiles") == 0) {
            char *v = pic_setting("piSessionFiles");
            (void)pic_setting_set("piSessionFiles", v && strcmp(v, "1") == 0 ? "0" : "1");
            free(v);
        } else if (strcmp(id, "hideThinking") == 0) {
            a->hide_thinking = !a->hide_thinking;
            (void)pic_setting_set("hideThinking", a->hide_thinking ? "true" : "false");
        } else if (strcmp(id, "scopedModels") == 0) {
            scoped_open(a);
            return;
        }
        a->lvl_for[0] = '\0';
        settings_open(a, sel);
        break;
    case OV_SCOPED:
        a->ov_on[row] = (unsigned char)!a->ov_on[row];
        break;
    case OV_THINKING:
        ov_free(a);
        set_level(a, id);
        break;
    case OV_TREE:
        tree_enter(a);
        break;
    case OV_TRUST:
        ov_free(a);
        trust_save(a, strcmp(id, "yes") == 0);
        break;
    default: /* OV_SHARE */
        if (strcmp(id, "yes") == 0) {
            share_run(a);
        } else {
            ov_free(a);
            notice(a, DIM, "not shared");
        }
        break;
    }
}

static void overlay_lines(app *a, tui_lines *tail) {
    char line[1024];
    int first = a->ov_sel < 10 ? 0 : a->ov_sel - 9;
    add_fit(tail, BOLD, a->ov_title, a->cols);
    if (ov_filterable(a)) {
        (void)snprintf(line, sizeof line, "> %s", a->ov_filter);
        add_fit(tail, "", line, a->cols);
    }
    for (int r = 0; r < 10 && first + r < (int)a->ov_m; r++) {
        int i = (int)a->ov_order[first + r], sel = first + r == a->ov_sel;
        const char *mark = a->ov == OV_SCOPED ? (a->ov_on[i] ? "[x] " : "[ ] ")
                           : (a->ov == OV_THINKING || a->ov == OV_TRUST) ? (a->ov_on[i] ? "\xe2\x9c\x93 " : "  ")
                                                                         : "";
        (void)snprintf(line, sizeof line, "%s %s%s", sel ? "\xe2\x86\x92" : " ", mark, a->ov_label[i]);
        add_fit(tail, sel ? CYAN : "", line, a->cols);
    }
    if (a->ov_m == 0) {
        add_fit(tail, DIM, a->ov_n ? "  nothing matches" : "  nothing to show", a->cols);
    } else if (a->ov_m > 10) {
        (void)snprintf(line, sizeof line, "  (%d/%zu)", a->ov_sel + 1, a->ov_m);
        add_fit(tail, DIM, line, a->cols);
    }
    add_fit(tail, DIM, a->ov_hint, a->cols);
}

static void overlay_key(app *a, const tui_key *k) {
    size_t len = strlen(a->ov_filter);
    switch (k->kind) {
    case TUI_KEY_UP:
        a->ov_sel = a->ov_m ? (a->ov_sel + (int)a->ov_m - 1) % (int)a->ov_m : 0;
        break;
    case TUI_KEY_DOWN:
        a->ov_sel = a->ov_m ? (a->ov_sel + 1) % (int)a->ov_m : 0;
        break;
    case TUI_KEY_PAGEUP:
        a->ov_sel = a->ov_sel > 10 ? a->ov_sel - 10 : 0;
        break;
    case TUI_KEY_PAGEDOWN:
        a->ov_sel = a->ov_m ? (a->ov_sel + 10 < (int)a->ov_m ? a->ov_sel + 10 : (int)a->ov_m - 1) : 0;
        break;
    case TUI_KEY_ENTER:
        ov_enter(a);
        break;
    case TUI_KEY_CTRL_S:
        if (a->ov == OV_SCOPED) {
            scoped_save(a);
        }
        break;
    case TUI_KEY_ESC:
    case TUI_KEY_CTRL_C:
        ov_free(a);
        break;
    case TUI_KEY_BACKSPACE:
        if (ov_filterable(a)) {
            while (len > 0 && ((unsigned char)a->ov_filter[len - 1] & 0xC0) == 0x80) {
                len--;
            }
            if (len > 0) {
                a->ov_filter[len - 1] = '\0';
            }
            ov_refilter(a);
        }
        break;
    case TUI_KEY_CHAR:
        if (a->ov == OV_SHARE) { /* y / N */
            if (k->text[0] == 'y' || k->text[0] == 'Y') {
                share_run(a);
            } else if (k->text[0] == 'n' || k->text[0] == 'N') {
                ov_free(a);
                notice(a, DIM, "not shared");
            }
        } else if (a->ov == OV_SCOPED && k->text[0] == ' ' && a->ov_m) {
            a->ov_on[a->ov_order[a->ov_sel]] = (unsigned char)!a->ov_on[a->ov_order[a->ov_sel]];
        } else if (ov_filterable(a) && len + strlen(k->text) < sizeof a->ov_filter) {
            memcpy(a->ov_filter + len, k->text, strlen(k->text) + 1);
            ov_refilter(a);
        }
        break;
    default:
        break;
    }
}

/* Ctrl+P: the next model. With a scope (/scoped-models) that is the next
 * one of it, in its patterns' order (a wildcard's matches alphabetically);
 * otherwise 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) {
    patterns pl = {NULL, 0};
    int *list = NULL, n = 0, at = -1;
    load_models(a);
    (void)pic_scoped_each(add_pattern, &pl);
    list = malloc(((size_t)a->nmodels + 1) * sizeof *list);
    for (int i = 0; list && pl.n == 0 && i < a->nmodels; i++) {
        list[n++] = i;
    }
    for (size_t j = 0; list && j < pl.n; j++) {
        int from = n;
        for (int i = 0; i < a->nmodels; i++) {
            int seen = 0;
            for (int k = 0; k < n; k++) {
                seen |= list[k] == i;
            }
            if (!seen && scope_matches(pl.p[j], a->mp_models[i])) {
                int p = n++;
                while (p > from && strcmp(a->mp_models[list[p - 1]], a->mp_models[i]) > 0) {
                    list[p] = list[p - 1];
                    p--;
                }
                list[p] = i;
            }
        }
    }
    for (int k = 0; k < n; k++) {
        at = strcmp(a->mp_models[list[k]], a->model) == 0 ? k : at;
    }
    if (n < 2) {
        notice(a, DIM, pl.n ? "only one model in the scope (/scoped-models changes it)" : "only one model available");
    } else {
        use_model(a, list[(at + 1) % n], 0);
    }
    free(list);
    patterns_free(&pl);
}

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

static const struct {
    const char *name, *hint, *what;
} commands[] = {
    {"settings", "", "open the settings menu"},
    {"model", "[provider/model]", "select a model"},
    {"scoped-models", "", "choose the models Ctrl+P cycles"},
    {"thinking", "[level]", "set the thinking level"},
    {"tree", "", "navigate the conversation tree (switch branches)"},
    {"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", "[FILE.html | DIR]", "write this conversation as a web page (or Pi session files into DIR)"},
    {"import", "FILE", "import a Pi session file as a conversation"},
    {"share", "", "share this conversation as a secret gist"},
    {"reload", "", "reload project instructions and the model catalog"},
    {"trust", "[yes|no]", "save the workspace trust decision"},
    {"changelog", "", "show what changed"},
    {"bug", "TEXT", "record a bug report (kept locally, sent nowhere)"},
    {"login", "", "configure provider authentication"},
    {"logout", "", "remove provider authentication"},
    {"hotkeys", "", "show keyboard shortcuts"},
    {"quit", "", "quit pic"},
};
#define NCOMMANDS (sizeof commands / sizeof commands[0])
#define MENU_ROWS 5

static int is_builtin(const char *name, size_t len) {
    if (len == 4 && strncmp(name, "exit", 4) == 0) {
        return 1;
    }
    for (size_t i = 0; i < NCOMMANDS; i++) {
        if (strlen(commands[i].name) == len && strncmp(commands[i].name, name, len) == 0) {
            return 1;
        }
    }
    return 0;
}

/* The template LINE ("/name ARGS") calls, unless a built-in command has the name. */
static const pic_prompt *template_for(const app *a, const char *line) {
    size_t len;
    if (line[0] != '/') {
        return NULL;
    }
    len = strcspn(line + 1, " \t\r\n");
    if (!len || is_builtin(line + 1, len)) {
        return NULL;
    }
    for (size_t i = 0; i < a->tpl.n; i++) {
        if (strlen(a->tpl.v[i].name) == len && strncmp(a->tpl.v[i].name, line + 1, len) == 0) {
            return &a->tpl.v[i];
        }
    }
    return NULL;
}

/* (Re)reads the templates: the user's, and the workspace's when it is trusted. */
static void load_templates(app *a) {
    char real[PATH_MAX];
    pic_prompts_free(&a->tpl);
    if (pic_prompts_load(&a->tpl, a->o->workspace, pic_trust_get(trust_path(a, real)) == 1) != 0) {
        notice(a, RED, "could not read the prompt templates");
    }
}

/* 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;
    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 = malloc((NCOMMANDS + a->tpl.n) * sizeof *names);
        size_t *ord = malloc((NCOMMANDS + a->tpl.n) * sizeof *ord);
        char query[128];
        size_t shown = 0;
        if (!names || !ord) {
            free(names);
            free(ord);
            return 0;
        }
        (void)snprintf(query, sizeof query, "%s", s + 1);
        for (size_t i = 0; i < NCOMMANDS; i++) {
            names[i] = commands[i].name;
        }
        for (size_t i = 0; i < a->tpl.n; i++) { /* a built-in of the same name hides the template */
            names[NCOMMANDS + i] = is_builtin(a->tpl.v[i].name, strlen(a->tpl.v[i].name)) ? "" : a->tpl.v[i].name;
        }
        n = tui_fuzzy_filter(query, names, NCOMMANDS + a->tpl.n, ord);
        for (size_t i = 0; i < n && shown < cap; i++) {
            const char *name, *hint, *what;
            if (ord[i] < NCOMMANDS) {
                name = commands[ord[i]].name, hint = commands[ord[i]].hint, what = commands[ord[i]].what;
            } else if (*names[ord[i]]) {
                const pic_prompt *tp = &a->tpl.v[ord[i] - NCOMMANDS];
                name = tp->name, hint = tp->hint, what = tp->description;
            } else {
                continue;
            }
            (void)snprintf(labels[shown], 256, "/%-13s %s%s%s", name, hint, *hint && *what ? " \xe2\x80\x94 " : "", what);
            (void)snprintf(values[shown], 256, "/%s", name);
            shown++;
        }
        free(names);
        free(ord);
        *is_command = 1;
        return shown;
    }
    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 && template_for(a, values[a->menu_sel]) && *template_for(a, values[a->menu_sel])->hint) {
            char v[260]; /* a template that takes arguments: complete it, the next Enter sends */
            (void)snprintf(v, sizeof v, "%s ", values[a->menu_sel]);
            tui_editor_set(a->ed, v);
            a->menu_sel = 0;
        } else 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, "/%-13s %-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 (strcmp(line, "/settings") == 0) {
        settings_open(a, 0);
    } else if (strcmp(line, "/scoped-models") == 0) {
        scoped_open(a);
    } else if (strcmp(line, "/thinking") == 0) {
        ensure_level(a);
        if (!*arg) {
            thinking_open(a);
        } else if (a->nlvl <= 1) {
            notice(a, DIM, "%s does not support thinking levels", a->model);
        } else {
            int ok = 0;
            for (int i = 0; i < a->nlvl; i++) {
                ok |= strcmp(a->lvls[i], arg) == 0;
            }
            if (ok) {
                set_level(a, arg);
            } else {
                text t = {NULL, 0, 0};
                for (int i = 0; i < a->nlvl; i++) {
                    (void)text_add(&t, i ? ", " : "", i ? 2 : 0);
                    (void)text_add(&t, a->lvls[i], strlen(a->lvls[i]));
                }
                notice(a, RED, "%s does not take thinking level %s (it takes: %s)", a->model, arg, t.buf ? t.buf : "");
                free(t.buf);
            }
        }
    } else if (strcmp(line, "/reload") == 0) {
        char *ins = pic_project_instructions(a->o->workspace), *def = pic_setting("defaultModel"), *hide = pic_setting("hideThinking");
        if (def && *def) {
            (void)snprintf(a->default_model, sizeof a->default_model, "%s", def);
        }
        a->hide_thinking = hide && strcmp(hide, "true") == 0;
        a->lvl_for[0] = '\0';
        load_models(a);
        load_templates(a);
        if (!a->refreshing) {
            const char *args[] = {"models", "--refresh", "--json", NULL};
            if (spawn(a, &a->refresh, args) == 0) {
                a->refreshing = 1;
            }
        }
        notice(a, DIM, "reloaded: %s; %zu prompt templates; %d models with a key (the catalog is refreshing in the background)",
               ins && *ins ? "project instructions found (every request reads them afresh)" : "no project instructions (AGENTS.md, CLAUDE.md)",
               a->tpl.n, a->nmodels);
        free(ins);
        free(def);
        free(hide);
    } else if (strcmp(line, "/trust") == 0) {
        if (*arg && strcmp(arg, "yes") != 0 && strcmp(arg, "no") != 0) {
            notice(a, RED, "/trust takes yes or no, or nothing to choose");
        } else if (*arg) {
            trust_save(a, strcmp(arg, "yes") == 0);
        } else {
            trust_open(a);
        }
    } else if (strcmp(line, "/import") == 0) {
        if (!*arg) {
            notice(a, RED, "/import needs the path of a Pi session file (.jsonl)");
        } else if (strcmp(arg, "-") == 0) {
            notice(a, RED, "the terminal interface reads the keyboard on stdin; run: pic import - < FILE");
        } else {
            const char *args[] = {"import", arg, NULL};
            if (run_sync(a, args, &out) == 0 && out) {
                out[strcspn(out, "\n")] = '\0';
                notice(a, DIM, "\xe2\x94\x80 imported %s as conversation %s (the text of its messages) \xe2\x94\x80", arg, out);
                resume(a, out);
            }
        }
    } else if (strcmp(line, "/changelog") == 0) {
        notice(a, DIM, "no changelog yet: pic does not ship one");
    } else if (strcmp(line, "/bug") == 0) {
        char real[PATH_MAX];
        long long id = *arg ? pic_bug_add(trust_path(a, real), a->conversation, a->model, arg) : -1;
        if (!*arg) {
            notice(a, RED, "/bug needs a description");
        } else if (id < 0) {
            notice(a, RED, "could not record the bug report");
        } else {
            notice(a, DIM, "bug %lld recorded in ~/.pic/pic.sqlite (table picu_bug); nothing was sent", id);
        }
    } else if (strcmp(line, "/login") == 0 || strcmp(line, "/logout") == 0) {
        notice(a, DIM, "%s is not available yet", line);
    } 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 ||
            strcmp(line, "/tree") == 0 || strcmp(line, "/share") == 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) {
        size_t n = strlen(arg);
        if (strcmp(arg, "-") == 0) {
            notice(a, RED, "the page would land in this terminal; run: pic export --html %s -", a->conversation);
        } else if (!*arg || (n > 5 && strcmp(arg + n - 5, ".html") == 0)) {
            char dflt[96];
            (void)snprintf(dflt, sizeof dflt, "pic-session-%s.html", a->conversation);
            const char *args[] = {"export", "--html", a->conversation, *arg ? arg : dflt, NULL};
            if (run_sync(a, args, &out) == 0) {
                notice(a, DIM, "written to %s as one self-contained web page", args[3]);
            }
        } else {
            const char *args[] = {"export", "--pi", arg, NULL};
            if (run_sync(a, args, &out) == 0) {
                notice(a, DIM, "written to %s as Pi session files (one per conversation)", arg);
            }
        }
    } else if (strcmp(line, "/tree") == 0) {
        tree_open(a);
    } else if (strcmp(line, "/share") == 0) {
        share_confirm(a);
    } 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 rows      ~/.pic/pic.sqlite (written after each "
               "request, for ctx)",
               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 && !template_for(a, msg)) {
        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->ov) {
        overlay_key(a, k);
        return;
    }
    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_BACKTAB: /* Pi's thinking level key */
        cycle_level(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;
    {
        char *hide = pic_setting("hideThinking");
        a.hide_thinking = hide && strcmp(hide, "true") == 0;
        free(hide);
    }
    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);
    load_templates(&a);
    (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[5]; /* stdin, wake, the request's two pipes, the catalog refresh */
        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);
    ov_free(&a);
    models_free(&a);
    free(a.last_reply);
    pic_prompts_free(&a.tpl);
    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;
}