Skip to content
pi-c Documentation
Login

Documentation

/* pic's terminal UI: the event loop, transcript, footer and commands.
 *
 * Output model: everything finished is committed once to the terminal's
 * scrollback (render.h); the live area at the bottom holds the reply being
 * streamed, a running tool call, the status line, queued messages, the
 * editor and the footer. A reply that fails mid-stream is only ever in the
 * live area, so dropping it leaves no trace. Requests run as a child
 * `pic --json --commands ... ask` (Pi's RPC command lines on its stdin: steer,
 * follow_up, clear_queue, abort; events on its stdout, notices on its stderr).
 * Esc sends abort; SIGINT, which pic also turns into a clean cancel, is the
 * fallback. A "!" command runs as `pic bash`, which journals it. */
#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 <time.h>
#include <unistd.h>

#include "cred.h"
#include "input.h"
#include "pic.h"
#include "platform.h"
#include "sqlite3.h"
#include "tui/editor.h"
#include "tui/remote.h"
#include "tui/atfile.h"
#include "tui/clipboard.h"
#include "tui/fuzzy.h"
#include "tui/markdown.h"
#include "tui/modelpanel.h"
#include "tui/panel.h"
#include "tui/render.h"
#include "tui/term.h"
#include "tui/theme.h"
#include "tui/themes.h"
#include "tui/transcript.h"
#include "tui/keymap.h"
#include "tui/tui.h"
#include "tui/view.h"
#include "tui/viewport.h"
#include "tui/width.h"

static void cl_proc_end(long long id, int exit_code, int sig);

/* A prompt template or skill as get_commands lists it. */
typedef struct {
    char *name, *description, *hint;
} tui_command;
typedef struct {
    tui_command *v;
    size_t n;
} tui_commands;

#define BOLD "\x1b[1m"
#define RESET "\x1b[0m"
/* Pi's theme tokens (tui/theme.h) where the colours used to be hard-coded. */
#define DIM tui_fg(TUI_T_DIM)
#define CYAN tui_fg(TUI_T_ACCENT)
#define GREEN tui_fg(TUI_T_SUCCESS)
#define RED tui_fg(TUI_T_ERROR)
#define YELLOW tui_fg(TUI_T_WARNING)
#define MAX_QUEUED 16

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

static int text_add(app_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(app_text *t) {
    t->len = 0;
    if (t->buf) {
        t->buf[0] = '\0';
    }
}

/* A call a codemode script made (its parentToolCallId is the block's): one line of the block. */
typedef struct {
    char id[128];
    char *what; /* the tool and its arguments, cut for the row */
    int state;
    long start_ms, ms;
} nestcall;

/* A tool call: shown as a block from its start until it is committed. */
typedef struct {
    char id[96], name[32];
    char *title, *diff, *output, *content; /* content: write's text, codemode's script */
    char *calls;                           /* codemode: its calls' lines, from nested */
    nestcall *nested;
    int nnested;
    int state;
    long start_ms, took_ms;
} toolblk;

/* A child pic process: a request (events) or a short command (output). */
typedef struct {
    pid_t pid;
    int in;       /* a request's command pipe (Pi's RPC lines); -1 when it takes none */
    int out, err; /* read ends; -1 once closed */
    app_text outbuf, errbuf;
    long long proc; /* its pic ps row; 0 when none */
} app_child;

/* A request child's row ends with it (pic ps). */
static void run_ended(app_child *c, int status) {
    if (c->proc > 0) {
        cl_proc_end(c->proc, WIFEXITED(status) ? WEXITSTATUS(status) : -1, WIFSIGNALED(status) ? WTERMSIG(status) : 0);
        c->proc = 0;
    }
}

typedef struct {
    const pic_tui_options *o;
    char model[160], conversation[64], name[128];
    char conv_title[192]; /* the conversation's title, as pic sessions shows it, when it has no name */
    int title_guess;      /* conv_title is the first prompt's line until the request ends and pic says */
    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 */
    app_child run;
    int working, interrupted, seen_end;
    app_text stream;          /* assistant text being streamed */
    app_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 */
    /* Tool calls of this reply, in order. A finished block stays here (live,
     * so ctrl+o can still expand it) until the next reply text or the end of
     * the request commits it; scrollback already printed cannot change. */
    toolblk *blocks;
    int nblocks;
    int retry_n, retry_max, retried; /* the running retry (attempt, of), and the last attempt run */
    long retry_delay, retry_at;      /* its delay (ms) and when it started */
    char branch[128];                /* the workspace's git branch, "" when none */
    int spin;
    /* tokens over this session of the UI */
    long long in, out, cache_read, cache_write, context;
    int expand_tools;
    /* Messages typed while a reply runs. Steering and follow-ups are the child's
     * (mirrored from its queue_update events, which is what is shown); queue holds
     * what it cannot take: /commands, and everything when it takes no commands. */
    char *steer_q[MAX_QUEUED], *follow_q[MAX_QUEUED];
    int nsteer, nfollow;
    char *sent_q[MAX_QUEUED]; /* sent over the pipe, not yet answered: lost if the child exits first */
    int nsent;
    char *queue[MAX_QUEUED];
    int nqueue;
    int skip_user;    /* the next user message event is the request's own, already shown */
    /* The continued conversation's request a crash left unfinished (its key),
     * offered to resume (Enter) or drop (Esc); "" when none. */
    char unfinished[96], unfinished_model[200];
    int resuming; /* the child finishes the unfinished request */
    /* The swap prompt: a reply was refused for its key (the child's
     * key_failure event) and its request left unfinished. pending: the event
     * came, the prompt shows once the child has gone; on: it is offered
     * (s, m, w, l, Esc, and Enter as for any unfinished request). */
    struct {
        int pending, on;
        char request[96], provider[PIC_CRED_PROVIDER_CAP], label[PIC_CRED_LABEL_CAP], other[PIC_CRED_LABEL_CAP], offers[8];
        int state, status;
        long long until;     /* a limit lifts (ms since the epoch) */
        long long wait_until; /* w: the request resumes then */
    } kp;
    /* The footer's key segment ("second") and warning, read now and then. */
    char key_seg[48], key_alert[96];
    long key_seg_at;
    /* --key: the label this run gives its provider's requests, and that
     * provider; a choice in /key or the swap prompt replaces it. */
    char key_run[PIC_CRED_LABEL_CAP], key_run_provider[PIC_CRED_PROVIDER_CAP];
    int compacting; /* the child is /compact's: it ends with no agent_end, its refusal on stderr */
    int finishing;    /* its last reply is in: the child is about to settle, so new messages wait for the next request */
    int clear_sent, clear_notice; /* a clear_queue is out; say what was restored when it answers */
    int abort_sent;   /* Esc sent abort over the pipe: SIGINT is the next rung */
    double cost;      /* the session's cost so far, when usage events carry one */
    int ctrl_c_armed; /* a second Ctrl-C quits */
    long d_at;        /* a Ctrl+D on an empty editor was pressed at this time (ms): a second within QUIT_WINDOW_MS quits */
    /* Ctrl+R: reverse search through the editor's history */
    struct {
        int on, fail; /* open; the query has no match (the last one shown stays) */
        char q[256];
        long at;      /* the history entry shown, -1: none */
    } hs;
    /* /resume picker, /trash's of deleted conversations (pick_trash: enter restores), and /archived's
     * of archived ones (pick_archived: a unarchives) */
    char **pick_ids, **pick_rows;
    char *pick_mark; /* rows marked with space, deleted together by d */
    int npick, pick_at, picking, pick_trash, pick_archived;
    char pick_msg[320];     /* what the last d or u did, under the picker's title */
    char **pick_undo;       /* what the last d deleted, for u */
    int npick_undo;
    /* the model picker */
    char **mp_models, **mp_names, **mp_search;
    char **mp_price;  /* "$3/$15", or "" */
    char **mp_status; /* the key's mark and where the list came from ("key refused", "from proxy"), or "" */
    char **mp_key;    /* the key the model uses ("second", "work by rule"), "" with no key */
    int *mp_avail;    /* its provider has a key */
    int *mp_warn;     /* that key failed: refused, out of credit or rate-limited */
    long *mp_window;
    size_t *mp_order, mp_n;
    int nmodels, mp_open, mp_sel;
    int mp_all; /* the list holds models with no key too (the picker's) */
    tui_mview mpv;   /* the picker's box or dock as last drawn (tui/modelpanel.h) */
    char *mp_recent[10]; /* the models used lately, the latest first */
    size_t mp_nrecent, mp_lead; /* how many; the suggestions' first rows: current, default, recent */
    int mp_remember; /* rememberModel as the picker opened: what Enter says it does */
    /* /model's "Add an endpoint": the form's step (EP_*), the field being typed, what was typed
     * before it, and the key while the store opens */
    int ep;
    char ep_field[1024], ep_name[40], ep_url[256], ep_key[1024], ep_err[256];
    size_t ep_len;
    int told_remember; /* the line saying new conversations start on the model has been shown */
    int told_model;    /* the line under the banner saying why this model has been shown */
    int kp_model; /* m at the swap prompt: the model chosen next takes the refused message */
    char *last_msg; /* the last message sent, for a refused one to go to another model */
    char mp_filter[128], default_model[160];
    app_child refresh; /* the background catalog refresh */
    int refreshing;
    app_child keychk; /* the background free check of keys: pic auth status --refresh */
    int keychk_on, keychk_more; /* running; an all-keys check wanted when it ends */
    long keychk_at, keychk_limit_ms; /* when it started; when to stop waiting for it */
    tui_commands skl; /* skills (names without "skill:"): /skill:name ARGS goes to the request as typed */
    tui_commands tpl; /* prompt templates: /name ARGS goes to the request as typed */
    /* the slash menu */
    int menu_sel;
    char menu_dismissed[512];
    /* the @file menu: the typed token it was listed for, and the list */
    char at_key[520];
    atfile_item at_items[5];
    size_t at_n;
    int at_valid;
    char *last_reply; /* for /copy and ctrl+x */
    int quit;
    int links;        /* TUI_LINKS_*: how the terminal shows links */
    int press_x, press_y; /* where the left button went down (fullscreen) */
    int link_x, link_y;   /* the last link click: where, and when (ms) */
    long link_at;
    char title[320];  /* the terminal title last written */
    long esc_at;      /* an Escape on an empty editor was pressed at this time (ms): a second one opens /tree */
    /* a "!" or "!!" command the user ran: its output is drawn live, then committed */
    struct {
        app_child c; /* pic bash: its events are the output so far, then Pi's bash response */
        int running, cancelled, no_context, kill_level, got_resp, exit_code, has_exit;
        char *cmd, *live, *final;
        long kill_at;
    } bash;
    /* 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;
    /* The settings panel (tui/panel.h): a layer of its own over whatever else is open, which it never
     * touches; the list as get_settings last answered, re-read now and then while open. back: the row a
     * picker opened from it was on, to come back to when that picker closes. */
    struct {
        int on;
        tui_panel p;
        tui_settings l;
        long at; /* the list was last asked for then (ms) */
        char back[64];
    } sp;
    /* /auth: every key and sign-in in the settings panel's frame (tui/panel.h), its rows built here from
     * what pic knows of each; rebuilt while open as checks answer. confirm: the row d asked to remove. */
    struct {
        int on;
        tui_panel p;
        tui_settings l;
        long at;
        char head[400], confirm[200];
        char bind[200], text[PIC_CRED_RULE_CAP]; /* b or e: the row being typed for, and what is typed */
        char mode;                                /* 'b' a pattern, 'e' an expiry */
        pic_cred_rule *rules;                     /* keyFor:PATTERN, read with the rows */
        int nrules;
    } au;
    /* /mcp: the MCP servers in the same frame, rows from get_mcp_servers; while busy, a `pic mcp list`
     * child connects each one and the rows are read again as it goes. confirm: the row d asked to
     * remove. */
    struct {
        int on, busy;
        tui_panel p;
        tui_settings l;
        long at;
        char head[300], confirm[200];
        app_child c;
    } mc;
    /* an overlay: /scoped-models, /thinking, /tree, /trust, /share, the theme picker */
    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; the login choice: its provider */
    /* /login in place: the step, its provider and method, the masked field, and the sign-in child */
    int lg, lg_oauth;
    char lg_provider[64], lg_field[2048], lg_key[1024], lg_pass[512];
    char lg_label[PIC_CRED_LABEL_CAP]; /* the swap prompt's l: the refused key's label, stored again under it; "": the provider's own */
    size_t lg_len;
    char lg_url[2048], lg_code[64], lg_msg[256], lg_err[256];
    long lg_cancel_ms; /* when Esc asked the sign-in to stop; -1 once it was killed */
    int lg_request, lg_after; /* the passphrase is for a held request (AFTER_*): lg_pending and its images */
    char *lg_pending;
    tui_attachment *lg_pending_img;
    size_t lg_pending_n;
    app_child lg_child;
    /* /rc: the phones paired through the relay, and a pairing in a child (pic remote pair --pipe) */
    tui_remote rc_info;
    app_child rc_child;
    int rc_pairing, rc_stage, rc_confirm, rc_ndev, rc_running;
    int rc_ssh;  /* /rc ssh: the ssh page, nothing of the relay */
    int rc_view; /* RC_MAIN, or RC_DEVICES or RC_QR behind their keys */
    int rc_direct; /* /rc devices or /rc qr: Esc there closes, rather than going back to /rc */
    int rc_copied; /* how the link reached a clipboard: COPY_* */
    int rc_auto; /* /rc with no phone paired went straight to pairing: Esc there closes */
    char rc_link[2048]; /* the phone page's address for this conversation, "" with no phone paired */
    long rc_cancel_ms;
    char rc_after;    /* the key that waits for the store's passphrase */
    char rc_url[1024], rc_name[80], rc_code[16], rc_note[300];
    char rc_dev[8][36], rc_devname[8][80], rc_devseen[8][40];
    /* pic remote, started here detached (/rc): restarted if it crashes while this runs */
    pid_t rcp_pid;
    int rcp_want, rcp_crashes;
    long rcp_restart_at, rc_status_at;
    char rc_state[64], rc_relay[256], rc_err[256], rc_agent[16];
    int rc_stale; /* the running pic remote runs an older pic than the one installed */
    int rc_on, rc_devices, rc_attempts;
    int rc_watch;           /* phones showing this conversation now (pic remote's status) */
    char rc_watch_name[48]; /* the first one's name */
    long rc_retry_ms;
    char rc_origin[8][48], rc_oname[8][80]; /* remote:DEVICE to the phone's name, for "from NAME:" */
    int rc_norigin;
    long rc_names_at;
    /* following this conversation while idle (pic attach): a request from elsewhere, a phone's,
     * shows here, and a message typed meanwhile goes to it through the inbox */
    app_child fw;
    int fw_on, ext_running;
    char fw_conv[64];
    long fw_retry_at;
    char *ext_sent[8]; /* steers sent to it from here, whose user message is not shown twice */
    /* loops, monitors and goals of this conversation, as get_wakes last said (its fire: true fires
     * what is due in the journal: this interface is one of the processes that keep time) */
    struct app_wake {
        char name[16], kind[12], state[12], why[160], prompt[96];
        long long every, due, fires, rounds, max_rounds;
        double cost;
        int late, waiting, asking;
    } wk[8];
    /* A newer pic installed over this one (up_tick): its file as it was at start, and the stamp last seen. */
    int ft_hit[6];        /* where the footer's model, thinking level and key were drawn (start, end columns; -1: not drawn) */
    int rc_x;             /* the footer's "/rc" starts at this column; -1: not drawn (a click there opens /rc) */
    char up_exe[PATH_MAX], up_stamp[128], up_seen[128];
    long up_next, up_since;
    long up_kick;         /* when pic update --auto is next started (monotonic ms) */
    int up_ready;         /* the notice is up, for good */
    int up_want;          /* /restart: 1 waits for the reply to end; the loop then quits and restarts */
    int restart;          /* the loop ended to start the new pic on this conversation */
    char wk_asked[8][16]; /* the wakes whose OK was asked for here already (OV_APPROVE) */
    char ask_shown[16][24];  /* the asks (get_asks) put to the person here already (OV_ASK) */
    char ask_kind[16];       /* the open OV_ASK's: confirm, select or input */
    long ask_at;             /* when the asks were read (monotonic ms) */
    int wk_n, wk_seen;    /* wk_seen: the list has been read once, so a change is news */
    long wk_at;           /* when it was read (monotonic ms) */
    long long wk_skew;    /* the wakes' clock less this monotonic one */
    char wk_conv[64];     /* the conversation it was read for */
    int next_sent;
    /* /tree: the entry chosen (and a conversation that ends there) while Pi's
     * "Summarize branch?" is asked; custom: the editor's next line is the
     * summary's instructions */
    char branch_at[32], branch_sess[64];
    int branch_custom;
    /* fullscreen (Pi's tuiMode and fullscreen* settings) */
    int copy_on_select;
    tui_wheel wheel;
    char flash[64];   /* a short confirmation in the status row ("Copied!") */
    long flash_until;
    /* the mouse: mouse_on is the setting or /mouse for this session; a right click releases it to the
     * terminal until the next key or focus-in (tui/term.h tracks it) */
    int mouse_on, mouse_released;
    const char *released_why; /* the status row while released; NULL: MOUSE_RELEASED */
    unsigned focus_in;   /* the focus-in reports seen */
    /* Pi's themes and keybindings (tui/theme.h, tui/keymap.h) */
    tui_themeset themes;
    char theme_cli[64];  /* --theme: for this run, until a theme is chosen in /settings */
    char theme_prev[64]; /* the theme before the picker previewed others */
    tui_keymap *km;
    char *startup_warn;  /* problems found loading them at start, shown once the header is */
    tui_transcript *tr;  /* what was committed, to draw again when Ctrl+O or Ctrl+T changes it */
    int last_blank;      /* the last line committed was empty */
    /* the terminal's answers (tui/term.h) */
    long probe_until;    /* replies are expected until then; 0 once DA1 came or the window closed */
    unsigned reply_seq;  /* the decoder's reply count last acted on */
    long turn_t0;        /* when the running request started */
    int done_kind;       /* the request ended waiting for the user: 1, or 2 when it failed; 0 otherwise */
} app;

/* How long a stopping request gets after SIGINT before SIGTERM, and after
 * that before SIGKILL. It normally exits at once; the margin is for a slow
 * disk or a loaded machine, where recording the cancellation can take
 * seconds and is worth waiting for. */
#define STOP_GRACE_MS 10000
/* Claude Code: Ctrl+D on an empty editor exits only when pressed twice within this long. */
#define QUIT_WINDOW_MS 800

enum { OV_NONE, OV_SCOPED, OV_THINKING, OV_TREE, OV_TRUST, OV_SHARE, OV_SUMMARY, OV_THEME, OV_FORK, OV_LOGIN, OV_LOGIN_PROVIDER,
       OV_REWIND, OV_REWIND_MODE, OV_REWIND_CONFIRM, OV_REMOTE, OV_WAKES, OV_APPROVE, OV_ASK };
/* /login's steps after the overlays: a key, the store's passphrase (new, and again), a sign-in. */
enum { LG_NONE, LG_KEY, LG_PASS, LG_PASS_NEW, LG_PASS_AGAIN, LG_WAIT, LG_OFFER };

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

static long now_ms(void) { return (long)(pic_platform_get()->mono_ns() / 1000000); }
static void key_footer(app *a);
static void up_restart_ask(app *a);
static void wk_mark(const app *a, char *out, size_t cap);
static const char *wk_word(const char *kind);
static const char *wk_Word(const char *kind);

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;
    }
}

/* With hooks configured: `pic hooks end other` with this interface's
 * PIC_HOOK_OWNER, made ready at start so stop_check runs it with
 * no allocation. */
static pic_host_exec stop_exec;

/* 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).
 * Nothing forks here: a crash can leave the allocator locked, and fork()
 * takes its locks. */
static void on_crash(int sig) {
    pid_t run = child_pid;
    if (run > 0) {
        (void)kill(run, SIGINT);
    }
    tui_term_restore();
    (void)signal(sig, SIG_DFL);
    (void)raise(sig);
}

/* Terminated or hung up: noted here, acted on by stop_check. On macOS a
 * fork() in a handler that interrupted malloc() crashes or deadlocks, and
 * ending the conversations forks. */
static volatile sig_atomic_t stop_signal;

static void on_stop(int sig) {
    stop_signal = sig;
    if (wake_pipe[1] >= 0) {
        ssize_t n = write(wake_pipe[1], "s", 1);
        (void)n;
    }
}

/* After a noted SIGTERM, SIGHUP or SIGQUIT: what on_crash does, and with
 * hooks a detached process ends the conversations (SessionEnd) once the
 * cancelled request has let the journal go; then pic dies of the signal. */
static void stop_check(void) {
    int sig = stop_signal;
    pid_t run = child_pid;
    if (!sig) {
        return;
    }
    if (run > 0) {
        (void)kill(run, SIGINT);
    }
    tui_term_restore();
    pic_host_exec_start(&stop_exec, run);
    (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 int jget_has(app *a, const char *doc, const char *path) {
    char *s = jget(a, doc, path);
    free(s);
    return s != NULL;
}

/* Whether DOC's PATH is the string WANT. */
static int jget_is(app *a, const char *doc, const char *path, const char *want) {
    char *s = jget(a, doc, path);
    int is = s && strcmp(s, want) == 0;
    free(s);
    return is;
}

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;
}

/* ---- asking: components and core state, through the command surface ----- */

/* The interface reaches components and the user's state only by asking
 * commands (pic_tui_options.ask, Pi's RPC shapes with pic's own commands), so
 * it stays a client: what it asks, any RPC client can ask. */
static const app *cl_app;
static sqlite3 *cl_db; /* JSON work on the answers */

static void cl_quote_to(sqlite3_str *t, const char *s) {
    sqlite3_str_appendchar(t, 1, '"');
    for (const unsigned char *p = (const unsigned char *)(s ? s : ""); *p; p++) {
        if (*p == '"' || *p == '\\') {
            sqlite3_str_appendchar(t, 1, '\\');
            sqlite3_str_appendchar(t, 1, (char)*p);
        } else if (*p < 0x20) {
            sqlite3_str_appendf(t, "\\u%04x", *p);
        } else {
            sqlite3_str_appendchar(t, 1, (char)*p);
        }
    }
    sqlite3_str_appendchar(t, 1, '"');
}

/* SQL over DOC (?1) and ARG (?2) giving one text value, malloc'd; NULL when none. */
static char *cl_sql(const char *sql, const char *doc, const char *arg) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (!cl_db && sqlite3_open(":memory:", &cl_db) != SQLITE_OK) {
        return NULL;
    }
    if (sqlite3_prepare_v2(cl_db, sql, -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, doc ? doc : "", -1, SQLITE_STATIC);
        if (sqlite3_bind_parameter_count(q) > 1) {
            sqlite3_bind_text(q, 2, arg ? arg : "", -1, SQLITE_STATIC);
        }
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* json_extract(DOC, PATH), malloc'd; NULL when absent or null. */
static char *cl_get(const char *doc, const char *path) {
    return cl_sql("SELECT CASE WHEN json_valid(?1) THEN json_extract(?1, ?2) END", doc, path);
}

/* Asks TYPE with MEMBERS (more JSON object members, or ""): the answer's
 * data (malloc'd JSON; "null" when it has none), or NULL when it failed (the
 * error in ERR when it is not NULL). */
static char *cl_ask(const char *type, const char *members, char *err, size_t errcap) {
    sqlite3_str *t = sqlite3_str_new(NULL);
    char *line, *res = NULL, *data = NULL, *ok;
    sqlite3_str_appendall(t, "{\"type\":");
    cl_quote_to(t, type);
    if (members && *members) {
        sqlite3_str_appendf(t, ",%s", members);
    }
    sqlite3_str_appendall(t, "}");
    line = sqlite3_str_finish(t);
    if (line && cl_app && cl_app->o->ask) {
        res = cl_app->o->ask(cl_app->conversation, cl_app->model, line);
    }
    sqlite3_free(line);
    ok = res ? cl_sql("SELECT json_extract(?1, '$.success')", res, NULL) : NULL;
    if (ok && strcmp(ok, "1") == 0) {
        data = cl_sql("SELECT coalesce(json_extract(?1, '$.data'), 'null')", res, NULL);
        data = data ? data : strdup("null");
    } else if (err && errcap) {
        char *e = res ? cl_get(res, "$.error") : NULL;
        (void)snprintf(err, errcap, "%s", e ? e : "pic could not answer");
        free(e);
    }
    free(ok);
    free(res);
    return data;
}

/* MEMBERS for cl_ask: "\"KEY\":VALUE" with VALUE quoted (NULL: null), malloc'd. */
static char *cl_member(const char *key, const char *value) {
    sqlite3_str *t = sqlite3_str_new(NULL);
    char *r, *out;
    cl_quote_to(t, key);
    sqlite3_str_appendchar(t, 1, ':');
    if (value) {
        cl_quote_to(t, value);
    } else {
        sqlite3_str_appendall(t, "null");
    }
    r = sqlite3_str_finish(t);
    out = r ? strdup(r) : NULL;
    sqlite3_free(r);
    return out;
}

/* Asks TYPE with up to three string fields (a NULL key ends them); the
 * answer's data, as cl_ask. */
static char *cl_ask3(const char *type, const char *k1, const char *v1, const char *k2, const char *v2, const char *k3,
                     const char *v3) {
    const char *k[3] = {k1, k2, k3}, *v[3] = {v1, v2, v3};
    sqlite3_str *t = sqlite3_str_new(NULL);
    char *members, *data;
    for (int i = 0; i < 3 && k[i]; i++) {
        char *m = cl_member(k[i], v[i]);
        sqlite3_str_appendf(t, "%s%s", i ? "," : "", m ? m : "");
        free(m);
    }
    members = sqlite3_str_finish(t);
    data = cl_ask(type, members ? members : "", NULL, 0);
    sqlite3_free(members);
    return data;
}

/* The answer's field at PATH, malloc'd; NULL when it failed or has none. */
static char *cl_field(const char *type, const char *k1, const char *v1, const char *path) {
    char *data = cl_ask3(type, k1, v1, NULL, NULL, NULL, NULL), *v = data ? cl_get(data, path) : NULL;
    free(data);
    return v;
}

/* A setting's value (malloc'd), or NULL when unset. */
static char *cl_setting(const char *key) { return cl_field("get_setting", "key", key, "$.value"); }

/* Saves KEY (VALUE NULL removes it). 0 or -1. */
static int cl_setting_set(const char *key, const char *value) {
    char *data = cl_ask3("set_setting", "key", key, "value", value, NULL, NULL);
    free(data);
    return data ? 0 : -1;
}

/* Whether PATH (a real path) is trusted: 1, 0, or -1 undecided. */
static int cl_trust_get(const char *path) {
    char *v = cl_field("get_trust", "path", path, "$.trusted");
    int t = v ? atoi(v) : -1;
    free(v);
    return t;
}

static int cl_trust_set(const char *path, int trusted) {
    char *data = cl_ask3("set_trust", "path", path, "trusted", trusted ? "1" : "0", NULL, NULL);
    free(data);
    return data ? 0 : -1;
}

/* Calls FN for each string of the array at PATH in the answer of TYPE (no fields), until it returns nonzero. */
static int cl_each(const char *type, const char *path, int (*fn)(void *ctx, const char *s), void *ctx) {
    char *data = cl_ask(type, "", NULL, 0);
    sqlite3_stmt *q = NULL;
    if (!data) {
        return -1;
    }
    if (cl_db && sqlite3_prepare_v2(cl_db, "SELECT value FROM json_each(?1, ?2) WHERE type = 'text'", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, data, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        while (sqlite3_step(q) == SQLITE_ROW && !fn(ctx, (const char *)sqlite3_column_text(q, 0))) {
        }
    }
    sqlite3_finalize(q);
    free(data);
    return 0;
}

/* Ctrl+P's scope, in cycling order. */
static int cl_scoped_each(int (*fn)(void *ctx, const char *pattern), void *ctx) {
    return cl_each("get_scoped_models", "$.patterns", fn, ctx);
}

/* Replaces the scope with PATTERNS (N 0 clears it). 0 or -1. */
static int cl_scoped_set(const char *const *patterns, size_t n) {
    sqlite3_str *t = sqlite3_str_new(NULL);
    char *members, *data;
    sqlite3_str_appendall(t, "\"patterns\":[");
    for (size_t i = 0; i < n; i++) {
        sqlite3_str_appendall(t, i ? "," : "");
        cl_quote_to(t, patterns[i]);
    }
    sqlite3_str_appendall(t, "]");
    members = sqlite3_str_finish(t);
    data = cl_ask("set_scoped_models", members ? members : "", NULL, 0);
    sqlite3_free(members);
    free(data);
    return data ? 0 : -1;
}

/* Keeps a bug report; its id, or -1. */
static long long cl_bug_add(const char *workspace, const char *conversation, const char *model, const char *description) {
    sqlite3_str *t = sqlite3_str_new(NULL);
    const char *k[4] = {"workspace", "session", "model", "description"}, *v[4] = {workspace, conversation, model, description};
    char *members, *data, *id;
    long long r;
    for (int i = 0; i < 4; i++) {
        char *m = cl_member(k[i], v[i]);
        sqlite3_str_appendf(t, "%s%s", i ? "," : "", m ? m : "");
        free(m);
    }
    members = sqlite3_str_finish(t);
    data = cl_ask("report_bug", members ? members : "", NULL, 0);
    sqlite3_free(members);
    id = data ? cl_get(data, "$.id") : NULL;
    r = id ? strtoll(id, NULL, 10) : -1;
    free(id);
    free(data);
    return r;
}

/* How many phones are paired for remote control. */
static int cl_remote_phones(void) {
    char *v = cl_field("get_remote_phones", NULL, NULL, "$.count");
    int n = v ? atoi(v) : 0;
    free(v);
    return n;
}

/* Whether hooks are configured for the workspace. */
static int cl_hooks_configured(void) {
    char *v = cl_field("get_hooks", NULL, NULL, "$.configured");
    int on = v && strcmp(v, "1") == 0;
    free(v);
    return on;
}

/* A process this interface started, recorded for pic ps under its
 * conversation: its id for cl_proc_end, or -1. */
static long long cl_proc_start(const char *kind, const char *command, long pid) {
    char members[512], *k = cl_member("kind", kind), *c = cl_member("command", command), *data, *id;
    long long r;
    (void)snprintf(members, sizeof members, "%s,%s,\"pid\":%ld,\"pgid\":%ld", k ? k : "\"kind\":\"\"",
                   c ? c : "\"command\":\"\"", pid, pid);
    free(k);
    free(c);
    data = cl_ask("proc_start", members, NULL, 0);
    id = data ? cl_get(data, "$.id") : NULL;
    r = id ? strtoll(id, NULL, 10) : -1;
    free(id);
    free(data);
    return r;
}

static void cl_proc_end(long long id, int exit_code, int sig) {
    char members[96], *data;
    (void)snprintf(members, sizeof members, "\"id\":%lld,\"exitCode\":%d,\"signal\":%d", id, exit_code, sig);
    data = cl_ask("proc_end", members, NULL, 0);
    free(data);
}

/* Pi's branchSummary.skipPrompt. */
static int cl_branch_skip_prompt(void) {
    char *v = cl_field("get_compaction_settings", NULL, NULL, "$.branchSummary.skipPrompt");
    int on = v && strcmp(v, "1") == 0;
    free(v);
    return on;
}

/* The manual's topic NAME as its file holds it (malloc'd), or NULL when there is no such topic. */
static char *cl_help_text(const char *name) { return cl_field("get_help", "topic", name, "$.text"); }

/* The manual's topic names joined by SEP (malloc'd), or NULL. */
static char *cl_help_topics(const char *sep) {
    char *data = cl_ask("get_help", "", NULL, 0), *v = data ? cl_sql("SELECT group_concat(value, ?2) FROM json_each(?1, '$.topics')", data, sep) : NULL;
    free(data);
    return v;
}

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

static void commit_lines(app *a, tui_lines *l) {
    (void)tui_transcript_lines(a->tr, (const char *const *)l->lines, l->n);
    (void)tui_render_commit(a->r, (const char *const *)l->lines, l->n);
    if (l->n) {
        a->last_blank = !*l->lines[l->n - 1];
    }
    tui_lines_clear(l);
}

/* Commits a tool call, a "!" command or thinking as an item Ctrl+O and Ctrl+T
 * draw again: its lines as they look now go to the screen. */
static void commit_drawn(app *a, tui_lines *l) {
    (void)tui_render_commit(a->r, (const char *const *)l->lines, l->n);
    if (l->n) {
        a->last_blank = !*l->lines[l->n - 1];
    }
    tui_lines_clear(l);
}

static void commit_tool(app *a, const tui_tool *t) {
    tui_lines l = {NULL, 0, 0};
    if (!a->last_blank) { /* Pi's spacer above a tool block */
        (void)tui_lines_add(&l, "", 0);
        commit_lines(a, &l);
    }
    (void)tui_transcript_tool(a->tr, t);
    (void)tui_tool_lines(t, a->expand_tools, a->cols > 2 ? (size_t)a->cols : 2, &l);
    commit_drawn(a, &l);
}

static void commit_bash(app *a, const tui_bash *b) {
    tui_lines l = {NULL, 0, 0};
    (void)tui_transcript_bash(a->tr, b);
    (void)tui_bash_lines(b, a->expand_tools, a->cols > 2 ? (size_t)a->cols : 2, &l);
    commit_drawn(a, &l);
}

/* Everything committed, drawn again with the toggles as they are now (Pi
 * re-renders every block on Ctrl+O and Ctrl+T). */
static void redraw_transcript(app *a) {
    tui_lines l = {NULL, 0, 0};
    if (tui_transcript_render(a->tr, a->expand_tools, a->hide_thinking, a->cols > 2 ? (size_t)a->cols : 2, &l) == 0) {
        (void)tui_render_replace(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++) {
        app_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 small[1024], *msg = small;
    va_list ap;
    int n;
    va_start(ap, fmt);
    n = vsnprintf(small, sizeof small, fmt, ap);
    va_end(ap);
    if (n >= (int)sizeof small && (msg = malloc((size_t)n + 1)) != NULL) { /* /hotkeys, /help: several kilobytes */
        va_start(ap, fmt);
        (void)vsnprintf(msg, (size_t)n + 1, fmt, ap);
        va_end(ap);
    }
    commit_text(a, style, msg ? msg : small);
    if (msg != small) {
        free(msg);
    }
}

/* A message the user sent, on Pi's user-message background. */
static void commit_user(app *a, const char *msg) {
    tui_lines l = {NULL, 0, 0};
    (void)tui_lines_add(&l, "", 0);
    (void)tui_user_message_lines(msg, a->cols > 2 ? (size_t)a->cols : 2, a->links, &l);
    (void)tui_lines_add(&l, "", 0);
    commit_lines(a, &l);
}

static void md_opts(const app *a, tui_md_opts *o) {
    o->base = NULL;
    o->links = a->links;
    o->preserve = 0;
}

/* The uncommitted part of the streamed reply as styled, wrapped lines. */
static void stream_lines(app *a, tui_lines *out) {
    tui_md_opts o;
    const char *s = a->stream.buf ? a->stream.buf + a->stream_off : "";
    md_opts(a, &o);
    (void)tui_markdown(s, strlen(s), a->cols > 1 ? (size_t)a->cols : 1, &o, out);
}

/* Commits the first finished block of the reply: up to its blank line. A block
 * too long to wait for (no blank line yet) goes a line at a time. 0 when there
 * is nothing finished. */
static int commit_head_line(app *a) {
    const char *s = a->stream.buf ? a->stream.buf + a->stream_off : "", *nl;
    size_t cols = a->cols > 1 ? (size_t)a->cols : 1, n = tui_markdown_block_len(s);
    tui_md_opts o;
    tui_lines l = {NULL, 0, 0};
    md_opts(a, &o);
    if (n) {
        (void)tui_markdown(s, n, cols, &o, &l);
        (void)tui_lines_add(&l, "", 0); /* the blank line between blocks */
        commit_lines(a, &l);
        a->stream_off += n;
        return 1;
    }
    if (!(nl = strchr(s, '\n')) || (!a->stream_fence && tui_markdown_table_open(s))) {
        return 0;
    }
    (void)tui_markdown_line(s, (size_t)(nl - s), &a->stream_fence, cols, &o, &l);
    commit_lines(a, &l);
    a->stream_off += (size_t)(nl - s) + 1;
    return 1;
}

/* Whether thinking is hidden, read from the saved setting (the settings
 * menu, Ctrl+T and other pics may change it at any time). */
static int thinking_hidden(app *a) {
    char *hide = cl_setting("hideThinking");
    a->hide_thinking = hide && strcmp(hide, "true") == 0;
    free(hide);
    return a->hide_thinking;
}

/* Commits the reply's thinking: Pi's thinking block, or its one-line marker
 * when hidden, after a blank line. */
static void commit_thinking(app *a) {
    if (a->thinking.len && a->thinking.buf[strspn(a->thinking.buf, " \t\r\n")]) {
        tui_lines l = {NULL, 0, 0};
        (void)tui_lines_add(&l, "", 0);
        commit_lines(a, &l);
        (void)tui_transcript_thinking(a->tr, a->thinking.buf);
        (void)tui_thinking_lines(a->thinking.buf, thinking_hidden(a), a->cols > 2 ? (size_t)a->cols : 2, &l);
        commit_drawn(a, &l);
        (void)tui_lines_add(&l, "", 0); /* Pi's spacer after a thinking run */
        commit_lines(a, &l);
    }
    text_clear(&a->thinking);
}

/* 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};
    commit_thinking(a);
    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) {
    app_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);
    if (pic_model_resolve(a->model, &m, err, sizeof err) == 0) {
        a->nlvl = pic_model_thinking_levels(&m, a->lvls);
        a->window = a->o->context_window >= 0 ? a->o->context_window : m.context_window; /* the footer's percentage before the first request */
    } else {
        a->nlvl = 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 = cl_setting(key);
    if (pic_thinking_index(saved) < 0) {
        free(saved);
        saved = cl_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_draw(app *a, int form, size_t width, size_t list, tui_lines *out, int *crow, int *ccol);
static size_t picker_box_list(app *a, size_t w, size_t h);
static void picker_key(app *a, const tui_key *k);
static void stg_open(app *a, const char *id);
static void stg_lines(app *a, tui_lines *tail, int *crow, int *ccol);
static void overlay_lines(app *a, tui_lines *tail);
static void login_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 void restore_texts(app *a, char *const *texts, int n);
static const tui_command *template_for(const app *a, const char *line);
static int skill_for(const app *a, const char *line);
static void pump_refresh(app *a);
static void pump_keychk(app *a);
static void app_models_free(app *a);
static void menu_lines(app *a, tui_lines *tail);
static void block_lines(const toolblk *b, int expanded, size_t cols, tui_lines *out);

/* Pi colours the editor's border by thinking level, and as bash mode while the line starts with "!". */
static const char *editor_border(app *a) {
    const char *cur = tui_editor_text(a->ed);
    if (cur[strspn(cur, " \t")] == '!') {
        return tui_fg(TUI_T_BASH_MODE);
    }
    ensure_level(a);
    return tui_fg(tui_thinking_token(a->nlvl > 1 ? a->level : "off"));
}

#ifdef __APPLE__
#define LINK_CLICK "Cmd-click"
#else
#define LINK_CLICK "Ctrl-click"
#endif
static int mouse_apply(app *a);
static void mouse_set(app *a, int on);
static void mouse_take_back(app *a);

/* The status row while a right click has handed the mouse to the terminal. */
#define MOUSE_RELEASED "mouse released: terminal menu, selection and " LINK_CLICK " work until a key"
/* Over ssh a link click releases the mouse so the next click is the local terminal's, which opens the link on the
 * user's computer (whose platform pic cannot see from here). */
#define MOUSE_RELEASED_LINK "Cmd- or Ctrl-click the link again to open it on this computer (copied)"

static void ep_lines(app *a, tui_lines *tail);

/* How often the open panel asks whether a setting changed (pic settings, a phone, another pic). */
#define STG_POLL_MS 500

/* The rows docked above the footer, or the panel's one line under STG_LINE_COLS x STG_LINE_ROWS. */
#define STG_LINE_COLS 40
#define STG_LINE_ROWS 8
#define STG_DOCK_LIST 10
/* It floats in fullscreen with this much room for the transcript, at most STG_BOX_COLS wide, a margin
 * of STG_BOX_MARGIN on each side, and a row above and below. */
#define STG_FLOAT_COLS 64
#define STG_FLOAT_ROWS 14
#define STG_BOX_COLS 72
#define STG_BOX_MARGIN 4

/* The model picker's box is at most this wide: its columns need more room than the settings. */
#define MP_BOX_COLS 100

/* The panel on screen: the settings panel over /auth over /mcp, or NULL when none is open. */
static tui_panel *stg_panel(app *a, tui_settings **l) {
    *l = a->sp.on ? &a->sp.l : a->au.on ? &a->au.l : &a->mc.l;
    return a->sp.on ? &a->sp.p : a->au.on ? &a->au.p : a->mc.on ? &a->mc.p : NULL;
}

/* The layer over everything, the settings panel or /auth (stg_panel) or else the model picker, as a box
 * over the transcript when it is open, the screen is fullscreen and the transcript has room for one above
 * a dock of DOCK rows: 1. Otherwise there is no box: 0. */
static int stg_float(app *a, int dock) {
    int area = a->rows - dock;
    tui_settings *pl;
    tui_panel *pp = stg_panel(a, &pl);
    if ((pp || a->mp_open) && tui_render_is_fullscreen(a->r) && a->cols >= STG_FLOAT_COLS && area >= STG_FLOAT_ROWS) {
        size_t w = (size_t)a->cols - 2 * STG_BOX_MARGIN, h = (size_t)area - 2;
        tui_lines box = {NULL, 0, 0};
        int r = -1, c = 0;
        if (pp) {
            size_t len = tui_panel_list_len(pp, pl);
            if (w > STG_BOX_COLS) {
                w = STG_BOX_COLS;
            }
            if (h > len + TUI_PANEL_CHROME) {
                h = len + TUI_PANEL_CHROME;
            }
            (void)tui_panel_lines(pp, pl, TUI_PANEL_BOX, w, h - TUI_PANEL_CHROME, &box, &r, &c);
        } else {
            if (w > MP_BOX_COLS) {
                w = MP_BOX_COLS;
            }
            picker_draw(a, TUI_PANEL_BOX, w, picker_box_list(a, w, h), &box, &r, &c);
        }
        (void)tui_render_box(a->r, (const char *const *)box.lines, box.n, w, r, c);
        tui_lines_clear(&box);
        return 1;
    }
    (void)tui_render_box(a->r, NULL, 0, 0, -1, 0);
    return 0;
}

/* The panel docked above the footer (regular mode, a small window), or its one line in a tiny one; the
 * cursor at line *crow (of tail), column *ccol. */
static void stg_lines(app *a, tui_lines *tail, int *crow, int *ccol) {
    size_t base = tail->n;
    int list = a->rows - 2 - (TUI_PANEL_CHROME - 1) - 1; /* the footer, the panel's own rows, a row to spare */
    int r = -1, c = 0;
    tui_settings *pl;
    tui_panel *pp = stg_panel(a, &pl);
    if (!pp) {
        return;
    }
    if (list > STG_DOCK_LIST) {
        list = STG_DOCK_LIST;
    }
    if (a->cols < STG_LINE_COLS || a->rows < STG_LINE_ROWS || list < 2) {
        (void)tui_panel_lines(pp, pl, TUI_PANEL_LINE, a->cols > 0 ? (size_t)a->cols : 1, 0, tail, &r, &c);
    } else {
        (void)tui_panel_lines(pp, pl, TUI_PANEL_DOCK, (size_t)a->cols, (size_t)list, tail, &r, &c);
    }
    *crow = r >= (int)base ? r : -1;
    *ccol = c;
}

/* The model picker docked above the footer, or its one line, as the settings panel's. */
static void picker_dock(app *a, tui_lines *tail, int *crow, int *ccol) {
    size_t base = tail->n, cols = a->cols > 0 ? (size_t)a->cols : 1, list;
    int r = -1, c = 0, room = a->rows - 2 - 1; /* the footer and a row to spare */
    /* the dock's own rows are the box's but its two borders, the box as wide as these columns' */
    list = room > 0 ? picker_box_list(a, cols + 3, (size_t)room + 2) : 1;
    if (list > STG_DOCK_LIST) {
        list = STG_DOCK_LIST;
    }
    if (a->cols < STG_LINE_COLS || a->rows < STG_LINE_ROWS || list < 2) {
        picker_draw(a, TUI_PANEL_LINE, cols, 0, tail, &r, &c);
    } else {
        picker_draw(a, TUI_PANEL_DOCK, cols, list, tail, &r, &c);
    }
    *crow = r >= (int)base ? r : -1;
    *ccol = c;
}

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], mdl[1024];
    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->lg) {
        login_lines(a, &tail);
    } else if (a->ep) {
        ep_lines(a, &tail);
    } else if (a->ov) {
        overlay_lines(a, &tail);
    } else if (a->picking) {
        add_fit(&tail, BOLD,
                a->pick_trash      ? "Deleted conversations (up/down, enter: restore, esc):"
                : a->pick_archived ? "Archived conversations (up/down, enter: resume, a: unarchive, esc):"
                                   : "Resume a conversation (up/down, enter, d: delete, a: archive, space: mark, esc):",
                a->cols);
        if (a->pick_msg[0]) {
            add_fit(&tail, YELLOW, a->pick_msg, 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 %s", at == a->pick_at ? ">" : " ",
                           a->pick_mark && a->pick_mark[at] ? "*" : " ", a->pick_rows[at]);
            add_fit(&tail, at == a->pick_at ? CYAN : "", line, a->cols);
        }
        if (a->npick > 12) { /* Pi's "(selected/total)" under a long list */
            (void)snprintf(line, sizeof line, "  (%d/%d)", a->pick_at + 1, a->npick);
            add_fit(&tail, DIM, line, a->cols);
        }
    } else {
        const char *bsgr = DIM, *bst = "";
        char bbuf[1024];
        if (a->flash[0] && now_ms() < a->flash_until) {
            bst = a->flash;
        } else if (a->mouse_released) {
            bst = a->released_why ? a->released_why : MOUSE_RELEASED;
        } else if (a->working) {
            char retry[160];
            if (a->retry_n > 0) {
                tui_retry_status(a->retry_n, a->retry_max, a->retry_delay, now_ms() - a->retry_at, retry, sizeof retry);
            }
            (void)snprintf(bbuf, sizeof bbuf, "%s %s", frames[a->spin % 10],
                           a->interrupted ? "Stopping\xe2\x80\xa6" : a->retry_n > 0 ? retry : a->status[0] ? a->status : "Working\xe2\x80\xa6 (esc to interrupt)");
            bst = bbuf;
            bsgr = a->retry_n > 0 || a->status[0] ? YELLOW : DIM;
        } else if (a->ext_running) { /* a request another pic runs: what typing and Esc do to it. Still, not
                                       * a spinner: this one redraws nothing while that request is quiet */
            bst = "\xe2\x97\x8f Running in another pic\xe2\x80\xa6 (type to steer, esc to stop)";
        } else if (a->status[0]) {
            bst = a->status;
            bsgr = YELLOW;
        }
        if (a->nsteer + a->nfollow + a->nqueue > 0) { /* Pi's pending-messages rows */
            (void)tui_lines_add(&tail, "", 0);
            for (int i = 0; i < a->nsteer; i++) {
                (void)snprintf(line, sizeof line, " Steering: %s", a->steer_q[i]);
                add_fit(&tail, DIM, line, a->cols);
            }
            for (int i = 0; i < a->nfollow; i++) {
                (void)snprintf(line, sizeof line, " Follow-up: %s", a->follow_q[i]);
                add_fit(&tail, DIM, line, a->cols);
            }
            for (int i = 0; i < a->nqueue; i++) {
                (void)snprintf(line, sizeof line, " Follow-up: %s", a->queue[i]);
                add_fit(&tail, DIM, line, a->cols);
            }
            add_fit(&tail, DIM, " \xe2\x86\xb3 alt+up to edit all queued messages", a->cols);
        }
        {
            size_t before, cols = a->cols > 2 ? (size_t)a->cols : 2;
            int er = 0, ec = 0;
            const char *bc = editor_border(a);
            /* Pi's editor: status in the top border; Claude Code's: the session's name at its right */
            (void)tui_border_line_titled(bc, bsgr, bst, a->name[0] ? a->name : a->conv_title, cols, &tail);
            before = tail.n;
            if (a->hs.on) { /* readline's prompt: the entry found, the query at the cursor */
                const char *pre = a->hs.fail ? "(failed reverse-i-search)`" : "(reverse-i-search)`";
                const char *m = a->hs.at >= 0 ? tui_editor_history_at(a->ed, (size_t)a->hs.at) : "";
                char row[1024];
                (void)snprintf(row, sizeof row, "%s%s': %.*s", pre, a->hs.q, (int)strcspn(m, "\n"), m);
                add_fit(&tail, "", row, (int)cols);
                crow = (int)before;
                ccol = (int)tui_width(pre, strlen(pre)) + (int)tui_width(a->hs.q, strlen(a->hs.q));
                if (ccol >= (int)cols) {
                    ccol = (int)cols - 1;
                }
            } else if (tui_editor_render(a->ed, cols, &tail, &er, &ec) == 0) {
                crow = (int)before + er;
                ccol = ec;
            }
            (void)tui_border_line_in(bc, NULL, "", cols, &tail);
        }
        menu_lines(a, &tail);
    }
    /* footer: where (cwd, branch, conversation), and "remote on" while pic remote is connected
     * (Claude Code's "/rc active"; left out when narrow); then tokens, context, model */
    {
        char watching[96];
        const char *mark = NULL;
        int rc_up = a->rc_on && strcmp(a->rc_state, "connected") == 0;
        int rc_show = (a->rc_on || a->rc_devices > 0) && a->cols >= 40; /* Claude Code's "/rc": green connected, dim otherwise */
        if (rc_up && a->rc_watch) { /* a phone has this conversation open */
            if (a->rc_watch == 1) {
                (void)snprintf(watching, sizeof watching, "%.40s watching", a->rc_watch_name);
            } else {
                (void)snprintf(watching, sizeof watching, "%d phones watching", a->rc_watch);
            }
            mark = watching;
        }
        char wakes[160], both[300];
        wk_mark(a, wakes, sizeof wakes);
        if (wakes[0]) { /* the loops, before remote control's mark */
            (void)snprintf(both, sizeof both, "%s%s%s", wakes, mark ? " \xc2\xb7 " : "", mark ? mark : "");
            mark = both;
        }
        int room = mark && a->cols >= 60 ? (int)strlen(mark) + 3 : 0;
        int rcw = rc_show ? 4 : 0;
        tui_footer_where(ws, home, a->branch, a->name[0] ? a->name : a->conv_title[0] ? a->conv_title : a->conversation[0] ? a->conversation : "new conversation",
                         a->cols - room - rcw > 0 ? (size_t)(a->cols - room - rcw) : 1, line, sizeof line);
        if (room) {
            size_t n = strlen(line);
            (void)snprintf(line + n, sizeof line - n, " \xc2\xb7 %s", mark);
        }
        a->rc_x = -1;
        if (rc_show) { /* "/rc" at the right edge of this row */
            app_text t = {NULL, 0, 0};
            size_t fit = tui_fit(line, strlen(line), (size_t)a->cols - 4), w = tui_width(line, fit);
            (void)text_add(&t, DIM, strlen(DIM));
            (void)text_add(&t, line, fit);
            for (size_t i = w; i + 3 < (size_t)a->cols; i++) {
                (void)text_add(&t, " ", 1);
            }
            (void)text_add(&t, RESET, strlen(RESET));
            (void)text_add(&t, rc_up ? GREEN : DIM, strlen(rc_up ? GREEN : DIM));
            (void)text_add(&t, "/rc", 3);
            (void)text_add(&t, RESET, strlen(RESET));
            a->rc_x = a->cols - 3;
            if (a->up_ready) {
                add_fit(&tail, GREEN, a->up_want ? "\xe2\x9c\x94 Update installed \xc2\xb7 restarting after this reply" : "\xe2\x9c\x94 Update installed \xc2\xb7 /restart to update", a->cols);
            }
            (void)tui_lines_add(&tail, t.buf, t.len);
            free(t.buf);
            goto footer_done;
        }
    }
    if (a->up_ready) { /* Claude Code's "Update installed", above where this is */
        add_fit(&tail, GREEN, a->up_want ? "\xe2\x9c\x94 Update installed \xc2\xb7 restarting after this reply" : "\xe2\x9c\x94 Update installed \xc2\xb7 /restart to update", a->cols);
    }
    add_fit(&tail, DIM, line, a->cols);
footer_done:
    ensure_level(a);
    {
        tui_footer f = {a->in, a->out, a->cache_read, a->cache_write, a->context, a->window, a->model,
                        a->nlvl > 1 ? a->level : "", a->expand_tools, a->cost, NULL, NULL, a->ft_hit};
        key_footer(a);
        f.key = a->key_seg;
        f.alert = a->key_alert;
        tui_footer_stats(&f, a->cols > 0 ? (size_t)a->cols : 1, mdl, sizeof mdl);
        (void)tui_lines_add(&tail, mdl, strlen(mdl));
    }
    /* The settings panel: a box over the transcript where there is room, everything above it as it
     * was; otherwise it takes the place of what is above the footer. */
    if (!stg_float(a, (int)tail.n) && (a->sp.on || a->au.on || a->mc.on || a->mp_open)) {
        tui_lines dock = tail;
        tail = (tui_lines){NULL, 0, 0};
        crow = -1;
        if (a->sp.on || a->au.on || a->mc.on) {
            stg_lines(a, &tail, &crow, &ccol);
        } else {
            picker_dock(a, &tail, &crow, &ccol);
        }
        for (size_t i = dock.n >= 2 ? dock.n - 2 : 0; i < dock.n; i++) {
            (void)tui_lines_add(&tail, dock.lines[i], strlen(dock.lines[i]));
        }
        tui_lines_clear(&dock);
    }
    /* 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->nblocks) {
        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) { /* Pi's thinking block as it grows: as much of its end as fits */
            tui_lines t = {NULL, 0, 0};
            (void)tui_lines_add(&s, "", 0);
            (void)tui_thinking_lines(a->thinking.buf, a->hide_thinking, a->cols > 2 ? (size_t)a->cols : 2, &t);
            for (size_t i = t.n > (size_t)budget ? t.n - (size_t)budget : 0; i < t.n; i++) {
                (void)tui_lines_add(&s, t.lines[i], strlen(t.lines[i]));
            }
            tui_lines_clear(&t);
        }
        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);
        for (int i = 0; i < a->nblocks; i++) {
            if (i > 0 || live.n > 0 || !a->last_blank) { /* Pi's spacer above a tool block */
                (void)tui_lines_add(&live, "", 0);
            }
            block_lines(&a->blocks[i], a->expand_tools, a->cols > 2 ? (size_t)a->cols : 2, &live);
        }
        (void)tui_lines_add(&live, "", 0);
    }
    if (a->bash.running) {
        tui_bash b = {a->bash.cmd, a->bash.live ? a->bash.live : "", TUI_BASH_RUNNING, 0, a->bash.no_context};
        (void)tui_bash_lines(&b, a->expand_tools, a->cols > 2 ? (size_t)a->cols : 2, &live);
    }
    size_t split = live.n; /* fullscreen: the transcript's live end, then the dock */
    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_split(a->r, (const char *const *)live.lines, live.n, split, crow, ccol, a->rows);
    tui_lines_clear(&live);
    tui_lines_clear(&tail);
}

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

/* The token that makes this interface the owner of its children's
 * conversations for hooks (PIC_HOOK_OWNER): each child fires SessionStart
 * once per conversation, and the interface ends them (hook_end). */
static char hook_owner[64];

/* argv for this pic with the journal, workspace and model, then ARGS. commands:
 * its stdin is a pipe (c->in) for Pi's RPC lines, else /dev/null. */
static int spawn_in(app *a, app_child *c, const char *const *args, int commands) {
    const char *argv[200];
    char exec_s[16], window_s[24];
    int n = 0, out[2], err[2], in[2] = {-1, -1}, keyfd;
    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;
    }
    if (a->o->system_replace) {
        argv[n++] = "--system-prompt";
        argv[n++] = a->o->system_replace;
    }
    for (size_t k = 0; k < a->o->system_nappend && n < 150; k++) {
        argv[n++] = "--append-system-prompt";
        argv[n++] = a->o->system_append[k];
    }
    if (a->o->tools) {
        argv[n++] = "--tools";
        argv[n++] = a->o->tools;
    }
    if (a->o->exclude_tools) {
        argv[n++] = "--exclude-tools";
        argv[n++] = a->o->exclude_tools;
    }
    if (a->o->no_tools) {
        argv[n++] = "--no-tools";
    }
    if (a->o->no_builtin_tools) {
        argv[n++] = "--no-builtin-tools";
    }
    if (a->key_run[0]) { /* --key, or what replaced it: for requests to its provider only */
        pic_model km;
        char why[256];
        if (pic_model_resolve(a->model, &km, why, sizeof why) == 0 && strcmp(km.provider, a->key_run_provider) == 0) {
            argv[n++] = "--key";
            argv[n++] = a->key_run;
        }
    }
    /* A reply refused for its key comes back here as the swap prompt, its request left unfinished. */
    argv[n++] = "--hold-key-failures";
    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 < 199; args++) {
        argv[n++] = *args;
    }
    argv[n] = NULL;
    memset(c, 0, sizeof *c);
    c->in = c->out = c->err = -1;
    if (pipe(out) != 0) {
        return -1;
    }
    if (pipe(err) != 0) {
        close(out[0]);
        close(out[1]);
        return -1;
    }
    if (commands && pipe(in) != 0) {
        close(out[0]);
        close(out[1]);
        close(err[0]);
        close(err[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);
    if (commands) {
        (void)fcntl(in[1], F_SETFD, FD_CLOEXEC);
    }
    /* The credential store's master key, when this process has unlocked it,
     * goes to the child in a pipe it inherits (cred.h, pic_cred_handoff):
     * the child has no terminal to ask on, and argv, the environment's
     * values, the journal and files must never hold a key. Only this child
     * gets the fd (it is close-on-exec until the child clears that), and the
     * child closes it before it can start anything of its own. */
    keyfd = pic_cred_handoff();
    c->pid = fork();
    if (c->pid == 0) {
        int null = open("/dev/null", O_RDONLY);
        if (keyfd >= 0) {
            char num[16];
            (void)fcntl(keyfd, F_SETFD, 0);
            (void)snprintf(num, sizeof num, "%d", keyfd);
            (void)setenv("PIC_KEY_FD", num, 1);
        }
        /* Its own session: no controlling terminal, so nothing it runs can
         * read the keyboard from under the interface. */
        (void)setsid();
        if (commands) {
            (void)dup2(in[0], STDIN_FILENO);
            close(in[0]);
        } else 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);
        (void)setenv("PIC_HOOK_OWNER", hook_owner, 1);
        (void)setenv("PIC_ORIGIN", pic_store_origin_get(), 1); /* its conversations are this terminal's */
        if (*pic_store_parent_get()) {
            (void)setenv("PIC_PARENT", pic_store_parent_get(), 1);
        }
        execv(a->o->self, (char *const *)(void *)argv);
        _exit(127);
    }
    if (keyfd >= 0) {
        close(keyfd);
    }
    close(out[1]);
    close(err[1]);
    if (commands) {
        close(in[0]);
    }
    if (c->pid < 0) {
        close(out[0]);
        close(err[0]);
        if (commands) {
            close(in[1]);
        }
        return -1;
    }
    c->in = in[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;
}

static int spawn(app *a, app_child *c, const char *const *args) { return spawn_in(a, c, args, 0); }

/* Reads what is available; 1 when both pipes are closed. */
static int drain(app_child *c) {
    int fds[2] = {c->out, c->err};
    app_text *bufs[2] = {&c->outbuf, &c->errbuf};
    for (int i = 0; i < 2; i++) {
        char buf[8192];
        ssize_t n = -1; /* read() assigns it whenever the loop condition is reached */
        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 in *err (malloc'd) when ERR is given, else its first
 * line is shown as a notice. */
static int run_capture(app *a, const char *const *args, char **out, char **err) {
    app_child c;
    int status = 0;
    *out = NULL;
    if (err) {
        *err = 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);
        stop_check();
    }
    while (waitpid(c.pid, &status, 0) < 0 && errno == EINTR) {
    }
    if (err) {
        *err = c.errbuf.buf ? c.errbuf.buf : strdup("");
    } else {
        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;
}

static int run_sync(app *a, const char *const *args, char **out) { return run_capture(a, args, out, NULL); }

/* SessionEnd for the conversations this interface's children began, when
 * hooks are configured: on leaving them (/new, /resume) and on exit. */
static void hook_end(app *a, const char *reason) {
    if (cl_hooks_configured()) {
        const char *args[] = {"hooks", "end", reason, NULL};
        char *out = NULL;
        (void)run_sync(a, args, &out);
        free(out);
    }
}

/* ---- "!" and "!!": a command the user runs ------------------------------ */

/* The command runs as `pic bash`, which journals it as Pi's bashExecution
 * message (so it survives a restart and reaches the model with the next
 * request unless it is "!!"). Its events are the output so far, then Pi's
 * bash response. */

static void bash_settle(app *a) {
    free(a->bash.cmd);
    free(a->bash.live);
    free(a->bash.final);
    free(a->bash.c.outbuf.buf);
    free(a->bash.c.errbuf.buf);
    if (a->bash.running) { /* the fds are only meaningful while it runs (the app starts zeroed) */
        if (a->bash.c.out >= 0) {
            close(a->bash.c.out);
        }
        if (a->bash.c.err >= 0) {
            close(a->bash.c.err);
        }
    }
    memset(&a->bash, 0, sizeof a->bash);
    a->bash.c.in = a->bash.c.out = a->bash.c.err = -1;
}

static int drop_unfinished(app *a);
static void kp_show(app *a);
static void au_open(app *a, const char *note);
static void mc_command(app *a, const char *arg);
static void mc_key(app *a, const tui_key *k);
static void mc_tick(app *a);
static void au_build(app *a);
static void key_chosen(app *a, const char *id);

static int bash_start(app *a, const char *cmd, int no_context) {
    const char *args[10];
    int n = 0;
    bash_settle(a);
    if (a->unfinished[0] && drop_unfinished(a) != 0) {
        return -1;
    }
    args[n++] = "--json";
    args[n++] = "bash";
    if (no_context) {
        args[n++] = "--no-context";
    }
    if (a->conversation[0]) {
        args[n++] = "--session";
        args[n++] = a->conversation;
    }
    args[n++] = cmd;
    args[n] = NULL;
    if (spawn(a, &a->bash.c, args) != 0) {
        bash_settle(a);
        return -1;
    }
    a->bash.running = 1;
    a->bash.no_context = no_context;
    a->bash.cmd = strdup(cmd);
    return 0;
}

/* Esc on a running command: SIGINT (pic bash cancels and journals it); Esc
 * again, or a grace period, SIGTERM and then SIGKILL. */
static void bash_cancel(app *a) {
    if (!a->bash.running) {
        return;
    }
    if (!a->bash.cancelled) {
        a->bash.cancelled = 1;
        a->bash.kill_at = now_ms() + 5000;
        (void)kill(a->bash.c.pid, SIGINT);
    } else if (a->bash.kill_level < 2) {
        (void)kill(a->bash.c.pid, ++a->bash.kill_level == 1 ? SIGTERM : SIGKILL);
        a->bash.kill_at = now_ms() + 2000;
    }
}

static void bash_event(app *a, const char *ev) {
    char *type = jget(a, ev, "$.type");
    if (type && strcmp(type, "bash_execution_update") == 0) {
        free(a->bash.live);
        a->bash.live = jget(a, ev, "$.output");
    } else if (type && strcmp(type, "response") == 0 && jnum(a, ev, "$.success")) {
        char *conv = jget(a, ev, "$.data.conversation"), *code = jget(a, ev, "$.data.exitCode");
        free(a->bash.final);
        a->bash.final = jget(a, ev, "$.data.output");
        a->bash.has_exit = code != NULL;
        a->bash.exit_code = code ? atoi(code) : 0;
        a->bash.cancelled = a->bash.cancelled || jnum(a, ev, "$.data.cancelled") == 1;
        a->bash.got_resp = 1;
        if (conv && *conv) {
            (void)snprintf(a->conversation, sizeof a->conversation, "%s", conv);
        }
        free(conv);
        free(code);
    }
    free(type);
}

/* Reads the events so far and, when pic bash has exited, commits the block. */
static void bash_pump(app *a) {
    int status = 0, code;
    tui_bash b;
    app_text *ob = &a->bash.c.outbuf;
    size_t used = 0;
    if (!a->bash.running) {
        return;
    }
    (void)drain(&a->bash.c);
    while (ob->buf && used < ob->len) {
        char *nl = memchr(ob->buf + used, '\n', ob->len - used);
        if (!nl) {
            break;
        }
        *nl = '\0';
        bash_event(a, ob->buf + used);
        used = (size_t)(nl - ob->buf) + 1;
    }
    if (used) {
        memmove(ob->buf, ob->buf + used, ob->len - used);
        ob->len -= used;
        ob->buf[ob->len] = '\0';
    }
    if (waitpid(a->bash.c.pid, &status, WNOHANG) != a->bash.c.pid) {
        if (a->bash.cancelled && a->bash.kill_level < 2 && now_ms() > a->bash.kill_at) {
            bash_cancel(a);
        }
        return;
    }
    (void)drain(&a->bash.c);
    if (ob->len) { /* a last line with no newline */
        bash_event(a, ob->buf);
    }
    if (!a->bash.got_resp) { /* it never answered: nothing was journaled */
        if (a->bash.c.errbuf.len) {
            notice(a, RED, "%.*s", (int)strcspn(a->bash.c.errbuf.buf, "\n"), a->bash.c.errbuf.buf);
        }
        if (!a->bash.cancelled) {
            notice(a, RED, "pic: the command was not run (exit %d)", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
            bash_settle(a);
            return;
        }
    }
    code = a->bash.has_exit ? a->bash.exit_code : 0;
    b = (tui_bash){a->bash.cmd, a->bash.final ? a->bash.final : a->bash.live ? a->bash.live : "",
                   a->bash.cancelled ? TUI_BASH_CANCELLED : TUI_BASH_DONE, code, a->bash.no_context};
    commit_bash(a, &b);
    bash_settle(a);
}

/* A message starting with "!" or "!!": run the rest as a command (Pi's handler
 * in interactive-mode.ts). 1 when it was handled. */
static int run_bang(app *a, const char *msg) {
    int excluded = msg[0] == '!' && msg[1] == '!';
    const char *cmd = msg + (excluded ? 2 : 1);
    size_t n;
    char *copy;
    if (msg[0] != '!') {
        return 0;
    }
    cmd += strspn(cmd, " \t\n");
    n = strlen(cmd);
    while (n > 0 && strchr(" \t\n", cmd[n - 1])) {
        n--;
    }
    if (n == 0) {
        return 0; /* a lone "!" is an ordinary message */
    }
    if (a->working || a->bash.running) { /* held with the other follow-ups; run_queued runs it when the journal is free */
        if (a->nqueue < MAX_QUEUED) {
            a->queue[a->nqueue++] = strdup(msg);
        } else {
            notice(a, YELLOW, "Warning: too many queued messages; the command was not queued");
            tui_editor_set(a->ed, msg);
        }
        return 1;
    }
    copy = strndup(cmd, n);
    if (!copy || bash_start(a, copy, excluded) != 0) {
        notice(a, RED, "pic: could not run the command: %s", strerror(errno));
    }
    free(copy);
    return 1;
}

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

/* A file descriptor holding IM's bytes, at offset 0: an unlinked temporary
 * file, so ask's --image reads it as /dev/fd/N and nothing stays on disk. -1
 * when it cannot be made. */
static int image_fd(const tui_attachment *im) {
    FILE *f = tmpfile();
    int fd = -1;
    if (!f) {
        return -1;
    }
    if (fwrite(im->data, 1, im->len, f) == im->len && fflush(f) == 0 && (fd = dup(fileno(f))) >= 0 &&
        lseek(fd, 0, SEEK_SET) != 0) {
        close(fd);
        fd = -1;
    }
    (void)fclose(f);
    return fd;
}

static void reset_screen(app *a);

/* The request's key is in the credential store and this process has not
 * unlocked it: the passphrase is asked in place (the request child has no
 * terminal, and gets the key by pic_cred_handoff), and the request, held
 * meanwhile, starts once the store opens. 1 when it is held. */
enum { AFTER_SEND, AFTER_RESUME, AFTER_COMPACT, AFTER_RC, AFTER_ENDPOINT }; /* what waits for the store: a message, /resume's request, /compact, /rc, a new endpoint's key */
static void login_hold(app *a, const char *provider, int after, const char *msg, const tui_attachment *images,
                       size_t nimages);

static int request_locked(app *a, const char *model, int after, const char *msg, const tui_attachment *images,
                          size_t nimages) {
    pic_model m;
    char err[256];
    if (pic_model_resolve(model, &m, err, sizeof err) != 0 || !pic_cred_needs_unlock(m.provider, m.key_env, m.key_literal) ||
        pic_cred_quiet(err, sizeof err) != 1) { /* a kept key opens it unasked; a refusal is the request's error */
        return 0;
    }
    login_hold(a, m.provider, after, msg, images, nimages);
    return 1;
}

static void request_started(app *a, const char *what);
static void login_open(app *a, const char *provider, const char *why);
static void login_begin(app *a, const char *provider, int oauth);

/* The request's provider needs a credential and has none: the login choice
 * opens instead of a request that would fail (the message stays in the
 * editor). 1 when it opened. */
static int needs_login(app *a, const char *model) {
    pic_model m;
    char err[256], why[200];
    if (pic_model_resolve(model, &m, err, sizeof err) != 0 || !m.key_env[0] ||
        pic_cred_source_of(m.provider, m.key_env, m.key_literal) != PIC_CRED_NONE) {
        return 0;
    }
    (void)snprintf(why, sizeof why, "%s has no credential: %s is not set and nothing is stored.", m.provider, m.key_env);
    notice(a, YELLOW, "%s has no key yet: log in below, or Esc then /model to pick another model (your message stays).",
           m.provider);
    login_open(a, m.provider, why);
    return 1;
}

static void fw_stop(app *a);
static int ext_send(app *a, const char *type, const char *msg);

/* A request child (a->run); the follower stops first, so its events are not shown twice. */
static int run_spawn(app *a, const char *const *args, int commands) {
    fw_stop(a);
    return spawn_in(a, &a->run, args, commands);
}

static void start_request(app *a, const char *msg, const tui_attachment *images, size_t nimages) {
    const char *args[4 + 2 * PIC_REQUEST_IMAGES + 2];
    char paths[PIC_REQUEST_IMAGES][24];
    int fds[PIC_REQUEST_IMAGES], n = 0, nfd = 0, bad = 0;
    if (a->ext_running && !nimages) { /* a request from elsewhere runs: this goes to it, as a steer */
        if (ext_send(a, "steer", msg) != 0) {
            tui_editor_set(a->ed, msg);
        }
        return;
    }
    if (needs_login(a, a->model)) {
        tui_editor_set(a->ed, msg);
        return;
    }
    if (request_locked(a, a->model, AFTER_SEND, msg, images, nimages)) {
        return;
    }
    if (!a->conversation[0] && !a->name[0] && !a->conv_title[0]) { /* pic's rule, until it says (load_title) */
        char *line = pic_one_line(msg, 60);
        if (line && *line) {
            (void)snprintf(a->conv_title, sizeof a->conv_title, "%s", line);
            a->title_guess = 1;
        }
        free(line);
    }
    args[n++] = "--json";
    args[n++] = "--commands";
    args[n++] = "ask";
    if (a->conversation[0]) {
        args[n++] = "--session";
        args[n++] = a->conversation;
    } else if (a->o->new_id) {
        args[n++] = "--session-id";
        args[n++] = a->o->new_id;
    }
    for (size_t i = 0; i < nimages && nfd < PIC_REQUEST_IMAGES; i++) {
        if ((fds[nfd] = image_fd(&images[i])) < 0) {
            bad = 1;
            break;
        }
        (void)snprintf(paths[nfd], sizeof paths[nfd], "/dev/fd/%d", fds[nfd]);
        args[n++] = "--image";
        args[n++] = paths[nfd++];
    }
    args[n++] = msg;
    args[n] = NULL;
    if (bad) {
        for (int i = 0; i < nfd; i++) {
            close(fds[i]);
        }
        notice(a, RED, "pic: could not hold the attached images: %s", strerror(errno));
        return;
    }
    if (a->unfinished[0] && drop_unfinished(a) != 0) { /* a new message leaves the interrupted one, as Pi's does */
        for (int i = 0; i < nfd; i++) {
            close(fds[i]);
        }
        tui_editor_set(a->ed, msg);
        return;
    }
    commit_user(a, msg);
    free(a->last_msg);
    a->last_msg = strdup(msg);
    n = run_spawn(a, args, 1);
    for (int i = 0; i < nfd; i++) {
        close(fds[i]);
    }
    if (n != 0) {
        notice(a, RED, "pic: could not start the request: %s", strerror(errno));
        return;
    }
    {
        char what[PATH_MAX + 8];
        (void)snprintf(what, sizeof what, "pic --json ask %.200s", msg);
        request_started(a, what);
    }
}

/* Drops the interrupted request (pic cancel journals it, as Esc's abort
 * would have): its prompt stays in the conversation, its reply never comes.
 * 0 when dropped. */
static int drop_unfinished(app *a) {
    const char *args[] = {"cancel", a->unfinished, NULL};
    char *out = NULL;
    int rc = run_sync(a, args, &out);
    free(out);
    if (rc != 0) {
        notice(a, RED, "pic: could not drop the interrupted request");
        return -1;
    }
    a->unfinished[0] = '\0';
    a->kp.on = 0;
    a->kp.wait_until = 0;
    notice(a, DIM, "interrupted request dropped");
    return 0;
}

/* Finishes the interrupted request here, as `pic run --session` does: with
 * the model and thinking level it was admitted with, its events shown as a
 * request's. */
static void resume_unfinished(app *a) {
    const char *args[] = {"--json", "--commands", "run", "--session", a->conversation, NULL};
    if (request_locked(a, a->unfinished_model[0] ? a->unfinished_model : a->model, AFTER_RESUME, "", NULL, 0)) {
        return; /* its own model's key; it resumes once the store opens */
    }
    if (run_spawn(a, args, 1) != 0) {
        notice(a, RED, "pic: could not resume the request: %s", strerror(errno));
        return;
    }
    request_started(a, "pic --json run --session");
    a->resuming = 1; /* the offer stands until the request has ended */
}

/* Pi's /compact: at once, in a child whose events (compaction_start and
 * _end) show it running and its result; Esc stops it as it does a reply. */
static void compact_start(app *a, const char *focus) {
    const char *args[] = {"--json", "compact", "--now", a->conversation, *focus ? focus : NULL, NULL};
    if (!a->conversation[0]) {
        notice(a, RED, "Nothing to compact (session too small)");
        return;
    }
    if (request_locked(a, a->model, AFTER_COMPACT, focus, NULL, 0)) {
        return;
    }
    if (run_spawn(a, args, 0) != 0) {
        notice(a, RED, "pic: could not start the compaction: %s", strerror(errno));
        return;
    }
    request_started(a, "pic --json compact --now");
    a->compacting = 1;
}

/* The bookkeeping of a request child just started (a->run). */
static void request_started(app *a, const char *what) {
    child_pid = a->run.pid;
    a->run.proc = cl_proc_start("tui-request", what, (long)a->run.pid);
    a->working = 1;
    a->turn_t0 = now_ms();
    a->done_kind = 0;
    a->interrupted = a->seen_end = 0;
    a->abort_sent = a->clear_sent = a->clear_notice = 0;
    a->skip_user = 1;
    a->finishing = 0;
    a->status[0] = '\0';
    a->retried = a->retry_n = 0;
    (void)thinking_hidden(a);
}

/* A line of Pi's RPC commands to the running request: 0 when it was written. */
static int send_command(app *a, const char *json) {
    size_t n = strlen(json), at = 0;
    ssize_t w = 0;
    if (a->run.in < 0) {
        return -1;
    }
    /* A line with an image is megabytes: the child reads while this writes. A
     * full pipe is a stuck child. */
    while (at < n && (w = write(a->run.in, json + at, n - at)) > 0) {
        at += (size_t)w;
    }
    if (at == n) {
        w = write(a->run.in, "\n", 1);
    }
    if (w < 0) {
        close(a->run.in);
        a->run.in = -1;
        return -1;
    }
    return 0;
}

/* {"type":TYPE,"message":MSG} as a line, MSG JSON-escaped through SQLite. */
static int send_message(app *a, const char *type, const char *msg, const tui_attachment *images, size_t nimages) {
    sqlite3_stmt *q = NULL;
    app_text arr = {NULL, 0, 0};
    int rc = -1;
    if (a->run.in < 0 ||
        sqlite3_prepare_v2(a->db, "SELECT json_object('type', ?1, 'message', ?2, 'images', json(?3))", -1, &q, NULL) !=
            SQLITE_OK) {
        return -1;
    }
    /* Pi's ImageContent blocks: {"type":"image","data":BASE64,"mimeType":TYPE}; both are plain. */
    (void)text_add(&arr, "[", 1);
    for (size_t i = 0; i < nimages; i++) {
        const char *mime = pic_image_sniff(images[i].data, images[i].len);
        char *b64 = malloc(4 * ((images[i].len + 2) / 3) + 1);
        if (!b64 || !mime) {
            free(b64);
            free(arr.buf);
            sqlite3_finalize(q);
            return -1;
        }
        (void)pic_base64_encode(images[i].data, images[i].len, b64);
        const char *head = i ? ",{\"type\":\"image\",\"data\":\"" : "{\"type\":\"image\",\"data\":\"",
                   *mid = "\",\"mimeType\":\"", *tail = "\"}";
        (void)text_add(&arr, head, strlen(head));
        (void)text_add(&arr, b64, strlen(b64));
        (void)text_add(&arr, mid, strlen(mid));
        (void)text_add(&arr, mime, strlen(mime));
        (void)text_add(&arr, tail, strlen(tail));
        free(b64);
    }
    (void)text_add(&arr, "]", 1);
    sqlite3_bind_text(q, 1, type, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, msg, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, arr.buf ? arr.buf : "[]", -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        rc = send_command(a, (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    free(arr.buf);
    return rc;
}

static void block_free(toolblk *b) {
    free(b->title);
    free(b->diff);
    free(b->output);
    free(b->content);
    free(b->calls);
    for (int i = 0; i < b->nnested; i++) {
        free(b->nested[i].what);
    }
    free(b->nested);
    memset(b, 0, sizeof *b);
}

static void block_lines(const toolblk *b, int expanded, size_t cols, tui_lines *out) {
    tui_tool t = {b->name, b->title ? b->title : "", b->diff, b->output, b->state,
                  b->state == TUI_TOOL_PENDING ? now_ms() - b->start_ms : b->took_ms, b->content, b->calls};
    (void)tui_tool_lines(&t, expanded, cols > 2 ? cols : 2, out);
}

/* Commits the finished blocks at the front, in the state ctrl+o has now; a
 * pending one holds back the rest so the order is kept. force: all of them
 * (the request is over: a pending one never finished and is dropped). */
static void blocks_flush(app *a, int force) {
    int n = 0;
    while (n < a->nblocks && (a->blocks[n].state != TUI_TOOL_PENDING || force)) {
        if (a->blocks[n].state != TUI_TOOL_PENDING) {
            const toolblk *b = &a->blocks[n];
            tui_tool t = {b->name, b->title ? b->title : "", b->diff, b->output, b->state, b->took_ms, b->content, b->calls};
            commit_tool(a, &t);
        }
        block_free(&a->blocks[n]);
        n++;
    }
    memmove(a->blocks, a->blocks + n, (size_t)(a->nblocks - n) * sizeof *a->blocks);
    a->nblocks -= n;
}

/* What a call acts on, from its arguments: bash's command, read's path and
 * range, write's path and size, edit's path, the pattern of find and grep. */
static void tool_title(app *a, const char *ev, const char *name, char *out, size_t cap) {
    char *cmd = jget(a, ev, "$.args.command"), *path = jget(a, ev, "$.args.path"),
         *pattern = jget(a, ev, "$.args.pattern"), *content = jget(a, ev, "$.args.content");
    long long offset = jnum(a, ev, "$.args.offset"), limit = jnum(a, ev, "$.args.limit"),
              timeout = jnum(a, ev, "$.args.timeout");
    size_t n = 0;
    out[0] = '\0';
    if (strcmp(name, "bash") == 0) {
        n = (size_t)snprintf(out, cap, "$ %s", cmd ? cmd : "...");
        if (timeout > 0 && n < cap) {
            (void)snprintf(out + n, cap - n, " (timeout %llds)", timeout);
        }
    } else if (strcmp(name, "read") == 0) {
        n = (size_t)snprintf(out, cap, "%s", path ? path : "");
        if ((offset > 0 || limit > 0) && n < cap) {
            if (limit > 0) {
                (void)snprintf(out + n, cap - n, ":%lld-%lld", offset > 0 ? offset : 1, (offset > 0 ? offset : 1) + limit - 1);
            } else {
                (void)snprintf(out + n, cap - n, ":%lld", offset);
            }
        }
    } else if (strcmp(name, "write") == 0) {
        size_t len = content ? strlen(content) : 0, lines = 0;
        char size[24];
        for (size_t i = 0; i < len; i++) {
            lines += content[i] == '\n';
        }
        lines += len > 0 && content[len - 1] != '\n';
        tui_fmt_size(len, size, sizeof size);
        (void)snprintf(out, cap, "%s (%zu %s, %s)", path ? path : "", lines, lines == 1 ? "line" : "lines", size);
    } else if (pattern) {
        (void)snprintf(out, cap, "%s%s%s", pattern, path ? " in " : "", path ? path : "");
    } else {
        (void)snprintf(out, cap, "%s", cmd ? cmd : path ? path : "");
    }
    free(cmd);
    free(path);
    free(pattern);
    free(content);
}

/* The file an edit touches (workspace-relative paths resolved), up to 8 MB; NULL when unreadable. */
static char *edit_file(app *a, const char *ev) {
    char *path = jget(a, ev, "$.args.path"), full[PATH_MAX * 2], *buf = NULL;
    FILE *f;
    long n;
    if (!path) {
        return NULL;
    }
    (void)snprintf(full, sizeof full, "%s%s%s", path[0] == '/' ? "" : a->o->workspace, path[0] == '/' ? "" : "/", path);
    free(path);
    f = fopen(full, "rb");
    if (!f) {
        return NULL;
    }
    if (fseek(f, 0, SEEK_END) == 0 && (n = ftell(f)) >= 0 && n <= 8L << 20 && fseek(f, 0, SEEK_SET) == 0 &&
        (buf = malloc((size_t)n + 1)) != NULL) {
        if (fread(buf, 1, (size_t)n, f) != (size_t)n) {
            free(buf);
            buf = NULL;
        } else {
            buf[n] = '\0';
        }
    }
    (void)fclose(f);
    return buf;
}

static long count_lines(const char *s) {
    long n = 1;
    for (; *s; s++) {
        n += *s == '\n';
    }
    return n;
}

/* The 1-based line of the first occurrence of needle in hay; 0 when absent or empty. */
static long line_of(const char *hay, const char *needle) {
    const char *at = *needle ? strstr(hay, needle) : NULL;
    long n = 1;
    if (!at) {
        return 0;
    }
    for (; hay < at; hay++) {
        n += *hay == '\n';
    }
    return n;
}

/* An edit's diff, one hunk per replacement ({oldText,newText} in edits[], or at the top level),
 * with Pi's line numbers when the file can be read: old lines by the file as it was, new lines
 * shifted by the earlier replacements. The tool has usually not run yet; when it has, the
 * replacement is found by its new text instead. */
static char *edit_diff(app *a, const char *ev) {
    app_text all = {NULL, 0, 0};
    char *file = edit_file(a, ev);
    long delta = 0, total = 0;
    int width = 0;
    for (int pass = 0; pass < 2; pass++) {
        delta = 0;
        for (int i = 0; i < 64; i++) {
            char key[2][48], *old, *new_;
            (void)snprintf(key[0], sizeof key[0], "$.args.edits[%d].oldText", i);
            (void)snprintf(key[1], sizeof key[1], "$.args.edits[%d].newText", i);
            old = jget(a, ev, key[0]);
            new_ = jget(a, ev, key[1]);
            if (i == 0 && !old && !new_) {
                old = jget(a, ev, "$.args.oldText");
                new_ = jget(a, ev, "$.args.newText");
            }
            if (old || new_) {
                const char *o = old ? old : "", *n = new_ ? new_ : "";
                if (pass == 0) {
                    total += count_lines(n) - count_lines(o);
                } else {
                    long ol = file ? line_of(file, o) : 0, nl;
                    char *d;
                    if (file && !ol) { /* already applied: the new text is in the file */
                        long at = line_of(file, n);
                        nl = at;
                        ol = at ? at - delta : 0;
                    } else {
                        nl = ol + delta;
                    }
                    d = tui_diff_numbered(o, n, ol ? ol : 1, nl ? nl : 1, ol ? width : 0);
                    if (d && *d) {
                        if (all.len) {
                            (void)text_add(&all, "\n \xe2\x80\xa6\n", 6);
                        }
                        (void)text_add(&all, d, strlen(d));
                    }
                    free(d);
                }
                delta += count_lines(n) - count_lines(o);
            }
            free(old);
            free(new_);
            if (!old && !new_) {
                break;
            }
        }
        if (pass == 0) {
            long fl = file ? count_lines(file) : 0, big = fl + (total > 0 ? total : 0);
            for (width = 1; big >= 10; big /= 10) {
                width++;
            }
            total = 0;
        }
    }
    free(file);
    return all.buf;
}

/* The pending block of call ID, or NULL. */
static toolblk *pending_block(app *a, const char *id) {
    for (int i = 0; id && i < a->nblocks; i++) {
        if (a->blocks[i].state == TUI_TOOL_PENDING && strcmp(a->blocks[i].id, id) == 0) {
            return &a->blocks[i];
        }
    }
    return NULL;
}

/* B's calls as lines (Pi's codemode row): a mark, the tool and its arguments, how long it took. */
static void nested_lines(toolblk *b) {
    app_text t = {NULL, 0, 0};
    for (int i = 0; i < b->nnested; i++) {
        const nestcall *c = &b->nested[i];
        char dur[32] = "";
        static const char *const marks[] = {"\xe2\x80\xa6", "\xe2\x9c\x93", "\xe2\x9c\x97"};
        if (c->state != TUI_TOOL_PENDING) {
            if (c->ms < 1000) {
                (void)snprintf(dur, sizeof dur, " %ldms", c->ms);
            } else {
                (void)snprintf(dur, sizeof dur, " %.1fs", (double)c->ms / 1000.0);
            }
        }
        (void)(text_add(&t, marks[c->state], strlen(marks[c->state])) || text_add(&t, " ", 1) ||
               text_add(&t, c->what, strlen(c->what)) || text_add(&t, dur, strlen(dur)) || text_add(&t, "\n", 1));
    }
    free(b->calls);
    b->calls = t.buf;
}

/* A call a script made: a line of its script's block, not a block of its own (Pi's renderer). */
static int nested_event(app *a, const char *ev, int start) {
    char *parent = jget(a, ev, "$.parentToolCallId"), *id = jget(a, ev, "$.toolCallId");
    toolblk *b = pending_block(a, parent);
    int handled = parent != NULL;
    if (b && id && start) {
        nestcall *grown = realloc(b->nested, (size_t)(b->nnested + 1) * sizeof *grown);
        char *name = jget(a, ev, "$.toolName"), *args = jget(a, ev, "$.args"), what[200];
        if (grown) {
            nestcall *c = &grown[b->nnested];
            b->nested = grown;
            memset(c, 0, sizeof *c);
            (void)snprintf(c->id, sizeof c->id, "%s", id);
            (void)snprintf(what, sizeof what, "%s %.80s%s", name ? name : "tool", args ? args : "",
                           args && strlen(args) > 80 ? "..." : "");
            c->what = strdup(what);
            c->start_ms = now_ms();
            if (c->what) {
                b->nnested++;
            }
        }
        free(name);
        free(args);
    } else if (b && id) {
        for (int i = 0; i < b->nnested; i++) {
            if (strcmp(b->nested[i].id, id) == 0 && b->nested[i].state == TUI_TOOL_PENDING) {
                b->nested[i].state = jnum(a, ev, "$.isError") ? TUI_TOOL_ERROR : TUI_TOOL_OK;
                b->nested[i].ms = now_ms() - b->nested[i].start_ms;
            }
        }
    }
    if (b) {
        nested_lines(b);
    }
    free(parent);
    free(id);
    return handled;
}

/* /codemode [on|off]: switches the codemode tool for this session (PIC_CODEMODE for the requests
 * this terminal starts) and the open conversation (set_codemode). */
static void codemode_switch(app *a, const char *arg) {
    const char *env = getenv("PIC_CODEMODE");
    char err[256], *data;
    int on;
    if (strcmp(arg, "on") == 0 || strcmp(arg, "off") == 0) {
        on = strcmp(arg, "on") == 0;
    } else if (*arg) {
        notice(a, RED, "/codemode takes on or off, or nothing to switch it");
        return;
    } else if (env && *env) {
        on = !(strcmp(env, "on") == 0 || strcmp(env, "true") == 0);
    } else {
        char *set = cl_setting("codemode");
        on = !(set && strcmp(set, "true") == 0);
        free(set);
    }
    if (!(data = cl_ask("set_codemode", on ? "\"enabled\":true" : "\"enabled\":false", err, sizeof err))) {
        notice(a, RED, "codemode: %s", err);
        return;
    }
    free(data);
    notice(a, DIM, on ? "codemode on for this session: the model can run scripts that call the other tools"
                      : "codemode off for this session");
}

static void tool_start(app *a, const char *ev) {
    char *name, *id, title[1024];
    toolblk *grown, *b;
    if (nested_event(a, ev, 1)) {
        return;
    }
    name = jget(a, ev, "$.toolName");
    id = jget(a, ev, "$.toolCallId");
    grown = realloc(a->blocks, (size_t)(a->nblocks + 1) * sizeof *grown);
    if (grown) {
        a->blocks = grown;
        b = &a->blocks[a->nblocks++];
        memset(b, 0, sizeof *b);
        (void)snprintf(b->name, sizeof b->name, "%s", name ? name : "tool");
        (void)snprintf(b->id, sizeof b->id, "%s", id ? id : "");
        tool_title(a, ev, b->name, title, sizeof title);
        b->title = strdup(title);
        b->diff = strcmp(b->name, "edit") == 0 ? edit_diff(a, ev) : NULL;
        b->content = strcmp(b->name, "write") == 0      ? jget(a, ev, "$.args.content")
                     : strcmp(b->name, "codemode") == 0 ? jget(a, ev, "$.args.script")
                                                        : NULL;
        b->start_ms = now_ms();
    }
    free(name);
    free(id);
}

static void tool_end(app *a, const char *ev) {
    char *id, *result;
    toolblk *b = NULL;
    if (nested_event(a, ev, 0)) {
        return;
    }
    id = jget(a, ev, "$.toolCallId");
    result = jget(a, ev, "$.result.content[0].text");
    for (int i = 0; i < a->nblocks; i++) {
        if (a->blocks[i].state == TUI_TOOL_PENDING && (!id || !a->blocks[i].id[0] || strcmp(a->blocks[i].id, id) == 0)) {
            b = &a->blocks[i];
            break;
        }
    }
    if (b) {
        b->state = jnum(a, ev, "$.isError") ? TUI_TOOL_ERROR : TUI_TOOL_OK;
        b->took_ms = now_ms() - b->start_ms;
        free(b->output); /* the live tail */
        b->output = result ? result : strdup("");
        result = NULL;
    }
    free(id);
    free(result);
}

static void qfree(char **q, int *n) {
    for (int i = 0; i < *n; i++) {
        free(q[i]);
    }
    *n = 0;
}

/* The strings of an array at PATH ("$.steering") into q. */
static void qload(app *a, const char *ev, const char *path, char **q, int *n) {
    qfree(q, n);
    for (int i = 0; i < MAX_QUEUED; i++) {
        char key[48], *t;
        (void)snprintf(key, sizeof key, "%s[%d]", path, i);
        if (!(t = jget(a, ev, key))) {
            break;
        }
        q[(*n)++] = t;
    }
}

/* Everything the child still holds (its queue, and what was sent and not yet
 * answered) back to the editor, with a note: the request ended without
 * running it. Pi puts queued messages back in the editor the same way. */
static void restore_held(app *a, int announce) {
    char *all[3 * MAX_QUEUED];
    int n = 0;
    for (int i = 0; i < a->nsteer && n < 3 * MAX_QUEUED; i++) {
        all[n++] = a->steer_q[i];
    }
    for (int i = 0; i < a->nfollow && n < 3 * MAX_QUEUED; i++) {
        all[n++] = a->follow_q[i];
    }
    for (int i = 0; i < a->nsent && n < 3 * MAX_QUEUED; i++) {
        all[n++] = a->sent_q[i];
    }
    if (n) {
        restore_texts(a, all, n);
        if (announce) {
            notice(a, DIM, "Restored %d queued message%s to editor", n, n > 1 ? "s" : "");
        }
    }
    qfree(a->steer_q, &a->nsteer);
    qfree(a->follow_q, &a->nfollow);
    qfree(a->sent_q, &a->nsent);
}

static const char *rc_origin_name(app *a, const char *origin);

/* The title pic gives the conversation (pic sessions), for the footer and the editor's border, in
 * place of the one guessed from its first prompt. Only between requests: pic sessions settles work
 * no process holds yet. */
static void load_title(app *a) {
    const char *args[] = {"sessions", "--json", NULL};
    char *out = NULL;
    a->title_guess = 0;
    if (!a->conversation[0] || a->name[0] || run_sync(a, args, &out) != 0) {
        free(out);
        return;
    }
    for (char *line = out, *nl; line && *line; line = nl ? nl + 1 : NULL) {
        char *id, *title;
        nl = strchr(line, '\n');
        if (nl) {
            *nl = '\0';
        }
        id = jget(a, line, "$.id");
        title = id && strcmp(id, a->conversation) == 0 ? jget(a, line, "$.title") : NULL;
        if (title) {
            (void)snprintf(a->conv_title, sizeof a->conv_title, "%s", title);
        }
        free(id);
        free(title);
    }
    free(out);
}

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");
        a->finishing = 0;
        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 || strcmp(kind, "thinking_delta") == 0)) {
            blocks_flush(a, 0); /* the reply goes below the tool calls before it */
            a->retry_n = 0;
            if (strcmp(kind, "text_delta") == 0 && a->thinking.len) {
                commit_thinking(a); /* the thinking is over: it goes above the text it precedes */
            }
            /* Thinking is always kept; whether it is shown is decided when it is committed. */
            (void)text_add(strcmp(kind, "text_delta") == 0 ? &a->stream : &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, "aborted") == 0) {
                /* Pi's abort: what streamed stays on screen (agent_end commits it);
                 * it is not in the context, and nothing is asked again. */
            } else 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 (auto_retry_start says whether it is asked again). */
                if (a->stream_off > 0) {
                    notice(a, YELLOW, "(the reply above was cut off)");
                }
                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");
                char *cost = jget(a, ev, "$.message.usage.cost.total");
                if (cost) { /* priced models only: nothing shows when absent */
                    a->cost += strtod(cost, NULL);
                    free(cost);
                }
                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;
                }
                if (!a->stream.len && a->ext_running) { /* followed, not streamed: the text is the message's */
                    for (int i = 0;; i++) {
                        char path[64], *bt, *tx;
                        (void)snprintf(path, sizeof path, "$.message.content[%d].type", i);
                        if (!(bt = jget(a, ev, path))) {
                            break;
                        }
                        (void)snprintf(path, sizeof path, "$.message.content[%d].text", i);
                        if (strcmp(bt, "text") == 0 && (tx = jget(a, ev, path)) != NULL) {
                            (void)text_add(&a->stream, tx, strlen(tx));
                            free(tx);
                        }
                        free(bt);
                    }
                    if (a->stream.len) {
                        blocks_flush(a, 0); /* no deltas came to put it there: the reply goes below its tool calls */
                    }
                }
                commit_stream(a);
                a->status[0] = '\0';
                a->retry_n = 0;
                a->finishing = stop && strcmp(stop, "toolUse") != 0 && a->nsteer == 0 && a->nfollow == 0;
                if (stop && (strcmp(stop, "length") == 0 || strcmp(stop, "max_tokens") == 0)) {
                    notice(a, RED, "Response was truncated before completion.");
                }
            }
        }
        free(role);
        free(stop);
    } else if (strcmp(type, "auto_retry_start") == 0) {
        a->retry_n = (int)jnum(a, ev, "$.attempt");
        a->retry_max = (int)jnum(a, ev, "$.maxAttempts");
        a->retry_delay = (long)jnum(a, ev, "$.delayMs");
        a->retry_at = now_ms();
        a->retried = a->retry_n;
        a->status[0] = '\0'; /* draw shows the live countdown instead */
    } else if (strcmp(type, "queue_update") == 0) {
        qload(a, ev, "$.steering", a->steer_q, &a->nsteer);
        qload(a, ev, "$.followUp", a->follow_q, &a->nfollow);
        /* What the child lists is journaled: nothing of ours is in flight any more. */
        qfree(a->sent_q, &a->nsent);
    } else if (strcmp(type, "queue_returned") == 0) {
        /* The request ended without running what it still held. */
        qload(a, ev, "$.steering", a->steer_q, &a->nsteer);
        qload(a, ev, "$.followUp", a->follow_q, &a->nfollow);
        restore_held(a, 1);
    } else if (strcmp(type, "message_start") == 0) {
        char *role = jget(a, ev, "$.message.role");
        if (role && strcmp(role, "user") == 0) {
            if (a->skip_user) { /* the request's own text, shown when it was sent */
                a->skip_user = 0;
            } else { /* steering or a follow-up, delivered where it lands in the reply */
                char *t = jget(a, ev, "$.message.content[0].text"), *origin = jget(a, ev, "$.origin");
                if (t && a->ext_running && a->ext_sent[0] && strcmp(a->ext_sent[0], t) == 0) {
                    free(a->ext_sent[0]); /* typed here and shown when sent */
                    memmove(a->ext_sent, a->ext_sent + 1, sizeof a->ext_sent - sizeof a->ext_sent[0]);
                    a->ext_sent[7] = NULL;
                } else if (t) {
                    blocks_flush(a, 0);
                    commit_stream(a);
                    if (origin && strncmp(origin, "remote:", 7) == 0) {
                        const char *name = rc_origin_name(a, origin);
                        size_t fn = strlen(name) + strlen(t) + 8;
                        char *from = malloc(fn);
                        if (from) {
                            (void)snprintf(from, fn, "from %s: %s", name, t);
                            commit_user(a, from);
                        }
                        free(from);
                    } else {
                        commit_user(a, t);
                    }
                }
                free(t);
                free(origin);
            }
        }
        free(role);
    } else if (strcmp(type, "response") == 0) {
        char *cmd = jget(a, ev, "$.command");
        int ok = jnum(a, ev, "$.success") == 1;
        if (cmd && (strcmp(cmd, "steer") == 0 || strcmp(cmd, "follow_up") == 0)) {
            if (a->nsent > 0) { /* answered in order: journaled, or refused */
                if (!ok) {
                    char *err = jget(a, ev, "$.error");
                    notice(a, RED, "%s", err ? err : "the message was not queued");
                    free(err);
                    restore_texts(a, a->sent_q, 1);
                }
                free(a->sent_q[0]);
                memmove(a->sent_q, a->sent_q + 1, (size_t)(a->nsent - 1) * sizeof *a->sent_q);
                a->nsent--;
            }
        } else if (cmd && strcmp(cmd, "clear_queue") == 0) {
            char *got[2 * MAX_QUEUED + MAX_QUEUED];
            int n = 0;
            a->clear_sent = 0;
            for (int i = 0; ok && i < MAX_QUEUED; i++) {
                char key[48];
                (void)snprintf(key, sizeof key, "$.data.steering[%d]", i);
                if (!(got[n] = jget(a, ev, key))) {
                    break;
                }
                n++;
            }
            for (int i = 0; ok && i < MAX_QUEUED; i++) {
                char key[48];
                (void)snprintf(key, sizeof key, "$.data.followUp[%d]", i);
                if (!(got[n] = jget(a, ev, key))) {
                    break;
                }
                n++;
            }
            for (int i = 0; i < a->nqueue && n < 3 * MAX_QUEUED; i++) {
                got[n++] = a->queue[i];
            }
            if (n) {
                restore_texts(a, got, n);
            }
            if (a->clear_notice) {
                if (n) {
                    notice(a, DIM, "Restored %d queued message%s to editor", n, n > 1 ? "s" : "");
                } else {
                    notice(a, DIM, "No queued messages to restore");
                }
            }
            for (int i = 0; i < n - a->nqueue; i++) {
                free(got[i]);
            }
            for (int i = 0; i < a->nqueue; i++) {
                free(a->queue[i]);
            }
            a->nqueue = 0;
            qfree(a->steer_q, &a->nsteer);
            qfree(a->follow_q, &a->nfollow);
            qfree(a->sent_q, &a->nsent);
            a->clear_notice = 0;
        }
        free(cmd);
    } else if (strcmp(type, "tool_execution_update") == 0) {
        char *id = jget(a, ev, "$.toolCallId"), *part = jget(a, ev, "$.partialResult.content[0].text"),
             *parent = jget(a, ev, "$.parentToolCallId");
        if (parent) { /* a script's call: its row is a line of the script's */
            free(part);
            part = NULL;
        }
        free(parent);
        for (int i = 0; part && i < a->nblocks; i++) {
            if (a->blocks[i].state == TUI_TOOL_PENDING && (!id || !a->blocks[i].id[0] || strcmp(a->blocks[i].id, id) == 0)) {
                free(a->blocks[i].output);
                a->blocks[i].output = part;
                part = NULL;
                break;
            }
        }
        free(id);
        free(part);
    } else if (strcmp(type, "tool_execution_start") == 0) {
        a->finishing = 0;
        commit_stream(a);
        tool_start(a, ev);
    } else if (strcmp(type, "tool_execution_end") == 0) {
        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 (a->compacting) {
            a->seen_end = 1; /* /compact's result is this */
        }
        if (err && strcmp(err, "Compaction cancelled") == 0) {
            notice(a, RED, "%s", err);
        } else 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, "key_failure") == 0) { /* a pic event: the swap prompt follows the child's end */
        char *req = jget(a, ev, "$.request"), *prov = jget(a, ev, "$.provider"), *label = jget(a, ev, "$.label"),
             *state = jget(a, ev, "$.state");
        memset(&a->kp, 0, sizeof a->kp);
        a->kp.pending = 1;
        (void)snprintf(a->kp.request, sizeof a->kp.request, "%s", req ? req : "");
        (void)snprintf(a->kp.provider, sizeof a->kp.provider, "%s", prov ? prov : "");
        (void)snprintf(a->kp.label, sizeof a->kp.label, "%s", label ? label : "");
        a->kp.state = !state                        ? PIC_KEY_OTHER
                      : strcmp(state, "invalid") == 0 ? PIC_KEY_INVALID
                      : strcmp(state, "credit") == 0  ? PIC_KEY_CREDIT
                      : strcmp(state, "limited") == 0 ? PIC_KEY_LIMITED
                                                      : PIC_KEY_OTHER;
        a->kp.status = (int)jnum(a, ev, "$.status");
        a->kp.until = jnum(a, ev, "$.until");
        a->status[0] = '\0';
        a->key_seg_at = 0; /* the footer reads the new state */
        free(req);
        free(prov);
        free(label);
        free(state);
    } else if (strcmp(type, "agent_end") == 0) {
        char *status = jget(a, ev, "$.status"), *err = jget(a, ev, "$.errorMessage");
        if (a->title_guess) {
            load_title(a);
        }
        blocks_flush(a, 1);
        commit_stream(a);
        a->seen_end = 1;
        /* the user cancelled: they are here, nothing to signal */
        a->done_kind = status && strcmp(status, "failed") == 0 ? (err && strcmp(err, "cancelled") == 0 ? 0 : 2) : 1;
        if (a->kp.pending) {
            a->done_kind = 2; /* waits on the user's choice of key */
        }
        if (status && strcmp(status, "failed") == 0) {
            if (err && strcmp(err, "cancelled") == 0) {
                notice(a, RED, "Operation aborted"); /* Pi's words for an abort */
            } else if (a->retried > 0) {
                notice(a, RED, "Retry failed after %d attempts: %s", a->retried, err ? err : "Unknown error");
            } else {
                notice(a, RED, "request failed: %s", err ? err : "");
            }
        } else if (status && strcmp(status, "stopped") == 0) {
            char *why = jget(a, ev, "$.stopReason");
            notice(a, YELLOW, "request stopped (%s); send a message to continue", why ? why : "");
            free(why);
        } else {
            /* The workspace's verify command, when it has one: one quiet line. */
            char *verdict = jget(a, ev, "$.verdict");
            if (verdict) {
                int pass = strcmp(verdict, "pass") == 0, fail = strcmp(verdict, "fail") == 0;
                notice(a, pass ? DIM : YELLOW, "verify: %s", pass ? "passed" : fail ? "failed" : "unknown (not run again)");
            }
            free(verdict);
        }
        a->status[0] = '\0';
        a->retry_n = 0;
        (void)tui_git_branch(a->o->workspace, a->branch, sizeof a->branch); /* the agent may have switched it */
        free(status);
        free(err);
    }
    free(type);
}

static void app_command(app *a, char *line);
static void done_signal(app *a);

/* Queued commands, then the next message, once nothing holds the journal. */
static void run_queued(app *a) {
    while (a->nqueue && !a->working && !a->bash.running && !a->quit) {
        char *next = a->queue[0];
        memmove(a->queue, a->queue + 1, (size_t)(a->nqueue - 1) * sizeof *a->queue);
        a->nqueue--;
        if (run_bang(a, next)) {
            /* a command: started above */
        } else if (next[0] == '/' && !template_for(a, next) && !skill_for(a, next)) {
            app_command(a, next);
        } else {
            start_request(a, next, NULL, 0);
        }
        free(next);
    }
}

/* Handles complete event lines; at the end of the child, settles the run. */
static void app_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 > STOP_GRACE_MS * 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;
        }
        run_ended(&a->run, status);
        (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);
        }
        if (a->run.in >= 0) {
            close(a->run.in);
        }
        child_pid = 0;
        a->abort_sent = a->clear_sent = a->clear_notice = 0;
        a->stop_at = 0;
        a->stop_level = 0;
        commit_stream(a);
        if (a->compacting) { /* Pi's showError: "Nothing to compact (session too small)", "Already compacted" */
            const char *e = a->run.errbuf.buf ? a->run.errbuf.buf : "";
            size_t n = strlen(e);
            while (n && (e[n - 1] == '\n' || e[n - 1] == '\r')) {
                n--;
            }
            if (!a->seen_end && WIFEXITED(status) && WEXITSTATUS(status) != 0 && n) {
                notice(a, RED, "%.*s", (int)(strncmp(e, "pic: ", 5) == 0 ? n - 5 : n), strncmp(e, "pic: ", 5) == 0 ? e + 5 : e);
            }
            a->seen_end = 1;
            a->compacting = 0;
        }
        if (a->kp.pending) { /* refused for its key: the request waits on the swap prompt */
            a->resuming = 0;
            a->seen_end = 1;
            kp_show(a);
        }
        if (a->resuming) { /* ended: done with it; else the offer stands (no key here, say) */
            int ended = a->seen_end;
            a->resuming = 0;
            if (ended) {
                a->unfinished[0] = '\0';
            } else {
                if (a->run.errbuf.len) {
                    notice(a, RED, "%s", a->run.errbuf.buf);
                }
                notice(a, YELLOW, "the last request was interrupted: Enter to resume, Esc to drop it");
                a->seen_end = 1;
            }
        }
        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));
                a->done_kind = 2;
            } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
                notice(a, RED, "the request failed (exit %d)", WEXITSTATUS(status));
                a->done_kind = 2;
            }
        }
        free(a->run.outbuf.buf);
        free(a->run.errbuf.buf);
        memset(&a->run, 0, sizeof a->run);
        a->run.in = a->run.out = a->run.err = -1;
        a->working = 0;
        restore_held(a, 1); /* sent or queued, and never run: back to the editor */
        blocks_flush(a, 1);
        a->status[0] = '\0';
        run_queued(a);
        if (a->done_kind && !a->working && !a->bash.running) { /* nothing queued ran: pic waits for the user */
            done_signal(a);
        }
        a->done_kind = 0;
    }
}

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

/* SQL over one JSON argument (?1) giving one text value, malloc'd; NULL when none. */
static char *jsql(app *a, const char *sql, const char *doc) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(a->db, sql, -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, doc, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* A journaled reply drawn as it was live: its thinking, text and tool calls
 * in order (a call waits in a->blocks for its result). */
static void history_reply(app *a, const char *line) {
    for (int i = 0;; i++) {
        char key[48], *block, *type;
        (void)snprintf(key, sizeof key, "$.content[%d]", i);
        if (!(block = jget(a, line, key))) {
            break;
        }
        type = jget(a, block, "$.type");
        if (type && strcmp(type, "thinking") == 0) {
            char *t = jget(a, block, "$.thinking");
            blocks_flush(a, 1);
            text_clear(&a->thinking);
            (void)text_add(&a->thinking, t ? t : "", t ? strlen(t) : 0);
            commit_thinking(a);
            free(t);
        } else if (type && strcmp(type, "text") == 0) {
            char *t = jget(a, block, "$.text");
            blocks_flush(a, 1);
            if (t && t[strspn(t, " \t\r\n")]) {
                text_clear(&a->stream);
                (void)text_add(&a->stream, t, strlen(t));
                commit_stream(a);
            }
            free(t);
        } else if (type && strcmp(type, "toolCall") == 0) {
            char *ev = jsql(a, "SELECT json_object('toolName', json_extract(?1, '$.name'), 'toolCallId', json_extract(?1, '$.id'),"
                               " 'args', json(coalesce(json_extract(?1, '$.arguments'), '{}')))", block);
            if (ev) {
                tool_start(a, ev);
            }
            free(ev);
        }
        free(type);
        free(block);
    }
}

/* A journaled tool result completes its call's block, drawn when the calls
 * before it are. */
static void history_result(app *a, const char *line) {
    char *ev = jsql(a, "SELECT json_object('toolCallId', json_extract(?1, '$.callId'), 'isError', json_extract(?1, '$.isError'),"
                       " 'result', json_object('content', json_array(json_object('type', 'text', 'text', json_extract(?1, '$.text')))))",
                    line);
    int found = 0;
    for (int i = 0; ev && i < a->nblocks; i++) {
        found |= a->blocks[i].state == TUI_TOOL_PENDING;
    }
    if (!found) { /* a result whose call is not on the path: draw it on its own */
        char *tool = jget(a, line, "$.tool"), *callid = jget(a, line, "$.callId"), *start;
        start = jsql(a, "SELECT json_object('toolName', ?1)", tool ? tool : "tool");
        if (start) {
            tool_start(a, start);
            if (callid) {
                (void)snprintf(a->blocks[a->nblocks - 1].id, sizeof a->blocks[0].id, "%s", callid);
            }
        }
        free(start);
        free(tool);
        free(callid);
    }
    if (ev) {
        tool_end(a, ev);
    }
    for (int i = 0; i < a->nblocks; i++) {
        if (a->blocks[i].state != TUI_TOOL_PENDING) {
            a->blocks[i].took_ms = -1; /* not journaled: no "Took" */
        }
    }
    blocks_flush(a, 0);
    free(ev);
}

static void app_show_history(app *a) {
    const char *args[] = {"log", "--json", a->conversation, NULL};
    char *out = NULL;
    /* the footer counts the conversation's requests, as Pi's counts its session's */
    a->in = a->out = a->cache_read = a->cache_write = a->context = 0;
    a->cost = 0;
    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");
            char *bash_cmd = kind && strcmp(kind, "user") == 0 ? jget(a, line, "$.bash.command") : NULL;
            if (!kind || strcmp(kind, "tool_result") != 0) {
                blocks_flush(a, 1);
            }
            if (jget_has(a, line, "$.usage")) {
                long long tin = jnum(a, line, "$.usage.pic_tokens.input"), tout = jnum(a, line, "$.usage.pic_tokens.output"),
                          tcr = jnum(a, line, "$.usage.pic_tokens.cacheRead"), tcw = jnum(a, line, "$.usage.pic_tokens.cacheWrite");
                char *cost = jget(a, line, "$.usage.pic_cost.total");
                a->in += tin;
                a->out += tout;
                a->cache_read += tcr;
                a->cache_write += tcw;
                if (tin + tout + tcr + tcw > 0) {
                    a->context = tin + tout + tcr + tcw;
                }
                a->cost += cost ? strtod(cost, NULL) : 0;
                free(cost);
            }
            if (bash_cmd) { /* a "!" command: drawn as it was when it ran */
                char *output = jget(a, line, "$.bash.output"), *code = jget(a, line, "$.bash.exitCode");
                tui_bash b = {bash_cmd, output ? output : "",
                              jnum(a, line, "$.bash.cancelled") == 1 ? TUI_BASH_CANCELLED : TUI_BASH_DONE,
                              code ? atoi(code) : 0, jnum(a, line, "$.bash.excludeFromContext") == 1};
                commit_bash(a, &b);
                free(output);
                free(code);
            } else if (kind && strcmp(kind, "user") == 0) {
                char *origin = jget(a, line, "$.origin");
                if (origin && strncmp(origin, "remote:", 7) == 0 && t) { /* a phone's, as it showed live */
                    const char *name = rc_origin_name(a, origin);
                    size_t fn = strlen(name) + strlen(t) + 8;
                    char *from = malloc(fn);
                    if (from) {
                        (void)snprintf(from, fn, "from %s: %s", name, t);
                    }
                    commit_user(a, from ? from : t);
                    free(from);
                } else {
                    commit_user(a, t ? t : "");
                }
                free(origin);
                if (t && *t) { /* Up/Down recalls the conversation's messages, oldest first */
                    tui_editor_history_add(a->ed, t);
                }
            } else if (kind && (strcmp(kind, "assistant") == 0 || strcmp(kind, "answer") == 0)) {
                if (jget_has(a, line, "$.content")) {
                    history_reply(a, line);
                } else if (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) {
                history_result(a, line);
            } else if (kind && strcmp(kind, "compaction") == 0) {
                notice(a, DIM, "\xe2\x94\x80 compacted history \xe2\x94\x80");
            } else if (kind && strcmp(kind, "branch_summary") == 0) { /* Pi's BranchSummaryMessageComponent */
                tui_lines shut = {NULL, 0, 0}, open_ = {NULL, 0, 0}, l = {NULL, 0, 0};
                tui_md_opts o;
                size_t cols = a->cols > 2 ? (size_t)a->cols : 2;
                char hint[96];
                notice(a, BOLD, "[branch]");
                (void)snprintf(hint, sizeof hint, "Branch summary (%sctrl+o%s to expand)", DIM, RESET);
                (void)tui_lines_add(&shut, hint, strlen(hint));
                (void)tui_lines_add(&open_, BOLD "Branch Summary" RESET, strlen(BOLD "Branch Summary" RESET));
                (void)tui_lines_add(&open_, "", 0);
                md_opts(a, &o);
                (void)tui_markdown(t ? t : "", t ? strlen(t) : 0, cols, &o, &open_);
                (void)tui_lines_add(&l, "", 0);
                commit_lines(a, &l);
                (void)tui_transcript_expandable(a->tr, (const char *const *)shut.lines, shut.n, (const char *const *)open_.lines,
                                                open_.n);
                if (a->expand_tools) {
                    commit_drawn(a, &open_);
                } else {
                    commit_drawn(a, &shut);
                }
                tui_lines_clear(&shut);
                tui_lines_clear(&open_);
            }
            free(bash_cmd);
            free(kind);
            free(t);
        }
        blocks_flush(a, 1);
    }
    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);
    free(a->pick_mark);
    a->pick_ids = a->pick_rows = NULL;
    a->pick_mark = NULL;
    a->npick = a->pick_at = a->picking = a->pick_trash = a->pick_archived = 0;
}

static void pick_undo_free(app *a) {
    for (int i = 0; i < a->npick_undo; i++) {
        free(a->pick_undo[i]);
    }
    free(a->pick_undo);
    a->pick_undo = NULL;
    a->npick_undo = 0;
}

/* The picker closed: what d did can no longer be undone with u (/restore still can). */
static void pick_close(app *a) {
    pick_free(a);
    pick_undo_free(a);
    a->pick_msg[0] = '\0';
}

/* Pi's session selector shows forks under the conversation they came from
 * (session-selector.ts: flattenSessionTree, buildTreePrefix): siblings ordered by
 * their subtree's latest activity, "\xe2\x94\x9c\xe2\x94\x80 " / "\xe2\x94\x94\xe2\x94\x80 " branches, a "\xe2\x94\x82  " where an ancestor continues.
 * ids and rows arrive most recent first, parents[i] is row i's forkedFrom (or NULL);
 * both arrays are reordered in place and the prefixes put in front of the rows. */
typedef struct {
    int *first, *next, *key, *order, n, out;
    char **ids, **rows, **parents;
    char **nids, **nrows;
} pick_tree_ctx;

static void pick_walk(pick_tree_ctx *c, int node, int depth, const char *anc, int last) {
    char prefix[256] = "", row[1024];
    if (depth > 0 && strlen(anc) + 8 < sizeof prefix) {
        (void)snprintf(prefix, sizeof prefix, "%s%s", anc, last ? "\xe2\x94\x94\xe2\x94\x80 " : "\xe2\x94\x9c\xe2\x94\x80 ");
    }
    (void)snprintf(row, sizeof row, "%s%s", prefix, c->rows[node]);
    c->nids[c->out] = c->ids[node];
    c->nrows[c->out++] = strdup(row);
    for (int ch = c->first[node]; ch >= 0; ch = c->next[ch]) {
        char sub[256];
        /* an ancestor below the root that is not the last child lets its line run down */
        (void)snprintf(sub, sizeof sub, "%s%s", anc, depth > 0 && !last ? "\xe2\x94\x82  " : "   ");
        if (depth < 40) {
            pick_walk(c, ch, depth + 1, sub, c->next[ch] < 0);
        }
    }
}

static void pick_tree(app *a, char **parents) {
    int n = a->npick;
    pick_tree_ctx c = {0};
    int *par = n ? malloc((size_t)n * sizeof *par) : NULL, *tail = n ? malloc((size_t)n * sizeof *tail) : NULL;
    int *ord = n ? malloc((size_t)n * sizeof *ord) : NULL;
    int roots_first = -1, roots_tail = -1;
    c.n = n;
    c.first = n ? malloc((size_t)n * sizeof *c.first) : NULL;
    c.next = n ? malloc((size_t)n * sizeof *c.next) : NULL;
    c.key = n ? malloc((size_t)n * sizeof *c.key) : NULL;
    c.nids = n ? malloc((size_t)n * sizeof *c.nids) : NULL;
    c.nrows = n ? malloc((size_t)n * sizeof *c.nrows) : NULL;
    c.ids = a->pick_ids;
    c.rows = a->pick_rows;
    if (n && par && tail && ord && c.first && c.next && c.key && c.nids && c.nrows) {
        for (int i = 0; i < n; i++) {
            par[i] = -1;
            for (int j = 0; j < n && parents[i]; j++) {
                par[i] = j != i && strcmp(a->pick_ids[j], parents[i]) == 0 ? j : par[i];
            }
            c.first[i] = c.next[i] = tail[i] = -1;
            c.key[i] = i;
        }
        for (int i = 0; i < n; i++) { /* a subtree sorts by its most recent member (the smallest index) */
            int guard = 0;
            for (int p = par[i]; p >= 0 && guard++ < n; p = par[p]) {
                c.key[p] = c.key[p] < i ? c.key[p] : i;
            }
        }
        for (int i = 0; i < n; i++) {
            ord[i] = i;
        }
        for (int i = 1; i < n; i++) { /* insertion sort by key: stable and cheap for a picker's size */
            int v = ord[i], j = i - 1;
            for (; j >= 0 && c.key[ord[j]] > c.key[v]; j--) {
                ord[j + 1] = ord[j];
            }
            ord[j + 1] = v;
        }
        for (int k = 0; k < n; k++) {
            int i = ord[k], p = par[i];
            if (p < 0) {
                if (roots_tail >= 0) {
                    c.next[roots_tail] = i;
                } else {
                    roots_first = i;
                }
                roots_tail = i;
            } else {
                if (tail[p] >= 0) {
                    c.next[tail[p]] = i;
                } else {
                    c.first[p] = i;
                }
                tail[p] = i;
            }
        }
        for (int r = roots_first; r >= 0; r = c.next[r]) {
            pick_walk(&c, r, 0, "", c.next[r] < 0);
        }
        if (c.out == n) {
            for (int i = 0; i < n; i++) {
                free(a->pick_rows[i]);
            }
            memcpy(a->pick_ids, c.nids, (size_t)n * sizeof *c.nids);
            memcpy(a->pick_rows, c.nrows, (size_t)n * sizeof *c.nrows);
        } else { /* a cycle left rows out: keep the flat list */
            for (int i = 0; i < c.out; i++) {
                free(c.nrows[i]);
            }
        }
    }
    free(par);
    free(tail);
    free(ord);
    free(c.first);
    free(c.next);
    free(c.key);
    free(c.nids);
    free(c.nrows);
}

enum { LIST_RESUME, LIST_TRASH, LIST_ARCHIVED };

/* The picker over the conversations (/resume), the deleted ones (/trash) or the archived ones
 * (/archived), by MODE; closed with a notice when there are none. */
static void open_list(app *a, int mode) {
    int trash = mode == LIST_TRASH;
    const char *args[] = {"sessions", trash ? "trash" : mode == LIST_ARCHIVED ? "archived" : "--json", mode ? "--json" : NULL, NULL};
    char *out = NULL, **parents = 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, *title, *forked, row[512], **ids, **rows, **pp;
            nl = strchr(line, '\n');
            if (nl) {
                *nl = '\0';
            }
            id = jget(a, line, "$.id");
            title = jget(a, line, "$.title");
            forked = trash ? NULL : jget(a, line, "$.forkedFrom");
            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;
            }
            pp = realloc(parents, (size_t)(a->npick + 1) * sizeof *pp);
            if (pp) {
                parents = pp;
            }
            if (id && ids && rows && pp) {
                if (trash) {
                    time_t t = (time_t)(jnum(a, line, "$.deletedMs") / 1000);
                    char when[32] = "";
                    struct tm tmv;
                    if (localtime_r(&t, &tmv)) {
                        (void)strftime(when, sizeof when, "%Y-%m-%d %H:%M", &tmv);
                    }
                    (void)snprintf(row, sizeof row, "%s  deleted %s  %s", id, when, title ? title : "-");
                } else {
                    (void)snprintf(row, sizeof row, "%s  %3lld  %s%s", id, jnum(a, line, "$.requests"), title ? title : "-",
                                   jnum(a, line, "$.live") == 1 ? "  \xe2\x97\x8f running in another pic" : "");
                }
                for (char *c = row; *c; c++) {
                    *c = *c == '\n' ? ' ' : *c;
                }
                a->pick_ids[a->npick] = id;
                a->pick_rows[a->npick] = strdup(row);
                parents[a->npick] = forked;
                a->npick++;
                id = forked = NULL;
            }
            free(id);
            free(title);
            free(forked);
        }
    }
    free(out);
    if (!trash) {
        pick_tree(a, parents);
    }
    for (int i = 0; i < a->npick; i++) {
        free(parents[i]);
    }
    free(parents);
    if (a->npick == 0) { /* the last one deleted closes the picker: u goes with it */
        char *undo = strstr(a->pick_msg, "u to undo");
        if (undo) {
            (void)snprintf(undo, sizeof a->pick_msg - (size_t)(undo - a->pick_msg), "%s",
                           a->npick_undo > 1 ? "/trash brings them back." : "/restore brings it back.");
        }
        if (a->pick_msg[0]) {
            notice(a, DIM, "%s", a->pick_msg);
        }
        notice(a, DIM, trash ? "no deleted conversations" : mode == LIST_ARCHIVED ? "no archived conversations" : "no conversations yet");
        pick_undo_free(a);
        a->pick_msg[0] = '\0';
        return;
    }
    a->pick_mark = calloc((size_t)a->npick, 1);
    a->pick_trash = trash;
    a->pick_archived = mode == LIST_ARCHIVED;
    a->picking = 1;
}

static void open_picker(app *a) { open_list(a, LIST_RESUME); }

/* The conversation pic deleted or restored, from its line "VERB ID  TITLE  ...": 0, or -1. */
static int done_line(const char *line, const char *verb, char *id, size_t idcap, char *title, size_t tcap) {
    size_t v = strlen(verb), n;
    const char *t, *end;
    if (strncmp(line, verb, v) != 0 || line[v] != ' ') {
        return -1;
    }
    line += v + 1;
    n = strcspn(line, " \n");
    (void)snprintf(id, idcap, "%.*s", (int)n, line);
    t = line + n;
    t += strspn(t, " ");
    end = strstr(t, "  (");
    n = end ? (size_t)(end - t) : strcspn(t, "\n");
    (void)snprintf(title, tcap, "%.*s", (int)n, t);
    return id[0] ? 0 : -1;
}

/* What pic said on stderr, as one line without its "pic: ". */
static void err_line(const char *err, char *out, size_t cap) {
    if (strncmp(err, "pic: ", 5) == 0) {
        err += 5;
    }
    (void)snprintf(out, cap, "%.*s", (int)strcspn(err, "\n"), err);
}

/* This conversation was deleted: the next message starts a new one, as after /new. */
static void deleted_current(app *a) {
    a->conversation[0] = a->name[0] = a->conv_title[0] = a->unfinished[0] = '\0';
    a->in = a->out = a->context = 0;
    a->cost = 0;
    notice(a, DIM, "\xe2\x94\x80 this conversation was deleted; your next message starts a new one \xe2\x94\x80");
}

/* The picker again after a change, the cursor near where it was (on ID when it is listed). */
static void pick_reload(app *a, const char *id) {
    int at = a->pick_at;
    open_list(a, a->pick_archived ? LIST_ARCHIVED : LIST_RESUME);
    if (!a->picking) {
        return;
    }
    a->pick_at = at < a->npick ? at : a->npick - 1;
    for (int i = 0; id && i < a->npick; i++) {
        a->pick_at = strcmp(a->pick_ids[i], id) == 0 ? i : a->pick_at;
    }
}

/* d in the picker: the marked conversations, or the selected one, deleted; u undoes it. */
/* a in the picker: the selected conversation archived (in /resume) or unarchived (in /archived). */
static void pick_archive(app *a) {
    const char *args[] = {a->pick_archived ? "unarchive" : "archive", a->pick_ids[a->pick_at], NULL};
    char *out = NULL, *err = NULL, id[64], title[200], why[256] = "";
    char *at = a->npick > a->pick_at + 1 ? strdup(a->pick_ids[a->pick_at + 1]) : NULL;
    (void)run_capture(a, args, &out, &err);
    if (out && done_line(out, a->pick_archived ? "unarchived" : "archived", id, sizeof id, title, sizeof title) == 0) {
        (void)snprintf(a->pick_msg, sizeof a->pick_msg, a->pick_archived ? "Unarchived \"%s\"." : "Archived \"%s\". /archived lists it.",
                       *title && strcmp(title, "-") != 0 ? title : id);
    } else {
        if (err && *err) {
            err_line(err, why, sizeof why);
        }
        (void)snprintf(a->pick_msg, sizeof a->pick_msg, "%s", why[0] ? why : "nothing changed");
    }
    free(out);
    free(err);
    pick_reload(a, at);
    free(at);
}

static void pick_delete(app *a) {
    const char **args = calloc((size_t)a->npick + 3, sizeof *args);
    char *out = NULL, *err = NULL, id[64], title[200], why[256] = "";
    int n = 0, marked = 0, current = 0;
    if (!args) {
        return;
    }
    args[n++] = "sessions";
    args[n++] = "delete";
    for (int i = 0; i < a->npick; i++) {
        marked += a->pick_mark && a->pick_mark[i];
    }
    for (int i = 0; i < a->npick; i++) {
        if (marked ? a->pick_mark[i] : i == a->pick_at) {
            args[n++] = a->pick_ids[i];
        }
    }
    (void)run_capture(a, args, &out, &err);
    free(args);
    pick_undo_free(a);
    for (char *line = out, *nl; line && *line; line = nl ? nl + 1 : NULL) {
        char **grown;
        nl = strchr(line, '\n');
        if (done_line(line, "deleted", id, sizeof id, title, sizeof title) != 0 ||
            !(grown = realloc(a->pick_undo, (size_t)(a->npick_undo + 1) * sizeof *grown))) {
            continue;
        }
        a->pick_undo = grown;
        a->pick_undo[a->npick_undo++] = strdup(id);
        current |= strcmp(id, a->conversation) == 0;
    }
    if (err && *err) {
        err_line(err, why, sizeof why);
    }
    if (a->npick_undo == 1) {
        (void)snprintf(a->pick_msg, sizeof a->pick_msg, "Deleted \"%s\". u to undo%s%s", title, why[0] ? " \xc2\xb7 " : "", why);
    } else if (a->npick_undo > 1) {
        (void)snprintf(a->pick_msg, sizeof a->pick_msg, "Deleted %d conversations. u to undo%s%s", a->npick_undo,
                       why[0] ? " \xc2\xb7 " : "", why);
    } else {
        (void)snprintf(a->pick_msg, sizeof a->pick_msg, "%s", why[0] ? why : "nothing was deleted");
    }
    free(out);
    free(err);
    if (current) {
        deleted_current(a);
    }
    pick_reload(a, NULL);
}

/* u in the picker: what the last d deleted, back. */
static void pick_restore(app *a) {
    char id[64] = "", title[200] = "", why[256] = "", first[64] = "";
    int restored = 0;
    if (a->npick_undo == 0) {
        (void)snprintf(a->pick_msg, sizeof a->pick_msg, "nothing to undo");
        return;
    }
    for (int i = 0; i < a->npick_undo; i++) {
        const char *args[] = {"sessions", "restore", a->pick_undo[i], NULL};
        char *out = NULL, *err = NULL;
        if (run_capture(a, args, &out, &err) == 0 && done_line(out, "restored", id, sizeof id, title, sizeof title) == 0) {
            if (!restored++) {
                (void)snprintf(first, sizeof first, "%s", id);
            }
        } else if (err && *err) {
            err_line(err, why, sizeof why);
        }
        free(out);
        free(err);
    }
    pick_undo_free(a);
    if (restored == 1) {
        (void)snprintf(a->pick_msg, sizeof a->pick_msg, "Restored \"%s\".", title);
    } else if (restored > 1) {
        (void)snprintf(a->pick_msg, sizeof a->pick_msg, "Restored %d conversations.", restored);
    } else {
        (void)snprintf(a->pick_msg, sizeof a->pick_msg, "%s", why[0] ? why : "nothing was restored");
    }
    pick_reload(a, first[0] ? first : NULL);
}

/* /delete [ID|NAME] (default: this conversation). */
static void trash_delete(app *a, const char *what) {
    const char *args[] = {"sessions", "delete", what, NULL};
    char *out = NULL, *err = NULL, id[64], title[200], why[256];
    if (run_capture(a, args, &out, &err) == 0 && done_line(out, "deleted", id, sizeof id, title, sizeof title) == 0) {
        notice(a, DIM, "Deleted \"%s\". /restore brings it back.", title);
        if (strcmp(id, a->conversation) == 0) {
            deleted_current(a);
        }
    } else {
        err_line(err ? err : "", why, sizeof why);
        notice(a, RED, "%s", why[0] ? why : "could not delete it");
    }
    free(out);
    free(err);
}

/* /restore [ID|NAME] (default: the one deleted last), and enter in /trash. */
static void trash_restore(app *a, const char *what) {
    const char *args[] = {"sessions", "restore", what && *what ? what : NULL, NULL};
    char *out = NULL, *err = NULL, id[64], title[200], why[256];
    if (run_capture(a, args, &out, &err) == 0 && done_line(out, "restored", id, sizeof id, title, sizeof title) == 0) {
        notice(a, DIM, "Restored \"%s\". /resume %s opens it.", title, id);
    } else {
        err_line(err ? err : "", why, sizeof why);
        notice(a, RED, "%s", why[0] ? why : "could not restore it");
    }
    free(out);
    free(err);
}

static int key_model_provider(const char *model, char *out, size_t cap, pic_model *m);

/* A conversation taken up goes on with its own model, key and thinking level (from pic sessions
 * --json), unless --model was given; one that cannot be had now is said, with the model it goes on
 * with and how to change it: never another model in silence. */
static void tui_resume_choice(app *a, const char *model, const char *credential, const char *thinking) {
    char why[400], label[PIC_CRED_LABEL_CAP] = "", named[PIC_CRED_LABEL_CAP + 16] = "";
    const char *colon = credential ? strchr(credential, ':') : NULL;
    pic_model m;
    pic_cred_used inuse;
    if (a->o->model_named || !model || !*model) {
        if (a->o->model_note && !a->told_model) {
            a->told_model = 1;
            notice(a, strncmp(a->o->model_note, "No key", 6) == 0 ? YELLOW : DIM, "%s", a->o->model_note);
        }
        return;
    }
    a->told_model = 1;
    if (colon) {
        (void)snprintf(label, sizeof label, "%s", colon + 1);
    }
    if (pic_model_usable(model, label, why, sizeof why) != PIC_MODEL_USABLE) {
        notice(a, YELLOW, "%s; it goes on with %s: /model picks another model, /login adds a key", why, a->model);
        return;
    }
    (void)snprintf(a->model, sizeof a->model, "%s", model);
    if (thinking && *thinking) {
        (void)snprintf(a->think_level, sizeof a->think_level, "%s", thinking);
    }
    if (label[0] && key_model_provider(model, a->key_run_provider, sizeof a->key_run_provider, &m) == 0) {
        if (pic_cred_active(m.provider, m.key_env, m.key_literal, &inuse) != 0 || strcmp(inuse.label, label) != 0) {
            (void)snprintf(named, sizeof named, ", key \"%s\"", label);
        }
        (void)snprintf(a->key_run, sizeof a->key_run, "%s", label);
        (void)pic_cred_override(m.provider, label);
    }
    notice(a, DIM, "model %s%s (this conversation's own; /model to change)", model, named);
}

static void resume(app *a, const char *id) {
    const char *args[] = {"sessions", "--json", NULL};
    char *out = NULL, *own_model = NULL, *own_key = NULL, *own_level = NULL;
    if (a->conversation[0] && strcmp(a->conversation, id) != 0 && !a->working) {
        hook_end(a, "other");
    }
    (void)snprintf(a->conversation, sizeof a->conversation, "%s", id);
    a->name[0] = a->conv_title[0] = a->unfinished[0] = '\0';
    if (run_sync(a, args, &out) == 0) {
        for (char *line = out, *nl; line && *line; line = nl ? nl + 1 : NULL) {
            char *lid, *name, *title, *pending, *model;
            nl = strchr(line, '\n');
            if (nl) {
                *nl = '\0';
            }
            lid = jget(a, line, "$.id");
            name = jget(a, line, "$.name");
            title = jget(a, line, "$.title");
            pending = jget(a, line, "$.pending");
            model = jget(a, line, "$.pendingModel");
            if (lid && strcmp(lid, id) == 0 && name) {
                (void)snprintf(a->name, sizeof a->name, "%s", name);
            }
            if (lid && strcmp(lid, id) == 0 && title) {
                (void)snprintf(a->conv_title, sizeof a->conv_title, "%s", title);
            }
            if (lid && strcmp(lid, id) == 0 && !own_model) {
                own_model = jget(a, line, "$.model");
                own_key = jget(a, line, "$.credential");
                own_level = jget(a, line, "$.thinking");
            }
            if (lid && strcmp(lid, id) == 0 && pending && !a->working && jnum(a, line, "$.live") != 1) {
                /* not one another pic is running now: the follower shows that one running */
                (void)snprintf(a->unfinished, sizeof a->unfinished, "%s", pending);
                (void)snprintf(a->unfinished_model, sizeof a->unfinished_model, "%s", model ? model : "");
            }
            free(model);
            free(lid);
            free(name);
            free(title);
            free(pending);
        }
    }
    free(out);
    notice(a, DIM, "\xe2\x94\x80 continuing %s \xe2\x94\x80", id);
    tui_resume_choice(a, own_model, own_key, own_level);
    free(own_model);
    free(own_key);
    free(own_level);
    app_show_history(a);
    if (a->unfinished[0]) { /* a crash cut it off: "a run that dies is picked up by the next pic" */
        notice(a, YELLOW, "the last request was interrupted: Enter to resume, Esc to drop it");
    }
}

/* ---- the model picker (Pi's, see model-selector.ts) ----------------------
 * A layer over everything but the settings panel, as that panel is (tui/modelpanel.h): it opens while a
 * reply runs, takes every key while open, and a model chosen in it applies from the next request. */

static void app_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_price[i]);
        free(a->mp_status[i]);
        free(a->mp_key[i]);
    }
    free(a->mp_models);
    free(a->mp_names);
    free(a->mp_search);
    free(a->mp_price);
    free(a->mp_status);
    free(a->mp_key);
    free(a->mp_avail);
    free(a->mp_warn);
    free(a->mp_window);
    free(a->mp_order);
    a->mp_models = a->mp_names = a->mp_search = a->mp_price = a->mp_status = a->mp_key = NULL;
    a->mp_avail = a->mp_warn = 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_in(app *a, int ranked, int all);

static void load_models(app *a) { load_models_in(a, 1, 0); }

/* A price per million tokens, short: $15, $2.5, $0.05. */
static void fmt_price(double v, char *out, size_t cap) {
    (void)snprintf(out, cap, v >= 10 ? "$%.0f" : v >= 1 ? "$%.3g" : "$%.2g", v);
}

/* The picker's words for how a provider's key stands (pic models --json's key), or NULL. */
static const char *key_mark(const char *key) {
    return !key                                ? NULL
           : strcmp(key, "none") == 0          ? "no key"
           : strcmp(key, "refused") == 0       ? "key refused"
           : strcmp(key, "no credit") == 0     ? "out of credit"
           : strcmp(key, "limited") == 0       ? "rate-limited"
           : strcmp(key, "ChatGPT plan") == 0  ? "ChatGPT plan"
                                               : NULL;
}

/* Room for CAP rows in every row array; 0, or -1 with the arrays as they were. */
static int models_grow(app *a, size_t cap) {
    char **m1 = realloc(a->mp_models, cap * sizeof *m1), **m2, **m3, **m4, **m5;
    int *av, *wr;
    long *w;
    size_t *o;
    if (m1) {
        a->mp_models = m1;
    }
    if ((m2 = realloc(a->mp_names, cap * sizeof *m2))) {
        a->mp_names = m2;
    }
    if ((m3 = realloc(a->mp_search, cap * sizeof *m3))) {
        a->mp_search = m3;
    }
    if ((m4 = realloc(a->mp_price, cap * sizeof *m4))) {
        a->mp_price = m4;
    }
    if ((m5 = realloc(a->mp_status, cap * sizeof *m5))) {
        a->mp_status = m5;
    }
    if ((m5 = realloc(a->mp_key, cap * sizeof *m5))) {
        a->mp_key = m5;
    }
    if ((av = realloc(a->mp_avail, cap * sizeof *av))) {
        a->mp_avail = av;
    }
    if ((wr = realloc(a->mp_warn, cap * sizeof *wr))) {
        a->mp_warn = wr;
    }
    if ((w = realloc(a->mp_window, cap * sizeof *w))) {
        a->mp_window = w;
    }
    if ((o = realloc(a->mp_order, (cap + 1) * sizeof *o))) {
        a->mp_order = o;
    }
    return m1 && m2 && m3 && m4 && m5 && av && wr && w && o ? 0 : -1;
}

/* RANKED: the picker's order (model_rank); otherwise pic models' own, Pi's
 * registry order, which Ctrl+P cycles through. ALL: models whose provider has
 * no key too (pic models --all), which the picker shows once something is typed. */
static void load_models_in(app *a, int ranked, int all) {
    const char *args[] = {"models", "--json", all ? "--all" : NULL, NULL};
    char *out = NULL;
    size_t cap = 0;
    app_models_free(a);
    a->mp_all = all;
    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 ((size_t)a->nmodels == cap) {
            if (models_grow(a, cap ? cap * 2 : 128) != 0) {
                break;
            }
            cap = cap ? cap * 2 : 128;
        }
        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], price[40] = "", status[160] = "", in[16], outp[16];
            char *key = jget(a, line, "$.key"), *avail = jget(a, line, "$.available"), *ep = jget(a, line, "$.endpoint");
            char *cred = jget(a, line, "$.credential"), *rule = jget(a, line, "$.rule"), keyed[80] = "";
            char *cin = jget(a, line, "$.cost.input"), *cout = jget(a, line, "$.cost.output");
            double ci = cin ? strtod(cin, NULL) : 0, co = cout ? strtod(cout, NULL) : 0;
            const char *mark = key_mark(key);
            if (ci > 0 || co > 0) {
                fmt_price(ci, in, sizeof in);
                fmt_price(co, outp, sizeof outp);
                (void)snprintf(price, sizeof price, "%s/%s", in, outp);
            }
            /* a saved endpoint's list is not checked to answer */
            (void)snprintf(status, sizeof status, "%s%s%s%s", mark ? mark : "", mark && ep ? " \xc2\xb7 " : "",
                           ep ? "from " : "", ep ? ep : "");
            (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_price[a->nmodels] = strdup(price);
            a->mp_status[a->nmodels] = strdup(status);
            if (cred && strchr(cred, ':')) { /* the key column: its label, and whether a rule chose it */
                (void)snprintf(keyed, sizeof keyed, "%s%s", strchr(cred, ':') + 1, rule ? " by rule" : "");
            }
            a->mp_key[a->nmodels] = strdup(keyed);
            free(cred);
            free(rule);
            a->mp_avail[a->nmodels] = !avail || strcmp(avail, "1") == 0 || strcmp(avail, "true") == 0;
            a->mp_warn[a->nmodels] = key && (strcmp(key, "refused") == 0 || strcmp(key, "no credit") == 0 ||
                                             strcmp(key, "limited") == 0);
            a->mp_window[a->nmodels] = jnum(a, line, "$.contextWindow");
            a->nmodels++;
            m = name = NULL;
            free(key);
            free(avail);
            free(ep);
            free(cin);
            free(cout);
        }
        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; ranked && 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;
            int av;
            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;
            t = a->mp_price[j], a->mp_price[j] = a->mp_price[j - 1], a->mp_price[j - 1] = t;
            t = a->mp_status[j], a->mp_status[j] = a->mp_status[j - 1], a->mp_status[j - 1] = t;
            t = a->mp_key[j], a->mp_key[j] = a->mp_key[j - 1], a->mp_key[j - 1] = t;
            av = a->mp_avail[j], a->mp_avail[j] = a->mp_avail[j - 1], a->mp_avail[j - 1] = av;
            av = a->mp_warn[j], a->mp_warn[j] = a->mp_warn[j - 1], a->mp_warn[j - 1] = av;
            w = a->mp_window[j], a->mp_window[j] = a->mp_window[j - 1], a->mp_window[j - 1] = w;
        }
    }
    if (!a->mp_order) {
        a->mp_order = malloc(((size_t)a->nmodels + 1) * sizeof *a->mp_order);
    }
}

/* How well the picker's FILTER names model I: 0 exactly (the whole name or
 * its id), 1 as a prefix of the name, the id or a part of the id after a
 * '/', 2 otherwise; 3 more when its provider has no key. */
static int filter_rank(const app *a, size_t i, const char *filter) {
    const char *m = a->mp_models[i], *id = strchr(m, '/');
    size_t n = strlen(filter);
    int r = 2;
    id = id ? id + 1 : m;
    if (n && !strchr(filter, ' ')) {
        if (strcasecmp(m, filter) == 0 || strcasecmp(id, filter) == 0) {
            r = 0;
        } else if (strncasecmp(m, filter, n) == 0) {
            r = 1;
        } else {
            for (const char *p = id; p; p = strchr(p, '/'), p = p ? p + 1 : NULL) {
                if (strncasecmp(p + (*p == '~'), filter, n) == 0) {
                    r = 1;
                    break;
                }
            }
        }
    }
    return r + (a->mp_avail[i] ? 0 : 3);
}

/* The models used lately (get_recent_models), the latest first, for the picker's suggestions. */
static void load_recent(app *a) {
    char *data = cl_ask("get_recent_models", "\"limit\":10", NULL, 0);
    for (size_t i = 0; i < a->mp_nrecent; i++) {
        free(a->mp_recent[i]);
    }
    a->mp_nrecent = 0;
    for (size_t i = 0; data && i < sizeof a->mp_recent / sizeof *a->mp_recent; i++) {
        char path[48], *m;
        (void)snprintf(path, sizeof path, "$.models[%zu].model", i);
        if (!(m = cl_get(data, path))) {
            break;
        }
        a->mp_recent[a->mp_nrecent++] = m;
    }
    free(data);
}

/* The picker's rows: with something typed, Pi's fuzzy order over every model, then exact and prefix
 * matches first and models with no key last. With nothing typed, the suggested models
 * (tui_models_suggest), the current one selected, then the picker's own rows. */
static void filter_models(app *a) {
    a->mp_sel = 0;
    a->mp_lead = 0;
    if (!a->mp_order) {
        a->mp_n = 0;
        return;
    }
    if (a->mp_filter[strspn(a->mp_filter, " ")] == '\0') {
        a->mp_n = tui_models_suggest((const char *const *)a->mp_models, a->mp_avail, a->mp_warn, (size_t)a->nmodels, a->model,
                                     a->default_model, (const char *const *)a->mp_recent, a->mp_nrecent, a->mp_order,
                                     &a->mp_lead);
        for (int i = 0; i < a->nmodels; i++) {
            if (a->mp_models[i][0] == '\x01') {
                a->mp_order[a->mp_n++] = (size_t)i;
            }
        }
        return;
    }
    a->mp_n = tui_fuzzy_filter(a->mp_filter, (const char *const *)a->mp_search, (size_t)a->nmodels, a->mp_order);
    for (size_t i = 1; i < a->mp_n; i++) { /* stable: the fuzzy order within a rank */
        size_t at = a->mp_order[i];
        int r = filter_rank(a, at, a->mp_filter);
        size_t j = i;
        while (j > 0 && filter_rank(a, a->mp_order[j - 1], a->mp_filter) > r) {
            a->mp_order[j] = a->mp_order[j - 1];
            j--;
        }
        a->mp_order[j] = at;
    }
}

/* rememberModel (default true): a model chosen here is the one new conversations start on. */
static int remember_model(void) {
    char *v = cl_setting("rememberModel");
    int on = !(v && strcmp(v, "false") == 0);
    free(v);
    return on;
}

/* Switches the conversation to model I. With rememberModel on the pick is also saved, so the next
 * conversation starts on it (`pic models --last`); EXPLICIT is Ctrl+S, which with it off saves the
 * default, as it always did. A reply running now keeps its model: the change is from the next request. */
static void use_model(app *a, int i, int explicit_save) {
    char before[16], was[sizeof a->model];
    int offered = 0, remember = remember_model();
    ensure_level(a);
    (void)snprintf(before, sizeof before, "%s", a->level);
    (void)snprintf(was, sizeof was, "%s", a->model);
    (void)snprintf(a->model, sizeof a->model, "%s", a->mp_models[i]);
    a->window = a->mp_window[i];
    if (remember || explicit_save) {
        const char *args[] = {"models", remember ? "--last" : "--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);
            if (!remember) {
                notice(a, GREEN, "model %s, saved as the default: new conversations, pic ask and pic -p start on it", a->model);
            } else if (explicit_save) {
                notice(a, GREEN, "model %s; already saved: new conversations, pic ask and pic -p start on it", a->model);
            } else if (!a->told_remember) {
                a->told_remember = 1;
                notice(a, DIM, "model %s; new conversations start on it (rememberModel false stops this)", a->model);
            } else {
                notice(a, DIM, "model %s", a->model);
            }
        } else {
            notice(a, RED, "model %s, but it could not be saved for the next conversation", a->model);
        }
        free(out);
    } else {
        notice(a, DIM, "model %s", a->model);
    }
    if (a->working && strcmp(was, a->model) != 0) {
        notice(a, DIM, "The reply running now stays on %s; the next message goes to %s.", was, a->model);
    }
    if (!a->mp_avail[i]) {
        char provider[PIC_CRED_PROVIDER_CAP];
        const char *slash = strchr(a->model, '/');
        (void)snprintf(provider, sizeof provider, "%.*s", slash ? (int)(slash - a->model) : 0, a->model);
        notice(a, YELLOW, "%s has no key yet: your next message opens its login (or /login now)", provider);
    }
    refresh_level(a);
    for (int l = 0; l < a->nlvl; l++) {
        offered |= strcmp(a->lvls[l], before) == 0;
    }
    if (before[0] && a->level[0] && strcmp(before, a->level) != 0) { /* never changed without a word */
        notice(a, DIM, offered ? "thinking level %s, as last used with this model (was %s)"
                               : "thinking level %s: this model does not offer %s",
               a->level, before);
    }
    if (a->unfinished[0] && (a->kp.on || a->kp_model) && a->last_msg) { /* the refused message goes to this model */
        char *msg = strdup(a->last_msg);
        a->kp_model = 0;
        if (msg && drop_unfinished(a) == 0) {
            tui_editor_set(a->ed, msg);
            notice(a, DIM, "Your message is back in the editor: Enter sends it to %s.", a->model);
        }
        free(msg);
    }
}

/* Starts the background catalog refresh unless one runs or the catalog is
 * offline (the setting, or PIC_MODEL_CATALOG=offline, where the child would do nothing).
 * 1 when one is running now. */
static int refresh_catalog(app *a) {
    const char *mode = getenv("PIC_MODEL_CATALOG");
    char *offline = a->refreshing ? NULL : cl_setting("offline");
    int off = (mode && strcmp(mode, "offline") == 0) || (offline && strcmp(offline, "true") == 0);
    free(offline);
    if (!a->refreshing && !off) {
        const char *args[] = {"models", "--refresh", "--json", NULL};
        if (spawn(a, &a->refresh, args) == 0) {
            a->refreshing = 1;
        }
    }
    return a->refreshing;
}

/* The picker's own rows after the models: add an endpoint, and refresh the saved ones' lists
 * when there are any. Their ids start with \x01, which no model's does. */
static void picker_extra(app *a, const char *id, const char *label) {
    int at = a->nmodels;
    if (models_grow(a, (size_t)at + 1) != 0) {
        return;
    }
    a->mp_models[at] = strdup(id);
    a->mp_names[at] = strdup(label);
    a->mp_search[at] = strdup(label);
    a->mp_price[at] = strdup("");
    a->mp_status[at] = strdup("");
    a->mp_key[at] = strdup("");
    a->mp_avail[at] = 1;
    a->mp_warn[at] = 0;
    a->mp_window[at] = 0;
    if (a->mp_models[at] && a->mp_names[at] && a->mp_search[at] && a->mp_price[at] && a->mp_status[at] && a->mp_key[at]) {
        a->nmodels++;
    } else {
        free(a->mp_models[at]);
        free(a->mp_names[at]);
        free(a->mp_search[at]);
        free(a->mp_price[at]);
        free(a->mp_status[at]);
        free(a->mp_key[at]);
    }
}

static void picker_extras(app *a) {
    char *data = cl_ask("get_endpoints", "", NULL, 0);
    picker_extra(a, "\x01" "add", "+ Add an endpoint\xe2\x80\xa6");
    if (data && strstr(data, "\"name\":")) {
        picker_extra(a, "\x01" "refresh", "\xe2\x86\xbb Refresh endpoint models");
    }
    free(data);
}

static void ep_begin(app *a);
static void ep_refresh(app *a);

static void open_models(app *a, const char *filter) {
    load_models_in(a, 1, 1);
    load_recent(a);
    picker_extras(a);
    (void)snprintf(a->mp_filter, sizeof a->mp_filter, "%s", filter ? filter : "");
    filter_models(a);
    memset(&a->mpv, 0, sizeof a->mpv);
    a->mp_remember = remember_model();
    a->mp_open = 1;
    (void)refresh_catalog(a);
}

static void picker_close(app *a) {
    a->mp_open = 0;
    a->mp_filter[0] = '\0';
}

/* 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_in(a, 1, 1);
        picker_extras(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);
    }
}

/* What Enter does on the selected row, for the panel's description. */
static void picker_enter(app *a, char *out, size_t cap) {
    const char *m;
    if (!a->mp_n) {
        out[0] = '\0';
        return;
    }
    m = a->mp_models[a->mp_order[a->mp_sel]];
    if (strcmp(m, "\x01" "add") == 0) {
        (void)snprintf(out, cap, "enter: add an OpenAI-compatible server by its URL; its models join this list");
    } else if (m[0] == '\x01') {
        (void)snprintf(out, cap, "enter: fetch each saved endpoint's list of models again");
    } else if (a->working && strcmp(m, a->model) != 0) {
        (void)snprintf(out, cap, "The reply running now stays on %s. enter: the next message goes to %s", a->model, m);
    } else if (strcmp(m, a->model) == 0) {
        (void)snprintf(out, cap, "In use now. enter: keep it%s", a->mp_remember ? "; new conversations start on it" : "");
    } else if (!a->mp_avail[a->mp_order[a->mp_sel]]) {
        (void)snprintf(out, cap, "enter: the next message goes to %s; it has no key yet, so that message opens its login", m);
    } else {
        (void)snprintf(out, cap, "enter: the next message goes to %s%s", m,
                       a->mp_remember ? "; new conversations start on it" : "");
    }
}

/* With the view's rows in ROWS (room for mp_n), the panel's list as it is now. */
static void picker_list(app *a, tui_mrow *rows, tui_mlist *m, char *enter, size_t enter_cap) {
    static char hints[400], dstatus[240], more[80]; /* one model is the default */
    int remember = a->mp_remember, all = 0;
    for (size_t k = 0; k < a->mp_n; k++) {
        size_t i = a->mp_order[k];
        const char *st = a->mp_status[i];
        tui_mrow *r = &rows[i];
        memset(r, 0, sizeof *r);
        r->model = a->mp_models[i];
        r->name = a->mp_names[i];
        r->price = a->mp_price[i];
        r->status = st;
        r->window = a->mp_window[i];
        r->avail = a->mp_avail[i];
        r->warn = a->mp_warn[i];
        r->key = a->mp_key && a->mp_key[i][0] ? a->mp_key[i] : NULL; /* which key the model uses (#73) */
        r->group = k < a->mp_lead && a->mp_filter[strspn(a->mp_filter, " ")] == '\0' ? "In use and recent" : NULL;
        if (strcmp(r->model, "\x01" "add") == 0) {
            r->about = "An OpenAI-compatible server you run or reach, such as a local proxy.";
        } else if (r->model[0] == '\x01') {
            r->about = "Each saved endpoint's list of models, fetched again.";
        }
        if (strcmp(r->model, a->default_model) == 0) {
            (void)snprintf(dstatus, sizeof dstatus, "default%s%s", st[0] ? " \xc2\xb7 " : "", st);
            r->status = dstatus;
        }
    }
    (void)snprintf(hints, sizeof hints,
                   "type to filter \xc2\xb7 \xe2\x86\x91\xe2\x86\x93 move \xc2\xb7 enter: use%s \xc2\xb7 esc: close \xc2\xb7 "
                   "prices are $ per million tokens in/out",
                   remember ? "" : " \xc2\xb7 ctrl+s: use and save as the default");
    for (int i = 0; i < a->nmodels; i++) {
        all += a->mp_models[i][0] != '\x01';
    }
    (void)snprintf(more, sizeof more, "type to search all %d models", all);
    picker_enter(a, enter, enter_cap);
    memset(m, 0, sizeof *m);
    m->rows = rows;
    m->order = a->mp_order;
    m->n = a->mp_n;
    m->sel = (size_t)a->mp_sel;
    m->grouped = a->mp_filter[strspn(a->mp_filter, " ")] == '\0';
    m->filter = a->mp_filter;
    m->current = a->model;
    m->enter = enter;
    m->hints = hints;
    m->more = m->grouped ? more : NULL;
}

/* The picker as a box over the transcript (fullscreen, room for it) or in the rows above the footer, as
 * the settings panel is: FORM, WIDTH and LIST rows of list, appended to OUT. */
static void picker_draw(app *a, int form, size_t width, size_t list, tui_lines *out, int *crow, int *ccol) {
    tui_mrow *rows = calloc((size_t)a->nmodels + 1, sizeof *rows);
    tui_mlist m;
    char enter[600];
    if (!rows) {
        return;
    }
    picker_list(a, rows, &m, enter, sizeof enter);
    (void)tui_mpanel_lines(&a->mpv, &m, form, width, list, out, crow, ccol);
    free(rows);
}

/* The box's size for the window: its list rows and its whole height, from the list's length. */
static size_t picker_box_list(app *a, size_t w, size_t h) {
    tui_mrow *rows = calloc((size_t)a->nmodels + 1, sizeof *rows);
    tui_mlist m;
    char enter[600];
    size_t len, chrome, list = 1;
    if (!rows) {
        return 1;
    }
    picker_list(a, rows, &m, enter, sizeof enter);
    len = tui_mpanel_list_len(&m);
    chrome = tui_mpanel_chrome(&m, w);
    len = len < 3 ? 3 : len; /* room to say there is no match */
    if (h > chrome) {
        list = h - chrome < len ? h - chrome : len;
    }
    free(rows);
    return list;
}

static void picker_type(app *a, const char *text, size_t n) {
    size_t len = strlen(a->mp_filter);
    for (size_t i = 0; i < n && len + 1 < sizeof a->mp_filter; i++) {
        unsigned char c = (unsigned char)text[i];
        if (c < 0x20 || c == 0x7f) {
            continue;
        }
        a->mp_filter[len++] = (char)c;
    }
    a->mp_filter[len] = '\0';
    { /* no half a character at the end, when the filter is full */
        size_t at = len;
        while (at > 0 && ((unsigned char)a->mp_filter[at - 1] & 0xC0) == 0x80) {
            at--;
        }
        if (at > 0 && (unsigned char)a->mp_filter[at - 1] >= 0xC0) {
            unsigned char c = (unsigned char)a->mp_filter[at - 1];
            size_t need = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : 2;
            if (len - (at - 1) < need) {
                a->mp_filter[at - 1] = '\0';
            }
        }
    }
    filter_models(a);
}

/* Enter (or Ctrl+S) on the selected row. With no row nothing happens: the panel says nothing matches. */
static void picker_choose(app *a, int save) {
    const char *m;
    if (!a->mp_n) {
        return;
    }
    m = a->mp_models[a->mp_order[a->mp_sel]];
    if (m[0] == '\x01') {
        if (strcmp(m + 1, "add") == 0) {
            picker_close(a);
            ep_begin(a);
        } else {
            ep_refresh(a);
        }
        return;
    }
    {
        int i = (int)a->mp_order[a->mp_sel];
        picker_close(a);
        use_model(a, i, save);
    }
}

/* Every key and paste while the picker is open, as decoded: none reaches the editor or the running
 * request. Esc and Ctrl+C close it and never interrupt; the wheel and a click work on it alone. */
static void picker_key(app *a, const tui_key *k) {
    size_t len = strlen(a->mp_filter);
    a->esc_at = 0;
    a->ctrl_c_armed = 0;
    if (k->kind == TUI_KEY_MOUSE) {
        int line, col, hit = tui_render_hit(a->r, k->mx, k->my, &line, &col);
        if (hit == TUI_HIT_VIEW) {
            return; /* a click outside does nothing; the selection behind stays */
        }
        if (k->mouse == TUI_MOUSE_WHEEL && a->mp_n) {
            a->mp_sel = (a->mp_sel + (int)a->mp_n + (k->button < 0 ? -1 : 1)) % (int)a->mp_n;
        } else if (k->mouse == TUI_MOUSE_PRESS && k->button == 0 && line >= 0) {
            tui_mrow *rows = calloc((size_t)a->nmodels + 1, sizeof *rows);
            tui_mlist m;
            char enter[600];
            if (rows) {
                long at;
                picker_list(a, rows, &m, enter, sizeof enter);
                at = tui_mpanel_click(&a->mpv, &m, (size_t)line);
                free(rows);
                if (at >= 0) {
                    a->mp_sel = (int)at;
                }
            }
        }
        return;
    }
    if (a->km && tui_keymap_has(a->km, "app.model.select", k)) {
        picker_close(a);
        return;
    }
    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_HOME:
    case TUI_KEY_CTRL_HOME:
        a->mp_sel = 0;
        break;
    case TUI_KEY_END:
    case TUI_KEY_CTRL_END:
        a->mp_sel = a->mp_n ? (int)a->mp_n - 1 : 0;
        break;
    case TUI_KEY_ENTER:
    case TUI_KEY_CTRL_S:
        picker_choose(a, k->kind == TUI_KEY_CTRL_S);
        break;
    case TUI_KEY_ESC:
    case TUI_KEY_CTRL_C:
        picker_close(a);
        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_KILL_START:
    case TUI_KEY_DELETE_WORD:
        a->mp_filter[0] = '\0';
        filter_models(a);
        break;
    case TUI_KEY_CHAR:
        picker_type(a, k->text, strlen(k->text));
        break;
    case TUI_KEY_PASTE:
        if (k->paste) {
            picker_type(a, k->paste, k->paste_len);
        }
        break;
    default:
        break;
    }
}

/* HAY has NEEDLE in it, ignoring case. */
static int has_text(const char *hay, const char *needle) {
    size_t n = strlen(needle);
    for (; *hay; hay++) {
        if (strncasecmp(hay, needle, n) == 0) {
            return 1;
        }
    }
    return n == 0;
}

/* /model NAME: one clear match switches at once (the one exact match among models with a key, else
 * among all; else the only model with a key whose name has NAME in it, else the only model that matches);
 * several open the picker on them, ranked; none opens it saying so. /model alone opens it. */
/* /model NAME for a profile's NAME: its model, and its key and thinking level. 1 when it was one. */
static int model_profile(app *a, const char *name) {
    char *data = strchr(name, '/') ? NULL : cl_ask("get_profiles", "", NULL, 0), path[96], *model = NULL, *cred = NULL, *level = NULL;
    int found = 0;
    for (int i = 0; data && i < 256 && !found; i++) {
        char *n;
        (void)snprintf(path, sizeof path, "$.profiles[%d].name", i);
        if (!(n = cl_get(data, path))) {
            break;
        }
        if (strcmp(n, name) == 0) {
            found = 1;
            (void)snprintf(path, sizeof path, "$.profiles[%d].model", i);
            model = cl_get(data, path);
            (void)snprintf(path, sizeof path, "$.profiles[%d].credential", i);
            cred = cl_get(data, path);
            (void)snprintf(path, sizeof path, "$.profiles[%d].thinking", i);
            level = cl_get(data, path);
        }
        free(n);
    }
    if (found && model) {
        const char *colon = cred ? strchr(cred, ':') : NULL;
        (void)snprintf(a->model, sizeof a->model, "%s", model);
        if (colon) {
            (void)snprintf(a->key_run_provider, sizeof a->key_run_provider, "%.*s", (int)(colon - cred), cred);
            (void)snprintf(a->key_run, sizeof a->key_run, "%s", colon + 1);
            (void)pic_cred_override(a->key_run_provider, a->key_run);
        }
        if (level && *level) {
            (void)snprintf(a->think_level, sizeof a->think_level, "%s", level);
        }
        a->key_seg_at = 0;
        notice(a, DIM, "profile %s: %s%s%s%s%s, from the next message", name, model, colon ? ", key " : "", colon ? colon + 1 : "",
               level && *level ? ", thinking " : "", level && *level ? level : "");
    }
    free(model);
    free(cred);
    free(level);
    free(data);
    return found;
}

static void model_command(app *a, const char *arg) {
    int pick = -1, keyed = 0, any = 0, models = 0, keyed_at = -1, any_at = -1, only = -1, usable = 0, usable_at = -1;
    if (!*arg) {
        open_models(a, NULL);
        return;
    }
    if (model_profile(a, arg)) {
        return;
    }
    load_models_in(a, 1, 1);
    load_recent(a);
    picker_extras(a);
    (void)snprintf(a->mp_filter, sizeof a->mp_filter, "%s", arg);
    filter_models(a);
    for (size_t k = 0; k < a->mp_n; k++) {
        size_t i = a->mp_order[k];
        int r;
        if (a->mp_models[i][0] == '\x01') {
            continue;
        }
        models++;
        only = (int)i;
        if (a->mp_avail[i] && has_text(a->mp_models[i], a->mp_filter)) {
            usable++;
            usable_at = (int)i;
        }
        r = filter_rank(a, i, a->mp_filter);
        if (r == 0) {
            keyed++;
            keyed_at = (int)i;
        } else if (r == 3) {
            any++;
            any_at = (int)i;
        }
    }
    pick = keyed == 1 ? keyed_at : keyed == 0 && any == 1 ? any_at : keyed + any == 0 && usable == 1 ? usable_at
                                                                   : models == 1 ? only : -1;
    if (pick >= 0) {
        a->mp_filter[0] = '\0';
        use_model(a, pick, 0);
        return;
    }
    memset(&a->mpv, 0, sizeof a->mpv);
    a->mp_remember = remember_model();
    a->mp_open = 1;
    (void)refresh_catalog(a);
}

/* ---- /model's "Add an endpoint": a name, a URL and an optional key ---------------
 * Asked as add_endpoint (endpoints.h), which saves it and fetches its list; a key goes to the
 * credential store under the endpoint's name, so a locked store is opened first, through the
 * login panel's passphrase field. Nothing here changes the model in use or the default. */

enum { EP_NONE, EP_NAME, EP_URL, EP_KEY };

static void ep_clear(app *a) {
    pic_cred_wipe(a->ep_field, sizeof a->ep_field);
    a->ep_len = 0;
}

static void ep_end(app *a) {
    ep_clear(a);
    pic_cred_wipe(a->ep_key, sizeof a->ep_key);
    a->ep = EP_NONE;
    a->ep_err[0] = '\0';
}

static void ep_begin(app *a) {
    ep_end(a);
    a->ep_name[0] = a->ep_url[0] = '\0';
    a->ep = EP_NAME;
}

/* Asks add_endpoint with what the form holds, then says what came of it. */
static void ep_save(app *a) {
    char err[512] = "", *n = cl_member("name", a->ep_name), *u = cl_member("url", a->ep_url),
         *k = a->ep_key[0] ? cl_member("key", a->ep_key) : NULL, *data, *fetch_err, *count;
    sqlite3_str *t = sqlite3_str_new(NULL);
    char *members;
    sqlite3_str_appendf(t, "%s,%s%s%s", n ? n : "", u ? u : "", k ? "," : "", k ? k : "");
    members = sqlite3_str_finish(t);
    data = cl_ask("add_endpoint", members ? members : "", err, sizeof err);
    if (members) {
        pic_cred_wipe(members, strlen(members));
    }
    sqlite3_free(members);
    if (k) {
        pic_cred_wipe(k, strlen(k));
    }
    free(k);
    free(n);
    free(u);
    pic_cred_wipe(a->ep_key, sizeof a->ep_key);
    a->ep = EP_NONE;
    draw(a);
    if (!data) {
        notice(a, RED, "pic: %s", err);
        return;
    }
    fetch_err = cl_get(data, "$.error");
    count = cl_get(data, "$.count");
    if (fetch_err) {
        notice(a, YELLOW, "Saved the endpoint %s, but its models could not be fetched: %s. Refresh endpoint models in /model tries again.",
               a->ep_name, fetch_err);
    } else {
        notice(a, DIM, "Saved the endpoint %s: %s model%s, in /model as %s/MODEL. pic has not checked that each one answers.",
               a->ep_name, count ? count : "0", count && strcmp(count, "1") == 0 ? "" : "s", a->ep_name);
    }
    free(fetch_err);
    free(count);
    free(data);
}

/* The key step's Enter: an empty field is no key; a key needs the store open first. */
static void ep_key_done(app *a) {
    char err[256] = "";
    int st, q;
    if (!a->ep_key[0]) {
        ep_save(a);
        return;
    }
    st = pic_cred_state();
    q = st == PIC_CRED_OPEN ? 0 : pic_cred_quiet(err, sizeof err);
    if (q < 0) {
        ep_end(a);
        draw(a);
        notice(a, RED, "pic: %s", err);
        return;
    }
    if (q == 0) {
        ep_save(a);
        return;
    }
    a->ep = EP_NONE; /* the key waits in ep_key while the passphrase is typed */
    login_hold(a, a->ep_name, AFTER_ENDPOINT, "", NULL, 0);
    a->lg = st == PIC_CRED_NEW ? LG_PASS_NEW : LG_PASS;
}

static void ep_submit(app *a) {
    char err[256] = "";
    a->ep_field[a->ep_len] = '\0';
    a->ep_err[0] = '\0';
    if (a->ep == EP_NAME) {
        if (!a->ep_len || a->ep_len >= sizeof a->ep_name) {
            (void)snprintf(a->ep_err, sizeof a->ep_err, "a short name, such as proxy: its models are NAME/MODEL");
            return;
        }
        memcpy(a->ep_name, a->ep_field, a->ep_len + 1);
        ep_clear(a);
        a->ep = EP_URL;
    } else if (a->ep == EP_URL) {
        if (!a->ep_len || a->ep_len >= sizeof a->ep_url) {
            (void)snprintf(a->ep_err, sizeof a->ep_err, "the server's base URL, such as http://127.0.0.1:8317/v1");
            return;
        }
        memcpy(a->ep_url, a->ep_field, a->ep_len + 1);
        ep_clear(a);
        a->ep = EP_KEY;
    } else if (a->ep == EP_KEY) {
        if (a->ep_len && pic_cred_check("the key", a->ep_field, err, sizeof err) != 0) {
            (void)snprintf(a->ep_err, sizeof a->ep_err, "%s", err);
            return;
        }
        memcpy(a->ep_key, a->ep_field, a->ep_len + 1);
        ep_clear(a);
        ep_key_done(a);
    }
}

static void ep_type(app *a, const char *text, size_t n) {
    for (size_t i = 0; i < n && a->ep_len + 1 < sizeof a->ep_field; i++) {
        if ((unsigned char)text[i] >= ' ' && text[i] != 0x7f) {
            a->ep_field[a->ep_len++] = text[i];
        }
    }
}

static void ep_key_in(app *a, const tui_key *k) {
    switch (k->kind) {
    case TUI_KEY_ESC:
    case TUI_KEY_CTRL_C:
        ep_end(a);
        draw(a);
        notice(a, DIM, "No endpoint added.");
        break;
    case TUI_KEY_ENTER:
        ep_submit(a);
        break;
    case TUI_KEY_BACKSPACE:
        while (a->ep_len > 0 && ((unsigned char)a->ep_field[a->ep_len - 1] & 0xC0) == 0x80) {
            a->ep_len--;
        }
        if (a->ep_len > 0) {
            a->ep_len--;
        }
        break;
    case TUI_KEY_CHAR:
        ep_type(a, k->text, strlen(k->text));
        break;
    case TUI_KEY_PASTE:
        if (k->paste) {
            ep_type(a, k->paste, k->paste_len);
        }
        break;
    default:
        break;
    }
}

static void ep_lines(app *a, tui_lines *tail) {
    char line[1400];
    add_fit(tail, BOLD, "Add an endpoint  (an OpenAI-compatible server; its models join /model)", a->cols);
    if (a->ep > EP_NAME) {
        (void)snprintf(line, sizeof line, "Name: %s", a->ep_name);
        add_fit(tail, DIM, line, a->cols);
    }
    if (a->ep > EP_URL) {
        (void)snprintf(line, sizeof line, "URL: %s", a->ep_url);
        add_fit(tail, DIM, line, a->cols);
    }
    if (a->ep == EP_KEY) {
        char dots[3 * 48 + 1] = "";
        size_t shown = 0;
        for (size_t i = 0; i < a->ep_len && shown < 48; i++) {
            if (((unsigned char)a->ep_field[i] & 0xC0) != 0x80) {
                memcpy(dots + 3 * shown++, "\xe2\x80\xa2", 3);
            }
        }
        dots[3 * shown] = '\0';
        (void)snprintf(line, sizeof line, "API key (Enter for none): %s", dots);
    } else {
        (void)snprintf(line, sizeof line, "%s %.*s", a->ep == EP_NAME ? "Name (its models are NAME/MODEL):" : "URL:",
                       (int)a->ep_len, a->ep_field);
    }
    add_fit(tail, "", line, a->cols);
    if (a->ep_err[0]) {
        add_fit(tail, RED, a->ep_err, a->cols);
    }
    add_fit(tail, DIM,
            a->ep == EP_NAME  ? "enter: next \xc2\xb7 esc: cancel \xc2\xb7 a-z, 0-9, - _ . ; not a provider pic has"
            : a->ep == EP_URL ? "enter: next \xc2\xb7 esc: cancel \xc2\xb7 the base, such as http://127.0.0.1:8317/v1; pic fetches URL/models"
                              : "enter: save and fetch its models \xc2\xb7 esc: cancel \xc2\xb7 the key is sealed in ~/.pic/pic.sqlite",
            a->cols);
}

/* "Refresh endpoint models": each saved endpoint's list fetched again, the picker reloaded. */
static void ep_refresh(app *a) {
    char err[512] = "", *data = cl_ask("refresh_endpoints", "", err, sizeof err);
    char *rows = data ? cl_sql("SELECT group_concat(json_extract(value, '$.name') || ': ' ||"
                               " coalesce('the list it had is kept: ' || json_extract(value, '$.error'),"
                               " json_extract(value, '$.count') || ' models'), '; ')"
                               " FROM json_each(?1, '$.endpoints')",
                               data, NULL)
                      : NULL;
    char *failed = data ? cl_sql("SELECT 1 FROM json_each(?1, '$.endpoints') WHERE json_extract(value, '$.error') IS NOT NULL",
                                 data, NULL)
                        : NULL;
    if (!data) {
        notice(a, RED, "pic: %s", err);
    } else {
        notice(a, failed ? YELLOW : DIM, "Endpoints refreshed: %s", rows ? rows : "none saved");
    }
    free(rows);
    free(failed);
    free(data);
    if (a->mp_open) {
        load_models_in(a, 1, 1);
        picker_extras(a);
        filter_models(a);
    }
}

/* ---- 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 || a->ov == OV_LOGIN_PROVIDER || (a->ov == OV_ASK && strcmp(a->ask_kind, "confirm") != 0);
}

/* 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;
}

/* ---- Pi's themes and keybindings -------------------------------------- */

static const char *home_dir(void) {
    const char *h = getenv("HOME");
    return h && *h ? h : NULL;
}

/* Problems found loading themes or keybindings: kept as lines of text, shown by warn_flush (at start, once
 * the header is; on /reload, at once). */
static void warn_add(app *a, const char *lines) {
    size_t old = a->startup_warn ? strlen(a->startup_warn) : 0, add = lines ? strlen(lines) : 0;
    char *g;
    if (!add) {
        return;
    }
    if ((g = realloc(a->startup_warn, old + add + 1))) {
        memcpy(g + old, lines, add + 1);
        a->startup_warn = g;
    }
}

static void warn_flush(app *a) {
    char *w = a->startup_warn, *nl;
    a->startup_warn = NULL;
    for (char *line = w; line && *line; line = nl ? nl + 1 : NULL) {
        nl = strchr(line, '\n');
        if (nl) {
            *nl = '\0';
        }
        notice(a, YELLOW, "%s", line);
    }
    free(w);
}

/* The theme setting in effect: --theme for this run, else the saved one; malloc'd, NULL when unset. */
static char *theme_setting(const app *a) {
    return a->theme_cli[0] ? strdup(a->theme_cli) : cl_setting("theme");
}

/* Makes the theme a setting names (see tui_theme_setting_name) the current one. A name nobody defines falls
 * back to the system theme, with a warning. */
static void theme_use(app *a, const char *setting) {
    char name[64];
    const tui_theme *t;
    (void)tui_theme_setting_name(setting, tui_terminal_light(NULL), name, sizeof name);
    if (!(t = tui_themeset_find(&a->themes, name))) {
        char msg[160];
        (void)snprintf(msg, sizeof msg, "Theme \"%s\" not found; using the system theme\n", name);
        warn_add(a, msg);
        (void)tui_theme_setting_name("system", tui_terminal_light(NULL), name, sizeof name);
        t = tui_themeset_find(&a->themes, name);
    }
    if (t) {
        tui_theme_use(t, tui_terminal_truecolor());
    }
}

/* (Re)reads the theme files (the user's, and the workspace's when it is trusted) and applies the setting. */
static void themes_load(app *a) {
    char real[PATH_MAX], *w = NULL, *set;
    tui_themeset_free(&a->themes);
    if (tui_themeset_load(&a->themes, home_dir(), a->o->workspace, cl_trust_get(trust_path(a, real)) == 1, &w) != 0) {
        warn_add(a, "could not read the themes\n");
    }
    warn_add(a, w);
    free(w);
    set = theme_setting(a);
    theme_use(a, set);
    free(set);
}

/* The probe (TUI_TERM_PROBE), once raw mode is on, and a short wait for its answers before anything is
 * drawn, so the first frame already has the terminal's light or dark theme. A terminal that answers
 * nothing costs PROBE_WAIT_MS; answers that come later, within PROBE_WINDOW_MS, still apply. */
#define PROBE_WAIT_MS 150
#define PROBE_WINDOW_MS 1000
static void probe_start(app *a) {
    static const char q[] = TUI_TERM_PROBE;
    const char *term = getenv("TERM");
    const tui_term_replies *r = tui_keys_replies(a->keys);
    long until;
    if ((term && strcmp(term, "dumb") == 0) || write(STDOUT_FILENO, q, sizeof q - 1) != (ssize_t)(sizeof q - 1)) {
        return;
    }
    tui_keys_expect(a->keys, 1);
    a->probe_until = now_ms() + PROBE_WINDOW_MS;
    until = now_ms() + PROBE_WAIT_MS;
    while (!r->da1) {
        struct pollfd p = {STDIN_FILENO, POLLIN, 0};
        char buf[512];
        long left = until - now_ms();
        ssize_t got;
        if (left <= 0) {
            break;
        }
        if (poll(&p, 1, (int)left) <= 0) {
            continue;
        }
        if ((got = read(STDIN_FILENO, buf, sizeof buf)) <= 0) {
            break;
        }
        tui_keys_feed(a->keys, buf, (size_t)got); /* keys typed meanwhile stay queued for the loop */
    }
    if (r->light >= 0) {
        tui_terminal_light_set(r->light);
    }
    if (r->da1) {
        a->probe_until = 0;
    }
    a->reply_seq = r->seq;
    a->focus_in = r->focus_in;
    tui_term_alt_scroll_was(r->alt_scroll);
}

/* After the decoder took in replies: a background answer that turns light into dark or back re-picks a
 * theme that follows the terminal (system, or a light/dark pair); the reply window closes on DA1 or its
 * timeout. */
static void replies_apply(app *a) {
    const tui_term_replies *r = tui_keys_replies(a->keys);
    if (a->probe_until && (r->da1 || now_ms() >= a->probe_until)) {
        tui_keys_expect(a->keys, 0);
        a->probe_until = 0;
    }
    if (r->seq == a->reply_seq) {
        return;
    }
    a->reply_seq = r->seq;
    tui_term_alt_scroll_was(r->alt_scroll);
    if (r->focus_in != a->focus_in) { /* back from the terminal's menu, a browser, another split */
        a->focus_in = r->focus_in;
        mouse_take_back(a);
    }
    if (r->light >= 0 && r->light != tui_terminal_light(NULL)) {
        char *set = theme_setting(a), before[64], after[64];
        (void)tui_theme_setting_name(set, tui_terminal_light(NULL), before, sizeof before);
        tui_terminal_light_set(r->light);
        (void)tui_theme_setting_name(set, r->light, after, sizeof after);
        if (strcmp(before, after) != 0 && a->ov != OV_THEME) {
            theme_use(a, set);
        }
        free(set);
    }
}

/* A request ended and pic waits for the user: tell the terminal (tui_term_done_signal), unless the
 * notifyWhenDone setting is false. */
static void done_signal(app *a) {
    char *set = cl_setting("notifyWhenDone"), out[160];
    int off = set && strcmp(set, "false") == 0;
    size_t n;
    free(set);
    if (off) {
        return;
    }
    n = tui_term_done_signal(out, sizeof out, tui_keys_replies(a->keys)->focus, now_ms() - a->turn_t0,
                             a->done_kind == 2 ? "request failed" : "reply ready");
    if (n && write(STDOUT_FILENO, out, n) < 0) {
        /* a notification is a courtesy */
    }
}

/* The first key an action is bound to as Pi's search box shows it ("Shift+Enter", "Option+x" on a Mac), or "Unbound". */
static void key_label(const char *action, const tui_keymap *km, char *out, size_t cap) {
    char keys[160];
    size_t n = 0;
    keys[0] = '\0';
    tui_keymap_keys(km, (size_t)tui_keymap_find(action), keys, sizeof keys);
    keys[strcspn(keys, ",")] = '\0';
    if (!keys[0]) {
        (void)snprintf(out, cap, "Unbound");
        return;
    }
    for (const char *p = keys; *p && n + 8 < cap;) {
        size_t len = strcspn(p, "+");
        char part[24];
        (void)snprintf(part, sizeof part, "%.*s", (int)len, p);
#ifdef __APPLE__
        if (strcmp(part, "alt") == 0) {
            (void)snprintf(part, sizeof part, "option");
        }
#endif
        part[0] = (char)toupper((unsigned char)part[0]);
        n += (size_t)snprintf(out + n, cap - n, "%s%s", n ? "+" : "", part);
        p += len + (p[len] == '+' ? 1 : 0);
    }
}

/* (Re)reads ~/.pic/keybindings.json over Pi's defaults. */
static void keys_load(app *a) {
    char path[1024], *text = NULL, *w = NULL, letters[40];
    size_t len = 0;
    const char *h = home_dir();
    if (!a->km && !(a->km = tui_keymap_new())) {
        return;
    }
    if (h && snprintf(path, sizeof path, "%s/.pic/keybindings.json", h) < (int)sizeof path) {
        errno = 0;
        text = pic_input_read(path, 1u << 20, 0, &len, NULL);
        if (!text && errno != ENOENT) {
            warn_add(a, "~/.pic/keybindings.json could not be read; using the default keybindings\n");
        }
    }
    (void)tui_keymap_load(a->km, text, len, "~/.pic/keybindings.json", &w);
    warn_add(a, w);
    free(text);
    free(w);
    tui_keymap_alt_letters(a->km, letters);
    tui_keys_alt_letters(a->keys, letters);
    {
        char prev[32], next[32];
        key_label("tui.altScreen.searchPrevious", a->km, prev, sizeof prev);
        key_label("tui.altScreen.searchNext", a->km, next, sizeof next);
        tui_render_search_keys(a->r, prev, next);
    }
}

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);
}

/* A setting's value in effect, as the settings list has it (an unset or disallowed one is its default);
 * malloc'd, NULL when the list has no such row. */
static char *cl_effective(const char *id) {
    return cl_field("get_settings", "setting", id, "$.settings[0].value");
}

/* Applies the fullscreen settings to the renderer and the input. */
static void fs_apply(app *a) {
    char *bar = cl_effective("fullscreenScrollbar"), *out = cl_effective("fullscreenExitOutput"),
         *copy = cl_effective("fullscreenCopyOnSelect"), *wheel = cl_effective("fullscreenWheelScrollLines");
    int accelerate = 1;
#ifdef __APPLE__
    /* Pi's terminalAcceleratesWheel: local macOS terminals already do it */
    accelerate = getenv("SSH_CONNECTION") || getenv("SSH_CLIENT") || getenv("SSH_TTY");
#endif
    char *links = cl_effective("hyperlinks");
    tui_render_options(a->r, tui_scrollbar_mode(bar), !out || strcmp(out, "transcript") == 0);
    a->copy_on_select = !copy || strcmp(copy, "false") != 0;
    a->links = tui_hyperlinks_supported(links);
    tui_links_set(a->links != TUI_LINKS_OFF, a->o->workspace);
    tui_render_hide_links(a->r, a->links == TUI_LINKS_TEXT);
    free(links);
    tui_wheel_init(&a->wheel, tui_wheel_lines(wheel), accelerate);
    free(bar);
    free(out);
    free(copy);
    free(wheel);
}

/* The theme picker: moving over a row previews that theme at once; enter keeps it (saved as the `theme`
 * setting), esc puts the earlier one back. */
static void theme_open(app *a) {
    char *cur = theme_setting(a);
    ov_open(a, OV_THEME, "Theme  (up/down: preview \xc2\xb7 enter: choose \xc2\xb7 esc: cancel)",
            "system and light/dark follow the terminal (COLORFGBG); themes are read from ~/.pic/themes (and, in a trusted workspace, .pic/themes).");
    (void)snprintf(a->theme_prev, sizeof a->theme_prev, "%s", cur && *cur ? cur : "system");
    ov_add(a, "system (dark or light, by the terminal)", "system", 0);
    ov_add(a, "light/dark (automatic)", "light/dark", 0);
    for (size_t i = 0; i < a->themes.n; i++) {
        char label[160];
        (void)snprintf(label, sizeof label, "%s%s", a->themes.t[i].name, a->themes.t[i].path[0] ? "  (custom)" : "");
        ov_add(a, label, a->themes.t[i].name, 0);
    }
    ov_refilter(a);
    for (int i = 0; i < a->ov_n; i++) {
        if (strcmp(a->ov_id[i], a->theme_prev) == 0) {
            a->ov_sel = i;
        }
    }
    free(cur);
}

static void theme_preview(app *a) {
    if (a->ov == OV_THEME && a->ov_m) {
        theme_use(a, a->ov_id[a->ov_order[a->ov_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)cl_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 && cl_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;
    }
}

/* /tree, the request ending at entry SELECT chosen (NULL: the newest on
 * the path), as Pi re-shows it after "Summarize branch?" is left. */
static void tree_open(app *a, const char *select) {
    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, *said, *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");
        said = jget(a, line, "$.text");
        sessions = jget(a, line, "$.sessions");
        if (end && said) {
            int depth = indent ? atoi(indent) : 0;
            size_t first = strcspn(said, "\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), said);
            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 (select ? strcmp(end, select) == 0 : act && strcmp(act, "1") == 0) {
                active = a->ov_n - 1;
            }
        }
        free(end);
        free(indent);
        free(act);
        free(said);
        free(sessions);
        if (!nl) {
            break;
        }
    }
    free(out);
    ov_refilter(a);
    a->ov_sel = active < (int)a->ov_m ? active : 0;
}

/* Pi's "Summarize branch?" after a /tree choice. */
static void summary_open(app *a) {
    ov_open(a, OV_SUMMARY, "Summarize branch?  (up/down \xc2\xb7 enter \xc2\xb7 esc: back to the tree)",
            "A summary of the branch you leave goes into the conversation you continue.");
    ov_add(a, "No summary", "none", 0);
    ov_add(a, "Summarize", "summarize", 0);
    ov_add(a, "Summarize with custom prompt", "custom", 0);
    ov_refilter(a);
    a->ov_sel = 0;
}

/* Continues from the chosen request: without a summary, in the conversation
 * that already ends there or a new fork of this one (Pi's /tree switches the
 * leaf; pic's conversations are paths, so the fork is the new leaf); with
 * one, in a new conversation that starts with the summary of the branch
 * left (pic fork --summarize, Pi's branchWithSummary). */
static void tree_go(app *a, int summarize, const char *instructions) {
    const char *args[10];
    char *out = NULL;
    int n = 0;
    if (!summarize && a->branch_sess[0]) {
        resume(a, a->branch_sess);
        return;
    }
    args[n++] = "fork";
    args[n++] = a->conversation;
    args[n++] = "--at";
    args[n++] = a->branch_at;
    if (summarize) {
        args[n++] = "--summarize";
        if (instructions && *instructions) {
            args[n++] = "--instructions";
            args[n++] = instructions;
        }
        notice(a, DIM, "Summarizing branch...");
        draw(a);
    }
    args[n] = 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);
}

/* /fork with no argument: Pi's "Fork from Message" (user-message-selector.ts):
 * the earlier user messages, oldest first, the newest selected, two lines
 * each. Each row's id is the entry before that message ("0": none) and the
 * message's text, which goes back into the editor after the fork. */
static void fork_open(app *a) {
    const char *args[] = {"log", "--json", a->conversation, NULL};
    char *out = NULL, prev[32] = "0";
    if (run_sync(a, args, &out) != 0 || !out) {
        free(out);
        return;
    }
    ov_open(a, OV_FORK, "Fork from Message  (up/down \xc2\xb7 enter: fork \xc2\xb7 esc)",
            "Select a user message to copy the active path up to that point into a new session");
    for (char *line = out, *nl; *line; line = nl ? nl + 1 : line + strlen(line)) {
        char *kind, *seq, *text, *cmd;
        nl = strchr(line, '\n');
        if (nl) {
            *nl = '\0';
        }
        kind = jget(a, line, "$.kind");
        seq = jget(a, line, "$.seq");
        text = jget(a, line, "$.text");
        cmd = jget(a, line, "$.bash.command");
        if (kind && strcmp(kind, "user") == 0 && !cmd && text) {
            size_t n = strlen(text), plen = strlen(prev);
            char *row = malloc(plen + n + 2), *one = strdup(text);
            if (row && one) {
                for (char *c = one; *c; c++) {
                    *c = *c == '\n' ? ' ' : *c;
                }
                (void)snprintf(row, plen + n + 2, "%s %s", prev, text);
                ov_add(a, one, row, 0);
            }
            free(row);
            free(one);
        }
        if (seq) {
            (void)snprintf(prev, sizeof prev, "%s", seq);
        }
        free(kind);
        free(seq);
        free(text);
        free(cmd);
        if (!nl) {
            break;
        }
    }
    free(out);
    if (!a->ov_n) {
        ov_free(a);
        notice(a, DIM, "No messages to fork from");
        return;
    }
    ov_refilter(a);
    a->ov_sel = (int)a->ov_m - 1;
}

/* Enter in the picker: a new conversation with the path before that message
 * (none: an empty one), its text in the editor (Pi: runtimeHost.fork). */
static void fork_go(app *a) {
    char *row = strdup(a->ov_id[a->ov_order[a->ov_sel]]), *text, *out = NULL;
    if (!row) {
        return;
    }
    ov_free(a);
    text = strchr(row, ' ');
    *text++ = '\0';
    if (strcmp(row, "0") == 0) {
        if (!a->working) {
            hook_end(a, "other");
        }
        a->conversation[0] = a->name[0] = a->conv_title[0] = a->unfinished[0] = '\0';
        notice(a, DIM, "\xe2\x94\x80 forked: a new conversation \xe2\x94\x80");
    } else {
        const char *args[] = {"fork", a->conversation, "--at", row, NULL};
        if (run_sync(a, args, &out) != 0 || !out) {
            free(out);
            free(row);
            return;
        }
        out[strcspn(out, "\n")] = '\0';
        notice(a, DIM, "\xe2\x94\x80 forked: now in %s \xe2\x94\x80", out);
        resume(a, out);
        free(out);
    }
    tui_editor_set(a->ed, text);
    free(row);
}

/* /rewind (Claude Code's, Esc Esc): this conversation's messages, newest
 * first, each with how many files write and edit changed after it; then
 * what to restore; then `pic rewind`, which refuses files changed since pic
 * wrote them and does nothing until the rest is confirmed. */
static void rewind_open(app *a) {
    const char *args[] = {"rewind", a->conversation, "--list", NULL};
    char *out = NULL;
    if (a->working) {
        notice(a, YELLOW, "a reply is running: stop it (esc) before rewinding");
        return;
    }
    if (run_sync(a, args, &out) != 0 || !out) {
        free(out);
        return;
    }
    ov_open(a, OV_REWIND, "Rewind  (up/down \xc2\xb7 enter: choose what to restore \xc2\xb7 esc)",
            "Go back to before a message. Changes made by bash or outside pic are not tracked.");
    for (char *line = out, *nl; *line; line = nl ? nl + 1 : line + strlen(line)) {
        char *seq, *text, label[512];
        long long files;
        nl = strchr(line, '\n');
        if (nl) {
            *nl = '\0';
        }
        seq = jget(a, line, "$.entry");
        text = jget(a, line, "$.text");
        files = jnum(a, line, "$.files");
        if (seq && text) {
            for (char *c = text; *c; c++) {
                *c = *c == '\n' ? ' ' : *c;
            }
            if (files) {
                (void)snprintf(label, sizeof label, "%.440s  (%lld file%s changed after)", text, files, files == 1 ? "" : "s");
            } else {
                (void)snprintf(label, sizeof label, "%.440s  (no file changes after)", text);
            }
            ov_add(a, label, seq, 0);
        }
        free(seq);
        free(text);
        if (!nl) {
            break;
        }
    }
    free(out);
    if (!a->ov_n) {
        ov_free(a);
        notice(a, DIM, "No messages to rewind to");
        return;
    }
    ov_refilter(a);
}

static void rewind_choose(app *a) {
    char seq[32], id[64];
    (void)snprintf(seq, sizeof seq, "%s", a->ov_id[a->ov_order[a->ov_sel]]);
    ov_open(a, OV_REWIND_MODE, "Restore to before this message?  (up/down \xc2\xb7 enter \xc2\xb7 esc)",
            "The conversation forks before the message (the old one stays in /resume); files go back to how they were.");
    (void)snprintf(id, sizeof id, "both %s", seq);
    ov_add(a, "Restore conversation and files", id, 0);
    (void)snprintf(id, sizeof id, "conversation %s", seq);
    ov_add(a, "Restore conversation only", id, 0);
    (void)snprintf(id, sizeof id, "files %s", seq);
    ov_add(a, "Restore files only", id, 0);
    ov_add(a, "Never mind", "cancel", 0);
    ov_refilter(a);
}

/* Runs the rewind ID names ("MODE SEQ"); FORCE restores what was not refused. */
static void rewind_go(app *a, const char *id, int force) {
    char mode[16] = "", seq[32] = "", *out = NULL, *conv, *text;
    const char *args[10];
    int n = 0, rc;
    if (sscanf(id, "%15s %31s", mode, seq) != 2) {
        ov_free(a);
        return;
    }
    ov_free(a);
    args[n++] = "rewind";
    args[n++] = a->conversation;
    args[n++] = "--to";
    args[n++] = seq;
    if (strcmp(mode, "both") != 0) {
        args[n++] = strcmp(mode, "files") == 0 ? "--files" : "--conversation";
    }
    if (force) {
        args[n++] = "--force-partial";
    }
    args[n++] = "--json";
    args[n] = NULL;
    rc = run_sync(a, args, &out);
    if (rc == 3 && out) { /* refused: nothing done yet */
        char hint[1024] = "", key[48], *path, *why, again[64];
        size_t used = 0;
        for (int i = 0; i < 8; i++) {
            (void)snprintf(key, sizeof key, "$.refused[%d].path", i);
            if (!(path = jget(a, out, key))) {
                break;
            }
            (void)snprintf(key, sizeof key, "$.refused[%d].why", i);
            why = jget(a, out, key);
            used += (size_t)snprintf(hint + used, sizeof hint - used, "%s%s: %s", used ? "; " : "", path, why ? why : "");
            used = used < sizeof hint ? used : sizeof hint - 1;
            free(path);
            free(why);
        }
        {
            int more = 0;
            (void)snprintf(key, sizeof key, "$.refused[%d]", 8 + more);
            while (jget_has(a, out, key)) {
                more++;
                (void)snprintf(key, sizeof key, "$.refused[%d]", 8 + more);
            }
            if (more && used < sizeof hint) {
                (void)snprintf(hint + used, sizeof hint - used, "; and %d more", more);
            }
        }
        ov_open(a, OV_REWIND_CONFIRM, "Some files cannot be restored. Restore the rest?  (up/down \xc2\xb7 enter \xc2\xb7 esc)", hint);
        (void)snprintf(again, sizeof again, "%s %s", mode, seq);
        ov_add(a, "Restore the rest", again, 0);
        ov_add(a, "Cancel", "cancel", 0);
        ov_refilter(a);
        free(out);
        return;
    }
    if (rc != 0 || !out) {
        free(out);
        return;
    }
    {
        static const char *const kinds[] = {"restored", "deleted", "refused", "left", "failed"};
        char key[48], *v, line[256];
        for (size_t k = 0; k < sizeof kinds / sizeof kinds[0]; k++) {
            for (int i = 0; i < 64; i++) {
                (void)snprintf(key, sizeof key, k == 2 ? "$.%s[%d].path" : "$.%s[%d]", kinds[k], i);
                if (!(v = jget(a, out, key))) {
                    break;
                }
                (void)snprintf(line, sizeof line, "%s %s", k < 2 ? kinds[k] : "not restored", v);
                notice(a, k < 2 ? DIM : YELLOW, "%s", line);
                free(v);
            }
        }
    }
    conv = jget(a, out, "$.conversation");
    text = jget(a, out, "$.text");
    if (conv) { /* the conversation went back: to a fork of it, or to a new one */
        if (!a->working) {
            hook_end(a, "other");
        }
        if (*conv) {
            notice(a, DIM, "\xe2\x94\x80 rewound: now in %s \xe2\x94\x80", conv);
            resume(a, conv);
        } else {
            a->conversation[0] = a->name[0] = a->conv_title[0] = a->unfinished[0] = '\0';
            notice(a, DIM, "\xe2\x94\x80 rewound: a new conversation \xe2\x94\x80");
        }
        tui_editor_set(a->ed, text ? text : "");
    } else {
        notice(a, DIM, "\xe2\x94\x80 rewound the files \xe2\x94\x80");
    }
    free(conv);
    free(text);
    free(out);
}

/* Enter on a request: Pi asks whether to summarize the branch left behind
 * (unless branchSummary.skipPrompt), then continues from there. */
static void tree_enter(app *a) {
    char *id = strdup(a->ov_id[a->ov_order[a->ov_sel]]), *space;
    ov_free(a);
    if (!id) {
        return;
    }
    space = strchr(id, ' ');
    *space = '\0';
    (void)snprintf(a->branch_at, sizeof a->branch_at, "%s", id);
    a->branch_sess[0] = '\0';
    if (space[1]) {
        (void)snprintf(a->branch_sess, sizeof a->branch_sess, "%.*s", (int)strcspn(space + 1, ","), space + 1);
    }
    free(id);
    if (strcmp(a->branch_sess, a->conversation) == 0) {
        notice(a, DIM, "already on %s", a->branch_sess);
        return;
    }
    if (cl_branch_skip_prompt()) {
        tree_go(a, 0, NULL);
    } else {
        summary_open(a);
    }
}

static void trust_open(app *a) {
    char real[PATH_MAX], hint[PATH_MAX + 64];
    int saved = cl_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 (cl_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;
    app_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;
}

/* /remote-control (/rc): remote control in one step, as Claude Code's /remote-control: with a
 * phone paired it turns pic remote on and shows two lines, whether it is on and the phone page's
 * address for this conversation, already copied; with none it goes straight to pairing one. The
 * QR code, the phones and pairing are behind keys (and /rc qr, devices, pair); /rc ssh is the ssh
 * page instead. The page is the overlay's data. Pairing, unpairing and reset run pic remote in a
 * child, with the store's key handed down: the store is unlocked here first, as for a request. */
enum { RC_OFFER, RC_CODE, RC_ANSWERED };
enum { RC_MAIN, RC_DEVICES, RC_QR };
enum { COPY_NONE, COPY_NATIVE, COPY_TERMINAL }; /* copy_text: nowhere, the system's clipboard, or asked of the terminal (OSC 52) */
#define RC_LINK '\x03' /* a page line that is a link: never cut, wrapped by the terminal itself */
#define RC_DIM '\x04'  /* a quiet page line */
static void login_end(app *a);
static void rc_status_load(app *a);
static void rc_toggle(app *a, int on);

/* Appends to a malloc'd page; on failure it stays as it was. */
static void rc_page_add(char **s, size_t *len, const char *add) {
    size_t n = strlen(add);
    char *grown = realloc(*s, *len + n + 1);
    if (grown) {
        memcpy(grown + *len, add, n + 1);
        *s = grown;
        *len += n;
    }
}

/* The paired phones, from pic remote devices --json: rc_ndev is -1 while the store is locked. */
static void rc_devices_load(app *a) {
    const char *args[] = {"remote", "devices", "--json", NULL};
    char *out = NULL;
    a->rc_ndev = 0;
    a->rc_running = 0;
    if (pic_cred_state() == PIC_CRED_LOCKED && pic_cred_quiet(NULL, 0) != 0) {
        a->rc_ndev = -1;
        return;
    }
    if (pic_cred_state() != PIC_CRED_OPEN || run_sync(a, args, &out) != 0 || !out) {
        free(out);
        return;
    }
    a->rc_running = (int)jnum(a, out, "$.running");
    for (int i = 0; i < 8; i++) {
        char path[48], *id, *name;
        long long seen;
        (void)snprintf(path, sizeof path, "$.devices[%d].id", i);
        if (!(id = jget(a, out, path))) {
            break;
        }
        (void)snprintf(path, sizeof path, "$.devices[%d].name", i);
        name = jget(a, out, path);
        (void)snprintf(path, sizeof path, "$.devices[%d].seenMs", i);
        seen = jnum(a, out, path);
        (void)snprintf(a->rc_dev[i], sizeof a->rc_dev[i], "%s", id);
        (void)snprintf(a->rc_devname[i], sizeof a->rc_devname[i], "%s", name ? name : "");
        if (seen > 0) {
            time_t t = (time_t)(seen / 1000);
            struct tm tm;
            (void)localtime_r(&t, &tm);
            (void)strftime(a->rc_devseen[i], sizeof a->rc_devseen[i], "last seen %Y-%m-%d %H:%M", &tm);
        } else {
            (void)snprintf(a->rc_devseen[i], sizeof a->rc_devseen[i], "never seen");
        }
        a->rc_ndev = i + 1;
        free(id);
        free(name);
    }
    free(out);
}

/* Appends TEXT's QR code to the page, each line marked for overlay_lines to colour. */
static void rc_page_qr(char **page, size_t *len, const char *text) {
    int rows = 0;
    char *qr = tui_remote_qr(text, 1, &rows);
    for (char *at = qr, *nl; at && (nl = strchr(at, '\n')) != NULL; at = nl + 1) {
        char mark[2] = {TUI_REMOTE_QR, '\0'};
        *nl = '\0';
        rc_page_add(page, len, mark);
        rc_page_add(page, len, at);
        rc_page_add(page, len, "\n");
    }
    free(qr);
}

/* The phone page's address for this conversation, from pic rc --link (no passphrase). */
static void rc_link_load(app *a) {
    const char *args[] = {"rc", "--link", "--session", a->conversation, NULL};
    char *out = NULL;
    a->rc_link[0] = '\0';
    if (run_sync(a, args, &out) == 0 && out) {
        out[strcspn(out, "\r\n")] = '\0';
        (void)snprintf(a->rc_link, sizeof a->rc_link, "%s", out);
    }
    free(out);
}

/* How the link got to a clipboard, for the first line of /rc. */
static const char *rc_copy_said(int how, int ssh_command) {
    return how == COPY_NATIVE     ? (ssh_command ? "Copied the command to the clipboard" : "link copied to the clipboard")
           : how == COPY_TERMINAL ? (ssh_command ? "Sent the command to the terminal's clipboard" : "link sent to the terminal's clipboard")
                                  : (ssh_command ? "Could not copy: select the command" : "select the link to copy it");
}

/* The link, on rows of its own from the first column so the terminal's own selection takes it. */
static void rc_page_link(char **page, size_t *len, const char *link) {
    char mark[2] = {RC_LINK, '\0'};
    rc_page_add(page, len, mark);
    rc_page_add(page, len, link);
    rc_page_add(page, len, "\n");
}

static void rc_page_dim(char **page, size_t *len, const char *text) {
    char mark[2] = {RC_DIM, '\0'};
    rc_page_add(page, len, mark);
    rc_page_add(page, len, text);
    rc_page_add(page, len, "\n");
}

/* The overlay's title and page for where /rc is. With a phone paired that is two lines, whether
 * it is on and the link, and one quiet line of keys; the phones, the QR code, a pairing and the
 * ssh page are each a page of their own behind those keys. */
static void rc_render(app *a) {
    char *page = NULL, line[2200];
    size_t len = 0;
    a->ov_hint[0] = '\0';
    if (a->rc_ssh) {
        char *ssh = tui_remote_page(&a->rc_info);
        (void)snprintf(a->ov_title, sizeof a->ov_title, "Remote control over ssh  (c: copy the ssh command \xc2\xb7 esc: close)");
        if (ssh) {
            rc_page_add(&page, &len, ssh);
            free(ssh);
        }
        if (a->rc_copied >= 0) {
            (void)snprintf(a->ov_hint, sizeof a->ov_hint, "%s", rc_copy_said(a->rc_copied, 1));
        }
    } else if (a->rc_pairing) {
        (void)snprintf(a->ov_title, sizeof a->ov_title, "Pair a phone  (%s)",
                       a->rc_stage == RC_CODE ? "y: pair \xc2\xb7 n: no \xc2\xb7 esc: cancel" : "esc: cancel");
        if (a->rc_cancel_ms) {
            rc_page_add(&page, &len, "Cancelling\xe2\x80\xa6\n");
        } else if (a->rc_stage == RC_ANSWERED) {
            rc_page_add(&page, &len, "Telling the phone\xe2\x80\xa6\n");
        } else if (a->rc_stage == RC_CODE) {
            (void)snprintf(line, sizeof line, "Pair \"%s\"? It should show %s. [y/N]\n", a->rc_name, a->rc_code);
            rc_page_add(&page, &len, line);
            rc_page_add(&page, &len, "Say y only if the phone shows the same six digits.\n");
        } else if (!a->rc_url[0]) {
            rc_page_add(&page, &len, "Making the pairing offer\xe2\x80\xa6\n");
        } else {
            rc_page_add(&page, &len, "Scan this with the phone's camera, or open the link on it (good once, for ten minutes):\n");
            rc_page_qr(&page, &len, a->rc_url);
            rc_page_link(&page, &len, a->rc_url);
            rc_page_add(&page, &len, "Then tap Pair this phone, and check its six digits here.\n");
        }
    } else if (a->rc_devices == 0 && a->rc_view != RC_DEVICES) {
        (void)snprintf(a->ov_title, sizeof a->ov_title, "\xe2\x97\x8b No phone is paired");
        rc_page_dim(&page, &len, "p pair a phone \xc2\xb7 /rc ssh \xc2\xb7 esc close");
    } else if (a->rc_view == RC_QR) {
        (void)snprintf(a->ov_title, sizeof a->ov_title, "%s  (esc: %s)", a->conversation[0] ? "This conversation, for a phone's camera" : "pic, for a phone's camera",
                       a->rc_direct ? "close" : "back");
        rc_page_qr(&page, &len, a->rc_link);
        rc_page_link(&page, &len, a->rc_link);
    } else if (a->rc_view == RC_DEVICES) {
        (void)snprintf(a->ov_title, sizeof a->ov_title, "Paired phones  (%s \xc2\xb7 p: pair \xc2\xb7 esc: %s)",
                       a->rc_ndev < 0 ? "u: unlock to list them" : a->rc_ndev == 0 ? "R then y: reset" : a->rc_ndev == 1 ? "1 then y: unpair \xc2\xb7 R then y: reset"
                                                                                    : "1-8 then y: unpair \xc2\xb7 R then y: reset",
                       a->rc_direct ? "close" : "back");
        if (a->rc_ndev < 0) {
            (void)snprintf(line, sizeof line, "%d phone%s paired; their names are sealed in pic's credential store.\n", a->rc_devices,
                           a->rc_devices == 1 ? "" : "s");
            rc_page_add(&page, &len, line);
        }
        for (int i = 0; i < a->rc_ndev; i++) {
            (void)snprintf(line, sizeof line, "  %d  %s, %s\n", i + 1, a->rc_devname[i], a->rc_devseen[i]);
            rc_page_add(&page, &len, line);
        }
        if (a->rc_ndev == 0) {
            rc_page_add(&page, &len, "  none\n");
        }
        if (a->rc_agent[0]) {
            (void)snprintf(line, sizeof line, "Remote control starts when you log in (%s).", a->rc_agent);
            rc_page_dim(&page, &len, line);
        } else {
            rc_page_dim(&page, &len, "Remote control does not start when you log in; pic remote install in a shell sets that up.");
        }
        if (a->rc_confirm >= 1 && a->rc_confirm <= a->rc_ndev) {
            (void)snprintf(a->ov_hint, sizeof a->ov_hint, "Unpair %s? [y/N]", a->rc_devname[a->rc_confirm - 1]);
        } else if (a->rc_confirm == 9) {
            (void)snprintf(a->ov_hint, sizeof a->ov_hint,
                           "Reset remote control: unpair every phone and delete its keys and mailbox? [y/N]");
        }
    } else {
        const char *mark = "\xe2\x97\x8c", *state = "Remote control is on, connecting\xe2\x80\xa6";
        if (!a->rc_on) {
            mark = "\xe2\x97\x8b";
            state = "Remote control is off";
        } else if (strcmp(a->rc_state, "connected") == 0) {
            mark = "\xe2\x97\x8f";
            state = "Remote control is on";
        } else if (strcmp(a->rc_state, "reconnecting") == 0) {
            state = "Remote control is on, reconnecting\xe2\x80\xa6";
        }
        if (a->rc_link[0] && a->rc_on) {
            (void)snprintf(a->ov_title, sizeof a->ov_title, "%s %s \xc2\xb7 %s", mark, state, rc_copy_said(a->rc_copied, 0));
        } else {
            (void)snprintf(a->ov_title, sizeof a->ov_title, "%s %s", mark, state);
        }
        if (a->rc_link[0]) {
            rc_page_link(&page, &len, a->rc_link);
        }
        if (a->rc_on && strcmp(a->rc_state, "reconnecting") == 0) {
            (void)snprintf(line, sizeof line, "Attempt %d, next try in %ld s%s%s\n", a->rc_attempts, (a->rc_retry_ms + 999) / 1000,
                           a->rc_err[0] ? ": " : "", a->rc_err);
            rc_page_add(&page, &len, line);
        }
        if (a->rc_on && a->rc_stale) {
            rc_page_add(&page, &len, "! It runs an older pic than the one installed now; r restarts it.\n");
        }
    }
    if (a->rc_note[0]) {
        (void)snprintf(line, sizeof line, "%s\n", a->rc_note);
        rc_page_add(&page, &len, line);
    }
    if (!a->rc_ssh && !a->rc_pairing && a->rc_devices > 0 && a->rc_view == RC_MAIN) {
        (void)snprintf(line, sizeof line,
                       "c copy \xc2\xb7 q QR code \xc2\xb7 p pair \xc2\xb7 d devices \xc2\xb7 s turn %s \xc2\xb7 /rc ssh \xc2\xb7 esc close",
                       a->rc_on ? "off" : "on");
        rc_page_dim(&page, &len, line);
    }
    free(a->ov_data);
    a->ov_data = page;
}

static int copy_text(const char *t);

/* The link goes to the clipboard as /rc shows it, so the panel can be closed at once. */
static void rc_copy(app *a) {
    const char *t = a->rc_ssh ? a->rc_info.command : a->rc_link;
    if (*t) {
        a->rc_copied = copy_text(t);
    }
}

static void rc_key(app *a, char c);

/* /rc [ssh | pair | devices | qr | off]. */
static void remote_open(app *a, const char *arg) {
    char real[PATH_MAX];
    static const char *const words[] = {"", "ssh", "pair", "devices", "qr", "off"};
    int word = -1;
    for (int i = 0; i < (int)(sizeof words / sizeof words[0]); i++) {
        if (strcmp(arg, words[i]) == 0) {
            word = i;
        }
    }
    if (word < 0) {
        notice(a, RED, "/rc takes nothing, or pair, devices, qr, off or ssh");
        return;
    }
    if (word == 5) { /* off: no panel */
        rc_status_load(a);
        if (a->rc_on) {
            rc_toggle(a, 0);
        }
        a->rc_note[0] = '\0';
        notice(a, DIM, "Remote control is off");
        return;
    }
    a->rc_ssh = word == 1;
    a->rc_view = word == 3 ? RC_DEVICES : word == 4 ? RC_QR : RC_MAIN;
    a->rc_direct = a->rc_view != RC_MAIN;
    a->rc_auto = 0;
    a->rc_confirm = 0;
    a->rc_copied = -1;
    a->rc_note[0] = '\0';
    a->rc_link[0] = '\0';
    if (a->rc_ssh) {
        tui_remote_info(&a->rc_info, a->o->self, realpath(a->o->workspace, real) ? real : a->o->workspace, a->conversation);
    }
    ov_open(a, OV_REMOTE, "Remote control", "");
    ov_add(a, "", "", 0);
    ov_refilter(a);
    if (!a->rc_ssh) {
        rc_status_load(a);
        rc_devices_load(a);
        if (a->rc_devices > 0) {
            rc_link_load(a);
            if (a->rc_view == RC_MAIN && word == 0) {
                rc_copy(a);
            }
        }
    }
    rc_render(a);
    if (!a->ov_data) {
        ov_free(a);
        notice(a, RED, "out of memory");
        return;
    }
    if (a->rc_ssh) {
        return;
    }
    if (a->rc_devices == 0 || word == 2) { /* nothing to turn on yet: pairing is the one step */
        a->rc_auto = a->rc_devices == 0;
        rc_key(a, 'p');
    } else if (!a->rc_on && word == 0) { /* /rc turns remote control on */
        rc_key(a, 'S');
    }
}

/* p: pic remote pair --pipe in a child, its lines read by rc_pump. */
static void rc_pair_start(app *a) {
    const char *args[] = {"remote", "pair", "--pipe", NULL};
    a->rc_note[0] = a->rc_url[0] = a->rc_name[0] = a->rc_code[0] = '\0';
    a->rc_confirm = 0;
    if (spawn_in(a, &a->rc_child, args, 1) != 0) {
        (void)snprintf(a->rc_note, sizeof a->rc_note, "\xe2\x9c\x97 could not start pic remote pair");
        rc_render(a);
        return;
    }
    a->rc_pairing = 1;
    a->rc_stage = RC_OFFER;
    a->rc_cancel_ms = 0;
    rc_render(a);
}

/* Unpair the phone numbered N (1-8), or reset (9), after its y. */
static void rc_confirmed(app *a, int n) {
    const char *args[4] = {"remote", "reset", NULL, NULL};
    char *out = NULL;
    if (n >= 1 && n <= a->rc_ndev) {
        args[1] = "unpair";
        args[2] = a->rc_dev[n - 1];
    }
    if (run_sync(a, args, &out) == 0) {
        if (n == 9) {
            (void)snprintf(a->rc_note, sizeof a->rc_note, "Reset: every phone unpaired, remote control's keys deleted.");
        } else {
            (void)snprintf(a->rc_note, sizeof a->rc_note, "Unpaired %s.", a->rc_devname[n - 1]);
        }
    } else {
        (void)snprintf(a->rc_note, sizeof a->rc_note, "\xe2\x9c\x97 %s did not finish", n == 9 ? "the reset" : "unpairing");
    }
    free(out);
    a->rc_confirm = 0;
    rc_devices_load(a);
    rc_status_load(a); /* how many are left, and whether it still runs */
}

/* A key on /rc's page, out of a pairing: p, R, a phone's number, or a y for one of them. A key
 * that needs the store while it is locked asks for the passphrase first and comes back here. */
static void rc_key(app *a, char c) {
    if (a->rc_confirm) {
        int n = a->rc_confirm;
        a->rc_confirm = 0;
        if (c == 'y' || c == 'Y') {
            rc_confirmed(a, n);
        }
        rc_render(a);
        return;
    }
    if (c != 'p' && c != 'R' && c != 's' && c != 'S' && c != 'u' && c != 'r' && !(c >= '1' && c <= '8')) {
        return;
    }
    if (c == 'r' && !(a->rc_on && a->rc_stale)) {
        return;
    }
    if (c == 's' && a->rc_on) { /* off needs no key */
        rc_toggle(a, 0);
        rc_render(a);
        return;
    }
    if (pic_cred_state() != PIC_CRED_OPEN) { /* pic remote's keys are sealed under the store's */
        char err[256] = "";
        int q = pic_cred_quiet(err, sizeof err);
        if (q < 0) {
            (void)snprintf(a->rc_note, sizeof a->rc_note, "%s", err);
            rc_render(a);
            return;
        }
        if (q == 0) {
            rc_key(a, c);
            return;
        }
        login_end(a);
        (void)snprintf(a->lg_provider, sizeof a->lg_provider, "remote control");
        a->lg_request = 1;
        a->lg_after = AFTER_RC;
        a->rc_after = c;
        a->lg = pic_cred_state() == PIC_CRED_NEW ? LG_PASS_NEW : LG_PASS;
        return;
    }
    a->rc_note[0] = '\0';
    if (c == 'p') {
        rc_pair_start(a);
        return;
    }
    if (c == 'u') {
        rc_devices_load(a);
        rc_render(a);
        return;
    }
    if (c == 's' || c == 'S') {
        if (!a->rc_on) {
            rc_toggle(a, 1);
        }
        rc_render(a);
        return;
    }
    if (c == 'r') { /* a pic remote too old to restart itself is stopped and started here */
        const char *args[] = {"remote", "restart", NULL};
        char *out = NULL;
        int ok = run_sync(a, args, &out) == 0;
        free(out);
        if (!ok) {
            rc_toggle(a, 0);
            rc_toggle(a, 1);
        }
        rc_status_load(a);
        (void)snprintf(a->rc_note, sizeof a->rc_note, a->rc_on && !a->rc_stale ? "pic remote restarted." : "\xe2\x9c\x97 pic remote did not restart");
        rc_render(a);
        return;
    }
    a->rc_confirm = c == 'R' ? 9 : c - '0' <= a->rc_ndev ? c - '0' : 0;
    rc_render(a);
}

/* The store opened for a key on /rc's page: the phones are listed, then the key goes on. */
static void rc_after_unlock(app *a) {
    char c = a->rc_after;
    a->rc_after = '\0';
    if (a->ov != OV_REMOTE) {
        return;
    }
    rc_devices_load(a);
    rc_render(a);
    if (c) {
        rc_key(a, c);
    }
}

/* Esc: a pairing is asked to stop (the phone hears no); a stubborn one is killed after 3 s. */
static void rc_cancel(app *a) {
    if (!a->rc_cancel_ms) {
        (void)kill(a->rc_child.pid, SIGTERM);
        a->rc_cancel_ms = now_ms();
        rc_render(a);
    }
}

/* The pairing's lines and, once it has ended, the list again with what happened. */
static void rc_pump(app *a) {
    app_child *c = &a->rc_child;
    int done = drain(c), status = 0;
    char *nl;
    while (c->outbuf.buf && (nl = memchr(c->outbuf.buf, '\n', c->outbuf.len))) {
        size_t used = (size_t)(nl - c->outbuf.buf) + 1;
        *nl = '\0';
        if (c->outbuf.buf[0] == '{') {
            char *type = jget(a, c->outbuf.buf, "$.type");
            if (type && strcmp(type, "offer") == 0) {
                char *url = jget(a, c->outbuf.buf, "$.url");
                (void)snprintf(a->rc_url, sizeof a->rc_url, "%s", url ? url : "");
                free(url);
            } else if (type && strcmp(type, "code") == 0) {
                char *name = jget(a, c->outbuf.buf, "$.name"), *code = jget(a, c->outbuf.buf, "$.code");
                (void)snprintf(a->rc_name, sizeof a->rc_name, "%s", name ? name : "");
                (void)snprintf(a->rc_code, sizeof a->rc_code, "%s", code ? code : "");
                a->rc_stage = RC_CODE;
                free(name);
                free(code);
            } else if (type && strcmp(type, "paired") == 0) {
                (void)snprintf(a->rc_note, sizeof a->rc_note, "Paired %s.", a->rc_name);
            } else if (type && strcmp(type, "refused") == 0) {
                (void)snprintf(a->rc_note, sizeof a->rc_note, "Not paired.");
            } else if (type && strcmp(type, "expired") == 0) {
                (void)snprintf(a->rc_note, sizeof a->rc_note, "The pairing offer expired.");
            } else if (type && strcmp(type, "cancelled") == 0) {
                (void)snprintf(a->rc_note, sizeof a->rc_note, "Pairing cancelled.");
            } else if (type && strcmp(type, "error") == 0) {
                char *m = jget(a, c->outbuf.buf, "$.message");
                (void)snprintf(a->rc_note, sizeof a->rc_note, "\xe2\x9c\x97 %s", m ? m : "pairing failed");
                free(m);
            }
            free(type);
        }
        memmove(c->outbuf.buf, c->outbuf.buf + used, c->outbuf.len - used + 1);
        c->outbuf.len -= used;
    }
    if (a->rc_cancel_ms > 0 && now_ms() - a->rc_cancel_ms > 3000) {
        (void)kill(c->pid, SIGKILL);
        a->rc_cancel_ms = -1;
    }
    if (done) {
        while (waitpid(c->pid, &status, 0) < 0 && errno == EINTR) {
        }
        if (c->in >= 0) {
            close(c->in);
        }
        if (!a->rc_note[0]) {
            (void)snprintf(a->rc_note, sizeof a->rc_note, a->rc_cancel_ms ? "Pairing cancelled." : "Not paired.");
        }
        free(c->outbuf.buf);
        free(c->errbuf.buf);
        memset(c, 0, sizeof *c);
        c->in = c->out = c->err = -1;
        a->rc_pairing = 0;
        if (a->ov == OV_REMOTE) {
            int paired = strncmp(a->rc_note, "Paired ", 7) == 0, auto_cancelled = a->rc_auto && a->rc_cancel_ms;
            char said[sizeof a->rc_note];
            a->rc_cancel_ms = 0;
            a->rc_auto = 0;
            rc_devices_load(a);
            rc_status_load(a);
            if (auto_cancelled && a->rc_devices == 0) { /* Esc on /rc's own pairing: back to the conversation */
                ov_free(a);
                return;
            }
            if (paired && !a->rc_on) { /* the first phone: remote control goes on */
                (void)snprintf(said, sizeof said, "%s", a->rc_note);
                rc_toggle(a, 1);
                (void)snprintf(a->rc_note, sizeof a->rc_note, "%s", said);
            }
            if (a->rc_devices > 0) {
                int had = a->rc_link[0] != '\0';
                rc_link_load(a);
                if (!had && a->rc_view == RC_MAIN) { /* the first phone: its link, as /rc gives it */
                    rc_copy(a);
                }
            }
        }
        a->rc_cancel_ms = 0;
    }
    if (a->ov == OV_REMOTE) {
        rc_render(a);
    }
}

/* ---- /rc: pic remote, started from here detached ---------------------------------------------
 * /rc turns remote control on: pic remote in a session of its own (it outlives this interface),
 * with the store's key on an inherited pipe (cred.h, pic_cred_handoff), never in argv or the
 * environment's values; its output goes to ~/.pic/remote.log. One that dies of a signal while
 * this runs is started again, after 1 s, doubling to 30. */

static void rc_status_load(app *a) {
    const char *args[] = {"remote", "status", "--json", NULL};
    char *out = NULL, *v;
    a->rc_status_at = now_ms();
    if (run_sync(a, args, &out) != 0 || !out) {
        free(out);
        return;
    }
    a->rc_on = (int)jnum(a, out, "$.running");
    a->rc_devices = (int)jnum(a, out, "$.devices");
    a->rc_attempts = (int)jnum(a, out, "$.attempts");
    a->rc_retry_ms = (long)jnum(a, out, "$.retryInMs");
    a->rc_stale = (int)jnum(a, out, "$.stale");
    v = jget(a, out, "$.state");
    (void)snprintf(a->rc_state, sizeof a->rc_state, "%s", v ? v : "");
    free(v);
    v = jget(a, out, "$.relay");
    (void)snprintf(a->rc_relay, sizeof a->rc_relay, "%s", v ? v : "");
    free(v);
    v = jget(a, out, "$.error");
    (void)snprintf(a->rc_err, sizeof a->rc_err, "%s", v ? v : "");
    free(v);
    v = jget(a, out, "$.loginAgent");
    (void)snprintf(a->rc_agent, sizeof a->rc_agent, "%s", v ? v : "");
    free(v);
    a->rc_watch = 0;
    for (int i = 0; i < 16 && a->conversation[0]; i++) { /* phones following this conversation, on screen */
        char path[48], *name, *sess;
        size_t sn, cn = strlen(a->conversation);
        (void)snprintf(path, sizeof path, "$.phones[%d].name", i);
        if (!(name = jget(a, out, path))) {
            break;
        }
        (void)snprintf(path, sizeof path, "$.phones[%d].session", i);
        sess = jget(a, out, path);
        (void)snprintf(path, sizeof path, "$.phones[%d].visible", i);
        sn = sess ? strlen(sess) : 0;
        if (sn > cn && sess[sn - cn - 1] == '/' && strcmp(sess + sn - cn, a->conversation) == 0 && jnum(a, out, path) == 1) {
            if (!a->rc_watch++) {
                (void)snprintf(a->rc_watch_name, sizeof a->rc_watch_name, "%s", name);
            }
        }
        free(name);
        free(sess);
    }
    free(out);
}

static int rcp_start(app *a) {
    char log[PATH_MAX], num[16];
    const char *home = getenv("HOME");
    int keyfd, fd;
    pid_t pid;
    if (pic_cred_state() != PIC_CRED_OPEN || !home) {
        return -1;
    }
    (void)snprintf(log, sizeof log, "%s/.pic/remote.log", home);
    fd = open(log, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0600);
    keyfd = pic_cred_handoff();
    pid = fork();
    if (pid == 0) {
        int null = open("/dev/null", O_RDONLY);
        sigset_t none;
        sigemptyset(&none);
        (void)sigprocmask(SIG_SETMASK, &none, NULL);
        (void)setsid();
        if (keyfd >= 0) {
            (void)fcntl(keyfd, F_SETFD, 0);
            (void)snprintf(num, sizeof num, "%d", keyfd);
            (void)setenv("PIC_KEY_FD", num, 1);
        }
        if (null >= 0) {
            (void)dup2(null, STDIN_FILENO);
        }
        if (fd >= 0) {
            (void)dup2(fd, STDOUT_FILENO);
            (void)dup2(fd, STDERR_FILENO);
        }
        for (int sig = 1; sig < 32; sig++) {
            if (sig != SIGKILL && sig != SIGSTOP) {
                (void)signal(sig, SIG_DFL);
            }
        }
        execl(a->o->self, a->o->self, "remote", "--detached", (char *)NULL);
        _exit(127);
    }
    if (keyfd >= 0) {
        close(keyfd);
    }
    if (fd >= 0) {
        close(fd);
    }
    if (pid < 0) {
        return -1;
    }
    a->rcp_pid = pid;
    a->rcp_want = 1;
    a->rcp_restart_at = now_ms(); /* when it started, for the crash count */
    return 0;
}

/* Each turn of the loop: the one started here, if it ended, and starting it again. */
static void rcp_tick(app *a) {
    long now = now_ms();
    if (a->rcp_pid > 0) {
        int st = 0;
        if (waitpid(a->rcp_pid, &st, WNOHANG) == a->rcp_pid) {
            a->rcp_pid = 0;
            if (WIFSIGNALED(st) && WTERMSIG(st) != SIGTERM && WTERMSIG(st) != SIGINT && WTERMSIG(st) != SIGHUP) {
                long wait;
                if (now - a->rcp_restart_at > 60000) {
                    a->rcp_crashes = 0; /* it had run a while: this is not a crash loop */
                }
                wait = 1000L << (a->rcp_crashes < 5 ? a->rcp_crashes : 5);
                a->rcp_crashes++;
                a->rcp_restart_at = now + (wait > 30000 ? 30000 : wait);
                notice(a, YELLOW, "pic remote ended (signal %d); starting it again", WTERMSIG(st));
            } else {
                a->rcp_want = 0;
                if (WIFEXITED(st) && WEXITSTATUS(st) != 0) {
                    notice(a, YELLOW, "pic remote stopped (exit %d): ~/.pic/remote.log says why", WEXITSTATUS(st));
                }
            }
            a->rc_status_at = 0; /* /rc looks again */
        }
    }
    if (a->rcp_want && a->rcp_pid == 0 && now >= a->rcp_restart_at) {
        rc_status_load(a);
        if (a->rc_on) {
            a->rcp_want = 0; /* someone else's runs: nothing to keep here */
        } else if (rcp_start(a) != 0) {
            a->rcp_restart_at = now + 30000;
        }
    }
    if (a->ov == OV_REMOTE && !a->rc_ssh && !a->rc_pairing && !a->lg && now - a->rc_status_at > 2000) {
        rc_status_load(a);
        rc_render(a);
    } else if (a->ov != OV_REMOTE && now - a->rc_status_at > 10000) { /* the footer's "remote on" */
        a->rc_status_at = now;
        if (a->rc_on || a->rcp_want || cl_remote_phones() > 0) {
            rc_status_load(a);
        } else {
            a->rc_on = 0;
        }
    }
}

/* s on /rc: turn remote control on (start pic remote here) or off (pic remote stop). */
static void rc_toggle(app *a, int on) {
    if (!on) {
        const char *args[] = {"remote", "stop", NULL};
        char *out = NULL;
        a->rcp_want = 0;
        (void)run_sync(a, args, &out);
        free(out);
    } else if (a->rc_devices == 0) {
        (void)snprintf(a->rc_note, sizeof a->rc_note, "Pair a phone first (p).");
    } else if (rcp_start(a) != 0) {
        (void)snprintf(a->rc_note, sizeof a->rc_note, "\xe2\x9c\x97 could not start pic remote");
    } else {
        int i = 0;
        a->rcp_crashes = 0;
        do { /* its first word, so the page says something true */
            struct timespec ts = {0, 50000000L};
            (void)nanosleep(&ts, NULL);
            rc_status_load(a);
        } while (!a->rc_on && ++i < 40);
    }
    rc_status_load(a);
}

/* "remote:DEVICE" as the phone's name; the names are sealed, so this needs the store open. */
static const char *rc_origin_name(app *a, const char *origin) {
    for (int pass = 0; pass < 2; pass++) {
        for (int i = 0; i < a->rc_norigin; i++) {
            if (strcmp(a->rc_origin[i], origin) == 0) {
                return a->rc_oname[i];
            }
        }
        if (pass || pic_cred_state() != PIC_CRED_OPEN || now_ms() - a->rc_names_at < 30000) {
            break;
        }
        {
            const char *args[] = {"remote", "devices", "--json", NULL};
            char *out = NULL;
            a->rc_names_at = now_ms();
            a->rc_norigin = 0;
            if (run_sync(a, args, &out) == 0 && out) {
                for (int i = 0; i < 8; i++) {
                    char path[48], *o, *n;
                    (void)snprintf(path, sizeof path, "$.devices[%d].origin", i);
                    if (!(o = jget(a, out, path))) {
                        break;
                    }
                    (void)snprintf(path, sizeof path, "$.devices[%d].name", i);
                    n = jget(a, out, path);
                    (void)snprintf(a->rc_origin[i], sizeof a->rc_origin[i], "%s", o);
                    (void)snprintf(a->rc_oname[i], sizeof a->rc_oname[i], "%s", n ? n : "your phone");
                    a->rc_norigin = i + 1;
                    free(o);
                    free(n);
                }
            }
            free(out);
        }
    }
    return "your phone";
}

/* ---- following this conversation while idle --------------------------------------------------
 * pic attach --from end in a child while no request of this interface runs: a request started
 * elsewhere (a phone's prompt, another terminal's) shows here as it is committed, and a message
 * typed meanwhile goes to it through the inbox (pic send). It stops before a request starts
 * here, and starts again after, from the end, so nothing is shown twice. */

static void fw_stop(app *a) {
    if (!a->fw_on) {
        return;
    }
    (void)kill(a->fw.pid, SIGKILL); /* it only reads; and a child may inherit a mask that holds SIGTERM */
    while (waitpid(a->fw.pid, NULL, 0) < 0 && errno == EINTR) {
    }
    if (a->fw.in >= 0) {
        close(a->fw.in);
    }
    if (a->fw.out >= 0) {
        close(a->fw.out);
    }
    if (a->fw.err >= 0) {
        close(a->fw.err);
    }
    free(a->fw.outbuf.buf);
    free(a->fw.errbuf.buf);
    memset(&a->fw, 0, sizeof a->fw);
    a->fw.in = a->fw.out = a->fw.err = -1;
    a->fw_on = 0;
    if (a->ext_running) {
        a->ext_running = 0;
        commit_stream(a);
    }
    for (int i = 0; i < 8; i++) {
        free(a->ext_sent[i]);
        a->ext_sent[i] = NULL;
    }
}

static void fw_event(app *a, const char *ev) {
    char *type = jget(a, ev, "$.type");
    if (!type) {
        return;
    }
    if (strcmp(type, "agent_start") == 0) { /* not this interface's: its model and window stay */
        char *req = jget(a, ev, "$.request");
        if (req && strcmp(req, a->unfinished) == 0) { /* another pic took the interrupted request up */
            a->unfinished[0] = '\0';
        }
        a->ext_running = 1;
        a->finishing = 0;
        if (req && strncmp(req, "inbox:wake:", 11) == 0) { /* a loop's run: Esc stops it and pauses the loop */
            long id = strtol(req + 11, NULL, 10);
            const char *kind = "loop";
            char name[24];
            (void)snprintf(name, sizeof name, "L%ld", id);
            for (int i = 0; i < a->wk_n; i++) {
                if (strtol(a->wk[i].name + 1, NULL, 10) == id) {
                    kind = a->wk[i].kind;
                    (void)snprintf(name, sizeof name, "%s", a->wk[i].name);
                }
            }
            notice(a, DIM, "%s %s is running here: type to steer it, Esc stops it and pauses the %s.", wk_Word(kind), name, wk_word(kind));
        } else {
            notice(a, DIM, "A request from elsewhere is running here: type to steer it, Esc stops it.");
        }
        free(req);
    } else if (strcmp(type, "agent_end") == 0 && jget_is(a, ev, "$.status", "interrupted")) {
        /* the pic running it is gone: what it streamed is not in the conversation; it can be resumed */
        char *req = jget(a, ev, "$.request"), *model = jget(a, ev, "$.model");
        a->ext_running = 0;
        blocks_flush(a, 1);
        if (a->stream.len || a->stream_off > 0) {
            notice(a, YELLOW, "(the reply above was cut off)");
        }
        text_clear(&a->stream);
        text_clear(&a->thinking);
        a->stream_off = 0;
        a->stream_fence = 0;
        if (req && !a->working) {
            (void)snprintf(a->unfinished, sizeof a->unfinished, "%s", req);
            (void)snprintf(a->unfinished_model, sizeof a->unfinished_model, "%s", model ? model : "");
            notice(a, YELLOW, "the pic running that request stopped: Enter to resume it here, Esc to drop it");
        }
        for (int i = 0; i < 8; i++) {
            free(a->ext_sent[i]);
            a->ext_sent[i] = NULL;
        }
        free(req);
        free(model);
    } else {
        on_event(a, ev);
        if (strcmp(type, "agent_end") == 0) {
            a->ext_running = 0;
            for (int i = 0; i < 8; i++) {
                free(a->ext_sent[i]);
                a->ext_sent[i] = NULL;
            }
        }
    }
    free(type);
}

static void fw_tick(app *a) {
    long now = now_ms();
    if (a->fw_on && (a->working || strcmp(a->fw_conv, a->conversation) != 0)) {
        fw_stop(a);
    }
    if (!a->fw_on && !a->working && !a->quit && a->conversation[0] && now >= a->fw_retry_at) {
        const char *args[] = {"attach", "--session", a->conversation, "--from", "end", "--format", "json", NULL};
        if (spawn_in(a, &a->fw, args, 1) == 0) { /* its stdin is its lifeline: it ends when this does */
            a->fw_on = 1;
            (void)snprintf(a->fw_conv, sizeof a->fw_conv, "%s", a->conversation);
        } else {
            a->fw_retry_at = now + 5000;
        }
    }
    if (a->fw_on) {
        int done = drain(&a->fw);
        char *nl;
        while (a->fw.outbuf.buf && (nl = memchr(a->fw.outbuf.buf, '\n', a->fw.outbuf.len))) {
            size_t used = (size_t)(nl - a->fw.outbuf.buf) + 1;
            *nl = '\0';
            if (a->fw.outbuf.buf[0] == '{') {
                fw_event(a, a->fw.outbuf.buf);
            }
            memmove(a->fw.outbuf.buf, a->fw.outbuf.buf + used, a->fw.outbuf.len - used + 1);
            a->fw.outbuf.len -= used;
        }
        if (a->fw.errbuf.len) { /* attach's notes are not this interface's to show */
            a->fw.errbuf.len = 0;
        }
        if (done) {
            fw_stop(a);
            a->fw_retry_at = now + 2000;
        }
    }
}

/* A message typed here, or Esc, for the request running from elsewhere: through the inbox. */
static int ext_send(app *a, const char *type, const char *msg) {
    const char *args[] = {"send", "--session", a->conversation, type, msg, NULL};
    char *out = NULL;
    int rc = run_sync(a, args, &out);
    free(out);
    if (rc != 0) {
        notice(a, RED, "could not send it to the running request");
        return -1;
    }
    if (!msg) {
        notice(a, DIM, "Asked the running request to stop.");
        return 0;
    }
    commit_user(a, msg);
    for (int i = 0; i < 8; i++) {
        if (!a->ext_sent[i]) {
            a->ext_sent[i] = strdup(msg);
            break;
        }
    }
    return 0;
}

/* ---- loops, monitors and goals --------------------------------------------------------------
 * A wake (pic's word; people see loop, monitor and goal) is a journal row that sends this
 * conversation its prompt when its time comes. This interface reads them every 2 seconds through
 * get_wakes with fire: true, which also fires what is due in the journal and starts its request
 * there; the request shows here through the follower, as any from elsewhere does. */

static long long wk_now(const app *a) { return (long long)now_ms() + a->wk_skew; }

static const char *wk_word(const char *kind) {
    return strcmp(kind, "monitor") == 0 ? "monitor" : strcmp(kind, "goal") == 0 ? "goal" : "loop";
}

static const char *wk_Word(const char *kind) {
    return strcmp(kind, "monitor") == 0 ? "Monitor" : strcmp(kind, "goal") == 0 ? "Goal" : "Loop";
}

static void wk_open(app *a);

/* "3:12" (minutes and seconds) up to an hour, then "2h05m", then "3d", until MS from now. */
static void wk_until(long long ms, char *out, size_t cap) {
    long long sec = ms > 0 ? (ms + 999) / 1000 : 0;
    if (sec < 3600) {
        (void)snprintf(out, cap, "%lld:%02lld", sec / 60, sec % 60);
    } else if (sec < 86400) {
        (void)snprintf(out, cap, "%lldh%02lldm", sec / 3600, sec % 3600 / 60);
    } else {
        (void)snprintf(out, cap, "%lldd", sec / 86400);
    }
}

static void wk_every(long long ms, char *out, size_t cap) {
    if (ms > 0 && ms % 86400000LL == 0) {
        (void)snprintf(out, cap, "%lldd", ms / 86400000LL);
    } else if (ms > 0 && ms % 3600000LL == 0) {
        (void)snprintf(out, cap, "%lldh", ms / 3600000LL);
    } else {
        (void)snprintf(out, cap, "%lldm", ms / 60000LL);
    }
}

/* Whether WORD is an interval as /loop takes one: digits with s, m, h or d after each run ("90s",
 * "5m", "1h30m"). A word that is not stays part of the prompt. */
static int wk_is_every(const char *word, size_t n) {
    size_t i = 0;
    if (!n) {
        return 0;
    }
    while (i < n) {
        size_t d = i;
        while (i < n && word[i] >= '0' && word[i] <= '9') {
            i++;
        }
        if (i == d || i == n || !strchr("smhd", word[i])) {
            return 0;
        }
        i++;
    }
    return 1;
}

/* This conversation's wakes from DATA (get_wakes' answer, or an action's). With TELL, what changed
 * since the last read is said once: a run stopped with Esc paused its loop; one needs a person. */
static void wk_load(app *a, const char *data, int tell) {
    struct app_wake old[8];
    int nold = a->wk_n;
    long long now = jnum(a, data, "$.nowMs");
    memcpy(old, a->wk, sizeof old);
    if (now) {
        a->wk_skew = now - (long long)now_ms();
    }
    a->wk_n = 0;
    for (int i = 0; i < 8; i++) {
        char path[48], *v;
        struct app_wake *w = &a->wk[a->wk_n];
        (void)snprintf(path, sizeof path, "$.wakes[%d].name", i);
        if (!(v = jget(a, data, path))) {
            break;
        }
        memset(w, 0, sizeof *w);
        (void)snprintf(w->name, sizeof w->name, "%s", v);
        free(v);
#define WK_TEXT(field, member)                                                                                         \
    (void)snprintf(path, sizeof path, "$.wakes[%d]." field, i);                                                        \
    if ((v = jget(a, data, path))) {                                                                                   \
        (void)snprintf(w->member, sizeof w->member, "%s", v);                                                         \
        free(v);                                                                                                       \
    }
        WK_TEXT("kind", kind)
        WK_TEXT("state", state)
        WK_TEXT("why", why)
        WK_TEXT("prompt", prompt)
        if (!w->prompt[0]) { /* a monitor: its command */
            WK_TEXT("command", prompt)
        }
#undef WK_TEXT
        (void)snprintf(path, sizeof path, "$.wakes[%d].everyMs", i);
        w->every = jnum(a, data, path);
        (void)snprintf(path, sizeof path, "$.wakes[%d].dueMs", i);
        w->due = jnum(a, data, path);
        (void)snprintf(path, sizeof path, "$.wakes[%d].fires", i);
        w->fires = jnum(a, data, path);
        (void)snprintf(path, sizeof path, "$.wakes[%d].rounds", i);
        w->rounds = jnum(a, data, path);
        (void)snprintf(path, sizeof path, "$.wakes[%d].maxRounds", i);
        w->max_rounds = jnum(a, data, path);
        (void)snprintf(path, sizeof path, "$.wakes[%d].late", i);
        w->late = jnum(a, data, path) != 0;
        (void)snprintf(path, sizeof path, "$.wakes[%d].waiting", i);
        w->waiting = jnum(a, data, path) != 0;
        (void)snprintf(path, sizeof path, "$.wakes[%d].asking", i);
        w->asking = jnum(a, data, path) != 0;
        (void)snprintf(path, sizeof path, "$.wakes[%d].cost", i);
        if ((v = jget(a, data, path))) {
            w->cost = strtod(v, NULL);
            free(v);
        }
        a->wk_n++;
    }
    for (int i = 0; tell && a->wk_seen && i < a->wk_n; i++) {
        const struct app_wake *w = &a->wk[i];
        const char *was = "";
        for (int j = 0; j < nold; j++) {
            if (strcmp(old[j].name, w->name) == 0) {
                was = old[j].state;
            }
        }
        if (strcmp(was, "active") == 0 && strcmp(w->state, "paused") == 0 && strstr(w->why, "during its run")) {
            notice(a, YELLOW, "\xe2\x96\xa0 Stopped. %s %s is paused.  /loop resume %s \xc2\xb7 /loop stop %s", wk_Word(w->kind), w->name,
                   w->name, w->name);
        } else if (w->asking) {
            /* the model asked for it: the person says yes or no, once, in a one-line prompt */
            int seen = 0;
            for (int k = 0; k < 8; k++) {
                seen |= strcmp(a->wk_asked[k], w->name) == 0;
            }
            if (!seen && !a->ov && !a->sp.on && !a->au.on && !a->mp_open) {
                char title[300], every[16];
                for (int k = 0; k < 8; k++) {
                    if (!a->wk_asked[k][0] || k == 7) {
                        (void)snprintf(a->wk_asked[k], sizeof a->wk_asked[k], "%s", w->name);
                        break;
                    }
                }
                wk_every(w->every, every, sizeof every);
                if (strcmp(w->kind, "goal") == 0) {
                    (void)snprintf(title, sizeof title, "The model wants to start goal %s: '%.120s'.", w->name, w->prompt);
                } else {
                    (void)snprintf(title, sizeof title, "The model wants to start loop %s: every %s '%.120s'.", w->name, every, w->prompt);
                }
                ov_open(a, OV_APPROVE, title, "y start \xc2\xb7 n no \xc2\xb7 esc later (/loop approve or decline it)");
                ov_add(a, "Yes, start it", "yes", 0);
                ov_add(a, "No", "no", 0);
                ov_refilter(a);
                a->ov_data = strdup(w->name);
            }
        } else if (strcmp(w->state, "needs") == 0 && strcmp(was, "needs") != 0) {
            notice(a, YELLOW, "\xe2\x96\xa0 %s %s needs you: %s.  /loop resume %s \xc2\xb7 /loop stop %s", wk_Word(w->kind), w->name,
                   w->why, w->name, w->name);
        }
    }
    a->wk_seen = 1;
}

/* get_wakes for this conversation; FIRE fires what is due in the journal first. */
static void wk_refresh(app *a, int fire, int tell) {
    char *m = cl_member("session", a->conversation), members[200], *data;
    (void)snprintf(members, sizeof members, "%s%s", m ? m : "\"session\":\"\"", fire ? ",\"fire\":true" : "");
    free(m);
    a->wk_at = now_ms();
    if (strcmp(a->wk_conv, a->conversation) != 0) { /* another conversation: its list is not news */
        (void)snprintf(a->wk_conv, sizeof a->wk_conv, "%s", a->conversation);
        a->wk_n = 0;
        a->wk_seen = 0;
    }
    if ((data = cl_ask("get_wakes", members, NULL, 0))) {
        wk_load(a, data, tell);
        free(data);
    }
}

/* ---- asks: a question the conversation waits on a person for (get_asks, answer_ask) ---------- */

/* The person's answer to ask ID: VALUE is JSON. */
static void ask_answer(app *a, const char *id, const char *value) {
    char err[PIC_ERR_CAP] = "", *members, *data, *state;
    size_t n = strlen(id) + strlen(value) + 48;
    if (!(members = malloc(n))) {
        return;
    }
    (void)snprintf(members, n, "\"ask\":\"%s\",\"value\":%s,\"by\":\"terminal\"", id, value);
    data = cl_ask("answer_ask", members, err, sizeof err);
    free(members);
    if (!data) {
        notice(a, RED, "question %s: %s", id, err);
        return;
    }
    state = jget(a, data, "$.result");
    if (state && strcmp(state, "expired") == 0) {
        notice(a, YELLOW, "question %s was not answered in time", id);
    } else if (state && strcmp(state, "already_answered") == 0) {
        char *by = jget(a, data, "$.standing.answeredBy");
        notice(a, YELLOW, "question %s was answered already%s%s", id, by ? " by " : "", by ? by : "");
        free(by);
    } else {
        notice(a, DIM, "answered");
    }
    free(state);
    free(data);
    a->ask_at = 0;
}

/* The asks of this conversation, every 2 s: one not put to the person here yet opens OV_ASK when
 * nothing else is open. A loop's or goal's OK has its own prompt (OV_APPROVE). */
static void ask_tick(app *a) {
    char *m, *data, path[64];
    if (now_ms() - a->ask_at < 2000 || !a->conversation[0] || a->ov || a->sp.on || a->au.on || a->mp_open) {
        return;
    }
    a->ask_at = now_ms();
    m = cl_member("session", a->conversation);
    data = m ? cl_ask("get_asks", m, NULL, 0) : NULL;
    free(m);
    if (!data) {
        return;
    }
    for (int i = 0; i < 100; i++) {
        char *id, *kind, *title, *wake, *body;
        int seen = 0;
        (void)snprintf(path, sizeof path, "$.asks[%d].id", i);
        if (!(id = jget(a, data, path))) {
            break;
        }
        (void)snprintf(path, sizeof path, "$.asks[%d].wake", i);
        wake = jget(a, data, path);
        for (int k = 0; k < 16; k++) {
            seen |= strcmp(a->ask_shown[k], id) == 0;
        }
        if (wake || seen) {
            free(wake);
            free(id);
            continue;
        }
        memmove(a->ask_shown + 1, a->ask_shown, 15 * sizeof a->ask_shown[0]);
        (void)snprintf(a->ask_shown[0], sizeof a->ask_shown[0], "%s", id);
        (void)snprintf(path, sizeof path, "$.asks[%d].kind", i);
        kind = jget(a, data, path);
        (void)snprintf(path, sizeof path, "$.asks[%d].title", i);
        title = jget(a, data, path);
        (void)snprintf(path, sizeof path, "$.asks[%d].body", i);
        body = jget(a, data, path);
        (void)snprintf(a->ask_kind, sizeof a->ask_kind, "%s", kind ? kind : "");
        {
            char head[300];
            (void)snprintf(head, sizeof head, "%.150s%s%.140s", title ? title : "", body ? ": " : "", body ? body : "");
            ov_open(a, OV_ASK, head,
                    strcmp(a->ask_kind, "confirm") == 0  ? "y yes \xc2\xb7 n no \xc2\xb7 esc later (pic answer, or the phone)"
                    : strcmp(a->ask_kind, "select") == 0 ? "type to filter \xc2\xb7 enter choose \xc2\xb7 esc later (pic answer, or the phone)"
                                                         : "type the answer \xc2\xb7 enter send \xc2\xb7 esc later (pic answer, or the phone)");
        }
        if (strcmp(a->ask_kind, "confirm") == 0) {
            ov_add(a, "Yes", "true", 0);
            ov_add(a, "No", "false", 0);
        } else if (strcmp(a->ask_kind, "select") == 0) {
            for (int o = 0; o < 32; o++) {
                char *opt, *quoted;
                (void)snprintf(path, sizeof path, "$.asks[%d].options[%d].label", i, o);
                if (!(opt = jget(a, data, path))) {
                    break;
                }
                quoted = cl_member("v", opt); /* "v":"OPTION": the option as JSON after the colon */
                ov_add(a, opt, quoted ? quoted + 4 : opt, 0);
                free(quoted);
                free(opt);
            }
        }
        ov_refilter(a);
        a->ov_data = strdup(id);
        free(kind);
        free(title);
        free(body);
        free(id);
        break;
    }
    free(data);
}

static void wk_tick(app *a) {
    /* every 2 s while this conversation has loops (the footer counts down); else every 15 s, which is
     * how soon another conversation's due loop fires here when nothing else is open */
    if (now_ms() - a->wk_at >= (a->wk_n ? 2000 : 15000) || strcmp(a->wk_conv, a->conversation) != 0) {
        wk_refresh(a, 1, 1);
        if (a->ov == OV_WAKES) {
            int sel = a->ov_sel;
            wk_open(a);
            a->ov_sel = sel < (int)a->ov_m ? sel : 0;
        }
    }
}

/* The footer's words for the wakes: the next active one and when, how many, what they spent. */
static void wk_mark(const app *a, char *out, size_t cap) {
    const struct app_wake *next = NULL;
    double cost = 0;
    int active = 0;
    char when[32];
    out[0] = '\0';
    for (int i = 0; i < a->wk_n; i++) {
        cost += a->wk[i].cost;
        if (strcmp(a->wk[i].state, "active") == 0) {
            active++;
            /* the loop due soonest; a monitor, which has no time, only when there is no loop */
            if (!next || (strcmp(next->kind, "loop") != 0 && strcmp(a->wk[i].kind, "loop") == 0) ||
                (strcmp(next->kind, "loop") == 0 && strcmp(a->wk[i].kind, "loop") == 0 && a->wk[i].due < next->due)) {
                next = &a->wk[i];
            }
        }
    }
    if (!a->wk_n) {
        return;
    }
    if (!next && a->wk_n == 1) {
        (void)snprintf(out, cap, "%s %s %s", wk_word(a->wk[0].kind), a->wk[0].name, a->wk[0].asking ? "waits for your OK" : a->wk[0].state);
    } else if (!next) {
        (void)snprintf(out, cap, "%d loops paused", a->wk_n);
    } else {
        if (strcmp(next->kind, "monitor") == 0) {
            (void)snprintf(when, sizeof when, next->waiting ? "running" : "watching");
        } else if (strcmp(next->kind, "goal") == 0) {
            (void)snprintf(when, sizeof when, "round %lld of %lld", next->rounds, next->max_rounds);
        } else if (next->late) {
            (void)snprintf(when, sizeof when, "not firing: open pic or turn on remote control");
        } else if (next->waiting || next->due <= wk_now(a)) {
            (void)snprintf(when, sizeof when, "running");
        } else {
            char t[16];
            wk_until(next->due - wk_now(a), t, sizeof t);
            (void)snprintf(when, sizeof when, "in %s", t);
        }
        if (active == 1) {
            (void)snprintf(out, cap, "%s %s %s", wk_word(next->kind), next->name, when);
        } else {
            (void)snprintf(out, cap, "%d running on their own \xc2\xb7 %s %s", active, next->name, when);
        }
    }
    if (cost >= 0.005) {
        size_t n = strlen(out);
        (void)snprintf(out + n, cap - n, " \xc2\xb7 $%.2f", cost);
    }
}

/* The list: /loop, /stop. p pauses, r resumes, s stops the chosen one; a pauses them all. */
static void wk_open(app *a) {
    double cost = 0;
    char title[160];
    for (int i = 0; i < a->wk_n; i++) {
        cost += a->wk[i].cost;
    }
    (void)snprintf(title, sizeof title, "Running on their own");
    if (cost >= 0.005) {
        (void)snprintf(title, sizeof title, "Running on their own   $%.2f spent", cost);
    }
    ov_open(a, OV_WAKES, title, "p pause \xc2\xb7 r resume \xc2\xb7 s stop \xc2\xb7 a pause all \xc2\xb7 y/n answer the model \xc2\xb7 esc close");
    for (int i = 0; i < a->wk_n; i++) {
        const struct app_wake *w = &a->wk[i];
        char row[320], every[16], when[64];
        wk_every(w->every, every, sizeof every);
        if (strcmp(w->kind, "monitor") == 0) {
            (void)snprintf(every, sizeof every, "line");
        } else if (strcmp(w->kind, "goal") == 0) {
            (void)snprintf(every, sizeof every, "round");
        }
        if (strcmp(w->state, "active") != 0) {
            (void)snprintf(when, sizeof when, "%s%s%s", w->state, w->why[0] ? ": " : "", w->why);
        } else if (strcmp(w->kind, "monitor") == 0) {
            (void)snprintf(when, sizeof when, w->waiting ? "running" : "watching");
        } else if (strcmp(w->kind, "goal") == 0) {
            (void)snprintf(when, sizeof when, "round %lld of %lld", w->rounds, w->max_rounds);
        } else if (w->late) {
            (void)snprintf(when, sizeof when, "not firing");
        } else if (w->waiting || w->due <= wk_now(a)) {
            (void)snprintf(when, sizeof when, "running");
        } else {
            char t[16];
            wk_until(w->due - wk_now(a), t, sizeof t);
            (void)snprintf(when, sizeof when, "next %s", t);
        }
        (void)snprintf(row, sizeof row, "%-4s %-7s every %-4s %-22s %3lld runs  $%.2f  %s", w->name, wk_word(w->kind), every, when,
                       w->fires, w->cost, w->prompt);
        ov_add(a, row, w->name, 0);
    }
    ov_refilter(a);
}

/* The person's answer to a loop or goal the model asked for. */
static void wk_decide(app *a, const char *name, int yes) {
    char err[PIC_ERR_CAP] = "", *m = cl_member("id", name), *data = cl_ask(yes ? "approve_wake" : "decline_wake", m ? m : "", err, sizeof err);
    free(m);
    if (!data) {
        notice(a, RED, "%s: %s", name, err);
        return;
    }
    wk_load(a, data, 0);
    free(data);
    a->wk_at = 0; /* approved: its first run, at the next tick */
    notice(a, DIM, yes ? "%s approved: it starts now." : "%s declined: it will not run.", name);
}

/* p, r, s on the list's chosen row; a for all of them. */
static void wk_key(app *a, char c) {
    const char *type = c == 'p' ? "pause_wake" : c == 'r' ? "resume_wake" : c == 's' ? "stop_wake" : c == 'a' ? "pause_wakes"
                       : c == 'y' ? "approve_wake" : c == 'n' ? "decline_wake" : NULL;
    char err[PIC_ERR_CAP] = "", *data, *m;
    int sel = a->ov_sel;
    if (!type || (c != 'a' && !a->ov_m)) {
        return;
    }
    m = c == 'a' ? cl_member("session", a->conversation) : cl_member("id", a->ov_id[a->ov_order[a->ov_sel]]);
    data = cl_ask(type, m ? m : "", err, sizeof err);
    free(m);
    if (!data) {
        notice(a, RED, "%s", err);
        return;
    }
    wk_load(a, data, 0);
    free(data);
    if (!a->wk_n) {
        ov_free(a);
        notice(a, DIM, "no loops in this conversation now");
        return;
    }
    wk_open(a);
    a->ov_sel = sel < (int)a->ov_m ? sel : 0;
}

/* /loop [EVERY] PROMPT, /loop pause|resume|stop ID, and /loop alone (the list). */
static void wk_command(app *a, const char *arg) {
    const char *sp = strchr(arg, ' ');
    size_t first = sp ? (size_t)(sp - arg) : strlen(arg);
    char err[PIC_ERR_CAP] = "", *data;
    if (!*arg) {
        wk_refresh(a, 0, 0);
        if (!a->wk_n) {
            notice(a, DIM, "no loops in this conversation: /loop 5m PROMPT starts one");
        } else {
            wk_open(a);
        }
        return;
    }
    if (sp && !strchr(sp + 1, ' ') && sp[1] &&
        ((first == 7 && (strncmp(arg, "approve", 7) == 0 || strncmp(arg, "decline", 7) == 0)))) {
        char name[32];
        (void)snprintf(name, sizeof name, "%s", sp + 1);
        wk_decide(a, name, arg[0] == 'a');
        return;
    }
    if (sp && !strchr(sp + 1, ' ') && sp[1] &&
        ((first == 5 && strncmp(arg, "pause", 5) == 0) || (first == 6 && strncmp(arg, "resume", 6) == 0) ||
         (first == 4 && strncmp(arg, "stop", 4) == 0))) {
        const char *type = arg[0] == 'p' ? "pause_wake" : arg[0] == 'r' ? "resume_wake" : "stop_wake";
        char *m = cl_member("id", sp + 1);
        data = cl_ask(type, m ? m : "", err, sizeof err);
        free(m);
        if (!data) {
            notice(a, RED, "%s: %s", sp + 1, err);
            return;
        }
        wk_load(a, data, 0);
        free(data);
        notice(a, DIM, "%s %s", sp + 1, arg[0] == 'p' ? "is paused" : arg[0] == 'r' ? "runs again" : "has ended");
        return;
    }
    {
        int every = sp && sp[1] && wk_is_every(arg, first);
        char ev[24] = "", *m1, *m2, *m3 = NULL, members[16384];
        if (every) {
            (void)snprintf(ev, sizeof ev, "%.*s", (int)first, arg);
        }
        m1 = cl_member("prompt", every ? sp + 1 : arg);
        m2 = cl_member("every", every ? ev : NULL);
        if (a->conversation[0]) {
            m3 = cl_member("session", a->conversation);
        }
        (void)snprintf(members, sizeof members, "%s,%s%s%s", m1 ? m1 : "", m2 ? m2 : "", m3 ? "," : "", m3 ? m3 : "");
        free(m1);
        free(m2);
        free(m3);
        if (!(data = cl_ask("create_wake", members, err, sizeof err))) {
            notice(a, RED, "%s", err);
            return;
        }
    }
    {
        char *sid = jget(a, data, "$.session"), *name = jget(a, data, "$.wake.name"), every[16], tokens[48] = "";
        wk_every(jnum(a, data, "$.wake.everyMs"), every, sizeof every);
        if (sid && !a->conversation[0]) { /* a loop in a new conversation: this is it now */
            (void)snprintf(a->conversation, sizeof a->conversation, "%s", sid);
        }
        if (a->context > 0) {
            (void)snprintf(tokens, sizeof tokens, " \xc2\xb7 about %lldk tokens a run", (a->context + 999) / 1000);
        }
        notice(a, DIM, "\xe2\x97\x8f loop %s every %s \xc2\xb7 first run now%s \xc2\xb7 ends in 7 days", name ? name : "?", every, tokens);
        notice(a, DIM, "  fires while pic is open here or pic remote runs \xc2\xb7 Esc during its run pauses it \xc2\xb7 /loop lists it");
        wk_load(a, data, 0);
        a->wk_at = 0; /* the first run: at the next tick */
        free(sid);
        free(name);
        free(data);
    }
}

/* /monitor [--done] [--restart] COMMAND: each new line of COMMAND's output wakes this conversation
 * (--done: once, when it exits). */
static void wk_monitor(app *a, const char *arg) {
    int done = 0, restart = 0;
    char err[PIC_ERR_CAP] = "", *data, *m1, *m2 = NULL, members[16384];
    for (;;) {
        if (strncmp(arg, "--done ", 7) == 0) {
            done = 1;
            arg += 7;
        } else if (strncmp(arg, "--restart ", 10) == 0) {
            restart = 1;
            arg += 10;
        } else {
            break;
        }
        while (*arg == ' ') {
            arg++;
        }
    }
    if (!*arg) {
        notice(a, RED, "/monitor needs a command: /monitor tail -f log/app.log | grep --line-buffered ERROR");
        return;
    }
    m1 = cl_member("command", arg);
    if (a->conversation[0]) {
        m2 = cl_member("session", a->conversation);
    }
    (void)snprintf(members, sizeof members, "\"kind\":\"monitor\",%s%s%s%s%s", m1 ? m1 : "", m2 ? "," : "", m2 ? m2 : "",
                   done ? ",\"done\":true" : "", restart ? ",\"restart\":true" : "");
    free(m1);
    free(m2);
    if (!(data = cl_ask("create_wake", members, err, sizeof err))) {
        notice(a, RED, "%s", err);
        return;
    }
    {
        char *sid = jget(a, data, "$.session"), *name = jget(a, data, "$.wake.name");
        if (sid && !a->conversation[0]) {
            (void)snprintf(a->conversation, sizeof a->conversation, "%s", sid);
        }
        notice(a, DIM, "\xe2\x97\x8f monitor %s \xc2\xb7 %s \xc2\xb7 ends in 7 days or when the command does", name ? name : "?",
               done ? "wakes this conversation once, when the command exits" : "each new line wakes this conversation");
        notice(a, DIM, "  runs while pic is open here or pic remote runs \xc2\xb7 Esc during its run pauses it \xc2\xb7 /loop lists it");
        wk_load(a, data, 0);
        a->wk_at = 0;
        free(sid);
        free(name);
        free(data);
    }
}

/* /goal CONDITION [--check CMD]: rounds until it is true (the check exits 0, or the model says so);
 * /goal pause, resume, clear on the conversation's goal; /goal alone, the list. */
static void wk_goal(app *a, const char *arg) {
    const char *goal = NULL, *chk;
    char err[PIC_ERR_CAP] = "", *data, cond[8192], check[4096] = "";
    for (int i = 0; i < a->wk_n; i++) {
        if (strcmp(a->wk[i].kind, "goal") == 0) {
            goal = a->wk[i].name;
        }
    }
    if (!*arg) {
        wk_command(a, "");
        return;
    }
    if (strcmp(arg, "pause") == 0 || strcmp(arg, "resume") == 0 || strcmp(arg, "clear") == 0 || strcmp(arg, "approve") == 0 ||
        strcmp(arg, "decline") == 0) {
        char line[64];
        if (!goal) {
            notice(a, RED, "this conversation has no goal: /goal CONDITION starts one");
            return;
        }
        (void)snprintf(line, sizeof line, "%s %s", arg[0] == 'c' ? "stop" : arg, goal);
        wk_command(a, line);
        return;
    }
    (void)snprintf(cond, sizeof cond, "%s", arg);
    if ((chk = strstr(arg, " --check ")) != NULL) {
        size_t n = (size_t)(chk - arg);
        const char *c = chk + 9;
        size_t cl;
        cond[n < sizeof cond ? n : sizeof cond - 1] = '\0';
        while (*c == ' ') {
            c++;
        }
        cl = strlen(c);
        if (cl >= 2 && (c[0] == '"' || c[0] == '\'') && c[cl - 1] == c[0]) { /* a quoted command */
            (void)snprintf(check, sizeof check, "%.*s", (int)(cl - 2), c + 1);
        } else {
            (void)snprintf(check, sizeof check, "%s", c);
        }
    }
    {
        char *m1 = cl_member("prompt", cond), *m2 = check[0] ? cl_member("check", check) : NULL, *m3 = NULL, members[16384];
        if (a->conversation[0]) {
            m3 = cl_member("session", a->conversation);
        }
        (void)snprintf(members, sizeof members, "\"kind\":\"goal\",%s%s%s%s%s", m1 ? m1 : "", m2 ? "," : "", m2 ? m2 : "", m3 ? "," : "",
                       m3 ? m3 : "");
        free(m1);
        free(m2);
        free(m3);
        if (!(data = cl_ask("create_wake", members, err, sizeof err))) {
            notice(a, RED, "%s", err);
            return;
        }
    }
    {
        char *sid = jget(a, data, "$.session"), *name = jget(a, data, "$.wake.name");
        long long rounds = jnum(a, data, "$.wake.maxRounds");
        if (sid && !a->conversation[0]) {
            (void)snprintf(a->conversation, sizeof a->conversation, "%s", sid);
        }
        if (check[0]) {
            notice(a, DIM, "\xe2\x97\x8f goal %s \xc2\xb7 checked with %s after each round \xc2\xb7 stops at %lld rounds or 3 with no progress",
                   name ? name : "?", check, rounds);
        } else {
            notice(a, DIM, "\xe2\x97\x8f goal %s \xc2\xb7 ends when the model says it is met (not checked) \xc2\xb7 stops at %lld rounds or 3 with no progress",
                   name ? name : "?", rounds);
        }
        notice(a, DIM, "  round 1 now \xc2\xb7 Esc during a round pauses it \xc2\xb7 /goal pause, resume, clear");
        wk_load(a, data, 0);
        a->wk_at = 0;
        free(sid);
        free(name);
        free(data);
    }
}

/* /stop: every loop, monitor and goal of this conversation paused, and the list. */
static void wk_stop_all(app *a) {
    char err[PIC_ERR_CAP] = "", *m = cl_member("session", a->conversation), *data = cl_ask("pause_wakes", m ? m : "", err, sizeof err);
    long long n;
    free(m);
    if (!data) {
        notice(a, RED, "%s", err);
        return;
    }
    n = jnum(a, data, "$.paused");
    wk_load(a, data, 0);
    free(data);
    if (!a->wk_n) {
        notice(a, DIM, "nothing runs on its own here: no loops, monitors or goals");
        return;
    }
    notice(a, DIM, "\xe2\x96\xa0 Paused %lld. r on a row resumes it.", n);
    wk_open(a);
}

/* A key while pairing: y or n once the code is up; Esc cancels. 1 when it was taken. */
static void rc_pair_key(app *a, char c) {
    if (a->rc_stage == RC_CODE && (c == 'y' || c == 'Y' || c == 'n' || c == 'N')) {
        const char *say = c == 'y' || c == 'Y' ? "y\n" : "n\n";
        if (a->rc_child.in >= 0 && write(a->rc_child.in, say, 2) != 2) {
            (void)kill(a->rc_child.pid, SIGTERM);
        }
        a->rc_stage = RC_ANSWERED;
        rc_render(a);
    }
}

/* /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;
    char id[200];
    if (a->ov == OV_ASK && (row >= 0 || strcmp(a->ask_kind, "input") == 0)) {
        char ask[24], *value = NULL;
        (void)snprintf(ask, sizeof ask, "%s", a->ov_data ? a->ov_data : "0");
        if (strcmp(a->ask_kind, "input") == 0) {
            char *m = cl_member("v", a->ov_filter);
            value = m ? strdup(m + 4) : NULL;
            free(m);
        } else {
            value = strdup(a->ov_id[row]);
        }
        ov_free(a);
        if (value) {
            ask_answer(a, ask, value);
        }
        free(value);
        return;
    }
    if (row < 0) {
        return;
    }
    if (a->ov == OV_FORK) {
        fork_go(a);
        return;
    }
    if (a->ov == OV_WAKES) {
        ov_free(a);
        return;
    }
    if (a->ov == OV_APPROVE) {
        char name[16];
        (void)snprintf(name, sizeof name, "%s", a->ov_data ? a->ov_data : "");
        ov_free(a);
        wk_decide(a, name, row == 0); /* "Yes, start it" is the first row */
        return;
    }
    if (a->ov == OV_REWIND) {
        rewind_choose(a);
        return;
    }
    if ((a->ov == OV_REWIND_MODE || a->ov == OV_REWIND_CONFIRM) && strcmp(a->ov_id[row], "cancel") != 0) {
        (void)snprintf(id, sizeof id, "%s", a->ov_id[row]);
        rewind_go(a, id, a->ov == OV_REWIND_CONFIRM);
        return;
    }
    if (a->ov == OV_REWIND_MODE || a->ov == OV_REWIND_CONFIRM) {
        ov_free(a);
        return;
    }
    (void)snprintf(id, sizeof id, "%s", a->ov_id[row]);
    switch (a->ov) {
    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_THEME:
        a->theme_cli[0] = '\0';
        (void)cl_setting_set("theme", id);
        theme_use(a, id);
        ov_free(a);
        notice(a, DIM, "theme: %s", id);
        break;
    case OV_TREE:
        tree_enter(a);
        break;
    case OV_SUMMARY:
        ov_free(a);
        if (strcmp(id, "custom") == 0) {
            a->branch_custom = 1;
            notice(a, DIM, "Custom summarization instructions: type them and press enter (esc goes back)");
        } else {
            tree_go(a, strcmp(id, "summarize") == 0, NULL);
        }
        break;
    case OV_TRUST:
        ov_free(a);
        trust_save(a, strcmp(id, "yes") == 0);
        break;
    case OV_LOGIN: {
        char provider[64];
        (void)snprintf(provider, sizeof provider, "%s", a->ov_data ? a->ov_data : "");
        ov_free(a);
        login_begin(a, provider, strcmp(id, "oauth") == 0);
        break;
    }
    case OV_LOGIN_PROVIDER:
        ov_free(a);
        if (pic_cred_oauth_label(id)) {
            login_open(a, id, "Signing in stores the subscription's tokens, sealed, in ~/.pic/pic.sqlite.");
        } else {
            login_begin(a, id, 0);
        }
        break;
    case OV_REMOTE:
        if (a->rc_pairing) {
            rc_cancel(a);
        } else {
            ov_free(a);
        }
        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;
    if (a->ov == OV_REMOTE) { /* its first line says whether it is on and copied: it wraps rather than lose its end */
        tui_lines w = {NULL, 0, 0};
        (void)tui_wrap(a->ov_title, strlen(a->ov_title), a->cols > 2 ? (size_t)a->cols : 2, &w);
        for (size_t i = 0; i < w.n; i++) {
            add_fit(tail, BOLD, w.lines[i], a->cols);
        }
        tui_lines_clear(&w);
    } else {
        add_fit(tail, BOLD, a->ov_title, a->cols);
    }
    if (a->ov == OV_REMOTE) { /* a page, not a list: the QR code white on black on any theme */
        /* Its rows, wrapped as they will be: a QR code that does not fit with
         * the rest (and the footer) is left out, never cut. */
        int need = 4, qr = 0, noted = 0;
        for (const char *at = a->ov_data ? a->ov_data : ""; *at;) {
            const char *nl = strchr(at, '\n');
            size_t n = nl ? (size_t)(nl - at) : strlen(at);
            int w = (int)tui_width(at, n);
            need += *at == TUI_REMOTE_QR ? 1 : a->cols > 0 && w > a->cols ? (w + a->cols - 1) / a->cols : 1;
            qr |= *at == TUI_REMOTE_QR;
            at += n + (nl != NULL);
        }
        qr = qr && need <= a->rows;
        for (char *at = a->ov_data ? a->ov_data : ""; *at;) {
            char *nl = strchr(at, '\n');
            size_t n = nl ? (size_t)(nl - at) : strlen(at);
            char *one = strndup(at, n);
            if (one) {
                if (one[0] == TUI_REMOTE_QR && qr) {
                    add_fit(tail, "\x1b[38;5;231;48;5;16m", one + 1, a->cols);
                } else if (one[0] == TUI_REMOTE_QR) {
                    if (!noted) {
                        add_fit(tail, DIM, "Make the window taller to show the QR code", a->cols);
                        noted = 1;
                    }
                } else if (one[0] == RC_LINK) { /* whole rows of it, wrapped by the terminal: its selection takes it as one line */
                    size_t cols = a->cols > 2 ? (size_t)a->cols : 2, left = n - 1;
                    for (const char *l = one + 1; left > 0;) {
                        size_t take = tui_fit(l, left, cols);
                        app_text t = {NULL, 0, 0};
                        take = take ? take : left;
                        (void)text_add(&t, l, take);
                        (void)text_add(&t, RESET, strlen(RESET));
                        if (take < left) {
                            (void)text_add(&t, TUI_ROW_WRAPS, strlen(TUI_ROW_WRAPS));
                        }
                        (void)tui_lines_add(tail, t.buf, t.len);
                        free(t.buf);
                        l += take;
                        left -= take;
                    }
                } else { /* the command wraps rather than lose its end */
                    tui_lines w = {NULL, 0, 0};
                    const char *style = strncmp(one, "\xe2\x9c\x97", 3) == 0 ? RED : one[0] == RC_DIM ? DIM : "";
                    if (one[0] == RC_DIM) {
                        memmove(one, one + 1, strlen(one));
                    }
                    (void)tui_wrap(one, strlen(one), a->cols > 2 ? (size_t)a->cols : 2, &w);
                    for (size_t i = 0; i < w.n; i++) {
                        add_fit(tail, style, w.lines[i], a->cols);
                    }
                    if (w.n == 0) {
                        add_fit(tail, "", "", a->cols);
                    }
                    tui_lines_clear(&w);
                }
                free(one);
            }
            at += n + (nl != NULL);
        }
        if (a->ov_hint[0]) {
            add_fit(tail, CYAN, a->ov_hint, a->cols);
        }
        return;
    }
    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 == OV_FORK) {
            (void)snprintf(line, sizeof line, "  Message %d of %d", i + 1, a->ov_n);
            add_fit(tail, DIM, line, a->cols);
        }
    }
    if (a->ov_m == 0 && !(a->ov == OV_ASK && !a->ov_n)) {
        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);
    }
    {
        tui_lines h = {NULL, 0, 0}; /* a long hint wraps rather than lose its end */
        (void)tui_wrap(a->ov_hint, strlen(a->ov_hint), a->cols > 2 ? (size_t)a->cols : 2, &h);
        for (size_t i = 0; i < h.n; i++) {
            add_fit(tail, DIM, h.lines[i], a->cols);
        }
        tui_lines_clear(&h);
    }
}

/* A key on /rc out of a pairing. The two lines take c, q, p, d and s (and r for an older pic remote); any other key there goes
 * back to the conversation. The phones' page takes p, R and the numbers; the QR code's, nothing. */
static void rc_page_key(app *a, char c) {
    if (a->rc_ssh) {
        if (c == 'c' || c == 'C') {
            rc_copy(a);
            rc_render(a);
        }
        return;
    }
    if (a->rc_confirm) {
        rc_key(a, c);
        return;
    }
    if (a->rc_devices == 0 && a->rc_view != RC_DEVICES) {
        if (c == 'p') {
            rc_key(a, c);
        } else {
            ov_free(a);
        }
        return;
    }
    if (a->rc_view == RC_DEVICES) {
        if (c == 'p') {
            a->rc_view = RC_MAIN;
            a->rc_direct = 0;
        }
        if (c == 'p' || c == 'R' || c == 'u' || (c >= '1' && c <= '8')) {
            rc_key(a, c);
        }
        return;
    }
    if (a->rc_view == RC_QR) {
        if (a->rc_direct) {
            ov_free(a);
            return;
        }
        a->rc_view = RC_MAIN;
        rc_render(a);
        return;
    }
    switch (c) {
    case 'c':
    case 'C':
        rc_copy(a);
        rc_render(a);
        break;
    case 'q':
    case 'd':
        a->rc_view = c == 'q' ? RC_QR : RC_DEVICES;
        a->rc_direct = 0;
        a->rc_note[0] = '\0';
        rc_render(a);
        break;
    case 'p':
    case 's':
        rc_key(a, c);
        break;
    case 'r':
        if (a->rc_on && a->rc_stale) {
            rc_key(a, c);
            break;
        }
        ov_free(a);
        break;
    default:
        ov_free(a);
        break;
    }
}

static void overlay_key(app *a, const tui_key *k) {
    size_t len = strlen(a->ov_filter);
    int moved = k->kind == TUI_KEY_UP || k->kind == TUI_KEY_DOWN || k->kind == TUI_KEY_PAGEUP || k->kind == TUI_KEY_PAGEDOWN;
    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:
        if (a->ov == OV_THEME) { /* the earlier theme comes back (and the settings panel, when it opened this) */
            theme_use(a, a->theme_prev);
            ov_free(a);
            break;
        }
        if (a->ov == OV_SUMMARY) { /* Pi: back to the tree */
            ov_free(a);
            tree_open(a, a->branch_at);
            break;
        }
        if (a->ov == OV_REMOTE && a->rc_pairing) { /* the pairing stops; the page stays */
            rc_cancel(a);
            break;
        }
        if (a->ov == OV_REMOTE && a->rc_confirm) {
            a->rc_confirm = 0;
            rc_render(a);
            break;
        }
        if (a->ov == OV_REMOTE && !a->rc_ssh && a->rc_view != RC_MAIN && !a->rc_direct) { /* back to /rc's two lines */
            a->rc_view = RC_MAIN;
            a->rc_note[0] = '\0';
            rc_render(a);
            break;
        }
        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_REMOTE) {
            if (a->rc_pairing) {
                rc_pair_key(a, k->text[0]);
            } else {
                rc_page_key(a, k->text[0]);
            }
        } else if (a->ov == OV_WAKES) {
            wk_key(a, k->text[0]);
        } else if (a->ov == OV_ASK && strcmp(a->ask_kind, "confirm") == 0) { /* y / n */
            char ask[24];
            (void)snprintf(ask, sizeof ask, "%s", a->ov_data ? a->ov_data : "0");
            if (k->text[0] == 'y' || k->text[0] == 'Y' || k->text[0] == 'n' || k->text[0] == 'N') {
                ov_free(a);
                ask_answer(a, ask, k->text[0] == 'y' || k->text[0] == 'Y' ? "true" : "false");
            }
        } else if (a->ov == OV_APPROVE) { /* y / n */
            char name[16];
            (void)snprintf(name, sizeof name, "%s", a->ov_data ? a->ov_data : "");
            if (k->text[0] == 'y' || k->text[0] == 'Y' || k->text[0] == 'n' || k->text[0] == 'N') {
                ov_free(a);
                wk_decide(a, name, k->text[0] == 'y' || k->text[0] == 'Y');
            }
        } else 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;
    }
    if (moved) {
        theme_preview(a);
    }
}

/* 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, int dir) {
    patterns pl = {NULL, 0};
    int *list = NULL, n = 0, at = -1;
    load_models_in(a, 0, 0); /* one stable order: ranked, the current model would always come first (Pi's _cycleAvailableModel) */
    (void)cl_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 < 0 ? (dir < 0 ? n - 1 : 0) : (at + (dir < 0 ? n - 1 : 1)) % n], 0);
    }
    free(list);
    patterns_free(&pl);
}

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

static const struct {
    const char *name, *hint, *what;
} commands[] = {
    {"settings", "", "open the settings, even while a reply runs"},
    {"config", "", "open the settings (Claude Code's name for /settings)"},
    {"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"},
    {"delete", "[ID|NAME]", "delete this conversation, or another (/restore brings it back)"},
    {"restore", "[ID|NAME]", "bring back the conversation deleted last, or that one"},
    {"trash", "", "list deleted conversations; enter restores one"},
    {"archived", "", "list archived conversations; enter resumes one, a unarchives it"},
    {"name", "NAME", "name this conversation"},
    {"session", "", "show this conversation's info and stats"},
    {"fork", "[ENTRY]", "pick an earlier message to branch from (or give an ENTRY, see /log)"},
    {"rewind", "", "go back to an earlier message: restore the conversation, the files, or both"},
    {"clone", "", "duplicate this conversation at its current point"},
    {"compact", "[FOCUS]", "summarize the history now"},
    {"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"},
    {"loop", "[EVERY] PROMPT", "send PROMPT now and every 5m, 1h, ... (10m when not given); alone: the list"},
    {"monitor", "[--done] COMMAND", "each new line of COMMAND's output wakes this conversation (--done: once, when it exits)"},
    {"goal", "CONDITION [--check CMD]", "work in rounds until CONDITION is true (CMD exits 0, or the model says so); pause, resume, clear"},
    {"stop", "", "pause every loop, monitor and goal of this conversation, and list them"},
    {"remote-control", "[pair|devices|qr|off|ssh]", "open this conversation on your phone: its link, copied, or pairing (also /rc)"},
    {"reload", "", "reload project instructions, skills, prompt templates, the model catalog, keybindings and themes"},
    {"trust", "[yes|no]", "save the workspace trust decision"},
    {"changelog", "", "show what changed"},
    {"restart", "", "start the newer pic that was installed, on this conversation"},
    {"bug", "TEXT", "record a bug report (kept locally, sent nowhere)"},
    {"auth", "", "every key and sign-in: what is left, which the model uses; enter fixes the selected one"},
    {"login", "[PROVIDER]", "sign in or store an API key for PROVIDER; without one, choose the provider (/auth's a)"},
    {"logout", "[PROVIDER]", "remove PROVIDER's stored sign-in or API key; without one, /auth"},
    {"key", "", "the same as /auth"},
    {"mcp", "[add ARGS]", "the MCP servers, their state and tools; add takes pic mcp add's arguments"},
    {"codemode", "[on|off]", "switch the codemode tool (scripts that call the other tools) for this session"},
    {"mouse", "[on|off]", "capture the mouse in fullscreen or leave it to the terminal, for this session (alt+m)"},
    {"hotkeys", "", "show keyboard shortcuts"},
    {"help", "[TOPIC]", "keys and commands, or a topic of the manual (pic help)"},
    {"quit", "", "quit pic"},
};
#define NCOMMANDS (sizeof commands / sizeof commands[0])
#define MENU_ROWS 5 /* rows shown at once (Pi's autocompleteMaxVisible) */
#define MENU_MAX 128 /* items kept, scrolled through */

static int is_builtin(const char *name, size_t len) {
    if ((len == 4 && strncmp(name, "exit", 4) == 0) || (len == 2 && strncmp(name, "rc", 2) == 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 tui_command *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;
}

/* Whether LINE ("/skill:name ARGS") names a skill. */
static int skill_for(const app *a, const char *line) {
    size_t len;
    if (strncmp(line, "/skill:", 7) != 0) {
        return 0;
    }
    len = strcspn(line + 7, " \t\r\n");
    for (size_t i = 0; i < a->skl.n; i++) {
        if (strlen(a->skl.v[i].name) == len && strncmp(a->skl.v[i].name, line + 7, len) == 0) {
            return 1;
        }
    }
    return 0;
}

static void commands_free(tui_commands *c) {
    for (size_t i = 0; i < c->n; i++) {
        free(c->v[i].name);
        free(c->v[i].description);
        free(c->v[i].hint);
    }
    free(c->v);
    c->v = NULL;
    c->n = 0;
}

static void commands_add(tui_commands *c, const char *name, const char *description, const char *hint) {
    tui_command *v = realloc(c->v, (c->n + 1) * sizeof *v);
    if (!v) {
        return;
    }
    c->v = v;
    v[c->n].name = strdup(name);
    v[c->n].description = strdup(description ? description : "");
    v[c->n].hint = strdup(hint ? hint : "");
    c->n++;
}

/* (Re)reads the templates and skills (get_commands): the user's, and the
 * workspace's when it is trusted. */
static void load_templates(app *a) {
    pic_model m;
    char err[PIC_ERR_CAP], members[64], *data, *warning;
    long window = a->o->context_window >= 0 ? a->o->context_window
                  : pic_model_resolve(a->model, &m, err, sizeof err) == 0 ? m.context_window : a->window;
    commands_free(&a->skl);
    commands_free(&a->tpl);
    (void)snprintf(members, sizeof members, "\"contextWindow\":%ld", window);
    if (!(data = cl_ask("get_commands", members, NULL, 0))) {
        notice(a, RED, "could not read the skills and prompt templates");
        return;
    }
    for (int i = 0;; i++) {
        char key[64], *name, *source, *description, *hint;
        (void)snprintf(key, sizeof key, "$.commands[%d].name", i);
        if (!(name = cl_get(data, key))) {
            break;
        }
        (void)snprintf(key, sizeof key, "$.commands[%d].source", i);
        source = cl_get(data, key);
        (void)snprintf(key, sizeof key, "$.commands[%d].description", i);
        description = cl_get(data, key);
        (void)snprintf(key, sizeof key, "$.commands[%d].argumentHint", i);
        hint = cl_get(data, key);
        if (source && strcmp(source, "skill") == 0) {
            commands_add(&a->skl, strncmp(name, "skill:", 6) == 0 ? name + 6 : name, description, NULL);
        } else {
            commands_add(&a->tpl, name, description, hint);
        }
        free(name);
        free(source);
        free(description);
        free(hint);
    }
    if ((warning = cl_get(data, "$.skillsWarning"))) { /* queued: at startup the width is not known yet; warn_flush shows it */
        char *line = malloc(strlen(warning) + 8);
        if (line) {
            (void)snprintf(line, strlen(warning) + 8, "pic: %s\n", warning);
            warn_add(a, line);
            free(line);
        }
        free(warning);
    }
    free(data);
}

/* @file completion's listing: pic's list_files, which leaves out what the ignore files say. */
static size_t at_list(void *ctx, const char *base, atfile_found **out) {
    char members[4600], *dir = cl_member("dir", base), *data;
    sqlite3_stmt *q = NULL;
    size_t n = 0, cap = 0;
    (void)ctx;
    *out = NULL;
    (void)snprintf(members, sizeof members, "%s,\"maxEntries\":%d,\"maxDepth\":%d", dir ? dir : "\"dir\":\".\"",
                   ATFILE_MAX_ENTRIES, ATFILE_MAX_DEPTH);
    free(dir);
    if (!(data = cl_ask("list_files", members, NULL, 0))) {
        return 0;
    }
    if (sqlite3_prepare_v2(cl_db,
                           "SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]'), json_extract(value, '$[2]')"
                           " FROM json_each(?1, '$.entries')",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, data, -1, SQLITE_STATIC);
        while (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            if (n == cap) {
                atfile_found *v = realloc(*out, (cap ? cap * 2 : 256) * sizeof *v);
                if (!v) {
                    break;
                }
                *out = v;
                cap = cap ? cap * 2 : 256;
            }
            (*out)[n].path = strdup((const char *)sqlite3_column_text(q, 0));
            (*out)[n].is_dir = sqlite3_column_int(q, 1);
            (*out)[n].depth = sqlite3_column_int(q, 2);
            if ((*out)[n].path) {
                n++;
            }
        }
    }
    sqlite3_finalize(q);
    free(data);
    return n;
}

/* The @file menu (Pi: files and folders under the workspace for "@" + a
 * partial path). Fills labels/values; the list is kept while the token is
 * unchanged so a redraw does not walk the tree again. */
static size_t at_items_for(app *a, char labels[][256], char values[][256], size_t cap) {
    const char *t = tui_editor_text(a->ed);
    char query[512], key[520];
    size_t start, n;
    int quoted;
    if (!atfile_token(t, tui_editor_cursor(a->ed), &start, query, sizeof query, &quoted)) {
        a->at_valid = 0;
        return 0;
    }
    (void)snprintf(key, sizeof key, "%d%s", quoted, query);
    if (!a->at_valid || strcmp(key, a->at_key) != 0) {
        a->at_n = atfile_candidates(a->o->workspace, query, quoted, a->at_items, sizeof a->at_items / sizeof *a->at_items,
                                    at_list, NULL);
        (void)snprintf(a->at_key, sizeof a->at_key, "%s", key);
        a->at_valid = 1;
    }
    n = a->at_n < cap ? a->at_n : cap;
    for (size_t i = 0; i < n; i++) {
        (void)snprintf(labels[i], 256, "%s", a->at_items[i].label);
        (void)snprintf(values[i], 256, "%s", a->at_items[i].value);
    }
    return n;
}

/* Puts the chosen completion in place of the token; a folder keeps the
 * cursor inside it so the next level completes, a file adds a space (Pi's
 * applyCompletion). */
static void at_accept(app *a, size_t sel) {
    const char *t = tui_editor_text(a->ed);
    char query[512], v[ATFILE_VALUE_MAX + 2];
    size_t start, cur = tui_editor_cursor(a->ed), len, end = cur;
    int quoted;
    const atfile_item *it = &a->at_items[sel];
    if (!atfile_token(t, cur, &start, query, sizeof query, &quoted)) {
        return;
    }
    len = strlen(it->value);
    if (it->value[len - 1] == '"' && t[end] == '"') {
        end++; /* the closing quote is already there */
    }
    (void)snprintf(v, sizeof v, "%s%s", it->value, it->is_dir ? "" : " ");
    tui_editor_replace(a->ed, start, end, v, it->is_dir && it->value[len - 1] == '"' ? len - 1 : strlen(v));
    a->at_valid = 0;
    a->menu_sel = 0;
}

/* 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 (strcmp(t, a->menu_dismissed) != 0 && (n = at_items_for(a, labels, values, cap)) > 0) {
        *is_command = 2;
        return n;
    }
    if (*s != '/' || memchr(t, '\n', cur) || cur < (size_t)(s - t) + 1 || strcmp(t, a->menu_dismissed) == 0) {
        return 0;
    }
    if (!strpbrk(s, " \t")) {
        size_t total = NCOMMANDS + a->tpl.n + a->skl.n;
        const char **names = malloc(total * sizeof *names);
        size_t *ord = malloc(total * sizeof *ord);
        char (*skill_names)[80] = malloc((a->skl.n + 1) * sizeof *skill_names);
        char query[128];
        size_t shown = 0;
        if (!names || !ord || !skill_names) {
            free(names);
            free(ord);
            free(skill_names);
            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;
        }
        for (size_t i = 0; i < a->skl.n; i++) {
            (void)snprintf(skill_names[i], sizeof skill_names[i], "skill:%s", a->skl.v[i].name);
            names[NCOMMANDS + a->tpl.n + i] = skill_names[i];
        }
        n = tui_fuzzy_filter(query, names, total, 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 (ord[i] >= NCOMMANDS + a->tpl.n) {
                name = names[ord[i]], hint = "", what = a->skl.v[ord[i] - NCOMMANDS - a->tpl.n].description;
            } else if (*names[ord[i]]) {
                const tui_command *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);
        free(skill_names);
        *is_command = 1;
        return shown;
    }
    if (strncmp(s, "/model ", 7) == 0 && !a->mp_open) { /* the open picker's rows are the models' arrays */
        const char *q = s + 7;
        size_t *ord;
        while (*q == ' ') {
            q++;
        }
        if (!a->nmodels || a->mp_all) {
            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_MAX][256], values[MENU_MAX][256];
    int is_command;
    size_t n = menu_items(a, labels, values, MENU_MAX, &is_command);
    if (a->menu_sel >= (int)n) {
        a->menu_sel = 0;
    }
    /* Pi's SelectList: a window of MENU_ROWS centred on the selection, and
     * "  (selected/total)" under it when the list is longer. */
    size_t from = 0, to = n;
    if (n > MENU_ROWS) {
        long f = (long)a->menu_sel - MENU_ROWS / 2;
        from = f < 0 ? 0 : (size_t)f > n - MENU_ROWS ? n - MENU_ROWS : (size_t)f;
        to = from + MENU_ROWS;
    }
    for (size_t i = from; i < to; i++) {
        add_fit(tail, (int)i == a->menu_sel ? CYAN : DIM, labels[i], a->cols);
    }
    if (n > MENU_ROWS) {
        char info[48];
        (void)snprintf(info, sizeof info, "  (%d/%zu)", a->menu_sel + 1, n);
        add_fit(tail, DIM, info, 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_MAX][256], values[MENU_MAX][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_MAX, &is_command);
    if (n == 0) {
        return 0;
    }
    if (a->menu_sel >= (int)n) {
        a->menu_sel = 0;
    }
    if (is_command == 2 && (k->kind == TUI_KEY_TAB || k->kind == TUI_KEY_ENTER)) {
        at_accept(a, (size_t)a->menu_sel);
        return 1;
    }
    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 if (strncmp(values[a->menu_sel], "/model ", 7) == 0) {
            /* one Enter: the only model offered, or one chosen with the arrows; else what is typed, which
             * switches on one clear match and otherwise opens the picker on the matches */
            const char *typed = tui_editor_text(a->ed);
            char *v;
            typed += strspn(typed, " ");
            v = strdup(n == 1 || a->menu_sel > 0 ? values[a->menu_sel] : typed);
            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;
    }
}

static int over_ssh(void);

/* Copies TEXT and says where it went. Here, the system's own clipboard command (clipboard.h),
 * which is the one way a terminal that ignores OSC 52 (Terminal.app) gets it. Over ssh that
 * command would fill the far machine's clipboard, so the terminal is asked instead with OSC 52
 * (through tmux's passthrough inside it; not for very long text), as it is here when there is no
 * such command. What the terminal did with OSC 52 cannot be known: COPY_TERMINAL is "asked". */
static int copy_text(const char *t) {
    size_t n = strlen(t), len;
    char *osc;
    if (!over_ssh() && tui_clipboard_write(t, n) == 0) {
        return COPY_NATIVE;
    }
    osc = tui_term_osc52(t, n, getenv("TMUX") != NULL, &len);
    if (osc) {
        ssize_t w = write(STDOUT_FILENO, osc, len);
        free(osc);
        return w == (ssize_t)len ? COPY_TERMINAL : COPY_NONE;
    }
    return COPY_NONE;
}

static void flash_for(app *a, const char *msg, long ms) {
    (void)snprintf(a->flash, sizeof a->flash, "%s", msg);
    a->flash_until = now_ms() + ms;
}

static void flash(app *a, const char *msg) {
    flash_for(a, msg, 1500);
}

/* Fullscreen: the transcript selection to the clipboard (Pi's
 * copySelectionToClipboard), with its "Copied!" flash. 0 when nothing is selected. */
static int copy_selection(app *a) {
    char *t = tui_render_selection(a->r);
    if (!t) {
        return 0;
    }
    (void)copy_text(t);
    free(t);
    flash(a, "Copied!");
    return 1;
}

static void copy_last(app *a) {
    if (a->last_reply && *a->last_reply) {
        if (copy_text(a->last_reply) != COPY_NONE) {
            notice(a, DIM, "Copied last agent message to clipboard");
        } else {
            notice(a, RED, "Could not copy: this text is too long for the terminal's clipboard");
        }
    } else {
        notice(a, RED, "Error: No agent messages to copy yet.");
    }
}

/* What /hotkeys adds to the bindings of keybindings.json: input that is not an action. */
static const char hotkeys_extra[] =
    "\nOther:\n"
    "  Esc Esc on an empty editor  open /tree\n"
    "  !cmd   run a bash command, recorded in the conversation (the model sees it with your next message)\n"
    "  !!cmd  run a bash command, output stays out of the context       Esc  cancel it\n"
    "  Fullscreen: the wheel scrolls the transcript, dragging selects (copied at once, or with the copy key when\n"
    "  fullscreenCopyOnSelect is false); Ctrl+F searches it (Pi's Ctrl+Shift+F too), elsewhere Ctrl+F is cursor right\n"
    "  A click opens a link; a right click hands the mouse to the terminal (its menu, selection, " LINK_CLICK ") until a key\n"
    "  Enter while a reply runs: steer it (Claude Code); Up on the first line pulls queued messages back; Esc Esc clears a draft\n"
    "  \\ then Enter: a newline (Claude Code)    Ctrl+L redraws the screen (Claude Code); the model picker is /model, Alt+P\n"
    "  Ctrl+D on an empty editor: press twice within 800 ms to exit (Claude Code)\n"
    "  Ctrl+R: search prompt history; type to filter, Ctrl+R again for an older match, Enter takes it into the editor, Esc cancels\n"
    "  Fullscreen search: the keys listed under Fullscreen; while the box is open typing goes to the query\n"
    "Defaults that differ from Pi are in the README (Mac Terminal and iTerm2 send these without Option as Meta).\n"
    "Rebind any action in ~/.pic/keybindings.json (Pi's format); /reload applies it.";

/* ---- /login: a provider, a method, then the sign-in or the key, in place --------
 * As Pi's (oauth-selector.ts and its login dialog): the picker shows what each
 * provider uses now; a provider with a subscription sign-in asks which method;
 * the key and the store's passphrase are typed into masked fields (paste
 * works); a sign-in runs as `pic auth login PROVIDER --pipe` in a child, whose
 * JSON lines give the address to open, and Esc or Ctrl-C cancels it. Nothing
 * is printed outside the interface, and nothing ends pic. */

/* PROVIDER's settings into m: 0, or -1 with the notice shown. */
static int login_provider(app *a, const char *provider, pic_model *m) {
    char name[128], err[256];
    (void)snprintf(name, sizeof name, "%s/x", provider);
    if (pic_model_resolve(name, m, err, sizeof err) != 0 || strcmp(m->provider, provider) != 0) {
        notice(a, RED, "unknown provider %s (/login PROVIDER; pic models --all lists them)", provider);
        return -1;
    }
    return 0;
}

/* What PROVIDER uses now, as a request would find it. */
static void login_state(const char *provider, char *out, size_t cap) {
    pic_model m;
    char err[256], name[128];
    const char *label = pic_cred_oauth_label(provider);
    (void)snprintf(name, sizeof name, "%s/x", provider);
    if (pic_model_resolve(name, &m, err, sizeof err) != 0) {
        (void)snprintf(out, cap, "\xe2\x80\xa2 unknown");
        return;
    }
    switch (pic_cred_source_of(provider, m.key_env, m.key_literal)) {
    case PIC_CRED_STORED_OAUTH:
    case PIC_CRED_STORED_KEY: {
        /* A stored credential is used first; say so when it shadows the variable. */
        const char *v = m.key_env[0] ? getenv(m.key_env) : NULL;
        char also[128] = "";
        if (v && *v) {
            (void)snprintf(also, sizeof also, " (in use; %s also set)", m.key_env);
        }
        if (pic_cred_source_of(provider, m.key_env, m.key_literal) == PIC_CRED_STORED_OAUTH) {
            (void)snprintf(out, cap, "\xe2\x9c\x93 signed in (%s)%s", label ? label : "subscription", also);
        } else {
            (void)snprintf(out, cap, "\xe2\x9c\x93 API key (stored)%s", also);
        }
        break;
    }
    case PIC_CRED_ENV:
        (void)snprintf(out, cap, "\xe2\x9c\x93 env: %s", m.key_env);
        break;
    case PIC_CRED_LITERAL:
        (void)snprintf(out, cap, "\xe2\x9c\x93 models.json");
        break;
    default:
        (void)snprintf(out, cap, m.key_env[0] ? "\xe2\x80\xa2 not configured" : "\xe2\x80\xa2 no key needed");
    }
}

static int login_pick_row(void *ctx, const char *provider) {
    app *a = ctx;
    char row[256], state[160];
    login_state(provider, state, sizeof state);
    (void)snprintf(row, sizeof row, "%-14s %s%s", provider, state,
                   pic_cred_oauth_label(provider) ? "  [subscription or API key]" : "");
    ov_add(a, row, provider, 0);
    return 0;
}

/* The provider picker, the model's provider selected. */
static void login_picker(app *a) {
    char current[64];
    (void)snprintf(current, sizeof current, "%.*s", (int)strcspn(a->model, "/"), a->model);
    ov_open(a, OV_LOGIN_PROVIDER, "Log in  (type to filter \xc2\xb7 up/down \xc2\xb7 enter: choose \xc2\xb7 esc)",
            "Choose a provider; each shows what it uses now.");
    (void)cl_each("get_providers", "$.providers", login_pick_row, a);
    ov_refilter(a);
    for (size_t i = 0; i < a->ov_m; i++) {
        if (strcmp(a->ov_id[a->ov_order[i]], current) == 0) {
            a->ov_sel = (int)i;
        }
    }
}

/* ---- keys: /key and alt+k, the footer's key, and the swap prompt ---------------
 * A provider may hold several keys (cred.h); pic remembers what the last
 * reply said of each. /key lists them all with that state, and Enter makes
 * one the provider's active key. When a reply is refused for its key, the
 * child leaves the request unfinished and says so (key_failure); the prompt
 * then offers another key, another model, a wait or a new login, with the
 * cost of starting the cache again. pic never swaps keys on its own. */

static long long key_wall_ms(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); }

/* The provider MODEL resolves to (a bare claude- id is anthropic's), into
 * out, and its settings into m: 0, or -1. */
static int key_model_provider(const char *model, char *out, size_t cap, pic_model *m) {
    char err[256];
    if (pic_model_resolve(model, m, err, sizeof err) != 0) {
        out[0] = '\0';
        return -1;
    }
    (void)snprintf(out, cap, "%s", m->provider);
    return 0;
}

/* A choice of key for PROVIDER made here replaces --key's for it, in this
 * process and in the requests it starts. */
static void key_run_replace(app *a, const char *provider, const char *label) {
    if (a->key_run[0] && strcmp(a->key_run_provider, provider) == 0) {
        (void)snprintf(a->key_run, sizeof a->key_run, "%s", label);
        (void)pic_cred_override(provider, label); /* --key already holds its slot */
    }
}

/* PROVIDER's settings into m: 0, or -1. */
static int key_provider_model(const char *provider, pic_model *m) {
    char name[128], err[256];
    (void)snprintf(name, sizeof name, "%s/x", provider);
    return pic_model_resolve(name, m, err, sizeof err) == 0 && strcmp(m->provider, provider) == 0 ? 0 : -1;
}

typedef struct {
    int n, env_active;
    char label[PIC_CRED_LABEL_CAP], alert[96], other_alert[96];
    long long now;
} key_scan;

/* NAME's recorded or reported expiry in words ("expires in 6 days (29 Nov, recorded)", "expired 22 Nov
 * (recorded)") into out, "" with none: 2 expired, 1 within keyExpiryWarnDays, 0 otherwise. */
static int key_expiry_words(const char *name, long long now, char *out, size_t cap) {
    long long exp = 0, left;
    char src[16], day[16], *w = cl_setting("keyExpiryWarnDays");
    long warn = w && *w ? strtol(w, NULL, 10) : 7;
    time_t t;
    struct tm tm;
    free(w);
    out[0] = '\0';
    if (!pic_cred_expiry_of(name, &exp, src, sizeof src, NULL)) {
        return 0;
    }
    left = exp - now;
    t = (time_t)(exp / 1000);
    (void)strftime(day, sizeof day, "%d %b", gmtime_r(&t, &tm));
    if (left <= 0) {
        (void)snprintf(out, cap, "expired %s (%s)", day, src);
        return 2;
    }
    (void)snprintf(out, cap, "expires in %lld day%s (%s, %s)", (left + 86399999LL) / 86400000LL, left <= 86400000LL ? "" : "s", day,
                   src);
    return left <= (long long)warn * 86400000LL;
}

static int key_scan_entry(void *ctx, const pic_cred_entry *e) {
    key_scan *k = ctx;
    pic_key_health h;
    char al[96];
    k->n++;
    (void)pic_cred_health_of(e->name, &h);
    pic_cred_key_alert(&h, k->now, al, sizeof al);
    if (!al[0] && e->active) { /* a key in use that expires soon, or has */
        char when[96];
        if (key_expiry_words(e->name, k->now, when, sizeof when)) {
            (void)snprintf(al, sizeof al, "! %.80s", when);
        }
    }
    if (e->active) {
        (void)snprintf(k->label, sizeof k->label, "%s", e->label);
        k->env_active = strcmp(e->kind, "env") == 0;
        (void)snprintf(k->alert, sizeof k->alert, "%s", al);
    } else if (al[0] && !k->other_alert[0]) {
        (void)snprintf(k->other_alert, sizeof k->other_alert, "%s: %s", al, e->label);
    }
    return 0;
}

/* The footer's key and warning for the model's provider, read at most every
 * two seconds (or at once after a change: key_seg_at 0). The key is shown
 * only when the provider has more than one or uses its variable. */
static void key_footer(app *a) {
    key_scan k;
    pic_model m;
    char provider[PIC_CRED_PROVIDER_CAP];
    if (a->key_seg_at && now_ms() - a->key_seg_at < 2000) {
        return;
    }
    a->key_seg_at = now_ms();
    a->key_seg[0] = a->key_alert[0] = '\0';
    pic_cred_model(a->model); /* the model's key follows its rule */
    if (key_model_provider(a->model, provider, sizeof provider, &m) != 0) {
        return;
    }
    memset(&k, 0, sizeof k);
    k.now = key_wall_ms();
    (void)pic_cred_entries(provider, m.key_env, m.key_literal, key_scan_entry, &k);
    if (k.label[0] && (k.n > 1 || k.env_active)) {
        (void)snprintf(a->key_seg, sizeof a->key_seg, "%s", k.label);
    }
    (void)snprintf(a->key_alert, sizeof a->key_alert, "%s", k.alert[0] ? k.alert : k.other_alert);
}


/* ---- free checks of keys, in a child ----------------------------------------
 * `pic auth status --refresh` runs in a child of its own (it holds no terminal and never asks for
 * the passphrase), so a slow provider cannot stall the interface; it records what it learns in the
 * credential table, which the footer and /key read. Opening /key checks every key not checked in
 * ten minutes; starting up checks the active one, and gives up on it after two seconds. */
static int keychk_start(app *a, const char *const *args, long limit_ms) {
    const char *off = getenv("PIC_NO_KEY_CHECKS");
    char *offline = cl_setting("offline");
    int none = (off && *off) || (offline && strcmp(offline, "true") == 0); /* PIC_NO_KEY_CHECKS: a test seam */
    free(offline);
    if (none) { /* no check goes out on its own */
        return 0;
    }
    if (a->keychk_on) {
        a->keychk_more = args[3] == NULL; /* only an all-keys check waits its turn */
        return 0;
    }
    if (spawn(a, &a->keychk, args) != 0) {
        return -1;
    }
    a->keychk_on = 1;
    a->keychk_at = now_ms();
    a->keychk_limit_ms = limit_ms;
    return 0;
}

/* The active key of the model's provider, once, as the interface starts. */
static void keychk_startup(app *a) {
    char provider[PIC_CRED_PROVIDER_CAP];
    pic_model m;
    const char *args[] = {"auth", "status", "--refresh", "--active", provider, NULL};
    if (key_model_provider(a->model, provider, sizeof provider, &m) == 0) {
        (void)keychk_start(a, args, 2000);
    }
}

/* The check running: its rows fill in as answers arrive; when it ends the footer rereads. */
static void pump_keychk(app *a) {
    int status;
    (void)drain(&a->keychk);
    if (a->au.on) {
        au_build(a);
    }
    if (waitpid(a->keychk.pid, &status, WNOHANG) != a->keychk.pid) {
        if (now_ms() - a->keychk_at > a->keychk_limit_ms) {
            (void)kill(a->keychk.pid, SIGTERM);
            a->keychk_limit_ms = 1 << 30; /* once */
        }
        return;
    }
    (void)drain(&a->keychk);
    if (a->keychk.out >= 0) {
        close(a->keychk.out);
    }
    if (a->keychk.err >= 0) {
        close(a->keychk.err);
    }
    free(a->keychk.outbuf.buf);
    free(a->keychk.errbuf.buf);
    memset(&a->keychk, 0, sizeof a->keychk);
    a->keychk.out = a->keychk.err = -1;
    a->keychk_on = 0;
    a->key_seg_at = 0;
    if (a->au.on) {
        au_build(a);
    }
    if (a->keychk_more) {
        const char *args[] = {"auth", "status", "--refresh", NULL};
        a->keychk_more = 0;
        (void)keychk_start(a, args, 12000);
    }
}


/* Makes the key ID ("provider label") its provider's active one. */
static void key_chosen(app *a, const char *id) {
    char provider[PIC_CRED_PROVIDER_CAP], err[256];
    const char *label = strchr(id, ' ');
    pic_model m;
    if (!label || (size_t)(label - id) >= sizeof provider) {
        return;
    }
    (void)snprintf(provider, sizeof provider, "%.*s", (int)(label - id), id);
    if (key_provider_model(provider, &m) != 0) {
        return;
    }
    label++;
    if (pic_cred_use(provider, label, m.key_env, m.key_literal, err, sizeof err) != 0) {
        notice(a, RED, "pic: %s", err);
        return;
    }
    key_run_replace(a, provider, label);
    a->key_seg_at = 0;
    notice(a, DIM, "Requests to %s use the key \"%s\" from the next one.", provider, label);
}

/* ---- /auth: every key and sign-in, in the settings panel's frame -----------------------------
 * One row a key or sign-in, grouped by provider (the model's first), with what pic last learnt of
 * it, which models it serves and the row's own keys; a row for the model's provider when it has no
 * key; and one to add a key or sign in. Enter does what the row needs: use a healthy key, replace a
 * refused one, sign in again, add where there is none. Plain keys only: a adds, d removes (after y),
 * c checks, m opens the models. Opening it runs the free checks, and its rows fill in as they answer. */

static void login(app *a, const char *arg);

typedef struct {
    app *a;
    tui_settings *l;
    size_t cap;
    long long now;
    const char *mprov; /* the model's provider */
} au_rows;

static tui_setting *au_row(au_rows *r) {
    tui_setting *row;
    if (r->l->n == r->cap) {
        size_t cap = r->cap ? 2 * r->cap : 16;
        tui_setting *s = realloc(r->l->s, cap * sizeof *s);
        if (!s) {
            return NULL;
        }
        r->l->s = s;
        r->cap = cap;
    }
    row = &r->l->s[r->l->n++];
    memset(row, 0, sizeof *row);
    row->key = strdup("");
    row->kind = strdup("info");
    row->def = strdup("");
    row->def_label = strdup("");
    row->valid = 1;
    return row;
}

static int au_entry(void *ctx, const pic_cred_entry *e) {
    au_rows *r = ctx;
    pic_key_health h;
    tui_setting *row = au_row(r);
    char buf[700], how[64], state[200], active_label[PIC_CRED_LABEL_CAP] = "";
    int bad, own = strcmp(e->provider, r->mprov) == 0 && e->active, stored = strcmp(e->kind, "env") != 0 &&
                                                                              strcmp(e->kind, "file") != 0;
    pic_model m;
    pic_cred_used u;
    if (!row) {
        return 1;
    }
    (void)pic_cred_health_of(e->name, &h);
    bad = pic_cred_key_bad(&h, r->now);
    pic_cred_key_phrase(&h, r->now, state, sizeof state);
    if (strcmp(e->kind, "env") == 0) {
        (void)snprintf(how, sizeof how, "%s", e->env);
    } else if (strcmp(e->kind, "oauth") == 0) {
        (void)snprintf(how, sizeof how, "%s", pic_cred_oauth_label(e->provider) ? pic_cred_oauth_label(e->provider) : "sign-in");
    } else {
        (void)snprintf(how, sizeof how, "%s", strcmp(e->kind, "file") == 0 ? "models.json key" : "API key");
    }
    if (key_provider_model(e->provider, &m) == 0 && pic_cred_active(e->provider, m.key_env, m.key_literal, &u) == 0) {
        (void)snprintf(active_label, sizeof active_label, "%s", u.label);
    }
    (void)snprintf(buf, sizeof buf, "%s %s", e->provider, e->label);
    row->id = strdup(buf);
    row->group = strdup(e->provider);
    (void)snprintf(buf, sizeof buf, "%s%s%s", e->label, e->active ? "*" : "", own ? "  \xe2\x86\x90 this model" : "");
    row->name = strdup(buf);
    {
        char when[96], age[48] = "";
        int near = key_expiry_words(e->name, r->now, when, sizeof when);
        long long as_of = h.probed_ms > h.checked_ms ? h.probed_ms : h.checked_ms;
        if (strcmp(e->kind, "command") == 0) {
            (void)snprintf(how, sizeof how, "command");
        }
        if (h.has_remaining && as_of) { /* a number is never shown without its age */
            long long mins = (r->now - as_of) / 60000;
            if (mins >= 1440) {
                (void)snprintf(age, sizeof age, " \xc2\xb7 last known");
            } else if (mins >= 1) {
                (void)snprintf(age, sizeof age, " \xc2\xb7 checked %lld min ago", mins);
            }
        }
        /* the expiry first: a date to act on outranks a reading */
        (void)snprintf(buf, sizeof buf, "%s \xc2\xb7 %s%s%s%s%s%s", how, near ? "! " : "", when, when[0] ? " \xc2\xb7 " : "",
                       bad ? "! " : "", state, age);
        bad |= near == 2;
    }
    row->value = strdup(buf);
    row->valid = !bad;
    if (r->a->au.nrules > 0) { /* the families a rule gives this key */
        size_t pn = strlen(e->provider), used = 0;
        char fams[400] = "";
        for (int i = 0; i < r->a->au.nrules; i++) {
            const pic_cred_rule *k = &r->a->au.rules[i];
            if (strncmp(k->pattern, e->provider, pn) == 0 && k->pattern[pn] == '/' && strcmp(k->label, e->label) == 0 &&
                used < sizeof fams) {
                used += (size_t)snprintf(fams + used, sizeof fams - used, "%s%s", used ? ", " : "", k->pattern);
            }
        }
        if (fams[0]) {
            (void)snprintf(buf, sizeof buf, "%s%sFor %s by rule%s", h.reason[0] && bad ? h.reason : "",
                           h.reason[0] && bad ? " " : "", fams, e->active ? ", and the rest of its provider's models." : ".");
            row->description = strdup(buf);
        }
    }
    if (row->description) {
        /* said: its rules */
    } else if (e->active) {
        (void)snprintf(buf, sizeof buf, "%s%sFor %s's models.", h.reason[0] && bad ? h.reason : "", h.reason[0] && bad ? " " : "",
                       e->provider);
    } else {
        (void)snprintf(buf, sizeof buf, "%s%sNot used: %s's requests use \"%s\".", h.reason[0] && bad ? h.reason : "",
                       h.reason[0] && bad ? " " : "", e->provider, active_label[0] ? active_label : "another");
    }
    if (!row->description) {
        row->description = strdup(buf);
    }
    if (bad) {
        (void)snprintf(buf, sizeof buf, "%s%s",
                       strcmp(e->kind, "oauth") == 0 ? "enter: sign in again" : stored ? "enter: replace this key"
                                                                                     : "enter: store a key instead",
                       stored ? " \xc2\xb7 e: expiry \xc2\xb7 d: remove" : " \xc2\xb7 e: expiry");
    } else {
        (void)snprintf(buf, sizeof buf, "%s \xc2\xb7 b: models for this key \xc2\xb7 e: expiry%s \xc2\xb7 c: check",
                       e->active ? "in use" : "enter: use this key", stored ? " \xc2\xb7 d: remove" : "");
    }
    row->applies = strdup(buf);
    return 0;
}

static int au_provider(void *ctx, const char *provider) {
    au_rows *r = ctx;
    pic_model m;
    if (strcmp(provider, r->mprov) != 0 && key_provider_model(provider, &m) == 0) {
        (void)pic_cred_entries(provider, m.key_env, m.key_literal, au_entry, ctx);
    }
    return 0;
}

/* The rows and the line above them again, from what pic knows now; the selected row stays. */
static void au_build(app *a) {
    au_rows r = {a, &a->au.l, 0, key_wall_ms(), ""};
    char mprov[PIC_CRED_PROVIDER_CAP] = "", key[PIC_CRED_LABEL_CAP] = "";
    pic_model m;
    size_t before;
    tui_setting *row;
    pic_cred_used u;
    int state = pic_cred_state();
    tui_settings_free(&a->au.l);
    free(a->au.rules);
    a->au.nrules = pic_cred_rules(&a->au.rules);
    pic_cred_model(a->model); /* the model's key follows its rule */
    if (key_model_provider(a->model, mprov, sizeof mprov, &m) == 0) {
        r.mprov = mprov;
        before = a->au.l.n;
        (void)pic_cred_entries(mprov, m.key_env, m.key_literal, au_entry, &r);
        if (a->au.l.n == before && (row = au_row(&r)) != NULL) { /* the model's provider has none */
            char buf[300];
            row->id = strdup(mprov);
            row->group = strdup(mprov);
            row->name = strdup("none  \xe2\x86\x90 this model");
            row->value = strdup("no key");
            (void)snprintf(buf, sizeof buf, "The model %s needs a key or a sign-in for %s.", a->model, mprov);
            row->description = strdup(buf);
            row->applies = strdup("enter: add a key or sign in");
        }
        if (pic_cred_active(mprov, m.key_env, m.key_literal, &u) == 0) {
            (void)snprintf(key, sizeof key, "%s", u.label);
        }
    }
    (void)cl_each("get_providers", "$.providers", au_provider, &r);
    if ((row = au_row(&r)) != NULL) {
        row->id = strdup("+");
        row->group = strdup("");
        row->name = strdup("+ add a key or sign in");
        row->value = strdup("");
        row->description = strdup("Store an API key, sealed, or sign in with a subscription.");
        row->applies = strdup("enter: choose a provider");
    }
    (void)snprintf(a->au.head, sizeof a->au.head, "model %s%s%s \xc2\xb7 store %s", a->model, key[0] ? " \xc2\xb7 key " : "",
                   key, state == PIC_CRED_OPEN ? "open" : state == PIC_CRED_LOCKED ? "not opened yet" : "not made yet");
    a->au.at = now_ms();
}

static void au_close(app *a) {
    a->au.on = 0;
    a->au.confirm[0] = a->au.bind[0] = '\0';
    tui_settings_free(&a->au.l);
    free(a->au.rules);
    a->au.rules = NULL;
    a->au.nrules = 0;
}

/* /auth (and /key, and /logout with no provider): NOTE, when given, under the description. /login
 * with none is /auth's add step, the providers. */
static void au_open(app *a, const char *note) {
    const char *refresh[] = {"auth", "status", "--refresh", NULL};
    char mprov[PIC_CRED_PROVIDER_CAP] = "";
    pic_model m;
    memset(&a->au.p, 0, sizeof a->au.p);
    a->au.p.title = "Auth";
    a->au.p.head = a->au.head;
    a->au.p.hint = "\xe2\x86\x91\xe2\x86\x93 move \xc2\xb7 enter: fix \xc2\xb7 a: add \xc2\xb7 b: models for a key \xc2\xb7 e: expiry \xc2\xb7 "
                   "d: remove \xc2\xb7 c: check \xc2\xb7 m: models \xc2\xb7 esc: close";
    a->au.confirm[0] = '\0';
    a->au.on = 1;
    au_build(a);
    (void)key_model_provider(a->model, mprov, sizeof mprov, &m);
    for (size_t i = 0; i < a->au.l.n; i++) { /* the model's key, or the first refused one */
        if (strcmp(a->au.l.s[i].group, mprov) == 0 && strstr(a->au.l.s[i].name, "this model")) {
            (void)snprintf(a->au.p.sel, sizeof a->au.p.sel, "%s", a->au.l.s[i].id);
        }
    }
    if (note) {
        (void)snprintf(a->au.p.note, sizeof a->au.p.note, "%s", note);
    }
    (void)keychk_start(a, refresh, 12000);
}

static void au_note(app *a, int err, const char *fmt, const char *x, const char *y) {
    (void)snprintf(a->au.p.note, sizeof a->au.p.note, fmt, x, y);
    a->au.p.note_err = err;
}

/* Enter: what the selected row needs. */
static void au_fix(app *a) {
    const tui_setting *row = tui_settings_get(&a->au.l, a->au.p.sel);
    char provider[PIC_CRED_PROVIDER_CAP], id[200];
    const char *label;
    if (!row) {
        return;
    }
    (void)snprintf(id, sizeof id, "%s", row->id);
    if (strcmp(id, "+") == 0) {
        au_close(a);
        login_picker(a);
        return;
    }
    label = strchr(id, ' ');
    (void)snprintf(provider, sizeof provider, "%.*s", label ? (int)(label - id) : (int)strlen(id), id);
    if (!label) { /* the model's provider, with no key */
        au_close(a);
        login(a, provider);
        return;
    }
    label++;
    if (!row->valid) {
        int again = strstr(row->applies, "sign in again") != NULL;
        au_close(a); /* row is gone with the list */
        if (again) {
            login_open(a, provider, "Signing in stores the subscription's tokens, sealed, in ~/.pic/pic.sqlite.");
        } else {
            login_begin(a, provider, 0);
            if (strcmp(label, "default") != 0 && strcmp(label, "env") != 0 && strcmp(label, "file") != 0) {
                (void)snprintf(a->lg_label, sizeof a->lg_label, "%s", label); /* stored again under its label */
            }
        }
        return;
    }
    if (strstr(row->name, "*")) {
        au_note(a, 0, "\"%s\" is already the key %s's requests use.", label, provider);
        return;
    }
    key_chosen(a, id);
    au_build(a);
    au_note(a, 0, "%s's requests use \"%s\" from the next one.", provider, label);
}

/* d, then y: removes the selected stored key or sign-in. */
static void au_remove(app *a, int confirmed) {
    const tui_setting *row = tui_settings_get(&a->au.l, a->au.p.sel);
    char provider[PIC_CRED_PROVIDER_CAP], name[PIC_CRED_NAME_CAP];
    const char *label = row ? strchr(row->id, ' ') : NULL;
    if (!label) {
        au_note(a, 0, "%s%sChoose a key to remove.", "", "");
        return;
    }
    (void)snprintf(provider, sizeof provider, "%.*s", (int)(label - row->id), row->id);
    label++;
    if (strcmp(label, "env") == 0 || strcmp(label, "file") == 0) {
        au_note(a, 0, "\"%s\" is not stored by pic: %s", label,
                strcmp(label, "env") == 0 ? "unset the variable in the shell that starts pic." : "remove it from models.json.");
        return;
    }
    if (!confirmed) {
        (void)snprintf(a->au.confirm, sizeof a->au.confirm, "%s", row->id);
        au_note(a, 0, "Remove %s's \"%s\"? y: remove \xc2\xb7 any other key: keep", provider, label);
        return;
    }
    (void)snprintf(name, sizeof name, strcmp(label, "default") == 0 ? "%s" : "%s:%s", provider, label);
    switch (pic_cred_logout(name)) {
    case 1:
        au_note(a, 0, "Removed %s's \"%s\".", provider, label);
        break;
    case 0:
        au_note(a, 0, "%s's \"%s\" was already gone.", provider, label);
        break;
    default:
        au_note(a, 1, "%s%scould not write ~/.pic/pic.sqlite", "", "");
    }
    a->key_seg_at = 0;
    au_build(a);
}

typedef struct {
    const char *label;
    char name[PIC_CRED_NAME_CAP];
} entry_name_find;

static int entry_name_of(void *ctx, const pic_cred_entry *e) {
    entry_name_find *f = ctx;
    if (strcmp(e->label, f->label) == 0) {
        (void)snprintf(f->name, sizeof f->name, "%s", e->name);
        return 1;
    }
    return 0;
}

/* b's line: the pattern typed so far. */
static void au_bind_note(app *a) {
    const char *label = strchr(a->au.bind, ' ');
    char note[sizeof a->au.p.note];
    if (a->au.mode == 'e') {
        (void)snprintf(note, sizeof note, "\"%s\" expires: %s_   a date (2027-01-31), 30d or never \xc2\xb7 enter: save \xc2\xb7 esc: cancel",
                       label ? label + 1 : "", a->au.text);
    } else {
        (void)snprintf(note, sizeof note, "Models for \"%s\": %s_   enter: save (a rule it has: remove) \xc2\xb7 esc: cancel",
                       label ? label + 1 : "", a->au.text);
    }
    (void)snprintf(a->au.p.note, sizeof a->au.p.note, "%s", note);
    a->au.p.note_err = 0;
}

/* Enter on b's line: the rule saved, or removed when the key has that rule already. */
static void au_bind_save(app *a) {
    char provider[PIC_CRED_PROVIDER_CAP], label[PIC_CRED_LABEL_CAP], err[300];
    const char *sp = strchr(a->au.bind, ' ');
    int has = 0, rc;
    pic_model m;
    (void)snprintf(provider, sizeof provider, "%.*s", sp ? (int)(sp - a->au.bind) : 0, a->au.bind);
    (void)snprintf(label, sizeof label, "%s", sp ? sp + 1 : "");
    a->au.bind[0] = '\0';
    for (int i = 0; i < a->au.nrules; i++) {
        has |= strcmp(a->au.rules[i].pattern, a->au.text) == 0 && strcmp(a->au.rules[i].label, label) == 0;
    }
    if (key_provider_model(provider, &m) != 0) {
        return;
    }
    rc = pic_cred_rule_set(provider, a->au.text, has ? NULL : label, m.key_env, m.key_literal, err, sizeof err);
    au_build(a);
    a->key_seg_at = 0;
    if (rc < 0) {
        au_note(a, 1, "%s%s", err, "");
    } else if (has) {
        au_note(a, 0, "Removed the rule for %s.%s", a->au.text, "");
    } else {
        au_note(a, 0, "%s uses \"%s\" from the next request.", a->au.text, label);
    }
}

/* Enter on e's line: the expiry recorded for the row's key. */
static void au_expiry_save(app *a) {
    char provider[PIC_CRED_PROVIDER_CAP], label[PIC_CRED_LABEL_CAP];
    const char *sp = strchr(a->au.bind, ' ');
    const tui_setting *row = tui_settings_get(&a->au.l, a->au.bind);
    pic_model m;
    entry_name_find f;
    long long ms = 0;
    (void)snprintf(provider, sizeof provider, "%.*s", sp ? (int)(sp - a->au.bind) : 0, a->au.bind);
    (void)snprintf(label, sizeof label, "%s", sp ? sp + 1 : "");
    a->au.bind[0] = '\0';
    (void)row;
    memset(&f, 0, sizeof f);
    f.label = label;
    if (key_provider_model(provider, &m) != 0 ||
        pic_cred_expiry_parse(a->au.text, key_wall_ms(), &ms) != 0) {
        au_note(a, 1, "%s%snot saved: a date (2027-01-31), a number of days (30d) or never", "", "");
        return;
    }
    (void)pic_cred_entries(provider, m.key_env, m.key_literal, entry_name_of, &f);
    if (!f.name[0] || pic_cred_expiry_set(f.name, ms, "recorded") != 0) {
        au_note(a, 1, "%s%snot saved: pic could not write ~/.pic/pic.sqlite", "", "");
        return;
    }
    a->key_seg_at = 0;
    au_build(a);
    au_note(a, 0, ms ? "The expiry of \"%s\" is recorded%s." : "No expiry is recorded for \"%s\"%s.", label, "");
}

static void au_bind_key(app *a, const tui_key *k) {
    size_t n = strlen(a->au.text);
    if (k->kind == TUI_KEY_ESC || k->kind == TUI_KEY_CTRL_C) {
        a->au.bind[0] = '\0';
        a->au.p.note[0] = '\0';
        return;
    }
    if (k->kind == TUI_KEY_ENTER) {
        if (a->au.mode == 'e') {
            au_expiry_save(a);
        } else {
            au_bind_save(a);
        }
        return;
    }
    if (k->kind == TUI_KEY_BACKSPACE && n > 0) {
        a->au.text[n - 1] = '\0';
    } else if (k->kind == TUI_KEY_CHAR && n + strlen(k->text) < sizeof a->au.text && (unsigned char)k->text[0] > ' ') {
        (void)snprintf(a->au.text + n, sizeof a->au.text - n, "%s", k->text);
    }
    au_bind_note(a);
}

/* Every key while /auth is open: none reaches the editor or the running request. */
static void au_key(app *a, const tui_key *k) {
    tui_panel_act act;
    char c = k->kind == TUI_KEY_CHAR && k->text[1] == '\0' ? k->text[0] : 0;
    a->esc_at = 0;
    a->ctrl_c_armed = 0;
    if (k->kind == TUI_KEY_MOUSE) {
        int line, col, hit = tui_render_hit(a->r, k->mx, k->my, &line, &col);
        if (hit == TUI_HIT_VIEW) {
            return;
        }
        if (k->mouse == TUI_MOUSE_WHEEL) {
            tui_key step = {.kind = k->button < 0 ? TUI_KEY_UP : TUI_KEY_DOWN};
            (void)tui_panel_key(&a->au.p, &a->au.l, &step, &act);
        } else if (k->mouse == TUI_MOUSE_PRESS && k->button == 0 && line >= 0) {
            (void)tui_panel_click(&a->au.p, &a->au.l, (size_t)line);
        }
        return;
    }
    if (a->au.bind[0]) { /* b: typing a pattern */
        au_bind_key(a, k);
        return;
    }
    if (a->au.confirm[0]) { /* d asked: y removes, anything else keeps */
        int yes = c == 'y' && strcmp(a->au.confirm, a->au.p.sel) == 0;
        a->au.confirm[0] = '\0';
        a->au.p.note[0] = '\0';
        if (yes) {
            au_remove(a, 1);
        }
        return;
    }
    a->au.p.note[0] = '\0';
    switch (k->kind) {
    case TUI_KEY_UP:
    case TUI_KEY_DOWN:
    case TUI_KEY_PAGEUP:
    case TUI_KEY_PAGEDOWN:
    case TUI_KEY_HOME:
    case TUI_KEY_END:
    case TUI_KEY_CTRL_HOME:
    case TUI_KEY_CTRL_END: (void)tui_panel_key(&a->au.p, &a->au.l, k, &act); return;
    case TUI_KEY_ESC:
    case TUI_KEY_CTRL_C: au_close(a); return;
    case TUI_KEY_ENTER: au_fix(a); return;
    default: break;
    }
    if (c == 'a') {
        au_close(a);
        login_picker(a);
    } else if (c == 'd') {
        au_remove(a, 0);
    } else if (c == 'c') {
        const char *check[] = {"auth", "status", "--check", "--refresh", NULL};
        (void)keychk_start(a, check, 12000);
        au_note(a, 0, "%s%sChecking every key; rows change as providers answer.", "", "");
    } else if (c == 'm') {
        au_close(a);
        open_models(a, NULL);
    } else if (c == 'b') {
        const tui_setting *row = tui_settings_get(&a->au.l, a->au.p.sel);
        const char *sp = row ? strchr(row->id, ' ') : NULL;
        if (!sp) {
            au_note(a, 0, "%s%sChoose a key first: b gives it a family of models.", "", "");
        } else {
            (void)snprintf(a->au.bind, sizeof a->au.bind, "%s", row->id);
            (void)snprintf(a->au.text, sizeof a->au.text, "%.*s/", (int)(sp - row->id), row->id);
            a->au.mode = 'b';
            au_bind_note(a);
        }
    } else if (c == 'e') {
        const tui_setting *row = tui_settings_get(&a->au.l, a->au.p.sel);
        if (!row || !strchr(row->id, ' ')) {
            au_note(a, 0, "%s%sChoose a key first: e records when it expires.", "", "");
        } else {
            (void)snprintf(a->au.bind, sizeof a->au.bind, "%s", row->id);
            a->au.text[0] = '\0';
            a->au.mode = 'e';
            au_bind_note(a);
        }
    }
}

/* Each turn of the loop: the open list is read again now and then, as checks answer. */
static void au_tick(app *a) {
    if (a->au.on && now_ms() - a->au.at >= 1000) {
        au_build(a);
    }
}

/* ---- /mcp: the MCP servers, in the settings panel's frame -------------------------------------
 * One row a server, those that need attention first, then the connected ones, then the ones turned
 * off, each with its tool count and MCP revision or its error, and the row's keys; and a row to add
 * one. Every answer is an RPC command (get_mcp_servers and the rest), so another client can show the
 * same. Opening it lists every server again in a `pic mcp list` child; the rows fill in as it goes. */

static void mc_note(app *a, int err, const char *fmt, const char *x, const char *y) {
    (void)snprintf(a->mc.p.note, sizeof a->mc.p.note, fmt, x, y);
    a->mc.p.note_err = err;
}

/* The rows again from get_mcp_servers; the selected row stays. */
static void mc_build(app *a) {
    char *data = cl_ask("get_mcp_servers", "", NULL, 0);
    sqlite3_stmt *q = NULL;
    size_t cap = 0;
    int servers = 0, tools = 0, bad = 0;
    tui_settings_free(&a->mc.l);
    if (data && cl_db && sqlite3_prepare_v2(cl_db,
                                            "SELECT json_extract(value, '$.name'), json_extract(value, '$.source'),"
                                            " json_extract(value, '$.transport'),"
                                            " coalesce(json_extract(value, '$.url'), json_extract(value, '$.command'), ''),"
                                            " json_extract(value, '$.enabled'), json_extract(value, '$.error'),"
                                            " coalesce(json_extract(value, '$.era'), ''), json_array_length(value, '$.tools'),"
                                            " json_extract(value, '$.description')"
                                            " FROM json_each(?1, '$.servers')"
                                            " ORDER BY CASE WHEN json_extract(value, '$.enabled') AND json_extract(value, '$.error')"
                                            " IS NOT NULL THEN 0 WHEN json_extract(value, '$.enabled') THEN 1 ELSE 2 END,"
                                            " json_extract(value, '$.name')",
                                            -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, data, -1, SQLITE_STATIC);
        while (sqlite3_step(q) == SQLITE_ROW) {
            const char *name = (const char *)sqlite3_column_text(q, 0), *source = (const char *)sqlite3_column_text(q, 1),
                       *where = (const char *)sqlite3_column_text(q, 3), *error = (const char *)sqlite3_column_text(q, 5),
                       *era = (const char *)sqlite3_column_text(q, 6), *desc = (const char *)sqlite3_column_text(q, 8);
            int on = sqlite3_column_int(q, 4), n = sqlite3_column_int(q, 7), project = source && strcmp(source, "user") != 0;
            char buf[700];
            tui_setting *row;
            if (!name) {
                continue;
            }
            if (a->mc.l.n == cap) {
                size_t more = cap ? 2 * cap : 8;
                tui_setting *grown = realloc(a->mc.l.s, more * sizeof *grown);
                if (!grown) {
                    break;
                }
                a->mc.l.s = grown;
                cap = more;
            }
            row = &a->mc.l.s[a->mc.l.n++];
            memset(row, 0, sizeof *row);
            row->id = strdup(name);
            row->key = strdup("");
            row->kind = strdup("info");
            row->def = strdup("");
            row->def_label = strdup("");
            row->group = strdup(on && error ? "Needs attention" : on ? "Servers" : "Turned off");
            (void)snprintf(buf, sizeof buf, "%s%s", name, project ? "  (project)" : "");
            row->name = strdup(buf);
            if (!on) {
                (void)snprintf(buf, sizeof buf, "off \xc2\xb7 %d tool%s", n, n == 1 ? "" : "s");
            } else if (error) {
                (void)snprintf(buf, sizeof buf, "! not connected \xc2\xb7 %d tool%s saved", n, n == 1 ? "" : "s");
            } else {
                (void)snprintf(buf, sizeof buf, "%d tool%s \xc2\xb7 MCP %s", n, n == 1 ? "" : "s", era[0] ? era : "?");
            }
            row->value = strdup(buf);
            row->valid = !(on && error);
            (void)snprintf(buf, sizeof buf, "%s%s%s%s%s", where, error && on ? ": " : desc ? ": " : "",
                           error && on ? error : desc ? desc : "", project ? " From " : "", project ? source : "");
            row->description = strdup(buf);
            row->applies = strdup(project ? "enter: its tools \xc2\xb7 r: reconnect (the project's file decides the rest)"
                                          : on ? "enter: its tools \xc2\xb7 r: reconnect \xc2\xb7 e: turn off \xc2\xb7 d: remove"
                                               : "e: turn on \xc2\xb7 d: remove");
            servers++;
            tools += on ? n : 0;
            bad += on && error;
        }
    }
    sqlite3_finalize(q);
    free(data);
    if (a->mc.l.n == cap) {
        tui_setting *grown = realloc(a->mc.l.s, (cap + 1) * sizeof *grown);
        if (grown) {
            a->mc.l.s = grown;
            cap++;
        }
    }
    if (a->mc.l.n < cap) {
        tui_setting *row = &a->mc.l.s[a->mc.l.n++];
        memset(row, 0, sizeof *row);
        row->id = strdup("+");
        row->key = strdup("");
        row->kind = strdup("info");
        row->def = strdup("");
        row->def_label = strdup("");
        row->group = strdup("");
        row->name = strdup("+ add a server");
        row->value = strdup("");
        row->valid = 1;
        row->description = strdup("A URL, a command or an mcpServers snippet, as pic mcp add takes them.");
        row->applies = strdup("enter: type /mcp add ...");
    }
    {
        char bad_s[48] = "";
        if (bad) {
            (void)snprintf(bad_s, sizeof bad_s, " \xc2\xb7 %d not connected", bad);
        }
        (void)snprintf(a->mc.head, sizeof a->mc.head, "%d server%s \xc2\xb7 %d tool%s%s%s", servers,
                       servers == 1 ? "" : "s", tools, tools == 1 ? "" : "s", bad_s,
                       a->mc.busy ? " \xc2\xb7 connecting\xe2\x80\xa6" : "");
    }
    a->mc.at = now_ms();
}

/* Lists every server again in the background: a pic mcp list child. */
static void mc_refresh(app *a) {
    const char *args[] = {"mcp", "list", NULL};
    if (a->mc.busy) {
        return;
    }
    if (spawn(a, &a->mc.c, args) == 0) {
        a->mc.busy = 1;
    }
    mc_build(a);
}

static void mc_close(app *a) {
    a->mc.on = 0;
    a->mc.confirm[0] = '\0';
    tui_settings_free(&a->mc.l);
}

static void mc_open(app *a) {
    memset(&a->mc.p, 0, sizeof a->mc.p);
    a->mc.p.title = "MCP servers";
    a->mc.p.head = a->mc.head;
    a->mc.p.hint = "enter: tools \xc2\xb7 r: reconnect \xc2\xb7 e: on/off \xc2\xb7 d: remove \xc2\xb7 a: add";
    a->mc.confirm[0] = '\0';
    a->mc.on = 1;
    mc_refresh(a);
}

/* The words of ARG as a shell splits them (quotes and backslashes), as a JSON array, malloc'd. */
static char *mc_split(const char *arg) {
    sqlite3_str *t = sqlite3_str_new(NULL), *w = NULL;
    char *res, *out;
    int any = 0;
    sqlite3_str_appendall(t, "[");
    for (const char *p = arg;;) {
        while (*p == ' ' || *p == '\t') {
            p++;
        }
        if (!*p) {
            break;
        }
        w = sqlite3_str_new(NULL);
        while (*p && *p != ' ' && *p != '\t') {
            if (*p == '\'') {
                for (p++; *p && *p != '\''; p++) {
                    sqlite3_str_appendchar(w, 1, *p);
                }
                p += *p == '\'';
            } else if (*p == '"') {
                for (p++; *p && *p != '"'; p++) {
                    if (*p == '\\' && (p[1] == '"' || p[1] == '\\')) {
                        p++;
                    }
                    sqlite3_str_appendchar(w, 1, *p);
                }
                p += *p == '"';
            } else {
                if (*p == '\\' && p[1]) {
                    p++;
                }
                sqlite3_str_appendchar(w, 1, *p++);
            }
        }
        res = sqlite3_str_finish(w);
        if (any) {
            sqlite3_str_appendchar(t, 1, ',');
        }
        cl_quote_to(t, res ? res : "");
        sqlite3_free(res);
        any = 1;
    }
    sqlite3_str_appendall(t, "]");
    res = sqlite3_str_finish(t);
    out = res ? strdup(res) : NULL;
    sqlite3_free(res);
    return out;
}

/* /mcp add ARGS: saved and listed, as pic mcp add does it (this waits for the server). */
static void mc_add(app *a, const char *args) {
    char err[PIC_ERR_CAP] = "", *words = mc_split(args), *members = NULL, *data = NULL, *say = NULL;
    size_t n;
    if (!words) {
        return;
    }
    n = strlen(words) + 16;
    if ((members = malloc(n))) {
        (void)snprintf(members, n, "\"args\":%s", words);
        data = cl_ask("add_mcp_server", members, err, sizeof err);
    }
    if (!data) {
        notice(a, RED, "pic: %s", err[0] ? err : "the server was not added");
    } else if ((say = cl_sql("SELECT group_concat(CASE WHEN json_extract(value, '$.error') IS NULL THEN 'Added ' ||"
                             " json_extract(value, '$.name') || ': ' || json_extract(value, '$.count') || ' tools, MCP ' ||"
                             " json_extract(value, '$.era') ELSE 'Added ' || json_extract(value, '$.name') ||"
                             " ', but it could not be reached: ' || json_extract(value, '$.error') END, '; ')"
                             " FROM json_each(?1, '$.servers')",
                             data, NULL))) {
        notice(a, strstr(say, "could not be reached") ? RED : DIM, "%s. Its tools reach requests from the next one.", say);
    }
    free(say);
    free(data);
    free(members);
    free(words);
    if (a->mc.on) {
        mc_build(a);
    }
}

static void mc_command(app *a, const char *arg) {
    if (strncmp(arg, "add", 3) == 0 && (arg[3] == ' ' || arg[3] == '\0')) {
        if (!arg[3] || !arg[4 + strspn(arg + 4, " ")]) {
            notice(a, RED, "/mcp add takes pic mcp add's arguments: NAME URL, or NAME -- COMMAND [ARGS...]");
            return;
        }
        mc_add(a, arg + 4);
        return;
    }
    if (*arg) {
        notice(a, RED, "/mcp opens the MCP servers; /mcp add NAME URL adds one");
        return;
    }
    mc_open(a);
}

/* d, then y: forgets the selected server. */
static void mc_remove(app *a, int confirmed) {
    const tui_setting *row = tui_settings_get(&a->mc.l, a->mc.p.sel);
    char err[PIC_ERR_CAP] = "", id[200], *data;
    if (!row || strcmp(row->id, "+") == 0) {
        mc_note(a, 0, "%s%sChoose a server to remove.", "", "");
        return;
    }
    (void)snprintf(id, sizeof id, "%s", row->id);
    if (!confirmed) {
        (void)snprintf(a->mc.confirm, sizeof a->mc.confirm, "%s", id);
        mc_note(a, 0, "Remove %s and its sealed values? y: remove \xc2\xb7 any other key: keep%s", id, "");
        return;
    }
    {
        char *m = cl_member("name", id);
        data = m ? cl_ask("remove_mcp_server", m, err, sizeof err) : NULL;
        free(m);
    }
    if (!data) {
        mc_note(a, 1, "%s%s", err[0] ? err : "pic could not answer", "");
    } else {
        mc_note(a, 0, "Removed %s.%s", id, "");
    }
    free(data);
    mc_build(a);
}

/* e: turns the selected server on or off. */
static void mc_toggle(app *a) {
    const tui_setting *row = tui_settings_get(&a->mc.l, a->mc.p.sel);
    char err[PIC_ERR_CAP] = "", members[300], *data;
    sqlite3_str *t;
    char *m;
    int off;
    if (!row || strcmp(row->id, "+") == 0) {
        return;
    }
    off = strcmp(row->group, "Turned off") != 0;
    t = sqlite3_str_new(NULL);
    sqlite3_str_appendall(t, "\"name\":");
    cl_quote_to(t, row->id);
    sqlite3_str_appendf(t, ",\"enabled\":%s", off ? "false" : "true");
    m = sqlite3_str_finish(t);
    (void)snprintf(members, sizeof members, "%s", m ? m : "");
    sqlite3_free(m);
    if ((data = cl_ask("set_mcp_server_enabled", members, err, sizeof err))) {
        mc_note(a, 0, off ? "%s is off: its tools are not offered from the next request.%s"
                          : "%s is on: its tools are offered from the next request.%s",
                row->id, "");
    } else {
        mc_note(a, 1, "%s%s", err, "");
    }
    free(data);
    mc_build(a);
}

/* Enter: the selected server's tools, or the add step. */
static void mc_enter(app *a) {
    const tui_setting *row = tui_settings_get(&a->mc.l, a->mc.p.sel);
    char *data, *names = NULL;
    if (!row) {
        return;
    }
    if (strcmp(row->id, "+") == 0) {
        mc_close(a);
        tui_editor_set(a->ed, "/mcp add ");
        return;
    }
    if ((data = cl_ask("get_mcp_servers", "", NULL, 0))) {
        names = cl_sql("SELECT group_concat(json_extract(t.value, '$.tool') ||"
                       " CASE WHEN json_extract(t.value, '$.readOnly') THEN ' (read-only)' ELSE '' END, ', ')"
                       " FROM json_each(?1, '$.servers') s, json_each(s.value, '$.tools') t"
                       " WHERE json_extract(s.value, '$.name') = ?2",
                       data, row->id);
    }
    mc_note(a, 0, "%s: %s", row->id, names ? names : "no tools saved; r lists them");
    free(names);
    free(data);
}

/* Every key while /mcp is open: none reaches the editor or the running request. */
static void mc_key(app *a, const tui_key *k) {
    tui_panel_act act;
    char c = k->kind == TUI_KEY_CHAR && k->text[1] == '\0' ? k->text[0] : 0;
    a->esc_at = 0;
    a->ctrl_c_armed = 0;
    if (k->kind == TUI_KEY_MOUSE) {
        int line, col, hit = tui_render_hit(a->r, k->mx, k->my, &line, &col);
        if (hit == TUI_HIT_VIEW) {
            return;
        }
        if (k->mouse == TUI_MOUSE_WHEEL) {
            tui_key step = {.kind = k->button < 0 ? TUI_KEY_UP : TUI_KEY_DOWN};
            (void)tui_panel_key(&a->mc.p, &a->mc.l, &step, &act);
        } else if (k->mouse == TUI_MOUSE_PRESS && k->button == 0 && line >= 0) {
            (void)tui_panel_click(&a->mc.p, &a->mc.l, (size_t)line);
        }
        return;
    }
    if (a->mc.confirm[0]) { /* d asked: y removes, anything else keeps */
        int yes = c == 'y' && strcmp(a->mc.confirm, a->mc.p.sel) == 0;
        a->mc.confirm[0] = '\0';
        a->mc.p.note[0] = '\0';
        if (yes) {
            mc_remove(a, 1);
        }
        return;
    }
    a->mc.p.note[0] = '\0';
    switch (k->kind) {
    case TUI_KEY_UP:
    case TUI_KEY_DOWN:
    case TUI_KEY_PAGEUP:
    case TUI_KEY_PAGEDOWN:
    case TUI_KEY_HOME:
    case TUI_KEY_END:
    case TUI_KEY_CTRL_HOME:
    case TUI_KEY_CTRL_END: (void)tui_panel_key(&a->mc.p, &a->mc.l, k, &act); return;
    case TUI_KEY_ESC:
    case TUI_KEY_CTRL_C: mc_close(a); return;
    case TUI_KEY_ENTER: mc_enter(a); return;
    default: break;
    }
    if (c == 'a') {
        mc_close(a);
        tui_editor_set(a->ed, "/mcp add ");
    } else if (c == 'd') {
        mc_remove(a, 0);
    } else if (c == 'e') {
        mc_toggle(a);
    } else if (c == 'r') {
        if (a->mc.busy) {
            mc_note(a, 0, "%s%sStill connecting; the rows change as servers answer.", "", "");
        } else {
            mc_refresh(a);
            mc_note(a, 0, "%s%sConnecting to every server; the rows change as they answer.", "", "");
        }
    }
}

/* Each turn of the loop: the listing child read and reaped, and the open list read again. */
static void mc_tick(app *a) {
    int status;
    if (a->mc.busy) {
        (void)drain(&a->mc.c);
        if (waitpid(a->mc.c.pid, &status, WNOHANG) == a->mc.c.pid) {
            (void)drain(&a->mc.c);
            if (a->mc.c.out >= 0) {
                close(a->mc.c.out);
            }
            if (a->mc.c.err >= 0) {
                close(a->mc.c.err);
            }
            free(a->mc.c.outbuf.buf);
            free(a->mc.c.errbuf.buf);
            memset(&a->mc.c, 0, sizeof a->mc.c);
            a->mc.c.out = a->mc.c.err = -1;
            a->mc.busy = 0;
            if (a->mc.on) {
                mc_build(a);
            }
            return;
        }
    }
    if (a->mc.on && now_ms() - a->mc.at >= 1000) {
        mc_build(a);
    }
}

typedef struct {
    const char *skip;
    char best[PIC_CRED_LABEL_CAP];
    long long best_rank;
    long long now;
} kp_pick;

/* The key the prompt offers instead: another of the provider's, the one whose request was
 * answered last first, then one a check said valid, then one never checked; never one whose
 * last request failed (refused, no credit, limited still). The first in the store's order
 * wins a tie. */
static int kp_pick_entry(void *ctx, const pic_cred_entry *e) {
    kp_pick *k = ctx;
    pic_key_health h;
    long long rank;
    if (strcmp(e->label, k->skip) == 0) {
        return 0;
    }
    (void)pic_cred_health_of(e->name, &h);
    if (pic_cred_key_bad(&h, k->now)) {
        return 0;
    }
    rank = h.answered_ms > 0 ? 2 + h.answered_ms : h.state == PIC_KEY_OK ? 1 : 0;
    if (!k->best[0] || rank > k->best_rank) {
        (void)snprintf(k->best, sizeof k->best, "%s", e->label);
        k->best_rank = rank;
    }
    return 0;
}

/* The swap prompt, in place: the request stays unfinished until a choice. */
static void kp_show(app *a) {
    pic_model m;
    pic_key_health h;
    kp_pick pick;
    char head[320], line[400], cost[160] = "";
    const char *offers;
    long long now = key_wall_ms();
    a->kp.pending = 0;
    a->kp.on = 1;
    (void)snprintf(a->unfinished, sizeof a->unfinished, "%s", a->kp.request);
    (void)snprintf(a->unfinished_model, sizeof a->unfinished_model, "%s", a->model);
    memset(&pick, 0, sizeof pick);
    pick.skip = a->kp.label;
    pick.now = now;
    if (key_provider_model(a->kp.provider, &m) == 0) {
        (void)pic_cred_entries(a->kp.provider, m.key_env, m.key_literal, kp_pick_entry, &pick);
        if (a->context > 0) { /* another key may not share the prompt cache: the conversation goes again, uncached */
            char toks[24];
            tui_fmt_tokens(a->context, toks, sizeof toks);
            (void)snprintf(cost, sizeof cost, "  (re-sends %s tokens uncached, about $%.2f)", toks,
                           (double)a->context * m.price.base.input / 1e6);
        }
    }
    (void)snprintf(a->kp.other, sizeof a->kp.other, "%s", pick.best);
    offers = pic_cred_key_offers((pic_key_state)a->kp.state, pick.best[0] != '\0');
    (void)snprintf(a->kp.offers, sizeof a->kp.offers, "%s", offers);
    memset(&h, 0, sizeof h);
    h.state = (pic_key_state)a->kp.state;
    h.status = a->kp.status;
    h.until_ms = a->kp.until;
    pic_cred_key_headline(a->kp.provider, a->kp.label, &h, now, head, sizeof head);
    notice(a, YELLOW, "%s", head);
    if (a->kp.state == PIC_KEY_CREDIT) { /* one choice a line, with the cost */
        for (const char *o = offers; *o; o++) {
            if (*o == 's') {
                notice(a, YELLOW, "  s  retry with \"%s\"%s", pick.best, cost);
            } else if (*o == 'm') {
                notice(a, YELLOW, "  m  another model");
            }
        }
        notice(a, YELLOW, "  esc  stop");
    } else {
        size_t n = 0;
        line[0] = '\0';
        for (const char *o = offers; *o; o++) {
            n += (size_t)snprintf(line + n, sizeof line - n, "%s",
                                  *o == 's'   ? (a->kp.state == PIC_KEY_INVALID ? "  s  use \"" : "  s  switch key")
                                  : *o == 'm' ? "  m  another model"
                                  : *o == 'w' ? "  w  wait and continue"
                                              : "  l  log in again");
            if (*o == 's' && a->kp.state == PIC_KEY_INVALID) {
                n += (size_t)snprintf(line + n, sizeof line - n, "%s\"", pick.best);
            }
            if (n >= sizeof line) {
                n = sizeof line - 1;
            }
            n += (size_t)snprintf(line + n, sizeof line - n, " ");
        }
        (void)snprintf(line + n, sizeof line - n, "  esc  stop");
        notice(a, YELLOW, "%s", line);
        if (!strchr(offers, 'm')) {
            notice(a, DIM, "  or /model to pick another model: your message goes back in the editor for it");
        }
        if (strchr(offers, 's') && cost[0]) {
            notice(a, DIM, "  another key%s", cost);
        }
    }
    a->key_seg_at = 0;
}

/* A choice at the swap prompt. 1 when the key was one. */
static int kp_key(app *a, const tui_key *k) {
    char c = k->kind == TUI_KEY_CHAR && k->text[1] == '\0' ? k->text[0] : 0;
    if (k->kind == TUI_KEY_ESC) {
        a->kp.on = 0;
        a->kp.wait_until = 0;
        (void)drop_unfinished(a);
        return 1;
    }
    if (k->kind == TUI_KEY_ENTER) { /* the same key again */
        a->kp.on = 0;
        a->kp.wait_until = 0;
        resume_unfinished(a);
        return 1;
    }
    if (!c || !strchr(a->kp.offers, c) || a->kp.wait_until) {
        return 0;
    }
    if (c == 's') {
        pic_model m;
        char err[256];
        if (key_provider_model(a->kp.provider, &m) != 0 ||
            pic_cred_use(a->kp.provider, a->kp.other, m.key_env, m.key_literal, err, sizeof err) != 0) {
            notice(a, RED, "pic: %s", err);
            return 1;
        }
        key_run_replace(a, a->kp.provider, a->kp.other);
        notice(a, DIM, "Requests to %s use the key \"%s\" now.", a->kp.provider, a->kp.other);
        a->kp.on = 0;
        a->key_seg_at = 0;
        resume_unfinished(a);
    } else if (c == 'm') {
        a->kp.on = 0;
        a->kp_model = 1;
        notice(a, DIM, "Choose a model: your message goes back in the editor for it.");
        open_models(a, NULL);
    } else if (c == 'w') {
        char until[48];
        a->kp.wait_until = a->kp.until > key_wall_ms() ? a->kp.until : key_wall_ms();
        pic_cred_key_until(a->kp.wait_until, key_wall_ms(), until, sizeof until);
        notice(a, DIM, "Waiting until %s, then the request goes on; Esc stops it.", until);
    } else if (c == 'l') {
        char provider[PIC_CRED_PROVIDER_CAP];
        (void)snprintf(provider, sizeof provider, "%s", a->kp.provider);
        a->kp.on = 0;
        notice(a, DIM, "Once you have logged in, Enter retries the request; Esc drops it.");
        if (strcmp(a->kp.label, "env") != 0 && strcmp(a->kp.label, "file") != 0 && strcmp(a->kp.label, "default") != 0) {
            login_begin(a, provider, 0); /* a named key: stored again under its label */
            (void)snprintf(a->lg_label, sizeof a->lg_label, "%s", a->kp.label);
        } else if (pic_cred_oauth_label(provider)) {
            login_open(a, provider, "Signing in stores the subscription's tokens, sealed, in ~/.pic/pic.sqlite.");
        } else {
            login_begin(a, provider, 0);
        }
    }
    return 1;
}

/* w: the limit has lifted, so the request goes on. */
static void kp_tick(app *a) {
    if (a->kp.on && a->kp.wait_until && key_wall_ms() >= a->kp.wait_until && !a->working) {
        a->kp.on = 0;
        a->kp.wait_until = 0;
        resume_unfinished(a);
    }
}

/* The method for PROVIDER: its subscription sign-in, when it has one, or an API key. */
static void login_open(app *a, const char *provider, const char *why) {
    const char *label = pic_cred_oauth_label(provider);
    char title[160];
    (void)snprintf(title, sizeof title, "Log in to %s  (up/down \xc2\xb7 enter: choose \xc2\xb7 esc)", provider);
    ov_open(a, OV_LOGIN, title, why);
    if (label) {
        ov_add(a, label, "oauth", 0);
    }
    ov_add(a, "Paste an API key", "api_key", 0);
    ov_refilter(a);
    a->ov_data = strdup(provider);
}

static void login_drop_pending(app *a) {
    for (size_t i = 0; i < a->lg_pending_n; i++) {
        free(a->lg_pending_img[i].data);
    }
    free(a->lg_pending_img);
    free(a->lg_pending);
    a->lg_pending = NULL;
    a->lg_pending_img = NULL;
    a->lg_pending_n = 0;
    a->lg_request = 0;
}

static void login_end(app *a) {
    login_drop_pending(a);
    pic_cred_wipe(a->lg_field, sizeof a->lg_field);
    pic_cred_wipe(a->lg_key, sizeof a->lg_key);
    pic_cred_wipe(a->lg_pass, sizeof a->lg_pass);
    a->lg_len = 0;
    a->lg = LG_NONE;
    a->lg_url[0] = a->lg_code[0] = a->lg_msg[0] = a->lg_err[0] = '\0';
    a->lg_label[0] = '\0';
    a->lg_cancel_ms = 0;
}

/* The passphrase typed into the field, as the platform's secret source for
 * one unlock (the host's would ask on the terminal under the interface). */
static const char *lg_secret_text;
static const pic_platform *lg_was;

static int login_secret(const pic_secret_ask *ask, unsigned char *buf, size_t cap, size_t *len, int *how, char *err,
                        size_t errcap) {
    size_t n = lg_secret_text ? strlen(lg_secret_text) : 0;
    if (strcmp(ask->source, "passphrase") != 0) { /* a kept key: the platform's own source */
        return lg_was->secret_key(ask, buf, cap, len, how, err, errcap);
    }
    if (n == 0 || n > cap) {
        (void)snprintf(err, errcap, "the passphrase is empty or too long");
        return -1;
    }
    memcpy(buf, lg_secret_text, n);
    *len = n;
    *how = PIC_SECRET_TYPED;
    return 0;
}

static int login_unlock(const char *pass, char *err, size_t errcap) {
    static pic_platform p;
    const pic_platform *was = pic_platform_get();
    int rc;
    p = *was;
    lg_was = was;
    p.secret_key = login_secret;
    lg_secret_text = pass;
    pic_platform_set(&p);
    rc = pic_cred_prepare(err, errcap);
    pic_platform_set(was);
    lg_secret_text = NULL;
    return rc;
}

static void login_save_key(app *a) {
    pic_model m;
    char err[256] = "";
    int ok = login_provider(a, a->lg_provider, &m) == 0,
        rc = ok ? pic_cred_login_as(a->lg_provider, a->lg_label[0] ? a->lg_label : NULL, a->lg_key, err, sizeof err) : -1;
    char provider[64];
    (void)snprintf(provider, sizeof provider, "%s", a->lg_provider);
    login_end(a);
    draw(a); /* the panel goes before the notice is added, so no frame repaints it */
    if (ok && rc != 0) {
        notice(a, RED, "pic: %s", err);
    } else if (ok && m.key_env[0] && getenv(m.key_env) && *getenv(m.key_env)) {
        notice(a, DIM, "Saved the API key for %s, sealed, in ~/.pic/pic.sqlite; %s is also set, and the stored key is used.",
               provider, m.key_env);
    } else if (ok) {
        notice(a, DIM, "Saved the API key for %s, sealed, in ~/.pic/pic.sqlite.", provider);
    }
}

static void login_start(app *a) {
    const char *args[] = {"auth", "login", a->lg_provider, "--pipe", NULL};
    if (spawn_in(a, &a->lg_child, args, 1) != 0) {
        notice(a, RED, "pic: could not start the sign-in");
        login_end(a);
        return;
    }
    a->lg = LG_WAIT;
    (void)snprintf(a->lg_msg, sizeof a->lg_msg, "Starting the sign-in\xe2\x80\xa6");
}

/* The store's passphrase when it is still locked (or new), then STEP. */
static void login_store_then(app *a, int key_step) {
    char err[256] = "";
    int st = pic_cred_state(), q = st == PIC_CRED_OPEN ? 0 : pic_cred_quiet(err, sizeof err);
    if (q < 0) {
        login_end(a);
        draw(a);
        notice(a, RED, "pic: %s", err);
        return;
    }
    if (q == 0) {
        if (key_step) {
            login_save_key(a);
        } else {
            login_start(a);
        }
        return;
    }
    a->lg = st == PIC_CRED_NEW ? LG_PASS_NEW : LG_PASS;
}

/* Starts METHOD (OAUTH: the sign-in, else a key) for PROVIDER. */
static void login_begin(app *a, const char *provider, int oauth) {
    pic_model m;
    if (login_provider(a, provider, &m) != 0) {
        return;
    }
    login_end(a);
    (void)snprintf(a->lg_provider, sizeof a->lg_provider, "%s", provider);
    a->lg_oauth = oauth;
    if (oauth) {
        login_store_then(a, 0);
    } else {
        a->lg = LG_KEY;
    }
}

static void login_hold(app *a, const char *provider, int after, const char *msg, const tui_attachment *images,
                       size_t nimages) {
    login_end(a);
    (void)snprintf(a->lg_provider, sizeof a->lg_provider, "%s", provider);
    a->lg_request = 1;
    a->lg_after = after;
    a->lg_pending = strdup(msg);
    if (nimages && (a->lg_pending_img = calloc(nimages, sizeof *a->lg_pending_img))) {
        for (size_t i = 0; i < nimages; i++) {
            if ((a->lg_pending_img[i].data = malloc(images[i].len ? images[i].len : 1))) {
                memcpy(a->lg_pending_img[i].data, images[i].data, images[i].len);
                a->lg_pending_img[i].len = images[i].len;
                a->lg_pending_n++;
            }
        }
    }
    a->lg = LG_PASS;
}

/* Esc or Ctrl-C: back to the editor. A running sign-in is asked to stop (it
 * closes its listener and exits); a stubborn one is killed after 3 s. */
static void login_cancel(app *a) {
    if (a->lg == LG_WAIT) {
        if (!a->lg_cancel_ms) {
            (void)kill(a->lg_child.pid, SIGTERM);
            a->lg_cancel_ms = now_ms();
            (void)snprintf(a->lg_msg, sizeof a->lg_msg, "Cancelling\xe2\x80\xa6");
        }
        return;
    }
    if (a->lg_request) { /* a held message goes back to the editor */
        if (a->lg_after == AFTER_ENDPOINT) {
            pic_cred_wipe(a->ep_key, sizeof a->ep_key);
        }
        if (a->lg_pending && a->lg_after == AFTER_SEND) {
            tui_editor_set(a->ed, a->lg_pending);
        }
        login_end(a);
        draw(a);
        notice(a, DIM, a->lg_after == AFTER_SEND ? "The store stays locked; the message is back in the editor."
                                                  : "The store stays locked.");
        return;
    }
    login_end(a);
    draw(a);
    notice(a, DIM, "Login cancelled.");
}

static void login_clear_field(app *a) {
    pic_cred_wipe(a->lg_field, sizeof a->lg_field);
    a->lg_len = 0;
}

static void login_unlocked(app *a);
static void login_wait_submit(app *a);

static void login_submit(app *a) {
    char err[512] = "";
    a->lg_field[a->lg_len] = '\0';
    a->lg_err[0] = '\0';
    switch (a->lg) {
    case LG_KEY:
        if (pic_cred_check("the key", a->lg_field, err, sizeof err) != 0) {
            (void)snprintf(a->lg_err, sizeof a->lg_err, "%s", err);
            return;
        }
        memcpy(a->lg_key, a->lg_field, a->lg_len + 1);
        login_clear_field(a);
        login_store_then(a, 1);
        return;
    case LG_PASS_NEW:
        if (!a->lg_len) {
            (void)snprintf(a->lg_err, sizeof a->lg_err, "the passphrase is empty");
            return;
        }
        memcpy(a->lg_pass, a->lg_field, a->lg_len + 1);
        login_clear_field(a);
        a->lg = LG_PASS_AGAIN;
        return;
    case LG_PASS_AGAIN:
        if (strcmp(a->lg_field, a->lg_pass) != 0) {
            (void)snprintf(a->lg_err, sizeof a->lg_err, "the two passphrases differ; type a new one");
            login_clear_field(a);
            pic_cred_wipe(a->lg_pass, sizeof a->lg_pass);
            a->lg = LG_PASS_NEW;
            return;
        }
        /* fall through - make the store with it */
    case LG_PASS:
        if (login_unlock(a->lg_field, err, sizeof err) != 0) {
            (void)snprintf(a->lg_err, sizeof a->lg_err, "%s", err);
            login_clear_field(a);
            if (a->lg == LG_PASS_AGAIN) {
                a->lg = LG_PASS_NEW;
            }
            return;
        }
        login_clear_field(a);
        pic_cred_wipe(a->lg_pass, sizeof a->lg_pass);
        if (pic_cred_offer_due()) { /* once: stop asking for it? */
            a->lg = LG_OFFER;
            return;
        }
        login_unlocked(a);
        return;
    case LG_OFFER:
        return;
    case LG_WAIT: /* a pasted redirect, for the child to check */
        login_wait_submit(a);
        return;
    default:
        return;
    }
}

/* The store just opened: what waited for it goes on. */
static void login_unlocked(app *a) {
    if (a->lg_request) { /* the held request goes now */
        int after = a->lg_after;
        char *msg = a->lg_pending;
        tui_attachment *img = a->lg_pending_img;
        size_t n = a->lg_pending_n;
        a->lg_pending = NULL;
        a->lg_pending_img = NULL;
        a->lg_pending_n = 0;
        login_end(a);
        draw(a);
        if (after == AFTER_RESUME) {
            resume_unfinished(a);
        } else if (after == AFTER_RC) {
            rc_after_unlock(a);
        } else if (after == AFTER_COMPACT) {
            compact_start(a, msg ? msg : "");
        } else if (after == AFTER_ENDPOINT) {
            ep_save(a);
        } else if (msg) {
            start_request(a, msg, img, n);
        }
        for (size_t i = 0; i < n; i++) {
            free(img[i].data);
        }
        free(img);
        free(msg);
    } else if (a->lg_oauth) {
        login_start(a);
    } else {
        login_save_key(a);
    }
}

/* A pasted redirect, for the sign-in child to check. */
static void login_wait_submit(app *a) {
    if (a->lg_len && a->lg_child.in >= 0) {
        a->lg_field[a->lg_len++] = '\n';
        if (write(a->lg_child.in, a->lg_field, a->lg_len) == (ssize_t)a->lg_len) {
            (void)snprintf(a->lg_msg, sizeof a->lg_msg, "Checking the pasted address\xe2\x80\xa6");
        }
    }
    login_clear_field(a);
}

/* The answer to "Stop asking for this passphrase?": y moves the key off it; anything else is a
 * no, remembered. Then what waited for the store goes on. */
static void login_offer_answer(app *a, int yes) {
    char err[512] = "", source[32] = "";
    int skipped = 0, rc = 0;
    pic_cred_offer_answer(yes);
    if (yes) {
        rc = pic_cred_rekey(NULL, source, sizeof source, &skipped, err, sizeof err);
    }
    a->lg = LG_PASS;
    login_unlocked(a);
    if (yes && rc < 0) {
        notice(a, RED, "pic: the key stays behind the passphrase: %s", err);
    } else if (yes) {
        notice(a, DIM, "The credential store's key is now in %s; pic auth rekey passphrase goes back.",
               pic_host_where(source));
    }
}

static void login_type(app *a, const char *s, size_t n) {
    for (size_t i = 0; i < n && a->lg_len + 2 < sizeof a->lg_field; i++) {
        if ((unsigned char)s[i] >= 0x20 && s[i] != 0x7f) { /* a paste's newlines and controls are dropped */
            a->lg_field[a->lg_len++] = s[i];
        }
    }
    a->lg_err[0] = '\0';
}

static void login_key_in(app *a, const tui_key *k) {
    if (a->lg == LG_OFFER) {
        login_offer_answer(a, k->kind == TUI_KEY_CHAR && (k->text[0] == 'y' || k->text[0] == 'Y'));
        return;
    }
    switch (k->kind) {
    case TUI_KEY_ESC:
    case TUI_KEY_CTRL_C:
        login_cancel(a);
        break;
    case TUI_KEY_ENTER:
        login_submit(a);
        break;
    case TUI_KEY_BACKSPACE:
        while (a->lg_len > 0 && ((unsigned char)a->lg_field[a->lg_len - 1] & 0xC0) == 0x80) {
            a->lg_len--;
        }
        if (a->lg_len > 0) {
            a->lg_len--;
        }
        break;
    case TUI_KEY_CHAR:
        login_type(a, k->text, strlen(k->text));
        break;
    case TUI_KEY_PASTE:
        if (k->paste) {
            login_type(a, k->paste, k->paste_len);
        }
        break;
    default:
        break;
    }
}

/* The running sign-in's lines and, once it has ended, its result in place. */
static void login_pump(app *a) {
    app_child *c = &a->lg_child;
    int done = drain(c), status = 0;
    char *nl;
    while (c->outbuf.buf && (nl = memchr(c->outbuf.buf, '\n', c->outbuf.len))) {
        size_t used = (size_t)(nl - c->outbuf.buf) + 1;
        *nl = '\0';
        if (c->outbuf.buf[0] == '{') {
            char *type = jget(a, c->outbuf.buf, "$.type");
            if (type && strcmp(type, "auth_url") == 0) {
                char *url = jget(a, c->outbuf.buf, "$.url");
                (void)snprintf(a->lg_url, sizeof a->lg_url, "%s", url ? url : "");
                (void)snprintf(a->lg_msg, sizeof a->lg_msg, "Waiting for the browser\xe2\x80\xa6");
                free(url);
            } else if (type && strcmp(type, "device_code") == 0) {
                char *uri = jget(a, c->outbuf.buf, "$.uri"), *code = jget(a, c->outbuf.buf, "$.code");
                (void)snprintf(a->lg_url, sizeof a->lg_url, "%s", uri ? uri : "");
                (void)snprintf(a->lg_code, sizeof a->lg_code, "%s", code ? code : "");
                (void)snprintf(a->lg_msg, sizeof a->lg_msg, "Waiting for the code to be entered\xe2\x80\xa6");
                free(uri);
                free(code);
            } else if (type && strcmp(type, "progress") == 0) {
                char *m = jget(a, c->outbuf.buf, "$.message");
                (void)snprintf(a->lg_msg, sizeof a->lg_msg, "%s", m ? m : "");
                free(m);
            }
            free(type);
        }
        memmove(c->outbuf.buf, c->outbuf.buf + used, c->outbuf.len - used + 1);
        c->outbuf.len -= used;
    }
    if (a->lg_cancel_ms > 0 && now_ms() - a->lg_cancel_ms > 3000) {
        (void)kill(c->pid, SIGKILL);
        a->lg_cancel_ms = -1;
    }
    if (!done) {
        return;
    }
    while (waitpid(c->pid, &status, 0) < 0 && errno == EINTR) {
    }
    if (c->in >= 0) {
        close(c->in);
        c->in = -1;
    }
    a->lg = LG_NONE;
    draw(a); /* the panel goes before the notice is added, so no frame repaints it */
    if (a->lg_cancel_ms) {
        notice(a, DIM, "Sign-in cancelled.");
    } else if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
        notice(a, DIM, "Signed in to %s (%s), sealed in ~/.pic/pic.sqlite.", a->lg_provider,
               pic_cred_oauth_label(a->lg_provider));
    } else {
        char *e = c->errbuf.buf ? c->errbuf.buf : "", *last = e;
        for (char *p = e; *p; p++) { /* the last line it wrote */
            if (*p == '\n' && p[1]) {
                last = p + 1;
            }
        }
        if (strncmp(last, "pic: ", 5) == 0) {
            last += 5;
        }
        notice(a, RED, "Sign-in failed: %.*s", (int)strcspn(last, "\n"), *last ? last : "the sign-in ended");
    }
    free(c->outbuf.buf);
    free(c->errbuf.buf);
    memset(c, 0, sizeof *c);
    c->in = c->out = c->err = -1;
    login_end(a);
}

static void login_lines(app *a, tui_lines *tail) {
    char line[2400];
    const char *label = pic_cred_oauth_label(a->lg_provider);
    int w = a->cols > 8 ? a->cols - 2 : 8;
    if (a->lg == LG_WAIT) {
        (void)snprintf(line, sizeof line, "%s for %s  (esc: cancel)", label ? label : "Sign in", a->lg_provider);
        add_fit(tail, BOLD, line, a->cols);
        if (a->lg_code[0]) {
            (void)snprintf(line, sizeof line, "Open the page below and enter the code %s", a->lg_code);
            add_fit(tail, "", line, a->cols);
        } else if (a->lg_url[0]) {
            add_fit(tail, "", "Open this URL to sign in (the browser should have opened it):", a->cols);
        }
        for (size_t at = 0, n = strlen(a->lg_url); at < n; at += (size_t)w) { /* the whole address, wrapped */
            (void)snprintf(line, sizeof line, "  %.*s", w, a->lg_url + at);
            add_fit(tail, CYAN, line, a->cols);
        }
        add_fit(tail, DIM, a->lg_msg, a->cols);
        add_fit(tail, DIM, "If the browser cannot reach this machine, paste the address it ends on and press enter:", a->cols);
        { /* the address up to its query: the code after it stays off the screen */
            const char *q = memchr(a->lg_field, '?', a->lg_len);
            int shown = q ? (int)(q - a->lg_field) : (int)a->lg_len;
            (void)snprintf(line, sizeof line, "> %.*s%s", shown, a->lg_field, q ? "?\xe2\x80\xa6" : "");
        }
        add_fit(tail, "", line, a->cols);
        return;
    }
    if (a->lg == LG_OFFER) {
        add_fit(tail, BOLD, "pic's credential store", a->cols);
        (void)snprintf(line, sizeof line, "Stop asking for this passphrase? pic can keep the key in %s. [y/N]",
                       pic_host_where(NULL));
        add_fit(tail, "", line, a->cols);
        add_fit(tail, DIM, "y: keep it there (pic auth rekey passphrase goes back) \xc2\xb7 any other key: keep asking", a->cols);
        return;
    }
    {
        const char *prompt = a->lg == LG_KEY ? "API key for %s:"
                             : a->lg == LG_PASS_NEW ? "New passphrase for pic's credential store:"
                             : a->lg == LG_PASS_AGAIN ? "Same passphrase again:"
                                                      : "Passphrase for pic's credential store:";
        char head[160], dots[3 * 48 + 1] = "";
        size_t shown = 0;
        if (a->lg == LG_KEY && a->lg_label[0] && strcmp(a->lg_label, "default") != 0) {
            (void)snprintf(head, sizeof head, "API key \"%s\" for %s:", a->lg_label, a->lg_provider);
        } else {
            (void)snprintf(head, sizeof head, prompt, a->lg_provider);
        }
        for (size_t i = 0; i < a->lg_len; i++) {
            if (((unsigned char)a->lg_field[i] & 0xC0) != 0x80 && shown < 48) {
                memcpy(dots + 3 * shown++, "\xe2\x80\xa2", 3);
            }
        }
        dots[3 * shown] = '\0';
        add_fit(tail, BOLD, a->lg == LG_KEY ? "Log in with an API key" : "pic's credential store", a->cols);
        if (a->lg_request && a->lg_after == AFTER_RC) {
            add_fit(tail, DIM, "Remote control's keys are sealed in pic's credential store; /rc goes on once it opens.", a->cols);
        } else if (a->lg_request && a->lg_after == AFTER_ENDPOINT) {
            add_fit(tail, DIM, "The endpoint's key is sealed in pic's credential store; it is saved once the store opens.", a->cols);
        } else if (a->lg_request) {
            (void)snprintf(line, sizeof line, "The key for %s is in pic's credential store; your message is sent once it opens.",
                           a->lg_provider);
            add_fit(tail, DIM, line, a->cols);
        }
        (void)snprintf(line, sizeof line, "%s %s%s", head, dots, a->lg_len > 48 ? "\xe2\x80\xa6" : "");
        add_fit(tail, "", line, a->cols);
        if (a->lg_err[0]) {
            add_fit(tail, RED, a->lg_err, a->cols);
        }
        add_fit(tail, DIM,
                a->lg == LG_KEY ? "enter: save \xc2\xb7 esc: cancel \xc2\xb7 paste works; the key is sealed in ~/.pic/pic.sqlite"
                                : "enter: unlock \xc2\xb7 esc: cancel; the passphrase seals every stored key",
                a->cols);
    }
}

/* /login [PROVIDER]: the provider picker, or PROVIDER's method. */
static void login(app *a, const char *arg) {
    pic_model m;
    if (!*arg) {
        login_picker(a);
        return;
    }
    if (login_provider(a, arg, &m) != 0) {
        return;
    }
    if (pic_cred_oauth_label(arg)) {
        login_open(a, arg, "Signing in stores the subscription's tokens, sealed, in ~/.pic/pic.sqlite.");
    } else {
        login_begin(a, arg, 0);
    }
}

static int add_key_name(void *ctx, const char *name, const char *kind, long long created_ms, long long used_ms) {
    app_text *t = ctx;
    (void)kind;
    (void)created_ms;
    (void)used_ms;
    if (t->len) {
        (void)text_add(t, ", ", 2);
    }
    (void)text_add(t, name, strlen(name));
    return 0;
}

/* /logout [PROVIDER]: without one, the stored names (Pi lists them). */
static void logout(app *a, const char *arg) {
    pic_cred_source was;
    if (!*arg) {
        app_text t = {NULL, 0, 0};
        (void)pic_cred_each(add_key_name, &t);
        if (t.len) {
            notice(a, DIM, "Stored keys: %s. /logout PROVIDER removes one.", t.buf);
        } else {
            notice(a, DIM, "No stored credentials to remove. /logout only removes credentials saved by /login; environment "
                           "variables and models.json config are unchanged.");
        }
        free(t.buf);
        return;
    }
    was = pic_cred_source_of(arg, NULL, NULL);
    switch (pic_cred_logout(arg)) {
    case 1:
        notice(a, DIM, "Removed the %s for %s. Environment variables and models.json config are unchanged.",
               was == PIC_CRED_STORED_OAUTH ? "sign-in" : "stored API key", arg);
        break;
    case 0:
        notice(a, DIM, "No stored credentials for %s. Environment variables and models.json config are unchanged.", arg);
        break;
    default:
        notice(a, RED, "could not write ~/.pic/pic.sqlite");
    }
}


/* A path the user typed, as a full path: relative ones belong to the
 * workspace (Pi's are relative to its working directory, the project), "~/"
 * is the home directory. */
static void in_workspace(const app *a, const char *p, char *out, size_t cap) {
    char real[PATH_MAX];
    const char *home = getenv("HOME");
    if (p[0] == '/') {
        (void)snprintf(out, cap, "%s", p);
    } else if (p[0] == '~' && p[1] == '/' && home) {
        (void)snprintf(out, cap, "%s/%s", home, p + 2);
    } else {
        (void)snprintf(out, cap, "%s/%s", realpath(a->o->workspace, real) ? real : a->o->workspace, p);
    }
}

/* /help TOPIC: the manual's topic as markdown between two rules, as
 * /changelog shows its text; keys adds the bindings in effect. */
static void help_topic(app *a, const char *name) {
    char *md = cl_help_text(name);
    tui_lines l = {NULL, 0, 0};
    tui_md_opts o;
    size_t cols = a->cols > 2 ? (size_t)a->cols : 2;
    if (!md) {
        char *topics = cl_help_topics(", ");
        notice(a, RED, "no help topic %s; the topics: %s", name, topics ? topics : "");
        free(topics);
        return;
    }
    (void)tui_lines_add(&l, "", 0);
    (void)tui_border_line(NULL, NULL, cols, &l);
    md_opts(a, &o);
    (void)tui_markdown(md, strlen(md), cols, &o, &l);
    (void)tui_border_line(NULL, NULL, cols, &l);
    commit_lines(a, &l);
    free(md);
    if (strcmp(name, "keys") == 0) {
        char *keys = a->km ? tui_keymap_hotkeys(a->km) : NULL;
        notice(a, DIM, "In effect now:\n%s%s", keys ? keys : "", hotkeys_extra);
        free(keys);
    }
}

static void app_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, "/restart") == 0) {
        up_restart_ask(a);
    } else if (strcmp(line, "/mouse") == 0) {
        if (*arg && strcmp(arg, "on") != 0 && strcmp(arg, "off") != 0) {
            notice(a, RED, "Usage: /mouse [on|off]");
        } else {
            mouse_set(a, *arg ? strcmp(arg, "on") == 0 : -1);
        }
    } else if (strcmp(line, "/help") == 0 && *arg) {
        help_topic(a, arg);
    } else if (strcmp(line, "/help") == 0 || strcmp(line, "/hotkeys") == 0) {
        {
            char *keys = a->km ? tui_keymap_hotkeys(a->km) : NULL;
            notice(a, DIM, "%s%s", keys ? keys : "", hotkeys_extra);
            free(keys);
        }
        if (strcmp(line, "/help") == 0) {
            app_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));
            }
            (void)text_add(&t, "/help TOPIC shows a topic of the manual:", 40);
            {
                char *topics = cl_help_topics(" ");
                if (topics) {
                    (void)text_add(&t, " ", 1);
                    (void)text_add(&t, topics, strlen(topics));
                }
                free(topics);
            }
            notice(a, DIM, "%s", t.buf ? t.buf : "");
            free(t.buf);
        }
    } else if (strcmp(line, "/new") == 0) {
        if (a->conversation[0] && !a->working) {
            hook_end(a, "clear");
        }
        a->conversation[0] = a->name[0] = a->conv_title[0] = a->unfinished[0] = '\0';
        a->in = a->out = a->context = 0;
        a->cost = 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, "/delete") == 0) {
        if (*arg || a->conversation[0]) {
            trash_delete(a, *arg ? arg : a->conversation);
        } else {
            notice(a, RED, "/delete needs a conversation: give its ID or name, or press d on one in /resume");
        }
    } else if (strcmp(line, "/restore") == 0) {
        trash_restore(a, arg);
    } else if (strcmp(line, "/trash") == 0) {
        open_list(a, LIST_TRASH);
    } else if (strcmp(line, "/archived") == 0) {
        open_list(a, LIST_ARCHIVED);
    } else if (strcmp(line, "/model") == 0) {
        model_command(a, arg);
    } else if (strcmp(line, "/copy") == 0) {
        copy_last(a);
    } else if (strcmp(line, "/settings") == 0 || strcmp(line, "/config") == 0) {
        stg_open(a, NULL);
    } 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 {
                app_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 = cl_field("get_context_files", NULL, NULL, "$.files[0]"), *def = cl_setting("defaultModel"),
             *hide = cl_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);
        keys_load(a);
        themes_load(a);
        notice(a, DIM, "reloaded: %s; %zu prompt templates; %zu skills; %d models with a key; keybindings; %zu themes%s",
               ins && *ins ? "project instructions found (every request reads them afresh)" : "no project instructions (AGENTS.md, CLAUDE.md)",
               a->tpl.n, a->skl.n, a->nmodels, a->themes.n, refresh_catalog(a) ? " (the catalog is refreshing in the background)" : "");
        warn_flush(a);
        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) {
        /* Pi's What's New: the entries oldest first, so the newest is next to
         * the editor, as markdown between two rules */
        app_text all = {NULL, 0, 0};
        app_text md = {NULL, 0, 0};
        tui_lines l = {NULL, 0, 0};
        tui_md_opts o;
        size_t cols = a->cols > 2 ? (size_t)a->cols : 2;
        const char *top;
        {
            char *text = cl_field("get_changelog", NULL, NULL, "$.text");
            if (text) {
                (void)text_add(&all, text, strlen(text));
            }
            free(text);
        }
        top = all.buf ? strstr(all.buf, "## ") : NULL;
        for (const char *end = top ? all.buf + all.len : NULL; top && end > top;) {
            const char *start = end - 1;
            while (start > top && !(start[-1] == '\n' && strncmp(start, "## ", 3) == 0)) {
                start--;
            }
            if (md.len) {
                (void)text_add(&md, "\n\n", 2);
            }
            (void)text_add(&md, start, (size_t)(end - start));
            end = start;
        }
        (void)tui_lines_add(&l, "", 0);
        (void)tui_border_line(NULL, NULL, cols, &l);
        commit_lines(a, &l);
        notice(a, BOLD, "What's New");
        (void)tui_lines_add(&l, "", 0);
        md_opts(a, &o);
        (void)tui_markdown(md.buf ? md.buf : "No changelog entries found.", md.buf ? md.len : 27, cols, &o, &l);
        (void)tui_border_line(NULL, NULL, cols, &l);
        commit_lines(a, &l);
        free(md.buf);
        free(all.buf);
    } else if (strcmp(line, "/bug") == 0) {
        char real[PATH_MAX];
        long long id = *arg ? cl_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, "/remote-control") == 0 || strcmp(line, "/rc") == 0) {
        remote_open(a, arg);
    } else if (strcmp(line, "/logout") == 0 && !*arg) {
        au_open(a, "d removes the selected key or sign-in");
    } else if (strcmp(line, "/login") == 0) {
        login(a, arg);
    } else if (strcmp(line, "/logout") == 0) {
        logout(a, arg);
    } else if (strcmp(line, "/auth") == 0 || strcmp(line, "/key") == 0) {
        au_open(a, NULL);
    } else if (strcmp(line, "/mcp") == 0) {
        mc_command(a, arg);
    } else if (strcmp(line, "/codemode") == 0) {
        codemode_switch(a, arg);
    } else if (strcmp(line, "/loop") == 0) {
        wk_command(a, arg);
    } else if (strcmp(line, "/stop") == 0) {
        wk_stop_all(a);
    } else if (strcmp(line, "/monitor") == 0) {
        wk_monitor(a, arg);
    } else if (strcmp(line, "/goal") == 0) {
        wk_goal(a, arg);
    } else if (!a->conversation[0]) {
        if (strcmp(line, "/compact") == 0) {
            compact_start(a, arg); /* Pi's "Nothing to compact (session too small)" */
        } else if (strcmp(line, "/name") == 0 || strcmp(line, "/fork") == 0 ||
            strcmp(line, "/session") == 0 || strcmp(line, "/clone") == 0 || strcmp(line, "/export") == 0 ||
            strcmp(line, "/tree") == 0 || strcmp(line, "/share") == 0 || strcmp(line, "/rewind") == 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 && !*arg) {
        fork_open(a);
    } else if (strcmp(line, "/rewind") == 0) {
        rewind_open(a);
    } 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);
            if (!a->working) {
                hook_end(a, "other");
            }
            (void)snprintf(a->conversation, sizeof a->conversation, "%s", out);
            a->name[0] = a->conv_title[0] = '\0';
        }
    } else if (strcmp(line, "/compact") == 0) {
        compact_start(a, arg);
    } 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], path[PATH_MAX + 128];
            (void)snprintf(dflt, sizeof dflt, "pic-session-%s.html", a->conversation);
            in_workspace(a, *arg ? arg : dflt, path, sizeof path);
            const char *args[] = {"export", "--html", a->conversation, path, NULL};
            if (run_sync(a, args, &out) == 0) {
                notice(a, DIM, "written to %s as one self-contained web page", path);
            }
        } else {
            char path[PATH_MAX + 128];
            in_workspace(a, arg, path, sizeof path);
            const char *args[] = {"export", "--pi", path, NULL};
            if (run_sync(a, args, &out) == 0) {
                notice(a, DIM, "written to %s as Pi session files (one per conversation)", path);
            }
        }
    } else if (strcmp(line, "/tree") == 0) {
        tree_open(a, NULL);
    } 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);
}

/* Enter, or (follow) Alt+Enter. While a reply runs the message goes to it as
 * Pi's steer (Enter) or follow_up; /commands wait for it to end (they need the
 * journal it holds), as does everything when it takes no commands. */
static void submit_mode(app *a, char *msg, int follow, const tui_attachment *images, size_t nimages) {
    if (a->branch_custom) { /* the custom prompt for a branch summary */
        a->branch_custom = 0;
        tree_go(a, 1, msg);
        return;
    }
    if (strcmp(msg, "/settings") == 0 || strcmp(msg, "/config") == 0) { /* at once, even while a reply runs */
        stg_open(a, NULL);
        return;
    }
    if (strcmp(msg, "/model") == 0 || strncmp(msg, "/model ", 7) == 0) { /* at once too: it applies from the next request */
        char *line = strdup(msg);
        if (line) {
            app_command(a, line);
        }
        free(line);
        return;
    }
    if (strcmp(msg, "/restart") == 0) { /* at once: while a reply runs it says it waits for it */
        up_restart_ask(a);
        return;
    }
    if (run_bang(a, msg)) {
        return;
    }
    if (msg[0] == '/' && !a->working && !template_for(a, msg) && !skill_for(a, msg)) {
        app_command(a, msg);
    } else if (a->working) {
        int plain = msg[0] != '/' || template_for(a, msg) || skill_for(a, msg);
        if (plain && !a->interrupted && !a->finishing && a->nsent + a->nsteer + a->nfollow < MAX_QUEUED &&
            send_message(a, follow ? "follow_up" : "steer", msg, images, nimages) == 0) {
            a->sent_q[a->nsent++] = strdup(msg);
        } else if (a->nqueue < MAX_QUEUED) {
            a->queue[a->nqueue++] = strdup(msg);
        }
    } else if (a->bash.running) { /* Pi lets them overlap; here the command holds the journal: after it */
        if (a->nqueue < MAX_QUEUED) {
            a->queue[a->nqueue++] = strdup(msg);
        }
    } else {
        start_request(a, msg, images, nimages);
    }
}

static void submit(app *a, char *msg) { submit_mode(a, msg, 0, NULL, 0); }

/* The texts come back to the editor in front of what is typed there,
 * blank-line separated, as Pi's restoreQueuedMessagesToEditor does. */
static void restore_texts(app *a, char *const *texts, int n) {
    app_text t = {NULL, 0, 0};
    char *cur;
    for (int i = 0; i < n; i++) {
        (void)text_add(&t, texts[i], strlen(texts[i]));
        if (i + 1 < n) {
            (void)text_add(&t, "\n\n", 2);
        }
    }
    cur = tui_editor_expanded(a->ed);
    if (cur && cur[strspn(cur, " \t\n")]) {
        (void)text_add(&t, "\n\n", 2);
        (void)text_add(&t, cur, strlen(cur));
    }
    free(cur);
    tui_editor_set(a->ed, t.buf ? t.buf : "");
    free(t.buf);
}

/* The messages the app itself holds (/commands, and what the child could not take)
 * back to the editor. Returns how many. */
static int restore_queue(app *a) {
    int n = a->nqueue;
    if (n == 0) {
        return 0;
    }
    restore_texts(a, a->queue, n);
    for (int i = 0; i < n; i++) {
        free(a->queue[i]);
    }
    a->nqueue = 0;
    return n;
}

/* Alt+Up, and Esc on a running reply: the queue comes back to the editor. The
 * child owns steering and follow-ups, so it is asked (clear_queue) and the
 * answer carries them; the rest is local. notify: say how many came back. */
static void dequeue(app *a, int notify) {
    if (a->working && a->run.in >= 0 && (a->nsteer + a->nfollow + a->nsent) > 0 && !a->clear_sent &&
        send_command(a, "{\"id\":\"dequeue\",\"type\":\"clear_queue\"}") == 0) {
        a->clear_sent = 1;
        a->clear_notice = notify;
        return;
    }
    {
        int n = restore_queue(a);
        if (notify) {
            if (n) {
                notice(a, DIM, "Restored %d queued message%s to editor", n, n > 1 ? "s" : "");
            } else {
                notice(a, DIM, "No queued messages to restore");
            }
        }
    }
}

/* A fresh renderer over the live area: after the terminal was handed to
 * another program and given back. */
static void reset_screen(app *a) {
    (void)tui_term_raw(STDIN_FILENO);
    tui_term_size(STDOUT_FILENO, &a->cols, &a->rows);
    tui_render_size(a->r, a->cols, a->rows);
    (void)tui_render_resume(a->r);
    a->title[0] = '\0';
}

/* Ctrl+Z: put the terminal back, stop, and come back on SIGCONT. */
static void suspend_ui(app *a) {
    (void)tui_render_pause(a->r);
    tui_term_restore();
    (void)signal(SIGTSTP, SIG_DFL);
    (void)raise(SIGTSTP);
    reset_screen(a);
}

/* Ctrl+G: the editor's text in a temporary file for $VISUAL / $EDITOR; what
 * it holds afterwards replaces the text (Pi's external-editor.ts). */
static void external_editor(app *a) {
    const char *cmd = getenv("VISUAL");
    char dir[PATH_MAX], file[PATH_MAX + 16], *content, *argv[16], *copy;
    const char *tmp = getenv("TMPDIR");
    int n = 0, status = 0;
    pid_t pid;
    FILE *f;
    if (!cmd || !*cmd) {
        cmd = getenv("EDITOR");
    }
    if (!cmd || !*cmd) {
        notice(a, YELLOW, "No editor configured. Set $VISUAL or $EDITOR environment variable.");
        return;
    }
    (void)snprintf(dir, sizeof dir, "%s/pic-editor-XXXXXX", tmp && *tmp ? tmp : "/tmp");
    if (!mkdtemp(dir)) {
        notice(a, RED, "could not create a temporary file: %s", strerror(errno));
        return;
    }
    (void)snprintf(file, sizeof file, "%s/prompt.md", dir);
    content = tui_editor_expanded(a->ed);
    f = fopen(file, "w");
    if (!f || !content || fputs(content, f) == EOF) {
        notice(a, RED, "could not write %s", file);
        if (f) {
            (void)fclose(f);
        }
        free(content);
        (void)unlink(file);
        (void)rmdir(dir);
        return;
    }
    (void)fclose(f);
    free(content);
    copy = strdup(cmd);
    for (char *w = copy ? strtok(copy, " ") : NULL; w && n < 14; w = strtok(NULL, " ")) {
        argv[n++] = w;
    }
    argv[n++] = file;
    argv[n] = NULL;
    (void)tui_render_pause(a->r);
    tui_term_restore();
    printf("Launching external editor: %s\npic will resume when the editor exits.\n", cmd);
    (void)fflush(stdout);
    pid = n > 1 ? fork() : -1;
    if (pid == 0) {
        (void)signal(SIGINT, SIG_DFL);
        execvp(argv[0], argv);
        _exit(127);
    }
    while (pid > 0 && waitpid(pid, &status, 0) < 0 && errno == EINTR) {
    }
    reset_screen(a);
    if (pid < 0 || (WIFEXITED(status) && WEXITSTATUS(status) == 127)) {
        notice(a, YELLOW, "Failed to launch external editor: %s", cmd);
    } else if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
        notice(a, YELLOW, "External editor exited with %s %d; prompt unchanged", WIFEXITED(status) ? "code" : "signal",
               WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status));
    } else {
        char *got = NULL;
        size_t len = 0;
        f = fopen(file, "r");
        if (f) {
            char buf[4096];
            size_t k;
            app_text t = {NULL, 0, 0};
            while ((k = fread(buf, 1, sizeof buf, f)) > 0) {
                (void)text_add(&t, buf, k);
            }
            (void)fclose(f);
            got = t.buf ? t.buf : strdup("");
            len = t.len;
        }
        if (got) {
            const char *body = len >= 3 && memcmp(got, "\xEF\xBB\xBF", 3) == 0 ? got + 3 : got;
            size_t bl = strlen(body);
            char *clean;
            if (bl > 0 && body[bl - 1] == '\n') {
                bl--;
            }
            clean = strndup(body, bl);
            if (clean) {
                tui_editor_set(a->ed, clean);
            }
            free(clean);
            free(got);
        }
    }
    free(copy);
    (void)unlink(file);
    (void)rmdir(dir);
}

/* Writes the terminal title when it changed: "pic - NAME - DIR". */
static void sync_title(app *a) {
    char t[320];
    tui_title(a->o->workspace, a->name, t, sizeof t);
    if (strcmp(t, a->title) != 0) {
        ssize_t w = write(STDOUT_FILENO, t, strlen(t));
        (void)w;
        (void)snprintf(a->title, sizeof a->title, "%s", t);
    }
}

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

static int over_ssh(void) {
    return getenv("SSH_CONNECTION") || getenv("SSH_CLIENT") || getenv("SSH_TTY");
}

static void mouse_sync(app *a) {
    tui_term_mouse(a->mouse_on && !a->mouse_released);
}

/* A key or the window's focus coming back ends a right click's release. */
static void mouse_take_back(app *a) {
    if (a->mouse_released) {
        a->mouse_released = 0;
        a->released_why = NULL;
        mouse_sync(a);
    }
}

/* The mouse setting auto: on, except in Apple's Terminal, which never passes Cmd-C to the program and copies only
 * its own selection, so with the mouse taken Cmd-C beeps; left to it, its selection, Cmd-C and Cmd-double-click
 * work. Inside tmux TERM_PROGRAM is tmux's. */
static int mouse_auto(void) {
    const char *tp = getenv("TERM_PROGRAM");
    return !(tp && strcmp(tp, "Apple_Terminal") == 0);
}

/* The mouse setting, at start and when /settings changes it. 1 when auto left the mouse to the terminal. */
static int mouse_apply(app *a) {
    char *v = cl_effective("mouse");
    int automatic = !v || strcmp(v, "auto") == 0;
    a->mouse_on = automatic ? mouse_auto() : strcmp(v, "off") != 0;
    a->mouse_released = 0;
    free(v);
    mouse_sync(a);
    return automatic && !a->mouse_on;
}

/* Alt+M and /mouse: capture on or off for this session (ON -1: the other way). */
static void mouse_set(app *a, int on) {
    if (on < 0) {
        on = !(a->mouse_on && !a->mouse_released);
    }
    a->mouse_on = on;
    a->mouse_released = 0;
    a->press_x = -1;
    mouse_sync(a);
    notice(a, DIM,
           on ? "Mouse on for this session: the wheel scrolls, a drag copies, a click opens a link; a right click hands "
                "it to the terminal. /settings saves it."
              : "Mouse off for this session: the terminal selects, scrolls its own way and opens links; PageUp and PageDown "
                "scroll the transcript. /settings saves it.");
}

/* A plain click on a hyperlink in the transcript: opened here, or over ssh (where this machine's opener is the
 * wrong one) a hint for the terminal's own way. */
static void link_click(app *a, int x, int y) {
    char *url = tui_render_link_at(a->r, x, y);
    long t = now_ms();
    if (!url) {
        return;
    }
    if (x == a->link_x && y == a->link_y && t - a->link_at < 500) { /* a double click (Terminal's Cmd-double-click) */
        free(url);
        return;
    }
    a->link_x = x, a->link_y = y, a->link_at = t;
    if (over_ssh() && strncmp(url, "file://", 7) == 0) {
        /* a path on this machine, which the user's terminal cannot open: the path, decoded and copied */
        char *o = url;
        for (const char *p = url + 7; *p; p++) {
            unsigned v;
            if (*p == '%' && isxdigit((unsigned char)p[1]) && isxdigit((unsigned char)p[2]) && sscanf(p + 1, "%2x", &v) == 1 && v) {
                *o++ = (char)v;
                p += 2;
            } else {
                *o++ = *p;
            }
        }
        *o = '\0';
        copy_text(url);
        flash_for(a, "this file is on the remote machine; its path is copied", 4000);
    } else if (!tui_link_safe(url)) {
        flash_for(a, "pic does not open that kind of link", 3000);
    } else if (over_ssh()) {
        /* this machine's opener would open it on the wrong computer: the next click goes to the user's terminal,
         * and OSC 52 puts the address on their clipboard for a terminal (or mosh) that drops OSC 8 */
        copy_text(url);
        a->mouse_released = 1;
        a->released_why = MOUSE_RELEASED_LINK;
        a->press_x = -1;
        mouse_sync(a);
    } else if (pic_host_open(url) != 0) {
        flash_for(a, "no program here opens that link", 3000);
    }
    free(url);
}

/* A click on the footer's model, thinking level or key opens what /model, /thinking or /auth would,
 * at once, even while a reply streams. 1 when the click was on one of them. */
static int footer_click(app *a, int x, int y) {
    int part = -1;
    if (y != a->rows - 1 || !tui_render_is_fullscreen(a->r) || !a->mouse_on || a->mouse_released) {
        return 0;
    }
    for (int i = 0; i < 3; i++) {
        if (a->ft_hit[2 * i] >= 0 && x >= a->ft_hit[2 * i] && x < a->ft_hit[2 * i + 1]) {
            part = i;
        }
    }
    if (part < 0) {
        return 0;
    }
    if (a->ov || a->mp_open || a->sp.on || a->au.on || a->mc.on) { /* one panel at a time */
        return 1;
    }
    if (part == 0) {
        open_models(a, NULL);
    } else if (part == 1) {
        thinking_open(a);
    } else {
        au_open(a, NULL);
    }
    return 1;
}

/* Fullscreen mouse input: the wheel scrolls the transcript (Alt: five times
 * as far, as Pi's), the left button selects in it or opens a link it clicks,
 * the right button hands the mouse to the terminal (its menu, its selection,
 * its own link clicks) until the next key. */
static void app_on_mouse(app *a, const tui_key *k) {
    if (k->mouse == TUI_MOUSE_PRESS && k->button == 0 && tui_render_jump_hit(a->r, k->mx, k->my)) {
        (void)tui_render_edge(a->r, 1); /* a click on the jump-to-latest button */
    } else if (k->mouse == TUI_MOUSE_WHEEL) {
        int lines = tui_wheel_next(&a->wheel, k->button, (double)now_ms());
        (void)tui_render_scroll(a->r, (long)k->button * lines * (k->alt ? 5 : 1));
    } else if (k->button == 2 && k->mouse == TUI_MOUSE_PRESS) {
        a->mouse_released = 1;
        a->released_why = NULL;
        a->press_x = -1;
        mouse_sync(a);
    } else if (k->button == 0) {
        int sel = tui_render_mouse(a->r, k->mouse, k->mx, k->my);
        if (k->mouse == TUI_MOUSE_PRESS) {
            a->press_x = k->mx;
            a->press_y = k->my;
        } else if (k->mouse == TUI_MOUSE_RELEASE) {
            int click = !sel && a->press_x == k->mx && a->press_y == k->my;
            a->press_x = -1;
            if (click && a->rc_x >= 0 && k->mx >= a->rc_x && k->my == a->rows - 2 && tui_render_is_fullscreen(a->r)) {
                char cmd[] = "/rc"; /* the footer's "/rc" */
                submit(a, cmd);
            } else if (click && footer_click(a, k->mx, k->my)) {
                (void)0;
            } else if (click) {
                link_click(a, k->mx, k->my);
            }
        }
        if (sel && a->copy_on_select) {
            (void)copy_selection(a);
        }
    }
}

/* Pi's tui.altScreen keys: PageUp/PageDown and Ctrl+Home/Ctrl+End move the
 * transcript in fullscreen. 1 when the key was one of them. */
static int scroll_key(app *a, const tui_key *k) {
    if (!tui_render_is_fullscreen(a->r)) {
        return 0;
    }
    switch (k->kind) {
    case TUI_KEY_PAGEUP: (void)tui_render_page(a->r, -1); return 1;
    case TUI_KEY_PAGEDOWN: (void)tui_render_page(a->r, 1); return 1;
    case TUI_KEY_CTRL_HOME: (void)tui_render_edge(a->r, 0); return 1;
    case TUI_KEY_CTRL_END: (void)tui_render_edge(a->r, 1); return 1;
    case TUI_KEY_ACTION: { /* Pi's tui.altScreen half-page and line actions */
        long half = (a->rows > 4 ? a->rows - 4 : 1) / 2 > 0 ? (a->rows > 4 ? a->rows - 4 : 1) / 2 : 1;
        switch (k->action) {
        case TUI_ACT_SCROLL_HALF_UP: (void)tui_render_scroll(a->r, -half); return 1;
        case TUI_ACT_SCROLL_HALF_DOWN: (void)tui_render_scroll(a->r, half); return 1;
        case TUI_ACT_SCROLL_LINE_UP: (void)tui_render_scroll(a->r, -1); return 1;
        case TUI_ACT_SCROLL_LINE_DOWN: (void)tui_render_scroll(a->r, 1); return 1;
        default: return 0;
        }
    }
    default: return 0;
    }
}

/* Text at the editor's cursor as a bracketed paste would put it. */
static void paste_into_editor(app *a, char *t, size_t n) {
    tui_key k = {.kind = TUI_KEY_PASTE, .paste = t, .paste_len = n};
    (void)tui_editor_key(a->ed, &k);
}

/* Ctrl+V, Pi's handleClipboardPaste: files copied in Finder go in as their
 * paths (with a space where they would touch a word), an image is attached
 * and shown as "[image #N]", else the clipboard's text is pasted. */
static void clipboard_paste(app *a) {
    tui_clip c;
    switch (tui_clipboard_read(&c)) {
    case TUI_CLIP_FILES: {
        const char *cur = tui_editor_text(a->ed);
        size_t at = tui_editor_cursor(a->ed), n = strlen(c.text);
        char *t;
        int lead = at > 0 && !isspace((unsigned char)cur[at - 1]), trail = cur[at] && !isspace((unsigned char)cur[at]);
        for (const char *q = c.text; *q; q++) {
            if (*q != '\n' && iscntrl((unsigned char)*q)) {
                notice(a, RED, "Failed to paste from clipboard: Clipboard file path contains control characters");
                tui_clip_free(&c);
                return;
            }
        }
        if ((t = malloc(n + 3)) != NULL) {
            (void)snprintf(t, n + 3, "%s%s%s", lead ? " " : "", c.text, trail ? " " : "");
            paste_into_editor(a, t, strlen(t));
            free(t);
        }
        break;
    }
    case TUI_CLIP_IMAGE: {
        pic_image im = {.mime = NULL, .data = c.image, .len = c.image_len};
        char why[160];
        if (tui_editor_attached(a->ed) >= PIC_REQUEST_IMAGES) {
            notice(a, RED, "Failed to paste from clipboard: at most %d images go with a message", PIC_REQUEST_IMAGES);
        } else if (pic_image_check(&im, NULL, why, sizeof why) != PIC_IMAGE_OK) {
            notice(a, RED, "Failed to paste from clipboard: %s", why);
        } else if (tui_editor_attach(a->ed, c.image, c.image_len) > 0) {
            c.image = NULL; /* the editor has it */
        }
        break;
    }
    case TUI_CLIP_TEXT:
        paste_into_editor(a, c.text, strlen(c.text));
        break;
    default:
        break;
    }
    tui_clip_free(&c);
}

/* ---- the settings panel (tui/panel.h) ------------------------------------------ */

/* A change to a setting the interface applies at once: made in the panel or, while it is open, elsewhere. */
static void stg_apply(app *a, const tui_setting *was, const tui_setting *now) {
    const char *id = now->id, *v = now->value;
    if (was && strcmp(was->value, now->value) == 0) {
        return;
    }
    if (strcmp(id, "hideThinking") == 0) {
        int hide = strcmp(v, "true") == 0;
        if (hide != a->hide_thinking) {
            a->hide_thinking = hide;
            redraw_transcript(a);
        }
    } else if (strcmp(id, "tuiMode") == 0) {
        int full = strcmp(v, "fullscreen") == 0;
        if (full != tui_render_is_fullscreen(a->r)) {
            (void)tui_render_fullscreen(a->r, full, a->cols, a->rows);
            (void)snprintf(a->status, sizeof a->status, "TUI mode: %s", full ? "fullscreen" : "regular");
        }
    } else if (strcmp(id, "theme") == 0) {
        if (!a->theme_cli[0]) {
            theme_use(a, v);
            redraw_transcript(a); /* what is on screen takes the new colours too */
        }
    } else if (strcmp(id, "mouse") == 0) {
        (void)mouse_apply(a);
    } else if (strcmp(id, "hyperlinks") == 0 || strncmp(id, "fullscreen", 10) == 0) {
        fs_apply(a);
    } else if (strcmp(id, "defaultThinkingLevel") == 0) {
        a->lvl_for[0] = '\0'; /* worked out again for the model */
    }
}

/* Reads the list again (only when it changed, unless all): applies what changed, and tells an open field
 * when its setting changed under it. */
static void stg_load(app *a, int all) {
    char members[64] = "", *data;
    tui_settings fresh = {NULL, 0, -1};
    int rc;
    if (!all && a->sp.l.version >= 0) {
        (void)snprintf(members, sizeof members, "\"since\":%lld", a->sp.l.version);
    }
    a->sp.at = now_ms();
    data = cl_ask("get_settings", members, NULL, 0);
    rc = tui_settings_parse(data, &fresh);
    free(data);
    if (rc != 0) {
        return;
    }
    for (size_t i = 0; i < fresh.n; i++) {
        tui_setting *s = &fresh.s[i];
        const tui_setting *was = tui_settings_get(&a->sp.l, s->id);
        if (strcmp(s->id, "defaultModel") == 0 && !s->value[0] && a->default_model[0]) { /* pic's own, named */
            free(s->value);
            s->value = strdup(a->default_model);
            if (!s->value) {
                tui_settings_free(&fresh);
                return;
            }
        }
        if (a->sp.l.n) {
            stg_apply(a, was, s);
        }
        if (a->sp.p.field && was && strcmp(s->id, a->sp.p.sel) == 0 && strcmp(was->value, s->value) != 0) {
            char shown[200];
            tui_setting_shown(s, shown, sizeof shown);
            (void)snprintf(a->sp.p.note, sizeof a->sp.p.note, "changed elsewhere to %s; enter saves yours", shown);
            a->sp.p.note_err = 0;
        }
    }
    tui_settings_free(&a->sp.l);
    a->sp.l = fresh;
}

/* Opens the panel on row ID (NULL: where it was last), over whatever is open; nothing under it changes. */
static void stg_open(app *a, const char *id) {
    char sel[64];
    (void)snprintf(sel, sizeof sel, "%s", id ? id : a->sp.p.sel);
    tui_settings_free(&a->sp.l);
    a->sp.l.version = -1;
    memset(&a->sp.p, 0, sizeof a->sp.p);
    stg_load(a, 1);
    if (!a->sp.l.n) {
        notice(a, RED, "the settings could not be read");
        return;
    }
    tui_panel_select(&a->sp.p, &a->sp.l, sel);
    a->sp.on = 1;
}

static void stg_close(app *a) {
    a->sp.on = 0;
    a->sp.p.field = 0;
    a->sp.p.filter[0] = '\0';
    a->sp.p.note[0] = '\0';
    tui_settings_free(&a->sp.l);
}

/* Saves ID (VALUE NULL: back to the default) and shows what a re-read gives, never what was hoped. */
static void stg_save(app *a, const char *id, const char *value) {
    char err[300] = "", *k = cl_member("key", id), *v = cl_member("value", value), *members = NULL, *data = NULL;
    if (strcmp(id, "scopedModels") == 0 && !value) { /* its patterns are kept on their own */
        data = cl_scoped_set(NULL, 0) == 0 ? strdup("null") : NULL;
        (void)snprintf(err, sizeof err, "could not clear the scoped models");
    } else if (k && v && (members = malloc(strlen(k) + strlen(v) + 2)) != NULL) {
        (void)snprintf(members, strlen(k) + strlen(v) + 2, "%s,%s", k, v);
        if (strcmp(id, "theme") == 0) {
            a->theme_cli[0] = '\0'; /* a theme chosen here outlasts --theme */
        }
        data = cl_ask("set_setting", members, err, sizeof err);
    }
    if (data) {
        a->sp.p.field = 0;
        a->sp.p.note[0] = '\0';
    } else {
        (void)snprintf(a->sp.p.note, sizeof a->sp.p.note, "not saved: %s", err[0] ? err : "pic could not answer");
        a->sp.p.note_err = 1;
    }
    free(data);
    free(members);
    free(k);
    free(v);
    stg_load(a, 0);
}

/* A row whose value is chosen in a picker of its own: the panel closes for it, and comes back on that row
 * when the picker closes (stg_tick). */
static void stg_pick(app *a, const char *id) {
    (void)snprintf(a->sp.back, sizeof a->sp.back, "%s", id);
    stg_close(a);
    if (strcmp(id, "defaultModel") == 0) {
        notice(a, DIM, remember_model() ? "pick a model; new conversations start on the one you last chose"
                                       : "pick a model; ctrl+s in the picker saves it as the default");
        open_models(a, NULL);
    } else if (strcmp(id, "scopedModels") == 0) {
        scoped_open(a);
    } else if (strcmp(id, "theme") == 0) {
        theme_open(a);
    } else {
        a->sp.back[0] = '\0';
    }
}

/* Every key and paste while the panel is open, as decoded: none reaches the editor, a picker or the
 * running request. Esc and Ctrl+C close it and never interrupt. */
static void stg_key(app *a, const tui_key *k) {
    tui_panel_act act;
    a->esc_at = 0;
    a->ctrl_c_armed = 0;
    if (k->kind == TUI_KEY_MOUSE) { /* the wheel moves the selection and a click selects, on the panel only */
        int line, col, hit = tui_render_hit(a->r, k->mx, k->my, &line, &col);
        if (hit == TUI_HIT_VIEW) {
            return; /* a click outside does nothing; the selection behind stays */
        }
        if (k->mouse == TUI_MOUSE_WHEEL) {
            tui_key step = {.kind = k->button < 0 ? TUI_KEY_UP : TUI_KEY_DOWN};
            (void)tui_panel_key(&a->sp.p, &a->sp.l, &step, &act);
        } else if (k->mouse == TUI_MOUSE_PRESS && k->button == 0 && line >= 0) {
            (void)tui_panel_click(&a->sp.p, &a->sp.l, (size_t)line);
        }
        return;
    }
    if (a->km && tui_keymap_has(a->km, "app.settings.open", k)) {
        stg_close(a);
        return;
    }
    (void)tui_panel_key(&a->sp.p, &a->sp.l, k, &act);
    switch (act.what) {
    case TUI_PANEL_CLOSE: stg_close(a); break;
    case TUI_PANEL_SET: stg_save(a, act.id, act.value); break;
    case TUI_PANEL_RESET: stg_save(a, act.id, NULL); break;
    case TUI_PANEL_PICK: stg_pick(a, act.id); break;
    default: break;
    }
}

/* Each turn of the loop: the open panel re-reads a changed list; a picker it opened, once closed, gives the
 * panel back. */
static void stg_tick(app *a) {
    if (a->sp.on && now_ms() - a->sp.at >= STG_POLL_MS) {
        stg_load(a, 0);
    }
    if (!a->sp.on && a->sp.back[0] && !a->mp_open && !a->ov && !a->ep && !a->lg) {
        char id[64];
        (void)snprintf(id, sizeof id, "%s", a->sp.back);
        a->sp.back[0] = '\0';
        stg_open(a, id);
    }
}

/* ---- Ctrl+R: reverse search through the prompt history ---------------------- */

static void hs_find(app *a, long from) {
    long at = tui_editor_history_find(a->ed, a->hs.q, from);
    a->hs.fail = at < 0;
    if (at >= 0) {
        a->hs.at = at;
    }
}

static void hs_open(app *a) {
    a->hs.on = 1;
    a->hs.q[0] = '\0';
    a->hs.at = -1;
    hs_find(a, -1);
    a->hs.fail = 0;
}

/* Readline's keys: typing filters, Ctrl+R again goes to an older match, Enter accepts the entry into the
 * editor (it is not sent), Esc or Ctrl+C cancels. Cursor and Tab keys accept it and then act on the editor.
 * 1 when the key was used here. */
static int hs_key(app *a, const tui_key *k) {
    size_t n = strlen(a->hs.q);
    switch (k->kind) {
    case TUI_KEY_CHAR:
        if (n + strlen(k->text) < sizeof a->hs.q) {
            (void)snprintf(a->hs.q + n, sizeof a->hs.q - n, "%s", k->text);
            hs_find(a, a->hs.at);
        }
        return 1;
    case TUI_KEY_PASTE:
        for (size_t i = 0; i < k->paste_len && n + 1 < sizeof a->hs.q; i++) {
            a->hs.q[n++] = k->paste[i] == '\n' || k->paste[i] == '\t' ? ' ' : k->paste[i];
        }
        a->hs.q[n] = '\0';
        hs_find(a, a->hs.at);
        return 1;
    case TUI_KEY_BACKSPACE:
        while (n > 0 && ((unsigned char)a->hs.q[n - 1] & 0xC0) == 0x80) {
            n--;
        }
        if (n > 0) {
            n--;
        }
        a->hs.q[n] = '\0';
        hs_find(a, -1);
        return 1;
    case TUI_KEY_KILL_START:
    case TUI_KEY_DELETE_WORD:
        a->hs.q[0] = '\0';
        hs_find(a, -1);
        return 1;
    case TUI_KEY_ACTION:
        if (k->action == TUI_ACT_HISTORY_SEARCH) { /* older */
            long at = a->hs.at >= 0 ? tui_editor_history_find(a->ed, a->hs.q, a->hs.at - 1) : -1;
            a->hs.fail = at < 0 || a->hs.at < 1;
            if (!a->hs.fail) {
                a->hs.at = at;
            }
        }
        return 1;
    case TUI_KEY_ENTER:
        a->hs.on = 0;
        if (a->hs.at >= 0) {
            tui_editor_set(a->ed, tui_editor_history_at(a->ed, (size_t)a->hs.at));
        }
        return 1;
    case TUI_KEY_ESC:
    case TUI_KEY_CTRL_C:
        a->hs.on = 0;
        return 1;
    case TUI_KEY_LEFT:
    case TUI_KEY_RIGHT:
    case TUI_KEY_HOME:
    case TUI_KEY_END:
    case TUI_KEY_TAB:
        a->hs.on = 0;
        if (a->hs.at >= 0) {
            tui_editor_set(a->ed, tui_editor_history_at(a->ed, (size_t)a->hs.at));
        }
        return 0;
    default:
        return 1;
    }
}

/* ---- the transcript search (Pi's tui.altScreen.search*) ----------------------- */

/* Appends text to the search query, newlines and tabs as spaces. */
static void search_type(app *a, const char *t, size_t len) {
    char q[512];
    size_t n = (size_t)snprintf(q, sizeof q, "%s", tui_render_search_query(a->r));
    for (size_t i = 0; i < len && n + 1 < sizeof q; i++) {
        q[n++] = t[i] == '\n' || t[i] == '\t' || t[i] == '\r' ? ' ' : t[i];
    }
    q[n] = '\0';
    tui_render_search_set(a->r, q);
}

/* While the search box is open it has the keyboard, as Pi's focused overlay does: the search keys, text
 * for the query, and the viewport's scroll keys; everything else is dropped. Wheel and mouse go on. Runs on
 * the key as decoded, before the keybindings turn it into what the editor wants (Enter, Escape). 1 when used. */
static int search_key(app *a, tui_key *k) {
    char q[512];
    size_t n;
    if (k->kind == TUI_KEY_MOUSE) {
        return 0;
    }
    if (a->km && tui_keymap_has(a->km, "tui.altScreen.search", k)) {
        tui_render_search_close(a->r);
        return 1;
    }
    if (a->km ? tui_keymap_has(a->km, "tui.altScreen.searchNext", k) : k->kind == TUI_KEY_ENTER) {
        tui_render_search_step(a->r, 1);
        return 1;
    }
    if (a->km && tui_keymap_has(a->km, "tui.altScreen.searchPrevious", k)) {
        tui_render_search_step(a->r, -1);
        return 1;
    }
    if (a->km ? tui_keymap_has(a->km, "tui.altScreen.searchClose", k) : k->kind == TUI_KEY_ESC) {
        tui_render_search_close(a->r);
        return 1;
    }
    (void)snprintf(q, sizeof q, "%s", tui_render_search_query(a->r));
    n = strlen(q);
    switch (k->kind) {
    case TUI_KEY_CHAR:
        search_type(a, k->text, strlen(k->text));
        return 1;
    case TUI_KEY_PASTE:
        search_type(a, k->paste, k->paste_len);
        return 1;
    case TUI_KEY_BACKSPACE:
        while (n > 0 && ((unsigned char)q[n - 1] & 0xC0) == 0x80) {
            n--;
        }
        q[n > 0 ? n - 1 : 0] = '\0';
        tui_render_search_set(a->r, q);
        return 1;
    case TUI_KEY_KILL_START:
        tui_render_search_set(a->r, "");
        return 1;
    case TUI_KEY_DELETE_WORD:
        while (n > 0 && q[n - 1] == ' ') {
            n--;
        }
        while (n > 0 && q[n - 1] != ' ') {
            n--;
        }
        q[n] = '\0';
        tui_render_search_set(a->r, q);
        return 1;
    default:
        break;
    }
    if (!a->km || tui_keymap_apply(a->km, k)) {
        (void)scroll_key(a, k);
    }
    return 1;
}

static void on_key(app *a, tui_key *k) {
    int follow_next = 0;
    tui_key enter = {.kind = TUI_KEY_ENTER};
    if (k->kind == TUI_KEY_MOUSE) {
        app_on_mouse(a, k);
        return;
    }
    if (a->hs.on && hs_key(a, k)) {
        return;
    }
    if (a->lg) {
        a->esc_at = 0; /* an Esc here cancels; it never starts an Esc Esc */
        login_key_in(a, k);
        return;
    }
    if (a->ep) {
        a->esc_at = 0;
        ep_key_in(a, k);
        return;
    }
    if (a->ov) {
        a->esc_at = 0;
        overlay_key(a, k);
        return;
    }
    if (a->branch_custom && k->kind == TUI_KEY_ESC) { /* Pi: back to "Summarize branch?" */
        a->branch_custom = 0;
        summary_open(a);
        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]);
            int trash = a->pick_trash;
            pick_close(a);
            if (id && trash) {
                trash_restore(a, id);
            } else if (id) {
                resume(a, id);
            }
            free(id);
        } else if (k->kind == TUI_KEY_ESC || k->kind == TUI_KEY_CTRL_C) {
            pick_close(a);
        } else if (!a->pick_trash && k->kind == TUI_KEY_CHAR && strcmp(k->text, "a") == 0) {
            pick_archive(a);
        } else if (!a->pick_trash && !a->pick_archived && k->kind == TUI_KEY_CHAR && strcmp(k->text, " ") == 0 && a->pick_mark) {
            a->pick_mark[a->pick_at] = !a->pick_mark[a->pick_at];
            if (a->pick_at + 1 < a->npick) {
                a->pick_at++;
            }
        } else if (!a->pick_trash && !a->pick_archived &&
                   ((k->kind == TUI_KEY_CHAR && strcmp(k->text, "d") == 0) || k->kind == TUI_KEY_DELETE ||
                    k->kind == TUI_KEY_BACKSPACE)) {
            pick_delete(a);
        } else if (!a->pick_trash && !a->pick_archived && k->kind == TUI_KEY_CHAR && strcmp(k->text, "u") == 0) {
            pick_restore(a);
        }
        return;
    }
    if (k->kind != TUI_KEY_CTRL_C) {
        a->ctrl_c_armed = 0;
    }
    if (k->kind != TUI_KEY_CTRL_D) {
        a->d_at = 0;
    }
    if (k->kind != TUI_KEY_ESC) {
        a->esc_at = 0;
    }
    if (menu_key(a, k) || scroll_key(a, k)) {
        return;
    }
    if ((k->kind == TUI_KEY_CHAR || k->kind == TUI_KEY_ENTER || k->kind == TUI_KEY_PASTE) && tui_render_scrolled(a->r)) {
        (void)tui_render_edge(a->r, 1); /* typing while scrolled up follows the end again (Claude Code's send does too) */
    }
    if (a->kp.on && !a->unfinished[0]) { /* its request went another way (dropped, resumed, another conversation) */
        a->kp.on = 0;
        a->kp.wait_until = 0;
    }
    if (a->kp.on && !a->working && !a->bash.running && tui_editor_empty(a->ed) && kp_key(a, k)) {
        return;
    }
    if (a->unfinished[0] && !a->working && !a->bash.running && tui_editor_empty(a->ed) &&
        (k->kind == TUI_KEY_ENTER || k->kind == TUI_KEY_ESC)) {
        if (k->kind == TUI_KEY_ENTER) {
            resume_unfinished(a);
        } else {
            (void)drop_unfinished(a);
        }
        return;
    }
    if (k->kind == TUI_KEY_CTRL_HOME || k->kind == TUI_KEY_CTRL_END) { /* regular mode: Home and End, as before */
        k->kind = k->kind == TUI_KEY_CTRL_HOME ? TUI_KEY_HOME : TUI_KEY_END;
    }
    switch (k->kind) {
    case TUI_KEY_CTRL_C:
        if (a->working && !a->interrupted) { /* Claude Code: Ctrl+C interrupts a running reply; again, it exits */
            tui_key esc = {.kind = TUI_KEY_ESC};
            on_key(a, &esc);
            a->ctrl_c_armed = 1;
            return;
        }
        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)) { /* Claude Code: a second press within QUIT_WINDOW_MS */
            long now = now_ms();
            if (a->d_at && now - a->d_at < QUIT_WINDOW_MS) {
                a->quit = 1;
            } else {
                a->d_at = now;
                flash_for(a, "press ctrl+d again to exit", QUIT_WINDOW_MS);
            }
        } else { /* Pi: delete the character under the cursor */
            tui_key del = {.kind = TUI_KEY_DELETE};
            (void)tui_editor_key(a->ed, &del);
        }
        return;
    case TUI_KEY_ESC: {
        const char *cur = tui_editor_text(a->ed);
        if (a->working) { /* interrupt: queued messages come back to the editor, as Pi does */
            dequeue(a, 0);
            if (!a->interrupted) {
                a->interrupted = 1;
                a->stop_at = now_ms();
                a->stop_level = 1;
                /* Pi's abort over the pipe; the signals are the fallback for a child that takes none. */
                if (send_command(a, "{\"id\":\"esc\",\"type\":\"abort\"}") == 0) {
                    a->abort_sent = 1;
                } else {
                    (void)kill(a->run.pid, SIGINT);
                }
            } else if (a->abort_sent) { /* Esc again: the signal */
                a->abort_sent = 0;
                a->stop_at = now_ms();
                (void)kill(a->run.pid, SIGINT);
            } else if (a->stop_level < 3) { /* and again: harder */
                a->stop_level++;
                (void)kill(a->run.pid, a->stop_level == 2 ? SIGTERM : SIGKILL);
            }
        } else if (a->bash.running) {
            bash_cancel(a);
        } else if (a->ext_running && !cur[strspn(cur, " \t\n")]) { /* a request from elsewhere: abort it */
            (void)ext_send(a, "abort", NULL);
        } else if (cur[strspn(cur, " \t")] == '!') { /* bash mode: Esc clears the line */
            tui_editor_clear(a->ed);
        } else if (cur[strspn(cur, " \t\n")]) { /* Claude Code: Esc Esc clears the draft */
            long now = now_ms();
            if (a->esc_at && now - a->esc_at < 500) {
                a->esc_at = 0;
                tui_editor_clear(a->ed);
            } else {
                a->esc_at = now;
            }
        } else { /* Esc Esc on an empty editor: /rewind (Claude Code's), or Pi's doubleEscapeAction */
            long now = now_ms();
            if (a->esc_at && now - a->esc_at < 500) {
                char *v = cl_setting("doubleEscapeAction"), cmd[16];
                a->esc_at = 0;
                (void)snprintf(cmd, sizeof cmd, "/%s",
                               v && (strcmp(v, "tree") == 0 || strcmp(v, "fork") == 0 || strcmp(v, "none") == 0) ? v : "rewind");
                free(v);
                if (strcmp(cmd, "/none") != 0) {
                    app_command(a, cmd);
                }
            } else {
                a->esc_at = now;
            }
        }
        return;
    }
    case TUI_KEY_UP: { /* Claude Code: Up from the first line pulls queued messages back into the editor */
        const char *t = tui_editor_text(a->ed);
        size_t c = tui_editor_cursor(a->ed);
        if (a->working && a->nsteer + a->nfollow + a->nqueue + a->nsent > 0 && !memchr(t, '\n', c)) {
            dequeue(a, 1);
            return;
        }
        break;
    }
    case TUI_KEY_ALT_UP: /* Pi's app.message.dequeue */
        dequeue(a, 1);
        return;
    case TUI_KEY_CTRL_G:
        external_editor(a);
        return;
    case TUI_KEY_CTRL_Z:
        suspend_ui(a);
        return;
    case TUI_KEY_CTRL_X: /* Pi's app.message.copy: the selection when it is not copied on select */
        if (tui_render_is_fullscreen(a->r) && !a->copy_on_select && copy_selection(a)) {
            return;
        }
        copy_last(a);
        return;
    case TUI_KEY_CTRL_L: /* Pi's model picker key; while a reply runs it applies from the next request */
        open_models(a, NULL);
        return;
    case TUI_KEY_CTRL_P:
        cycle_model(a, 1);
        return;
    case TUI_KEY_CTRL_P_BACK: /* Shift+Ctrl+P: the previous model */
        cycle_model(a, -1);
        return;
    case TUI_KEY_CTRL_T: /* Pi's toggle for thinking blocks, saved as hideThinking */
        a->hide_thinking = !thinking_hidden(a);
        (void)cl_setting_set("hideThinking", a->hide_thinking ? "true" : "false");
        redraw_transcript(a);
        notice(a, DIM, "thinking blocks: %s", a->hide_thinking ? "hidden" : "visible");
        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;
        redraw_transcript(a);
        return;
    case TUI_KEY_CTRL_S: /* Pi's app.thinking.save */
        ensure_level(a);
        if (a->nlvl > 1 && cl_setting_set("defaultThinkingLevel", a->level) == 0) {
            notice(a, DIM, "saved thinking level: %s", a->level);
        }
        return;
    case TUI_KEY_ACTION: { /* Pi's app.session.* actions run their slash commands */
        static const char *const cmds[] = {NULL, "/new", "/tree", "/fork", "/resume"};
        if (k->action == TUI_ACT_REDRAW) {
            tui_render_invalidate(a->r);
            return;
        }
        if (k->action == TUI_ACT_HISTORY_SEARCH) {
            hs_open(a);
            return;
        }
        if (k->action == TUI_ACT_CREDENTIAL_SELECT) { /* pic's: /auth, bound to no key by default */
            au_open(a, NULL);
            return;
        }
        if (k->action == TUI_ACT_SEARCH_TOGGLE) { /* Pi's alt-screen search: fullscreen only */
            (void)tui_render_search_toggle(a->r);
            return;
        }
        if (k->action >= TUI_ACT_SEARCH_NEXT && k->action <= TUI_ACT_SEARCH_CLOSE) { /* a key bound to one of them alone */
            if (k->action == TUI_ACT_SEARCH_CLOSE) {
                tui_render_search_close(a->r);
            } else {
                tui_render_search_step(a->r, k->action == TUI_ACT_SEARCH_NEXT ? 1 : -1);
            }
            return;
        }
        if (k->action == TUI_ACT_SETTINGS_OPEN) { /* the loop opens it first; a key bound here alone */
            stg_open(a, NULL);
            return;
        }
        if (k->action == TUI_ACT_MOUSE_TOGGLE) { /* pic's alt+m */
            mouse_set(a, -1);
            return;
        }
        if (k->action >= TUI_ACT_SESSION_NEW && k->action <= TUI_ACT_SESSION_RESUME) {
            char cmd[16];
            (void)snprintf(cmd, sizeof cmd, "%s", cmds[k->action]);
            app_command(a, cmd);
        }
        return;
    }
    case TUI_KEY_CTRL_V:
        clipboard_paste(a);
        return;
    default:
        break;
    }
    if (k->kind == TUI_KEY_ENTER) { /* Claude Code: a backslash then Enter is a newline */
        const char *t = tui_editor_text(a->ed);
        size_t c = tui_editor_cursor(a->ed);
        if (c > 0 && t[c - 1] == '\\' && c == strlen(t)) {
            tui_key bs = {.kind = TUI_KEY_BACKSPACE}, nl = {.kind = TUI_KEY_NEWLINE};
            (void)tui_editor_key(a->ed, &bs);
            (void)tui_editor_key(a->ed, &nl);
            return;
        }
    }
    if (k->kind == TUI_KEY_ALT_ENTER) { /* Pi's app.message.followUp: Enter's twin that queues a follow-up */
        follow_next = 1;
        k = &enter;
    }
    if (tui_editor_key(a->ed, k) == TUI_EDIT_SUBMIT) {
        tui_attachment *images = NULL;
        size_t nimages = 0;
        char *msg;
        /* Images go with the message, to a request or to the running one as a steer or follow-up;
         * the queues keep only text, so they wait (the editor is left as it is). */
        if (tui_editor_attached(a->ed) > 0 &&
            (a->bash.running ||
             (a->working && (a->interrupted || a->finishing || a->nsent + a->nsteer + a->nfollow >= MAX_QUEUED)))) {
            notice(a, RED, "images cannot be queued: send this once the reply has ended");
            return;
        }
        msg = tui_editor_take_attached(a->ed, &images, &nimages);
        if (msg) {
            if (a->status[0] && !a->working) {
                a->status[0] = '\0';
            }
            (void)tui_render_edge(a->r, 1); /* sending a message follows the end again */
            submit_mode(a, msg, follow_next, images, nimages);
        }
        for (size_t i = 0; i < nimages; i++) {
            free(images[i].data);
        }
        free(images);
        free(msg);
    }
}

/* ---- the startup header --------------------------------------------------- */

/* A path as Pi lists it: relative to the workspace when inside it, else with
 * the home directory as "~". */
static void short_path(const char *real_ws, const char *p, char *out, size_t cap) {
    const char *home = getenv("HOME");
    size_t wl = strlen(real_ws), hl = home ? strlen(home) : 0;
    if (strncmp(p, real_ws, wl) == 0 && p[wl] == '/') {
        (void)snprintf(out, cap, "%s", p + wl + 1);
    } else if (hl > 1 && strncmp(p, home, hl) == 0 && p[hl] == '/') {
        (void)snprintf(out, cap, "~%s", p + hl);
    } else {
        (void)snprintf(out, cap, "%s", p);
    }
}

static void add_section(app *a, const char *name, char **items, size_t n, int sort) {
    tui_lines l = {NULL, 0, 0};
    if (n == 0) {
        return;
    }
    (void)tui_loaded_section(name, (const char *const *)items, n, sort, a->cols > 2 ? (size_t)a->cols : 2, &l);
    (void)tui_lines_add(&l, "", 0);
    commit_lines(a, &l);
}

/* Pi's header: the name and model, the key hints, then what was loaded: the
 * instruction files, skills and prompt templates. */
static void startup_header(app *a) {
    char hints[512], real[PATH_MAX], **items;
    tui_lines l = {NULL, 0, 0};
    char *ctx = cl_ask("get_context_files", "", NULL, 0);
    size_t n = 0, cap;
    notice(a, BOLD, "pic %s", a->model);
    if (a->o->model_note && !(a->o->resume && !a->o->model_named)) { /* resume says why, from the conversation */
        a->told_model = 1;
        notice(a, strncmp(a->o->model_note, "No key", 6) == 0 ? YELLOW : DIM, "%s", a->o->model_note);
    }
    tui_startup_hints(hints, sizeof hints);
    (void)tui_wrap(hints, strlen(hints), a->cols > 2 ? (size_t)a->cols : 2, &l);
    commit_lines(a, &l);
    {
        static const char help[] = "  \xe2\x80\x94  /help for all keys and commands";
        size_t hw = tui_width(help, strlen(help));
        char fit[PATH_MAX + 8];
        /* a long workspace gives way from the left, so the line does not wrap */
        tui_fit_path(a->o->workspace, a->cols > (int)hw + 8 ? (size_t)a->cols - hw : (size_t)-1, fit, sizeof fit);
        notice(a, DIM, "%s%s", fit, help);
    }
    (void)tui_lines_add(&l, "", 0);
    commit_lines(a, &l);
    if (!realpath(a->o->workspace, real)) {
        (void)snprintf(real, sizeof real, "%s", a->o->workspace);
    }
    {
        char *count = ctx ? cl_sql("SELECT json_array_length(?1, '$.files')", ctx, NULL) : NULL;
        cap = 16 + a->skl.n + a->tpl.n + (count ? (size_t)atoi(count) : 0);
        free(count);
    }
    items = calloc(cap, sizeof *items);
    if (!items) {
        free(ctx);
        return;
    }
    for (int i = 0; ctx && n < cap; i++) {
        char key[32], *path, shown[PATH_MAX];
        (void)snprintf(key, sizeof key, "$.files[%d]", i);
        if (!(path = cl_get(ctx, key))) {
            break;
        }
        short_path(real, path, shown, sizeof shown);
        items[n++] = strdup(shown);
        free(path);
    }
    add_section(a, "Context", items, n, 0);
    for (size_t i = 0; i < n; i++) {
        free(items[i]);
    }
    n = 0;
    for (size_t i = 0; i < a->skl.n; i++) {
        items[n++] = a->skl.v[i].name;
    }
    add_section(a, "Skills", items, n, 1);
    n = 0;
    for (size_t i = 0; i < a->tpl.n; i++) {
        char name[160];
        (void)snprintf(name, sizeof name, "/%s", a->tpl.v[i].name);
        items[n++] = strdup(name);
    }
    add_section(a, "Prompts", items, n, 1);
    for (size_t i = 0; i < n; i++) {
        free(items[i]);
    }
    free(items);
    free(ctx);
}

/* ---- a newer pic: the notice and /restart ----------------------------------------------------
 * The file this pic started from is looked at every 30 s while idle (platform.h's file_stamp, as
 * pic remote does). A changed file that has stayed put for 2 s has been installed, not just
 * written: the footer says so for good. /restart ends this loop when no reply is running and
 * starts the file again on this conversation, handing the credential store's key over. */

#define UP_EVERY_MS 30000
#define UP_SETTLE_MS 2000
#define UP_DRAFT_MAX 16384 /* a longer draft is left behind, not carried in the environment */

static long up_ms(long normal) {
#ifdef PIC_FAULTS
    const char *v = getenv("PIC_TEST_UPDATE_MS"); /* the tests' seam: how often, and how long a file must stay put */
    if (v && *v) {
        return atol(v);
    }
#endif
    return normal;
}

static void up_start(app *a) {
    const pic_platform *p = pic_platform_get();
    if (p->self_path && p->file_stamp && p->self_path(a->up_exe, sizeof a->up_exe) == 0 &&
        p->file_stamp(a->up_exe, a->up_stamp, sizeof a->up_stamp) == 0) {
        a->up_next = now_ms() + up_ms(UP_EVERY_MS);
        a->up_kick = now_ms() + 5000; /* a few seconds after the screen is up */
        return;
    }
    a->up_exe[0] = a->up_stamp[0] = '\0'; /* no way to tell: nothing to watch */
}

/* pic update --auto, detached (a grandchild, so nothing is left to reap): it pulls trunk, builds, tests and
 * installs over this file when it is green. It decides for itself whether autoUpdate, offline or the last
 * look says to do nothing; started now and every ten minutes. */
static void up_kick(app *a) {
    pid_t pid;
    if (getenv("PIC_NO_AUTO_UPDATE")) { /* the tests' seam: no clone or build from a test's pic */
        return;
    }
    a->up_kick = now_ms() + 600000;
    pid = fork();
    if (pid == 0) {
        if (fork() == 0) {
            int dn = open("/dev/null", O_RDWR);
            const char *argv[] = {a->o->self, "update", "--auto", NULL};
            (void)setsid();
            if (dn >= 0) {
                (void)dup2(dn, 0);
                (void)dup2(dn, 1);
                (void)dup2(dn, 2);
            }
            execv(a->o->self, (char *const *)(void *)(uintptr_t)argv);
        }
        _exit(0);
    }
    if (pid > 0) {
        (void)waitpid(pid, NULL, 0);
    }
}

static void up_tick(app *a) {
    char now[128];
    long t;
    if (a->up_kick && now_ms() >= a->up_kick && !a->working && !a->bash.running) {
        up_kick(a);
    }
    if (!a->up_stamp[0] || a->up_ready || a->working || a->bash.running || (t = now_ms()) < a->up_next) {
        return;
    }
    a->up_next = t + up_ms(UP_EVERY_MS);
    if (pic_platform_get()->file_stamp(a->up_exe, now, sizeof now) != 0 || strcmp(now, a->up_stamp) == 0 ||
        access(a->up_exe, X_OK) != 0) {
        a->up_seen[0] = '\0';
        return;
    }
    if (strcmp(now, a->up_seen) != 0) { /* new: look again once it has settled */
        (void)snprintf(a->up_seen, sizeof a->up_seen, "%s", now);
        a->up_since = t;
        a->up_next = t + up_ms(UP_SETTLE_MS);
        return;
    }
    if (t - a->up_since >= up_ms(UP_SETTLE_MS)) {
        a->up_ready = 1;
    }
}

static void up_restart_ask(app *a) {
    if (!a->up_stamp[0]) {
        notice(a, RED, "/restart is not available here: this platform cannot find pic's own file");
    } else if (a->up_want) {
        notice(a, DIM, "Already restarting after this reply");
    } else if (a->working || a->bash.running || a->nqueue) {
        a->up_want = 1;
        notice(a, DIM, "restarting after this reply");
    } else {
        a->up_want = 1;
    }
}

/* The loop's end: a restart asked for and nothing left running. */
static void up_pump(app *a) {
    if (a->up_want && !a->working && !a->bash.running && !a->nqueue) {
        const char *draft = a->ed ? tui_editor_text(a->ed) : NULL; /* the editor is freed before the exec */
        if (draft && *draft && strlen(draft) <= UP_DRAFT_MAX) {
            (void)setenv("PIC_RESTART_DRAFT", draft, 1);
        }
        a->restart = 1;
        a->quit = 1;
    }
}

/* Starts the file again on the conversation (the draft is already in PIC_RESTART_DRAFT), with the store's key
 * in a pipe (cred.h's pic_cred_handoff, as pic remote does). Returns only when it could not. */
static void up_exec(const app *a) {
    const pic_tui_options *o = a->o;
    const char *argv[16];
    int n = 0, keyfd;
    argv[n++] = a->up_exe;
    if (o->tui_mode) {
        argv[n++] = "--tui-mode";
        argv[n++] = o->tui_mode;
    }
    if (o->theme) {
        argv[n++] = "--theme";
        argv[n++] = o->theme;
    }
    argv[n++] = "--db";
    argv[n++] = o->db;
    argv[n++] = "--workspace";
    argv[n++] = o->workspace;
    argv[n++] = "tui";
    if (a->conversation[0]) {
        argv[n++] = "--session";
        argv[n++] = a->conversation;
    }
    argv[n] = NULL;
    if ((keyfd = pic_cred_handoff()) >= 0) {
        char num[16];
        (void)fcntl(keyfd, F_SETFD, 0);
        (void)snprintf(num, sizeof num, "%d", keyfd);
        (void)setenv("PIC_KEY_FD", num, 1);
    }
    execv(a->up_exe, (char *const *)(void *)(uintptr_t)argv);
    fprintf(stderr, "pic: cannot start %s: %s\n", a->up_exe, strerror(errno));
    (void)unsetenv("PIC_KEY_FD");
    (void)unsetenv("PIC_RESTART_DRAFT");
    if (keyfd >= 0) {
        close(keyfd);
    }
}

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

int pic_tui_main(const pic_tui_options *o) {
    app a;
    int rc = 0;
    memset(&a, 0, sizeof a);
    a.o = o;
    cl_app = &a;
    a.press_x = a.press_y = -1;
    pic_cred_offer_register(NULL); /* the interface makes the offer in its own panel */
    (void)snprintf(hook_owner, sizeof hook_owner, "tui-%ld-%lld", (long)getpid(), (long long)pic_platform_get()->wall_ns());
    { /* what stop_check runs, when there are hooks to end conversations for */
        if (cl_hooks_configured()) {
            const char *argv[] = {o->self, "--db", o->db, "--workspace", o->workspace, "hooks", "end", "other", NULL};
            char owner[96];
            (void)snprintf(owner, sizeof owner, "PIC_HOOK_OWNER=%s", hook_owner);
            (void)pic_host_exec_prepare(&stop_exec, argv, owner);
        }
    }
    a.run.out = a.run.err = -1;
    (void)snprintf(a.model, sizeof a.model, "%s", o->model);
    if (o->key) { /* --key: main checked that the model's provider has it */
        pic_model km;
        if (key_model_provider(a.model, a.key_run_provider, sizeof a.key_run_provider, &km) == 0) {
            (void)snprintf(a.key_run, sizeof a.key_run, "%s", o->key);
        }
    }
    (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;
    a.keychk.out = a.keychk.err = -1;
    {
        char *hide = cl_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.tr = tui_transcript_new()) || !(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);
    probe_start(&a);
    load_templates(&a);
    if (o->theme) {
        (void)snprintf(a.theme_cli, sizeof a.theme_cli, "%s", o->theme);
    }
    keys_load(&a);
    themes_load(&a);
    (void)signal(SIGSEGV, on_crash);
    (void)signal(SIGABRT, on_crash);
    (void)signal(SIGBUS, on_crash);
    (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);
    fs_apply(&a);
    int mouse_left = mouse_apply(&a), full;
    {
        char *mode = o->tui_mode ? strdup(o->tui_mode) : cl_effective("tuiMode");
        const char *term = getenv("TERM");
        int dumb = term && strcmp(term, "dumb") == 0; /* no alternate screen to draw on: inline */
        full = !dumb && (!mode || strcmp(mode, "regular") != 0);
        (void)tui_render_fullscreen(a.r, full, a.cols, a.rows);
        free(mode);
    }
    (void)tui_git_branch(o->workspace, a.branch, sizeof a.branch);
    startup_header(&a);
    warn_flush(&a);
    char *told = full && mouse_left ? cl_setting("mouseNoticeShown") : NULL;
    if (full && mouse_left && !(told && strcmp(told, "true") == 0) && cl_setting_set("mouseNoticeShown", "true") == 0) {
        notice(&a, DIM,
               "Terminal.app: the mouse is left to the terminal, so its selection and Cmd-C work; /mouse on gives pic "
               "the wheel and drag-to-copy. pic settings mouse on keeps it.");
    }
    free(told);
    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);
        }
    }
    if (o->pick) {
        open_picker(&a);
    }
    keychk_startup(&a);
    up_start(&a);
    {
        const char *draft = getenv("PIC_RESTART_DRAFT"); /* a restart's: the editor as it was */
        if (draft && *draft) {
            tui_editor_set(a.ed, draft);
        }
        (void)unsetenv("PIC_RESTART_DRAFT");
    }
    while (!a.quit) {
        struct pollfd p[8]; /* stdin, wake, the request's two pipes, the catalog refresh, a "!" command, a sign-in */
        int n = 0, timeout = -1;
        tui_key k;
        if (resized) {
            resized = 0;
            tui_term_size(STDOUT_FILENO, &a.cols, &a.rows);
            tui_render_size(a.r, a.cols, a.rows);
            tui_render_invalidate(a.r);
        }
        sync_title(&a);
        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.bash.running && a.bash.c.out >= 0) {
            p[n++] = (struct pollfd){a.bash.c.out, POLLIN, 0};
        }
        if (a.lg == LG_WAIT && a.lg_child.out >= 0) {
            p[n++] = (struct pollfd){a.lg_child.out, POLLIN, 0};
        }
        if (a.lg == LG_WAIT && a.lg_child.err >= 0) {
            p[n++] = (struct pollfd){a.lg_child.err, POLLIN, 0};
        }
        if (a.rc_pairing && a.rc_child.out >= 0) {
            p[n++] = (struct pollfd){a.rc_child.out, POLLIN, 0};
        }
        if (a.rc_pairing && a.rc_child.err >= 0) {
            p[n++] = (struct pollfd){a.rc_child.err, POLLIN, 0};
        }
        if (a.rc_pairing && (timeout < 0 || timeout > 200)) {
            timeout = 200; /* a cancelled pairing's deadline */
        }
        if (a.fw_on && a.fw.out >= 0) {
            p[n++] = (struct pollfd){a.fw.out, POLLIN, 0};
        }
        if ((a.fw_on || a.rcp_want || a.rc_on || a.ov == OV_REMOTE || (!a.working && a.conversation[0])) && (timeout < 0 || timeout > 500)) {
            timeout = 500; /* the follower's start and end, pic remote's, /rc's state */
        }
        if (a.wk_n && (timeout < 0 || timeout > 1000)) {
            timeout = 1000; /* the footer's countdown */
        }
        if (a.up_kick && (timeout < 0 || timeout > 1000)) {
            timeout = 1000; /* the next pic update --auto */
        }
        if (a.up_stamp[0] && !a.up_ready) {
            long w = a.up_next - now_ms() + 1; /* the next look at pic's own file */
            if (timeout < 0 || w < timeout) {
                timeout = w < 1 ? 1 : (int)w;
            }
        }
        if ((a.refreshing || a.keychk_on || a.mc.busy) && timeout < 0) {
            timeout = 250; /* notice the refresh ending */
        }
        if (a.sp.on && (timeout < 0 || timeout > STG_POLL_MS)) {
            timeout = STG_POLL_MS; /* a setting changed elsewhere */
        }
        if (a.working) {
            timeout = 80; /* the spinner */
        }
        if (a.bash.running) {
            timeout = 50; /* the command may exit without closing its pipe (a background child) */
        }
        if (a.lg == LG_WAIT && (timeout < 0 || timeout > 200)) {
            timeout = 200; /* a cancelled sign-in's deadline */
        }
        if (tui_keys_waiting(a.keys)) {
            timeout = 50; /* a lone Esc, or the start of a sequence */
        }
        if (a.probe_until) { /* close the reply window on time */
            long w = a.probe_until - now_ms() + 1;
            if (timeout < 0 || w < timeout) {
                timeout = w < 1 ? 1 : (int)w;
            }
        }
        if (tui_keys_queued(a.keys)) {
            timeout = 0; /* keys typed while the probe was answered */
        }
        {
            long wake = tui_render_wake(a.r); /* the scrollbar hiding again */
            if (a.flash[0] && a.flash_until - now_ms() > 0 && (wake < 0 || a.flash_until - now_ms() < wake)) {
                wake = a.flash_until - now_ms() + 1;
            }
            if (wake >= 0 && (timeout < 0 || wake < timeout)) {
                timeout = (int)wake;
            }
        }
        if (poll(p, (nfds_t)n, timeout) < 0 && errno != EINTR) {
            rc = 1;
            break;
        }
        stop_check();
        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)) {
            if (a.mouse_released && k.kind != TUI_KEY_MOUSE && !(a.km && tui_keymap_has(a.km, "app.mouse.toggle", &k))) {
                mouse_take_back(&a); /* and the key does what it does */
            }
            /* The settings panel is above everything: it takes every key while open, and its key opens it
             * over anything, a running reply, a picker or the search box included. */
            if (a.sp.on) {
                stg_key(&a, &k);
                free(k.paste);
                continue;
            }
            if (a.au.on) {
                au_key(&a, &k);
                free(k.paste);
                continue;
            }
            if (a.mc.on) {
                mc_key(&a, &k);
                free(k.paste);
                continue;
            }
            if (a.km && tui_keymap_has(a.km, "app.settings.open", &k)) {
                a.esc_at = 0;
                stg_open(&a, NULL);
                free(k.paste);
                continue;
            }
            /* The model picker is the layer under it: every key is its own while it is open. */
            if (a.mp_open) {
                picker_key(&a, &k);
                free(k.paste);
                continue;
            }
            if (tui_render_search_active(a.r) && search_key(&a, &k)) {
                free(k.paste);
                continue;
            }
            /* In fullscreen the search key wins over an editor key it shares (ctrl+f, cursor right elsewhere). */
            if (a.km && tui_render_is_fullscreen(a.r) && !a.mp_open && !a.ov && !a.picking && !a.hs.on &&
                tui_keymap_has(a.km, "tui.altScreen.search", &k)) {
                (void)tui_render_search_toggle(a.r);
                free(k.paste);
                continue;
            }
            if (!a.km || tui_keymap_apply(a.km, &k)) { /* Pi's keybindings: a key bound to nothing is dropped */
                on_key(&a, &k);
            }
            free(k.paste);
        }
        replies_apply(&a);
        if (a.working && a.run.pid > 0) {
            app_pump(&a);
        }
        if (a.bash.running) {
            bash_pump(&a);
            run_queued(&a);
        }
        if (a.refreshing) {
            pump_refresh(&a);
        }
        if (a.keychk_on) {
            pump_keychk(&a);
        }
        if (a.lg == LG_WAIT) {
            login_pump(&a);
        }
        if (a.rc_pairing) {
            rc_pump(&a);
        }
        rcp_tick(&a);
        fw_tick(&a);
        wk_tick(&a);
        ask_tick(&a);
        kp_tick(&a);
        stg_tick(&a);
        au_tick(&a);
        up_tick(&a);
        up_pump(&a);
        mc_tick(&a);
    }
    if (a.lg == LG_WAIT) { /* quitting under a sign-in: it closes its listener and ends */
        (void)kill(a.lg_child.pid, SIGTERM);
        (void)waitpid(a.lg_child.pid, NULL, 0);
    }
    if (a.rc_pairing) { /* quitting under a pairing: the phone hears no */
        (void)kill(a.rc_child.pid, SIGTERM);
        (void)waitpid(a.rc_child.pid, NULL, 0);
    }
    fw_stop(&a); /* pic remote, if started here, keeps running */
    login_end(&a);
    if (a.bash.running) { /* quitting under a "!" command: it does not outlive pic */
        long t0 = now_ms();
        int level = 0;
        (void)kill(a.bash.c.pid, SIGINT); /* pic bash cancels the command and journals it */
        while (waitpid(a.bash.c.pid, NULL, WNOHANG) == 0) {
            (void)poll(NULL, 0, 20);
            if (now_ms() - t0 > 3000 * (level + 1) && level < 2) {
                (void)kill(a.bash.c.pid, ++level == 1 ? SIGTERM : SIGKILL);
            }
        }
    }
    if (a.working && a.run.pid > 0) { /* quitting mid-reply: cancel it, firmly if it must be */
        long t0 = now_ms();
        int level = 1, status = 0;
        (void)kill(a.run.pid, SIGINT);
        while (waitpid(a.run.pid, &status, 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 > STOP_GRACE_MS * level && level < 3) {
                level++;
                (void)kill(a.run.pid, level == 2 ? SIGTERM : SIGKILL);
            }
        }
        run_ended(&a.run, status);
        child_pid = 0;
        free(a.run.outbuf.buf);
        free(a.run.errbuf.buf);
        if (a.run.in >= 0) {
            close(a.run.in);
        }
    }
    if (a.refreshing && a.refresh.pid > 0) { /* the catalog refresh: not worth waiting long for */
        long t0 = now_ms();
        (void)kill(a.refresh.pid, SIGTERM);
        while (waitpid(a.refresh.pid, NULL, WNOHANG) == 0) {
            if (now_ms() - t0 > 2000) {
                (void)kill(a.refresh.pid, SIGKILL);
                (void)waitpid(a.refresh.pid, NULL, 0);
                break;
            }
            (void)poll(NULL, 0, 20);
        }
        free(a.refresh.outbuf.buf);
        free(a.refresh.errbuf.buf);
    }
    if (a.mc.busy && a.mc.c.pid > 0) { /* /mcp's listing: not worth waiting for */
        (void)kill(a.mc.c.pid, SIGTERM);
        (void)waitpid(a.mc.c.pid, NULL, 0);
        free(a.mc.c.outbuf.buf);
        free(a.mc.c.errbuf.buf);
    }
    if (a.keychk_on && a.keychk.pid > 0) { /* a free check: not worth waiting for */
        (void)kill(a.keychk.pid, SIGTERM);
        (void)waitpid(a.keychk.pid, NULL, 0);
        free(a.keychk.outbuf.buf);
        free(a.keychk.errbuf.buf);
    }
    if (a.r) {
        hook_end(&a, "prompt_input_exit");
    }
    (void)tui_render_finish(a.r);
done:
    tui_term_restore();
    if (a.conversation[0] && rc == 0 && !a.restart) { /* first, and flushed: what follows may be slow on a busy machine */
        printf("pic: conversation %s (pic chat --session %s, or pic tui -c)\n", a.conversation, a.conversation);
        (void)fflush(stdout);
    }
    pick_close(&a);
    ov_free(&a);
    tui_settings_free(&a.sp.l);
    app_models_free(&a);
    free(a.last_reply);
    bash_settle(&a);
    qfree(a.steer_q, &a.nsteer);
    qfree(a.follow_q, &a.nfollow);
    qfree(a.sent_q, &a.nsent);
    commands_free(&a.tpl);
    commands_free(&a.skl);
    for (int i = 0; i < a.nqueue; i++) {
        free(a.queue[i]);
    }
    free(a.stream.buf);
    free(a.thinking.buf);
    for (int i = 0; i < a.nblocks; i++) {
        block_free(&a.blocks[i]);
    }
    free(a.blocks);
    if (a.keys) {
        tui_keys_free(a.keys);
    }
    tui_keymap_free(a.km);
    tui_themeset_free(&a.themes);
    free(a.startup_warn);
    if (a.ed) {
        tui_editor_free(a.ed);
    }
    if (a.r) {
        tui_render_free(a.r);
    }
    tui_transcript_free(a.tr);
    sqlite3_finalize(a.get);
    sqlite3_close(a.db);
    if (a.restart) {
        up_exec(&a);
        fputs("pic: could not start the newer pic; the conversation is saved: pic tui -c\n", stderr);
        rc = 1;
    }
    return rc;
}