#!/bin/sh
# Terminal UI fork/changelog/reload, crash resume, login/oauth, rewind, /rc ssh, and presence.
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}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
here=$(cd "$(dirname "$0")" && pwd)
S=$(cd "$here/../pic/streams" && pwd)
V=$(cd "$here/streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-tui-recovery.XXXXXX")
export HOME="$T/home"
. "$here/tui_lib.sh"

mkdir -p "$T/ws" "$T/ws8"
start_server "$T/port" "$T/log" 300 "sse:$S/text.sse"
write_models "$T/port" "$T/models.json"
export PIC_MODELS_FILE="$T/models.json"
drive() { drive_with regular 80 24 "$T/j" "$T/ws" fake/m "$@"; }

# /fork with no argument: Pi's "Fork from Message" picker of earlier user
# messages. Enter on the newest forks the path before it into a new
# conversation and puts that message in the editor; /changelog shows the
# newest entry; /reload re-reads skills.
mkdir -p "$T/log7" "$T/ws7"
drive7() { # NAME [pic args]: the seventh journal and workspace
    name=$1
    shift
    "$DRIVE" "$T/$name.tx" 80 24 "$PIC" --tui-mode regular --db "$T/j7" --workspace "$T/ws7" --model fake/m "$@" ||
        fail "$name: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$name.tx" | grep -v '^\s*$' | tail -8)"
}
drive7 forkpick <<'EOF2'
expect pic fake/m
send first question\r
expect ↑25 ↓12
send second question\r
expect ↑25 ↓12
send /fork\r
expect Fork from Message
expect Message 1 of 2
expect Message 2 of 2
send \e[A
expect Message 1 of 2
send \e[B
send \r
expect forked: now in
expect first question
expect > second question
send \x15
send \x04\x04
EOF2
[ "$("$PIC" --db "$T/j7" sessions | wc -l | tr -d ' ')" = 2 ] || fail "fork picker: expected the conversation and its fork"
fork_id=$("$PIC" --db "$T/j7" sessions --json | head -1 | sed 's/.*"id":"\([^"]*\)".*/\1/')
"$PIC" --db "$T/j7" log "$fork_id" | grep -q 'first question' || fail "fork picker: the fork lacks the first message"
"$PIC" --db "$T/j7" log "$fork_id" | grep -q 'second question' && fail "fork picker: the fork kept the chosen message"
printf 'PASS: /fork opens the user-message picker; choosing forks before it and refills the editor\n'

drive7 forkfirst tui -c <<'EOF2'
expect first question
send /fork\r
expect Fork from Message
send \e[A
send \r
expect forked: a new conversation
expect > first question
send \x15
send \x04\x04
EOF2
printf 'PASS: forking from the first message starts an empty conversation with its text in the editor\n'

drive7 changelog <<'EOF2'
expect pic fake/m
send /changelog\r
expect What's New
wait 300
send \x04\x04
EOF2
# Pi's order: oldest first, the newest last, next to the editor; rendered as
# markdown (no "## " or backticks left)
newest=$({ grep -m1 '^## ' "$(dirname "$0")/../../CHANGELOG.md" | sed 's/^## //'; for f in "$(dirname "$0")"/../../changelog.d/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-*.md; do [ -f "$f" ] && basename "$f" | cut -c1-10; done; } | LC_ALL=C sort -r | head -1)
oldest=$(grep '^## ' "$(dirname "$0")/../../CHANGELOG.md" | tail -1 | sed 's/^## //')
perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/changelog.tx" > "$T/changelog.txt"
n=$(grep -n "$newest" "$T/changelog.txt" | tail -1 | cut -d: -f1)
o=$(grep -n "$oldest" "$T/changelog.txt" | tail -1 | cut -d: -f1)
[ -n "$n" ] && [ -n "$o" ] && [ "$o" -lt "$n" ] || fail "changelog: the newest entry ($newest, line $n) is not after the oldest ($oldest, line $o)"
grep -q '^## ' "$T/changelog.txt" && fail "changelog: raw markdown headings"
grep -q '`/fork`' "$T/changelog.txt" && fail "changelog: raw backticks"
printf 'PASS: /changelog shows the entries as Pi does, newest last, as markdown\n'

(
    n=0
    until grep -aqF 'reloaded:' "$T/reload.tx" 2>/dev/null; do
        n=$((n + 1))
        [ "$n" -lt 600 ] || exit 0
        sleep 0.05
    done
    mkdir -p "$HOME/.pic/skills/reloadme"
    printf -- '---\nname: reloadme\ndescription: A freshly reloaded skill\n---\nDo it.\n' > "$HOME/.pic/skills/reloadme/SKILL.md"
    : > "$T/skill-made"
) &
rpid=$!
bg "$rpid"
drive7 reload <<'EOF2'
expect pic fake/m
send /reload\r
expect reloaded:
waitfile $T/skill-made
send /skill:reloadm
wait 300
send \x15
send /reload\r
expect skills;
send /skill:reloadm
expect A freshly reloaded skill
send \x15
send \x04\x04
EOF2
wait "$rpid" 2>/dev/null || :
perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g' "$T/reload.tx" | grep -c 'A freshly reloaded skill' | grep -qx 1 || fail "reload: the new skill showed before /reload"
printf 'PASS: /reload picks up a new skill\n'

# The skill listing's budget: a notice at startup and on /reload naming what it cut; silent when
# everything fits.
"$PIC" settings skillBudget 10 > /dev/null
drive skillbudget <<'EOF'
expect pic fake/m
expect over its budget of 10
expect shown by name only
send /reload\r
expect reloaded:
send \x04\x04
EOF
[ "$(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\s+/ /g' "$T/skillbudget.tx" | grep -o 'over its budget of 10' | wc -l | tr -d ' ')" -ge 2 ] ||
    fail "skill budget: no notice again on /reload"
"$PIC" settings --unset skillBudget > /dev/null
drive skillfits <<'EOF'
expect pic fake/m
send /reload\r
expect reloaded:
send \x04\x04
EOF
! perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g' "$T/skillfits.tx" | grep -q 'over its budget' || fail "skill budget: a notice while everything fits"
printf 'PASS: the skill budget warns at startup and on /reload, and is silent when the listing fits\n'


# ---- a crash mid-request (field test #3) ---------------------------------
# kill -9 takes the interface and its request child; pic tui -c then offers
# the unfinished request: Enter resumes it with the model and thinking level
# it was admitted with (not the one the interface starts with), Esc drops it
# (journaled as a cancel; the prompt stays in the context, as Pi's does).
mkdir -p "$T/log9" "$T/ws9"
# 1 hang (killed), 2 text (resumed), 3 hang (killed), 4 text (after the drop),
# 5 hang (Esc), 6 text (forked after), 7 text
"$SERVER" "$T/port9" "$T/log9" 300 "hang:$S/text.sse:200" "sse:$S/text.sse" "hang:$S/text.sse:200" "sse:$S/text.sse" \
    "hang:$S/text.sse:200" "sse:$S/text.sse" "sse:$S/text.sse" &
spid9=$!
bg "$spid9"
i=0
while [ ! -s "$T/port9" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server 9"; 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},{"id":"r","contextWindow":200000,"reasoning":true}]}}}' \
    "$(cat "$T/port9")" > "$T/models9.json"
export PIC_MODELS_FILE="$T/models9.json"
drive9() { # NAME [pic args]: the ninth journal and workspace
    name=$1
    shift
    "$DRIVE" "$T/$name.tx" 80 24 "$PIC" --tui-mode regular --db "$T/j19" --workspace "$T/ws9" --model fake/m "$@" ||
        fail "$name: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$name.tx" | grep -v '^\s*$' | tail -8)"
}
orphans9() { # the request child outlives a killed interface (its own session): kill it too
    pkill -9 -f -- "--db $T/j19 " 2>/dev/null || :
    i=0
    while pgrep -f -- "--db $T/j19 " > /dev/null 2>&1; do i=$((i + 1)); [ "$i" -lt 200 ] || fail "orphan request child"; sleep 0.05; done
}
drive9 kill1 --model fake/r --thinking high <<'EOF2'
expect pic fake/r
send first ask\r
expect Working
waitfile $T/log9/1.req
signal 9
EOF2
orphans9
drive9 resume1 tui -c <<'EOF2'
expect first ask
expect the last request was interrupted: Enter to resume, Esc to drop it
send \r
expect Hello, "world"
expect ↑25 ↓12
send \x04\x04
expect pic: conversation
EOF2
grep -q '"model":"r"' "$T/log9/2.req" || fail "tui resume: not the admitted model: $(grep -o '"model":"[^"]*"' "$T/log9/2.req")"
[ "$(grep -o '"thinking":{[^}]*}' "$T/log9/1.req")" = "$(grep -o '"thinking":{[^}]*}' "$T/log9/2.req")" ] ||
    fail "tui resume: not the admitted thinking level"
"$PIC" --db "$T/j19" --workspace "$T/ws9" dump | grep -q '^submission 1 .* answered | first ask' ||
    fail "tui resume: not answered: $("$PIC" --db "$T/j19" --workspace "$T/ws9" dump | grep "^submission")"
printf 'PASS: after kill -9, pic tui -c resumes the interrupted request with its own model\n'

drive9 kill2 <<'EOF2'
expect pic fake/m
send second ask\r
expect Working
waitfile $T/log9/3.req
signal 9
EOF2
orphans9
drive9 drop tui -c <<'EOF2'
expect second ask
expect the last request was interrupted: Enter to resume, Esc to drop it
send \e
expect interrupted request dropped
send third ask\r
expect Hello, "world"
send \x04\x04
expect pic: conversation
EOF2
"$PIC" --db "$T/j19" --workspace "$T/ws9" dump | grep -q '^submission 2 .* failed | second ask error=cancelled' ||
    fail "tui drop: not journaled: $("$PIC" --db "$T/j19" --workspace "$T/ws9" dump | grep '^submission')"
grep -q 'second ask' "$T/log9/4.req" && grep -q 'third ask' "$T/log9/4.req" || fail "tui drop: the next request's context"
"$PIC" --db "$T/j19" --workspace "$T/ws9" check > /dev/null || fail "tui drop: integrity"
printf 'PASS: Esc drops the interrupted request durably; the next message goes through\n'

# Ctrl+P with no scoped models walks one stable list, the models with a key
# in the registry's order (pic models, Pi's available models), and
# Shift+Ctrl+P walks back to where it started (field test #5: it bounced
# between two models).
"$PIC" --db "$T/j19" --workspace "$T/ws9" scoped-models --clear > /dev/null
"$PIC" --db "$T/j19" --workspace "$T/ws9" models --json | sed 's/.*"model":"\([^"]*\)".*/\1/' > "$T/cycle9"
at=$(grep -nx 'fake/m' "$T/cycle9" | cut -d: -f1)
n=$(wc -l < "$T/cycle9" | tr -d ' ')
next1=$(sed -n "$((at % n + 1))p" "$T/cycle9")
next2=$(sed -n "$(((at + 1) % n + 1))p" "$T/cycle9")
next3=$(sed -n "$(((at + 2) % n + 1))p" "$T/cycle9")
drive9 cycle <<EOF2
expect pic fake/m
send \x10
expect model $next1
send \x10
expect model $next2
send \x10
expect model $next3
send \e[112;6u
expect model $next2
send \e[112;6u
expect model $next1
send \e[112;6u
expect model fake/m
send \x04\x04
EOF2
printf 'PASS: Ctrl+P and Shift+Ctrl+P walk one stable list of models\n'

# /fork and /tree offer only points that can be continued from: after a
# prompt cancelled with Esc and a "!" command, forking before the next
# message and continuing from the cancelled prompt both work (field test #6).
# Esc keeps the prompt in the context and asks for nothing again, as Pi's
# abort does.
drive9 forkpoints <<'EOF2'
expect pic fake/m
send to be cancelled\r
expect Working
waitfile $T/log9/5.req
send \e
expect Operation aborted
send !echo from-bang\r
expect from-bang
wait 400
send after both\r
expect Hello, "world"
send /fork\r
expect Fork from Message
send \r
expect forked: now in
expect > after both
send \x15
send /tree\r
expect Conversation tree
send to be cancelled
wait 200
send \r
expect Summarize branch?
send \r
expect branched: now in
send next one\r
expect Hello, "world"
send \x04\x04
expect pic: conversation
EOF2
perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g' "$T/forkpoints.tx" | grep -q 'not a point to' && fail "forkpoints: a row was refused"
perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g' "$T/forkpoints.tx" | grep -q 'requested again' && fail "forkpoints: Esc said the reply is asked again"
grep -q 'to be cancelled' "$T/log9/6.req" || fail "forkpoints: the cancelled prompt left the context (Pi keeps it)"
grep -q 'to be cancelled' "$T/log9/7.req" && ! grep -q 'after both' "$T/log9/7.req" || fail "forkpoints: /tree did not continue from the cancelled prompt"
printf 'PASS: /fork and /tree rows after a cancel and a ! command can be chosen\n'

# First run with only an OpenRouter key: the saved default's provider has no
# key, so pic starts on Pi's default for the first provider that has one
# (defaultModelPerProvider), not on a model that cannot work.
"$PIC" --db "$T/j19" --workspace "$T/ws9" models --default fake/m > /dev/null
env -u ANTHROPIC_API_KEY OPENROUTER_API_KEY=pic-tui-test-key "$DRIVE" "$T/firstrun.tx" 80 24 "$PIC" --tui-mode regular \
    --db "$T/j19" --workspace "$T/ws9" <<'EOF2' ||
expect pic openrouter/deepseek/deepseek-v4.1-flash
send \x04\x04
EOF2
    fail "firstrun: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/firstrun.tx" | grep -v '^\s*$' | tail -8)"
printf 'PASS: with only an OpenRouter key, pic starts on a model it can use\n'

# /compact compacts at once, as Pi's does: too small a conversation says so;
# otherwise the summary request runs then and the result is shown.
drive9 compactsmall <<'EOF2'
expect pic fake/m
send /compact\r
expect Nothing to compact (session too small)
send \x04\x04
EOF2
"$PIC" settings compaction '{"keepRecentTokens":1}' > /dev/null
before=$(ls "$T/log9" | wc -l | tr -d ' ')
drive9 compactnow <<'EOF2'
expect pic fake/m
send one\r
expect ↑25 ↓12
send two\r
expect ↑50 ↓24
send /compact keep the names\r
expect compacted
send \x04\x04
expect pic: conversation
EOF2
"$PIC" settings compaction '{}' > /dev/null
after=$(ls "$T/log9" | wc -l | tr -d ' ')
[ "$after" -ge $((before + 3)) ] || fail "compact: $((after - before)) requests, expected two replies and a summary"
grep -l 'keep the names' "$T/log9/$((before + 3)).req" > /dev/null || fail "compact: the summary request lacks the focus"
"$PIC" --db "$T/j19" --workspace "$T/ws9" dump | grep -q '^entry .* compaction |' || fail "compact: no compaction journaled"
printf 'PASS: /compact compacts at once and says what it did\n'

# A resume that cannot finish the request here (its model's key is not in
# this shell) leaves it unfinished and the offer standing; Esc still drops it.
mkdir -p "$T/log10" "$T/ws10"
"$SERVER" "$T/port10" "$T/log10" 300 "hang:$S/text.sse:200" "sse:$S/text.sse" &
spid10=$!
bg "$spid10"
i=0
while [ ! -s "$T/port10" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server 10"; 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}]},"fake9":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$PIC_TUI_KEY9","models":[{"id":"k","contextWindow":200000}]}}}' \
    "$(cat "$T/port10")" "$(cat "$T/port10")" > "$T/models10.json"
export PIC_MODELS_FILE="$T/models10.json"
drive10() { # NAME [pic args]: the tenth journal and workspace
    name=$1
    shift
    "$DRIVE" "$T/$name.tx" 80 24 "$PIC" --tui-mode regular --db "$T/j20" --workspace "$T/ws10" --model fake/m "$@" ||
        fail "$name: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$name.tx" | grep -v '^\s*$' | tail -8)"
}
PIC_TUI_KEY9=pic-tui-key9 drive10 kill9 --model fake9/k <<'EOF2'
expect pic fake9/k
send needs its key\r
expect Working
waitfile $T/log10/1.req
signal 9
EOF2
pkill -9 -f -- "--db $T/j20 " 2>/dev/null || :
i=0
while pgrep -f -- "--db $T/j20 " > /dev/null 2>&1; do i=$((i + 1)); [ "$i" -lt 200 ] || fail "orphan request child 9"; sleep 0.05; done
unset PIC_TUI_KEY9 # a prefix on a function call persists in POSIX sh
drive10 nokey9 tui -c <<'EOF2'
expect needs its key
expect the last request was interrupted: Enter to resume, Esc to drop it
send \r
expect left unfinished: its model fake9/k needs
expect the last request was interrupted: Enter to resume, Esc to drop it
send \e
expect interrupted request dropped
send \x04\x04
expect pic: conversation
EOF2
"$PIC" --db "$T/j20" --workspace "$T/ws10" dump | grep -q '^submission 1 .* failed | needs its key error=cancelled' ||
    fail "nokey9: $("$PIC" --db "$T/j20" --workspace "$T/ws10" dump | grep '^submission')"
"$PIC" --db "$T/j20" --workspace "$T/ws10" check > /dev/null || fail "nokey9: integrity"
printf 'PASS: a resume that cannot have its model keeps the offer; Esc then drops it\n'

# Pi's SelectList scrolls the slash menu and counts "(selected/total)" under it;
# Pi's session selector shows a fork under the conversation it came from.
mkdir -p "$T/log11" "$T/ws11"
"$SERVER" "$T/port11" "$T/log11" 60 "sse:$S/text.sse" &
spid11=$!
bg "$spid11"
i=0
while [ ! -s "$T/port11" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server 11"; 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/port11")" > "$T/models11.json"
export PIC_MODELS_FILE="$T/models11.json"
drive11() { # NAME [pic args]: the eleventh journal and workspace
    name=$1
    shift
    "$DRIVE" "$T/$name.tx" 80 24 "$PIC" --tui-mode regular --db "$T/j21" --workspace "$T/ws11" --model fake/m "$@" ||
        fail "$name: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$name.tx" | grep -v '^\s*$' | tail -8)"
}
drive11 forkseed <<'EOF2'
expect pic fake/m
send root question\r
expect Working
expect Hello
send \x04\x04
EOF2
root=$("$PIC" --db "$T/j21" --workspace "$T/ws11" sessions --json | perl -ne 'print $1 if /"id":"([^"]+)"/' | head -n 1)
[ -n "$root" ] || fail "forks: no conversation"
"$PIC" --db "$T/j21" --workspace "$T/ws11" fork "$root" > /dev/null || fail "forks: fork"
"$PIC" --db "$T/j21" --workspace "$T/ws11" fork "$root" > /dev/null || fail "forks: second fork"
drive11 forkpick <<'EOF2'
expect pic fake/m
send /
expect (1/
send \e[B
expect (2/
send \e
send \x15
send /resume\r
expect Resume a conversation
expect ├─ 
expect └─ 
send \e
send \x04\x04
EOF2
"$PIC" --db "$T/j21" --workspace "$T/ws11" check > /dev/null || fail "forks: integrity"
printf 'PASS: the slash menu counts and scrolls; /resume shows forks under their parent\n'

# /login in place: the provider picker shows what each provider uses, a provider with a sign-in asks
# the method, the key is pasted into a masked field, and the new store keeps its key without asking
# for a passphrase (in ~/.pic/master.key here: this HOME is not the account's own), and nothing is
# printed outside the interface. The key never reaches the screen.
LKEY="sk-tui-login-sentinel-$$"
LPASS="tui-login-pass-$$"
(GROQ_API_KEY=pic-tui-env-key && export GROQ_API_KEY && drive login1) <<EOF
expect pic fake/m
send /login\r
expect Log in
expect ✓ env: ANTHROPIC_API_KEY
send groq
expect env: GROQ_API_KEY
send \x7f\x7f\x7f\x7f
send openai
expect not configured
wait 300
send \r
expect Log in to openai
expect Sign in with ChatGPT
expect Paste an API key
send \e[B
wait 100
send \r
expect API key for openai:
send \e[200~$LKEY\e[201~
expect ••••
send \r
expect Saved the API key for openai
send /login\r
expect Log in
send openai
expect API key (stored)
send \x03
wait 200
send /login openai\r
expect Log in to openai
send \e
wait 100
send \e
wait 600
send \x04\x04
EOF
! grep -a -q 'Rewind  (' "$T/login1.tx" || fail "login1: the Esc that closed the login choice began an Esc Esc (/rewind)"
for secret in "$LKEY" "$LPASS"; do
    ! grep -a -q -- "$secret" "$T/login1.tx" || fail "login1: a secret reached the screen"
done
"$PIC" --db "$T/j" --workspace "$T/ws" auth status | grep -q '^openai  *default\*  *API key' || fail "login1: the key was not stored"
! grep -a -q 'Passphrase for' "$T/login1.tx" || fail "login1: a passphrase was asked"
[ -s "$HOME/.pic/master.key" ] || fail "login1: no key file"
printf 'PASS: /login: the provider picker with states, the method, a pasted masked key, no passphrase asked\n'

if [ "$FAULTS" = yes ]; then
    # A sign-in in place: the address is shown, Esc cancels it and Ctrl-C cancels the next (each child
    # closes its listener: the next sign-in binds the same port), and the third, its browser scripted,
    # signs in; pic keeps running throughout.
    mkdir "$T/olog"
    "${OAUTH:?set OAUTH to the fake_oauth binary}" "$T/oport" "$T/olog" 120 "$S/../responses-streams/reasoning_text.sse" &
    opid=$!
bg "$opid"
    i=0
    while [ ! -s "$T/oport" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "oauth server"; sleep 0.05; done
    # The third launch signs in. Launches are counted with mkdir, which is atomic: they can run at
    # once, as macOS holds every run of a new executable while it checks the file (about half a
    # second, on its first run). That first run is made here, so the launches start in the order
    # pic makes them.
    cat > "$T/browser" <<EOB
#!/bin/sh
[ \$# -eq 0 ] && exit 0
n=1
until mkdir "$T/bcount.\$n" 2>/dev/null; do n=\$((n + 1)); done
[ \$n -ge 3 ] && curl -s -L --max-time 20 "\$1" > /dev/null 2>&1
exit 0
EOB
    chmod +x "$T/browser"
    "$T/browser"
    CBPORT=$(perl -MIO::Socket::INET -e 'print IO::Socket::INET->new(Listen => 1, LocalAddr => "127.0.0.1", LocalPort => 0)->sockport')
    (PIC_TEST_OPENAI_AUTH="http://127.0.0.1:$(cat "$T/oport")" PIC_TEST_OAUTH_PORT=$CBPORT PIC_TEST_BROWSER="$T/browser" &&
        export PIC_TEST_OPENAI_AUTH PIC_TEST_OAUTH_PORT PIC_TEST_BROWSER && drive signin) <<EOF
expect pic fake/m
send /login openai\r
expect Log in to openai
send \r
expect esc: cancel
expect Open this URL to sign in
expect api/accounts/authorize
send \e
expect Sign-in cancelled.
send /login openai\r
expect Log in to openai
send \r
expect Open this URL to sign in
send \x03
expect Sign-in cancelled.
send /login openai\r
expect Log in to openai
send \r
expect Signed in to openai (Sign in with ChatGPT)
send /login\r
expect Log in
send openai
expect signed in (Sign in with ChatGPT)
send \e
send \x04\x04
EOF
    ! grep -a -q 'in use' "$T/signin.tx" || fail "signin: a cancelled sign-in kept its port"
    ! grep -a -q 'oauth-sentinel' "$T/signin.tx" || fail "signin: a token reached the screen"
    opened=$(ls -d "$T"/bcount.* | wc -l | tr -d ' ')
    [ "$opened" = 3 ] || fail "signin: the browser opened $opened times"
    printf 'PASS: a sign-in in place: Esc and Ctrl-C cancel it and free its port; the next signs in\n'
fi

# /rewind (and Esc Esc on an empty editor): the conversation's messages,
# newest first, with the files changed after each; then what to restore. A
# file changed outside pic is refused and the rest restored only after a
# yes. doubleEscapeAction tree gives Esc Esc back to Pi's /tree.
mkdir -p "$T/ws12"
p12() { "$PIC" --db "$T/j22" --workspace "$T/ws12" "$@"; }
printf 'v0' > "$T/ws12/a.txt"
printf 'tool write a.txt v1\twrite c.txt c1\ntext done\n' > "$T/rw1"
printf 'tool write a.txt v2\twrite b.txt b1\ntext done\n' > "$T/rw2"
p12 submit rw1 'first edit' > /dev/null && p12 run --script "$T/rw1" > /dev/null || fail "rewind: setup 1"
rsid=$(p12 sessions --json | perl -ne 'print $1 if /"id":"([^"]+)"/' | head -n 1)
p12 submit rw2 'second edit' --session "$rsid" > /dev/null && p12 run --script "$T/rw2" > /dev/null || fail "rewind: setup 2"
drive12() { # NAME [pic args]: the twelfth workspace
    name=$1
    shift
    "$DRIVE" "$T/$name.tx" 100 24 "$PIC" --tui-mode regular --db "$T/j22" --workspace "$T/ws12" --model fake/m "$@" ||
        fail "$name: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$name.tx" | grep -v '^\s*$' | tail -8)"
}
drive12 rewindboth tui -c <<'EOF2'
expect second edit
send \e
wait 100
send \e
expect Rewind
expect second edit  (2 files changed after)
expect first edit  (3 files changed after)
send \r
expect Restore conversation and files
send \r
expect restored a.txt
expect deleted b.txt
expect rewound: the 1 message above is undone; now in
expect > second edit
send \x15
send \x04\x04
EOF2
[ "$(cat "$T/ws12/a.txt")" = v1 ] || fail "rewind: a.txt is $(cat "$T/ws12/a.txt")"
[ ! -e "$T/ws12/b.txt" ] || fail "rewind: b.txt was not deleted"
[ "$(p12 sessions | wc -l | tr -d ' ')" = 2 ] || fail "rewind: expected the conversation and its fork"
printf 'mine' > "$T/ws12/a.txt"
drive12 rewindrefuse tui -c <<'EOF2'
expect first edit
send /rewind\r
expect Rewind
send \r
expect Restore conversation and files
send \e[B
send \e[B
send \r
expect Some files cannot be restored
expect a.txt: it changed since pic last wrote it
send \r
expect deleted c.txt
expect rewound the files
send \x04\x04
EOF2
[ "$(cat "$T/ws12/a.txt")" = mine ] || fail "rewind: the changed file was overwritten"
[ ! -e "$T/ws12/c.txt" ] || fail "rewind: the rest was not restored after the yes"
"$PIC" settings doubleEscapeAction tree > /dev/null
drive12 rewindtree tui -c <<'EOF2'
expect first edit
send \e
wait 100
send \e
expect Conversation tree
send \e
send \x04\x04
EOF2
"$PIC" settings --unset doubleEscapeAction > /dev/null
p12 check > /dev/null || fail "rewind: integrity"
printf 'PASS: /rewind and Esc Esc pick a message and restore conversation and files; refusals ask first\n'

# /remote-control ssh (and /rc ssh): the phone's ssh address, the command, the checks with their
# fixes, as text; c copies the command (OSC 52 here), Esc closes. The host lookups are faked. /rc
# itself, the relay's, is test/tui/rc.sh.
if [ "$FAULTS" = yes ]; then
    export PIC_TEST_RC="-|testmac.local|0"
    drive40() { # NAME [pic args]: 100 by 40
        "$DRIVE" "$T/$1.tx" 100 40 "$PIC" --db "$T/j8" --workspace "$T/ws8" --model fake/m ||
            fail "$1: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$1.tx" | grep -v '^\s*$' | tail -8)"
    }
    drive40 remote <<'EOF2'
expect pic fake/m
send /rc ssh\r
expect Remote control over ssh
expect @testmac.local
expect then run: cd
expect --format text
expect Remote Login is off. Turn on Remote Login: System Settings → General → Sharing
expect install Tailscale to reach it from anywhere
send c
expect Sent the command to the terminal's clipboard
send \x1b
wait 300
send /remote-control ssh\r
expect then run:
send \x1b
wait 300
send /rc sh\r
expect /rc takes nothing, or pair, devices, qr, off or ssh
send /hotkeys\r
expect Other:
send \x04\x04
EOF2
    unset PIC_TEST_RC
    ! grep -q '▀' "$T/remote.tx" || fail "remote: a QR code drawn for ssh"
    grep -aq "$(printf '\033]52;c;')" "$T/remote.tx" || fail "remote: c copied nothing"
    printf 'PASS: /remote-control ssh and /rc ssh show the ssh address, the command and the checks; c copies, Esc closes\n'
fi

# A request from elsewhere (a phone's, another terminal's) on the conversation open here: its tool
# block is drawn before the reply that follows it, and a stop of one says it was aborted.
mkdir -p "$T/wsx"
px() { "$PIC" --db "$T/jx" --workspace "$T/wsx" "$@"; }
printf 'text first reply\n' > "$T/x1"
printf 'tool bash echo hi-there\ntext done-elsewhere\n' > "$T/x2"
printf 'tool bash sleep 30\ntext never\n' > "$T/x3"
px submit x1 'start' > /dev/null && px run --script "$T/x1" > /dev/null || fail "elsewhere: setup"
mkfifo "$T/x.in"
"$DRIVE" "$T/x.tx" 80 24 "$PIC" --tui-mode regular --db "$T/jx" --workspace "$T/wsx" --model fake/m tui -c < "$T/x.in" > "$T/x.drv" 2>&1 &
xp=$!
bg "$xp"
exec 4> "$T/x.in"
printf '%s\n' 'expect first reply' 'wait 1500' >&4
sleep 2
px submit x2 'from afar' --session latest > /dev/null && px run --script "$T/x2" > /dev/null || fail "elsewhere: run"
printf '%s\n' 'expect done-elsewhere' 'wait 800' 'send \x0f' 'wait 500' 'send \x0f' 'wait 500' >&4
sleep 2
px submit x3 'hold on' --session latest > /dev/null
px run --script "$T/x3" > /dev/null 2>&1 &
x3p=$!
bg "$x3p"
printf '%s\n' 'expect sleep 30' 'wait 500' 'send \e' 'expect Operation aborted' 'wait 300' 'send \x04\x04' >&4
exec 4>&-
wait "$xp" || fail "elsewhere: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/x.tx" | grep -v '^\s*$' | tail -12)"
wait "$x3p" || :
# Ctrl+O draws the whole transcript again, as committed: the last such drawing shows the order.
perl -0777 -ne 'my $t = $_; $t =~ s/\e\[[0-9;?]*[A-Za-z]//g; $t = substr($t, rindex($t, "first reply"));
    my $b = index($t, "echo hi-there"); my $r = index($t, "done-elsewhere"); exit(!($b >= 0 && $r > $b))' "$T/x.tx" ||
    fail "elsewhere: the tool block was drawn after the reply"
printf 'PASS: a request from elsewhere is drawn in order, its tool block before its reply, and Esc stops it\n'

# An idle terminal on a conversation holds its presence marker (a sender with wake off is told it
# is open in a terminal), draws the request a peer's message wakes there, and lets the marker go
# when it exits (#96).
mkdir -p "$T/wsw" "$T/logw"
"$SERVER" "$T/portw" "$T/logw" 60 "sse:$S/text.sse" "sse:$S/text.sse" &
wpid=$!
bg "$wpid"
i=0
while [ ! -s "$T/portw" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server w"; 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/portw")" > "$T/modelsw.json"
export PIC_MODELS_FILE="$T/modelsw.json"
pw() { "$PIC" --db "$T/jw" --workspace "$T/wsw" "$@"; }
pw --model fake/m ask 'first' > /dev/null 2>&1 || fail "idle tui: setup"
wsid=$(pw sessions | awk 'NR == 1 { print $1 }')
mkfifo "$T/w.in"
"$DRIVE" "$T/w.tx" 80 24 "$PIC" --tui-mode regular --db "$T/jw" --workspace "$T/wsw" --model fake/m tui -c < "$T/w.in" > "$T/w.drv" 2>&1 &
wdp=$!
bg "$wdp"
exec 4> "$T/w.in"
printf '%s\n' 'expect Hello' 'wait 1500' >&4
i=0
until pw settings grapevine.wake false > /dev/null 2>&1 && pw send --session "$wsid" prompt 'probe' 2> "$T/w.probe" > /dev/null &&
    grep -q 'open in a terminal' "$T/w.probe"; do
    i=$((i + 1))
    [ "$i" -lt 60 ] || fail "idle tui: a sender with wake off was not told it is open in a terminal: $(cat "$T/w.probe")"
    sleep 0.25
done
pw settings grapevine.wake true > /dev/null
pw send --session "$wsid" prompt 'ping from afar' > /dev/null 2>&1 || fail "idle tui: send"
printf '%s\n' 'expect ping from afar' 'wait 300' 'send \x04\x04' 'expect pic: conversation' >&4
exec 4>&-
wait "$wdp" || fail "idle tui: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/w.tx" | grep -v '^\s*$' | tail -12)"
pw settings grapevine.wake false > /dev/null
i=0
while :; do
    pw send --session "$wsid" prompt 'after' 2> "$T/w.after" > /dev/null || :
    ! grep -q 'open in a terminal' "$T/w.after" && break
    i=$((i + 1))
    [ "$i" -lt 40 ] || fail "idle tui: the presence marker outlived the terminal"
    sleep 0.25
done
# A crash lets it go too: the follower's lifeline closes with the terminal.
mkfifo "$T/w2.in"
"$DRIVE" "$T/w2.tx" 80 24 "$PIC" --tui-mode regular --db "$T/jw" --workspace "$T/wsw" --model fake/m tui -c < "$T/w2.in" > "$T/w2.drv" 2>&1 &
wdp=$!
bg "$wdp"
exec 4> "$T/w2.in"
printf '%s\n' 'expect Hello' 'wait 60000' >&4
i=0
until pw send --session "$wsid" prompt 'probe' 2> "$T/w.probe" > /dev/null && grep -q 'open in a terminal' "$T/w.probe"; do
    i=$((i + 1))
    [ "$i" -lt 60 ] || fail "idle tui: the second terminal holds no marker: $(cat "$T/w.probe")"
    sleep 0.25
done
tpid=$(pgrep -f "^$PIC --tui-mode regular --db $T/jw " | head -1)
[ -n "$tpid" ] || fail "idle tui: the terminal's pid"
kill -9 "$tpid"
i=0
while :; do
    pw send --session "$wsid" prompt 'after the crash' 2> "$T/w.after" > /dev/null || :
    ! grep -q 'open in a terminal' "$T/w.after" && break
    i=$((i + 1))
    [ "$i" -lt 40 ] || fail "idle tui: the presence marker outlived a crashed terminal"
    sleep 0.25
done
exec 4>&-
kill "$wdp" 2> /dev/null || :
kill "$wpid" 2> /dev/null || :
printf 'PASS: an idle terminal holds the presence marker, draws a request a peer wakes, and lets the marker go on exit or crash\n'

