Skip to content
pi-c Artifact [f616bf5776]
Login

Artifact [f616bf5776]

Artifact f616bf57760446e09b32f791fd2f1bac6576a5511b04132ac2563ddf51684b7b:


#!/bin/sh
# Terminal UI fullscreen mode, lifecycle hooks, display regressions, and practical settings parity.
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-screen.XXXXXX")
export HOME="$T/home"
. "$here/tui_lib.sh"
export TERM_PROGRAM=ghostty # enable mouse reporting in fullscreen (Apple_Terminal leaves it off)

# ---- fullscreen, Pi's default tuiMode ------------------------------------
# The alternate screen: a transcript viewport over a pinned editor and footer.
mkdir "$T/log5" "$T/ws5"
# 1 text, 2 "Hello" and then nothing (quit while it streams)
"$SERVER" "$T/port5" "$T/log5" 300 "sse:$S/text.sse" "hang:$S/text.sse:492" &
spid5=$!
bg "$spid5"
i=0
while [ ! -s "$T/port5" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server 5"; 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/port5")" > "$T/models5.json"
export PIC_MODELS_FILE="$T/models5.json"
drive5() { # NAME ROWS [pic args]: the fifth journal, no --tui-mode (the default)
    name=$1
    rows=$2
    shift 2
    "$DRIVE" "$T/$name.tx" 80 "$rows" "$PIC" --db "$T/j5" --workspace "$T/ws5" --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)"
}
pic5() { "$PIC" --db "$T/j5" --workspace "$T/ws5" "$@"; }
# FILE SEQ: the byte offset of the last SEQ in FILE (-1: none)
last_at() { perl -0777 -ne 'BEGIN { $s = shift; $s =~ s/\\e/\e/g } print rindex($_, $s), "\n"' "$2" "$1"; }
# FILE: the text written after the alternate screen was last left, escapes removed
after_leave() {
    perl -0777 -ne '$i = rindex($_, "\e[?1049l"); $_ = $i < 0 ? "" : substr($_, $i + 8);
        s/\e\][^\a]*\a//g; s/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g; print' "$1"
}

# Enter and leave: the alternate screen and mouse reporting go on and off; on
# exit the transcript is printed to the normal screen (fullscreenExitOutput).
drive5 fs 24 <<'EOF2'
expect pic fake/m
send hello\r
expect Hello, "world"
send \x04\x04
expect pic: conversation
EOF2
on=$(last_at "$T/fs.tx" '\e[?1049h')
off=$(last_at "$T/fs.tx" '\e[?1049l')
[ "$on" -ge 0 ] || fail "fullscreen: the alternate screen was not entered"
[ "$off" -gt "$on" ] || fail "fullscreen: the alternate screen was not left"
[ "$(last_at "$T/fs.tx" '\e[?1006h')" -ge 0 ] || fail "fullscreen: no mouse reporting"
[ "$(last_at "$T/fs.tx" '\e[?1000l')" -gt "$on" ] || fail "fullscreen: mouse reporting left on"
after_leave "$T/fs.tx" > "$T/fs.out"
grep -q 'pic fake/m' "$T/fs.out" && grep -q '^ hello' "$T/fs.out" && grep -q 'Hello, "world"' "$T/fs.out" &&
    grep -q 'pic: conversation' "$T/fs.out" || fail "fullscreen: the transcript was not printed on exit: $(cat "$T/fs.out")"
printf 'PASS: fullscreen enters and leaves the alternate screen; the transcript is printed on exit\n'

# Scrolling: PageUp shows earlier lines and Pi's jump-to-latest label, Ctrl+End
# follows again, the wheel scrolls, Ctrl+Home reaches the top; a drag selects
# and copies (OSC 52; PIC_NO_NATIVE_CLIPBOARD keeps the real clipboard out).
drive5 scroll 12 tui -c <<'EOF2'
expect Hello, "world"
send \e[5~
expect ↓ 
send \e[1;5F
wait 300
send \e[<64;10;2M
expect ↓ 
send \e[6~
send \e[6~
send \e[1;5H
expect pic fake/m
send \e[<0;1;1M
send \e[<32;10;1M
send \e[<0;10;1m
expect Copied!
send \x04\x04
expect pic: conversation
EOF2
grep -aqF "$(printf '\033]52;c;cGljIGZha2UvbQ==')" "$T/scroll.tx" || fail "fullscreen: the selection was not copied"
printf 'PASS: fullscreen PageUp/PageDown, Ctrl+Home/End and the wheel scroll the transcript; a drag copies\n'

# A Mac keyboard has no End key (Ctrl+Fn+Right is Spaces, Shift+PageDown is the
# terminal's own scrollback): Ctrl+Shift+Down jumps to the latest message; so
# does a click on the button at the right of the last row, and so does typing.
drive5 macjump 12 tui -c <<'EOF2'
expect Hello, "world"
send \e[5~
expect ↓ 
send \e[1;6A
expect pic fake/m
send \e[1;6B
expect Hello, "world"
send \e[1;6A
expect pic fake/m
send \e[<0;78;7M
send \e[<0;78;7m
expect Hello, "world"
send \e[1;6A
expect pic fake/m
send x
expect Hello, "world"
send \x7f
send \x04\x04
expect pic: conversation
EOF2
! grep -aqi "ctrl+shift+down" "$T/macjump.tx" || fail "macjump: the button names a key"
printf 'PASS: Ctrl+Shift+Down, a click on the jump button and typing jump to the latest message\n'

# The transcript scrolls while a reply streams: PageUp during the request
# holds the view while the dock below keeps drawing; Ctrl+End follows again.
drive5 stream 12 tui -c <<'EOF2'
expect Hello, "world"
send again\r
expect Hello
send \e[5~
expect ↓ 
expect Working
send \e[1;5F
expect Hello
send \x04\x04
expect pic: conversation
EOF2
printf 'PASS: fullscreen scrolls while a reply streams\n'

# fullscreenCopyOnSelect false: a selection waits for Ctrl+X.
pic5 settings fullscreenCopyOnSelect false
drive5 ctrlx 12 tui -c <<'EOF2'
expect Hello, "world"
send \e[1;5H
expect pic fake/m
send \e[<0;1;1M
send \e[<32;10;1M
send \e[<0;10;1m
wait 300
send \x18
expect Copied!
send \x04\x04
expect pic: conversation
EOF2
pic5 settings --unset fullscreenCopyOnSelect
[ "$(grep -ac 'Copied!' "$T/ctrlx.tx")" -ge 1 ] || fail "fullscreen: Ctrl+X did not copy the selection"
printf 'PASS: fullscreenCopyOnSelect false copies the selection with Ctrl+X\n'

# fullscreenExitOutput resume-hint: leaving prints only the conversation line.
pic5 settings fullscreenExitOutput resume-hint
drive5 hint 24 <<'EOF2'
expect pic fake/m
send \x04\x04
EOF2
pic5 settings --unset fullscreenExitOutput
after_leave "$T/hint.tx" > "$T/hint.out"
grep -q 'pic fake/m' "$T/hint.out" && fail "resume-hint: the transcript was printed"
printf 'PASS: fullscreenExitOutput resume-hint prints no transcript\n'

# A resize redraws the frame at the new size.
drive5 resize 24 tui -c <<'EOF2'
expect Hello, "world"
size 60 16
expect Hello, "world"
send \x04\x04
expect pic: conversation
EOF2
printf 'PASS: fullscreen redraws on resize\n'

# SIGTERM and a crash signal put the screen back.
for sig in 15 11; do
    drive5 "sig$sig" 24 <<EOF2
expect pic fake/m
signal $sig
EOF2
    on=$(last_at "$T/sig$sig.tx" '\e[?1049h')
    [ "$on" -ge 0 ] || fail "signal $sig: fullscreen was not on"
    [ "$(last_at "$T/sig$sig.tx" '\e[?1049l')" -gt "$on" ] || fail "signal $sig: the alternate screen was not left"
    [ "$(last_at "$T/sig$sig.tx" '\e[?1000l')" -gt "$on" ] || fail "signal $sig: mouse reporting left on"
    [ "$(last_at "$T/sig$sig.tx" '\e[?2004l')" -gt "$on" ] || fail "signal $sig: bracketed paste left on"
done
printf 'PASS: SIGTERM and SIGSEGV leave the alternate screen and restore the terminal\n'

# Regular mode, by flag and by setting: no alternate screen.
drive5 regular 24 --tui-mode regular <<'EOF2'
expect pic fake/m
send \x04\x04
EOF2
[ "$(last_at "$T/regular.tx" '\e[?1049h')" -lt 0 ] || fail "--tui-mode regular entered the alternate screen"
if "$PIC" --tui-mode wide tui > "$T/badmode.out" 2>&1; then fail "--tui-mode wide was accepted"; fi
grep -q 'Valid values: regular, fullscreen' "$T/badmode.out" || fail "--tui-mode: $(cat "$T/badmode.out")"
# /settings lists Pi's entries; Enter on TUI mode switches to regular at once and saves it.
drive5 settings 24 <<'EOF2'
expect pic fake/m
send /settings\r
send tui mode
expect → TUI mode                   fullscreen
send \r
expect → TUI mode                   regular
send \e
wait 150
send \e
expect TUI mode: regular
send \x04\x04
EOF2
[ "$(last_at "$T/settings.tx" '\e[?1049l')" -gt "$(last_at "$T/settings.tx" '\e[?1049h')" ] ||
    fail "settings: switching to regular did not leave the alternate screen"
[ "$(pic5 settings tuiMode)" = regular ] || fail "settings: tuiMode not saved"
drive5 setreg 24 <<'EOF2'
expect pic fake/m
send \x04\x04
EOF2
[ "$(last_at "$T/setreg.tx" '\e[?1049h')" -lt 0 ] || fail "tuiMode regular entered the alternate screen"
pic5 settings --unset tuiMode
printf 'PASS: regular mode by --tui-mode and by setting; /settings has the fullscreen entries\n'

# ---- hooks: the interface owns its conversations' lifecycle -------------
# In both modes: SessionStart once per conversation (the children share the
# interface's PIC_HOOK_OWNER), SessionEnd on /new and on quit, and on SIGTERM.
mkdir -p "$T/log6" "$T/ws6" "$HOME/.pic"
"$SERVER" "$T/port6" "$T/log6" 300 "sse:$S/text.sse" &
spid6=$!
bg "$spid6"
i=0
while [ ! -s "$T/port6" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server 6"; 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/port6")" > "$T/models6.json"
export PIC_MODELS_FILE="$T/models6.json"
# The hook appends "EVENT CONVERSATION SOURCE-OR-REASON" to $T/hooks.log.
cat > "$T/hook.sh" <<'SH'
in=$(cat)
field() { printf '%s' "$in" | sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p"; }
printf '%s %s %s%s\n' "$1" "$(field session_id)" "$(field source)" "$(field reason)" >> "$(dirname "$0")/hooks.log"
SH
printf '{"hooks": {"SessionStart": [{"hooks": [{"type": "command", "command": "sh %s/hook.sh SessionStart"}]}],
 "SessionEnd": [{"hooks": [{"type": "command", "command": "sh %s/hook.sh SessionEnd"}]}]}}\n' "$T" "$T" > "$HOME/.pic/hooks.json"
for mode in regular fullscreen; do
    rm -f "$T/hooks.log"
    "$DRIVE" "$T/hooks-$mode.tx" 80 24 "$PIC" --tui-mode "$mode" --db "$T/j6" --workspace "$T/ws6" --model fake/m <<'EOF2' ||
expect pic fake/m
send one\r
expect ↑25 ↓12
send two\r
expect ↑50 ↓24
send /new\r
expect new conversation
send three\r
expect ↑25 ↓12
send \x04\x04
expect pic: conversation
EOF2
        fail "hooks $mode: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/hooks-$mode.tx" | grep -v '^\s*$' | tail -8)"
    awk '{print $1, $3}' "$T/hooks.log" | tr '\n' ',' > "$T/hooks.seq"
    [ "$(cat "$T/hooks.seq")" = 'SessionStart startup,SessionEnd clear,SessionStart startup,SessionEnd prompt_input_exit,' ] ||
        fail "hooks $mode: $(cat "$T/hooks.log")"
    a=$(awk 'NR == 1 {print $2}' "$T/hooks.log")
    b=$(awk 'NR == 3 {print $2}' "$T/hooks.log")
    [ -n "$a" ] && [ "$a" != "$b" ] && [ "$(awk 'NR == 2 {print $2}' "$T/hooks.log")" = "$a" ] &&
        [ "$(awk 'NR == 4 {print $2}' "$T/hooks.log")" = "$b" ] || fail "hooks $mode: conversations: $(cat "$T/hooks.log")"
done
rm -f "$T/hooks.log"
# PIC_LAUNCH_DELAY_MS (development builds) holds the SessionEnd launcher in
# the terminal's session until it has died and the pty has hung up: the
# SIGHUP that brings must not kill it.
PIC_LAUNCH_DELAY_MS=300 "$DRIVE" "$T/hooks-term.tx" 80 24 "$PIC" --tui-mode fullscreen --db "$T/j6" --workspace "$T/ws6" --model fake/m <<'EOF2' ||
expect pic fake/m
send four\r
expect ↑25 ↓12
signal 15
EOF2
    fail "hooks SIGTERM: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/hooks-term.tx" | grep -v '^\s*$' | tail -8)"
i=0
until grep -q '^SessionEnd ' "$T/hooks.log" 2>/dev/null; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "hooks SIGTERM: no SessionEnd: $(cat "$T/hooks.log" 2>/dev/null)"; sleep 0.05; done
[ "$(awk '{print $1, $3}' "$T/hooks.log" | tr '\n' ',')" = 'SessionStart startup,SessionEnd other,' ] || fail "hooks SIGTERM: $(cat "$T/hooks.log")"
# SIGTERM after SessionStart has fired but before the first prompt is admitted (the hook is still
# running): the conversation has no row in the journal yet, and SessionEnd still runs for it.
cat > "$T/slow.sh" <<'SH'
sh "$(dirname "$0")/hook.sh" SessionStart
: > "$(dirname "$0")/ss.started"
sleep 5
SH
printf '{"hooks": {"SessionStart": [{"hooks": [{"type": "command", "command": "sh %s/slow.sh"}]}],
 "SessionEnd": [{"hooks": [{"type": "command", "command": "sh %s/hook.sh SessionEnd"}]}]}}\n' "$T" "$T" > "$HOME/.pic/hooks.json"
for mode in regular fullscreen; do
    rm -f "$T/hooks.log" "$T/ss.started"
    PIC_LAUNCH_DELAY_MS=300 "$DRIVE" "$T/hooks-early-$mode.tx" 80 24 "$PIC" --tui-mode "$mode" --db "$T/j6" --workspace "$T/ws6" --model fake/m <<EOF2 ||
expect pic fake/m
send five\r
waitfile $T/ss.started
signal 15
EOF2
        fail "hooks early SIGTERM $mode: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/hooks-early-$mode.tx" | grep -v '^\s*$' | tail -8)"
    i=0
    until grep -q '^SessionEnd ' "$T/hooks.log" 2>/dev/null; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "hooks early SIGTERM $mode: no SessionEnd: $(cat "$T/hooks.log" 2>/dev/null)"; sleep 0.05; done
    [ "$(awk '{print $1, $3}' "$T/hooks.log" | tr '\n' ',')" = 'SessionStart startup,SessionEnd other,' ] || fail "hooks early SIGTERM $mode: $(cat "$T/hooks.log")"
done
rm -f "$HOME/.pic/hooks.json"
printf 'PASS: with hooks, both modes start each conversation once and end it on /new, on quit and on SIGTERM, even before its first prompt\n'


# ---- field-test regressions ------------------------------------------------
mkdir -p "$T/log8" "$T/ws8"
# 1 a line exactly 120 columns wide; 2-3 a long bash output, then text; 4
# thinking; 5-6 bash again; 7 thinking then a long answer, slowly; 8 thinking,
# then nothing; 9-10 thinking, a tool call, then text (to resume)
"$SERVER" "$T/port8" "$T/log8" 300 "sse:$V/wide.sse" "sse:$V/bash.sse" "sse:$V/done.sse" "sse:$V/thinking_text.sse" \
    "sse:$V/bash.sse" "sse:$V/done.sse" "slow:$V/thinking_long.sse:15" "hang:$V/thinking_long.sse:902" \
    "sse:$S/thinking_tool.sse" "sse:$S/text.sse" &
spid8=$!
bg "$spid8"
i=0
while [ ! -s "$T/port8" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server 8"; 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/port8")" > "$T/models8.json"
export PIC_MODELS_FILE="$T/models8.json"
SCREEN="$(dirname "$0")/screen.pl"
drive8() { # NAME COLS [pic args]: the eighth journal, fullscreen unless told otherwise
    name=$1
    cols=$2
    shift 2
    "$DRIVE" "$T/$name.tx" "$cols" 30 "$PIC" --db "$T/j8" --workspace "$T/ws8" --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)"
}

# Fullscreen draws a line as wide as the terminal whole: its last character,
# and the footer's, are not erased.
drive8 fullwidth 120 <<'EOF2'
expect pic fake/m
send hi\r
expect next line
wait 300
send \x04\x04
expect pic: conversation
EOF2
perl "$SCREEN" --alt 120 30 < "$T/fullwidth.tx" > "$T/fullwidth.scr"
grep -q 'word lastZ$' "$T/fullwidth.scr" || fail "fullwidth: the last column was lost: $(grep 'word last' "$T/fullwidth.scr")"
grep -q ' fake/m$' "$T/fullwidth.scr" || fail "fullwidth: the footer lost its last column: $(tail -1 "$T/fullwidth.scr")"
printf 'PASS: fullscreen keeps the last column of a full-width line and of the footer\n'

# /hotkeys lists every group, not the first kilobyte of them.
drive8 hotkeys 120 --tui-mode regular <<'EOF2'
expect pic fake/m
send /hotkeys\r
expect Other:
expect Ctrl+F searches it
expect Rebind any action
send \x04\x04
EOF2
printf 'PASS: /hotkeys shows every group\n'

# Ctrl+O draws the tool blocks already shown again, expanded (Pi re-renders
# them all), and Ctrl+T the thinking blocks, hidden.
drive8 ctrlo 80 <<'EOF2'
expect pic fake/m
send list\r
expect 7 earlier lines, ctrl+o to expand
expect All done.
wait 300
send \x0f
expect tools expanded
wait 300
send \x04\x04
expect pic: conversation
EOF2
perl "$SCREEN" --alt 80 30 < "$T/ctrlo.tx" > "$T/ctrlo.scr"
grep -q '^  101$' "$T/ctrlo.scr" || fail "ctrl+o: the block shown was not expanded: $(cat "$T/ctrlo.scr")"
grep -q 'ctrl+o to expand' "$T/ctrlo.scr" && fail "ctrl+o: a collapsed hint is still shown: $(cat "$T/ctrlo.scr")"
# Pi's spacer: a blank line above each tool block
grep -B1 '^✓ \$ seq 101 112' "$T/ctrlo.scr" | head -1 | grep -q '^$' || fail "ctrl+o: no blank line above the tool block: $(cat "$T/ctrlo.scr")"
drive8 ctrlt 80 <<'EOF2'
expect pic fake/m
send ponder\r
expect Done thinking.
wait 300
send \x14
expect thinking blocks: hidden
wait 300
send \x04\x04
expect pic: conversation
EOF2
"$PIC" --db "$T/j8" --workspace "$T/ws8" settings --unset hideThinking
perl "$SCREEN" --alt 80 30 < "$T/ctrlt.tx" > "$T/ctrlt.scr"
grep -q 'pondering the answer carefully' "$T/ctrlt.scr" && fail "ctrl+t: the thinking shown was not hidden: $(cat "$T/ctrlt.scr")"
grep -q 'Thinking\.\.\.' "$T/ctrlt.scr" || fail "ctrl+t: no Thinking... label: $(cat "$T/ctrlt.scr")"
printf 'PASS: fullscreen Ctrl+O and Ctrl+T draw the blocks already shown again\n'

# Regular mode: Ctrl+O redraws the whole transcript (Pi's full redraw, with
# the scrollback cleared).
drive8 ctrlo-reg 80 --tui-mode regular <<'EOF2'
expect pic fake/m
send list\r
expect 7 earlier lines, ctrl+o to expand
expect All done.
wait 300
send \x0f
expect tools expanded
wait 300
send \x04\x04
expect pic: conversation
EOF2
grep -aqF "$(printf '\033[3J')" "$T/ctrlo-reg.tx" || fail "ctrl+o regular: the transcript was not redrawn"
perl -0777 -ne 'print substr($_, rindex($_, "\e[3J"))' "$T/ctrlo-reg.tx" | perl "$SCREEN" 80 30 > "$T/ctrlo-reg.scr"
grep -q '^  101$' "$T/ctrlo-reg.scr" || fail "ctrl+o regular: not expanded: $(cat "$T/ctrlo-reg.scr")"
grep -q 'ctrl+o to expand' "$T/ctrlo-reg.scr" && fail "ctrl+o regular: still collapsed: $(cat "$T/ctrlo-reg.scr")"
printf 'PASS: regular Ctrl+O redraws the transcript with the blocks expanded\n'

# Thinking goes above the answer it precedes, also when the answer is long
# enough to be committed while it streams.
drive8 order 80 <<'EOF2'
expect pic fake/m
send think long\r
expect Para 40
wait 500
send \x04\x04
expect pic: conversation
EOF2
after_leave "$T/order.tx" > "$T/order.out"
t=$(grep -n 'think one is about the plan' "$T/order.out" | head -1 | cut -d: -f1)
p=$(grep -n 'Para 01' "$T/order.out" | head -1 | cut -d: -f1)
[ -n "$t" ] && [ -n "$p" ] && [ "$t" -lt "$p" ] || fail "order: thinking (line $t) is not above the answer (line $p): $(cat "$T/order.out")"
[ "$(grep -c 'think one is about the plan' "$T/order.out")" = 1 ] || fail "order: the thinking was committed twice"
printf 'PASS: thinking is committed above a long streamed answer\n'

# Thinking streams as a growing block, as Pi draws it, not one line at a time.
drive8 ticker 80 <<'EOF2'
expect pic fake/m
send think more\r
expect think three decides
wait 500
send \x03
wait 100
send \x03
expect pic: conversation
EOF2
# the screen as the frame that first drew the last thought left it
perl -0777 -ne '$i = index($_, "think three decides"); $j = index($_, "\e[?2026l", $i); print substr($_, 0, $j)' \
    "$T/ticker.tx" | perl "$SCREEN" --alt 80 30 > "$T/ticker.scr"
grep -q 'think one is about the plan' "$T/ticker.scr" && grep -q 'think three decides' "$T/ticker.scr" ||
    fail "ticker: the thinking so far is not all shown: $(cat "$T/ticker.scr")"
printf 'PASS: thinking streams as a growing block\n'

# A continued conversation is drawn as it looked live: thinking, the tool
# block with its mark and title, and the footer's totals from the journal.
"$DRIVE" "$T/resume-src.tx" 80 30 "$PIC" --tui-mode regular --db "$T/j9" --workspace "$T/ws8" --model fake/r <<'EOF2' ||
expect pic fake/r
send write it\r
expect Hello, "world"
expect ↑55 ↓32
wait 300
send \x04\x04
EOF2
    fail "resume-src: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/resume-src.tx" | grep -v '^\s*$' | tail -8)"
"$DRIVE" "$T/resume-full.tx" 80 30 "$PIC" --tui-mode regular --db "$T/j9" --workspace "$T/ws8" --model fake/r tui -c <<'EOF2' ||
expect continuing
expect ↑55 ↓32
wait 300
send \x04\x04
EOF2
    fail "resume-full: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/resume-full.tx" | grep -v '^\s*$' | tail -8)"
perl "$SCREEN" 80 30 < "$T/resume-full.tx" > "$T/resume-full.scr"
grep -q '^Write it\.$' "$T/resume-full.scr" && grep -q '^✓ write t.txt (1 line, 1B)$' "$T/resume-full.scr" &&
    grep -q '^  x$' "$T/resume-full.scr" || fail "resume-full: $(cat "$T/resume-full.scr")"
grep -q 'write: Successfully' "$T/resume-full.scr" && fail "resume-full: a tool shown as a one-liner"
printf 'PASS: a continued conversation is drawn with its thinking, tool blocks and token totals\n'

# /export with no path writes next to the workspace, as Pi writes into its
# working directory, not into the directory pic was started from; the notice
# names the file in full.
mkdir -p "$T/elsewhere"
(cd "$T/elsewhere" && drive8 export 250 --tui-mode regular tui -c <<'EOF2'
expect continuing
send /export\r
expect as one self-contained web page
send \x04\x04
EOF2
)
ls "$T/ws8"/pic-session-*.html > /dev/null 2>&1 || fail "export: no page in the workspace"
ls "$T/elsewhere"/pic-session-*.html > /dev/null 2>&1 && fail "export: the page went to the launch directory"
perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g' "$T/export.tx" | grep -q 'written to /.*ws8/pic-session-' || fail "export: the notice does not name the full path"
printf 'PASS: /export with no path writes into the workspace and names the file in full\n'

# A long workspace path gives way from the left in the header and the footer:
# the header does not wrap, and the footer keeps the directory and the name.
drive8 narrow 60 --tui-mode regular <<'EOF2'
expect /help for all keys and commands
expect ws8 • new conversation
send \x04\x04
EOF2
printf 'PASS: long paths are shortened on the left in the header and footer\n'

# /settings: Esc in the theme picker goes back one level, to the settings
# list (Pi's nested menus); booleans read true or false, as Pi's do.
drive8 themeesc 120 --tui-mode regular <<'EOF2'
expect pic fake/m
send /settings\r
send hide
expect → Hide thinking              false
send \x15theme
expect → Theme
send \r
expect Theme  (up/down: preview
send \e
expect type to filter
send \e
wait 300
send \x04\x04
EOF2
printf 'PASS: Esc in the theme picker returns to /settings; booleans read true/false\n'


# Practical Pi settings parity in TUI: quietStartup, externalEditor, terminal.showTerminalProgress,
# treeFilterMode (+ ^O cycling), and enableSkillCommands.
mkdir -p "$T/wsp" "$T/logp" "$HOME/.pic/skills/tuipar"
printf -- '---\nname: tuipar\ndescription: Parity skill demo\n---\nPARITY_SKILL_BODY_TOKEN\n' > "$HOME/.pic/skills/tuipar/SKILL.md"
"$SERVER" "$T/portp" "$T/logp" 120 "sse:$S/thinking_tool.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" "sse:$S/text.sse" &
opid=$!
bg "$opid"
i=0
while [ ! -s "$T/portp" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server p"; 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/portp")" > "$T/modelsp.json"
export PIC_MODELS_FILE="$T/modelsp.json"
old_term=${TERM:-}
export TERM=xterm-256color
drivep() {
    name=$1
    shift
    "$DRIVE" "$T/$name.tx" 90 28 "$PIC" --tui-mode regular --db "$T/jp" --workspace "$T/wsp" --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)"
}

printf 'printf "from-ext-editor\\n" > "$1"\n' > "$T/ext-ed.sh"
"$PIC" settings quietStartup true > /dev/null
"$PIC" settings terminal.showTerminalProgress true > /dev/null
"$PIC" settings externalEditor "sh $T/ext-ed.sh" > /dev/null
export VISUAL=false EDITOR=false
drivep parity1 <<'EOF2'
expect >
send make file\r
expectraw \x1b]9;4;3\x07
expect ✓ write
expect Hello, "world"
expectraw \x1b]9;4;0\x07
send \x07
expect > from-ext-editor
send \x15
wait 100
send \x04\x04
expect pic: conversation
EOF2
unset VISUAL EDITOR
[ -f "$T/wsp/t.txt" ] || fail "parity1: write tool did not create t.txt"
! perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g' "$T/parity1.tx" | grep -q '/help for all keys' || fail "quietStartup: hints shown"
! perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g' "$T/parity1.tx" | grep -q 'pic fake/m' || fail "quietStartup: banner shown"
grep -aq "$(printf '\033]9;4;3\007')" "$T/parity1.tx" || fail "terminal.showTerminalProgress: no OSC 9;4;3 start"
grep -aq "$(printf '\033]9;4;0\007')" "$T/parity1.tx" || fail "terminal.showTerminalProgress: no OSC 9;4;0 clear"

"$PIC" settings --unset quietStartup > /dev/null
"$PIC" settings --unset terminal.showTerminalProgress > /dev/null
"$PIC" settings --unset externalEditor > /dev/null
"$PIC" settings enableSkillCommands false > /dev/null
"$PIC" settings treeFilterMode no-tools > /dev/null
drivep parity2 tui -c <<'EOF2'
expect pic fake/m
expect continuing
expect Hello, "world"
send /tree\r
expect [no-tools]
send \x0f
expect [user]
send \x0f
expect [labeled]
expect nothing to show
send \x0f
expect [all]
expect [tool result: write]
send \e
wait 200
send /skill:tuip
wait 300
send ar\r
waitfile $T/logp/3.req
expect Hello, "world"
wait 200
send \x04\x04
EOF2
! grep -aq "$(printf '\033]9;4;')" "$T/parity2.tx" || fail "terminal.showTerminalProgress=false: emitted OSC 9;4"
! perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g' "$T/parity2.tx" | grep -q 'Parity skill demo' || fail "enableSkillCommands=false: skill autocomplete shown"
! grep -q 'PARITY_SKILL_BODY_TOKEN' "$T/logp/3.req" || fail "enableSkillCommands=false: expanded skill body"
grep -q '/skill:tuipar' "$T/logp/3.req" || fail "enableSkillCommands=false: /skill:tuipar missing from request"

"$PIC" settings enableSkillCommands true > /dev/null
"$PIC" settings treeFilterMode user-only > /dev/null
drivep parity3 tui -c <<'EOF2'
expect pic fake/m
expect continuing
expect Hello, "world"
expect Hello, "world"
send /tree\r
expect [user]
send \e
wait 200
send /skill:tuip
expect Parity skill demo
send \x15
send /skill:tuipar\r
waitfile $T/logp/4.req
expect Hello, "world"
wait 200
send \x04\x04
EOF2
grep -q 'PARITY_SKILL_BODY_TOKEN' "$T/logp/4.req" || fail "enableSkillCommands=true: did not expand /skill:tuipar"

# enableSkillCommands=false while streaming steers /skill:... immediately as plain text.
"$PIC" settings enableSkillCommands false > /dev/null
"$PIC" settings --unset treeFilterMode > /dev/null
rm -f "$T/wsp/release" "$T/wsp/started"
touch_when "$T/parity4.tx" "Steering: /skill:tuipar steered" "$T/wsp/release"
"$DRIVE" "$T/parity4.tx" 90 28 "$PIC" --tui-mode regular --db "$T/jp4" --workspace "$T/wsp" --model fake/m <<'EOF2' ||
expect pic fake/m
send start hold\r
expect $ touch started
send /skill:tuipar steered\r
expect Steering: /skill:tuipar steered
expect held
expect Hello, "world"
wait 200
send \x04\x04
EOF2
    fail "parity4: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/parity4.tx" | grep -v '^\s*$' | tail -8)"
wait "$rpid" 2>/dev/null || :
grep -q '/skill:tuipar steered' "$T/logp/6.req" || fail "enableSkillCommands=false steer: missing literal /skill:"
! grep -q 'PARITY_SKILL_BODY_TOKEN' "$T/logp/6.req" || fail "enableSkillCommands=false steer: leaked skill body"
! grep -q '/skill:tuipar steered' "$T/logp/5.req" || fail "enableSkillCommands=false steer: leaked into request 5"

# TUI !cmd with missing shellPath reports non-zero exit code, and external_editor honors tabs & quotes.
printf 'printf "tab-quoted-ed\\n" > "$1"\n' > "$T/ext ed.sh"
"$PIC" settings shellPath "$T/no-such-shell" > /dev/null
VISUAL=$(printf "'sh'\t\"%s\"" "$T/ext ed.sh")
export VISUAL
drivep parity5 <<'EOF2'
expect pic fake/m
send !echo nope\r
expect Shell not found or not executable:
expect (exit 1)
send \x07
expect > tab-quoted-ed
send \x15
wait 100
send \x04\x04
EOF2
unset VISUAL
"$PIC" settings --unset shellPath > /dev/null
"$PIC" settings --unset enableSkillCommands > /dev/null
if [ -n "$old_term" ]; then export TERM="$old_term"; else unset TERM; fi
kill "$opid" 2> /dev/null || :
opid=
printf 'PASS: quietStartup, externalEditor, terminal.showTerminalProgress, treeFilterMode and enableSkillCommands work in TUI\n'