Skip to content
pi-c Documentation
Login

Documentation

/* Unit tests for the terminal UI modules (width, term decoder, render, editor). */
#include "ignore.h"
#include "tui/atfile.h"
#include "tui/editor.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/transcript.h"
#include "tui/themes.h"
#include "tui/keymap.h"
#include "tui/remote.h"
#include "tui/view.h"
#include "tui/theme.h"
#include "tui/themes.h"
#include "tui/keymap.h"
#include "tui/viewport.h"
#include "tui/width.h"

#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#define SYNC_ON "\x1b[?2026h"
#define SYNC_OFF "\x1b[?2026l"
#define HIDE "\x1b[?25l"
#define SHOW "\x1b[?25h"

static void fail(const char *what, const char *fmt, ...)
{
    va_list ap;
    fprintf(stderr, "FAIL: %s: ", what);
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    fputc('\n', stderr);
    exit(1);
}

static void pass(const char *what)
{
    printf("PASS: %s\n", what);
}

/* Escapes control bytes so a failure message is readable. */
static void show(const char *s, size_t n, char *out, size_t cap)
{
    size_t o = 0;
    for (size_t i = 0; i < n && o + 8 < cap; i++) {
        unsigned char c = (unsigned char)s[i];
        if (c == 0x1b)
            o += (size_t)snprintf(out + o, cap - o, "\\e");
        else if (c == '\n')
            o += (size_t)snprintf(out + o, cap - o, "\\n");
        else if (c == '\r')
            o += (size_t)snprintf(out + o, cap - o, "\\r");
        else if (c < 0x20)
            o += (size_t)snprintf(out + o, cap - o, "\\x%02x", c);
        else
            out[o++] = (char)c;
    }
    out[o] = 0;
}

static void check_str(const char *what, const char *got, const char *want)
{
    if (strcmp(got, want) != 0) {
        char a[1024], b[1024];
        show(got, strlen(got), a, sizeof a);
        show(want, strlen(want), b, sizeof b);
        fail(what, "got \"%s\" want \"%s\"", a, b);
    }
}

static void check_int(const char *what, long got, long want)
{
    if (got != want)
        fail(what, "got %ld want %ld", got, want);
}

/* ---- width ------------------------------------------------------------- */

static void test_width(void)
{
    uint32_t cp;
    check_int("decode ascii", (long)tui_utf8_decode("a", 1, &cp), 1);
    check_int("decode ascii cp", cp, 'a');
    check_int("decode 2-byte", (long)tui_utf8_decode("\xC3\xA9", 2, &cp), 2);
    check_int("decode 2-byte cp", cp, 0xE9);
    check_int("decode 3-byte", (long)tui_utf8_decode("\xE4\xB8\xAD", 3, &cp), 3);
    check_int("decode 3-byte cp", cp, 0x4E2D);
    check_int("decode 4-byte", (long)tui_utf8_decode("\xF0\x9F\x98\x80", 4, &cp), 4);
    check_int("decode 4-byte cp", cp, 0x1F600);
    check_int("decode truncated", (long)tui_utf8_decode("\xE4\xB8", 2, &cp), 1);
    check_int("decode truncated cp", cp, 0xFFFD);
    check_int("decode overlong", (long)tui_utf8_decode("\xC0\x80", 2, &cp), 1);
    check_int("decode surrogate", (long)tui_utf8_decode("\xED\xA0\x80", 3, &cp), 1);
    check_int("decode stray continuation", (long)tui_utf8_decode("\x80", 1, &cp), 1);
    check_int("decode real U+FFFD", (long)tui_utf8_decode("\xEF\xBF\xBD", 3, &cp), 3);
    pass("utf8 decode");

    check_int("width a", tui_cp_width('a'), 1);
    check_int("width nul", tui_cp_width(0), 0);
    check_int("width esc", tui_cp_width(0x1b), 0);
    check_int("width C1", tui_cp_width(0x85), 0);
    check_int("width e-acute", tui_cp_width(0xE9), 1);
    check_int("width combining acute", tui_cp_width(0x301), 0);
    check_int("width combining 1AB0", tui_cp_width(0x1AB0), 0);
    check_int("width combining 1DC0", tui_cp_width(0x1DC0), 0);
    check_int("width combining 20D0", tui_cp_width(0x20D0), 0);
    check_int("width ZWSP", tui_cp_width(0x200B), 0);
    check_int("width ZWJ", tui_cp_width(0x200D), 0);
    check_int("width VS16", tui_cp_width(0xFE0F), 0);
    check_int("width VS supplement", tui_cp_width(0xE0100), 0);
    check_int("width CJK", tui_cp_width(0x4E2D), 2);
    check_int("width hangul", tui_cp_width(0xAC00), 2);
    check_int("width jamo", tui_cp_width(0x1100), 2);
    check_int("width fullwidth A", tui_cp_width(0xFF21), 2);
    check_int("width 303F narrow", tui_cp_width(0x303F), 1);
    check_int("width emoji", tui_cp_width(0x1F600), 2);
    check_int("width emoji 1F9FF", tui_cp_width(0x1F9FF), 2);
    check_int("width CJK ext B", tui_cp_width(0x20000), 2);
    check_int("width cent sign", tui_cp_width(0xA2), 1);
    check_int("width plain symbol", tui_cp_width(0x2603), 1);
    pass("code point width");

    const char *s = "\x1b[31mred\x1b[0m";
    check_int("width ignores sgr", (long)tui_width(s, strlen(s)), 3);
    s = "\x1b]8;;http://x\x1b\\link\x1b]8;;\x1b\\";
    check_int("width ignores osc", (long)tui_width(s, strlen(s)), 4);
    s = "\x1b]0;title\a" "ab";
    check_int("width ignores osc bel", (long)tui_width(s, strlen(s)), 2);
    check_int("width tab", (long)tui_width("a\tb", 3), 6);
    check_int("width cjk string", (long)tui_width("\xE4\xB8\xAD\xE6\x96\x87", 6), 4);
    check_int("width combining string", (long)tui_width("e\xCC\x81", 3), 1);
    check_int("width truncated escape", (long)tui_width("a\x1b[3", 4), 1);
    pass("display width");

    check_int("fit all", (long)tui_fit("hello", 5, 10), 5);
    check_int("fit prefix", (long)tui_fit("hello", 5, 3), 3);
    check_int("fit wide", (long)tui_fit("\xE4\xB8\xAD\xE6\x96\x87", 6, 3), 3);
    check_int("fit wide exact", (long)tui_fit("\xE4\xB8\xAD\xE6\x96\x87", 6, 4), 6);
    s = "\x1b[31mabc";
    check_int("fit keeps escape whole", (long)tui_fit(s, strlen(s), 2), 7);
    check_int("fit zero cols", (long)tui_fit("abc", 3, 0), 0);
    pass("fit");
}

static void lines_eq(const char *what, const tui_lines *l, size_t n, ...)
{
    va_list ap;
    va_start(ap, n);
    if (l->n != n) {
        for (size_t i = 0; i < l->n; i++)
            fprintf(stderr, "  line %zu: \"%s\"\n", i, l->lines[i]);
        fail(what, "got %zu lines want %zu", l->n, n);
    }
    for (size_t i = 0; i < n; i++) {
        const char *want = va_arg(ap, const char *);
        char label[128];
        snprintf(label, sizeof label, "%s line %zu", what, i);
        check_str(label, l->lines[i], want);
    }
    va_end(ap);
}

static void wrap_check(const char *what, const char *text, size_t cols, size_t n, ...)
{
    tui_lines l = {0};
    if (tui_wrap(text, strlen(text), cols, &l) != 0)
        fail(what, "wrap failed");
    va_list ap;
    va_start(ap, n);
    if (l.n != n)
        fail(what, "got %zu lines want %zu", l.n, n);
    for (size_t i = 0; i < n; i++) {
        const char *want = va_arg(ap, const char *);
        char label[128];
        snprintf(label, sizeof label, "%s line %zu", what, i);
        check_str(label, l.lines[i], want);
        if (tui_width(l.lines[i], strlen(l.lines[i])) > cols)
            fail(what, "line %zu wider than %zu", i, cols);
    }
    va_end(ap);
    tui_lines_clear(&l);
}

static void test_wrap(void)
{
    tui_lines l = {0};
    check_int("lines add", tui_lines_add(&l, "abc", 2), 0);
    check_str("lines copy", l.lines[0], "ab");
    tui_lines_clear(&l);
    check_int("lines cleared", (long)l.n, 0);
    pass("lines list");

    wrap_check("wrap short", "hello", 10, 1, "hello");
    wrap_check("wrap empty", "", 10, 1, "");
    wrap_check("wrap newline", "ab\ncd", 10, 2, "ab", "cd");
    wrap_check("wrap trailing newline", "ab\n", 10, 2, "ab", "");
    wrap_check("wrap words", "hello world foo", 11, 2, "hello world", "foo");
    wrap_check("wrap drops spaces at break", "hello   world", 6, 2, "hello", "world");
    wrap_check("wrap hard break", "abcdefghij", 4, 3, "abcd", "efgh", "ij");
    wrap_check("wrap long word after text", "ab cdefghij", 4, 3, "ab", "cdef", "ghij");
    wrap_check("wrap exact fit", "abcd efgh", 4, 2, "abcd", "efgh");
    wrap_check("wrap space at edge", "abcd efgh", 5, 2, "abcd", "efgh");
    wrap_check("wrap tab", "a\tb", 10, 1, "a    b");
    wrap_check("wrap wide", "\xE4\xB8\xAD\xE6\x96\x87\xE5\xAD\x97", 4, 2,
               "\xE4\xB8\xAD\xE6\x96\x87", "\xE5\xAD\x97");
    wrap_check("wrap keeps leading indent", "  ab", 10, 1, "  ab");
    pass("wrap plain");

    wrap_check("wrap sgr carries", "\x1b[31mred green blue\x1b[0m", 9, 2,
               "\x1b[31mred green\x1b[0m", "\x1b[31mblue\x1b[0m");
    wrap_check("wrap sgr reset before break", "\x1b[1mbold\x1b[0m plain text", 10, 2,
               "\x1b[1mbold\x1b[0m plain", "text");
    wrap_check("wrap sgr hard break", "\x1b[32mabcdef", 3, 2, "\x1b[32mabc\x1b[0m", "\x1b[32mdef");
    wrap_check("wrap sgr across newline", "\x1b[4mab\ncd", 10, 2, "\x1b[4mab\x1b[0m", "\x1b[4mcd");
    wrap_check("wrap sgr two styles", "\x1b[1m\x1b[31mab cd", 2, 2,
               "\x1b[1m\x1b[31mab\x1b[0m", "\x1b[1m\x1b[31mcd");
    pass("wrap sgr");

    wrap_check("wrap drops non-SGR csi", "a\x1b[2Jb\x1b[?25lc", 10, 1, "abc");
    wrap_check("wrap drops osc (title) but keeps OSC 8 hyperlinks", "a\x1b]0;title\ab\x1b]8;;u\x1b\\c", 10, 1,
               "ab\x1b]8;;u\x1b\\c");
    wrap_check("wrap closes a hyperlink at a break and reopens it", "\x1b]8;;u\x1b\\abcdef\x1b]8;;\x1b\\", 3, 2,
               "\x1b]8;;u\x1b\\abc\x1b]8;;\x1b\\", "\x1b]8;;u\x1b\\def\x1b]8;;\x1b\\");
    wrap_check("wrap drops ESC x", "a\x1b" "7b", 10, 1, "ab");
    wrap_check("wrap drops C0 controls", "a\rb\bc\ad\x01" "e\x7f", 10, 1, "abcde");
    wrap_check("wrap drops C1 controls", "a\xC2\x85" "b\xC2\x9F", 10, 1, "ab");
    wrap_check("wrap keeps sgr among dropped", "\x1b[1ma\x1b[Kb", 10, 1, "\x1b[1mab");
    check_int("fit stops at newline", (long)tui_fit("ab\ncd", 5, 10), 2);
    pass("wrap sanitizes");
}

/* 1 when HAY has the foreground/background sequence SGR immediately followed by AFTER. */
static int has_after(const char *hay, const char *sgr, const char *after)
{
    char n[256];
    (void)snprintf(n, sizeof n, "%s%s", sgr, after);
    return strstr(hay, n) != NULL;
}

/* ---- key decoder ------------------------------------------------------- */

static const char *key_name(tui_key_kind k)
{
    static const char *names[] = {
        "CHAR", "ENTER", "NEWLINE", "TAB", "BACKSPACE", "DELETE", "LEFT", "RIGHT", "UP", "DOWN",
        "HOME", "END", "PAGEUP", "PAGEDOWN", "WORD_LEFT", "WORD_RIGHT", "DELETE_WORD", "KILL_LINE",
        "KILL_START", "ESC", "CTRL_C", "CTRL_D", "CTRL_L", "CTRL_O", "PASTE", "CTRL_S", "CTRL_P",
        "BACKTAB", "CTRL_T", "DELETE_WORD_FWD", "YANK", "YANK_POP", "UNDO", "JUMP", "JUMP_BACK", "CTRL_G",
        "CTRL_X", "CTRL_Z", "ALT_UP", "CTRL_P_BACK", "ALT_ENTER", "CTRL_HOME", "CTRL_END", "CTRL_V", "MOUSE",
        "OTHER", "ACTION", "HISTORY_PREV", "HISTORY_NEXT",
    };
    return (size_t)k < sizeof names / sizeof names[0] ? names[k] : "?";
}

/* Drains the decoder into a space-separated description. */
static void drain(tui_keys *k, char *out, size_t cap)
{
    size_t o = 0;
    tui_key key;
    out[0] = 0;
    while (tui_keys_next(k, &key)) {
        if (o)
            o += (size_t)snprintf(out + o, cap - o, " ");
        if (key.kind == TUI_KEY_CHAR) {
            o += (size_t)snprintf(out + o, cap - o, "CHAR:%s", key.text);
        } else if (key.kind == TUI_KEY_PASTE) {
            char esc[512];
            show(key.paste, key.paste_len, esc, sizeof esc);
            o += (size_t)snprintf(out + o, cap - o, "PASTE:%s", esc);
            free(key.paste);
        } else {
            o += (size_t)snprintf(out + o, cap - o, "%s", key_name(key.kind));
        }
    }
}

static void decode_check(const char *what, const char *bytes, size_t n, const char *want)
{
    tui_keys *k = tui_keys_new();
    char got[1024];
    tui_keys_feed(k, bytes, n);
    drain(k, got, sizeof got);
    check_str(what, got, want);
    tui_keys_free(k);
}

#define DECODE(what, bytes, want) decode_check(what, bytes, sizeof(bytes) - 1, want)

static void test_decoder(void)
{
    DECODE("printable", "abc", "CHAR:a CHAR:b CHAR:c");
    DECODE("utf8 2-byte", "\xC3\xA9", "CHAR:\xC3\xA9");
    DECODE("utf8 3-byte", "\xE4\xB8\xAD", "CHAR:\xE4\xB8\xAD");
    DECODE("utf8 emoji", "\xF0\x9F\x98\x80", "CHAR:\xF0\x9F\x98\x80");
    DECODE("space", " ", "CHAR: ");
    DECODE("invalid bytes dropped", "\xFF\x80z", "CHAR:z");
    pass("decode printable");

    DECODE("cr", "\r", "ENTER");
    DECODE("lf", "\n", "NEWLINE");
    DECODE("tab", "\t", "TAB");
    DECODE("del", "\x7f", "BACKSPACE");
    DECODE("ctrl-h", "\x08", "BACKSPACE");
    DECODE("ctrl-a", "\x01", "HOME");
    DECODE("ctrl-e", "\x05", "END");
    DECODE("ctrl-c", "\x03", "CTRL_C");
    DECODE("ctrl-d", "\x04", "CTRL_D");
    DECODE("ctrl-k", "\x0b", "KILL_LINE");
    DECODE("ctrl-l", "\x0c", "CTRL_L");
    DECODE("ctrl-o", "\x0f", "CTRL_O");
    DECODE("ctrl-s", "\x13", "CTRL_S");
    DECODE("ctrl-p", "\x10", "CTRL_P");
    DECODE("ctrl-t", "\x14", "CTRL_T");
    DECODE("shift-tab (CSI Z)", "\x1b[Z", "BACKTAB");
    DECODE("ctrl-u", "\x15", "KILL_START");
    DECODE("ctrl-w", "\x17", "DELETE_WORD");
    DECODE("other control keys have no kind of their own", "\x00\x1c", "OTHER");
    pass("decode control keys");

    DECODE("csi arrows", "\x1b[A\x1b[B\x1b[C\x1b[D", "UP DOWN RIGHT LEFT");
    DECODE("ss3 arrows", "\x1bOA\x1bOB\x1bOC\x1bOD", "UP DOWN RIGHT LEFT");
    DECODE("csi home end", "\x1b[H\x1b[F", "HOME END");
    DECODE("ss3 home end", "\x1bOH\x1bOF", "HOME END");
    DECODE("tilde home end", "\x1b[1~\x1b[4~\x1b[7~\x1b[8~", "HOME END HOME END");
    DECODE("delete pgup pgdn", "\x1b[3~\x1b[5~\x1b[6~", "DELETE PAGEUP PAGEDOWN");
    pass("decode navigation");

    DECODE("alt-b alt-f", "\x1b" "b\x1b" "f", "WORD_LEFT WORD_RIGHT");
    DECODE("alt arrows", "\x1b[1;3D\x1b[1;3C", "WORD_LEFT WORD_RIGHT");
    DECODE("ctrl arrows", "\x1b[1;5D\x1b[1;5C", "WORD_LEFT WORD_RIGHT");
    DECODE("shift arrow is plain", "\x1b[1;2D", "LEFT");
    DECODE("alt backspace", "\x1b\x7f", "DELETE_WORD");
    DECODE("alt enter", "\x1b\r", "ALT_ENTER");
    DECODE("alt enter kitty", "\x1b[13;3u", "ALT_ENTER");
    DECODE("alt enter modifyOtherKeys", "\x1b[27;3;13~", "ALT_ENTER");
    DECODE("ctrl+alt enter kitty", "\x1b[13;7u", "ALT_ENTER");
    DECODE("esc then a key", "\x1bx", "ESC CHAR:x");
    DECODE("esc then a command, one read", "\x1b/s\r", "ESC CHAR:/ CHAR:s ENTER");
    pass("decode word keys");

    DECODE("shift-enter kitty", "\x1b[13;2u", "NEWLINE");
    DECODE("shift-enter modifyOtherKeys", "\x1b[27;2;13~", "NEWLINE");
    DECODE("enter kitty plain", "\x1b[13u", "ENTER");
    DECODE("enter kitty mod 1", "\x1b[13;1u", "ENTER");
    pass("decode shift-enter");

    DECODE("unknown csi dropped", "\x1b[99;1Xa", "CHAR:a");
    DECODE("unknown csi with intermediate", "\x1b[?25$pb", "CHAR:b");
    DECODE("esc then csi", "\x1b\x1b[A", "ESC UP");
    pass("decode unknown sequences");

    /* Split sequences: a CSI cut at every byte boundary still decodes. */
    {
        tui_keys *k = tui_keys_new();
        const char seq[] = "\x1b[1;5D";
        char got[128];
        for (size_t i = 0; i + 1 < sizeof seq; i++) {
            tui_keys_feed(k, seq + i, 1);
            if (i + 2 < sizeof seq) {
                drain(k, got, sizeof got);
                check_str("split csi nothing early", got, "");
                check_int("split csi waiting", tui_keys_waiting(k), 1);
            }
        }
        drain(k, got, sizeof got);
        check_str("split csi done", got, "WORD_LEFT");
        check_int("split csi not waiting", tui_keys_waiting(k), 0);
        const char u[] = "\xF0\x9F";
        tui_keys_feed(k, u, 2);
        check_int("split utf8 waiting", tui_keys_waiting(k), 1);
        tui_keys_feed(k, "\x98\x80", 2);
        drain(k, got, sizeof got);
        check_str("split utf8 done", got, "CHAR:\xF0\x9F\x98\x80");
        tui_keys_free(k);
    }
    pass("decode split input");

    {
        tui_keys *k = tui_keys_new();
        char got[128];
        tui_keys_feed(k, "\x1b", 1);
        drain(k, got, sizeof got);
        check_str("lone esc pending", got, "");
        check_int("lone esc waiting", tui_keys_waiting(k), 1);
        tui_keys_flush(k);
        drain(k, got, sizeof got);
        check_str("lone esc flushed", got, "ESC");
        check_int("lone esc done", tui_keys_waiting(k), 0);

        tui_keys_feed(k, "\x1b[", 2);
        check_int("unfinished csi waiting", tui_keys_waiting(k), 1);
        for (int i = 0; i < 2; i++) {
            tui_keys_flush(k);
            check_int("unfinished csi kept through flush", tui_keys_waiting(k), 1);
        }
        tui_keys_feed(k, "A", 1);
        drain(k, got, sizeof got);
        check_str("late rest completes the csi", got, "UP");
        tui_keys_feed(k, "\x1b[", 2);
        for (int i = 0; i < 3; i++)
            tui_keys_flush(k);
        drain(k, got, sizeof got);
        check_str("unfinished csi dropped after 3 flushes", got, "");
        check_int("unfinished csi done", tui_keys_waiting(k), 0);
        tui_keys_feed(k, "\xE4\xB8", 2);
        tui_keys_flush(k);
        tui_keys_feed(k, "\xAD", 1);
        drain(k, got, sizeof got);
        check_str("utf8 split across a flush", got, "CHAR:\xE4\xB8\xAD");

        tui_keys_feed(k, "\x1b", 1);
        tui_keys_feed(k, "[A", 2);
        drain(k, got, sizeof got);
        check_str("esc then rest is a key", got, "UP");
        tui_keys_free(k);
    }
    pass("lone esc");

    DECODE("paste", "\x1b[200~hello\x1b[201~", "PASTE:hello");
    DECODE("paste crlf", "\x1b[200~a\r\nb\rc\nd\x1b[201~", "PASTE:a\\nb\\nc\\nd");
    DECODE("paste keeps escapes inside", "\x1b[200~x\x1b[Ay\x1b[201~", "PASTE:x\\e[Ay");
    DECODE("paste empty", "\x1b[200~\x1b[201~", "PASTE:");
    DECODE("keys around paste", "a\x1b[200~b\x1b[201~c", "CHAR:a PASTE:b CHAR:c");
    {
        tui_keys *k = tui_keys_new();
        char got[256];
        const char *parts[] = {"\x1b[20", "0~line1\r", "\nline2\x1b", "[20", "1", "~z"};
        for (size_t i = 0; i < sizeof parts / sizeof parts[0]; i++) {
            tui_keys_feed(k, parts[i], strlen(parts[i]));
            drain(k, got, sizeof got);
            if (i < 5)
                check_str("paste split quiet", got, "");
            else
                check_str("paste split done", got, "PASTE:line1\\nline2 CHAR:z");
        }
        /* a lone ESC inside a paste is not flushed away */
        tui_keys_feed(k, "\x1b[200~ab\x1b", 9);
        check_int("paste not waiting", tui_keys_waiting(k), 0);
        tui_keys_flush(k);
        tui_keys_feed(k, "[201~", 5);
        drain(k, got, sizeof got);
        check_str("paste survives flush", got, "PASTE:ab");
        tui_keys_free(k);
    }
    pass("decode bracketed paste");
}

/* ---- render ------------------------------------------------------------ */

static int rfd[2];

static void render_expect(const char *what, const char *want)
{
    char got[4096];
    ssize_t n = read(rfd[0], got, sizeof got - 1);
    if (n < 0)
        n = 0;
    got[n] = 0;
    check_str(what, got, want);
    if (read(rfd[0], got, 1) > 0)
        fail(what, "extra output after the expected frame");
}

static void test_render(void)
{
    if (pipe(rfd) != 0)
        fail("render", "pipe");
    int fl = fcntl(rfd[0], F_GETFL);
    fcntl(rfd[0], F_SETFL, fl | O_NONBLOCK);
    tui_render *r = tui_render_new(rfd[1]);

    const char *ab[] = {"a", "b"};
    tui_render_draw(r, ab, 2, 1, 3, 24);
    render_expect("first draw", SYNC_ON HIDE "a\r\nb" "\r" "\x1b[4G" SHOW SYNC_OFF);

    const char *abc[] = {"a", "b", "c"};
    tui_render_draw(r, abc, 3, 2, 0, 24);
    render_expect("append writes only the new line", SYNC_ON HIDE "\r\nc" "\r" SHOW SYNC_OFF);

    const char *aXc[] = {"a", "X", "c"};
    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("middle change", SYNC_ON HIDE "\x1b[1A" "\r\x1b[J" "X\r\nc" "\r\x1b[2G" SHOW SYNC_OFF);

    tui_render_draw(r, aXc, 3, 0, 0, 24);
    render_expect("identical lines move only the cursor", SYNC_ON HIDE "\x1b[2A" "\r" SHOW SYNC_OFF);

    const char *aX[] = {"a", "X"};
    tui_render_draw(r, aX, 2, 1, 0, 24);
    render_expect("shrink", SYNC_ON HIDE "\x1b[2B" "\r\x1b[J" "\x1b[1A" "\r" SHOW SYNC_OFF);
    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("regrow", SYNC_ON HIDE "\r\n" "c" "\r\x1b[2G" SHOW SYNC_OFF);

    const char *done[] = {"done"};
    tui_render_commit(r, done, 1);
    render_expect("commit", SYNC_ON HIDE "\x1b[2A" "\r\x1b[J" "done\r\n" "a\r\nX\r\nc" "\r\x1b[2G" SHOW SYNC_OFF);

    tui_render_invalidate(r);
    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("invalidate redraws everything",
                  SYNC_ON HIDE "\x1b[2A" "\r\x1b[J" "a\r\nX\r\nc" "\r\x1b[2G" SHOW SYNC_OFF);

    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("no redraw after invalidate is consumed", SYNC_ON HIDE "\r" "\x1b[2G" SHOW SYNC_OFF);

    const char *many[] = {"l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7", "l8", "l9"};
    tui_render_draw(r, many, 10, 9, 1, 4);
    render_expect("more lines than rows keeps the last rows-1",
                  SYNC_ON HIDE "\x1b[2A" "\r\x1b[J" "l7\r\nl8\r\nl9" "\r\x1b[2G" SHOW SYNC_OFF);
    tui_render_draw(r, many, 10, -1, 0, 4);
    render_expect("hidden cursor stays hidden", SYNC_ON HIDE SYNC_OFF);

    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("redraw after clip", SYNC_ON HIDE "\x1b[2A" "\r\x1b[J" "a\r\nX\r\nc" "\r\x1b[2G" SHOW SYNC_OFF);
    tui_render_invalidate(r);
    tui_render_commit(r, done, 1);
    render_expect("commit while invalid does not redraw old lines",
                  SYNC_ON HIDE "\x1b[2A" "\r\x1b[J" "done\r\n" SHOW SYNC_OFF);
    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("draw after invalid commit rewrites fully",
                  SYNC_ON HIDE "a\r\nX\r\nc" "\r\x1b[2G" SHOW SYNC_OFF);

    tui_render_finish(r);
    render_expect("finish", "\r\n" SHOW);
    tui_render_free(r);

    /* A row that wraps: no line break after it, and it is rewritten with the row it runs into. */
    r = tui_render_new(rfd[1]);
    {
        const char *w1[] = {"t", ("aaaa" TUI_ROW_WRAPS), "bb", "k"};
        const char *w2[] = {"t", ("aaaa" TUI_ROW_WRAPS), "cc", "k"};
        tui_render_draw(r, w1, 4, -1, 0, 24);
        render_expect("a wrapping row has no line break after it", SYNC_ON HIDE "t\r\naaaa" TUI_ROW_WRAPS "bb\r\nk" SYNC_OFF);
        tui_render_draw(r, w2, 4, -1, 0, 24);
        render_expect("its continuation changed: both rows are written again",
                      SYNC_ON HIDE "\x1b[2A" "\r\x1b[J" "aaaa" TUI_ROW_WRAPS "cc\r\nk" SYNC_OFF);
    }
    tui_render_finish(r);
    render_expect("finish after a wrapped row", "\r\n" SHOW);
    tui_render_free(r);

    /* An empty live area: commit just writes the lines. */
    r = tui_render_new(rfd[1]);
    tui_render_commit(r, done, 1);
    render_expect("commit with empty live area", SYNC_ON HIDE "done\r\n" SHOW SYNC_OFF);
    tui_render_free(r);

    /* A closed fd reports an error. */
    r = tui_render_new(-1);
    check_int("write error", tui_render_draw(r, ab, 2, 0, 0, 24), -1);
    tui_render_free(r);
    close(rfd[0]);
    close(rfd[1]);
    pass("render");
}

/* ---- editor ------------------------------------------------------------ */

static int press(tui_editor *e, tui_key_kind kind)
{
    tui_key k;
    memset(&k, 0, sizeof k);
    k.kind = kind;
    return tui_editor_key(e, &k);
}

static void type(tui_editor *e, const char *s)
{
    while (*s) {
        uint32_t cp;
        size_t n = tui_utf8_decode(s, strlen(s), &cp);
        tui_key k;
        memset(&k, 0, sizeof k);
        k.kind = TUI_KEY_CHAR;
        memcpy(k.text, s, n);
        tui_editor_key(e, &k);
        s += n;
    }
}

static void paste_text(tui_editor *e, const char *s)
{
    tui_key k;
    memset(&k, 0, sizeof k);
    k.kind = TUI_KEY_PASTE;
    k.paste = (char *)(uintptr_t)s;
    k.paste_len = strlen(s);
    tui_editor_key(e, &k);
}

/* The editor's text, "|" marking nothing: read it with take on a copy. */
static char *text_of(tui_editor *e)
{
    tui_lines l = {0};
    int row, col;
    tui_editor_render(e, 1000, &l, &row, &col);
    size_t cap = 1;
    for (size_t i = 0; i < l.n; i++)
        cap += strlen(l.lines[i]) + 1;
    char *out = calloc(cap, 1);
    for (size_t i = 0; i < l.n; i++) {
        if (i)
            strcat(out, "\n");
        strcat(out, l.lines[i] + 2);
    }
    tui_lines_clear(&l);
    return out;
}

static void text_is(const char *what, tui_editor *e, const char *want)
{
    char *t = text_of(e);
    check_str(what, t, want);
    free(t);
}

static void cursor_is(const char *what, tui_editor *e, size_t cols, int want_row, int want_col)
{
    tui_lines l = {0};
    int row, col;
    if (tui_editor_render(e, cols, &l, &row, &col) != 0)
        fail(what, "render failed");
    if (row != want_row || col != want_col)
        fail(what, "cursor at %d,%d want %d,%d", row, col, want_row, want_col);
    tui_lines_clear(&l);
}

static void take_is(const char *what, tui_editor *e, const char *want)
{
    char *t = tui_editor_take(e);
    if (!t)
        fail(what, "take returned NULL");
    check_str(what, t, want);
    free(t);
}

static void test_editor(void)
{
    tui_editor *e = tui_editor_new();
    check_int("new is empty", tui_editor_empty(e), 1);
    type(e, "hello");
    text_is("typing", e, "hello");
    check_int("typing makes it non-empty", tui_editor_empty(e), 0);
    check_int("enter submits", press(e, TUI_KEY_ENTER), TUI_EDIT_SUBMIT);
    take_is("take returns text", e, "hello");
    check_int("empty after take", tui_editor_empty(e), 1);
    check_int("empty enter ignored", press(e, TUI_KEY_ENTER), TUI_EDIT_NONE);
    type(e, "  ");
    check_int("blank enter ignored", press(e, TUI_KEY_ENTER), TUI_EDIT_NONE);
    check_int("typing reports changed", press(e, TUI_KEY_NEWLINE), TUI_EDIT_CHANGED);
    check_int("blank multi-line enter ignored", press(e, TUI_KEY_ENTER), TUI_EDIT_NONE);
    check_int("unhandled key", press(e, TUI_KEY_CTRL_C), TUI_EDIT_NONE);
    check_int("tab not handled", press(e, TUI_KEY_TAB), TUI_EDIT_NONE);
    tui_editor_clear(e);
    pass("editor type and submit");

    type(e, "ab");
    press(e, TUI_KEY_NEWLINE);
    type(e, "cd");
    text_is("newline", e, "ab\ncd");
    press(e, TUI_KEY_HOME);
    check_int("backspace joins lines", press(e, TUI_KEY_BACKSPACE), TUI_EDIT_CHANGED);
    text_is("joined", e, "abcd");
    cursor_is("cursor after join", e, 80, 0, 4);
    press(e, TUI_KEY_BACKSPACE);
    text_is("backspace", e, "acd");
    press(e, TUI_KEY_DELETE);
    text_is("delete", e, "ad");
    press(e, TUI_KEY_HOME);
    check_int("backspace at start", press(e, TUI_KEY_BACKSPACE), TUI_EDIT_NONE);
    press(e, TUI_KEY_END);
    check_int("delete at end", press(e, TUI_KEY_DELETE), TUI_EDIT_NONE);
    tui_editor_clear(e);
    type(e, "a\xC3\xA9\xE4\xB8\xAD");
    press(e, TUI_KEY_BACKSPACE);
    text_is("backspace removes a whole UTF-8 char", e, "a\xC3\xA9");
    press(e, TUI_KEY_LEFT);
    press(e, TUI_KEY_DELETE);
    text_is("delete removes a whole UTF-8 char", e, "a");
    tui_editor_clear(e);
    pass("editor backspace and delete");

    tui_editor_free(e); /* a fresh editor: no history yet */
    e = tui_editor_new();
    type(e, "one");
    press(e, TUI_KEY_NEWLINE);
    type(e, "two2");
    press(e, TUI_KEY_NEWLINE);
    type(e, "x");
    check_int("up moves", press(e, TUI_KEY_UP), TUI_EDIT_CHANGED);
    check_int("up again", press(e, TUI_KEY_UP), TUI_EDIT_CHANGED);
    check_int("up on first line without history", press(e, TUI_KEY_UP), TUI_EDIT_NONE);
    cursor_is("up keeps the column (clamped)", e, 80, 0, 3);
    press(e, TUI_KEY_END);
    press(e, TUI_KEY_DOWN);
    cursor_is("down into a longer line", e, 80, 1, 5);
    press(e, TUI_KEY_DOWN);
    cursor_is("down into a shorter line", e, 80, 2, 3);
    press(e, TUI_KEY_UP);
    cursor_is("goal column is remembered", e, 80, 1, 5);
    for (int i = 0; i < 4; i++)
        press(e, TUI_KEY_LEFT);
    cursor_is("left crosses a line break", e, 80, 0, 5);
    press(e, TUI_KEY_RIGHT);
    cursor_is("right crosses a line break", e, 80, 1, 2);
    tui_editor_clear(e);
    pass("editor vertical movement");

    type(e, "first");
    take_is("take first", e, "first");
    type(e, "second");
    take_is("take second", e, "second");
    type(e, "draft");
    check_int("up into history", press(e, TUI_KEY_UP), TUI_EDIT_CHANGED);
    text_is("newest entry", e, "second");
    press(e, TUI_KEY_UP);
    text_is("older entry", e, "first");
    check_int("up past the oldest", press(e, TUI_KEY_UP), TUI_EDIT_NONE);
    text_is("still the oldest", e, "first");
    press(e, TUI_KEY_DOWN);
    text_is("back to newer", e, "second");
    press(e, TUI_KEY_DOWN);
    text_is("unsent text restored", e, "draft");
    check_int("down past the newest", press(e, TUI_KEY_DOWN), TUI_EDIT_NONE);
    tui_editor_clear(e);
    type(e, "second");
    take_is("no repeat of last entry", e, "second");
    press(e, TUI_KEY_UP);
    press(e, TUI_KEY_UP);
    text_is("history has no duplicate", e, "first");
    tui_editor_clear(e);
    for (int i = 0; i < 210; i++) {
        char b[16];
        snprintf(b, sizeof b, "m%d", i);
        type(e, b);
        take_is("fill history", e, b);
    }
    for (int i = 0; i < 300; i++)
        press(e, TUI_KEY_UP);
    text_is("history capped at 200", e, "m10");
    tui_editor_clear(e);
    pass("editor history");

    type(e, "foo bar  baz");
    press(e, TUI_KEY_WORD_LEFT);
    cursor_is("word left", e, 80, 0, 11);
    press(e, TUI_KEY_WORD_LEFT);
    cursor_is("word left again", e, 80, 0, 6);
    press(e, TUI_KEY_WORD_RIGHT);
    cursor_is("word right", e, 80, 0, 9);
    press(e, TUI_KEY_DELETE_WORD);
    text_is("delete word", e, "foo   baz");
    press(e, TUI_KEY_HOME);
    press(e, TUI_KEY_WORD_RIGHT);
    cursor_is("word right from start", e, 80, 0, 5);
    press(e, TUI_KEY_KILL_LINE);
    text_is("kill line", e, "foo");
    tui_editor_set(e, "abc\ndef");
    press(e, TUI_KEY_UP);
    press(e, TUI_KEY_END);
    press(e, TUI_KEY_KILL_LINE);
    text_is("kill line at end joins next", e, "abcdef");
    press(e, TUI_KEY_RIGHT);
    press(e, TUI_KEY_KILL_START);
    text_is("kill start", e, "ef");
    tui_editor_set(e, "ab\ncd");
    press(e, TUI_KEY_HOME);
    press(e, TUI_KEY_KILL_START);
    text_is("kill start at line start joins previous", e, "abcd");
    pass("editor word moves and kills");

    tui_editor_clear(e);
    paste_text(e, "short\npaste");
    text_is("small paste literal", e, "short\npaste");
    tui_editor_clear(e);
    check_int("empty after clear", tui_editor_empty(e), 1);

    char big[256] = "";
    for (int i = 1; i <= 20; i++) {
        char l[16];
        snprintf(l, sizeof l, "line%d%s", i, i < 20 ? "\n" : "");
        strcat(big, l);
    }
    type(e, "x ");
    paste_text(e, big);
    text_is("big paste collapsed", e, "x [paste #1 +20 lines]");
    type(e, " y");
    check_int("marker plus text can submit", press(e, TUI_KEY_ENTER), TUI_EDIT_SUBMIT);
    char *taken = tui_editor_take(e);
    char want[320];
    snprintf(want, sizeof want, "x %s y", big);
    check_str("take expands marker", taken, want);
    free(taken);

    paste_text(e, big);
    text_is("numbering restarts after submit", e, "[paste #1 +20 lines]");
    paste_text(e, big);
    text_is("second paste", e, "[paste #1 +20 lines][paste #2 +20 lines]");
    check_int("backspace on marker", press(e, TUI_KEY_BACKSPACE), TUI_EDIT_CHANGED);
    text_is("marker removed whole", e, "[paste #1 +20 lines]");
    press(e, TUI_KEY_HOME);
    press(e, TUI_KEY_DELETE);
    text_is("delete removes a whole marker", e, "");
    check_int("paste table cleared on removal still safe", tui_editor_empty(e), 1);

    /* cursor moves jump over a marker whole */
    tui_editor_clear(e);
    type(e, "ab");
    paste_text(e, big);
    type(e, "cd");
    for (int i = 0; i < 3; i++)
        press(e, TUI_KEY_LEFT);
    cursor_is("left from after marker lands before it", e, 80, 0, 4);
    press(e, TUI_KEY_RIGHT);
    cursor_is("right from before marker lands after it", e, 80, 0, 2 + 2 + 20);
    press(e, TUI_KEY_LEFT);
    type(e, "X");
    press(e, TUI_KEY_WORD_RIGHT);
    cursor_is("word right does not stop inside the marker", e, 80, 0, 2 + 3 + 20);
    press(e, TUI_KEY_WORD_LEFT);
    cursor_is("word left does not stop inside the marker", e, 80, 0, 2 + 3);
    press(e, TUI_KEY_RIGHT);
    press(e, TUI_KEY_RIGHT);
    type(e, "Y");
    taken = tui_editor_take(e);
    snprintf(want, sizeof want, "abX%scYd", big);
    check_str("typing beside a marker keeps it expandable", taken, want);
    free(taken);
    tui_editor_clear(e);
    paste_text(e, big);
    type(e, "\nabcdefghijklmnopqrstuvwxyz");
    press(e, TUI_KEY_UP);
    press(e, TUI_KEY_END);
    press(e, TUI_KEY_DOWN);
    press(e, TUI_KEY_UP);
    press(e, TUI_KEY_LEFT);
    type(e, "Q");
    taken = tui_editor_take(e);
    snprintf(want, sizeof want, "Q%s\nabcdefghijklmnopqrstuvwxyz", big);
    check_str("up/down never land inside a marker", taken, want);
    free(taken);
    tui_editor_clear(e);

    char *chars = malloc(1201);
    memset(chars, 'z', 1200);
    chars[1200] = 0;
    paste_text(e, chars);
    text_is("long single line collapsed ", e, "[paste #1 1200 chars]");
    taken = tui_editor_take(e);
    check_str("long paste expands", taken, chars);
    free(taken);
    free(chars);
    paste_text(e, "[paste #1 +20 lines]");
    take_is("typed lookalike marker is literal", e, "[paste #1 +20 lines]");
    tui_editor_clear(e);
    pass("editor paste markers");

    tui_editor_clear(e);
    tui_editor_set(e, "hello");
    cursor_is("set puts cursor at end", e, 80, 0, 7);
    tui_lines l = {0};
    int row, col;
    check_int("render ok", tui_editor_render(e, 80, &l, &row, &col), 0);
    lines_eq("render one line", &l, 1, "> hello");
    tui_lines_clear(&l);

    tui_editor_set(e, "aaa bbb ccc");
    check_int("render wrapped", tui_editor_render(e, 10, &l, &row, &col), 0);
    lines_eq("wrapped lines", &l, 2, "> aaa bbb", "  ccc");
    check_int("wrapped cursor row", row, 1);
    check_int("wrapped cursor col", col, 5);
    tui_lines_clear(&l);

    tui_editor_set(e, "ab\ncd");
    tui_editor_render(e, 80, &l, &row, &col);
    lines_eq("render multi-line prefixes", &l, 2, "> ab", "  cd");
    tui_lines_clear(&l);

    tui_editor_set(e, "\xE4\xB8\xAD\xE6\x96\x87x");
    cursor_is("cursor after wide chars", e, 80, 0, 7);
    press(e, TUI_KEY_LEFT);
    cursor_is("cursor between wide and narrow", e, 80, 0, 6);
    press(e, TUI_KEY_LEFT);
    cursor_is("cursor between wide chars", e, 80, 0, 4);

    tui_editor_set(e, "\xE4\xB8\xAD\xE6\x96\x87\xE5\xAD\x97\xE5\xAD\x97");
    tui_editor_render(e, 9, &l, &row, &col); /* wrap width 6: three wide chars a row */
    lines_eq("wide chars wrap", &l, 2, "> \xE4\xB8\xAD\xE6\x96\x87\xE5\xAD\x97", "  \xE5\xAD\x97");
    check_int("wide wrap cursor row", row, 1);
    check_int("wide wrap cursor col", col, 4);
    tui_lines_clear(&l);

    tui_editor_set(e, "abcdefgh");
    tui_editor_render(e, 8, &l, &row, &col); /* wrap width 5 */
    lines_eq("hard wrap in editor", &l, 2, "> abcde", "  fgh");
    check_int("cursor at end after hard wrap row", row, 1);
    check_int("cursor at end after hard wrap col", col, 5);
    tui_lines_clear(&l);
    tui_editor_set(e, "abcde");
    cursor_is("cursor at end of a full line stays on screen", e, 8, 0, 7);

    tui_editor_set(e, "ab\ncd");
    press(e, TUI_KEY_LEFT);
    check_str("text accessor", tui_editor_text(e), "ab\ncd");
    check_int("cursor accessor", (long)tui_editor_cursor(e), 4);
    tui_editor_clear(e);
    check_str("text accessor empty", tui_editor_text(e), "");
    check_int("cursor accessor empty", (long)tui_editor_cursor(e), 0);
    paste_text(e, big);
    check_str("text accessor shows the marker", tui_editor_text(e), "[paste #1 +20 lines]");
    check_int("cursor after marker", (long)tui_editor_cursor(e), 20);

    tui_editor_set(e, "ab\n");
    cursor_is("cursor on trailing empty line", e, 80, 1, 2);
    tui_editor_set(e, "");
    cursor_is("cursor in empty editor", e, 80, 0, 2);
    tui_editor_free(e);
    pass("editor render");
}

static void near(const char *what, double got, double want)
{
    if (got < want - 0.001 || got > want + 0.001)
        fail(what, "got %f want %f", got, want);
}

static void order_is(const char *what, const char *query, const char *const *items, size_t n, size_t want_n, ...)
{
    size_t order[16];
    size_t got = tui_fuzzy_filter(query, items, n, order);
    va_list ap;
    va_start(ap, want_n);
    if (got != want_n)
        fail(what, "got %zu matches want %zu", got, want_n);
    for (size_t i = 0; i < want_n; i++) {
        size_t w = va_arg(ap, size_t);
        if (order[i] != w)
            fail(what, "rank %zu is item %zu want %zu", i, order[i], w);
    }
    va_end(ap);
}

static void test_fuzzy(void)
{
    double s;
    check_int("match yes", tui_fuzzy_match("son", "claude-sonnet-5-5", &s), 1);
    near("score at a word boundary", s, -22.6); /* -10+.7, -5+.8, -10+.9 */
    check_int("match no", tui_fuzzy_match("son", "gpt-5-nano", &s), 0);
    check_int("empty query matches", tui_fuzzy_match("", "abc", &s), 1);
    near("empty query scores 0", s, 0);
    check_int("query longer than text", tui_fuzzy_match("abcd", "abc", &s), 0);
    check_int("case folded", tui_fuzzy_match("SON", "Claude-Sonnet", &s), 1);
    near("exact match bonus", (tui_fuzzy_match("sonnet", "sonnet", &s), s), -213.5);
    check_int("digits and letters swapped", tui_fuzzy_match("nano5", "gpt-5-nano", &s), 1);
    near("swapped match costs 5", s, -39.6); /* "5nano" scores -44.6 there */
    near("first character at index 0 also counts as consecutive (as in Pi)",
         (tui_fuzzy_match("son", "sonnet", &s), s), -39.7);
    pass("fuzzy match");

    const char *models[] = {"gpt-5-nano", "claude-sonnet-5-5", "sonnet", "deepseek/deepseek-v4-flash", "xsonx"};
    order_is("son ranking", "son", models, 5, 3, (size_t)2, (size_t)1, (size_t)4);
    const char *anth[] = {"anthropic/claude-haiku-4-5", "claude-haiku", "anthropic/claude-sonnet", "anth-haiku"};
    order_is("multi-token query", "anth haiku", anth, 4, 2, (size_t)3, (size_t)0);
    order_is("slash separates tokens", "anth/haiku", anth, 4, 2, (size_t)3, (size_t)0);
    order_is("no match", "zzz", models, 5, 0);
    order_is("empty query keeps order", "", models, 5, 5, (size_t)0, (size_t)1, (size_t)2, (size_t)3, (size_t)4);
    order_is("blank query keeps order", "  \t ", models, 5, 5, (size_t)0, (size_t)1, (size_t)2, (size_t)3, (size_t)4);
    const char *ties[] = {"axb", "azb", "a-b"};
    order_is("ties keep input order", "ab", ties, 3, 3, (size_t)2, (size_t)0, (size_t)1);
    pass("fuzzy filter");
}

/* ---- view: tool blocks, diffs, footer ---------------------------------- */

/* SGR sequences removed, for comparing text. */
static void plain(const char *s, char *out, size_t cap)
{
    size_t o = 0;
    for (; *s && o + 1 < cap; s++) {
        if (*s == 0x1b && s[1] == '[') {
            s += 2;
            while (*s && !(*s >= '@' && *s <= '~'))
                s++;
            if (!*s)
                break;
        } else {
            out[o++] = *s;
        }
    }
    out[o] = '\0';
}

static void plain_line_is(const char *what, const tui_lines *l, size_t i, const char *want)
{
    char p[512];
    if (i >= l->n)
        fail(what, "no line %zu (%zu lines)", i, l->n);
    plain(l->lines[i], p, sizeof p);
    check_str(what, p, want);
}

static void test_view(void)
{
    char buf[512];
    char *d;
    tui_lines l = {NULL, 0, 0};

    tui_fmt_duration(4200, buf, sizeof buf);
    check_str("duration seconds", buf, "4.2s");
    tui_fmt_duration(0, buf, sizeof buf);
    check_str("duration zero", buf, "0.0s");
    tui_fmt_duration(65000, buf, sizeof buf);
    check_str("duration minutes", buf, "1m 5s");
    tui_fmt_duration(3723000, buf, sizeof buf);
    check_str("duration hours", buf, "1h 2m 3s");
    tui_fmt_tokens(999, buf, sizeof buf);
    check_str("tokens small", buf, "999");
    tui_fmt_tokens(1500, buf, sizeof buf);
    check_str("tokens k", buf, "1.5k");
    tui_fmt_tokens(15400, buf, sizeof buf);
    check_str("tokens rounded k", buf, "15k");
    tui_fmt_tokens(2500000, buf, sizeof buf);
    check_str("tokens M", buf, "2.5M");
    tui_fmt_size(12, buf, sizeof buf);
    check_str("size bytes", buf, "12B");
    tui_fmt_size(1536, buf, sizeof buf);
    check_str("size KB", buf, "1.5KB");
    pass("view: durations, tokens, sizes");

    d = tui_diff_text("a\nb\nc\nd\ne\n", "a\nb\nX\nY\nd\ne\n");
    check_str("diff", d, " a\n b\n-c\n+X\n+Y\n d\n e");
    free(d);
    d = tui_diff_text("one\ntwo", "one\ntwo");
    check_str("equal texts: no diff", d, "");
    free(d);
    d = tui_diff_text("x", "y");
    check_str("diff of one line", d, "-x\n+y");
    free(d);
    d = tui_diff_text("", "new\n");
    check_str("diff from nothing", d, "+new");
    free(d);
    d = tui_diff_numbered("b\nc\n", "b\nX\nY\n", 9, 9, 2);
    check_str("numbered diff", d, "  9 b\n-10 c\n+10 X\n+11 Y");
    free(d);
    pass("view: edit diff");

    {
        tui_tool t = {"edit", "t.txt", "-x\n+y", "Successfully replaced 1 block(s) in t.txt.", TUI_TOOL_OK, 4200, NULL};
        tui_tool_lines(&t, 0, 40, &l);
        plain_line_is("edit header", &l, 0, "\xe2\x9c\x93 edit t.txt");
        plain_line_is("diff removed", &l, 1, "  -x");
        plain_line_is("diff added", &l, 2, "  +y");
        plain_line_is("took", &l, 3, "  Took 4.2s");
        check_int("edit success hides the result text", (long)l.n, 4);
        if (!strstr(l.lines[1], tui_fg(TUI_T_TOOL_DIFF_REMOVED)) || !strstr(l.lines[2], tui_fg(TUI_T_TOOL_DIFF_ADDED)))
            fail("diff colours", "removed %s added %s", l.lines[1], l.lines[2]);
        tui_lines_clear(&l);
    }
    {
        tui_tool t = {"bash", "$ seq 1 12", NULL, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n", TUI_TOOL_OK, 300, NULL};
        tui_tool_lines(&t, 0, 60, &l);
        plain_line_is("bash header", &l, 0, "\xe2\x9c\x93 $ seq 1 12");
        plain_line_is("bash hint", &l, 1, "  ... (7 earlier lines, ctrl+o to expand)");
        plain_line_is("bash keeps the last lines", &l, 2, "  8");
        plain_line_is("bash last", &l, 6, "  12");
        plain_line_is("bash took", &l, 7, "  Took 0.3s");
        tui_lines_clear(&l);
        tui_tool_lines(&t, 1, 60, &l);
        check_int("expanded shows everything", (long)l.n, 1 + 12 + 1);
        plain_line_is("expanded first", &l, 1, "  1");
        tui_lines_clear(&l);
    }
    {
        tui_tool t = {"read", "f.c", NULL, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n", TUI_TOOL_OK, -1, NULL};
        tui_tool_lines(&t, 0, 60, &l);
        plain_line_is("read keeps the first lines", &l, 1, "  1");
        plain_line_is("read hint", &l, 11, "  ... (3 more lines, ctrl+o to expand)");
        check_int("no duration, no line", (long)l.n, 12);
        tui_lines_clear(&l);
    }
    {
        tui_tool t = {"bash", "$ false", NULL, "boom", TUI_TOOL_ERROR, 10, NULL};
        tui_tool_lines(&t, 0, 60, &l);
        plain_line_is("error header", &l, 0, "\xe2\x9c\x97 $ false");
        if (!strstr(l.lines[0], tui_fg(TUI_T_ERROR)) || !strstr(l.lines[1], tui_fg(TUI_T_ERROR)))
            fail("error colour", "%s | %s", l.lines[0], l.lines[1]);
        tui_tool_lines(&(tui_tool){"bash", "$ sleep 5", NULL, NULL, TUI_TOOL_PENDING, 1200, NULL}, 0, 60, &l);
        plain_line_is("pending header", &l, 3, "\xe2\x97\x8f $ sleep 5");
        plain_line_is("pending elapsed", &l, 4, "  Elapsed 1.2s");
        tui_lines_clear(&l);
    }
    {
        /* write shows the file it wrote, as Pi's write renderer does: the first
         * 10 lines, then how many more of how many; the result only on error */
        char content[200] = "";
        for (int i = 1; i <= 12; i++)
            snprintf(content + strlen(content), sizeof content - strlen(content), "w%d\n", i);
        tui_tool w = {"write", "f.txt (12 lines, 36B)", NULL, "Successfully wrote to f.txt", TUI_TOOL_OK, -1, content};
        tui_lines_clear(&l);
        tui_tool_lines(&w, 0, 60, &l);
        plain_line_is("write: first line", &l, 1, "  w1");
        plain_line_is("write: tenth line", &l, 10, "  w10");
        plain_line_is("write: hint", &l, 11, "  ... (2 more lines, 12 total, ctrl+o to expand)");
        check_int("write: no result", (int)l.n, 12);
        tui_lines_clear(&l);
        tui_tool_lines(&w, 1, 60, &l);
        plain_line_is("write expanded: last line", &l, 12, "  w12");
        tui_lines_clear(&l);
        w.state = TUI_TOOL_ERROR;
        w.output = "permission denied";
        tui_tool_lines(&w, 0, 60, &l);
        plain_line_is("write error: the error", &l, 1, "  permission denied");
        tui_lines_clear(&l);
    }
    pass("view: tool blocks");

    {
        tui_footer f = {1500, 200, 300, 40, 140000, 200000, "m", "high", 0, 0, NULL, NULL, NULL};
        tui_footer_stats(&f, 60, buf, sizeof buf);
        {
            char p[512];
            plain(buf, p, sizeof p);
            check_str("footer", p, "\xe2\x86\x91" "1.5k \xe2\x86\x93" "200 R300 W40 70.0%/200k                      m \xe2\x80\xa2 high");
            if (strstr(buf, tui_fg(TUI_T_WARNING)) || strstr(buf, tui_fg(TUI_T_ERROR)))
                fail("footer at 70%", "coloured: %s", buf);
        }
        f.cost = 0.0123;
        tui_footer_stats(&f, 60, buf, sizeof buf);
        {
            char p[512];
            plain(buf, p, sizeof p);
            if (!strstr(p, "W40 $0.012 70.0%/200k"))
                fail("footer cost", "not after the cache counts: %s", p);
        }
        f.cost = 0;
        f.context = 140001;
        tui_footer_stats(&f, 60, buf, sizeof buf);
        if (!has_after(buf, tui_fg(TUI_T_WARNING), "70.0%/200k"))
            fail("footer past 70%", "not the warning colour: %s", buf);
        f.context = 190000;
        f.level = "off";
        f.in = f.out = f.cache_read = f.cache_write = 0;
        tui_footer_stats(&f, 60, buf, sizeof buf);
        if (!has_after(buf, tui_fg(TUI_T_ERROR), "95.0%/200k"))
            fail("footer past 90%", "not the error colour: %s", buf);
        {
            char p[512];
            plain(buf, p, sizeof p);
            check_str("footer: only the percentage, thinking off", p, "95.0%/200k                                  m \xe2\x80\xa2 thinking off");
        }
        f.level = NULL;
        tui_footer_stats(&f, 12, buf, sizeof buf);
        {
            char p[512];
            plain(buf, p, sizeof p);
            if (tui_width(p, strlen(p)) > 12)
                fail("footer fits", "%zu columns: %s", tui_width(p, strlen(p)), p);
        }
    }
    tui_footer_where("/home/u/proj", "/home/u", "main", "work", 0, buf, sizeof buf);
    check_str("where", buf, "~/proj (main) \xe2\x80\xa2 work");
    tui_footer_where("/srv/x", "/home/u", NULL, "", 0, buf, sizeof buf);
    check_str("where without branch or name", buf, "/srv/x");
    tui_footer_where("/home/user2", "/home/user", NULL, "", 0, buf, sizeof buf);
    check_str("home is a whole path component", buf, "/home/user2");
    /* a long path gives way from the left: the directory, branch and name stay */
    tui_footer_where("/home/u/a/very/long/path/to/the/project", "/home/u", "main", "work", 30, buf, sizeof buf);
    check_str("where: long path shortened on the left", buf, "\xe2\x80\xa6/to/the/project (main) \xe2\x80\xa2 work");
    check_int("where fits", (int)tui_width(buf, strlen(buf)), 30);
    tui_fit_path("/srv/abc/def", 8, buf, sizeof buf);
    check_str("fit path", buf, "\xe2\x80\xa6" "abc/def");
    tui_fit_path("/srv/x", 8, buf, sizeof buf);
    check_str("fit path that fits", buf, "/srv/x");
    {
        /* the provider prefix goes before the model name is cut */
        tui_footer f = {0, 0, 0, 0, 0, 200000, "openrouter/deepseek/deepseek-v4-pro", "xhigh", 0, 0, NULL, NULL, NULL};
        char p[512];
        tui_footer_stats(&f, 50, buf, sizeof buf);
        plain(buf, p, sizeof p);
        if (!strstr(p, "deepseek/deepseek-v4-pro \xe2\x80\xa2 xhigh") || strstr(p, "openrouter"))
            fail("footer: provider dropped first", "%s", p);
    }
    {
        /* the key in use after the model, and a key's warning in red at the end */
        tui_footer f = {0, 0, 0, 0, 0, 200000, "fake/m", NULL, 0, 0, "second", "! out of credit: default", NULL};
        char p[512];
        tui_footer_stats(&f, 70, buf, sizeof buf);
        plain(buf, p, sizeof p);
        check_str("footer: key and warning", p, "0.0%/200k                fake/m \xc2\xb7 key second  ! out of credit: default");
        if (!has_after(buf, tui_fg(TUI_T_ERROR), "! out of credit"))
            fail("footer: warning", "not the error colour: %s", buf);
        tui_footer_stats(&f, 40, buf, sizeof buf);
        plain(buf, p, sizeof p);
        if (tui_width(p, strlen(p)) > 40 || !strstr(p, "! out of credit"))
            fail("footer: narrow, the warning stays", "%s", p);
    }
    {
        /* where the model, the level and the key are drawn, so a click can find them */
        int h[6];
        tui_footer f = {0, 0, 0, 0, 0, 200000, "fake/r", "medium", 0, 0, "default", NULL, h};
        char p[512];
        tui_footer_stats(&f, 60, buf, sizeof buf);
        plain(buf, p, sizeof p);
        if (strncmp(p + 60 - 29, "fake/r \xe2\x80\xa2 medium \xc2\xb7 key default", 6) != 0 || h[0] != 31 || h[1] != 37 ||
            h[2] != 40 || h[3] != 46 || h[4] != 49 || h[5] != 60)
            fail("footer: hits", "%d-%d %d-%d %d-%d in %s", h[0], h[1], h[2], h[3], h[4], h[5], p);
        tui_footer_stats(&f, 20, buf, sizeof buf); /* the provider goes, then the end is cut: what is cut is no target */
        if (h[0] != 11 || h[1] != 12 || h[2] != 15 || h[3] != 20 || h[4] != -1 || h[5] != -1)
            fail("footer: hits, narrow", "%d-%d %d-%d %d-%d", h[0], h[1], h[2], h[3], h[4], h[5]);
    }
    pass("view: footer");

    {
        char dir[] = "/tmp/pic-view.XXXXXX", p[600];
        FILE *f;
        if (!mkdtemp(dir))
            fail("git branch", "mkdtemp");
        snprintf(p, sizeof p, "%s/.git", dir);
        mkdir(p, 0700);
        snprintf(p, sizeof p, "%s/sub", dir);
        mkdir(p, 0700);
        snprintf(p, sizeof p, "%s/.git/HEAD", dir);
        f = fopen(p, "w");
        fputs("ref: refs/heads/feature/x\n", f);
        fclose(f);
        snprintf(p, sizeof p, "%s/sub", dir);
        check_int("branch found from a subdirectory", tui_git_branch(p, buf, sizeof buf), 1);
        check_str("branch name", buf, "feature/x");
        snprintf(p, sizeof p, "%s/.git/HEAD", dir);
        f = fopen(p, "w");
        fputs("0123456789abcdef0123456789abcdef01234567\n", f);
        fclose(f);
        check_int("detached", tui_git_branch(dir, buf, sizeof buf), 1);
        check_str("detached name", buf, "detached");
        snprintf(p, sizeof p, "%s/.git/HEAD", dir);
        unlink(p);
        snprintf(p, sizeof p, "%s/.git", dir);
        rmdir(p);
        snprintf(p, sizeof p, "%s/sub", dir);
        rmdir(p);
        rmdir(dir);
    }
    pass("view: git branch");

    tui_retry_status(2, 5, 8000, 1500, buf, sizeof buf);
    check_str("retry countdown", buf, "Retrying (2/5) in 7s\xe2\x80\xa6 (esc to cancel)");
    tui_retry_status(2, 5, 8000, 9000, buf, sizeof buf);
    check_str("retry countdown ends", buf, "Retrying (2/5) in 0s\xe2\x80\xa6 (esc to cancel)");
    tui_retry_status(3, 3, 0, 0, buf, sizeof buf);
    check_str("retry without a delay", buf, "Retrying (3/3)\xe2\x80\xa6 (esc to cancel)");
    pass("view: retry status");

    {
        tui_editor *e = tui_editor_new();
        tui_editor_history_add(e, "first");
        tui_editor_history_add(e, "second");
        tui_editor_history_add(e, "second");
        check_int("up into seeded history", press(e, TUI_KEY_UP), TUI_EDIT_CHANGED);
        text_is("newest seeded entry", e, "second");
        press(e, TUI_KEY_UP);
        text_is("older seeded entry", e, "first");
        press(e, TUI_KEY_DOWN);
        press(e, TUI_KEY_DOWN);
        text_is("back to the unsent text", e, "");
        tui_editor_free(e);
    }
    pass("editor: seeded history");
}

/* ---- round 2: keys, kill ring, undo, markdown, bash blocks ---------------- */

static void keys_are(const char *what, const char *bytes, size_t n, const tui_key_kind *want, size_t nwant)
{
    tui_keys *k = tui_keys_new();
    tui_key key;
    size_t got = 0;
    tui_keys_feed(k, bytes, n);
    while (tui_keys_next(k, &key)) {
        if (got < nwant && key.kind != want[got])
            fail(what, "key %zu is %d want %d", got, (int)key.kind, (int)want[got]);
        got++;
    }
    if (got != nwant)
        fail(what, "%zu keys want %zu", got, nwant);
    tui_keys_free(k);
}

static void test_keys2(void)
{
    tui_key_kind one;
    struct {
        const char *bytes;
        tui_key_kind kind;
        const char *what;
    } t[] = {
        {"\x19", TUI_KEY_YANK, "ctrl+y"},
        {"\x1b" "y", TUI_KEY_YANK_POP, "alt+y"},
        {"\x1b" "d", TUI_KEY_DELETE_WORD_FWD, "alt+d"},
        {"\x1b[3;3~", TUI_KEY_DELETE_WORD_FWD, "alt+delete"},
        {"\x1f", TUI_KEY_UNDO, "ctrl+- (0x1f)"},
        {"\x1b[45;5u", TUI_KEY_UNDO, "ctrl+- (kitty)"},
        {"\x1d", TUI_KEY_JUMP, "ctrl+]"},
        {"\x1b\x1d", TUI_KEY_JUMP_BACK, "ctrl+alt+]"},
        {"\x07", TUI_KEY_CTRL_G, "ctrl+g"},
        {"\x18", TUI_KEY_CTRL_X, "ctrl+x"},
        {"\x16", TUI_KEY_CTRL_V, "ctrl+v"},
        {"\x1b[118;5u", TUI_KEY_CTRL_V, "ctrl+v (kitty)"},
        {"\x1b[27;5;118~", TUI_KEY_CTRL_V, "ctrl+v (modifyOtherKeys)"},
        {"\x1a", TUI_KEY_CTRL_Z, "ctrl+z"},
        {"\x1b[1;3A", TUI_KEY_ALT_UP, "alt+up"},
        {"\x1b[A", TUI_KEY_UP, "plain up"},
        {"\x1b[112;6u", TUI_KEY_CTRL_P_BACK, "shift+ctrl+p (kitty)"},
        {"\x1b[27;6;112~", TUI_KEY_CTRL_P_BACK, "shift+ctrl+p (modifyOtherKeys)"},
        {"\x02", TUI_KEY_LEFT, "ctrl+b"},
        {"\x06", TUI_KEY_RIGHT, "ctrl+f"},
    };
    for (size_t i = 0; i < sizeof t / sizeof t[0]; i++) {
        one = t[i].kind;
        keys_are(t[i].what, t[i].bytes, strlen(t[i].bytes), &one, 1);
    }
    pass("term: Pi's editor and app keys decode");
}

static unsigned char *bytes_of(const char *s, size_t *n)
{
    *n = strlen(s);
    unsigned char *b = malloc(*n + 1);
    memcpy(b, s, *n + 1);
    return b;
}

static void test_editor_images(void)
{
    tui_editor *e = tui_editor_new();
    tui_attachment *list = NULL;
    size_t n = 0, len;
    unsigned char *b;
    char *out;
    type(e, "look ");
    b = bytes_of("AAAA", &len);
    check_int("first image is #1", tui_editor_attach(e, b, len), 1);
    text_is("marker at the cursor", e, "look [image #1]");
    type(e, " and ");
    b = bytes_of("BBBBBB", &len);
    check_int("second image is #2", tui_editor_attach(e, b, len), 2);
    text_is("two markers", e, "look [image #1] and [image #2]");
    check_int("two attached", (long)tui_editor_attached(e), 2);
    press(e, TUI_KEY_BACKSPACE);
    text_is("backspace removes the marker whole", e, "look [image #1] and ");
    check_int("one attached after the delete", (long)tui_editor_attached(e), 1);
    press(e, TUI_KEY_UNDO);
    text_is("undo brings the marker back", e, "look [image #1] and [image #2]");
    check_int("and its attachment", (long)tui_editor_attached(e), 2);
    press(e, TUI_KEY_BACKSPACE);
    press(e, TUI_KEY_HOME);
    for (int i = 0; i < 5; i++)
        press(e, TUI_KEY_RIGHT);
    press(e, TUI_KEY_DELETE);
    text_is("delete removes the marker under the cursor", e, "look  and ");
    check_int("no attachment left", (long)tui_editor_attached(e), 0);
    tui_editor_free(e);

    e = tui_editor_new();
    type(e, "x");
    b = bytes_of("one", &len);
    (void)tui_editor_attach(e, b, len);
    b = bytes_of("two!", &len);
    (void)tui_editor_attach(e, b, len);
    out = tui_editor_take_attached(e, &list, &n);
    check_str("the marker text stays in the sent message", out, "x[image #1][image #2]");
    check_int("both images come out", (long)n, 2);
    check_int("first length", (long)list[0].len, 3);
    check_int("first bytes", memcmp(list[0].data, "one", 3), 0);
    check_int("second length", (long)list[1].len, 4);
    check_int("the editor is empty", tui_editor_empty(e), 1);
    check_int("nothing attached after the take", (long)tui_editor_attached(e), 0);
    for (size_t i = 0; i < n; i++)
        free(list[i].data);
    free(list);
    free(out);
    b = bytes_of("again", &len);
    check_int("numbering restarts after a submit", tui_editor_attach(e, b, len), 1);
    tui_editor_clear(e);
    check_int("clear drops the attachment", (long)tui_editor_attached(e), 0);
    b = bytes_of("gone", &len);
    (void)tui_editor_attach(e, b, len);
    b = bytes_of("kept", &len);
    (void)tui_editor_attach(e, b, len);
    press(e, TUI_KEY_BACKSPACE);
    out = tui_editor_take_attached(e, &list, &n);
    check_str("only the remaining marker is sent", out, "[image #1]");
    check_int("one image out", (long)n, 1);
    check_int("it is the one still in the text", memcmp(list[0].data, "gone", 4), 0);
    free(list[0].data);
    free(list);
    free(out);
    tui_editor_free(e);
    pass("editor: image markers are atomic, deleting one drops its attachment, numbering restarts");
}

static void test_editor_paste_unchanged(void)
{
    tui_editor *e = tui_editor_new();
    paste_text(e, "plain pasted text");
    text_is("a short bracketed paste is inserted as typed", e, "plain pasted text");
    check_int("it attaches nothing", (long)tui_editor_attached(e), 0);
    tui_editor_free(e);
    pass("editor: plain text paste is unchanged");
}

static void test_history_find(void)
{
    tui_editor *e = tui_editor_new();
    tui_editor_history_add(e, "fix the Parser");
    tui_editor_history_add(e, "run the tests");
    tui_editor_history_add(e, "parser again\nsecond line");
    tui_editor_history_add(e, "deploy");
    check_int("count", (long)tui_editor_history_count(e), 4);
    check_str("at", tui_editor_history_at(e, 1), "run the tests");
    check_int("newest match first", tui_editor_history_find(e, "PARSER", -1), 2);
    check_int("an older one", tui_editor_history_find(e, "parser", 1), 0);
    check_int("none older than the oldest", tui_editor_history_find(e, "parser", -1) == 2 && tui_editor_history_find(e, "parser", 0) == 0, 1);
    check_int("none before the first", tui_editor_history_find(e, "tests", 0), -1);
    check_int("a later line of an entry matches", tui_editor_history_find(e, "second", -1), 2);
    check_int("an empty query matches the newest", tui_editor_history_find(e, "", -1), 3);
    check_int("an empty query steps back", tui_editor_history_find(e, "", 2), 2);
    check_int("no match", tui_editor_history_find(e, "zebra", -1), -1);
    tui_editor_free(e);
    e = tui_editor_new();
    check_int("an empty history", tui_editor_history_find(e, "", -1), -1);
    tui_editor_free(e);
    pass("editor: history search finds the newest entry containing the text");
}

static void test_editor2(void)
{
    tui_editor *e = tui_editor_new();
    type(e, "alpha beta gamma");
    press(e, TUI_KEY_DELETE_WORD);
    text_is("ctrl+w kills the word", e, "alpha beta ");
    press(e, TUI_KEY_DELETE_WORD);
    text_is("ctrl+w again", e, "alpha ");
    press(e, TUI_KEY_YANK);
    text_is("yank restores both words (consecutive kills merged, prepended)", e, "alpha beta gamma");
    tui_editor_free(e);

    e = tui_editor_new();
    type(e, "one two");
    press(e, TUI_KEY_KILL_START);
    text_is("ctrl+u kills to the line start", e, "");
    type(e, "x");
    press(e, TUI_KEY_YANK);
    text_is("yank inserts the killed text", e, "xone two");
    press(e, TUI_KEY_YANK_POP);
    text_is("yank-pop with one entry does nothing", e, "xone two");
    tui_editor_free(e);

    e = tui_editor_new();
    type(e, "first");
    press(e, TUI_KEY_KILL_START);
    type(e, "second");
    press(e, TUI_KEY_KILL_START);
    press(e, TUI_KEY_YANK);
    text_is("yank gives the newest kill", e, "second");
    press(e, TUI_KEY_YANK_POP);
    text_is("yank-pop swaps in the older kill", e, "first");
    press(e, TUI_KEY_YANK_POP);
    text_is("yank-pop cycles back", e, "second");
    type(e, "!");
    press(e, TUI_KEY_YANK_POP);
    text_is("yank-pop only works right after a yank", e, "second!");
    tui_editor_free(e);

    e = tui_editor_new();
    type(e, "ab cd ef");
    press(e, TUI_KEY_HOME);
    press(e, TUI_KEY_DELETE_WORD_FWD);
    text_is("alt+d kills the next word", e, " cd ef");
    press(e, TUI_KEY_DELETE_WORD_FWD);
    press(e, TUI_KEY_YANK);
    text_is("alt+d kills append: yank returns both", e, "ab cd ef");
    tui_editor_free(e);

    e = tui_editor_new();
    type(e, "hello world");
    press(e, TUI_KEY_UNDO);
    text_is("undo removes the last typed word", e, "hello");
    press(e, TUI_KEY_UNDO);
    text_is("undo removes the first word", e, "");
    press(e, TUI_KEY_UNDO);
    text_is("undo on an empty stack does nothing", e, "");
    type(e, "keep");
    press(e, TUI_KEY_KILL_START);
    text_is("killed", e, "");
    press(e, TUI_KEY_UNDO);
    text_is("undo restores a kill", e, "keep");
    cursor_is("undo restores the cursor", e, 40, 0, 6);
    tui_editor_free(e);

    e = tui_editor_new();
    type(e, "a.b.c d");
    press(e, TUI_KEY_HOME);
    press(e, TUI_KEY_JUMP);
    type(e, ".");
    cursor_is("ctrl+] then . jumps to the next .", e, 40, 0, 3);
    press(e, TUI_KEY_JUMP);
    type(e, "d");
    cursor_is("jumps to d", e, 40, 0, 8);
    press(e, TUI_KEY_JUMP_BACK);
    type(e, "a");
    cursor_is("ctrl+alt+] jumps back to a", e, 40, 0, 2);
    press(e, TUI_KEY_JUMP);
    press(e, TUI_KEY_JUMP);
    type(e, "z");
    text_is("pressing the jump key again cancels it: z is typed", e, "za.b.c d");
    tui_editor_free(e);
    pass("editor: kill ring, yank, yank-pop, alt+d, undo, jump to character");
}

/* The lines joined with '\n', escape sequences removed. */
static char *plain_lines(const tui_lines *l)
{
    size_t cap = 1, n = 0;
    char *out;
    for (size_t i = 0; i < l->n; i++)
        cap += strlen(l->lines[i]) + 1;
    out = malloc(cap);
    for (size_t i = 0; i < l->n; i++) {
        const char *p = l->lines[i];
        while (*p) {
            if (*p == 0x1b) {
                p++;
                if (*p == '[') {
                    p++;
                    while (*p && !(*p >= 0x40 && *p <= 0x7e))
                        p++;
                    p += *p != 0;
                } else if (*p == ']') {
                    while (*p && *p != 0x07 && !(*p == 0x1b && p[1] == '\\'))
                        p++;
                    p += *p == 0x1b ? 2 : *p ? 1 : 0;
                }
            } else {
                out[n++] = *p++;
            }
        }
        out[n++] = '\n';
    }
    if (n)
        n--;
    out[n] = 0;
    return out;
}

static char *md_plain(const char *text, size_t cols, int links)
{
    tui_md_opts o = {NULL, links, 0};
    tui_lines l = {0};
    char *p;
    if (tui_markdown(text, strlen(text), cols, &o, &l) != 0)
        fail("markdown", "render failed");
    p = plain_lines(&l);
    tui_lines_clear(&l);
    return p;
}

static void md_is(const char *what, const char *text, size_t cols, const char *want)
{
    char *got = md_plain(text, cols, 0);
    check_str(what, got, want);
    free(got);
}

/* md_has for a token's foreground sequence followed by TEXT (the sequence is rebuilt per call: tui_fg's buffer). */
static void md_has_tok(const char *what, const char *text, size_t cols, tui_token t, const char *after);

static void md_has(const char *what, const char *text, size_t cols, int links, const char *needle)
{
    tui_md_opts o = {NULL, links, 0};
    tui_lines l = {0};
    size_t total = 0;
    char *all;
    tui_markdown(text, strlen(text), cols, &o, &l);
    for (size_t i = 0; i < l.n; i++)
        total += strlen(l.lines[i]) + 1;
    all = calloc(total + 1, 1);
    for (size_t i = 0; i < l.n; i++) {
        strcat(all, l.lines[i]);
        strcat(all, "\n");
    }
    if (!strstr(all, needle)) {
        char shown[2048];
        show(all, strlen(all), shown, sizeof shown);
        fail(what, "no \"%s\" in \"%s\"", needle, shown);
    }
    free(all);
    tui_lines_clear(&l);
}

static void md_has_tok(const char *what, const char *text, size_t cols, tui_token t, const char *after)
{
    char n[256];
    (void)snprintf(n, sizeof n, "%s%s", tui_fg(t), after);
    md_has(what, text, cols, 0, n);
}

static const char *const md_long_table =
    "| Item | Fix and evidence |\n|---|---|\n"
    "| 1. Renewal deadline | `dispatch_renewal_reserve` verifies that CGI and the timer refuse a renewal with less than **1,000 ms** left, without claiming, marking, or calling the issuer. `revoke_and_cancel` verifies a post-send 503\xe2\x80\x94" "even a ledger-close failure after a 2xx\xe2\x80\x94" "does not mean it failed. |\n"
    "| 2. App revocation | `dispatch_grant_revoke_windows` covers `GRANT_READY` / `LEDGER_SAVED`; Alice's next request is denied and `f.retired=0` holds. |\n";

/* Every output line of a rendered table is a box row, never a raw pipe line. */
static void md_no_raw(const char *what, const char *text, size_t cols)
{
    char *got = md_plain(text, cols, 0);
    if (strstr(got, "|---") || strstr(got, "| Item"))
        fail(what, "raw table lines in \"%s\"", got);
    if (!strstr(got, "\xe2\x94\x82"))
        fail(what, "no box rows in \"%s\"", got);
    free(got);
}

static void md_table_cases(void)
{
    char buf[4096];
    md_no_raw("long table at 100", md_long_table, 100);
    md_no_raw("long table at 60", md_long_table, 60);
    md_no_raw("long table at 30", md_long_table, 30);
    (void)snprintf(buf, sizeof buf, "Here is the table:\n%s", md_long_table);
    md_no_raw("table right after a paragraph", buf, 80);
    (void)snprintf(buf, sizeof buf, "- a list line\n%s", md_long_table);
    md_no_raw("table right after a list", buf, 80);
    md_no_raw("pipe in a code span", "| a | b |\n|---|---|\n| `x|y` | z |\n", 40);
    md_no_raw("escaped pipe", "| Item | b |\n|---|---|\n| x\\|y | z |\n", 40);
    md_no_raw("short row", "| Item | b |\n|---|---|\n| x |\n", 40);
    md_no_raw("long row", "| Item | b |\n|---|---|\n| x | y | z |\n", 40);
    md_no_raw("no outer pipes", "Item | b\n--- | ---\nx | y\n", 40);
    md_is("narrow window: one Header: cell line per cell", "| Item | b |\n|---|---|\n| xxxx | yyyy |\n| p | q |\n", 6,
          "Item:\nxxxx\nb:\nyyyy\n\nItem:\np\nb: q");
    {
        const char *t = "| A | B |\n|---|---|\n| 1 | 2 |\n";
        char two[128];
        check_int("streaming: header alone is held", tui_markdown_table_open("intro\n| A | B |\n"), 1);
        check_int("streaming: table so far is held", tui_markdown_table_open(t), 1);
        check_int("streaming: table so far is not a block", (int)tui_markdown_block_len(t), 0);
        check_int("streaming: a partial row is held", tui_markdown_table_open("| A | B |\n|---|---|\n| 1 | 2"), 1);
        check_int("streaming: plain lines are not held", tui_markdown_table_open("one\ntwo\n"), 0);
        (void)snprintf(two, sizeof two, "%safter\nmore\n", t);
        check_int("streaming: a table ends at the first non-row line", (int)tui_markdown_block_len(two), (int)strlen(t));
        (void)snprintf(two, sizeof two, "%s\nafter\n", t);
        check_int("streaming: a table ends at a blank line", (int)tui_markdown_block_len(two), (int)strlen(t) + 1);
    }
}

static void test_markdown(void)
{
    md_is("paragraph and heading", "# Title\n\nSome text.", 40, "Title\n\nSome text.");
    md_is("h3 keeps its hashes", "### Deep", 40, "### Deep");
    md_is("soft line breaks stay", "a\nb", 40, "a\nb");
    md_is("bullets are dashes (Pi)", "- one\n- two\n  - nested\n- three", 40, "- one\n- two\n    - nested\n- three");
    md_is("numbered lists count from their start", "3. c\n4. d", 40, "3. c\n4. d");
    md_is("a long item wraps under its text", "1. aaa bbb ccc ddd", 12, "1. aaa bbb\n   ccc ddd");
    md_is("a loose list has blank lines", "- a\n\n- b", 40, "- a\n\n- b");
    md_is("task items", "- [x] done\n- [ ] todo", 40, "- [x] done\n- [ ] todo");
    md_is("quote", "> quoted *text*\n> more", 40, "\xe2\x94\x82 quoted text\n\xe2\x94\x82 more");
    md_is("nested block in a quote", "> - a\n> - b", 40, "\xe2\x94\x82 - a\n\xe2\x94\x82 - b");
    {
        tui_lines l = {0};
        tui_md_opts o = {NULL, 0, 0};
        size_t worst = 0;
        tui_markdown("2) a very long item", 19, 3, &o, &l);
        for (size_t i = 0; i < l.n; i++) {
            size_t w = tui_width(l.lines[i], strlen(l.lines[i]));
            worst = w > worst ? w : worst;
        }
        if (worst > 3)
            fail("markdown: lines always fit", "a %zu-column line in 3", worst);
        tui_lines_clear(&l);
    }
    md_is("rule", "a\n\n---\n\nb", 10, "a\n\n\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n\nb");
    md_is("code fence shows its language", "```c\nint x;\n```", 40, "```c\n  int x;\n```");
    md_is("code fence without a language, followed by text", "```\nx\n```\ntext", 40, "```\n  x\n```\n\ntext");
    md_is("an unterminated fence (streaming)", "```py\nprint(1)", 40, "```py\n  print(1)\n```");
    md_is("a partial closing fence is not code", "```py\nx\n``", 40, "```py\n  x\n```");
    md_has_tok("highlighted C block: keyword coloured", "```c\nreturn 1;\n```", 40, TUI_T_SYNTAX_KEYWORD, "return");
    md_is("highlighted C block: text unchanged", "```c\nreturn 1; // done\n```", 40, "```c\n  return 1; // done\n```");
    md_has_tok("unknown language stays plain", "```zzz\nreturn 1;\n```", 40, TUI_T_MD_CODE_BLOCK, "return 1;");
    md_has_tok("no language stays plain", "```\nreturn 1;\n```", 40, TUI_T_MD_CODE_BLOCK, "return 1;");
    {
        tui_md_opts o = {NULL, 0, 0};
        tui_lines l = {0};
        const char *src = "```c\n// aaaa bbbb cccc dddd eeee ffff gggg hhhh\n```";
        size_t colored = 0;
        tui_markdown(src, strlen(src), 20, &o, &l);
        for (size_t i = 1; i + 1 < l.n; i++) {
            if (tui_width(l.lines[i], strlen(l.lines[i])) > 20)
                fail("highlighted wrap", "line %zu is wider than 20 columns", i);
            if (strstr(l.lines[i], tui_fg(TUI_T_SYNTAX_COMMENT)))
                colored++;
        }
        if (l.n < 5 || colored != l.n - 2)
            fail("highlighted wrap", "%zu lines, %zu carrying the comment colour", l.n, colored);
        tui_lines_clear(&l);
    }
    md_is("table", "| a | bb |\n|---|---|\n| 1 | 2 |\n| 33 | 4 |", 40,
          "\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x90\n"
          "\xe2\x94\x82 a  \xe2\x94\x82 bb \xe2\x94\x82\n"
          "\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n"
          "\xe2\x94\x82 1  \xe2\x94\x82 2  \xe2\x94\x82\n"
          "\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n"
          "\xe2\x94\x82 33 \xe2\x94\x82 4  \xe2\x94\x82\n"
          "\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xb4\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x98");
    md_table_cases();
    pass("markdown: blocks (headings, lists, quotes, rules, fences, tables)");

    md_is("inline markers are consumed", "a **b** *c* ~~d~~ `e` f", 40, "a b c d e f");
    md_is("intraword underscores stay", "snake_case_name and 2 * 3 * 4", 40, "snake_case_name and 2 * 3 * 4");
    md_is("backslash escapes", "\\*not italic\\*", 40, "*not italic*");
    md_is("unmatched markers are literal", "a *b", 40, "a *b");
    md_is("a link shows its url when the text differs", "[docs](https://x.dev/a)", 60, "docs (https://x.dev/a)");
    md_is("a bare url is not repeated", "see https://x.dev/a.", 60, "see https://x.dev/a.");
    md_is("an autolink", "<https://x.dev>", 60, "https://x.dev");
    md_has("bold is SGR 1", "**b**", 40, 0, "\x1b[1m" "b");
    md_has("italic is SGR 3", "*i*", 40, 0, "\x1b[3m" "i");
    md_has_tok("inline code is the mdCode colour", "`c`", 40, TUI_T_MD_CODE, "c");
    md_has_tok("a link is the mdLink colour, underlined", "[t](http://u)", 40, TUI_T_MD_LINK, "\x1b[4m");
    md_has("a link becomes an OSC 8 hyperlink", "[docs](https://x.dev/a)", 60, 1, ";https://x.dev/a\x1b\\");
    {
        char *with = md_plain("[docs](https://x.dev/a)", 60, 1);
        check_str("OSC 8: the url is not printed", with, "docs");
        free(with);
        with = md_plain("[docs](https://x.dev/a)", 60, TUI_LINKS_TEXT);
        check_str("links as text: the url is printed", with, "docs (https://x.dev/a)");
        free(with);
        md_has("links as text: text and url are one link", "[docs](https://x.dev/a)", 60, TUI_LINKS_TEXT, ";https://x.dev/a\x1b\\");
        md_has("links as text: the link closes after the url", "[docs](https://x.dev/a)", 60, TUI_LINKS_TEXT, "https://x.dev/a)\x1b]8;;\x1b\\");
    }
    {
        tui_md_opts o = {NULL, 1, 0};
        tui_lines l = {0};
        tui_markdown("[aaa bbb ccc](https://x.dev/a)", 30, 8, &o, &l);
        check_int("a hyperlink wrapped over two lines", (long)l.n, 2);
        if (!strstr(l.lines[0], "\x1b]8;;\x1b\\") || strncmp(l.lines[1], "\x1b[", 2) != 0 || !strstr(l.lines[1], ";https://x.dev/a\x1b\\"))
            fail("hyperlink across a wrap", "line 0 closes it and line 1 reopens it");
        tui_lines_clear(&l);
    }
    pass("markdown: italics, links (OSC 8), code spans, escapes");

    check_int("block len: open paragraph", (long)tui_markdown_block_len("abc\ndef\n"), 0);
    check_int("block len: finished paragraph", (long)tui_markdown_block_len("abc\n\ndef"), 5);
    check_int("block len: blank lines inside a fence do not end it", (long)tui_markdown_block_len("```\na\n\nb\n```\n\nx"), 14);
    check_int("block len: leading blank lines", (long)tui_markdown_block_len("\n\nabc\n\nx"), 7);
    {
        int fence = 0;
        tui_lines l = {0};
        tui_markdown_line("```sh", 6, &fence, 40, NULL, &l);
        check_int("line: fence opens", fence, 1);
        tui_markdown_line("ls -l", 5, &fence, 40, NULL, &l);
        tui_markdown_line("```", 3, &fence, 40, NULL, &l);
        check_int("line: fence closes", fence, 0);
        {
            char *p = plain_lines(&l);
            check_str("line: rendered as code", p, "```sh\n  ls -l\n```");
            free(p);
        }
        tui_lines_clear(&l);
    }
    pass("markdown: streaming block boundaries");

    {
        tui_lines l = {0};
        char *p;
        tui_user_message_lines("hello **you**", 20, 0, &l);
        check_int("user message: blank row, text, blank row", (long)l.n, 3);
        p = plain_lines(&l);
        check_str("user message text is padded to the width", p, "                    \n hello you          \n                    ");
        free(p);
        if (strncmp(l.lines[1], "\x1b[48;", 5) != 0)
            fail("user message", "rows start with a background colour");
        tui_lines_clear(&l);
        for (size_t i = 0; i < l.n; i++)
            if (strncmp(l.lines[i], "\x1b[48;", 5) != 0)
                fail("user message", "row %zu starts with the background", i);
        tui_lines_clear(&l);
        setenv("COLORTERM", "truecolor", 1);
        unsetenv("COLORFGBG");
        tui_user_message_lines("a long message that has to wrap onto lines", 14, 0, &l);
        check_int("user message: wrapped, with padding rows", (long)l.n >= 5, 1);
        for (size_t i = 0; i < l.n; i++) {
            if (strncmp(l.lines[i], "\x1b[48;2;33;59;73m", 16) != 0)
                fail("user message", "dark truecolor bg on row %zu", i);
            check_int("user message: row width is exactly cols", (long)tui_width(l.lines[i], strlen(l.lines[i])), 14);
        }
        tui_lines_clear(&l);
        setenv("COLORFGBG", "0;15", 1);
        tui_user_message_lines("hi", 10, 0, &l);
        if (strncmp(l.lines[0], "\x1b[48;2;223;231;236m", 19) != 0)
            fail("user message", "light bg when COLORFGBG says light");
        tui_lines_clear(&l);
        unsetenv("COLORFGBG");
        tui_user_message_lines("1) a\n2) b", 20, 0, &l);
        p = plain_lines(&l);
        if (!strstr(p, "1) a") || !strstr(p, "2) b"))
            fail("user message keeps its list markers", "%s", p);
        free(p);
        tui_lines_clear(&l);
    }
    pass("markdown: user messages on a background");
}

/* ---- hyperlinks -------------------------------------------------------- */

/* The opening OSC 8 sequence's parameters (between "ESC ] 8 ;" and the next
 * ";") of the first link in s, or "" when s opens none; static. */
static const char *link_params(const char *s)
{
    static char p[256];
    const char *o = strstr(s, "\x1b]8;"), *e;
    p[0] = '\0';
    while (o && o[4] == ';' && o[5] == '\x1b') /* a closing sequence */
        o = strstr(o + 4, "\x1b]8;");
    if (!o || !(e = strchr(o + 4, ';')) || (size_t)(e - o - 4) >= sizeof p)
        return p;
    memcpy(p, o + 4, (size_t)(e - o - 4));
    p[e - o - 4] = '\0';
    return p;
}

static void links_env(const char *term, const char *program, const char *version, const char *tmux)
{
    term ? setenv("TERM", term, 1) : unsetenv("TERM");
    program ? setenv("TERM_PROGRAM", program, 1) : unsetenv("TERM_PROGRAM");
    version ? setenv("TERM_PROGRAM_VERSION", version, 1) : unsetenv("TERM_PROGRAM_VERSION");
    tmux ? setenv("TMUX", tmux, 1) : unsetenv("TMUX");
    unsetenv("STY");
}

static void test_links(void)
{
    char dir[] = "/tmp/pic-links.XXXXXX", path[512], want[600], *u, *s;
    size_t n;
    if (!mkdtemp(dir))
        fail("links", "mkdtemp");
    (void)snprintf(path, sizeof path, "%s/src", dir);
    (void)mkdir(path, 0755);
    (void)snprintf(path, sizeof path, "%s/src/foo.c", dir);
    {
        FILE *f = fopen(path, "w");
        if (f)
            fclose(f);
    }
    (void)snprintf(path, sizeof path, "%s/a b.md", dir);
    {
        FILE *f = fopen(path, "w");
        if (f)
            fclose(f);
    }
    tui_links_set(1, dir);

    /* targets */
    u = tui_link_url("https://x.dev/a?b=1#c", 21);
    check_str("an https target stays as it is", u ? u : "(null)", "https://x.dev/a?b=1#c");
    free(u);
    u = tui_link_url("mailto:[email protected]", 15);
    check_str("a mailto target stays as it is", u ? u : "(null)", "mailto:[email protected]");
    free(u);
    u = tui_link_url("docs/design/flak.md", 19);
    (void)snprintf(want, sizeof want, "file://%s/docs/design/flak.md", dir);
    check_str("a relative path resolves against the workspace", u ? u : "(null)", want);
    free(u);
    u = tui_link_url("./src/../src/foo.c:42:7", 23);
    (void)snprintf(want, sizeof want, "file://%s/src/foo.c", dir);
    check_str("dot segments fold and :LINE:COL is left out", u ? u : "(null)", want);
    free(u);
    u = tui_link_url("/etc/a b%.txt#L3", 16);
    check_str("an absolute path is percent-encoded, its fragment dropped", u ? u : "(null)", "file:///etc/a%20b%25.txt");
    free(u);
    u = tui_link_url("t.txt:10-20", 11);
    (void)snprintf(want, sizeof want, "file://%s/t.txt", dir);
    check_str("a line range is left out", u ? u : "(null)", want);
    free(u);
    u = tui_link_url("#section", 8);
    check_str("an anchor alone is no link", u ? u : "(null)", "(null)");
    free(u);
    pass("links: targets are URLs a terminal opens (file:// for paths)");

    /* markdown links */
    {
        tui_md_opts o = {NULL, 1, 0};
        tui_lines l = {0};
        tui_markdown("[design doc](docs/design/flak.md)", 33, 60, &o, &l);
        (void)snprintf(want, sizeof want, ";file://%s/docs/design/flak.md\x1b\\", dir);
        if (l.n != 1 || !strstr(l.lines[0], want) || strncmp(link_params(l.lines[0]), "id=", 3) != 0)
            fail("a relative markdown link", "one line opening an OSC 8 link with an id to %s", want + 1);
        tui_lines_clear(&l);
    }
    {
        char *p = md_plain("[design doc](docs/design/flak.md)", 60, 1);
        check_str("a markdown link shows only its text", p, "design doc");
        free(p);
    }

    {
        tui_md_opts o = {NULL, 1, 0};
        tui_lines l = {0};
        const char *p;
        size_t opens = 0;
        tui_markdown("see https://x.dev/a", 19, 60, &o, &l);
        for (p = l.n ? l.lines[0] : ""; (p = strstr(p, "\x1b]8;id=")); p++)
            opens++;
        check_int("a bare url in a reply opens one link, not one inside another", (long)opens, 1);
        tui_lines_clear(&l);
    }

    /* bare URLs and paths */
    s = tui_linkify("see https://x.dev/a. and (src/foo.c:12) or nope/missing.c", 57, &n);
    if (!s)
        fail("linkify", "found nothing");
    else {
        char *plain = tui_line_plain(s, 0, (size_t)-1);
        check_str("linkify keeps the visible text", plain ? plain : "", "see https://x.dev/a. and (src/foo.c:12) or nope/missing.c");
        free(plain);
        if (!strstr(s, ";https://x.dev/a\x1b\\https://x.dev/a\x1b]8;;\x1b\\."))
            fail("a bare url", "is linked without its trailing period: %s", s);
        (void)snprintf(want, sizeof want, ";file://%s/src/foo.c\x1b\\src/foo.c:12\x1b]8;;\x1b\\)", dir);
        if (!strstr(s, want))
            fail("a bare path that exists", "is linked with its :LINE, without the parenthesis");
        if (strstr(s, "missing"))
            if (strstr(s, "nope/missing.c\x1b]8;;"))
                fail("a path that does not exist", "is not linked");
        check_int("linkify's length", (long)n, (long)strlen(s));
        free(s);
    }
    s = tui_linkify("\x1b]8;;https://a.b\x1b\\https://a.b/c\x1b]8;;\x1b\\", 33, &n);
    check_str("text inside a link is left alone", s ? "changed" : "(null)", "(null)");
    free(s);
    s = tui_linkify("plain words only", 16, &n);
    check_str("no link, no copy", s ? "changed" : "(null)", "(null)");
    free(s);

    /* a long URL wrapped by pic stays one link: every segment opens it with the same id */
    {
        const char *url = "https://example.com/a/very/long/path/that/wraps/over/several/lines/of/the/screen";
        tui_md_opts o = {NULL, 1, 0};
        tui_lines l = {0};
        char text[256], first[256];
        (void)snprintf(text, sizeof text, "see %s now", url);
        tui_markdown(text, strlen(text), 30, &o, &l);
        if (l.n < 3)
            fail("a long url", "wraps over at least 3 lines, got %zu", l.n);
        first[0] = '\0';
        {
            size_t linked = 0;
            for (size_t i = 0; i < l.n; i++) {
                const char *p = link_params(l.lines[i]);
                if (!*p)
                    continue;
                if (!linked++)
                    (void)snprintf(first, sizeof first, "%s", p);
                else if (strcmp(p, first) != 0)
                    fail("a wrapped url", "line %zu opens it with another id", i);
                if (!strstr(l.lines[i], url))
                    fail("a wrapped url", "line %zu links somewhere else", i);
            }
            if (linked < 3 || strncmp(first, "id=", 3) != 0)
                fail("a wrapped url", "%zu segments, id %s", linked, first);
        }
        tui_lines_clear(&l);
    }

    /* tool output and titles */
    {
        tui_tool t = {"read", "src/foo.c:3-9", NULL, "see src/foo.c for more", TUI_TOOL_OK, 10, NULL};
        tui_lines l = {0};
        int head = 0, body = 0;
        (void)snprintf(want, sizeof want, ";file://%s/src/foo.c\x1b\\", dir);
        tui_tool_lines(&t, 0, 60, &l);
        for (size_t i = 0; i < l.n; i++) {
            if (strstr(l.lines[i], want))
                *(strstr(l.lines[i], "for more") ? &body : &head) = 1;
        }
        if (!head || !body)
            fail("tool paths", "the title (%d) and the output (%d) link to %s", head, body, want + 1);
        tui_lines_clear(&l);
    }
    tui_links_set(0, dir);
    {
        tui_tool t = {"read", "src/foo.c", NULL, "src/foo.c", TUI_TOOL_OK, 10, NULL};
        tui_lines l = {0};
        tui_tool_lines(&t, 0, 60, &l);
        for (size_t i = 0; i < l.n; i++)
            if (strstr(l.lines[i], "\x1b]8;"))
                fail("links off", "a tool line has a link");
        tui_lines_clear(&l);
    }

    /* what a click may open */
    check_int("an https link may be opened", tui_link_safe("https://x.dev/a"), 1);
    check_int("a bare scheme may not", tui_link_safe("https://"), 0);
    check_int("another scheme may not", tui_link_safe("ssh://x"), 0);
    (void)snprintf(want, sizeof want, "file://%s/src/foo.c", dir);
    check_int("a plain file may be opened", tui_link_safe(want), 1);
    (void)snprintf(want, sizeof want, "file://%s/src", dir);
    check_int("a directory may be opened", tui_link_safe(want), 1);
    (void)snprintf(want, sizeof want, "file://%s/a%%20b.md", dir);
    check_int("a percent-encoded path is decoded", tui_link_safe(want), 1);
    (void)snprintf(want, sizeof want, "file://%s/nope.c", dir);
    check_int("a missing file may not", tui_link_safe(want), 0);
    (void)snprintf(path, sizeof path, "%s/run.command", dir);
    {
        FILE *f = fopen(path, "w");
        if (f)
            fclose(f);
    }
    (void)snprintf(want, sizeof want, "file://%s/run.command", dir);
    check_int("a file the opener would run may not", tui_link_safe(want), 0);
    (void)snprintf(path, sizeof path, "%s/src/foo.c", dir);
    (void)chmod(path, 0755);
    (void)snprintf(want, sizeof want, "file://%s/src/foo.c", dir);
    check_int("an executable file may not", tui_link_safe(want), 0);
    (void)chmod(path, 0644);
    check_int("a file URL with a host may not", tui_link_safe("file://host/etc/hosts"), 0);

    /* the link under a cell */
    u = tui_line_link_at("ab\x1b]8;id=1;https://x\x1b\\c\xe4\xb8\xad" "d\x1b]8;;\x1b\\e", 4);
    check_str("the link at a wide character's second cell", u ? u : "(null)", "https://x");
    free(u);
    u = tui_line_link_at("ab\x1b]8;id=1;https://x\x1b\\cd\x1b]8;;\x1b\\e", 4);
    check_str("no link after it closes", u ? u : "(null)", "(null)");
    free(u);
    pass("links: bare URLs and paths, wrapped URLs keep one id, tool lines");

    /* detection */
    {
        char *saved[5];
        const char *names[5] = {"TERM", "TERM_PROGRAM", "TERM_PROGRAM_VERSION", "TMUX", "STY"};
        for (int i = 0; i < 5; i++)
            saved[i] = getenv(names[i]) ? strdup(getenv(names[i])) : NULL;
        links_env("xterm-ghostty", "ghostty", NULL, NULL);
        check_int("ghostty", tui_hyperlinks_supported("auto"), 1);
        links_env("xterm-256color", NULL, NULL, NULL);
        check_int("an unknown terminal is on", tui_hyperlinks_supported(NULL), 1);
        links_env("xterm-256color", "Apple_Terminal", NULL, NULL);
        check_int("Apple Terminal: the address as text, marked for pic's clicks", tui_hyperlinks_supported("auto"), TUI_LINKS_TEXT);
        links_env("dumb", NULL, NULL, NULL);
        check_int("TERM=dumb is off", tui_hyperlinks_supported("auto"), 0);
        links_env("linux", NULL, NULL, NULL);
        check_int("the Linux console is off", tui_hyperlinks_supported("auto"), 0);
        links_env("tmux-256color", "tmux", "3.4", "/tmp/tmux-501/default,1,0");
        check_int("tmux 3.4 is on", tui_hyperlinks_supported("auto"), 1);
        links_env("tmux-256color", "tmux", "3.3a", "/tmp/tmux-501/default,1,0");
        check_int("tmux 3.3a is off", tui_hyperlinks_supported("auto"), 0);
        links_env("screen-256color", "tmux", "next-3.6", "/tmp/tmux-501/default,1,0");
        check_int("tmux next-3.6 is on", tui_hyperlinks_supported("auto"), 1);
        links_env("screen-256color", "ghostty", NULL, "/tmp/tmux-501/default,1,0");
        check_int("tmux without its version is off", tui_hyperlinks_supported("auto"), 0);
        check_int("on forces it", tui_hyperlinks_supported("on"), 1);
        links_env("xterm-ghostty", "ghostty", NULL, NULL);
        check_int("off forces it", tui_hyperlinks_supported("off"), 0);
        setenv("STY", "1.pts-0", 1);
        check_int("screen is off", tui_hyperlinks_supported("auto"), 0);
        for (int i = 0; i < 5; i++) {
            saved[i] ? setenv(names[i], saved[i], 1) : unsetenv(names[i]);
            free(saved[i]);
        }
    }
    pass("links: on unless the terminal is known not to draw them; tmux 3.4+");
    (void)snprintf(path, sizeof path, "rm -rf '%s'", dir);
    (void)system(path);
}

static void test_border(void)
{
    static const size_t widths[] = {2, 6, 10, 40};
    tui_lines l = {0};
    char *p;
    setenv("COLORTERM", "truecolor", 1);
    unsetenv("COLORFGBG");
    for (size_t k = 0; k < 4; k++) {
        tui_border_line(NULL, "", widths[k], &l);
        check_int("border: plain row width", (long)tui_width(l.lines[0], strlen(l.lines[0])), (long)widths[k]);
        tui_lines_clear(&l);
        tui_border_line("\x1b[2m", "Working", widths[k], &l);
        check_int("border: status row width", (long)tui_width(l.lines[0], strlen(l.lines[0])), (long)widths[k]);
        tui_lines_clear(&l);
    }
    tui_border_line("\x1b[2m", "Working", 20, &l);
    if (strncmp(l.lines[0], "\x1b[38;2;95;168;204m", 18) != 0)
        fail("border", "starts with the dark border colour");
    p = plain_lines(&l);
    check_str("border: status inside", p, "\xe2\x94\x80\xe2\x94\x80 Working \xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80");
    free(p);
    tui_lines_clear(&l);
    tui_border_line(NULL, "a very long status that cannot fit", 12, &l);
    check_int("border: long status is cut to fit", (long)tui_width(l.lines[0], strlen(l.lines[0])), 12);
    tui_lines_clear(&l);
    pass("border: editor border rows");
}

/* The conversation's title at the right of the editor's top border, dim, cut with an ellipsis,
 * never over the status (Claude Code's session name in its prompt box). */
static void test_border_title(void)
{
    static const size_t widths[] = {2, 6, 10, 18, 40, 80};
    tui_lines l = {0};
    char *p;
    setenv("COLORTERM", "truecolor", 1);
    unsetenv("COLORFGBG");
    for (size_t k = 0; k < 6; k++) {
        tui_border_line_titled(NULL, NULL, "Working", "fix the login bug", widths[k], &l);
        check_int("border title: row width", (long)tui_width(l.lines[0], strlen(l.lines[0])), (long)widths[k]);
        tui_lines_clear(&l);
        tui_border_line_titled(NULL, NULL, NULL, "fix the login bug", widths[k], &l);
        check_int("border title: row width, no status", (long)tui_width(l.lines[0], strlen(l.lines[0])), (long)widths[k]);
        tui_lines_clear(&l);
    }
    tui_border_line_titled(NULL, NULL, NULL, "main", 20, &l);
    p = plain_lines(&l);
    check_str("border title: at the right", p, "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80 main \xe2\x94\x80\xe2\x94\x80");
    free(p);
    if (!strstr(l.lines[0], tui_fg(TUI_T_DIM)))
        fail("border title", "is dim");
    tui_lines_clear(&l);
    tui_border_line_titled(NULL, NULL, "Working", "a title much too long to fit beside it", 30, &l);
    p = plain_lines(&l);
    check_str("border title: cut with an ellipsis after the status", p,
              "\xe2\x94\x80\xe2\x94\x80 Working \xe2\x94\x80\xe2\x94\x80\xe2\x94\x80 a title muc\xe2\x80\xa6 \xe2\x94\x80\xe2\x94\x80");
    free(p);
    tui_lines_clear(&l);
    tui_border_line_titled(NULL, NULL, "a status that takes the whole row", "main", 30, &l);
    p = plain_lines(&l);
    if (strstr(p, "main"))
        fail("border title", "left out when the status leaves no room");
    free(p);
    tui_lines_clear(&l);
    tui_border_line_titled(NULL, NULL, NULL, "", 20, &l);
    p = plain_lines(&l);
    check_str("border title: none, a plain row", p, "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80");
    free(p);
    tui_lines_clear(&l);
    pass("border title: the conversation's title at the right of the editor's border");
}

static void test_view2(void)
{
    tui_lines l = {0};
    char *p;
    tui_bash b = {"echo hi", "hi\n", TUI_BASH_DONE, 0, 0};
    tui_bash_lines(&b, 0, 20, &l);
    p = plain_lines(&l);
    check_str("bash block: rule, command, output, rule",
              p, "\n\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n$ echo hi\nhi\n\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80");
    free(p);
    tui_lines_clear(&l);

    {
        char out[4096] = "";
        for (int i = 1; i <= 30; i++)
            snprintf(out + strlen(out), sizeof out - strlen(out), "line%d\n", i);
        b = (tui_bash){"seq", out, TUI_BASH_DONE, 3, 0};
        tui_bash_lines(&b, 0, 30, &l);
        p = plain_lines(&l);
        if (strstr(p, "line10\n") || !strstr(p, "line11\n") || !strstr(p, "line30") || !strstr(p, "... 10 more lines (ctrl+o to expand)") ||
            !strstr(p, "(exit 3)"))
            fail("bash block: the last 20 lines, a hint, the exit code", "%s", p);
        free(p);
        tui_lines_clear(&l);
        tui_bash_lines(&b, 1, 30, &l);
        p = plain_lines(&l);
        if (!strstr(p, "line1\n") || strstr(p, "more lines") || !strstr(p, "(ctrl+o to collapse)"))
            fail("bash block expanded", "%s", p);
        free(p);
        tui_lines_clear(&l);
    }
    b = (tui_bash){"sleep 9", "\x1b[31mred\x1b[0m\r\nx\r", TUI_BASH_RUNNING, 0, 1};
    tui_bash_lines(&b, 0, 40, &l);
    p = plain_lines(&l);
    if (!strstr(p, "red\nx") || strstr(p, "[31m") || !strstr(p, "Running... (esc to cancel)"))
        fail("bash block running: output cleaned, status shown", "%s", p);
    if (!strstr(l.lines[1], tui_fg(TUI_T_DIM)))
        fail("bash block: !! is dim", "%s", l.lines[1]);
    free(p);
    tui_lines_clear(&l);
    b = (tui_bash){"x", "", TUI_BASH_CANCELLED, 0, 0};
    tui_bash_lines(&b, 0, 40, &l);
    p = plain_lines(&l);
    if (!strstr(p, "(cancelled)"))
        fail("bash block cancelled", "%s", p);
    free(p);
    tui_lines_clear(&l);
    pass("view: user bash blocks");

    {
        char *c = tui_bash_context("ls", "a\nb\n", 0, 0);
        check_str("bash context", c, "Ran `ls`\n```\na\nb\n```");
        free(c);
        c = tui_bash_context("false", "", 0, 1);
        check_str("bash context: no output, exit code", c, "Ran `false`\n(no output)\n\nCommand exited with code 1");
        free(c);
        c = tui_bash_context("sleep 9", "\x1b[1mx\x1b[0m", 1, 130);
        check_str("bash context: cancelled, escapes removed", c, "Ran `sleep 9`\n```\nx\n```\n\n(command cancelled)");
        free(c);
        {
            char big[20000];
            size_t n = 0;
            for (int i = 1; i <= 3000; i++)
                n += (size_t)snprintf(big + n, sizeof big - n, "l%d\n", i);
            c = tui_bash_context("seq", big, 0, 0);
            if (strstr(c, "l1\n") || !strstr(c, "l3000\n```") || !strstr(c, "[Output truncated]"))
                fail("bash context: the last 2000 lines", "%.80s", c);
            free(c);
        }
    }
    pass("view: bash context for the model");

    {
        char buf[512];
        const char *items[] = {"zeta", "alpha", "mid"};
        tui_startup_hints(buf, sizeof buf);
        p = (char *)"esc interrupt \xc2\xb7 ctrl+c/ctrl+d clear/exit \xc2\xb7 / commands \xc2\xb7 ! bash \xc2\xb7 ctrl+o more";
        {
            tui_lines one = {0};
            char *got;
            tui_lines_add(&one, buf, strlen(buf));
            got = plain_lines(&one);
            check_str("startup key hints", got, p);
            free(got);
            tui_lines_clear(&one);
        }
        tui_loaded_section("Skills", items, 3, 1, 40, &l);
        p = plain_lines(&l);
        check_str("loaded section sorted", p, "[Skills]\n  alpha, mid, zeta");
        free(p);
        tui_lines_clear(&l);
        tui_loaded_section("Context", items, 3, 0, 40, &l);
        p = plain_lines(&l);
        check_str("loaded section keeps load order", p, "[Context]\n  zeta, alpha, mid");
        free(p);
        tui_lines_clear(&l);
        check_int("an empty section prints nothing", tui_loaded_section("X", items, 0, 1, 40, &l), 0);
        check_int("and adds no lines", (long)l.n, 0);
    }
    {
        char t[256];
        tui_title("/home/me/work/proj/", NULL, t, sizeof t);
        check_str("terminal title", t, "\x1b]0;pic - proj\x07");
        tui_title("/home/me/work/proj", "my\x1b chat", t, sizeof t);
        check_str("terminal title with a name, controls dropped", t, "\x1b]0;pic - my chat - proj\x07");
        tui_title("/", NULL, t, sizeof t);
        check_str("terminal title at the root", t, "\x1b]0;pic - /\x07");
    }
    pass("view: startup hints, loaded sections, terminal title");
}

static void touch(const char *dir, const char *rel)
{
    char p[512];
    int fd;
    snprintf(p, sizeof p, "%s/%s", dir, rel);
    fd = open(p, O_WRONLY | O_CREAT, 0600);
    if (fd < 0)
        fail("atfile setup", "%s", p);
    close(fd);
}

static void put(const char *dir, const char *rel, const char *text)
{
    char p[512];
    FILE *f;
    snprintf(p, sizeof p, "%s/%s", dir, rel);
    if (!(f = fopen(p, "w")))
        fail("atfile setup", "%s", p);
    fputs(text, f);
    fclose(f);
}

/* What the interface gets from list_files: ignore.c's walk. */
static size_t walk_list(void *ctx, const char *base, atfile_found **out)
{
    pic_ignore_entry *v = NULL;
    size_t n = pic_ignore_walk(base, ATFILE_MAX_ENTRIES, ATFILE_MAX_DEPTH, &v);
    (void)ctx;
    *out = calloc(n ? n : 1, sizeof **out);
    for (size_t i = 0; *out && i < n; i++) {
        (*out)[i].path = v[i].path;
        (*out)[i].is_dir = v[i].is_dir;
        (*out)[i].depth = v[i].depth;
        v[i].path = NULL;
    }
    pic_ignore_entries_free(v, n);
    return *out ? n : 0;
}

static int offers(const char *root, const char *query, const char *value)
{
    atfile_item it[64];
    size_t n = atfile_candidates(root, query, 0, it, 64, walk_list, NULL);
    for (size_t i = 0; i < n; i++)
        if (strcmp(it[i].value, value) == 0)
            return 1;
    return 0;
}

static void test_atfile_ignore(void)
{
    char root[] = "/tmp/pic-atign.XXXXXX", p[512];
    if (!mkdtemp(root))
        fail("atfile ignore", "mkdtemp");
    snprintf(p, sizeof p, "%s/sub", root), mkdir(p, 0700);
    snprintf(p, sizeof p, "%s/gi", root), mkdir(p, 0700);
    snprintf(p, sizeof p, "%s/zi", root), mkdir(p, 0700);
    snprintf(p, sizeof p, "%s/.fossil-settings", root), mkdir(p, 0700);
    snprintf(p, sizeof p, "%s/.zit-settings", root), mkdir(p, 0700);
    snprintf(p, sizeof p, "%s/.zit", root), mkdir(p, 0700);
    snprintf(p, sizeof p, "%s/sub/deep", root), mkdir(p, 0700);
    for (const char *f = "keepme.txt gitgone.txt zitgone.txt fslgone.txt quoted one.txt comma1.txt comma2.txt wsp.txt "
                         "settgone.txt zsettgone.txt sub/keepme.txt sub/subgone.txt sub/deep/subgone.txt sub/rel.o "
                         "gi/inner.txt zi/inner.txt .zit/x .fslckout _FOSSIL_ .fossil-settings/ignore-glob "
                         ".zit-settings/ignore-glob";
         *f;) {
        char name[128];
        size_t k = strcspn(f, " ");
        snprintf(name, sizeof name, "%.*s", (int)k, f);
        if (strcmp(name, ".fossil-settings/ignore-glob") && strcmp(name, ".zit-settings/ignore-glob"))
            touch(root, name);
        f += k + (f[k] != 0);
    }
    put(root, ".gitignore", "gitgone.txt\ngi/\n");
    put(root, ".zitignore", "zitgone.txt\nzi/\n");
    put(root, ".fslignore", "fslgone.txt \"quoted one.txt\",comma1.txt\ncomma2.txt\twsp.txt");
    put(root, ".fossil-settings/ignore-glob", "settgone.txt\n");
    put(root, ".zit-settings/ignore-glob", "zsettgone.txt");
    put(root, "sub/.fslignore", "subgone.txt *.o");
    /* the "quoted one.txt" pattern names a file that does not exist: assert it again below */
    touch(root, "quoted one.txt");
    /* ignore files keep files out of commits, not out of a listing */
    if (!offers(root, "keepme", "@keepme.txt") || !offers(root, "keepme", "@sub/keepme.txt"))
        fail("atfile ignore", "kept files missing");
    if (!offers(root, "gitgone", "@gitgone.txt") || !offers(root, "inner", "@gi/inner.txt") || !offers(root, "gi", "@gi/"))
        fail("atfile ignore", ".gitignore leaves files out");
    if (!offers(root, "zitgone", "@zitgone.txt") || !offers(root, "inner", "@zi/inner.txt"))
        fail("atfile ignore", ".zitignore leaves files out");
    if (!offers(root, "fslgone", "@fslgone.txt") || !offers(root, "quoted", "@\"quoted one.txt\"") ||
        !offers(root, "comma1", "@comma1.txt") || !offers(root, "comma2", "@comma2.txt") || !offers(root, "wsp", "@wsp.txt"))
        fail("atfile ignore", ".fslignore leaves files out");
    if (!offers(root, "subgone", "@sub/subgone.txt") || !offers(root, "rel", "@sub/rel.o") ||
        !offers(root, "subgone", "@sub/deep/subgone.txt"))
        fail("atfile ignore", "sub/.fslignore leaves files out");
    if (!offers(root, "settgone", "@settgone.txt") || !offers(root, "zsettgone", "@zsettgone.txt"))
        fail("atfile ignore", "settings ignore-glob leaves files out");
    if (offers(root, "", "@.zit/") || offers(root, "", "@.fossil-settings/") || offers(root, "", "@.zit-settings/") ||
        offers(root, "fslckout", "@.fslckout") || offers(root, "FOSSIL", "@_FOSSIL_") || offers(root, "x", "@.zit/x"))
        fail("atfile ignore", "version-control metadata offered");
    snprintf(p, sizeof p, "rm -rf '%s'", root);
    if (system(p) != 0)
        fail("atfile ignore cleanup", "rm");
    pass("@file completion honours .gitignore, .zitignore, .fslignore, ignore-glob settings");
}

static void test_atfile(void)
{
    char root[] = "/tmp/pic-atfile.XXXXXX", p[512], q[256];
    atfile_item it[8];
    size_t start, n;
    int quoted;
    const char *txt = "see @src/ma and more";
    tui_editor *e = tui_editor_new();

    if (!mkdtemp(root))
        fail("atfile", "mkdtemp");
    snprintf(p, sizeof p, "%s/src", root), mkdir(p, 0700);
    snprintf(p, sizeof p, "%s/src/deep", root), mkdir(p, 0700);
    snprintf(p, sizeof p, "%s/.git", root), mkdir(p, 0700);
    snprintf(p, sizeof p, "%s/node_modules", root), mkdir(p, 0700);
    touch(root, "src/main.c");
    touch(root, "src/deep/main.h");
    touch(root, "README.md");
    touch(root, "a b.txt");
    touch(root, ".git/config");
    touch(root, "node_modules/x.js");

    if (!atfile_token(txt, 11, &start, q, sizeof q, &quoted) || start != 4 || strcmp(q, "src/ma") != 0 || quoted)
        fail("atfile token", "start %zu query '%s'", start, q);
    if (atfile_token("mail a@b", 8, &start, q, sizeof q, &quoted) || atfile_token("plain", 5, &start, q, sizeof q, &quoted))
        fail("atfile token", "a mid-word @ or no @ must not open the menu");
    if (!atfile_token("go @\"my f", 10, &start, q, sizeof q, &quoted) || !quoted || start != 3 || strcmp(q, "my f") != 0)
        fail("atfile token", "quoted: %zu '%s'", start, q);
    if (!atfile_token("(@a", 3, &start, q, sizeof q, &quoted) || start != 1 || strcmp(q, "a") != 0)
        fail("atfile token", "wrapper: %zu '%s'", start, q);

    n = atfile_candidates(root, "", 0, it, 8, walk_list, NULL);
    if (n != 6 || strcmp(it[0].value, "@src/") != 0 || !it[0].is_dir || strcmp(it[1].value, "@\"a b.txt\"") != 0 ||
        strcmp(it[2].value, "@README.md") != 0 || strcmp(it[3].value, "@src/deep/") != 0 ||
        strcmp(it[4].value, "@src/main.c") != 0 || strcmp(it[5].value, "@src/deep/main.h") != 0)
        fail("atfile empty query", "n %zu: %s %s %s", n, it[0].value, n > 1 ? it[1].value : "", n > 2 ? it[2].value : "");
    for (size_t i = 0; i < n; i++)
        if (strstr(it[i].value, ".git") || strstr(it[i].value, "node_modules"))
            fail("atfile skip", "%s", it[i].value);

    n = atfile_candidates(root, "main", 0, it, 8, walk_list, NULL);
    if (n != 2 || strcmp(it[0].value, "@src/main.c") != 0 || strcmp(it[1].value, "@src/deep/main.h") != 0)
        fail("atfile filter", "n %zu first %s", n, n ? it[0].value : "");
    n = atfile_candidates(root, "mnc", 0, it, 8, walk_list, NULL);
    if (n != 1 || strcmp(it[0].value, "@src/main.c") != 0)
        fail("atfile fuzzy", "n %zu", n);
    n = atfile_candidates(root, "src/de", 0, it, 8, walk_list, NULL);
    if (n != 1 || strcmp(it[0].value, "@src/deep/") != 0 || !it[0].is_dir)
        fail("atfile scoped", "n %zu %s", n, n ? it[0].value : "");
    n = atfile_candidates(root, "src/deep/", 0, it, 8, walk_list, NULL);
    if (n != 1 || strcmp(it[0].value, "@src/deep/main.h") != 0)
        fail("atfile scoped folder", "n %zu", n);
    if (atfile_candidates(root, "nope/", 0, it, 8, walk_list, NULL) != 0 || atfile_candidates(root, "zzzz", 0, it, 8, walk_list, NULL) != 0)
        fail("atfile none", "expected nothing");
    pass("@file token, candidates, filtering, skips");

    tui_editor_set(e, "see @sr and more");
    tui_editor_replace(e, 4, 7, "@src/", 5);
    text_is("replace", e, "see @src/ and more");
    if (tui_editor_cursor(e) != 9)
        fail("replace cursor", "%zu", tui_editor_cursor(e));
    pass("editor replace");
    tui_editor_free(e);

    snprintf(p, sizeof p, "rm -rf '%s'", root);
    if (system(p) != 0)
        fail("atfile cleanup", "rm");
}

/* ---- the fullscreen viewport ------------------------------------------ */

static void scroll_is(const char *what, const tui_scroll *s, size_t top, int follow)
{
    if (s->top != top || s->follow != follow)
        fail(what, "top %zu follow %d, want top %zu follow %d", s->top, s->follow, top, follow);
}

static const char *vp_lines[] = {"hello world", "\x1b[1mbold\x1b[0m  ", "xyz"};

static const char *vp_line_at(void *ctx, size_t i)
{
    (void)ctx;
    return i < 3 ? vp_lines[i] : "";
}

static void test_viewport(void)
{
    tui_scroll s;
    tui_scrollbar g;
    tui_wheel w;
    tui_selection sel;
    tui_point a, b;
    size_t c0, c1;
    char *t;

    /* follow: new content keeps the end in view */
    tui_scroll_init(&s);
    tui_scroll_layout(&s, 10, 4);
    scroll_is("follow layout", &s, 6, 1);
    tui_scroll_layout(&s, 12, 4);
    scroll_is("follow grows", &s, 8, 1);
    /* scrolling up stops following; growth keeps the top */
    if (!tui_scroll_by(&s, -3))
        fail("scroll up", "did not move");
    scroll_is("scroll up", &s, 5, 0);
    tui_scroll_layout(&s, 20, 4);
    scroll_is("no follow grows", &s, 5, 0);
    /* reaching the end follows again */
    (void)tui_scroll_by(&s, 100);
    scroll_is("scroll to end", &s, 16, 1);
    tui_scroll_layout(&s, 25, 4);
    scroll_is("follow again", &s, 21, 1);
    if (tui_scroll_by(&s, 1))
        fail("scroll past end", "moved");
    (void)tui_scroll_by(&s, -100);
    scroll_is("scroll past start", &s, 0, 0);
    /* a taller viewport clamps the top; content that fits follows */
    (void)tui_scroll_by(&s, 10);
    tui_scroll_layout(&s, 25, 20);
    scroll_is("taller clamps", &s, 5, 1);
    tui_scroll_layout(&s, 3, 20);
    scroll_is("fits", &s, 0, 1);
    tui_scroll_layout(&s, 50, 10);
    tui_scroll_start(&s);
    scroll_is("start", &s, 0, 0);
    tui_scroll_end(&s);
    scroll_is("end", &s, 40, 1);
    /* PageUp/PageDown: the height less 4 lines of overlap, at least 1 */
    if (tui_scroll_page(&s, -1) != -6 || tui_scroll_page(&s, 1) != 6)
        fail("page", "%ld %ld", tui_scroll_page(&s, -1), tui_scroll_page(&s, 1));
    tui_scroll_layout(&s, 50, 3);
    if (tui_scroll_page(&s, -1) != -1)
        fail("page short", "%ld", tui_scroll_page(&s, -1));
    pass("viewport scrolling follows the end, PageUp/PageDown overlap 4 lines");

    /* Pi's scrollbar geometry */
    tui_scroll_init(&s);
    tui_scroll_layout(&s, 100, 10);
    s.top = 0, s.follow = 0;
    if (!tui_scrollbar_geometry(&s, &g) || g.thumb_top != 0 || g.thumb_height != 2)
        fail("bar top", "%zu+%zu", g.thumb_top, g.thumb_height);
    s.top = 45;
    if (!tui_scrollbar_geometry(&s, &g) || g.thumb_top != 4 || g.thumb_height != 2)
        fail("bar middle", "%zu+%zu", g.thumb_top, g.thumb_height);
    s.top = 90;
    if (!tui_scrollbar_geometry(&s, &g) || g.thumb_top != 8)
        fail("bar end", "%zu+%zu", g.thumb_top, g.thumb_height);
    tui_scroll_layout(&s, 20, 10);
    s.top = 0;
    if (!tui_scrollbar_geometry(&s, &g) || g.thumb_height != 5 || g.thumb_top != 0)
        fail("bar half", "%zu+%zu", g.thumb_top, g.thumb_height);
    tui_scroll_layout(&s, 4, 10);
    if (!tui_scrollbar_geometry(&s, &g) || g.thumb_height != 10)
        fail("bar fits", "%zu+%zu", g.thumb_top, g.thumb_height);
    tui_scroll_layout(&s, 4, 0);
    if (tui_scrollbar_geometry(&s, &g))
        fail("bar no rows", "drawn");
    if (tui_scrollbar_mode("always") != TUI_BAR_ALWAYS || tui_scrollbar_mode("hidden") != TUI_BAR_HIDDEN ||
        tui_scrollbar_mode("auto") != TUI_BAR_AUTO || tui_scrollbar_mode(NULL) != TUI_BAR_AUTO ||
        tui_scrollbar_mode("bogus") != TUI_BAR_AUTO)
        fail("bar mode", "parse");
    pass("viewport scrollbar geometry");

    /* the wheel: fixed counts, auto without acceleration, auto with it */
    tui_wheel_init(&w, 3, 1);
    if (tui_wheel_next(&w, 1, 0) != 3)
        fail("wheel fixed", "not 3");
    tui_wheel_init(&w, 0, 0);
    if (tui_wheel_next(&w, 1, 0) != 1 || tui_wheel_next(&w, 1, 10) != 1)
        fail("wheel auto macOS", "not 1");
    tui_wheel_init(&w, 0, 1);
    if (tui_wheel_next(&w, 1, 1000) != 1)
        fail("wheel first", "not 1");
    if (tui_wheel_next(&w, 1, 1020) != 5)
        fail("wheel fast", "20 ms apart is not 5");
    if (tui_wheel_next(&w, 1, 1022) != 1)
        fail("wheel burst", "2 ms apart is not 1");
    if (tui_wheel_next(&w, -1, 1030) != 1)
        fail("wheel reverse", "a new direction is not 1");
    if (tui_wheel_next(&w, -1, 1035) != 6)
        fail("wheel max", "5 ms apart is not 6");
    if (tui_wheel_next(&w, -1, 2000) != 1)
        fail("wheel pause", "a new gesture is not 1");
    tui_wheel_init(&w, 0, 1);
    (void)tui_wheel_next(&w, 1, 0);
    if (tui_wheel_next(&w, 1, 100) != 1 || tui_wheel_next(&w, 1, 150) != 1 || tui_wheel_next(&w, 1, 200) != 1 ||
        tui_wheel_next(&w, 1, 250) != 2)
        fail("wheel carry", "the fraction is not carried");
    if (tui_wheel_lines("auto") != 0 || tui_wheel_lines(NULL) != 0 || tui_wheel_lines("3") != 3 ||
        tui_wheel_lines("0") != 1 || tui_wheel_lines("500") != 100 || tui_wheel_lines("x") != 0)
        fail("wheel lines", "parse");
    pass("viewport wheel lines follow Pi's accelerator");

    /* selection: ordered bounds, columns per line, the text */
    memset(&sel, 0, sizeof sel);
    sel.on = 1;
    sel.anchor = (tui_point){2, 1};
    sel.focus = sel.anchor;
    if (tui_selection_bounds(&sel, &a, &b))
        fail("selection click", "a click selected");
    sel.focus = (tui_point){0, 6};
    if (!tui_selection_bounds(&sel, &a, &b) || a.line != 0 || a.col != 6 || b.line != 2 || b.col != 1)
        fail("selection bounds", "%zu:%zu-%zu:%zu", a.line, a.col, b.line, b.col);
    if (!tui_selection_cols(&sel, 0, 11, &c0, &c1) || c0 != 6 || c1 != 11)
        fail("selection first", "%zu-%zu", c0, c1);
    if (!tui_selection_cols(&sel, 1, 6, &c0, &c1) || c0 != 0 || c1 != 6)
        fail("selection middle", "%zu-%zu", c0, c1);
    if (!tui_selection_cols(&sel, 2, 3, &c0, &c1) || c0 != 0 || c1 != 2)
        fail("selection last", "%zu-%zu", c0, c1);
    if (tui_selection_cols(&sel, 3, 3, &c0, &c1))
        fail("selection after", "selected");
    t = tui_selection_text(&sel, vp_line_at, NULL);
    check_str("selection text", t ? t : "(null)", "world\nbold\nxy");
    free(t);
    sel.on = 0;
    if (tui_selection_text(&sel, vp_line_at, NULL))
        fail("selection off", "text");
    pass("viewport selection bounds and text");

    t = tui_line_plain("a\xe7\x95\x8c" "b", 1, 3);
    check_str("plain wide", t, "\xe7\x95\x8c");
    free(t);
    t = tui_line_plain("a\xe7\x95\x8c" "b", 2, 4);
    check_str("plain wide start", t, "b");
    free(t);
    t = tui_line_plain("\x1b]8;;http://x\x07link\x1b]8;;\x07!", 0, 100);
    check_str("plain osc", t, "link!");
    free(t);
    /* the hyperlink under a column: OSC 8 with or without parameters, BEL or ST */
    {
        static const char ln[] = "see \x1b]8;id=a1;file:///tmp/x.c\x1b\\x.c\x1b]8;;\x1b\\ or \x1b[4m\x1b]8;;https://e.org\x07site\x1b]8;;\x07\x1b[0m.";
        t = tui_line_link_at(ln, 4);
        check_str("link at its first column", t ? t : "(null)", "file:///tmp/x.c");
        free(t);
        t = tui_line_link_at(ln, 6);
        check_str("link at its last column", t ? t : "(null)", "file:///tmp/x.c");
        free(t);
        if ((t = tui_line_link_at(ln, 7)) != NULL)
            fail("link after its end", "%s", t);
        if ((t = tui_line_link_at(ln, 2)) != NULL)
            fail("link before it", "%s", t);
        t = tui_line_link_at(ln, 12);
        check_str("second link, SGR around it", t ? t : "(null)", "https://e.org");
        free(t);
        if ((t = tui_line_link_at(ln, 40)) != NULL)
            fail("past the line", "%s", t);
        if ((t = tui_line_link_at("\x1b]8;;\x1b\\open", 1)) != NULL)
            fail("an empty target is no link", "%s", t);
    }
    t = tui_line_highlight("ab\x1b[1mcd\x1b[0mef", 1, 5);
    check_str("highlight", t, "a\x1b[7mb\x1b[1m\x1b[7mcd\x1b[0m\x1b[7me\x1b[27mf");
    free(t);
    t = tui_line_highlight("abc", 1, 9);
    check_str("highlight to end", t, "a\x1b[7mbc\x1b[27m");
    free(t);
    t = tui_line_bar("abcdef", 5, "|");
    check_str("bar cut", t, "abcd\x1b[0m|");
    free(t);
    t = tui_line_bar("ab", 5, "|");
    check_str("bar pad", t, "ab\x1b[0m  |");
    free(t);
    {
        tui_lines l = {NULL, 0, 0};
        if (tui_line_layout("hello", 10, &l) != 0 || l.n != 1)
            fail("layout fits", "%zu", l.n);
        check_str("layout fits", l.lines[0], "hello");
        tui_lines_clear(&l);
        (void)tui_line_layout("\x1b[44mabc      \x1b[0m", 5, &l);
        if (l.n != 1)
            fail("layout padded", "%zu lines", l.n);
        check_str("layout padded", l.lines[0], "\x1b[44mabc  \x1b[0m");
        tui_lines_clear(&l);
        (void)tui_line_layout("hello world", 5, &l);
        if (l.n != 2)
            fail("layout wraps", "%zu lines", l.n);
        check_str("layout wraps 1", l.lines[0], "hello");
        check_str("layout wraps 2", l.lines[1], "world");
        tui_lines_clear(&l);
    }
    pass("viewport line plain text, highlight, scrollbar cell, layout");
}

static void mouse_is(const char *what, const char *bytes, int mouse, int button, int x, int y, int alt)
{
    tui_keys *k = tui_keys_new();
    tui_key key;
    tui_keys_feed(k, bytes, strlen(bytes));
    if (!tui_keys_next(k, &key) || key.kind != TUI_KEY_MOUSE)
        fail(what, "not a mouse event");
    if (key.mouse != mouse || key.button != button || key.mx != x || key.my != y || key.alt != alt)
        fail(what, "got %d %d %d,%d alt %d", key.mouse, key.button, key.mx, key.my, key.alt);
    if (tui_keys_next(k, &key))
        fail(what, "more than one key");
    tui_keys_free(k);
}

static void test_keys_fullscreen(void)
{
    tui_key_kind one = TUI_KEY_CTRL_HOME;
    keys_are("ctrl+home", "\x1b[1;5H", 7, &one, 1);
    one = TUI_KEY_CTRL_END;
    keys_are("ctrl+end", "\x1b[1;5F", 7, &one, 1);
    one = TUI_KEY_HOME;
    keys_are("plain home", "\x1b[H", 3, &one, 1);
    mouse_is("left press", "\x1b[<0;10;5M", TUI_MOUSE_PRESS, 0, 9, 4, 0);
    mouse_is("left drag", "\x1b[<32;12;6M", TUI_MOUSE_DRAG, 0, 11, 5, 0);
    mouse_is("left release", "\x1b[<0;12;6m", TUI_MOUSE_RELEASE, 0, 11, 5, 0);
    mouse_is("wheel up", "\x1b[<64;1;1M", TUI_MOUSE_WHEEL, -1, 0, 0, 0);
    mouse_is("wheel down", "\x1b[<65;3;2M", TUI_MOUSE_WHEEL, 1, 2, 1, 0);
    mouse_is("alt wheel", "\x1b[<72;3;2M", TUI_MOUSE_WHEEL, -1, 2, 1, 1);
    mouse_is("right press", "\x1b[<2;3;2M", TUI_MOUSE_PRESS, 2, 2, 1, 0);
    pass("term: ctrl+home/end and SGR mouse reports decode");
}

/* ---- render: fullscreen --------------------------------------------- */

/* a row written over what is there, then cleared to its end; ROWF: one as wide as the screen, not cleared */
#define ROW(n, s) "\x1b[" #n ";1H" s "\x1b[0m\x1b[K"
#define ROWF(n, s) "\x1b[" #n ";1H" s "\x1b[0m"

static char fs_got[65536];

/* Everything written since the last call. */
static const char *fs_read(void)
{
    size_t o = 0;
    ssize_t n;
    while (o < sizeof fs_got - 1 && (n = read(rfd[0], fs_got + o, sizeof fs_got - 1 - o)) > 0)
        o += (size_t)n;
    fs_got[o] = 0;
    return fs_got;
}

static void fs_has(const char *what, const char *got, const char *want)
{
    char a[2048], b[512];
    if (!strstr(got, want)) {
        show(got, strlen(got), a, sizeof a);
        show(want, strlen(want), b, sizeof b);
        fail(what, "no \"%s\" in \"%s\"", b, a);
    }
}

static void fs_lacks(const char *what, const char *got, const char *want)
{
    char a[2048];
    if (strstr(got, want)) {
        show(got, strlen(got), a, sizeof a);
        fail(what, "unexpected \"%s\" in \"%s\"", want, a);
    }
}

static void test_render_fullscreen(void)
{
    const char *t123[] = {"t1", "t2", "t3"}, *dock[] = {"ed", "ft"}, *body[] = {"b1", "ed", "ft"};
    const char *got;
    char *sel;
    if (pipe(rfd) != 0)
        fail("render fullscreen", "pipe");
    fcntl(rfd[0], F_SETFL, fcntl(rfd[0], F_GETFL) | O_NONBLOCK);
    tui_render *r = tui_render_new(rfd[1]);

    /* Lines committed before fullscreen are part of the transcript. */
    tui_render_commit(r, t123, 1);
    (void)fs_read();
    tui_render_options(r, TUI_BAR_HIDDEN, 1);
    check_int("fullscreen on", tui_render_fullscreen(r, 1, 40, 4), 0);
    check_int("is fullscreen", tui_render_is_fullscreen(r), 1);
    got = fs_read();
    fs_has("enter", got, "\x1b[?1049h");
    fs_has("mouse on", got, "\x1b[?1006h");
    tui_render_commit(r, t123 + 1, 2);
    check_str("commit draws nothing", fs_read(), "");

    /* the viewport (2 rows) shows the end; the dock is pinned below */
    tui_render_draw_split(r, dock, 2, 0, 0, 2, 4);
    check_str("first frame", fs_read(),
              SYNC_ON HIDE "\x1b[2J" ROW(1, "t2") ROW(2, "t3") ROW(3, "ed") ROW(4, "ft") "\x1b[3;3H" SHOW SYNC_OFF);
    tui_render_draw_split(r, dock, 2, 0, 0, 2, 4);
    check_str("same frame", fs_read(), SYNC_ON HIDE "\x1b[3;3H" SHOW SYNC_OFF);
    /* live lines before split end the transcript */
    tui_render_draw_split(r, body, 3, 1, 1, 0, 4);
    check_str("live line", fs_read(), SYNC_ON HIDE ROW(1, "t3") ROW(2, "b1") "\x1b[3;1H" SHOW SYNC_OFF);

    /* PageUp: Pi's height - 4, at least a line; the view stops following */
    check_int("page up", tui_render_page(r, -1), 1);
    tui_render_draw_split(r, body, 3, 1, -1, 0, 4);
    got = fs_read();
    fs_has("page up row 1", got, ROW(1, "t2"));
    fs_has("jump button", got, "\xe2\x86\x93 ");
    fs_lacks("cursor hidden", got, SHOW);
    /* a commit does not move a view that was scrolled up */
    tui_render_commit(r, t123, 1);
    tui_render_draw_split(r, body, 3, 1, -1, 0, 4);
    check_str("scrolled view stays", fs_read(), SYNC_ON HIDE SYNC_OFF);
    check_int("to the top", tui_render_edge(r, 0), 1);
    tui_render_draw_split(r, body, 3, 1, -1, 0, 4);
    fs_has("top row", fs_read(), ROW(1, "t1"));
    check_int("to the end", tui_render_edge(r, 1), 1);
    tui_render_draw_split(r, body, 3, 1, -1, 0, 4);
    got = fs_read();
    fs_has("end rows 2", got, ROW(2, "b1"));
    check_int("scroll past end", tui_render_scroll(r, 5), 0);
    check_int("scroll up", tui_render_scroll(r, -1), 1);
    check_int("scroll down", tui_render_scroll(r, 1), 1);

    /* selection: press, drag, release; the text and the highlight */
    check_int("press", tui_render_mouse(r, TUI_MOUSE_PRESS, 0, 0), 0);
    check_int("drag", tui_render_mouse(r, TUI_MOUSE_DRAG, 0, 1), 0);
    check_int("release", tui_render_mouse(r, TUI_MOUSE_RELEASE, 1, 1), 1);
    sel = tui_render_selection(r);
    check_str("selection", sel ? sel : "(null)", "t1\nb1");
    free(sel);
    tui_render_draw_split(r, body, 3, 1, -1, 0, 4);
    fs_has("highlight", fs_read(), "\x1b[7mt1");
    check_int("click in the dock", tui_render_mouse(r, TUI_MOUSE_PRESS, 0, 3), 0);
    check_int("click release", tui_render_mouse(r, TUI_MOUSE_RELEASE, 0, 3), 0);
    if (tui_render_selection(r))
        fail("click clears", "still selected");

    /* the scrollbar: always, in the last column */
    tui_render_options(r, TUI_BAR_ALWAYS, 1);
    tui_render_draw_split(r, body, 3, 1, -1, 0, 4);
    fs_has("scrollbar", fs_read(), "\xe2\x94\x83"); /* the thumb */

    /* resize: wide lines are laid out again */
    tui_render_options(r, TUI_BAR_HIDDEN, 1);
    {
        const char *wide[] = {"hello world"};
        tui_render_commit(r, wide, 1);
    }
    tui_render_size(r, 5, 6);
    tui_render_invalidate(r);
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 6);
    got = fs_read();
    fs_has("resize clears", got, "\x1b[2J");
    fs_has("resize wraps 1", got, ROWF(3, "hello"));
    fs_has("resize wraps 2", got, ROWF(4, "world"));

    /* pause and resume keep the transcript, print nothing */
    check_int("pause", tui_render_pause(r), 0);
    got = fs_read();
    fs_has("pause leaves", got, "\x1b[?1049l");
    fs_lacks("pause prints nothing", got, "t1");
    check_int("resume", tui_render_resume(r), 0);
    fs_has("resume enters", fs_read(), "\x1b[?1049h");
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 6);
    fs_has("resume redraws", fs_read(), ROWF(3, "hello"));

    /* finish: leave, then the transcript and the dock on the normal screen */
    tui_render_size(r, 40, 6);
    check_int("finish", tui_render_finish(r), 0);
    got = fs_read();
    fs_has("finish leaves", got, "\x1b[?1049l");
#define PR(s) "\r\x1b[2K" s "\x1b[0m\r\n"
    fs_has("finish prints", got, PR("t1") PR("t2") PR("t3") PR("t1") PR("hello world") PR("ed") PR("ft"));
    if (strstr(got, "\x1b[?1049l") > strstr(got, PR("t1")))
        fail("finish order", "printed before leaving");
    check_int("finished", tui_render_is_fullscreen(r), 0);
    tui_render_free(r);

    /* resume-hint: finish only leaves */
    r = tui_render_new(rfd[1]);
    tui_render_commit(r, t123, 3);
    tui_render_options(r, TUI_BAR_AUTO, 0);
    (void)tui_render_fullscreen(r, 1, 40, 4);
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 4);
    (void)fs_read();
    (void)tui_render_finish(r);
    got = fs_read();
    fs_has("hint leaves", got, "\x1b[?1049l");
    fs_lacks("hint prints nothing", got, "t1");
    tui_render_free(r);

    /* switching off prints the transcript; regular drawing goes on */
    r = tui_render_new(rfd[1]);
    tui_render_commit(r, t123, 3);
    (void)tui_render_fullscreen(r, 1, 40, 4);
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 4);
    (void)fs_read();
    check_int("switch off", tui_render_fullscreen(r, 0, 40, 4), 0);
    got = fs_read();
    fs_has("switch off leaves", got, "\x1b[?1049l");
    fs_has("switch off prints", got, PR("t1") PR("t2") PR("t3"));
    fs_lacks("switch off: no dock", got, "ed");
    tui_render_draw_split(r, dock, 2, 0, 1, 1, 24);
    check_str("regular after switch", fs_read(), SYNC_ON HIDE "ed\r\nft" "\r" "\x1b[2G" SHOW SYNC_OFF);
    check_int("regular scroll is a no-op", tui_render_scroll(r, -1), 0);
    tui_render_free(r);
    tui_term_restore();
    close(rfd[0]);
    close(rfd[1]);
    pass("render: fullscreen viewport, dock, scrolling, selection, resize, exit output");
}


/* A row as wide as the screen keeps its last column: it is cleared before it
 * is written, never erased after (the cursor stays on the last column). */
/* Mouse tracking follows tui_term_mouse; off, alternate scroll is off too and the terminal's own is put back
 * on leaving; OSC 52 is capped and wrapped for tmux. */
static void test_mouse_modes(void)
{
    const char *got;
    char *o;
    size_t n;
    if (pipe(rfd) != 0)
        fail("mouse modes", "pipe");
    fcntl(rfd[0], F_SETFL, fcntl(rfd[0], F_GETFL) | O_NONBLOCK);
    tui_render *r = tui_render_new(rfd[1]);
    tui_render_options(r, TUI_BAR_HIDDEN, 0);
    tui_term_mouse(0);
    check_int("mouse not wanted", tui_term_mouse_wanted(), 0);
    (void)tui_render_fullscreen(r, 1, 40, 4);
    got = fs_read();
    fs_has("off: alternate screen", got, "\x1b[?1049h");
    fs_lacks("off: no tracking", got, "\x1b[?1000h");
    fs_has("off: no alternate scroll", got, "\x1b[?1007l");
    {
        const char *ln[] = {"go \x1b]8;;https://e.org\x1b\\here\x1b]8;;\x1b\\"}, *dock[] = {"ed"};
        char *u;
        (void)tui_render_commit(r, ln, 1);
        (void)tui_render_draw_split(r, dock, 1, 0, 0, 0, 4);
        (void)fs_read();
        u = tui_render_link_at(r, 4, 0);
        check_str("render: the link under the pointer", u ? u : "(null)", "https://e.org");
        free(u);
        if ((u = tui_render_link_at(r, 1, 0)) != NULL)
            fail("render: no link there", "%s", u);
        if ((u = tui_render_link_at(r, 4, 3)) != NULL)
            fail("render: the dock has no links", "%s", u);
    }
    tui_term_mouse(1);
    got = fs_read();
    fs_has("on at once", got, "\x1b[?1000h\x1b[?1002h\x1b[?1006h");
    tui_term_mouse(1);
    check_str("on twice writes nothing", fs_read(), "");
    tui_term_mouse(0);
    got = fs_read();
    fs_has("released at once", got, "\x1b[?1006l\x1b[?1002l\x1b[?1000l\x1b[?1007l");
    tui_term_alt_scroll_was(1);
    (void)tui_render_pause(r);
    got = fs_read();
    fs_has("pause: alternate scroll put back", got, "\x1b[?1007h");
    fs_has("pause: tracking off", got, "\x1b[?1000l");
    fs_has("pause: wrap back on", got, "\x1b[?7h");
    (void)tui_render_resume(r);
    got = fs_read();
    fs_lacks("resume keeps it released", got, "\x1b[?1000h");
    fs_has("resume: no alternate scroll", got, "\x1b[?1007l");
    tui_term_alt_scroll_was(0);
    tui_term_mouse(1);
    (void)fs_read();
    (void)tui_render_finish(r);
    got = fs_read();
    fs_lacks("tracking was on: nothing to put back", got, "\x1b[?1007h");
    tui_render_free(r);
    tui_term_restore();
    close(rfd[0]);
    close(rfd[1]);

    o = tui_term_osc52("hi", 2, 0, &n);
    check_str("osc 52", o ? o : "(null)", "\x1b]52;c;aGk=\x07");
    check_int("osc 52 length", (long)n, 12);
    free(o);
    o = tui_term_osc52("hi", 2, 1, &n);
    check_str("osc 52 in tmux", o ? o : "(null)", "\x1bPtmux;\x1b\x1b]52;c;aGk=\x07\x1b\\");
    free(o);
    {
        size_t big = TUI_OSC52_MAX + 1;
        char *b = malloc(big);
        if (!b)
            fail("osc 52", "malloc");
        memset(b, 'a', big);
        if ((o = tui_term_osc52(b, big, 0, &n)) != NULL)
            fail("osc 52 over the cap", "%zu bytes", n);
        o = tui_term_osc52(b, TUI_OSC52_MAX, 0, &n);
        if (!o)
            fail("osc 52 at the cap", "NULL");
        free(o);
        free(b);
    }
    pass("mouse tracking on and off, alternate scroll, OSC 52");
}

static void test_render_fullwidth(void)
{
    const char *full[] = {"abcd"}, *dock[] = {"wxyz"};
    const char *got;
    if (pipe(rfd) != 0)
        fail("render fullwidth", "pipe");
    fcntl(rfd[0], F_SETFL, fcntl(rfd[0], F_GETFL) | O_NONBLOCK);
    tui_render *r = tui_render_new(rfd[1]);
    tui_render_commit(r, full, 1);
    (void)fs_read();
    tui_render_options(r, TUI_BAR_AUTO, 0);
    (void)tui_render_fullscreen(r, 1, 4, 3);
    (void)fs_read();
    tui_render_draw_split(r, dock, 1, 0, -1, 0, 3);
    got = fs_read();
    fs_has("full-width row", got, ROWF(1, "abcd"));
    fs_has("full-width dock row", got, ROWF(3, "wxyz"));
    fs_lacks("no erase after a full-width row", got, "abcd\x1b[0m\x1b[K");
    fs_lacks("no erase after a full-width dock row", got, "wxyz\x1b[0m\x1b[K");
    fs_lacks("no row cleared before it is written", got, "\x1b[2K");
    (void)tui_render_finish(r);
    tui_render_free(r);
    tui_term_restore();
    close(rfd[0]);
    close(rfd[1]);
    pass("render: fullscreen rows as wide as the screen keep their last column");
}


/* ---- transcript: committed items drawn again on Ctrl+O and Ctrl+T ---------- */

/* The lines joined with "\n", escape sequences removed. */
static char *plain_join(const tui_lines *l)
{
    size_t cap = 1, o = 0;
    for (size_t i = 0; i < l->n; i++)
        cap += strlen(l->lines[i]) + 1;
    char *out = malloc(cap);
    for (size_t i = 0; i < l->n; i++) {
        for (const char *p = l->lines[i]; *p; p++) {
            if (*p == 0x1b) {
                p++;
                if (*p == '[')
                    while (p[1] && !(p[1] >= 0x40 && p[1] <= 0x7e))
                        p++;
                if (*p)
                    p++;
                if (!*p)
                    break;
                continue;
            }
            out[o++] = *p;
        }
        out[o++] = '\n';
    }
    out[o] = 0;
    return out;
}

static void plain_has(const char *what, const char *got, const char *want, int yes)
{
    if ((strstr(got, want) != NULL) != yes)
        fail(what, "%s \"%s\" in:\n%s", yes ? "no" : "unexpected", want, got);
}

/* The settings panel's box: centred over the viewport, above it; the cursor in it; an unchanged frame
 * writes no row; gone, the rows under it come back. */
static void test_render_box(void)
{
    const char *hist[] = {"h1", "h2", "h3", "h4", "h5", "h6"}, *dock[] = {"ed", "ft"};
    const char *box[] = {"+--------+", "|  box   |", "+--------+"};
    const char *got;
    if (pipe(rfd) != 0)
        fail("render box", "pipe");
    fcntl(rfd[0], F_SETFL, fcntl(rfd[0], F_GETFL) | O_NONBLOCK);
    tui_render *r = tui_render_new(rfd[1]);
    tui_render_commit(r, hist, 6);
    tui_render_options(r, TUI_BAR_HIDDEN, 0);
    (void)tui_render_fullscreen(r, 1, 20, 8);
    (void)tui_render_draw_split(r, dock, 2, 0, 0, 2, 8);
    (void)fs_read();
    check_int("box", tui_render_box(r, box, 3, 10, 1, 3), 0);
    (void)tui_render_draw_split(r, dock, 2, 0, 0, 2, 8);
    got = fs_read();
    /* six viewport rows: the box on rows 2 to 4, from column 6 */
    fs_has("box top", got, ROW(2, "h2   \x1b[0m+--------+\x1b[0m"));
    fs_has("box middle", got, ROW(3, "h3   \x1b[0m|  box   |\x1b[0m"));
    fs_has("box bottom", got, ROW(4, "h4   \x1b[0m+--------+\x1b[0m"));
    fs_lacks("rows beside the box unchanged", got, "\x1b[1;1H");
    fs_lacks("the dock unchanged", got, "\x1b[7;1H");
    fs_has("the cursor in the box", got, "\x1b[3;9H" SHOW);
    {
        int line, col;
        check_int("a click in the box", tui_render_hit(r, 6, 2, &line, &col), TUI_HIT_BOX);
        check_int("its line", line, 1);
        check_int("its column", col, 1);
        check_int("beside the box", tui_render_hit(r, 4, 2, &line, &col), TUI_HIT_VIEW);
        check_int("above the box", tui_render_hit(r, 6, 0, &line, &col), TUI_HIT_VIEW);
        check_int("on the dock", tui_render_hit(r, 0, 7, &line, &col), TUI_HIT_DOCK);
        check_int("the dock's line", line, 1);
    }
    fs_lacks("no full clear", got, "\x1b[2J");
    (void)tui_render_draw_split(r, dock, 2, 0, 0, 2, 8);
    got = fs_read();
    fs_lacks("an unchanged frame writes no row", got, ";1H");
    check_int("no box", tui_render_box(r, NULL, 0, 0, -1, 0), 0);
    (void)tui_render_draw_split(r, dock, 2, 0, 0, 2, 8);
    got = fs_read();
    fs_has("row 3 back", got, ROW(3, "h3"));
    fs_has("the editor's cursor back", got, "\x1b[7;3H" SHOW);
    (void)tui_render_finish(r);
    tui_render_free(r);
    tui_term_restore();
    close(rfd[0]);
    close(rfd[1]);
    pass("render: a box over the viewport, centred, with its cursor; unchanged rows are not written");
}

static void test_transcript(void)
{
    tui_transcript *t = tui_transcript_new();
    const char *head[] = {"pic fake/m", ""};
    char out[400] = "", *got;
    tui_lines l = {NULL, 0, 0};
    for (int i = 1; i <= 30; i++)
        snprintf(out + strlen(out), sizeof out - strlen(out), "line %d\n", i);
    tui_tool tool = {"read", "f.txt", NULL, out, TUI_TOOL_OK, -1, NULL};
    tui_bash bash = {"seq 30", out, TUI_BASH_DONE, 0, 0};
    if (!t || tui_transcript_lines(t, head, 2) || tui_transcript_thinking(t, "pondering the answer") ||
        tui_transcript_tool(t, &tool) || tui_transcript_bash(t, &bash))
        fail("transcript", "add");
    out[0] = 0; /* the items keep copies */

    tui_transcript_render(t, 0, 0, 40, &l);
    got = plain_join(&l);
    plain_has("collapsed: header kept", got, "pic fake/m", 1);
    plain_has("collapsed: thinking shown", got, "pondering the answer", 1);
    plain_has("collapsed: tool hint", got, "20 more lines, ctrl+o to expand", 1);
    plain_has("collapsed: tool tail hidden", got, "line 30\n  ", 0);
    free(got);
    tui_lines_clear(&l);

    tui_transcript_render(t, 1, 1, 40, &l);
    got = plain_join(&l);
    plain_has("expanded: no hint", got, "ctrl+o to expand", 0);
    plain_has("expanded: every line", got, "  line 30", 1);
    plain_has("hidden: Pi's label", got, "Thinking...", 1);
    plain_has("hidden: no text", got, "pondering", 0);
    free(got);
    tui_lines_clear(&l);

    /* thinking is markdown, as Pi draws it (line breaks kept, as Pi keeps them) */
    tui_thinking_lines("  a **b** `c`\nnext\n\n", 0, 80, &l);
    got = plain_join(&l);
    plain_has("thinking as markdown", got, "a b c\nnext\n", 1);
    check_int("thinking trimmed", (int)l.n, 2);
    free(got);
    tui_lines_clear(&l);

    /* an item with a collapsed and an expanded form (Pi's branch summary) */
    {
        const char *shut[] = {"Branch summary (ctrl+o to expand)"}, *open_[] = {"Branch Summary", "", "what was done"};
        tui_transcript_clear(t);
        if (tui_transcript_expandable(t, shut, 1, open_, 3))
            fail("transcript", "expandable");
        tui_transcript_render(t, 0, 0, 40, &l);
        got = plain_join(&l);
        check_str("expandable collapsed", got, "Branch summary (ctrl+o to expand)\n");
        free(got);
        tui_lines_clear(&l);
        tui_transcript_render(t, 1, 0, 40, &l);
        got = plain_join(&l);
        check_str("expandable expanded", got, "Branch Summary\n\nwhat was done\n");
        free(got);
        tui_lines_clear(&l);
    }

    tui_transcript_clear(t);
    tui_transcript_render(t, 0, 0, 40, &l);
    check_int("cleared", (int)l.n, 0);
    tui_transcript_free(t);
    pass("transcript: tool, bash and thinking items are drawn again for Ctrl+O and Ctrl+T");
}

/* Replacing the committed lines: fullscreen shows them at the next draw;
 * regular mode clears the screen and its scrollback and writes them again
 * (Pi's full redraw), and the live area starts below. */
static void test_render_replace(void)
{
    const char *old[] = {"old1", "old2"}, *now[] = {"new1", "new2", "new3"}, *dock[] = {"ed"};
    const char *got;
    if (pipe(rfd) != 0)
        fail("render replace", "pipe");
    fcntl(rfd[0], F_SETFL, fcntl(rfd[0], F_GETFL) | O_NONBLOCK);
    tui_render *r = tui_render_new(rfd[1]);
    tui_render_commit(r, old, 2);
    tui_render_draw(r, dock, 1, 0, 2, 24);
    (void)fs_read();
    check_int("replace (regular)", tui_render_replace(r, now, 3), 0);
    got = fs_read();
    fs_has("regular: clears screen and scrollback", got, "\x1b[2J\x1b[H\x1b[3J");
    fs_has("regular: writes the new lines", got, "new1\r\nnew2\r\nnew3\r\n");
    fs_lacks("regular: not the old", got, "old1");
    tui_render_draw(r, dock, 1, 0, 2, 24);
    fs_has("regular: the live area again", fs_read(), "ed");

    tui_render_options(r, TUI_BAR_HIDDEN, 1);
    (void)tui_render_fullscreen(r, 1, 20, 6);
    (void)fs_read();
    tui_render_draw_split(r, dock, 1, 0, -1, 0, 6);
    got = fs_read();
    fs_has("fullscreen: before", got, ROW(1, "new1"));
    check_int("replace (fullscreen)", tui_render_replace(r, old, 2), 0);
    check_str("fullscreen: nothing until the draw", fs_read(), "");
    tui_render_draw_split(r, dock, 1, 0, -1, 0, 6);
    got = fs_read();
    fs_has("fullscreen: replaced row 1", got, ROW(1, "old1"));
    fs_has("fullscreen: row 3 cleared", got, ROW(3, ""));
    (void)tui_render_finish(r);
    tui_render_free(r);
    tui_term_restore();
    close(rfd[0]);
    close(rfd[1]);
    pass("render: replacing the committed lines redraws them in both modes");
}


/* ---- transcript search (Pi's alt-screen-search.ts) ---------------------- */

static const char *const *srch_lines;
static const char *srch_at(void *ctx, size_t i)
{
    (void)ctx;
    return srch_lines[i];
}

/* Runs a search over L and checks the hits' segments, written "row:c0-c1,row:c0-c1;..." */
static void find_is(const char *what, const char *const *l, size_t n, const char *query, const char *want)
{
    tui_found f;
    char got[512] = "";
    size_t o = 0;
    srch_lines = l;
    if (tui_search_find(n, srch_at, NULL, query, &f) != 0)
        fail(what, "search failed");
    for (size_t i = 0; i < f.nhits; i++) {
        if (i)
            o += (size_t)snprintf(got + o, sizeof got - o, ";");
        for (size_t j = 0; j < f.hits[i].n; j++) {
            const tui_seg *s = &f.segs[f.hits[i].first + j];
            o += (size_t)snprintf(got + o, sizeof got - o, "%s%zu:%zu-%zu", j ? "," : "", s->row, s->c0, s->c1);
        }
    }
    tui_found_free(&f);
    check_str(what, got, want);
}

static void test_search(void)
{
    const char *l[] = {"Hello World", "hello again", "wor", "ld end"};
    tui_found f;
    tui_scroll s;
    tui_span sp[4];
    tui_lines box = {NULL, 0, 0};
    char *t;

    /* matching: case-insensitive, one text with whitespace collapsed, wrapping across rows */
    find_is("case", l, 4, "world", "0:6-11");
    find_is("a line break is a space", l, 4, "or ld", "2:1-3,3:0-2");
    find_is("both cases", l, 4, "HELLO", "0:0-5;1:0-5");
    find_is("across words", l, 1, "o w", "0:4-5,0:6-7");
    find_is("whitespace in the query", l, 1, "  o   w ", "0:4-5,0:6-7");
    find_is("blank query", l, 4, "   ", "");
    find_is("empty query", l, 4, "", "");
    find_is("no match", l, 4, "zebra", "");
    {
        const char *e[] = {"\x1b[1mfoo\x1b[0mbar", "\xe7\x95\x8c" "a", "\xc3\x84" "B", "aaaa", "tab\there"};
        find_is("escapes take no columns", e, 1, "foobar", "0:0-6");
        find_is("wide characters count two columns", e, 2, "a", "0:4-5;1:2-3");
        find_is("Latin-1 folds", e, 3, "\xc3\xa4" "b", "2:0-2");
        find_is("matches do not overlap", e, 4, "aa", "3:0-2;3:2-4");
        find_is("a tab is a separator", e, 5, "b h", "4:2-3,4:7-8");
    }
    pass("search: matching is case-insensitive over the whole text, with columns");

    /* selection: from the anchor, next and previous wrap, retain clamps */
    srch_lines = l;
    if (tui_search_find(4, srch_at, NULL, "o", &f) != 0 || f.nhits < 3)
        fail("search o", "%zu hits", f.nhits);
    check_int("anchor 0", tui_search_pick(&f, TUI_PICK_QUERY, -1, 0), 0);
    check_int("anchor past the first", tui_search_pick(&f, TUI_PICK_QUERY, -1, 1), 2);
    check_int("anchor past all wraps to the first", tui_search_pick(&f, TUI_PICK_QUERY, -1, 99), 0);
    check_int("next", tui_search_pick(&f, TUI_PICK_NEXT, 0, 0), 1);
    check_int("next wraps", tui_search_pick(&f, TUI_PICK_NEXT, (long)f.nhits - 1, 0), 0);
    check_int("next with none", tui_search_pick(&f, TUI_PICK_NEXT, -1, 0), 0);
    check_int("previous", tui_search_pick(&f, TUI_PICK_PREV, 2, 0), 1);
    check_int("previous wraps", tui_search_pick(&f, TUI_PICK_PREV, 0, 0), (long)f.nhits - 1);
    check_int("previous with none", tui_search_pick(&f, TUI_PICK_PREV, -1, 0), (long)f.nhits - 1);
    check_int("retain clamps", tui_search_pick(&f, TUI_PICK_RETAIN, 99, 0), (long)f.nhits - 1);
    {
        size_t key[4];
        tui_hit_key(&f, 1, key);
        check_int("find by key", tui_found_by_key(&f, key), 1);
        key[1]++;
        check_int("find by a stale key", tui_found_by_key(&f, key), -1);
    }
    tui_found_free(&f);
    check_int("no hits", tui_search_pick(&f, TUI_PICK_NEXT, 0, 0), -1);
    pass("search: selection from the anchor, next/previous wrap");

    /* highlight spans of a row: the selected hit is current */
    if (tui_search_find(4, srch_at, NULL, "world", &f) != 0 || f.nhits != 1)
        fail("search world", "failed");
    check_int("spans on row 0", (long)tui_found_row(&f, 0, 0, sp, 4), 1);
    check_int("span c0", (long)sp[0].c0, 6);
    check_int("span c1", (long)sp[0].c1, 11);
    check_int("span is current", sp[0].current, 1);
    check_int("row 1 has none", (long)tui_found_row(&f, 0, 1, sp, 4), 0);
    tui_found_free(&f);
    if (tui_search_find(4, srch_at, NULL, "or ld", &f) != 0 || f.nhits != 1)
        fail("search or ld", "failed");
    check_int("wrapped hit, row 2", (long)tui_found_row(&f, -1, 2, sp, 4), 1);
    check_int("it is not current", sp[0].current, 0);
    check_int("wrapped hit, row 3", (long)tui_found_row(&f, 0, 3, sp, 4), 1);
    check_int("it is current", sp[0].current, 1);
    check_int("span c1 on the last row", (long)sp[0].c1, 2);
    tui_found_free(&f);
    t = tui_line_style("ab\x1b[1mcd\x1b[0mef", 1, 5, "<", ">");
    check_str("style each run", t, "a<b>\x1b[1m<cd>\x1b[0m<e>f");
    free(t);
    t = tui_line_style("abc", 0, 9, "<", ">");
    check_str("style to the end", t, "<abc>");
    free(t);
    t = tui_line_splice("abcdefgh", 2, 3, "XYZ");
    check_str("splice", t, "ab\x1b[0mXYZ\x1b[0mfgh");
    free(t);
    t = tui_line_splice("ab", 4, 2, "XY");
    check_str("splice pads", t, "ab  \x1b[0mXY\x1b[0m");
    free(t);
    t = tui_line_splice("a\xe7\x95\x8c" "bc", 2, 2, "XY");
    check_str("splice cuts a wide character", t, "a \x1b[0mXY\x1b[0m" "c");
    free(t);
    pass("search: highlight spans, styled runs, splice");

    /* the viewport goes to the match */
    srch_lines = l;
    tui_scroll_init(&s);
    tui_scroll_layout(&s, 100, 12);
    {
        const char *rows[100];
        char buf[100][12];
        for (int i = 0; i < 100; i++) {
            snprintf(buf[i], sizeof buf[i], i == 5 || i == 41 || i == 50 || i == 3 || i == 20 ? "needle" : "x");
            rows[i] = buf[i];
        }
        srch_lines = rows;
        if (tui_search_find(100, srch_at, NULL, "needle", &f) != 0 || f.nhits != 5)
            fail("search needle", "%zu hits", f.nhits);
        tui_scroll_start(&s);
        check_int("in view stays", (long)tui_search_reveal(&s, &f, 1), 0);
        check_int("below: a third of the viewport from the top", (long)tui_search_reveal(&s, &f, 3), 37);
        check_int("further down", (long)tui_search_reveal(&s, &f, 4), 46);
        tui_scroll_to(&s, 40, 0);
        check_int("in view after scrolling", (long)tui_search_reveal(&s, &f, 3), 40);
        check_int("above, near the top", (long)tui_search_reveal(&s, &f, 0), 0);
        check_int("above", (long)tui_search_reveal(&s, &f, 2), 16);
        tui_found_free(&f);
    }
    /* scrollTo: a view that lands on the end holds there instead of following */
    tui_scroll_init(&s);
    tui_scroll_layout(&s, 20, 5);
    tui_scroll_to(&s, 3, 1);
    scroll_is("scrollTo", &s, 3, 0);
    tui_scroll_to(&s, 99, 1);
    scroll_is("scrollTo the end, held", &s, 15, 0);
    tui_scroll_layout(&s, 30, 5);
    scroll_is("held while the text grows", &s, 15, 0);
    tui_scroll_to(&s, 99, 0);
    scroll_is("scrollTo the end follows again", &s, 25, 1);
    tui_scroll_to(&s, 99, 1);
    (void)tui_scroll_by(&s, -1);
    (void)tui_scroll_by(&s, 1);
    scroll_is("scrolling ends the hold", &s, 25, 1);

    /* the box */
    check_int("box", tui_search_box("", -1, 0, "Shift+Enter", "Enter", 40, &box), 0);
    check_int("three rows", (long)box.n, 3);
    fs_has("box top left", box.lines[0], "\xe2\x94\x8c\xe2\x94\x80");
    fs_has("box top right", box.lines[0], "\xe2\x94\x80\xe2\x94\x90");
    for (size_t i = 0; i < 3; i++)
        check_int("box row width", (long)tui_width(box.lines[i], strlen(box.lines[i])), 40);
    fs_has("placeholder", box.lines[1], "\x1b[7m\x1b[2mF\x1b[22m\x1b[27m\x1b[2mind in transcript\x1b[22m");
    fs_has("key hints", box.lines[2], " \xe2\x86\x91 Shift+Enter \xc2\xb7 \xe2\x86\x93 Enter ");
    fs_lacks("no count without a query", box.lines[1], "/");
    tui_lines_clear(&box);
    (void)tui_search_box("wor", 0, 5, "Shift+Enter", "Enter", 40, &box);
    fs_has("query and cursor", box.lines[1], "\xe2\x94\x82 wor\x1b[7m \x1b[27m");
    fs_has("count", box.lines[1], "\x1b[2m 1/5 \x1b[22m\xe2\x94\x82");
    check_int("query row width", (long)tui_width(box.lines[1], strlen(box.lines[1])), 40);
    tui_lines_clear(&box);
    (void)tui_search_box("zzz", -1, 0, "Shift+Enter", "Enter", 40, &box);
    fs_has("no matches", box.lines[1], "No matches");
    tui_lines_clear(&box);
    (void)tui_search_box("wor", 0, 5, "Shift+Enter", "Enter", 20, &box);
    fs_has("short hints", box.lines[2], " \xe2\x86\x91 \xe2\x86\x93 ");
    for (size_t i = 0; i < 3; i++)
        check_int("narrow row width", (long)tui_width(box.lines[i], strlen(box.lines[i])), 20);
    tui_lines_clear(&box);
    (void)tui_search_box("a very long query that cannot fit in the box", 0, 5, "Shift+Enter", "Enter", 32, &box);
    check_int("long query row width", (long)tui_width(box.lines[1], strlen(box.lines[1])), 32);
    fs_has("the tail of the query shows", box.lines[1], "fit in the box\x1b[7m ");
    tui_lines_clear(&box);
    pass("search: reveal");
}

static void test_render_search(void)
{
    const char *dock[] = {"ed", "ft"}, *live[] = {"live needle", "ed", "ft"};
    const char *got;
    long idx;
    if (pipe(rfd) != 0)
        fail("render search", "pipe");
    fcntl(rfd[0], F_SETFL, fcntl(rfd[0], F_GETFL) | O_NONBLOCK);
    tui_render *r = tui_render_new(rfd[1]);
    tui_render_options(r, TUI_BAR_HIDDEN, 1);

    /* regular mode has no search */
    check_int("not in regular mode", tui_render_search_toggle(r), 0);
    check_int("it is not open", tui_render_search_active(r), 0);
    (void)tui_render_fullscreen(r, 1, 60, 8);
    for (int i = 0; i < 30; i++) {
        char line[32];
        const char *c[1] = {line};
        (void)snprintf(line, sizeof line, i == 5 || i == 20 || i == 25 ? "x needle %d" : "line %d", i);
        tui_render_commit(r, c, 1);
    }
    tui_render_search_keys(r, "Shift+Enter", "Enter");
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 8);
    (void)fs_read();

    check_int("opens", tui_render_search_toggle(r), 1);
    check_int("is open", tui_render_search_active(r), 1);
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 8);
    got = fs_read();
    fs_has("the box", got, "ind in transcript");
    fs_has("the hints", got, "\xe2\x86\x91 Shift+Enter \xc2\xb7 \xe2\x86\x93 Enter");
    fs_lacks("no highlight without a query", got, "\x1b[4m");
    tui_render_search_set(r, "NEEDLE");
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 8);
    got = fs_read();
    check_int("three matches", (long)tui_render_search_hits(r, &idx), 3);
    check_int("the first at or after the view's top", idx, 2);
    fs_has("count", got, "\x1b[2m 3/3 \x1b[22m");
    fs_has("the current match", got, "\x1b[1m\x1b[7m");
    fs_lacks("the others are not in view", got, "\x1b[22m 20");

    /* previous scrolls to a match out of view, a third of the viewport down */
    tui_render_search_step(r, -1);
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 8);
    got = fs_read();
    check_int("previous", (long)tui_render_search_hits(r, &idx), 3);
    check_int("it is the second", idx, 1);
    fs_has("scrolled to it", got, "\x1b[22m 20");
    fs_has("count 2", got, "2/3");
    fs_has("it is current", got, "\x1b[1m\x1b[7m");
    tui_render_search_step(r, -1);
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 8);
    got = fs_read();
    check_int("first", (tui_render_search_hits(r, &idx), idx), 0);
    fs_has("scrolled to the top match", got, "\x1b[22m 5 ");
    tui_render_search_step(r, -1);
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 8);
    (void)fs_read();
    check_int("previous wraps", (tui_render_search_hits(r, &idx), idx), 2);
    tui_render_search_step(r, 1);
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 8);
    (void)fs_read();
    check_int("next wraps", (tui_render_search_hits(r, &idx), idx), 0);
    tui_render_search_step(r, 1);
    tui_render_draw_split(r, dock, 2, 0, -1, 0, 8);
    (void)fs_read();
    check_int("next", (tui_render_search_hits(r, &idx), idx), 1);

    /* a reply being written is searched as it grows; the current match stays */
    tui_render_draw_split(r, live, 3, 1, -1, 0, 8);
    (void)fs_read();
    check_int("a match in the live end", (long)tui_render_search_hits(r, &idx), 4);
    check_int("the current one is kept", idx, 1);
    tui_render_search_set(r, "zzz");
    tui_render_draw_split(r, live, 3, 1, -1, 0, 8);
    got = fs_read();
    check_int("none", (long)tui_render_search_hits(r, &idx), 0);
    fs_has("no matches", got, "No matches");

    check_int("closes", tui_render_search_toggle(r), 1);
    check_int("it is closed", tui_render_search_active(r), 0);
    tui_render_draw_split(r, live, 3, 1, -1, 0, 8);
    got = fs_read();
    fs_lacks("the box is gone", got, "ind in transcript");
    fs_lacks("the highlight is gone", got, "\x1b[4m");
    tui_render_free(r);
    tui_term_restore();
    close(rfd[0]);
    close(rfd[1]);
    pass("render: search opens, highlights, steps, scrolls, follows a growing reply, closes");
}


/* ---- themes (Pi's theme model) ----------------------------------------- */

static void rgb_is(const char *what, const tui_theme *t, tui_token tok, int r, int g, int b)
{
    const tui_color *c = &t->c[tok];
    if (c->kind != TUI_COLOR_RGB || c->r != r || c->g != g || c->b != b)
        fail(what, "%s is %d,%d,%d (kind %d), want %d,%d,%d", tui_token_name(tok), c->r, c->g, c->b, c->kind, r, g, b);
}

static void parse_fails(const char *what, const char *json, const char *needle)
{
    tui_theme t;
    char err[2048];
    if (tui_theme_parse(json, strlen(json), "t.json", &t, err, sizeof err) == 0)
        fail(what, "parsed");
    if (!strstr(err, needle))
        fail(what, "message \"%s\" lacks \"%s\"", err, needle);
}

/* A minimal valid theme: every required token set to the variable "c" (a colour), plus EXTRA inside "colors". */
static char *theme_json(const char *top, const char *vars, const char *extra_colors, const char *skip)
{
    char *out = malloc(8192);
    size_t o = (size_t)snprintf(out, 8192, "{%s\"vars\":{%s},\"colors\":{%s", top, vars, extra_colors);
    for (int t = 0; t < TUI_T_N; t++) {
        const char *n = tui_token_name((tui_token)t);
        if (t == TUI_T_SCROLLBAR_TRACK || t == TUI_T_SCROLLBAR_THUMB || t == TUI_T_SEARCH_MATCH_BG ||
            t == TUI_T_SEARCH_MATCH_TEXT || t == TUI_T_THINKING_MAX || (skip && strcmp(skip, n) == 0) ||
            strstr(extra_colors, n))
            continue;
        o += (size_t)snprintf(out + o, 8192 - o, "%s\"%s\":\"c\"", out[o - 1] == '{' || out[o - 1] == ',' ? "" : ",", n);
    }
    snprintf(out + o, 8192 - o, "}}");
    return out;
}

static void test_theme(void)
{
    tui_theme dark, light, t;
    char err[2048];
    int r, g, b;

    /* the conversion against Pi's own okhslToRgb (packages/tui/src/oklab.ts) */
    tui_okhsl_to_rgb(233, 0.41, 0.24, &r, &g, &b);
    check_int("okhsl(233 41% 24%) r", r, 33);
    check_int("okhsl(233 41% 24%) g", g, 59);
    check_int("okhsl(233 41% 24%) b", b, 73);
    tui_okhsl_to_rgb(0, 0, 0.5, &r, &g, &b);
    check_int("okhsl gray r=g", r == g && g == b, 1);
    pass("theme: okhsl conversion");

    if (tui_theme_builtin("dark", &dark) != 0 || tui_theme_builtin("light", &light) != 0)
        fail("builtin themes", "do not parse");
    check_str("dark name", dark.name, "dark");
    check_int("dark appearance", dark.appearance, 0);
    check_int("light appearance", light.appearance, 1);
    check_int("no other built-in", tui_theme_builtin("solarized", &t), -1);
    /* five tokens each, exact sRGB (the values Pi's own conversion gives for dark.json and light.json) */
    rgb_is("dark userMessageBg", &dark, TUI_T_USER_MESSAGE_BG, 33, 59, 73);
    rgb_is("dark border", &dark, TUI_T_BORDER, 95, 168, 204);
    rgb_is("dark mdHeading", &dark, TUI_T_MD_HEADING, 205, 154, 34);
    rgb_is("dark syntaxKeyword", &dark, TUI_T_SYNTAX_KEYWORD, 105, 173, 208);
    rgb_is("dark toolSuccessBg", &dark, TUI_T_TOOL_SUCCESS_BG, 37, 65, 49);
    rgb_is("light userMessageBg", &light, TUI_T_USER_MESSAGE_BG, 223, 231, 236);
    rgb_is("light border", &light, TUI_T_BORDER, 61, 142, 179);
    rgb_is("light mdHeading", &light, TUI_T_MD_HEADING, 143, 104, 2);
    rgb_is("light syntaxKeyword", &light, TUI_T_SYNTAX_KEYWORD, 47, 120, 153);
    rgb_is("light toolSuccessBg", &light, TUI_T_TOOL_SUCCESS_BG, 222, 233, 225);
    /* a variable reference resolves to the variable's colour; the optional tokens inherit */
    rgb_is("dark accent is violet", &dark, TUI_T_ACCENT, 167, 152, 215);
    rgb_is("dark mdListBullet is violet", &dark, TUI_T_MD_LIST_BULLET, 167, 152, 215);
    check_int("dark scrollbarTrack is its own", dark.c[TUI_T_SCROLLBAR_TRACK].kind, TUI_COLOR_RGB);
    pass("theme: built-in dark and light, exact RGB");

    {
        char *j = theme_json("\"name\":\"mine\",", "\"c\":\"#102030\"", "\"muted\":\"#0af\",\"text\":\"\",\"accent\":39,", NULL);
        if (tui_theme_parse(j, strlen(j), "mine.json", &t, err, sizeof err) != 0)
            fail("custom theme", "%s", err);
        check_str("custom name", t.name, "mine");
        check_int("appearance not declared", t.appearance, -1);
        rgb_is("hex #102030", &t, TUI_T_BORDER, 0x10, 0x20, 0x30);
        rgb_is("hex #0af", &t, TUI_T_MUTED, 0x00, 0xaa, 0xff);
        check_int("\"\" is the terminal default", t.c[TUI_T_TEXT].kind, TUI_COLOR_DEFAULT);
        check_int("an integer is a 256-colour index", t.c[TUI_T_ACCENT].kind, TUI_COLOR_INDEX);
        check_int("the index", t.c[TUI_T_ACCENT].index, 39);
        rgb_is("scrollbarTrack falls back to muted", &t, TUI_T_SCROLLBAR_TRACK, 0x00, 0xaa, 0xff);
        check_int("scrollbarThumb falls back to text (the default)", t.c[TUI_T_SCROLLBAR_THUMB].kind, TUI_COLOR_DEFAULT);
        rgb_is("searchMatchBg falls back to selectedBg", &t, TUI_T_SEARCH_MATCH_BG, 0x10, 0x20, 0x30);
        rgb_is("thinkingMax falls back to thinkingXhigh", &t, TUI_T_THINKING_MAX, 0x10, 0x20, 0x30);
        free(j);
        j = theme_json("\"name\":\"m\",\"appearance\":\"light\",\"$schema\":\"x\",\"export\":{\"pageBg\":\"#fff\"},",
                       "\"c\":\"b\",\"b\":\"oklch(62% 0.1 200)\"", "", NULL);
        if (tui_theme_parse(j, strlen(j), "m.json", &t, err, sizeof err) != 0)
            fail("chained variables, oklch, appearance, $schema, export", "%s", err);
        check_int("declared appearance", t.appearance, 1);
        check_int("oklch resolves through two variables", t.c[TUI_T_BORDER].kind, TUI_COLOR_RGB);
        free(j);
    }
    pass("theme: custom theme files, every colour form, fallbacks");

    {
        char *j = theme_json("\"name\":\"m\",", "\"c\":\"#000\"", "", "bashMode");
        parse_fails("a missing token", j, "Missing required color tokens:\n  - bashMode");
        free(j);
        j = theme_json("\"name\":\"m\",", "\"c\":\"#000\"", "\"nonsense\":\"c\",", NULL);
        parse_fails("an unknown token", j, "nonsense");
        free(j);
        j = theme_json("\"name\":\"m\",", "\"c\":\"nowhere\"", "", NULL);
        parse_fails("a missing variable", j, "Variable reference not found: nowhere");
        free(j);
        j = theme_json("\"name\":\"m\",", "\"c\":\"d\",\"d\":\"c\"", "", NULL);
        parse_fails("a circular variable", j, "Circular variable reference detected");
        free(j);
        j = theme_json("\"name\":\"a/b\",", "\"c\":\"#000\"", "", NULL);
        parse_fails("a name with a slash", j, "cannot contain \"/\"");
        free(j);
        j = theme_json("\"name\":\"m\",\"extra\":1,", "\"c\":\"#000\"", "", NULL);
        parse_fails("an unknown top-level key", j, "extra");
        free(j);
        j = theme_json("\"name\":\"m\",", "\"c\":\"okhsl(10 200% 50%)\"", "", NULL);
        parse_fails("an out-of-range okhsl", j, "s must be between 0 and 1");
        free(j);
        j = theme_json("\"name\":\"m\",", "\"c\":\"red\"", "", NULL);
        parse_fails("a bare colour name is a variable", j, "Variable reference not found: red");
        free(j);
        j = theme_json("\"name\":\"m\",", "\"c\":300", "", NULL);
        parse_fails("an index over 255", j, "0 to 255");
        free(j);
    }
    parse_fails("not JSON", "{\"name\":", "Failed to parse theme t.json");
    parse_fails("not an object", "[1]", "expected an object");
    if (tui_theme_parse("\xEF\xBB\xBF{}", 5, "bom.json", &t, err, sizeof err) == 0 || !strstr(err, "Invalid theme \"bom.json\""))
        fail("a BOM is skipped", "%s", err);
    pass("theme: Pi's validation messages");

    /* the SGR sequences: truecolor, the 256-colour fallback as Pi's rgbToAnsi256, and the terminal default */
    tui_theme_use(&dark, 1);
    check_str("truecolor foreground", tui_fg(TUI_T_MD_HEADING), "\x1b[38;2;205;154;34m");
    check_str("truecolor background", tui_bg(TUI_T_USER_MESSAGE_BG), "\x1b[48;2;33;59;73m");
    tui_theme_use(&dark, 0);
    check_str("256-colour foreground", tui_fg(TUI_T_MD_HEADING), "\x1b[38;5;172m");
    check_str("256-colour background", tui_bg(TUI_T_USER_MESSAGE_BG), "\x1b[48;5;23m");
    check_str("256-colour border", tui_fg(TUI_T_BORDER), "\x1b[38;5;74m");
    check_str("256-colour thinkingHigh", tui_fg(TUI_T_THINKING_HIGH), "\x1b[38;5;104m");
    tui_theme_use(&light, 0);
    check_str("light 256-colour userMessageBg", tui_bg(TUI_T_USER_MESSAGE_BG), "\x1b[48;5;189m");
    check_str("light 256-colour syntaxKeyword", tui_fg(TUI_T_SYNTAX_KEYWORD), "\x1b[38;5;30m");
    {
        char *j = theme_json("\"name\":\"m\",", "\"c\":\"#000\"", "\"text\":\"\",\"accent\":39,", NULL);
        (void)tui_theme_parse(j, strlen(j), "m", &t, err, sizeof err);
        tui_theme_use(&t, 1);
        check_str("terminal-default foreground", tui_fg(TUI_T_TEXT), "\x1b[39m");
        check_str("terminal-default background", tui_bg(TUI_T_TEXT), "\x1b[49m");
        check_str("an index is the same in truecolor", tui_fg(TUI_T_ACCENT), "\x1b[38;5;39m");
        free(j);
    }
    check_int("rgbToAnsi256: gray ramp", tui_rgb_to_256(128, 128, 128), 244);
    check_int("rgbToAnsi256: cube", tui_rgb_to_256(255, 0, 0), 196);
    {
        tui_hl_theme h;
        tui_theme_use(&dark, 1);
        tui_hl_theme_current(&h);
        check_str("highlight keyword is syntaxKeyword", h.sgr[TUI_HL_KEYWORD], "\x1b[38;2;105;173;208m");
        check_str("highlight add is toolDiffAdded", h.sgr[TUI_HL_ADD], tui_fg(TUI_T_TOOL_DIFF_ADDED));
    }
    pass("theme: SGR sequences, 256-colour fallback, terminal default");

    /* until a theme is chosen the current one follows the environment */
    tui_theme_follow_env();
    setenv("COLORTERM", "truecolor", 1);
    unsetenv("COLORFGBG");
    check_str("env: dark by default", tui_bg(TUI_T_USER_MESSAGE_BG), "\x1b[48;2;33;59;73m");
    setenv("COLORFGBG", "0;15", 1);
    check_str("env: COLORFGBG 15 is light", tui_bg(TUI_T_USER_MESSAGE_BG), "\x1b[48;2;223;231;236m");
    setenv("COLORFGBG", "15;7", 1);
    check_int("Pi: bg 7 is light", tui_terminal_light(NULL), 1);
    check_int("Pi: bg 8 is dark", tui_terminal_light("7;8"), 0);
    check_int("Pi: bg 6 is dark", tui_terminal_light("7;6"), 0);
    check_int("Pi: bg 9 is light", tui_terminal_light("0;9"), 1);
    check_int("Pi: rxvt fg;xpm;bg", tui_terminal_light("0;default;15"), 1);
    check_int("Pi: default is dark", tui_terminal_light("0;default"), 0);
    check_int("Pi: an index over 15 says nothing", tui_terminal_light("0;100"), 0);
    setenv("COLORTERM", "", 1);
    setenv("COLORFGBG", "0;15", 1);
    check_str("env: 256 colours without COLORTERM", tui_bg(TUI_T_USER_MESSAGE_BG), "\x1b[48;5;189m");
    unsetenv("COLORFGBG");
    unsetenv("COLORTERM");
    tui_theme_use(&dark, 1);
    tui_theme_follow_env();
    pass("theme: dark/light by COLORFGBG as Pi decides");

    {
        char buf[64];
        check_str("setting: a name", tui_theme_setting_name("solarized", 0, buf, sizeof buf), "solarized");
        check_str("setting: none is system, dark", tui_theme_setting_name(NULL, 0, buf, sizeof buf), "dark");
        check_str("setting: system, light", tui_theme_setting_name("system", 1, buf, sizeof buf), "light");
        check_str("setting: light/dark in a light terminal", tui_theme_setting_name("sol-light/sol-dark", 1, buf, sizeof buf), "sol-light");
        check_str("setting: light/dark in a dark terminal", tui_theme_setting_name("sol-light / sol-dark", 0, buf, sizeof buf), "sol-dark");
        check_str("setting: a/b/c is invalid", tui_theme_setting_name("a/b/c", 1, buf, sizeof buf), "light");
        check_str("setting: /b is invalid", tui_theme_setting_name("/b", 0, buf, sizeof buf), "dark");
    }
    pass("theme: the theme setting's forms");
}

static void write_file(const char *path, const char *text)
{
    FILE *f = fopen(path, "w");
    if (!f)
        fail("write_file", "%s", path);
    fputs(text, f);
    fclose(f);
}

static void test_themeset(void)
{
    char dir[256], home[320], ws[320], p[400], *warn = NULL;
    tui_themeset s;
    char *good, *proj, *dup;
    (void)snprintf(dir, sizeof dir, "%s/pic-themes.XXXXXX", getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp");
    if (!mkdtemp(dir))
        fail("mkdtemp", "%s", dir);
    (void)snprintf(home, sizeof home, "%s/home", dir);
    (void)snprintf(ws, sizeof ws, "%s/ws", dir);
    (void)snprintf(p, sizeof p, "%s/home/.pic", dir);
    mkdir(home, 0700), mkdir(p, 0700);
    (void)snprintf(p, sizeof p, "%s/home/.pic/themes", dir);
    mkdir(p, 0700);
    mkdir(ws, 0700);
    (void)snprintf(p, sizeof p, "%s/ws/.pic", dir);
    mkdir(p, 0700);
    (void)snprintf(p, sizeof p, "%s/ws/.pic/themes", dir);
    mkdir(p, 0700);
    good = theme_json("\"name\":\"mine\",", "\"c\":\"#102030\"", "", NULL);
    proj = theme_json("\"name\":\"projonly\",", "\"c\":\"#405060\"", "", NULL);
    dup = theme_json("\"name\":\"mine\",", "\"c\":\"#ffffff\"", "", NULL);
    (void)snprintf(p, sizeof p, "%s/home/.pic/themes/mine.json", dir);
    write_file(p, good);
    (void)snprintf(p, sizeof p, "%s/home/.pic/themes/broken.json", dir);
    write_file(p, "{\"name\":\"broken\",\"colors\":{}}");
    (void)snprintf(p, sizeof p, "%s/home/.pic/themes/notes.txt", dir);
    write_file(p, "not a theme");
    (void)snprintf(p, sizeof p, "%s/home/.pic/themes/sys.json", dir);
    {
        char *sysj = theme_json("\"name\":\"system\",", "\"c\":\"#000\"", "", NULL);
        write_file(p, sysj);
        free(sysj);
    }
    (void)snprintf(p, sizeof p, "%s/ws/.pic/themes/proj.json", dir);
    write_file(p, proj);
    (void)snprintf(p, sizeof p, "%s/ws/.pic/themes/dup.json", dir);
    write_file(p, dup);

    if (tui_themeset_load(&s, home, ws, 0, &warn) != 0)
        fail("themeset", "load");
    check_int("untrusted workspace: dark, light, mine", (long)s.n, 3);
    check_str("sorted: dark first", s.t[0].name, "dark");
    check_str("then light", s.t[1].name, "light");
    check_str("then the custom one", s.t[2].name, "mine");
    check_int("custom themes remember their file", s.t[2].path[0] != 0, 1);
    check_int("built-in themes have no file", s.t[0].path[0], 0);
    if (!strstr(warn, "broken.json") || !strstr(warn, "Missing required color tokens"))
        fail("themeset warnings", "no report of the invalid file: %s", warn);
    if (!strstr(warn, "\"system\" is a reserved name"))
        fail("themeset warnings", "no report of the reserved name: %s", warn);
    if (strstr(warn, "projonly") || strstr(warn, "dup.json"))
        fail("themeset warnings", "the untrusted project's themes were read: %s", warn);
    check_int("find", tui_themeset_find(&s, "mine") != NULL, 1);
    check_int("find: not there", tui_themeset_find(&s, "projonly") == NULL, 1);
    free(warn);
    tui_themeset_free(&s);

    if (tui_themeset_load(&s, home, ws, 1, &warn) != 0)
        fail("themeset", "load trusted");
    check_int("trusted workspace adds its themes", (long)s.n, 4);
    check_int("the project's theme is found", tui_themeset_find(&s, "projonly") != NULL, 1);
    {
        const tui_theme *m = tui_themeset_find(&s, "mine");
        check_int("the user's theme wins a name two files claim", m && m->c[TUI_T_BORDER].r == 0x10, 1);
    }
    if (!strstr(warn, "Theme name \"mine\" collision"))
        fail("themeset warnings", "no collision report: %s", warn);
    free(warn);
    tui_themeset_free(&s);
    free(good);
    free(proj);
    free(dup);
    {
        char cmd[400];
        (void)snprintf(cmd, sizeof cmd, "rm -rf '%s'", dir);
        if (system(cmd) != 0)
            fail("cleanup", "%s", dir);
    }
    pass("themeset: user themes, project themes only when trusted, invalid files and collisions reported");
}

/* ---- keybindings ------------------------------------------------------- */

static tui_key mkkey(unsigned mods, const char *base, tui_key_kind kind)
{
    tui_key k;
    memset(&k, 0, sizeof k);
    k.kind = kind;
    k.mods = mods;
    snprintf(k.base, sizeof k.base, "%s", base);
    return k;
}

/* What the key becomes under the map: the kind's name, or "dropped". */
static const char *resolved(const tui_keymap *m, unsigned mods, const char *base, tui_key_kind kind)
{
    tui_key k = mkkey(mods, base, kind);
    return tui_keymap_apply(m, &k) ? key_name(k.kind) : "dropped";
}

static char *keys_warn(tui_keymap *m, const char *json)
{
    char *w = NULL;
    if (tui_keymap_load(m, json, strlen(json), "kb.json", &w) != 0)
        fail("keymap load", "oom");
    return w;
}

static void test_keymap(void)
{
    tui_keymap *m = tui_keymap_new();
    tui_keyid id;
    char keys[200], *w;
    int i;

    check_int("ctrl+x", tui_keyid_parse("ctrl+x", &id), 0);
    check_int("its modifiers", (long)id.mods, TUI_MOD_CTRL);
    check_str("its base", id.base, "x");
    check_int("shift+ctrl+p", tui_keyid_parse("shift+ctrl+p", &id), 0);
    check_int("modifiers in any order", (long)id.mods, TUI_MOD_CTRL | TUI_MOD_SHIFT);
    check_int("esc is escape", tui_keyid_parse("esc", &id) == 0 && strcmp(id.base, "escape") == 0, 1);
    check_int("return is enter", tui_keyid_parse("return", &id) == 0 && strcmp(id.base, "enter") == 0, 1);
    check_int("pageUp", tui_keyid_parse("ctrl+pageUp", &id), 0);
    check_int("ctrl+-", tui_keyid_parse("ctrl+-", &id), 0);
    check_int("ctrl+]", tui_keyid_parse("ctrl+]", &id), 0);
    check_int("ctrl++", tui_keyid_parse("ctrl++", &id), 0);
    check_int("super+k", tui_keyid_parse("super+k", &id), 0);
    check_int("four modifiers", tui_keyid_parse("ctrl+shift+alt+super+k", &id), 0);
    check_int("f12", tui_keyid_parse("alt+f12", &id), 0);
    check_int("a repeated modifier is invalid", tui_keyid_parse("ctrl+ctrl+x", &id), -1);
    check_int("a modifier alone is invalid", tui_keyid_parse("ctrl+", &id), -1);
    check_int("upper case is invalid", tui_keyid_parse("Ctrl+x", &id), -1);
    check_int("an unknown key name is invalid", tui_keyid_parse("ctrl+pagedown", &id), -1);
    check_int("an empty string is invalid", tui_keyid_parse("", &id), -1);
    check_int("two keys are invalid", tui_keyid_parse("ctrl+x+y", &id), -1);
    check_int("f13 is invalid", tui_keyid_parse("f13", &id), -1);
    pass("keymap: Pi's key syntax");

    /* Pi's action names and defaults */
    check_int("every action Pi defines, and pic's redraw, history search, key selector, mouse toggle and settings", (long)tui_keymap_count(), 95);
    i = tui_keymap_find("app.exit");
    tui_keymap_keys(m, (size_t)i, keys, sizeof keys);
    check_str("app.exit default", keys, "ctrl+d");
    tui_keymap_keys(m, (size_t)tui_keymap_find("tui.input.newLine"), keys, sizeof keys);
    check_str("tui.input.newLine defaults", keys, "shift+enter, ctrl+j");
    tui_keymap_keys(m, (size_t)tui_keymap_find("app.model.cycleBackward"), keys, sizeof keys);
    check_str("app.model.cycleBackward defaults", keys, "shift+ctrl+p, ctrl+n");
    tui_keymap_keys(m, (size_t)tui_keymap_find("app.session.new"), keys, sizeof keys);
    check_str("app.session.new has none", keys, "");
    tui_keymap_keys(m, (size_t)tui_keymap_find("app.credential.select"), keys, sizeof keys);
    check_str("app.credential.select default", keys, "");
    tui_keymap_keys(m, (size_t)tui_keymap_find("app.mouse.toggle"), keys, sizeof keys);
    check_str("app.mouse.toggle default", keys, "alt+m");
    tui_keymap_keys(m, (size_t)tui_keymap_find("app.settings.open"), keys, sizeof keys);
    check_str("app.settings.open default", keys, "f2");
    {
        tui_keys *dec = tui_keys_new();
        tui_key f2;
        tui_keys_feed(dec, "\x1bOQ\x1b[12~", 8);
        check_int("F2 as SS3 Q", tui_keys_next(dec, &f2), 1);
        check_int("F2 is the settings key", tui_keymap_has(m, "app.settings.open", &f2), 1);
        check_int("F2 maps to the action", tui_keymap_apply(m, &f2) && f2.kind == TUI_KEY_ACTION && f2.action == TUI_ACT_SETTINGS_OPEN, 1);
        check_int("F2 as CSI 12~", tui_keys_next(dec, &f2), 1);
        check_int("CSI 12~ is the settings key", tui_keymap_has(m, "app.settings.open", &f2), 1);
        tui_keys_free(dec);
    }
    tui_keymap_keys(m, (size_t)tui_keymap_find("tui.editor.cursorWordLeft"), keys, sizeof keys);
    check_str("tui.editor.cursorWordLeft defaults", keys, "alt+left, ctrl+left, alt+b");
    check_str("a description", tui_keymap_desc((size_t)tui_keymap_find("app.tools.expand")), "Toggle tool output");
    check_int("an unknown action", tui_keymap_find("app.nothing"), -1);
    pass("keymap: action names and defaults");

    /* the defaults translate every key pic decodes to what it did */
    check_str("default ctrl+d", resolved(m, TUI_MOD_CTRL, "d", TUI_KEY_CTRL_D), "CTRL_D");
    check_str("default ctrl+a is line start", resolved(m, TUI_MOD_CTRL, "a", TUI_KEY_HOME), "HOME");
    check_str("default escape", resolved(m, 0, "escape", TUI_KEY_ESC), "ESC");
    check_str("default shift+tab", resolved(m, TUI_MOD_SHIFT, "tab", TUI_KEY_BACKTAB), "BACKTAB");
    check_str("default alt+enter", resolved(m, TUI_MOD_ALT, "enter", TUI_KEY_ALT_ENTER), "ALT_ENTER");
    check_str("default alt+up", resolved(m, TUI_MOD_ALT, "up", TUI_KEY_ALT_UP), "ALT_UP");
    check_str("default pageUp", resolved(m, 0, "pageUp", TUI_KEY_PAGEUP), "PAGEUP");
    check_str("default ctrl+home", resolved(m, TUI_MOD_CTRL, "home", TUI_KEY_CTRL_HOME), "CTRL_HOME");
    check_str("default ctrl+left is word left", resolved(m, TUI_MOD_CTRL, "left", TUI_KEY_WORD_LEFT), "WORD_LEFT");
    check_str("default shift+ctrl+p", resolved(m, TUI_MOD_CTRL | TUI_MOD_SHIFT, "p", TUI_KEY_CTRL_P_BACK), "CTRL_P_BACK");
    check_str("default ctrl+-", resolved(m, TUI_MOD_CTRL, "-", TUI_KEY_UNDO), "UNDO");
    check_str("default ctrl+] jump", resolved(m, TUI_MOD_CTRL, "]", TUI_KEY_JUMP), "JUMP");
    check_str("default ctrl+alt+] jump back", resolved(m, TUI_MOD_CTRL | TUI_MOD_ALT, "]", TUI_KEY_JUMP_BACK), "JUMP_BACK");
    check_str("text passes", resolved(m, 0, "", TUI_KEY_CHAR), "CHAR");
    check_str("a key bound to nothing is dropped", resolved(m, TUI_MOD_CTRL, "\\", TUI_KEY_OTHER), "dropped");
    check_str("shift+up pages the transcript (a Mac-reachable PageUp)", resolved(m, TUI_MOD_SHIFT, "up", TUI_KEY_UP), "PAGEUP");
    check_str("shift+down pages down", resolved(m, TUI_MOD_SHIFT, "down", TUI_KEY_DOWN), "PAGEDOWN");
    check_str("shift+pageDown jumps to the end", resolved(m, TUI_MOD_SHIFT, "pageDown", TUI_KEY_PAGEDOWN), "CTRL_END");
    check_str("shift+pageUp jumps to the top", resolved(m, TUI_MOD_SHIFT, "pageUp", TUI_KEY_PAGEUP), "CTRL_HOME");
    check_str("ctrl+shift+down jumps to the end (no End key needed)", resolved(m, TUI_MOD_CTRL | TUI_MOD_SHIFT, "down", TUI_KEY_DOWN), "CTRL_END");
    check_str("ctrl+shift+up jumps to the top", resolved(m, TUI_MOD_CTRL | TUI_MOD_SHIFT, "up", TUI_KEY_UP), "CTRL_HOME");
    check_str("ctrl+q queues a follow-up (Alt+Enter needs Option as Meta)", resolved(m, TUI_MOD_CTRL, "q", TUI_KEY_OTHER), "ALT_ENTER");
    check_str("alt+enter still does", resolved(m, TUI_MOD_ALT, "enter", TUI_KEY_ALT_ENTER), "ALT_ENTER");
    check_str("alt+p opens the model picker", resolved(m, TUI_MOD_ALT, "p", TUI_KEY_OTHER), "CTRL_L");
    check_str("alt+t cycles thinking", resolved(m, TUI_MOD_ALT, "t", TUI_KEY_OTHER), "BACKTAB");
    check_str("ctrl+n is the previous model", resolved(m, TUI_MOD_CTRL, "n", TUI_KEY_OTHER), "CTRL_P_BACK");
    check_str("ctrl+l redraws (Claude Code), not the model picker", resolved(m, TUI_MOD_CTRL, "l", TUI_KEY_CTRL_L), "ACTION");
    {
        tui_key k = mkkey(TUI_MOD_CTRL, "l", TUI_KEY_CTRL_L);
        (void)tui_keymap_apply(m, &k);
        check_int("the redraw action", k.action, TUI_ACT_REDRAW);
    }
    pass("keymap: defaults give the keys' usual kinds");

    /* Ctrl+F searches the fullscreen transcript as well as Pi's Ctrl+Shift+F (Mac Terminal sends no
     * Ctrl+Shift+F); outside the search it stays the editor's cursor right, and sharing it is no conflict */
    {
        tui_key cf = mkkey(TUI_MOD_CTRL, "f", TUI_KEY_RIGHT);
        tui_keymap_keys(m, (size_t)tui_keymap_find("tui.altScreen.search"), keys, sizeof keys);
        check_str("search defaults", keys, "ctrl+shift+f, ctrl+f");
        check_int("ctrl+f is a search key", tui_keymap_has(m, "tui.altScreen.search", &cf), 1);
        check_str("ctrl+f still moves right", resolved(m, TUI_MOD_CTRL, "f", TUI_KEY_RIGHT), "RIGHT");
        w = keys_warn(m, "{\"tui.altScreen.search\": [\"ctrl+shift+f\", \"ctrl+f\"], \"tui.editor.cursorRight\": [\"right\", \"ctrl+f\"]}");
        check_str("search and cursor right may share ctrl+f", w, "");
        free(w);
        w = keys_warn(m, "{\"app.exit\": \"ctrl+f\", \"tui.editor.cursorRight\": [\"right\", \"ctrl+f\"]}");
        if (!strstr(w, "more than one action"))
            fail("other sharing is still a conflict", "%s", w);
        free(w);
        free(keys_warn(m, "{}"));
    }
    pass("keymap: ctrl+f searches in fullscreen and is cursor right elsewhere, without a conflict");

    /* user overrides in Pi's format */
    w = keys_warn(m, "{\"$schema\":\"https://pi.dev/schemas/keybindings.schema.json\","
                     "\"app.exit\":\"ctrl+q\",\"app.suspend\":[],\"app.session.new\":[\"ctrl+shift+n\",\"alt+n\"],"
                     "\"tui.editor.cursorLineStart\":\"ctrl+shift+a\"}");
    check_str("no warnings for a good file", w, "");
    free(w);
    check_str("app.exit moved: ctrl+q", resolved(m, TUI_MOD_CTRL, "q", TUI_KEY_OTHER), "CTRL_D");
    check_str("ctrl+d is now delete (the editor's own binding)", resolved(m, TUI_MOD_CTRL, "d", TUI_KEY_CTRL_D), "DELETE");
    check_str("a disabled action: ctrl+z is dropped", resolved(m, TUI_MOD_CTRL, "z", TUI_KEY_CTRL_Z), "dropped");
    check_str("cursorLineStart replaced: ctrl+a is dropped", resolved(m, TUI_MOD_CTRL, "a", TUI_KEY_HOME), "dropped");
    check_str("home is dropped too (a value replaces the defaults)", resolved(m, 0, "home", TUI_KEY_HOME), "dropped");
    check_str("the new key works", resolved(m, TUI_MOD_CTRL | TUI_MOD_SHIFT, "a", TUI_KEY_OTHER), "HOME");
    check_str("an unassigned action gets a key: ctrl+shift+n", resolved(m, TUI_MOD_CTRL | TUI_MOD_SHIFT, "n", TUI_KEY_OTHER), "ACTION");
    {
        tui_key k = mkkey(TUI_MOD_ALT, "n", TUI_KEY_OTHER);
        check_int("the action key applies", tui_keymap_apply(m, &k), 1);
        check_int("and says which action", k.action, TUI_ACT_SESSION_NEW);
    }
    tui_keymap_keys(m, (size_t)tui_keymap_find("app.session.new"), keys, sizeof keys);
    check_str("effective keys as written", keys, "ctrl+shift+n, alt+n");
    {
        char letters[40];
        tui_keymap_alt_letters(m, letters);
        if (!strchr(letters, 'n') || !strchr(letters, 'b') || !strchr(letters, 'y'))
            fail("alt letters", "\"%s\"", letters);
    }
    pass("keymap: overrides replace defaults, [] disables, unassigned actions bind");

    /* a file's problems */
    w = keys_warn(m, "{\"app.exit\":\"ctrl+ctrl+q\",\"nope.action\":\"ctrl+q\",\"app.clear\":[\"ctrl+x\",\"bogus key\"],\"app.interrupt\":5}");
    if (!strstr(w, "kb.json: ctrl+ctrl+q is not a valid key for app.exit") && !strstr(w, "\"ctrl+ctrl+q\" is not a valid key for app.exit"))
        fail("invalid key warning", "%s", w);
    if (!strstr(w, "unknown action \"nope.action\" is ignored"))
        fail("unknown action warning", "%s", w);
    if (!strstr(w, "bogus key is not a valid key for app.clear"))
        fail("invalid list entry warning", "%s", w);
    if (!strstr(w, "app.interrupt needs a key or a list of keys"))
        fail("invalid value warning", "%s", w);
    free(w);
    check_str("an invalid value keeps the default (app.exit)", resolved(m, TUI_MOD_CTRL, "d", TUI_KEY_CTRL_D), "CTRL_D");
    check_str("an invalid list keeps the default (app.clear)", resolved(m, TUI_MOD_CTRL, "c", TUI_KEY_CTRL_C), "CTRL_C");
    check_str("and does not take its good entries", resolved(m, TUI_MOD_CTRL, "x", TUI_KEY_CTRL_X), "CTRL_X");
    w = keys_warn(m, "{\"app.exit\":\"ctrl+q\",\"app.suspend\":\"ctrl+q\",\"app.tools.expand\":\"ctrl+o\"}");
    if (!strstr(w, "ctrl+q is bound to more than one action (app.exit, app.suspend)"))
        fail("conflict warning", "%s", w);
    if (strstr(w, "ctrl+o"))
        fail("conflict warning", "a lone binding is no conflict: %s", w);
    free(w);
    check_str("a conflict resolves to the first action: ctrl+q", resolved(m, TUI_MOD_CTRL, "q", TUI_KEY_OTHER), "CTRL_D");
    w = keys_warn(m, "{\"app.exit\":\"ctrl+q\",\"app.suspend\":\"shift+ctrl+q\",\"app.model.select\":\"ctrl+shift+q\"}");
    if (!strstr(w, "shift+ctrl+q is bound to more than one action (app.suspend, app.model.select)"))
        fail("conflict warning, modifiers in another order", "%s", w);
    free(w);
    w = keys_warn(m, "{not json");
    if (!strstr(w, "kb.json:") || !strstr(w, "using the default keybindings"))
        fail("malformed file", "%s", w);
    free(w);
    check_str("a malformed file leaves the defaults", resolved(m, TUI_MOD_CTRL, "d", TUI_KEY_CTRL_D), "CTRL_D");
    w = keys_warn(m, "[1]");
    if (!strstr(w, "expected an object"))
        fail("array file", "%s", w);
    free(w);
    w = keys_warn(m, "{\"cursorUp\":\"ctrl+p\",\"submit\":\"ctrl+s\",\"tui.input.submit\":\"enter\"}");
    check_str("legacy names are migrated without a warning", w, "");
    free(w);
    check_str("legacy cursorUp: ctrl+p", resolved(m, TUI_MOD_CTRL, "p", TUI_KEY_OTHER), "CTRL_P"); /* app.model.cycleForward still first */
    check_str("legacy submit loses to the new name", resolved(m, TUI_MOD_CTRL, "s", TUI_KEY_CTRL_S), "CTRL_S");
    pass("keymap: invalid entries, unknown actions, conflicts, malformed files, legacy names");

    {
        char *h;
        w = keys_warn(m, "{\"app.exit\":\"ctrl+q\",\"app.suspend\":[]}");
        free(w);
        h = tui_keymap_hotkeys(m);
        if (!strstr(h, "ctrl+q") || !strstr(h, "app.exit") || !strstr(h, "Exit when editor is empty"))
            fail("hotkeys", "app.exit missing: %s", h);
        if (strstr(h, "app.suspend"))
            fail("hotkeys", "a disabled action is listed: %s", h);
        if (!strstr(h, "tui.editor.cursorLeft") || !strstr(h, "left, ctrl+b"))
            fail("hotkeys", "defaults missing: %s", h);
        if (strstr(h, "app.tree.foldOrUp"))
            fail("hotkeys", "an action pic does nothing for is listed: %s", h);
        free(h);
    }
    {
        tui_keymap *d = tui_keymap_new();
        tui_key k = mkkey(TUI_MOD_CTRL | TUI_MOD_SHIFT, "f", TUI_KEY_OTHER);
        char *h;
        check_int("ctrl+shift+f opens the search", tui_keymap_apply(d, &k) && k.kind == TUI_KEY_ACTION && k.action == TUI_ACT_SEARCH_TOGGLE, 1);
        k = mkkey(TUI_MOD_CTRL, "r", TUI_KEY_OTHER);
        check_int("ctrl+r searches the history", tui_keymap_apply(d, &k) && k.kind == TUI_KEY_ACTION && k.action == TUI_ACT_HISTORY_SEARCH, 1);
        k = mkkey(0, "enter", TUI_KEY_ENTER);
        check_int("enter is next while searching", tui_keymap_has(d, "tui.altScreen.searchNext", &k), 1);
        check_int("enter still submits otherwise", tui_keymap_apply(d, &k) && k.kind == TUI_KEY_ENTER, 1);
        k = mkkey(TUI_MOD_SHIFT, "enter", TUI_KEY_NEWLINE);
        check_int("shift+enter is previous", tui_keymap_has(d, "tui.altScreen.searchPrevious", &k), 1);
        k = mkkey(0, "escape", TUI_KEY_ESC);
        check_int("escape closes", tui_keymap_has(d, "tui.altScreen.searchClose", &k), 1);
        check_int("and is not the next key", tui_keymap_has(d, "tui.altScreen.searchNext", &k), 0);
        k = mkkey(TUI_MOD_CTRL, "g", TUI_KEY_CTRL_G);
        check_int("ctrl+g is next", tui_keymap_has(d, "tui.altScreen.searchNext", &k), 1);
        check_int("an unknown action", tui_keymap_has(d, "nope", &k), 0);
        h = tui_keymap_hotkeys(d);
        if (!strstr(h, "ctrl+r") || !strstr(h, "app.history.search") || !strstr(h, "ctrl+shift+f") || !strstr(h, "tui.altScreen.searchClose"))
            fail("hotkeys", "search keys missing: %s", h);
        free(h);
        tui_keymap_free(d);
    }
    pass("keymap: /hotkeys shows the effective bindings");
    tui_keymap_free(m);
}

/* The decoder gives keys the names keybindings use. */
static void test_key_ids(void)
{
    static const struct {
        const char *bytes;
        unsigned mods;
        const char *base;
    } cases[] = {
        {"\x01", TUI_MOD_CTRL, "a"},
        {"\x11", TUI_MOD_CTRL, "q"},
        {"\x7f", 0, "backspace"},
        {"\r", 0, "enter"},
        {"\x1b[Z", TUI_MOD_SHIFT, "tab"},
        {"\x1b[1;3A", TUI_MOD_ALT, "up"},
        {"\x1b[1;5D", TUI_MOD_CTRL, "left"},
        {"\x1b[1;6A", TUI_MOD_CTRL | TUI_MOD_SHIFT, "up"},
        {"\x1b[5~", 0, "pageUp"},
        {"\x1b[6;5~", TUI_MOD_CTRL, "pageDown"},
        {"\x1b[3;3~", TUI_MOD_ALT, "delete"},
        {"\x1b[2~", 0, "insert"},
        {"\x1b[15~", 0, "f5"},
        {"\x1b[24~", 0, "f12"},
        {"\x1bOP", 0, "f1"},
        {"\x1b[112;6u", TUI_MOD_CTRL | TUI_MOD_SHIFT, "p"},
        {"\x1b[13;2u", TUI_MOD_SHIFT, "enter"},
        {"\x1b[27;5;118~", TUI_MOD_CTRL, "v"},
        {"\x1b[113;9u", TUI_MOD_SUPER, "q"},
        {"\x1b[27u", 0, "escape"},
        {"\x1b" "b", TUI_MOD_ALT, "b"},
        {"\x1b\x1d", TUI_MOD_CTRL | TUI_MOD_ALT, "]"},
        {"\x1f", TUI_MOD_CTRL, "-"},
    };
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        tui_keys *k = tui_keys_new();
        tui_key key;
        size_t n = strlen(cases[i].bytes);
        if (cases[i].bytes[0] == '\x1b' && n == 2 && cases[i].bytes[1] == '[')
            n = 2;
        tui_keys_feed(k, cases[i].bytes, n);
        if (!tui_keys_next(k, &key))
            fail("key ids", "case %zu decoded nothing", i);
        if (key.mods != cases[i].mods || strcmp(key.base, cases[i].base) != 0)
            fail("key ids", "case %zu: mods %u base \"%s\", want %u \"%s\"", i, key.mods, key.base, cases[i].mods, cases[i].base);
        tui_keys_free(k);
    }
    {
        tui_keys *k = tui_keys_new();
        tui_key key;
        tui_keys_feed(k, "\x1bq", 2);
        check_int("alt+q is Escape then q by default", tui_keys_next(k, &key) && key.kind == TUI_KEY_ESC && tui_keys_next(k, &key) && key.kind == TUI_KEY_CHAR, 1);
        tui_keys_alt_letters(k, "q");
        tui_keys_feed(k, "\x1bq\x1bw", 4);
        if (!tui_keys_next(k, &key) || key.kind != TUI_KEY_OTHER || key.mods != TUI_MOD_ALT || strcmp(key.base, "q") != 0)
            fail("alt letters", "alt+q is not a key once asked for");
        check_int("other alt+letters stay Escape and the letter", tui_keys_next(k, &key) && key.kind == TUI_KEY_ESC, 1);
        tui_keys_free(k);
    }
    pass("keymap: the decoder names keys as keybindings do; alt letters on request");
}


/* ---- terminal replies --------------------------------------------------- */

/* Feeds bytes to a decoder expecting replies (as after the probe) and describes the keys. */
static void reply_check(const char *what, tui_keys *k, const char *bytes, size_t n, const char *want)
{
    char got[1024];
    tui_keys_feed(k, bytes, n);
    drain(k, got, sizeof got);
    check_str(what, got, want);
}

#define REPLY(what, k, bytes, want) reply_check(what, k, bytes, sizeof(bytes) - 1, want)

static void test_replies(void)
{
    {
        tui_keys *k = tui_keys_new();
        const tui_term_replies *r = tui_keys_replies(k);
        check_int("no background reply yet", r->light, -1);
        check_int("focus unknown at first", r->focus, -1);
        check_int("no DA1 yet", r->da1, 0);
        tui_keys_expect(k, 1);
        REPLY("OSC 11 reply (ST) is consumed", k, "a\x1b]11;rgb:ffff/ffff/ffff\x1b\\b", "CHAR:a CHAR:b");
        check_int("white is light", r->light, 1);
        REPLY("OSC 11 reply (BEL) is consumed", k, "\x1b]11;rgb:1e1e/1e1e/2e2e\x07", "");
        check_int("near black is dark", r->light, 0);
        REPLY("XTVERSION (DCS) is consumed", k, "\x1bP>|ghostty 1.4.0\x1b\\x", "CHAR:x");
        REPLY("APC is consumed", k, "\x1b_Gi=1;OK\x1b\\", "");
        REPLY("DECRQM mode report is consumed", k, "\x1b[?2026;2$y", "");
        REPLY("kitty flags reply is consumed", k, "\x1b[?1u", "");
        REPLY("colour scheme report is consumed", k, "\x1b[?997;1n", "");
        REPLY("cursor position report is consumed", k, "\x1b[12;40R", "");
        REPLY("DA2 is consumed", k, "\x1b[>1;10;0c", "");
        check_int("DA2 is not DA1", r->da1, 0);
        {
            /* a reply split across reads, as over a slow link */
            static const char osc[] = "\x1b]11;rgb:ff/ff/ff\x1b\\";
            for (size_t i = 0; i + 1 < sizeof osc; i++)
                reply_check("a reply fed a byte at a time yields nothing", k, osc + i, 1, "");
        }
        REPLY("DA1 is consumed", k, "\x1b[?62;22;52c", "");
        check_int("DA1 seen", r->da1, 1);
        /* DA1 ends the window: Alt+] and Esc P are keys again */
        REPLY("after DA1, ESC ] is Escape then ]", k, "\x1b]", "ESC CHAR:]");
        REPLY("focus out", k, "\x1b[O", "");
        check_int("focus out reported", r->focus, 0);
        REPLY("focus in", k, "\x1b[I", "");
        check_int("focus in reported", r->focus, 1);
        check_int("focus-ins counted", (long)r->focus_in, 1);
        check_int("alternate scroll unknown at first", r->alt_scroll, -1);
        REPLY("DECRQM 1007 set is consumed", k, "\x1b[?1007;1$y", "");
        check_int("alternate scroll was set", r->alt_scroll, 1);
        REPLY("DECRQM 1007 reset", k, "\x1b[?1007;2$y", "");
        check_int("alternate scroll was reset", r->alt_scroll, 0);
        REPLY("DECRQM 1007 not recognised", k, "\x1b[?1007;0$y", "");
        check_int("alternate scroll unknown again", r->alt_scroll, -1);
        tui_keys_free(k);
    }
    {
        tui_keys *k = tui_keys_new();
        unsigned seq;
        tui_keys_expect(k, 1);
        seq = tui_keys_replies(k)->seq;
        tui_keys_feed(k, "\x1b]11;rgb:ffff/", 14);
        check_int("an unfinished reply waits", tui_keys_waiting(k), 1);
        for (int i = 0; i < 5; i++)
            tui_keys_flush(k);
        check_int("flushes keep an unfinished reply while expecting", tui_keys_waiting(k), 1);
        REPLY("the rest of the reply arrives late", k, "ffff/ffff\x1b\\", "");
        check_int("the late reply counted", tui_keys_replies(k)->light, 1);
        check_int("seq moved", tui_keys_replies(k)->seq != seq, 1);
        /* a reply cut off by another sequence: the string is dropped, the key after it kept */
        REPLY("a cut-off reply drops, the next key stays", k, "\x1b]11;rgb:00\x1b[A", "UP");
        tui_keys_expect(k, 0);
        REPLY("without expecting, ESC P is Escape then P", k, "\x1bP", "ESC CHAR:P");
        tui_keys_free(k);
    }
    {
        tui_keys *k = tui_keys_new();
        tui_keys_expect(k, 1);
        tui_keys_feed(k, "\x1b", 1);
        tui_keys_flush(k);
        tui_keys_flush(k);
        check_int("a lone Esc waits a little longer while expecting", tui_keys_waiting(k), 1);
        tui_keys_flush(k);
        {
            char got[64];
            drain(k, got, sizeof got);
            check_str("then it is Escape", got, "ESC");
        }
        tui_keys_free(k);
    }
    check_int("rgb:ffff/ffff/ffff light", tui_color_spec_light("rgb:ffff/ffff/ffff", 18), 1);
    check_int("rgb:0/0/0 dark", tui_color_spec_light("rgb:0/0/0", 9), 0);
    check_int("rgb:fd/f6/e3 (8-bit) light", tui_color_spec_light("rgb:fd/f6/e3", 12), 1);
    check_int("rgb:2/2/2 (4-bit) dark", tui_color_spec_light("rgb:2/2/2", 9), 0);
    check_int("rgba: light", tui_color_spec_light("rgba:eeee/eeee/eeee/ffff", 24), 1);
    check_int("#ffffff light", tui_color_spec_light("#ffffff", 7), 1);
    check_int("#000 dark", tui_color_spec_light("#000", 4), 0);
    check_int("garbage", tui_color_spec_light("blue", 4), -1);
    check_int("too many digits", tui_color_spec_light("rgb:fffff/0/0", 13), -1);
    pass("replies: OSC/DCS/APC and CSI replies consumed while expected, DA1 ends the window, focus, colour specs");

    {
        char out[256];
        size_t n;
        unsetenv("VTE_VERSION");
        setenv("TERM", "xterm-ghostty", 1);
        n = tui_term_done_signal(out, sizeof out, 0, 1000, "reply ready");
        out[n] = 0;
        check_str("unfocused: BEL and OSC 9", out, "\x07\x1b]9;pic: reply ready\x1b\\");
        check_int("focused: nothing", (long)tui_term_done_signal(out, sizeof out, 1, 60000, "reply ready"), 0);
        check_int("focus unknown, short turn: nothing", (long)tui_term_done_signal(out, sizeof out, -1, 3000, "x"), 0);
        n = tui_term_done_signal(out, sizeof out, -1, 30000, "reply ready");
        out[n] = 0;
        check_str("focus unknown, long turn: signal", out, "\x07\x1b]9;pic: reply ready\x1b\\");
        setenv("VTE_VERSION", "7600", 1);
        n = tui_term_done_signal(out, sizeof out, 0, 0, "request failed");
        out[n] = 0;
        check_str("VTE: OSC 777", out, "\x07\x1b]777;notify;pic;request failed\x1b\\");
        unsetenv("VTE_VERSION");
        setenv("TERM", "foot", 1);
        n = tui_term_done_signal(out, sizeof out, 0, 0, "reply ready");
        out[n] = 0;
        check_str("foot: OSC 777", out, "\x07\x1b]777;notify;pic;reply ready\x1b\\");
        unsetenv("TERM");
    }
    {
        tui_theme_follow_env();
        setenv("COLORTERM", "truecolor", 1);
        setenv("COLORFGBG", "15;0", 1);
        tui_terminal_light_set(1);
        check_int("the OSC 11 answer wins over COLORFGBG", tui_terminal_light(NULL), 1);
        check_str("implicit theme follows the answer", tui_bg(TUI_T_USER_MESSAGE_BG), "\x1b[48;2;223;231;236m");
        check_int("an explicit COLORFGBG argument is still read as given", tui_terminal_light("0;15"), 1);
        tui_terminal_light_set(0);
        check_str("a dark answer gives dark", tui_bg(TUI_T_USER_MESSAGE_BG), "\x1b[48;2;33;59;73m");
        tui_terminal_light_set(-1);
        setenv("COLORFGBG", "0;15", 1);
        check_int("no answer: COLORFGBG again", tui_terminal_light(NULL), 1);
        unsetenv("COLORFGBG");
        unsetenv("COLORTERM");
    }
    pass("theme: the terminal's background answer picks light or dark");
    pass("done signal: BEL plus OSC 9 (777 in foot and VTE), only when unfocused or a long turn with focus unknown");
}

/* /remote-control's QR code against an independent encoder: Python's
 * qrcode 8.2, QRCode(version=2, error_correction=Q, mask_pattern=0) of
 * b"ssh://[email protected]", drawn the same way (light modules as blocks, a
 * quiet zone of 4, two module rows per line). qrcodegen picks Q (medium,
 * boosted: it still fits version 2) and mask 0 by itself; the vector pins the
 * encoding, error correction and placement against another implementation. */
static void test_remote_qr(void) {
    static const char want[] =
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 \xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84 \xe2\x96\x88  \xe2\x96\x80\xe2\x96\x84\xe2\x96\x88\xe2\x96\x80\xe2\x96\x84 \xe2\x96\x80\xe2\x96\x88 \xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84 \xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 \xe2\x96\x88   \xe2\x96\x88 \xe2\x96\x88 \xe2\x96\x88\xe2\x96\x88 \xe2\x96\x88\xe2\x96\x88\xe2\x96\x80 \xe2\x96\x84\xe2\x96\x88 \xe2\x96\x88   \xe2\x96\x88 \xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 \xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88 \xe2\x96\x88\xe2\x96\x84\xe2\x96\x80\xe2\x96\x84\xe2\x96\x88\xe2\x96\x80   \xe2\x96\x80\xe2\x96\x88 \xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88 \xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88 \xe2\x96\x88\xe2\x96\x84\xe2\x96\x80\xe2\x96\x84\xe2\x96\x80\xe2\x96\x84\xe2\x96\x88 \xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88\xe2\x96\x84\xe2\x96\x88\xe2\x96\x84 \xe2\x96\x80\xe2\x96\x80\xe2\x96\x84\xe2\x96\x88\xe2\x96\x80\xe2\x96\x88\xe2\x96\x84\xe2\x96\x84 \xe2\x96\x80\xe2\x96\x84\xe2\x96\x88\xe2\x96\x84    \xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 \xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x80\xe2\x96\x84\xe2\x96\x80\xe2\x96\x88\xe2\x96\x84\xe2\x96\x88\xe2\x96\x80\xe2\x96\x88\xe2\x96\x84\xe2\x96\x88\xe2\x96\x80 \xe2\x96\x80\xe2\x96\x84 \xe2\x96\x88\xe2\x96\x80\xe2\x96\x84\xe2\x96\x84 \xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x80\xe2\x96\x80\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88 \xe2\x96\x84\xe2\x96\x84\xe2\x96\x88 \xe2\x96\x80\xe2\x96\x88\xe2\x96\x84   \xe2\x96\x88\xe2\x96\x88 \xe2\x96\x80\xe2\x96\x88 \xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x84\xe2\x96\x80\xe2\x96\x80\xe2\x96\x84\xe2\x96\x80 \xe2\x96\x84\xe2\x96\x88\xe2\x96\x84\xe2\x96\x80\xe2\x96\x88 \xe2\x96\x80\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88 \xe2\x96\x84\xe2\x96\x88  \xe2\x96\x80\xe2\x96\x88\xe2\x96\x84 \xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x84\xe2\x96\x88\xe2\x96\x84\xe2\x96\x88\xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84  \xe2\x96\x88\xe2\x96\x80\xe2\x96\x84\xe2\x96\x80   \xe2\x96\x84\xe2\x96\x84\xe2\x96\x84 \xe2\x96\x88\xe2\x96\x80\xe2\x96\x88 \xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 \xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84 \xe2\x96\x88\xe2\x96\x84 \xe2\x96\x88\xe2\x96\x88\xe2\x96\x84\xe2\x96\x80   \xe2\x96\x88\xe2\x96\x84\xe2\x96\x88  \xe2\x96\x88\xe2\x96\x84 \xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 \xe2\x96\x88   \xe2\x96\x88 \xe2\x96\x88\xe2\x96\x84 \xe2\x96\x80\xe2\x96\x84 \xe2\x96\x80\xe2\x96\x88\xe2\x96\x88 \xe2\x96\x84\xe2\x96\x84  \xe2\x96\x88\xe2\x96\x80\xe2\x96\x88\xe2\x96\x84\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 \xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88 \xe2\x96\x88 \xe2\x96\x80  \xe2\x96\x84 \xe2\x96\x88\xe2\x96\x80 \xe2\x96\x80\xe2\x96\x88 \xe2\x96\x84\xe2\x96\x84\xe2\x96\x88\xe2\x96\x80\xe2\x96\x84\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88\xe2\x96\x84\xe2\x96\x84\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n"
        "\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\xe2\x96\x80\n"
        ;
    int rows = 0;
    char *got = tui_remote_qr("ssh://[email protected]", 1, &rows);
    check_str("remote qr: segno's modules", got ? got : "(null)", want);
    check_int("remote qr: rows", rows, 17);
    free(got);
}

/* ---- the settings panel ------------------------------------------------------ */

static char *slurp_file(const char *path)
{
    FILE *f = fopen(path, "rb");
    char *buf;
    long n;
    if (!f)
        fail("slurp", "cannot open %s", path);
    (void)fseek(f, 0, SEEK_END);
    n = ftell(f);
    (void)fseek(f, 0, SEEK_SET);
    buf = calloc((size_t)n + 1, 1);
    if (!buf || fread(buf, 1, (size_t)n, f) != (size_t)n)
        fail("slurp", "cannot read %s", path);
    fclose(f);
    return buf;
}

/* Every line exactly WIDTH columns (exact) or at most (not). */
static void panel_widths(const char *what, const tui_lines *l, size_t width, int exact)
{
    for (size_t i = 0; i < l->n; i++) {
        size_t w = tui_width(l->lines[i], strlen(l->lines[i]));
        if (exact ? w != width : w > width) {
            char p[1024];
            plain(l->lines[i], p, sizeof p);
            fail(what, "line %zu is %zu columns, want %s%zu: \"%s\"", i, w, exact ? "" : "at most ", width, p);
        }
    }
}

static tui_panel_act panel_send(tui_panel *p, const tui_settings *l, tui_key_kind kind, const char *text)
{
    tui_key k;
    tui_panel_act act;
    memset(&k, 0, sizeof k);
    k.kind = kind;
    if (text)
        (void)snprintf(k.text, sizeof k.text, "%s", text);
    (void)tui_panel_key(p, l, &k, &act);
    return act;
}

static tui_panel_act panel_ctrl(tui_panel *p, const tui_settings *l, const char *base)
{
    tui_key k;
    tui_panel_act act;
    memset(&k, 0, sizeof k);
    k.kind = TUI_KEY_OTHER;
    k.mods = TUI_MOD_CTRL;
    (void)snprintf(k.base, sizeof k.base, "%s", base);
    (void)tui_panel_key(p, l, &k, &act);
    return act;
}

/* The panel dressed for another list (/auth): its title, a line in the filter's place, its own keys,
 * and "info" rows that show their value as it is and their own keys under the description. */
static void panel_info_row(tui_setting *r, const char *id, const char *group, const char *name, const char *value,
                           int valid, const char *desc, const char *keys)
{
    memset(r, 0, sizeof *r);
    r->id = strdup(id);
    r->key = strdup("");
    r->group = strdup(group);
    r->name = strdup(name);
    r->kind = strdup("info");
    r->def = strdup("");
    r->def_label = strdup("");
    r->description = strdup(desc);
    r->applies = strdup(keys);
    r->value = strdup(value);
    r->valid = valid;
}

static void test_panel_skin(void)
{
    tui_settings l = {NULL, 0, -1};
    tui_panel p;
    tui_lines out = {NULL, 0, 0};
    int crow, ccol;
    char *all;
    l.s = calloc(2, sizeof *l.s);
    l.n = 2;
    panel_info_row(&l.s[0], "fake default", "fake", "default*", "API key \xc2\xb7 ok", 1, "for fake/*", "enter: in use");
    panel_info_row(&l.s[1], "fake second", "fake", "second", "API key \xc2\xb7 ! out of credit", 0,
                   "Your credit balance is too low.", "enter: replace this key");
    memset(&p, 0, sizeof p);
    p.title = "Auth";
    p.head = "model fake/m \xc2\xb7 key default";
    p.hint = "enter: fix \xc2\xb7 esc: close";
    (void)snprintf(p.sel, sizeof p.sel, "fake second");
    check_int("skin box", tui_panel_lines(&p, &l, TUI_PANEL_BOX, 60, 3, &out, &crow, &ccol), 0);
    panel_widths("skin box 60", &out, 60, 1);
    all = plain_join(&out);
    plain_has("skin title", all, "\xe2\x94\x8c\xe2\x94\x80 Auth \xe2\x94\x80", 1);
    plain_has("skin count", all, "2 of 2 \xe2\x94\x80\xe2\x94\x90", 1);
    plain_has("skin head", all, "\xe2\x94\x82 model fake/m \xc2\xb7 key default", 1);
    plain_has("skin no filter", all, "type to filter", 0);
    plain_has("skin bad value shown", all, "second                     API key \xc2\xb7 ! out of credit", 1);
    plain_has("skin not settings words", all, "not valid", 0);
    plain_has("skin row keys", all, "enter: replace this key", 1);
    plain_has("skin no default", all, "default none", 0);
    plain_has("skin keys", all, "\xe2\x94\x94\xe2\x94\x80 enter: fix \xc2\xb7 esc: close", 1);
    check_int("skin no cursor", crow, -1);
    free(all);
    tui_lines_clear(&out);
    (void)tui_panel_lines(&p, &l, TUI_PANEL_DOCK, 80, 3, &out, &crow, &ccol);
    plain_line_is("skin dock title", &out, 0, "Auth  2 of 2");
    check_int("skin dock no cursor", crow, -1);
    tui_lines_clear(&out);
    (void)tui_panel_lines(&p, &l, TUI_PANEL_LINE, 60, 0, &out, &crow, &ccol);
    plain_line_is("skin line", &out, 0, "Auth 2/2 second: API key \xc2\xb7 ! out of credit");
    tui_lines_clear(&out);
    tui_settings_free(&l);
}

static void test_panel(void)
{
    char *json = slurp_file("test/tui/fixtures/settings.json"), *all;
    tui_settings l = {NULL, 0, -1};
    tui_panel p;
    tui_lines out = {NULL, 0, 0};
    tui_panel_act act;
    int crow, ccol;
    char line[1024];
    tui_setting *wide;

    check_int("panel parse", tui_settings_parse(json, &l), 0);
    check_int("panel rows", (long)l.n, 35);
    check_int("panel unchanged", tui_settings_parse("{\"version\":7,\"unchanged\":true}", &l), 1);
    check_int("panel unchanged keeps the rows", (long)l.n, 35);
    check_int("panel not an answer", tui_settings_parse("[1]", &l), -1);
    check_str("panel row", tui_settings_get(&l, "hyperlinks")->name, "Hyperlinks");
    check_int("panel choice values", (long)tui_settings_get(&l, "hyperlinks")->nvalues, 3);
    check_int("panel number range", (long)tui_settings_get(&l, "lapseSeconds")->min, 1);
    check_int("panel groups and rows", (long)tui_panel_list_len(&(tui_panel){0}, &l), 35 + 8);

    /* 80x24: a box 72 wide, 11 list rows, 18 lines, the cursor in the filter */
    memset(&p, 0, sizeof p);
    check_int("panel box", tui_panel_lines(&p, &l, TUI_PANEL_BOX, 72, 11, &out, &crow, &ccol), 0);
    check_int("panel box lines", (long)out.n, 18);
    panel_widths("panel box 72", &out, 72, 1);
    plain_line_is("panel box title", &out, 0,
                  "\xe2\x94\x8c\xe2\x94\x80 Settings \xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80 1 of 35 \xe2\x94\x80\xe2\x94\x90");
    all = plain_join(&out);
    plain_has("panel box filter", all, "\xe2\x94\x82 > type to filter", 1);
    plain_has("panel box heading", all, "\xe2\x94\x82 Model ", 1);
    plain_has("panel box selected", all, "\xe2\x94\x82 \xe2\x86\x92 Default model              pic's own", 1);
    plain_has("panel box value column", all, "\xe2\x94\x82   Default thinking level     medium", 1);
    plain_has("panel box more", all, "\xe2\x86\x93 ", 1);
    plain_has("panel box keys", all,
              "\xe2\x94\x94\xe2\x94\x80 \xe2\x86\x91\xe2\x86\x93 move \xc2\xb7 \xe2\x86\x90\xe2\x86\x92 enter: change \xc2\xb7 ^R: default \xc2\xb7 esc: close", 1);
    plain_has("panel box applies", all, "default pic's own \xc2\xb7 next conversation", 1);
    plain_has("panel box separator", all, "\xe2\x94\x9c\xe2\x94\x80", 1);
    check_int("panel box cursor row", crow, 1);
    check_int("panel box cursor col", ccol, 4);
    free(all);
    tui_lines_clear(&out);

    /* 120x36: still 72 wide; taller */
    (void)tui_panel_lines(&p, &l, TUI_PANEL_BOX, 72, 23, &out, &crow, &ccol);
    check_int("panel 120x36 lines", (long)out.n, 30);
    panel_widths("panel box 120x36", &out, 72, 1);
    tui_lines_clear(&out);
    /* 64x14: the smallest box, 56 wide */
    (void)tui_panel_lines(&p, &l, TUI_PANEL_BOX, 56, 5, &out, &crow, &ccol);
    check_int("panel 64x14 lines", (long)out.n, 12);
    panel_widths("panel box 64x14", &out, 56, 1);
    tui_lines_clear(&out);

    /* docked: a title, the filter, ten rows, the description, the keys */
    (void)tui_panel_lines(&p, &l, TUI_PANEL_DOCK, 80, 10, &out, &crow, &ccol);
    check_int("panel dock lines", (long)out.n, 16);
    panel_widths("panel dock 80", &out, 80, 0);
    plain_line_is("panel dock title", &out, 0, "Settings  1 of 35");
    plain_line_is("panel dock filter", &out, 1, "> type to filter");
    check_int("panel dock cursor", crow, 1);
    check_int("panel dock cursor col", ccol, 2);
    tui_lines_clear(&out);
    (void)tui_panel_lines(&p, &l, TUI_PANEL_DOCK, 40, 4, &out, &crow, &ccol);
    panel_widths("panel dock 40", &out, 40, 0);
    tui_lines_clear(&out);

    /* one line, at 39x7 and 10x2 */
    (void)tui_panel_lines(&p, &l, TUI_PANEL_LINE, 39, 0, &out, &crow, &ccol);
    check_int("panel line lines", (long)out.n, 2);
    panel_widths("panel line 39", &out, 39, 0);
    plain_line_is("panel line", &out, 0, "Settings 1/35 Default model: pic's own");
    tui_lines_clear(&out);
    (void)tui_panel_lines(&p, &l, TUI_PANEL_LINE, 10, 0, &out, &crow, &ccol);
    panel_widths("panel line 10", &out, 10, 0);
    tui_lines_clear(&out);

    /* moving keeps a row of margin and says how many more */
    for (int i = 0; i < 13; i++)
        (void)panel_send(&p, &l, TUI_KEY_DOWN, NULL);
    check_str("panel down", p.sel, "fullscreenWheelScrollLines");
    (void)tui_panel_lines(&p, &l, TUI_PANEL_BOX, 72, 11, &out, &crow, &ccol);
    all = plain_join(&out);
    plain_has("panel scrolled up count", all, "\xe2\x86\x91 ", 1);
    plain_has("panel scrolled selected", all, "\xe2\x86\x92 Wheel scrolling", 1);
    plain_has("panel scrolled count", all, "14 of 35", 1);
    plain_has("panel choices with a tick", all, "   \xe2\x9c\x93 auto   1   2   3   5   10", 1);
    free(all);
    tui_lines_clear(&out);
    (void)panel_send(&p, &l, TUI_KEY_UP, NULL);
    check_str("panel up", p.sel, "fullscreenCopyOnSelect");
    (void)panel_send(&p, &l, TUI_KEY_END, NULL);
    check_str("panel end", p.sel, "passphraseCommand");
    (void)panel_send(&p, &l, TUI_KEY_DOWN, NULL);
    check_str("panel down wraps", p.sel, "defaultModel");

    /* a long value and a wide one are cut to the box */
    wide = NULL;
    for (size_t i = 0; i < l.n; i++)
        if (strcmp(l.s[i].id, "remote.relay") == 0)
            wide = &l.s[i];
    free(wide->value);
    wide->value = strdup("https://\xe4\xb8\xad\xe6\x96\x87\xe4\xb8\xad\xe6\x96\x87\xe4\xb8\xad\xe6\x96\x87\xe4\xb8\xad\xe6\x96\x87\xe4\xb8\xad\xe6\x96\x87\xe4\xb8\xad\xe6\x96\x87\xe4\xb8\xad\xe6\x96\x87\xe4\xb8\xad\xe6\x96\x87\xe4\xb8\xad\xe6\x96\x87\xe4\xb8\xad\xe6\x96\x87.example/a-very-long-path");
    tui_panel_select(&p, &l, "remote.relay");
    (void)tui_panel_lines(&p, &l, TUI_PANEL_BOX, 56, 5, &out, &crow, &ccol);
    panel_widths("panel wide value", &out, 56, 1);
    all = plain_join(&out);
    plain_has("panel wide value cut", all, "\xe2\x80\xa6", 1);
    free(all);
    tui_lines_clear(&out);
    (void)tui_panel_lines(&p, &l, TUI_PANEL_DOCK, 41, 3, &out, &crow, &ccol);
    panel_widths("panel wide value docked", &out, 41, 0);
    tui_lines_clear(&out);

    /* the filter: names that start with it, then names that have it, then descriptions */
    memset(&p, 0, sizeof p);
    (void)panel_send(&p, &l, TUI_KEY_CHAR, "m");
    (void)panel_send(&p, &l, TUI_KEY_CHAR, "o");
    check_str("panel filter best", p.sel, "mouse");
    (void)tui_panel_lines(&p, &l, TUI_PANEL_DOCK, 80, 10, &out, &crow, &ccol);
    plain_line_is("panel filter row", &out, 1, "> mo");
    plain_line_is("panel filter first", &out, 2, " \xe2\x86\x92 Mouse                      auto");
    plain_line_is("panel filter then contains", &out, 3, "   Default model              pic's own");
    check_int("panel filter cursor", ccol, 4);
    tui_lines_clear(&out);
    (void)panel_send(&p, &l, TUI_KEY_CHAR, " ");
    check_str("panel space types with a filter", p.filter, "mo ");
    act = panel_send(&p, &l, TUI_KEY_ESC, NULL);
    check_int("panel esc clears the filter", act.what, TUI_PANEL_NONE);
    check_str("panel esc cleared", p.filter, "");
    check_str("panel the found row stays", p.sel, "mouse");
    act = panel_send(&p, &l, TUI_KEY_ESC, NULL);
    check_int("panel esc closes", act.what, TUI_PANEL_CLOSE);
    act = panel_send(&p, &l, TUI_KEY_CTRL_C, NULL);
    check_int("panel ctrl+c closes", act.what, TUI_PANEL_CLOSE);
    (void)panel_send(&p, &l, TUI_KEY_CHAR, "z");
    (void)panel_send(&p, &l, TUI_KEY_CHAR, "z");
    (void)tui_panel_lines(&p, &l, TUI_PANEL_BOX, 72, 11, &out, &crow, &ccol);
    check_int("panel no match keeps the size", (long)out.n, 18);
    panel_widths("panel no match", &out, 72, 1);
    all = plain_join(&out);
    plain_has("panel no match says so", all, "No setting matches \"zz\".", 1);
    plain_has("panel no match count", all, "0 of 35", 1);
    plain_has("panel no match keys", all, "esc: clear the filter", 1);
    free(all);
    tui_lines_clear(&out);
    act = panel_send(&p, &l, TUI_KEY_ENTER, NULL);
    check_int("panel enter on nothing", act.what, TUI_PANEL_NONE);
    p.filter[0] = '\0';

    /* a paste goes into the filter, control characters dropped, cut to its room */
    {
        char big[2101];
        tui_key k;
        memset(big, 'x', 2000);
        memcpy(big + 10, "\x1b[31m\n\t", 7);
        big[2000] = '\0';
        memset(&k, 0, sizeof k);
        k.kind = TUI_KEY_PASTE;
        k.paste = big;
        k.paste_len = 2000;
        (void)tui_panel_key(&p, &l, &k, &act);
        check_int("panel paste action", act.what, TUI_PANEL_NONE);
        check_int("panel paste cut", (long)strlen(p.filter), (long)sizeof p.filter - 1);
        check_int("panel paste no controls", strchr(p.filter, '\x1b') == NULL && strchr(p.filter, '\n') == NULL, 1);
        p.filter[0] = '\0';
    }

    /* choices: Right, Space and Enter step on, Left back; Ctrl+R is the default */
    tui_panel_select(&p, &l, "hyperlinks");
    act = panel_send(&p, &l, TUI_KEY_RIGHT, NULL);
    check_int("panel right", act.what, TUI_PANEL_SET);
    check_str("panel right id", act.id, "hyperlinks");
    check_str("panel right value", act.value, "on");
    act = panel_send(&p, &l, TUI_KEY_LEFT, NULL);
    check_str("panel left wraps", act.value, "off");
    act = panel_send(&p, &l, TUI_KEY_CHAR, " ");
    check_str("panel space", act.value, "on");
    act = panel_send(&p, &l, TUI_KEY_ENTER, NULL);
    check_str("panel enter on a choice", act.value, "on");
    act = panel_ctrl(&p, &l, "r");
    check_int("panel ctrl+r", act.what, TUI_PANEL_RESET);
    check_str("panel ctrl+r id", act.id, "hyperlinks");
    /* every choice row cycles through exactly its list */
    for (size_t i = 0; i < l.n; i++) {
        tui_setting *s = &l.s[i];
        char *was = s->value;
        size_t at = 0;
        if (!s->nvalues)
            continue;
        while (at < s->nvalues && strcmp(s->values[at], was) != 0)
            at++;
        check_int("panel cycle starts on a value", at < s->nvalues, 1);
        tui_panel_select(&p, &l, s->id);
        for (size_t j = 1; j <= s->nvalues; j++) {
            act = panel_send(&p, &l, TUI_KEY_RIGHT, NULL);
            (void)snprintf(line, sizeof line, "panel cycle %s", s->id);
            check_str(line, act.value, s->values[(at + j) % s->nvalues]);
            s->value = s->values[(at + j) % s->nvalues];
        }
        check_str("panel cycle back to the start", s->value, was);
        s->value = was;
    }
    tui_panel_select(&p, &l, "defaultModel");
    act = panel_send(&p, &l, TUI_KEY_ENTER, NULL);
    check_int("panel enter on a picker", act.what, TUI_PANEL_PICK);
    check_str("panel picker id", act.id, "defaultModel");

    /* a number field: digits only, saved only in range, Ctrl+R puts the default in */
    tui_panel_select(&p, &l, "lapseSeconds");
    act = panel_send(&p, &l, TUI_KEY_ENTER, NULL);
    check_int("panel enter opens a field", p.field, 1);
    check_str("panel field starts empty for a worked-out default", p.text, "");
    (void)panel_send(&p, &l, TUI_KEY_CHAR, "a");
    (void)panel_send(&p, &l, TUI_KEY_CHAR, "0");
    check_str("panel letters ignored", p.text, "0");
    act = panel_send(&p, &l, TUI_KEY_ENTER, NULL);
    check_int("panel out of range not saved", act.what, TUI_PANEL_NONE);
    check_int("panel field stays", p.field, 1);
    (void)tui_panel_lines(&p, &l, TUI_PANEL_BOX, 72, 11, &out, &crow, &ccol);
    all = plain_join(&out);
    plain_has("panel field says what is wrong", all, "Seconds: 0   at least 1", 1);
    plain_has("panel field keys", all, "enter: save \xc2\xb7 ^R: default \xc2\xb7 esc: keep cache lifetime", 1);
    check_int("panel field cursor row", crow, 1 + 1 + 11 + 1 + 2);
    check_int("panel field cursor col", ccol, 2 + (int)strlen("  Seconds: 0"));
    free(all);
    tui_lines_clear(&out);
    (void)panel_send(&p, &l, TUI_KEY_BACKSPACE, NULL);
    (void)panel_send(&p, &l, TUI_KEY_CHAR, "9");
    (void)panel_send(&p, &l, TUI_KEY_CHAR, "0");
    act = panel_send(&p, &l, TUI_KEY_ENTER, NULL);
    check_int("panel in range saves", act.what, TUI_PANEL_SET);
    check_str("panel saved id", act.id, "lapseSeconds");
    check_str("panel saved value", act.value, "90");
    (void)panel_send(&p, &l, TUI_KEY_HOME, NULL);
    (void)panel_send(&p, &l, TUI_KEY_CHAR, "1");
    check_str("panel field cursor home", p.text, "190");
    act = panel_send(&p, &l, TUI_KEY_ESC, NULL);
    check_int("panel esc leaves the field", p.field, 0);
    check_int("panel esc in a field does not close", act.what, TUI_PANEL_NONE);
    tui_panel_select(&p, &l, "compaction.reserveTokens");
    (void)panel_send(&p, &l, TUI_KEY_ENTER, NULL);
    check_str("panel field starts with the value", p.text, "16384");
    for (int i = 0; i < 5; i++)
        (void)panel_send(&p, &l, TUI_KEY_BACKSPACE, NULL);
    (void)panel_ctrl(&p, &l, "r");
    check_str("panel ctrl+r in a field", p.text, "16384");
    p.field = 0;
    /* a text field takes any line; core checks it */
    tui_panel_select(&p, &l, "defaultTools");
    (void)panel_send(&p, &l, TUI_KEY_ENTER, NULL);
    check_int("panel text field", p.field, 1);
    (void)panel_send(&p, &l, TUI_KEY_CHAR, "x");
    act = panel_send(&p, &l, TUI_KEY_ENTER, NULL);
    check_int("panel text saves", act.what, TUI_PANEL_SET);
    check_str("panel text value", act.value, "read,bash,edit,write,send_messagex");
    (void)tui_panel_lines(&p, &l, TUI_PANEL_LINE, 39, 0, &out, &crow, &ccol);
    panel_widths("panel line field", &out, 39, 0);
    check_int("panel line field cursor", crow, 0);
    tui_lines_clear(&out);
    p.note_err = 1;
    (void)snprintf(p.note, sizeof p.note, "not saved: defaultTools is a comma list of tool names");
    (void)tui_panel_lines(&p, &l, TUI_PANEL_BOX, 72, 11, &out, &crow, &ccol);
    panel_widths("panel note", &out, 72, 1);
    all = plain_join(&out);
    plain_has("panel note shown", all, "not saved: defaultTools", 1);
    free(all);
    tui_lines_clear(&out);

    /* a click selects the setting on its line; a heading, a border or a "more" line selects nothing */
    memset(&p, 0, sizeof p);
    (void)tui_panel_lines(&p, &l, TUI_PANEL_BOX, 72, 11, &out, &crow, &ccol);
    tui_lines_clear(&out);
    check_int("panel click on the border", tui_panel_click(&p, &l, 0), 0);
    check_int("panel click on the filter", tui_panel_click(&p, &l, 1), 0);
    check_int("panel click on a heading", tui_panel_click(&p, &l, 2), 0);
    check_int("panel click on a row", tui_panel_click(&p, &l, 4), 1);
    check_str("panel click selects", p.sel, "defaultThinkingLevel");
    check_int("panel click below the list", tui_panel_click(&p, &l, 2 + 11), 0);
    tui_panel_select(&p, &l, "remote.notify");
    (void)tui_panel_lines(&p, &l, TUI_PANEL_BOX, 72, 11, &out, &crow, &ccol);
    tui_lines_clear(&out);
    check_int("panel click on \"more\"", tui_panel_click(&p, &l, 2), 0);
    check_int("panel click after scrolling", tui_panel_click(&p, &l, 3), 1);
    check_int("panel click moved off the row", strcmp(p.sel, "remote.notify") != 0, 1);
    (void)tui_panel_lines(&p, &l, TUI_PANEL_LINE, 39, 0, &out, &crow, &ccol);
    tui_lines_clear(&out);
    check_int("panel click on the one line", tui_panel_click(&p, &l, 0), 0);

    tui_settings_free(&l);
    free(json);
    pass("settings panel: rows, box, dock and line at every size, filter, choices, fields, clicks");
}

/* The column a plain line has TEXT at, in columns; -1 when it has none. */
static long plain_col(const tui_lines *l, size_t i, const char *text)
{
    char p[1024], *at;
    plain(l->lines[i], p, sizeof p);
    at = strstr(p, text);
    return at ? (long)tui_width(p, (size_t)(at - p)) : -1;
}

/* The line of L whose plain text has TEXT, or -1. */
static long plain_find(const tui_lines *l, const char *text)
{
    char p[1024];
    for (size_t i = 0; i < l->n; i++) {
        plain(l->lines[i], p, sizeof p);
        if (strstr(p, text))
            return (long)i;
    }
    return -1;
}

static void test_mpanel(void)
{
    static const tui_mrow rows[] = {
        {"anthropic/claude-opus-5-5", "Claude Opus 5.5", "$5/$25", "", NULL, NULL, NULL, 200000, 1, 0},
        {"anthropic/claude-haiku-5-5", "Claude Haiku 5.5", "$1/$5", "default", NULL, NULL, NULL, 200000, 1, 0},
        {"openrouter/deepseek/deepseek-v4.1-flash", "DeepSeek V4.1 Flash", "$0.1/$0.4", "key refused", NULL, NULL, NULL, 128000, 1, 1},
        {"\x01" "add", "+ Add an endpoint\xe2\x80\xa6", "", "", NULL, "a server's URL; its models join this list", NULL, 0, 1, 0},
    };
    static const size_t order[] = {0, 1, 2, 3};
    const char *hints = "type to filter \xc2\xb7 \xe2\x86\x91\xe2\x86\x93 move \xc2\xb7 enter: use \xc2\xb7 esc: close \xc2\xb7 "
                        "prices are $ per million tokens in/out \xc2\xb7 models with no key show once you type";
    tui_mlist m = {rows, order, 4, 0, 1, "", "anthropic/claude-opus-5-5",
                   "enter: the next message goes to anthropic/claude-opus-5-5", hints, NULL};
    tui_mview v = {0, 0, 0};
    tui_lines out = {NULL, 0, 0};
    int crow, ccol;
    long h, o, d, c;
    char *all;

    check_int("mpanel list grouped", (long)tui_mpanel_list_len(&m), 4 + 3);

    /* a box 80 wide: every line 80 columns, the title and the count in the top border */
    check_int("mpanel box", tui_mpanel_lines(&v, &m, TUI_PANEL_BOX, 80, 7, &out, &crow, &ccol), 0);
    check_int("mpanel box lines", (long)out.n, (long)(7 + tui_mpanel_chrome(&m, 80)));
    panel_widths("mpanel box 80", &out, 80, 1);
    all = plain_join(&out);
    plain_has("mpanel title", all, "\xe2\x94\x8c\xe2\x94\x80 Select a model ", 1);
    plain_has("mpanel count", all, " 1 of 3 \xe2\x94\x80\xe2\x94\x90", 1);
    plain_has("mpanel filter", all, "\xe2\x94\x82 > type to filter", 1);
    plain_has("mpanel heading", all, "\xe2\x94\x82 anthropic", 1);
    plain_has("mpanel endpoints heading", all, "\xe2\x94\x82 Endpoints", 1);
    plain_has("mpanel selected and current", all, "\xe2\x86\x92 \xe2\x9c\x93 claude-opus-5-5 ", 1);
    plain_has("mpanel id without provider", all, "    anthropic/claude", 0);
    plain_has("mpanel status", all, "key refused", 1);
    plain_has("mpanel action", all, "+ Add an endpoint", 1);
    plain_has("mpanel description", all, "Claude Opus 5.5 \xc2\xb7 200k context \xc2\xb7 $5/$25", 1);
    plain_has("mpanel enter", all, "enter: the next message goes to anthropic/claude-opus-5-5", 1);
    plain_has("mpanel hints wrapped whole", all, "show once you type", 1);
    plain_has("mpanel separator", all, "\xe2\x94\x9c\xe2\x94\x80", 1);
    /* aligned: names, prices and statuses each start in one column */
    o = plain_find(&out, "claude-opus-5-5");
    h = plain_find(&out, "claude-haiku-5-5");
    d = plain_find(&out, "deepseek-v4.1-flash");
    check_int("mpanel names aligned", plain_col(&out, (size_t)o, "Claude Opus"), plain_col(&out, (size_t)h, "Claude Haiku"));
    check_int("mpanel names aligned 2", plain_col(&out, (size_t)o, "Claude Opus"), plain_col(&out, (size_t)d, "DeepSeek"));
    check_int("mpanel prices aligned", plain_col(&out, (size_t)o, "$5/$25"), plain_col(&out, (size_t)d, "$0.1/$0.4"));
    check_int("mpanel status aligned", plain_col(&out, (size_t)h, "default"), plain_col(&out, (size_t)d, "key refused"));
    /* secondary text is muted; a key problem is a warning */
    plain_has("mpanel muted name", out.lines[h], tui_fg(TUI_T_MUTED), 1);
    plain_has("mpanel warning", out.lines[d], tui_fg(TUI_T_WARNING), 1);
    check_int("mpanel cursor row", crow, 1);
    check_int("mpanel cursor col", ccol, 4);
    /* clicks: the first list line is the heading, the next the first model */
    check_int("mpanel click heading", tui_mpanel_click(&v, &m, 2), -1);
    check_int("mpanel click row", tui_mpanel_click(&v, &m, 3), 0);
    check_int("mpanel click deepseek", tui_mpanel_click(&v, &m, (size_t)d), 2);
    check_int("mpanel click filter", tui_mpanel_click(&v, &m, 1), -1);
    free(all);
    tui_lines_clear(&out);

    /* a narrow box drops the name before cutting the id */
    (void)tui_mpanel_lines(&v, &m, TUI_PANEL_BOX, 56, 7, &out, &crow, &ccol);
    panel_widths("mpanel box 56", &out, 56, 1);
    all = plain_join(&out);
    plain_has("mpanel narrow id whole", all, "deepseek/deepseek-v4.1-flash", 1);
    plain_has("mpanel narrow hints whole", all, "show once you type", 1);
    free(all);
    tui_lines_clear(&out);

    /* a short list scrolls and says how many more */
    m.sel = 2;
    (void)tui_mpanel_lines(&v, &m, TUI_PANEL_BOX, 80, 3, &out, &crow, &ccol);
    panel_widths("mpanel scrolled", &out, 80, 1);
    all = plain_join(&out);
    plain_has("mpanel scrolled selected", all, "\xe2\x86\x92   deepseek", 1);
    plain_has("mpanel scrolled more", all, " more", 1);
    plain_has("mpanel scrolled count", all, " 3 of 3 ", 1);
    c = plain_find(&out, "deepseek");
    check_int("mpanel scrolled click", tui_mpanel_click(&v, &m, (size_t)c), 2);
    free(all);
    tui_lines_clear(&out);
    m.sel = 0;

    /* filtered: one ranked list, ids with their provider, no headings */
    m.grouped = 0;
    m.filter = "deep";
    check_int("mpanel list flat", (long)tui_mpanel_list_len(&m), 4);
    (void)tui_mpanel_lines(&v, &m, TUI_PANEL_BOX, 80, 4, &out, &crow, &ccol);
    all = plain_join(&out);
    plain_has("mpanel flat filter", all, "\xe2\x94\x82 > deep", 1);
    plain_has("mpanel flat ids", all, "openrouter/deepseek/deepseek-v4.1-flash", 1);
    plain_has("mpanel flat no heading", all, "\xe2\x94\x82 anthropic ", 0);
    check_int("mpanel flat cursor col", ccol, 8);
    free(all);
    tui_lines_clear(&out);

    /* no match says so */
    m.n = 0;
    m.filter = "zzz";
    (void)tui_mpanel_lines(&v, &m, TUI_PANEL_BOX, 80, 3, &out, &crow, &ccol);
    panel_widths("mpanel none", &out, 80, 1);
    all = plain_join(&out);
    plain_has("mpanel none says", all, "No model matches \"zzz\".", 1);
    plain_has("mpanel none count", all, " 0 of 0 ", 1);
    free(all);
    tui_lines_clear(&out);
    m.n = 4;
    m.filter = "";
    m.grouped = 1;

    /* docked: a title, the filter, the list, the description, the keys wrapped */
    (void)tui_mpanel_lines(&v, &m, TUI_PANEL_DOCK, 60, 7, &out, &crow, &ccol);
    panel_widths("mpanel dock", &out, 60, 0);
    plain_line_is("mpanel dock title", &out, 0, "Select a model  1 of 3");
    plain_line_is("mpanel dock filter", &out, 1, "> type to filter");
    all = plain_join(&out);
    plain_has("mpanel dock hints whole", all, "once you type", 1);
    check_int("mpanel dock click row", tui_mpanel_click(&v, &m, 3), 0);
    check_int("mpanel dock cursor", crow, 1);
    free(all);
    tui_lines_clear(&out);

    /* one line */
    (void)tui_mpanel_lines(&v, &m, TUI_PANEL_LINE, 39, 0, &out, &crow, &ccol);
    check_int("mpanel line lines", (long)out.n, 2);
    panel_widths("mpanel line", &out, 39, 0);
    plain_line_is("mpanel line", &out, 0, "Model 1/3 claude-opus-5-5 $5/$25");
    tui_lines_clear(&out);

    /* the key column (#73) shows only when rows carry one */
    {
        tui_mrow k[2];
        memcpy(k, rows, sizeof k);
        k[0].key = "work";
        k[1].key = "";
        m.rows = k;
        m.n = 2;
        (void)tui_mpanel_lines(&v, &m, TUI_PANEL_BOX, 80, 4, &out, &crow, &ccol);
        panel_widths("mpanel key column", &out, 80, 1);
        all = plain_join(&out);
        plain_has("mpanel key column", all, "work", 1);
        free(all);
        tui_lines_clear(&out);
        m.rows = rows;
        m.n = 4;
    }
    pass("model picker: grouped and flat rows, aligned columns, muted text, wrapped keys, clicks, box, dock and line");
}

static void family_is(const char *model, const char *key, long v0, long v1, long date)
{
    char k[128], what[200];
    long ver[6], d;
    (void)snprintf(what, sizeof what, "family %s", model);
    check_int(what, tui_model_family(model, k, sizeof k, ver, &d), 0);
    check_str(what, k, key);
    check_int(what, ver[0], v0);
    check_int(what, ver[1], v1);
    check_int(what, d, date);
}

static void test_suggest(void)
{
    static const char *const models[] = {
        "anthropic/claude-opus-4-5",          /* 0: superseded by 4-6 */
        "anthropic/claude-opus-4-6",          /* 1 */
        "anthropic/claude-haiku-4-5",         /* 2: the alias */
        "anthropic/claude-haiku-4-5-20251001",/* 3: its snapshot */
        "anthropic/claude-3-5-haiku-latest",  /* 4: an older generation of haiku */
        "openrouter/anthropic/claude-opus-4.6",       /* 5: a flagship */
        "openrouter/anthropic/claude-opus-4.6:batch", /* 6: a variant */
        "openrouter/meta-llama/llama-4-scout",        /* 7: neither used nor a flagship */
        "openrouter/qwen/qwen3-coder",                /* 8: used */
        "fake/refused-1",                     /* 9: its key was refused */
        "nokey/m",                            /* 10: no key */
        "fake/current",                       /* 11 */
    };
    static const int avail[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1};
    static const int warn[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1};
    static const char *const recent[] = {"openrouter/qwen/qwen3-coder", "fake/refused-1", "gone/model"};
    size_t out[12], lead = 0, n;
    char got[400] = "";

    family_is("claude-opus-4-6", "claude-opus", 4, 6, 0);
    family_is("claude-haiku-4-5-20251001", "claude-haiku", 4, 5, 20251001);
    family_is("claude-3-5-haiku-latest", "claude-haiku", 3, 5, 0);
    family_is("gpt-5.4-mini", "gpt-mini", 5, 4, 0);
    family_is("gpt-4o-2024-08-06", "gpt-4o", -1, -1, 20240806);
    family_is("deepseek/deepseek-v4.1-flash-1017", "deepseek/deepseek-flash", 4, 1, 1017);
    family_is("google/gemini-3.1-pro-preview", "google/gemini-pro", 3, 1, 0);
    family_is("moonshotai/kimi-k2.5", "moonshotai/kimi-k", 2, 5, 0);
    family_is("deep-research-preview-04-2026", "deep-research", -1, -1, 202604);
    {
        char k[64];
        long v[6], d;
        check_int("family variant", tui_model_family("anthropic/claude-opus-4.6:batch", k, sizeof k, v, &d), -1);
    }

    n = tui_models_suggest(models, avail, warn, 12, "fake/current", "anthropic/claude-haiku-4-5", recent, 3, out, &lead);
    for (size_t i = 0; i < n; i++) {
        size_t k = strlen(got);
        (void)snprintf(got + k, sizeof got - k, "%s%zu", i ? " " : "", out[i]);
    }
    /* current (refused, still shown), default, recent; anthropic's newest per family; OpenRouter's flagship */
    check_str("suggest", got, "11 2 8 1 5");
    check_int("suggest lead", (long)lead, 3);
    pass("model picker suggestions: current, default, recent, the newest of each family, flagships only from OpenRouter");
}

int main(void)
{
    test_width();
    test_wrap();
    test_decoder();
    test_render();
    test_fuzzy();
    test_atfile();
    test_atfile_ignore();
    test_editor();
    test_view();
    test_keys2();
    test_history_find();
    test_editor2();
    test_editor_images();
    test_editor_paste_unchanged();
    test_markdown();
    test_links();
    test_view2();
    test_border();
    test_border_title();
    test_viewport();
    test_keys_fullscreen();
    test_render_fullscreen();
    test_mouse_modes();
    test_render_fullwidth();
    test_render_box();
    test_transcript();
    test_render_replace();
    test_search();
    test_render_search();
    test_theme();
    test_themeset();
    test_keymap();
    test_key_ids();
    test_replies();
    test_remote_qr();
    test_panel();
    test_panel_skin();
    test_mpanel();
    test_suggest();
    return 0;
}