#!/bin/sh
# The settings panel (docs/manual/settings-panel.md) on a pseudo-terminal
# against a fake server: it opens at any time, a running reply or tool
# included, without interrupting it; it takes every key while open and gives
# back exactly what was under it; its fields cannot save a bad value; a change
# made elsewhere shows within a second. Cases A to H run in regular mode (the
# panel above the footer) and in fullscreen (a box over the transcript); I to K
# are fullscreen's: resizing, how frames are written, the scroll position, the
# search box and when changes apply. The release run's --no-faults is accepted.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
DRIVE=${DRIVE:?set DRIVE to the pty_drive binary}
S=$(cd "$(dirname "$0")/../pic/streams" && pwd)
V=$(cd "$(dirname "$0")/streams" && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
T0=$(mktemp -d "${TMPDIR:-/tmp}/pic-settings.XXXXXX")
T=$T0
MODE=regular
spids=
rpids=
cleanup() { [ -n "$spids$rpids" ] && kill $spids $rpids 2>/dev/null || :; rm -rf -- "$T0"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s: %s\n' "$MODE" "$*" >&2; exit 1; }
unset SSH_CONNECTION SSH_CLIENT SSH_TTY TMUX TERM_PROGRAM
TERM=xterm-256color # a real terminal always sets it; CI runners do not
export TERM ANTHROPIC_API_KEY=pic-settings-test-key PIC_MODEL_CATALOG=offline PIC_NO_NATIVE_CLIPBOARD=1
# mode T: a directory and a HOME of its own for each pass
mode() {
    MODE=$1
    T=$T0/$1
    mkdir -p "$T/home"
    HOME=$T/home
    export HOME
}
# Script lines for what only one mode shows: regular mode's live area holds the
# reply while the panel is open; fullscreen's box covers it until it closes.
open_sees() { if [ "$MODE" = regular ]; then printf 'expect %s' "$*"; else printf 'wait 1'; fi; }
closed_sees() { if [ "$MODE" = fullscreen ]; then printf 'expect %s' "$*"; else printf 'wait 1'; fi; }
F2='\eOQ'
DRIVE_ENV=

# serve NAME SPEC...: a fake server whose models file is $T/NAME.json
serve() {
    name=$1
    shift
    mkdir "$T/log-$name" "$T/ws-$name"
    "$SERVER" "$T/port-$name" "$T/log-$name" 300 "$@" &
    spids="$spids $!"
    i=0
    while [ ! -s "$T/port-$name" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server $name"; sleep 0.05; done
    printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"m","contextWindow":200000}]}}}' \
        "$(cat "$T/port-$name")" > "$T/$name.json"
}
# drive NAME [COLS ROWS]: pic against server NAME in MODE, the script on stdin
drive() {
    name=$1
    cols=${2:-80}
    rows=${3:-24}
    env $DRIVE_ENV PIC_MODELS_FILE="$T/$name.json" "$DRIVE" "$T/$name.tx" "$cols" "$rows" "$PIC" --tui-mode "$MODE" --db "$T/j-$name" \
        --workspace "$T/ws-$name" --model fake/m ||
        fail "$name: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$name.tx" | grep -av '^\s*$' | tail -8)"
}
plain() { perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\e\][^\a\e]*(\a|\e\\)//g; s/\eO.//g' "$1"; }
reqs() { ls "$T/log-$1" | grep -c '\.req$' || true; }
# when FILE PATTERN COMMAND...: runs COMMAND once PATTERN is in FILE (gives up after 30 s)
when() {
    file=$1
    pat=$2
    shift 2
    (
        n=0
        until grep -aqF -- "$pat" "$file" 2>/dev/null; do
            n=$((n + 1))
            [ "$n" -lt 600 ] || exit 0
            sleep 0.05
        done
        "$@"
    ) &
    rpids="$rpids $!"
}
setting() { "$PIC" settings "$1"; }
# the reply was not cut short: no abort, no stop, and its end arrived
whole() {
    plain "$T/$1.tx" | grep -aq 'Operation aborted' && fail "$1: the reply was aborted"
    plain "$T/$1.tx" | grep -aq 'Stopping' && fail "$1: the reply was stopped"
    [ "$(reqs "$1")" = "${2:-1}" ] || fail "$1: $(reqs "$1") requests, want ${2:-1}"
}

# A reply of 40 lines, one text delta each, sent slowly.
{
    cat <<'EOF'
event: message_start
data: {"type":"message_start","message":{"id":"msg_long","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"usage":{"input_tokens":25,"output_tokens":1}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}

EOF
    n=1
    while [ "$n" -le 40 ]; do
        printf 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"row %02d of the reply\\n"}}\n\n' "$n"
        n=$((n + 1))
    done
    cat <<'EOF'
event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":99}}

event: message_stop
data: {"type":"message_stop"}

EOF
} > "$T0/long.sse"

cases() {
# ---- A. during a reply --------------------------------------------------------
# F2 while the reply streams: the panel is on screen, the reply's last words
# still arrive, and the server saw one whole request and no cancel. Then with
# TERM unset and LC_ALL=C, as the forge runs. The window has lost focus, so the
# reply's end rings the bell and asks for a notification (on a slow machine a
# turn over ten seconds does that anyway), written outside any frame: waiting
# for it is waiting for the request to end, and case J sees it.
case_a() {
    serve "$1" "slow:$T0/long.sse:60"
    drive "$1" <<EOF
expect pic fake/m
send \e[O
send go\r
expect row 05
send $F2
expect type to filter
expect Default model
$(open_sees row 40)
expect ↓99
expect reply ready
send \e
wait 150
send Xtyped-later
expect Xtyped-later
send \x15
send \x04\x04
expect pic: conversation
EOF
    whole "$1"
}
DRIVE_ENV=
case_a a
printf 'PASS: A. %s: the panel opens during a reply, which finishes whole\n' "$MODE"
DRIVE_ENV="-u TERM LC_ALL=C"
case_a a-noterm
DRIVE_ENV=
printf 'PASS: A. %s: with TERM unset and LC_ALL=C the panel draws and closes\n' "$MODE"

# ---- B. during a tool ---------------------------------------------------------
# The panel opens while a bash call waits; its output appears and the reply ends.
serve b "sse:$V/bash_live.sse" "sse:$V/done.sse"
when "$T/b.tx" "type to filter" touch "$T/ws-b/live-release"
drive b <<EOF
expect pic fake/m
send go\r
expect out-alpha
send $F2
expect type to filter
$(open_sees out-beta)
waitfile $T/log-b/2.req
$(open_sees All done.)
wait 500
send \e
$(closed_sees All done.)
wait 150
send \x04\x04
expect pic: conversation
EOF
whole b 2
printf 'PASS: B. %s: a tool call runs on behind the panel\n' "$MODE"

# ---- C. editor text ---------------------------------------------------------------
# Half a message, the cursor three back; open, change a setting, close: the same
# text and cursor (X lands there), and Enter sends it whole.
serve c "sse:$S/text.sse"
drive c <<EOF
expect pic fake/m
send half a message
send \e[D\e[D\e[D
send $F2
expect type to filter
send hyper
expect → Hyperlinks
send \e[C
expect ✓ on
send \e
wait 150
send \e
wait 150
send X
expect messXage
send \r
expect Hello
send \x04\x04
expect pic: conversation
EOF
grep -aq 'half a messXage' "$T/log-c/1.req" || fail "C: the message sent was not the one typed"
[ "$(setting hyperlinks)" = on ] || fail "C: hyperlinks is $(setting hyperlinks)"
"$PIC" settings --unset hyperlinks
printf 'PASS: C. %s: the editor keeps its text and cursor under the panel\n' "$MODE"

# ---- D. over a picker and a prompt ------------------------------------------------------
# The model picker with a filter and the trust prompt moved down come back as they were.
serve d "sse:$S/text.sse"
drive d <<EOF
expect pic fake/m
send /model\r
expect Select a model
send fak
expect > fak
send $F2
expect type to filter
send \e
wait 150
send e
expect > fake
send \e
wait 150
send /trust\r
expect Workspace trust
send \e[B
expect →   Do not trust this workspace
send $F2
expect type to filter
send \e
wait 150
send \e[A
expect →   Trust this workspace
send \e
wait 150
send \x04\x04
EOF
printf 'PASS: D. %s: a picker and a prompt under the panel come back as they were\n' "$MODE"

# ---- E. /settings during a reply ------------------------------------------------------
# It opens at once; nothing is queued, and no second request follows.
serve e "slow:$T0/long.sse:60" "sse:$S/text.sse"
drive e <<EOF
expect pic fake/m
send go\r
expect row 05
send /settings\r
expect type to filter
expect ↓99
send \e
wait 150
send \x04\x04
expect pic: conversation
EOF
plain "$T/e.tx" | grep -aq 'Follow-up: /settings' && fail "E: /settings was queued"
whole e
printf 'PASS: E. %s: /settings during a reply opens at once and queues nothing\n' "$MODE"

# ---- F. input -----------------------------------------------------------------------
# A 2000-character paste and a burst of keys with the panel open reach neither
# the editor nor the request; Ctrl+C and Esc close it and the reply runs on.
serve f "slow:$T0/long.sse:60" "sse:$S/text.sse"
big=$(awk 'BEGIN { while (n++ < 2000) printf "q" }')
drive f <<EOF
expect pic fake/m
send go\r
expect row 05
send $F2
expect type to filter
send \e[200~$big\e[201~
expect No setting matches
send zz\r\r\x7f\x7f\tqq
send \x15
expect type to filter
send \x03
wait 150
send $F2
expect type to filter
send \e
wait 150
expect ↓99
send Xtyped-later
expect Xtyped-later
send \x15
send \x04\x04
expect pic: conversation
EOF
whole f
grep -aq qqqq "$T/log-f/1.req" && fail "F: the paste reached the request"
plain "$T/f.tx" | grep -aq 'Follow-up' && fail "F: a key was queued"
printf 'PASS: F. %s: keys and pastes go to the panel only; Ctrl+C and Esc close it\n' "$MODE"

# ---- G. values ------------------------------------------------------------------------
# A number field ignores letters and saves only in its range; a choice cycles
# through exactly its list; Ctrl+R puts the default back.
serve g "sse:$S/text.sse"
drive g <<EOF
expect pic fake/m
send $F2
expect type to filter
send lapse after
expect → Lapse after
send \r
expect Seconds:
send x0
expect at least 1
send \r
wait 200
send \x7f90\r
expect 90 seconds
send \x15
send hyperlinks
expect → Hyperlinks
send \e[C
expect ✓ on
send \e[C
expect ✓ off
send \e[C
expect ✓ auto
send \e[C
expect ✓ on
send \x12
expect ✓ auto
send \e
wait 150
send \e
wait 150
send \x04\x04
EOF
[ "$(setting lapseSeconds)" = 90 ] || fail "G: lapseSeconds is '$(setting lapseSeconds)', want 90"
[ -z "$(setting hyperlinks)" ] || fail "G: hyperlinks is '$(setting hyperlinks)' after Ctrl+R"
"$PIC" settings --unset lapseSeconds
printf 'PASS: G. %s: fields refuse bad values, choices cycle, Ctrl+R restores the default\n' "$MODE"

# ---- H. changed elsewhere -------------------------------------------------------------
# pic settings and an RPC set_setting change values under the open panel; the
# rows show them, and an open field keeps its text.
serve h "sse:$S/text.sse"
when "$T/h.tx" "✓ auto" "$PIC" settings hyperlinks off
when "$T/h.tx" "Tokens: 77" sh -c "printf '%s\n' '{\"id\":\"s\",\"type\":\"set_setting\",\"key\":\"compaction.reserveTokens\",\"value\":\"4096\"}' |
    PIC_MODELS_FILE='$T/h.json' '$PIC' --mode rpc --db '$T/j-h2' --workspace '$T/ws-h' --model fake/m > '$T/h-rpc.out' 2>&1"
drive h <<EOF
expect pic fake/m
send $F2
expect type to filter
send hyperlinks
expect ✓ auto
expect ✓ off
send \x15
send reserve
expect → Compaction reserve
send \r
send \x15
send 77
expect → Compaction reserve         4096 tokens
expect changed elsewhere to 4096 tokens
send 8
expect Tokens: 778
send \e
wait 150
send \e
wait 150
send \e
wait 150
send \x04\x04
EOF
grep -aq '"success":true' "$T/h-rpc.out" || fail "H: set_setting over RPC: $(cat "$T/h-rpc.out")"
[ "$(setting compaction.reserveTokens)" = 4096 ] || fail "H: reserveTokens is $(setting compaction.reserveTokens)"
printf 'PASS: H. %s: changes made elsewhere show in the open panel\n' "$MODE"
}

mode regular
cases
mode fullscreen
cases

# ---- I. resize ----------------------------------------------------------------------
# While open and streaming: 120x36, 80x24, 60x12, 34x7, 8x2 and back to 80x24.
# No crash; what the frames after that leave on the screen equals a fresh 80x24
# frame (a resize away and back draws one), in the screen model.
serve i "slow:$T0/long.sse:60"
drive i <<EOF
expect pic fake/m
send go\r
expect row 03
send $F2
expect type to filter
send \e[B\e[B
size 120 36
wait 300
size 80 24
wait 300
size 60 12
wait 300
size 34 7
wait 300
send \e[B
size 8 2
wait 300
size 80 24
expect ↓99
wait 500
size 81 24
wait 300
size 80 24
wait 500
send \e
wait 150
send \x04\x04
expect pic: conversation
EOF
whole i
T=$T perl -e '
    local $/; binmode STDIN; my $t = <STDIN>;
    my $leave = rindex($t, "\e[?1049l"); $t = substr($t, 0, $leave) if $leave > 0;
    my $close = rindex($t, "Settings"); # the last frame with the panel: Esc closes it after
    my $cut = index($t, "\e[?2026l", $close); $t = substr($t, 0, $cut + 8) if $close > 0 && $cut > 0;
    my @p = split /\e\[2J/, $t, -1;
    die "too few repaints\n" if @p < 4;
    open my $a, ">", "$ENV{T}/i-after.tx" or die; print $a $p[-3]; close $a;
    open my $b, ">", "$ENV{T}/i-fresh.tx" or die; print $b $p[-1]; close $b;
' < "$T/i.tx" || fail "I: the transcript"
perl "$HERE/screen.pl" 80 24 < "$T/i-after.tx" > "$T/i-after.screen"
perl "$HERE/screen.pl" 80 24 < "$T/i-fresh.tx" > "$T/i-fresh.screen"
grep -q 'Settings' "$T/i-after.screen" || fail "I: no panel on the screen after the resizes"
cmp -s "$T/i-after.screen" "$T/i-fresh.screen" ||
    fail "I: the screen after resizing differs from a fresh one: $(diff "$T/i-after.screen" "$T/i-fresh.screen" | head -12)"
printf 'PASS: I. resizing while open and streaming, down to 8x2 and back, leaves what a fresh frame draws\n'

# ---- J. redraw ----------------------------------------------------------------------
# Case A's fullscreen frames, the reply streaming behind the box: no clear after
# the first frame, every frame one synchronized update, no row written whose
# cells did not change.
grep -aqF "$(printf '\a\033]9;pic: reply ready')" "$T/a.tx" || fail "J: no done signal to check frames around"
perl "$HERE/frames.pl" 80 24 < "$T/a.tx" > "$T/a.frames" || fail "J: $(cat "$T/a.frames")"
printf 'PASS: J. %s\n' "$(cat "$T/a.frames")"

# ---- K. scroll, search, when a change applies ----------------------------------------------
# Scrolled up, open and close: the view is where it was. The search box open
# under the panel keeps its query and takes keys again after.
serve k1 "sse:$T0/long.sse"
drive k1 <<EOF
expect pic fake/m
send go\r
expect ↓99
send \e[5~
expect row 15 of the reply
send $F2
expect type to filter
send \e
wait 200
expect row 15 of the reply
send \x06
send row 3
expect 1/10
send $F2
expect type to filter
send \e
wait 200
expect row 3
send 9
expect 1/1
send \e
wait 150
send \x04\x04
expect pic: conversation
EOF
printf 'PASS: K. the scroll position and the search box under the panel come back as they were\n'

# A change to cache retention during a reply leaves that request as it was; the
# next one has it. A theme set elsewhere applies at once, to what is on screen.
serve k2 "slow:$T0/long.sse:60" "sse:$S/text.sse"
light_bg='48;2;223;231;236'
when "$T/k2.tx" "✓ none" "$PIC" settings theme light
DRIVE_ENV="COLORTERM=truecolor"
drive k2 <<EOF
expect pic fake/m
send go\r
expect row 03
send $F2
expect type to filter
send cache retention
expect ✓ short
send \e[D
expect ✓ none
wait 1200
expect ↓99
send \e
wait 150
send \e
wait 150
send next\r
expect Hello
send \x04\x04
expect pic: conversation
EOF
DRIVE_ENV=
# the box's border takes the light theme's colour before the panel closes
perl -e 'local $/; my $t = <STDIN>; $t = substr($t, 0, rindex($t, "type to filter")); my %c;
    $c{$1} = 1 while $t =~ /\e\[([0-9;]*)m\x{e2}\x{94}\x{8c}/g; exit(keys %c >= 2 ? 0 : 1);' < "$T/k2.tx" ||
    fail "K: the theme set elsewhere did not apply while the panel was open"
has_light() { grep -aqF "$(printf '\033[%sm' "$light_bg")" "$T/k2.tx"; }
has_light || fail "K: the light theme was not used"
grep -aq cache_control "$T/log-k2/1.req" || fail "K: the running request lost its cache retention"
if grep -aq cache_control "$T/log-k2/2.req"; then fail "K: the next request still asked for the cache"; fi
"$PIC" settings --unset cacheRetention
"$PIC" settings --unset theme
printf 'PASS: K. a running request keeps its settings and the next takes the change; a theme applies at once\n'
