Skip to content
pi-c Artifact [78f3a9292d]
Login

Artifact [78f3a9292d]

Artifact 78f3a9292df607bf473cf2e9c772adffb27103c4b76d3cd0233cd01ebc667b5e:


#!/bin/sh
# Remote control through a relay (docs/design/remote-protocol.md): pic remote pair and pic remote
# against the test relay (test/pic/fake_relay.c, section 6 with the deployed Worker's deviations)
# and a scripted phone (test/pic/fake_phone.c, the initiator on pic's own Noise module). Pairing:
# the happy path, a wrong secret, a no, an expired offer, an offer used twice, and the phone that
# was not reading when paired was posted. Sessions: an unknown key, the wrong channel, a replayed
# and a reordered record, reconnecting and catching up from a cursor, a steer, an idle prompt, an
# abort, unpairing at the terminal and from the phone, pic remote killed at any moment, and two
# phones at once. The reply as it streams, and notifications to a test push service.
# Usage: test/pic/remote.sh [--no-faults]
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
RELAY=${RELAY:?set RELAY to the fake_relay binary}
PHONE=${PHONE:?set PHONE to the fake_phone binary}
SQLITE3=${SQLITE3:-sqlite3}
FAULTS=1
[ "${1:-}" = --no-faults ] && FAULTS=0
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-remote.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME/.pic"
unset PIC_KEY_FD
export ANTHROPIC_API_KEY=pic-remote-test-key PIC_PI_EXPORT=0
pids=
cleanup() {
    exec 2> /dev/null # the shell's notes on the jobs it kills
    for p in $pids; do kill -9 "$p" 2>/dev/null || true; done
    rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
fail() {
    printf 'FAIL: %s\n' "$*" >&2
    for f in "$T"/*.out "$T"/*.err "$T"/*.run "$HOME/.pic/remote.log"; do [ -s "$f" ] && { printf -- '--- %s\n' "$f" >&2; tail -20 "$f" >&2; }; done
    exit 1
}
bg() { pids="$pids $1"; }
await() { # FILE PATTERN [TRIES]: wait for the fixed string PATTERN in FILE (50 ms a try, 30 s by default)
    i=0
    until grep -qF -- "$2" "$1" 2>/dev/null; do
        i=$((i + 1))
        [ "$i" -lt "${3:-600}" ] || fail "timed out waiting for $2 in $1"
        sleep 0.05
    done
}
gone() { # PID: wait up to 30 s for it to exit; its status in rc
    rc=0
    wait "$1" || rc=$?
}
uq() { "$SQLITE3" "$HOME/.pic/pic.sqlite" "$1"; }

if [ "$FAULTS" = 0 ]; then
    # The release build: pic remote with no store yet says to pair first, and pairs nothing. The
    # rest needs PIC_TEST_PASSPHRASE, a dev build's seam.
    if "$PIC" remote < /dev/null > "$T/notty.out" 2> "$T/notty.err"; then fail "release: pic remote ran with no terminal"; fi
    [ -s "$T/notty.err" ] || fail "release: no message"
    printf 'PASS: release: pic remote without a terminal exits with a message\n'
    exit 0
fi
export PIC_TEST_PASSPHRASE=remote-test-pass
# Notifications go to the test push service on loopback, as often as a test asks.
export PIC_TEST_RC_PUSH_HTTP=1 PIC_TEST_RC_PUSH_GAP_MS=0

# One relay for the whole run; its deadline outlives the script.
"$RELAY" "$T/relay.port" 600 test-invite > "$T/relay.out" 2> "$T/relay.err" &
bg $!
i=0
while [ ! -s "$T/relay.port" ]; do
    i=$((i + 1))
    [ "$i" -lt 600 ] || fail "relay did not start"
    sleep 0.05
done
BASE="http://127.0.0.1:$(cat "$T/relay.port")"
"$PIC" settings remote.relay "$BASE" > /dev/null
state() { curl -s -X POST "$BASE/_test/state"; }
ctl() { curl -s -X POST "$BASE/_test/$1" > /dev/null; }

np=0
offer() { # start pic remote pair --pipe; its output in $PO, its stdin the fifo $PI (fd 3)
    np=$((np + 1))
    PO="$T/pair$np.out"
    PI="$T/pair$np.in"
    mkfifo "$PI"
    "$PIC" remote pair --pipe < "$PI" > "$PO" 2> "$T/pair$np.err" &
    PP=$!
    bg $PP
    exec 3> "$PI"
    await "$PO" '"type":"offer"'
    URL=$(sed -n 's/.*"url":"\([^"]*\)".*/\1/p' "$PO" | head -1)
    [ -n "$URL" ] || fail "offer: no address in $(cat "$PO")"
}
phone_pair() { # DIR NAME [ARGS]: the phone pairs in the background; its output in DIR.out
    mkdir -p "$1"
    "$PHONE" "$1" pair "$URL" "$2" ${3:-} > "$1.out" 2>&1 &
    PH=$!
    bg $PH
}

# ---- pairing -------------------------------------------------------------------------------
# Without the invite the relay refuses a new mailbox (403), and pairing says which setting to set.
if "$PIC" remote pair --pipe < /dev/null > "$T/noinv.out" 2> "$T/noinv.err"; then fail "invite: paired without one"; fi
grep -qF 'remote.invite' "$T/noinv.err" || fail "invite: message: $(cat "$T/noinv.err")"
"$PIC" settings remote.invite test-invite > /dev/null
printf 'PASS: a relay that wants an invite: pairing names the setting\n'

# The happy path: the two codes match, a yes commits one sealed device row, the phone hears paired,
# and the pairing channel is gone at the relay afterwards.
offer
case "$URL" in "$BASE/#p1."*) ;; *) fail "offer: address $URL" ;; esac
phone_pair "$T/ph1" "Phone One"
await "$PO" '"type":"code"'
await "$T/ph1.out" 'code '
want=$(sed -n 's/^code //p' "$T/ph1.out")
grep -qF "\"code\":\"$want\"" "$PO" || fail "pair: the codes differ: $(cat "$PO") / $want"
grep -qF '"name":"Phone One"' "$PO" || fail "pair: name: $(cat "$PO")"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 0 ] || fail "pair: a row before the yes"
echo y >&3
gone $PH
[ "$rc" = 0 ] || fail "pair: phone exit $rc"
grep -qx paired "$T/ph1.out" || fail "pair: phone: $(cat "$T/ph1.out")"
gone $PP
exec 3>&-
[ "$rc" = 0 ] || fail "pair: pic exit $rc"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "pair: rows"
[ "$(uq 'SELECT count(*) FROM picu_remote_key')" = 3 ] || fail "pair: keys"
uq "SELECT sealed FROM picu_remote_device" | grep -qF 'Phone One' && fail "pair: the device row is not sealed"
state | grep -qF 'channels 1 ' || fail "pair: relay channels: $(state)"
"$PIC" remote devices > "$T/devices.out" || fail "devices"
grep -qF 'Phone One' "$T/devices.out" || fail "devices: $(cat "$T/devices.out")"
grep -qF 'not running' "$T/devices.out" || fail "devices: running: $(cat "$T/devices.out")"
printf 'PASS: pairing: matching codes, a yes, one sealed row, the pairing channel deleted\n'

# The same address again: the offer was spent, its channel deleted; the phone hears it is gone.
phone_pair "$T/ph1b" "Phone Again"
gone $PH
[ "$rc" = 4 ] || fail "reused: phone exit $rc: $(cat "$T/ph1b.out")"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "reused: rows"
printf 'PASS: a used pairing address is refused by the relay\n'

# A no at the terminal: the phone hears pair_refused and nothing is written.
offer
phone_pair "$T/ph2" "Phone No"
await "$PO" '"type":"code"'
echo n >&3
gone $PH
[ "$rc" = 3 ] || fail "no: phone exit $rc: $(cat "$T/ph2.out")"
gone $PP
exec 3>&-
[ "$rc" != 0 ] || fail "no: pic exit 0"
grep -qF '"type":"refused"' "$PO" || fail "no: $(cat "$PO")"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "no: rows"
state | grep -qF 'channels 1 ' || fail "no: relay channels: $(state)"
printf 'PASS: a no at the terminal: the phone is refused, nothing is written\n'

# The wrong secret: a first message that does not verify is ignored (the phone hears nothing), and
# five end the offer.
offer
for k in 1 2 3 4 5; do phone_pair "$T/bad$k" "Bad $k" wrong-psk; done
await "$PO" 'too many pairing attempts failed'
gone $PP
exec 3>&-
[ "$rc" != 0 ] || fail "wrong psk: pic exit 0"
grep -qF '"type":"code"' "$PO" && fail "wrong psk: a code was shown"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "wrong psk: rows"
for k in 1 2 3 4 5; do grep -qF 'paired' "$T/bad$k.out" && fail "wrong psk: phone $k paired"; done
printf 'PASS: a first message under the wrong secret is ignored; five end the offer\n'

# An offer that expires: a phone past its time refuses it itself; one that got as far as the code
# hears pair_refused when it ends, and the channel goes.
PIC_TEST_PAIR_TTL=3 offer
phone_pair "$T/ph3" "Phone Slow"
await "$PO" '"type":"code"'
gone $PH
[ "$rc" = 3 ] || fail "expired: phone exit $rc: $(cat "$T/ph3.out")"
gone $PP
exec 3>&-
grep -qF '"type":"expired"' "$PO" || fail "expired: $(cat "$PO")"
sleep 1
phone_pair "$T/ph3b" "Phone Late"
gone $PH
[ "$rc" = 5 ] || fail "expired: late phone exit $rc: $(cat "$T/ph3b.out")"
state | grep -qF 'channels 1 ' || fail "expired: relay channels: $(state)"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "expired: rows"
printf 'PASS: an expired offer: refused to a phone mid-pairing, and by a phone that comes late\n'

# The phone is reconnecting when paired is posted (the relay says Pic-Peer: 0): the pairing channel
# stays until the phone reads again, so paired is not lost with it.
offer
phone_pair "$T/ph4" "Phone Away" "late 2500"
await "$T/ph4.out" away
echo y >&3
gone $PH
[ "$rc" = 0 ] || fail "away: phone exit $rc: $(cat "$T/ph4.out")"
gone $PP
exec 3>&-
[ "$rc" = 0 ] || fail "away: pic exit $rc"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 2 ] || fail "away: rows"
state | grep -qF 'channels 2 ' || fail "away: relay channels: $(state)"
printf 'PASS: paired reaches a phone that was reconnecting; the pairing channel goes after\n'

# ---- pic remote ------------------------------------------------------------------------------
n=0
spid=
serve() { # SPEC...: a fresh scripted model, journal and workspace
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    n=$((n + 1))
    mkdir "$T/log$n" "$T/ws$n"
    DB="$T/j$n.sqlite"
    WS="$T/ws$n"
    LOG="$T/log$n"
    "$SERVER" "$T/sport$n" "$LOG" 300 "$@" &
    spid=$!
    bg $spid
    i=0
    while [ ! -s "$T/sport$n" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "model server did not start"
        sleep 0.05
    done
    printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"m"}]}}}' \
        "$(cat "$T/sport$n")" > "$T/models$n.json"
    export PIC_MODELS_FILE="$T/models$n.json"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" --model fake/m "$@"; }
q() { "$SQLITE3" "$DB" "$1"; }
until_sql() { # SQL VALUE: wait up to 30 s for the query to print VALUE
    i=0
    until [ "$(q "$1")" = "$2" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for [$1] = $2: $(q "$1")"
        sleep 0.05
    done
}
nr=0
remote() { # start pic remote; its output in $RO
    nr=$((nr + 1))
    RO="$T/remote$nr.out"
    "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
    RP=$!
    bg $RP
    await "$RO" 'pic remote: connected'
}
script() { # DIR: run the phone of DIR on the script on stdin, in the background; output in DIR.run
    cat > "$1.script"
    rm -f "$1"/go* "$1"/at*
    "$PHONE" "$1" run < "$1.script" > "$1.run" 2>&1 &
    PR=$!
    bg $PR
}
done_ok() { # PID WHAT: the phone's script ran to its end
    gone "$1"
    [ "$rc" = 0 ] || fail "$2: phone exit $rc"
}
DEV1=$(uq "SELECT lower(hex(id)) FROM picu_remote_device WHERE paired_ms = (SELECT min(paired_ms) FROM picu_remote_device)")
DEVJ=$("$PIC" remote devices --json)
DEV1B=$("$SQLITE3" :memory: "SELECT substr(json_extract(value, '\$.origin'), 8) FROM json_each(json_extract('$DEVJ', '\$.devices'))
    WHERE json_extract(value, '\$.id') = '$DEV1'")
[ -n "$DEV1B" ] || fail "devices --json: no origin for $DEV1: $DEVJ"

# A conversation to look at: one request, finished.
# Connections: the first ask, the phone's prompt, the steer's hold, its reply and the follow-up, the
# abort's hold, the cut's hold and reply, then each crash's hold, reply and follow-up.
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" \
    "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse" \
    "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse"
pic ask 'first question' > /dev/null 2> "$T/ask.err" || fail "ask: $(cat "$T/ask.err")"
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
SESS="$DB/$SID"
remote
grep -qF '2 devices' "$RO" || fail "remote: $(cat "$RO")"
"$PIC" remote devices > "$T/devices2.out"
grep -qF 'pic remote is running' "$T/devices2.out" || fail "devices: running: $(cat "$T/devices2.out")"
"$PIC" remote > "$T/second.out" 2> "$T/second.err" && fail "a second pic remote ran"
grep -qF 'already running' "$T/second.err" || fail "second: $(cat "$T/second.err")"
printf 'PASS: pic remote: serves the paired phones; a second one refuses; devices says it runs\n'

# The list, ping and pong, following from the start, the journal's events with their seq and a
# mark; get_state and get_messages answered from the journal.
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$SESS"
send {"type":"ping"}
expect {"type":"pong"}
send {"type":"sync","session":"$SESS","seq":0}
expect "type":"agent_start"
expect "type":"agent_end"
expect {"type":"sync","session":"$SESS"
keyed
cmd k-state-0000000001 {"type":"command","session":"$SESS","key":"k-state-0000000001","payload":{"type":"get_state","id":"s1"}}
expect "command":"get_state"
cmd k-msgs-00000000001 {"type":"command","session":"$SESS","key":"k-msgs-00000000001","payload":{"type":"get_messages"}}
expect "first question"
send {"type":"bogus"}
expect "unknown_type"
EOS
done_ok $PR follow
grep -qF '"running":false' "$T/ph1.run" || fail "follow: no idle mark: $(cat "$T/ph1.run")"
grep -qF '"origin":"local","payload":{"type":"message_start","message":{"role":"user","content":[{"type":"text","text":"first question"' "$T/ph1.run" ||
    fail "follow: the terminal's message has no origin local: $(grep -F 'first question' "$T/ph1.run")"
grep -qF '"sessionId":"'"$SID"'"' "$T/ph1.run" || fail "follow: get_state: $(grep get_state "$T/ph1.run")"
printf 'PASS: a phone lists conversations, follows one from the journal (its sync'"'"'s key on each event and mark, the terminal'"'"'s message local), and asks for its state\n'

# Replayed and reordered records are dropped before decryption and change nothing.
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "type":"sessions"
replay
expectnot "type":"sessions" 1500
swapsend {"type":"sessions"}
expectnot "type":"sessions" 1500
count {"type":"pong"} 2
count "type":"sessions" 1
EOS
done_ok $PR replay
printf 'PASS: a replayed record and one that arrives after a later one are dropped\n'

# A key from another phone's static key on this phone's channel: no answer.
mkdir -p "$T/thief"
{ sed -n 1p "$T/ph4/pairing"; sed -n 2,4p "$T/ph4/pairing"; sed -n 5p "$T/ph1/pairing"; sed -n 6p "$T/ph4/pairing"; } > "$T/thief/pairing"
script "$T/thief" <<EOS
nosession 3000
EOS
done_ok $PR "wrong channel"
printf 'PASS: a known static key on another device'"'"'s channel gets no answer\n'

# A prompt while nothing runs is a keyed admission: one request under rc:DEVICE:KEY, in a process of
# its own, with the conversation's model; the same key again reports it and starts nothing more.
script "$T/ph1" <<EOS
send {"type":"sync","session":"$SESS","seq":-1}
expect "running":false
cmd k-prompt-000000001 {"type":"command","session":"$SESS","key":"k-prompt-000000001","payload":{"type":"prompt","message":"from the phone"}}
expect "command":"prompt","success":true
expect "status":"answered"
count "text":"from the phone" 2
send {"type":"command","session":"$SESS","key":"k-prompt-000000001","payload":{"type":"prompt","message":"from the phone"}}
expect "command":"prompt","success":true
sleep 1000
EOS
done_ok $PR prompt
[ "$(q "SELECT count(*) FROM pic_submission WHERE request_key LIKE 'rc:%:k-prompt-000000001'")" = 1 ] ||
    fail "prompt: submissions: $(q 'SELECT request_key, status FROM pic_submission')"
[ "$(q "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%'")" = answered ] ||
    fail "prompt: $(q "SELECT status, error FROM pic_submission WHERE request_key LIKE 'rc:%'")"
[ -e "$LOG/2.req" ] || fail "prompt: the conversation's model was not asked"
[ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body = 'from the phone'")" = 1 ] || fail "prompt: entries"
[ "$(q 'SELECT count(*) FROM pic_submission')" = 2 ] || fail "prompt: an extra request"
printf 'PASS: a prompt from the phone starts one request; its key again starts nothing\n'

# While a request runs: a steer goes through the inbox (ack once committed, the response once it is
# delivered, the sender the device); a prompt without streamingBehavior gets Pi's error, and with
# it becomes a follow-up.
rm -f "$WS/started" "$WS/release"
pic ask --session "$SID" 'hold on' > "$T/hold.out" 2> "$T/hold.err" &
HP=$!
bg $HP
i=0
until [ -e "$WS/started" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "hold: did not start"; sleep 0.05; done
script "$T/ph1" <<EOS
send {"type":"sync","session":"$SESS","seq":-1}
expect "running":true
cmd k-steer-0000000001 {"type":"command","session":"$SESS","key":"k-steer-0000000001","payload":{"type":"steer","message":"steer from the phone"}}
expect {"type":"ack","key":"k-steer-0000000001","payload":{"state":"pending"}}
cmd k-prompt-000000002 {"type":"command","session":"$SESS","key":"k-prompt-000000002","payload":{"type":"prompt","message":"too soon"}}
expect Agent is already processing
cmd k-prompt-000000003 {"type":"command","session":"$SESS","key":"k-prompt-000000003","payload":{"type":"prompt","message":"after that","streamingBehavior":"followUp"}}
expect {"type":"ack","key":"k-prompt-000000003"
mark go-release
expect "status":"answered"
sleep 500
count "key":"k-steer-0000000001","payload":{"type":"response","command":"steer","success":true 1
count "message":{"role":"user","content":[{"type":"text","text":"steer from the phone"}]},"origin":"remote:$DEV1B"} 2
EOS
i=0
until [ -e "$T/ph1/go-release" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "steer: the phone did not get its ack: $(cat "$T/ph1.run")"; sleep 0.05; done
touch "$WS/release"
done_ok $PR steer
gone $HP
[ "$rc" = 0 ] || fail "steer: the held request: exit $rc: $(cat "$T/hold.err")"
[ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-steer-0000000001' AND sender LIKE 'remote:%' AND state = 'delivered'")" = 1 ] ||
    fail "steer: inbox: $(q 'SELECT msg_key, sender, state FROM pic_inbox')"
[ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-prompt-000000003'")" = 1 ] || fail "follow-up: inbox"
[ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-prompt-000000002'")" = 0 ] || fail "too soon: a row"
[ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body = 'steer from the phone'")" = 1 ] || fail "steer: entries"
"$PIC" --db "$DB" check > /dev/null || fail "steer: integrity"
printf 'PASS: a steer from the phone reaches the running request once; a prompt then follows Pi\n'

hold() { # a request in SESS whose bash call waits for $WS/release
    rm -f "$WS/started" "$WS/release"
    pic ask --session "$SID" 'hold on' > "$T/hold.out" 2> "$T/hold.err" &
    HP=$!
    bg $HP
    i=0
    until [ -e "$WS/started" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "hold: did not start: $(cat "$T/hold.err")"; sleep 0.05; done
}

# An abort from the phone cancels the running request.
hold
script "$T/ph1" <<EOS
cmd k-abort-0000000001 {"type":"command","session":"$SESS","key":"k-abort-0000000001","payload":{"type":"abort"}}
expect "key":"k-abort-0000000001","payload":{"type":"response","command":"abort","success":true
EOS
done_ok $PR abort
gone $HP
[ "$rc" != 0 ] || fail "abort: the request was not stopped"
[ "$(q "SELECT status || ' ' || error FROM pic_submission ORDER BY id DESC LIMIT 1")" = "failed cancelled" ] ||
    fail "abort: $(q 'SELECT status, error FROM pic_submission ORDER BY id DESC LIMIT 1')"
printf 'PASS: an abort from the phone stops the running request\n'

# Two phones at once: each has its own session, its own followed conversation and its own answers.
script "$T/ph4" <<EOS
send {"type":"sync","session":"$SESS","seq":-1}
expect "running":false
send {"type":"ping"}
expect {"type":"pong"}
mark go-two
waitfor $T/ph1/go-one
EOS
P4=$PR
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "type":"sessions"
mark go-one
waitfor $T/ph4/go-two
EOS
done_ok $PR "two phones: one"
done_ok $P4 "two phones: four"
grep -qF '"type":"sync"' "$T/ph1.run" && fail "two phones: a mark reached the phone that follows nothing"
grep -qF '"type":"sync"' "$T/ph4.run" || fail "two phones: no mark: $(cat "$T/ph4.run")"
printf 'PASS: two phones at once, each with its own session and conversation\n'

# Mid-follow the relay ends every stream and pic remote is killed: started again, the phone's next
# session catches up from its cursor with no event twice and none missed.
hold
script "$T/ph1" <<EOS
send {"type":"sync","session":"$SESS","seq":-1}
expect "running":true
mark go-cut
waitfor at-cut
newsession
expect "type":"agent_end"
expect "running":false
EOS
i=0; until [ -e "$T/ph1/go-cut" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "cut: $(cat "$T/ph1.run")"; sleep 0.05; done
ctl cut
kill -9 "$RP"
gone "$RP"
touch "$WS/release"
gone $HP
remote
touch "$T/ph1/at-cut"
done_ok $PR "cut"
dups=$(grep -o '"seq":[0-9]*,"payload":{"type":"message_end"' "$T/ph1.run" | sort | uniq -d)
[ -z "$dups" ] || fail "cut: events twice: $dups"
grep -qF '"text":"Hello, \"world\"' "$T/ph1.run" || fail "cut: the reply was missed: $(cat "$T/ph1.run")"
printf 'PASS: a broken stream and a new session: caught up from the cursor, nothing twice or missed\n'

# pic remote killed at the inbox's commit, before and after it: the phone repeats the command until
# it is answered, and it is one row either way.
for at in 1 2; do
    hold
    kill "$RP"
    gone "$RP"
    PIC_CRASH_AT=inbox_accept:$at "$PIC" remote > "$T/crash$at.out" 2> "$T/crash$at.err" &
    RP=$!
    bg $RP
    await "$T/crash$at.out" 'pic remote: connected'
    script "$T/ph1" <<EOS
cmd k-crash-00000000$at {"type":"command","session":"$SESS","key":"k-crash-00000000$at","payload":{"type":"follow_up","message":"crash $at"}}
expect {"type":"ack","key":"k-crash-00000000$at"
EOS
    PC=$PR
    gone "$RP"
    [ "$rc" = 77 ] || fail "crash $at: exit $rc: $(cat "$T/crash$at.err")"
    [ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-crash-00000000$at'")" = $((at - 1)) ] ||
        fail "crash $at: rows before the retry"
    remote
    done_ok $PC "crash $at"
    [ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-crash-00000000$at'")" = 1 ] || fail "crash $at: rows"
    touch "$WS/release"
    gone $HP
    until_sql "SELECT state FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-crash-00000000$at'" delivered
done
"$PIC" --db "$DB" check > /dev/null || fail "crash: integrity"
printf 'PASS: pic remote killed before or after a command'"'"'s commit: the phone'"'"'s retry makes it one row\n'

# pic remote status: running, connected, the phones counted without the passphrase.
env -u PIC_TEST_PASSPHRASE "$PIC" remote status > "$T/status.out" 2>&1 || fail "status: $(cat "$T/status.out")"
grep -qF "pic remote is running (pid $RP): connected to $BASE; 2 phones paired" "$T/status.out" || fail "status: $(cat "$T/status.out")"
env -u PIC_TEST_PASSPHRASE "$PIC" remote status --json > "$T/status.json"
grep -qF '"running":true' "$T/status.json" && grep -qF '"state":"connected"' "$T/status.json" && grep -qF '"devices":2' "$T/status.json" ||
    fail "status --json: $(cat "$T/status.json")"
printf 'PASS: pic remote status says it runs, connected, with the phones paired\n'

# A new conversation from the phone: every workspace is listed, even one with no conversation, and
# a prompt to +W starts one there; its key again names the same conversation and starts nothing.
SAVE_DB=$DB SAVE_WS=$WS SAVE_LOG=$LOG SAVE_SPID=$spid SAVE_MODELS=$PIC_MODELS_FILE
spid=
serve "sse:$S/text.sse" "sse:$S/text.sse"
pic ask 'another workspace' > /dev/null 2> "$T/ask2.err" || fail "ask: $(cat "$T/ask2.err")"
W2=$DB
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "workspaces":[{"id":"$W2","workspace":"
seen "unavailable":[
cmd k-newconv-00000001 {"type":"command","session":"+$W2","key":"k-newconv-00000001","payload":{"type":"prompt","message":"a new one"}}
expect "key":"k-newconv-00000001","session":"$W2/
send {"type":"command","session":"+$W2","key":"k-newconv-00000001","payload":{"type":"prompt","message":"a new one"}}
expect "key":"k-newconv-00000001","session":"$W2/
send {"type":"command","session":"+$T/nowhere","key":"k-newconv-00000002","payload":{"type":"prompt","message":"x"}}
expect "no such workspace"
send {"type":"sessions","payload":{"workspace":"$W2"}}
expect {"type":"sessions","payload":{"workspace":"$W2","sessions":[{"session":"$W2/
send {"type":"sessions","payload":{"workspace":"$T/nowhere"}}
expect "no such workspace"
EOS
done_ok $PR "new conversation"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-newconv-00000001'" answered
[ "$(q "SELECT count(*) FROM pic_session")" = 2 ] || fail "new conversation: sessions: $(q 'SELECT id FROM pic_session')"
NEW=$(q "SELECT session_id FROM pic_submission WHERE request_key LIKE 'rc:%:k-newconv-00000001'")
named=$(grep -F '"key":"k-newconv-00000001"' "$T/ph1.run" | grep -o "\"session\":\"$W2/[a-z0-9]*\"" | sort -u)
[ "$named" = "\"session\":\"$W2/$NEW\"" ] || fail "new conversation: the responses name $named, not $NEW"
[ "$(q "SELECT count(*) FROM pic_submission WHERE request_key LIKE 'rc:%'")" = 1 ] || fail "new conversation: two requests"
printf 'PASS: a phone starts a new conversation in any workspace pic knows; its key again starts nothing; one workspace is listed on its own\n'
kill "$spid" 2> /dev/null
DB=$SAVE_DB WS=$SAVE_WS LOG=$SAVE_LOG spid=$SAVE_SPID PIC_MODELS_FILE=$SAVE_MODELS

# The reply as it streams: live values while it runs, rev rising, each the reply's text from its
# offset (the last 8 KiB of it), none after the committed reply, which carries the text once.
SAVE_DB=$DB SAVE_WS=$WS SAVE_LOG=$LOG SAVE_SPID=$spid SAVE_MODELS=$PIC_MODELS_FILE
spid=
{
    ev() { printf 'event: %s\ndata: %s\n\n' "$1" "$2"; }
    pause() { for p in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30; do ev ping '{"type": "ping"}'; done; }
    delta() { ev content_block_delta "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"$1\"}}"; }
    ev message_start '{"type":"message_start","message":{"id":"msg_l","type":"message","role":"assistant","model":"m","content":[],"stop_reason":null,"usage":{"input_tokens":5,"output_tokens":1}}}'
    ev content_block_start '{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}'
    for w in one two three four five six; do delta "$w "; pause; done
    delta "$(head -c 9000 /dev/zero | tr '\0' y)"
    pause
    delta ' é end.'
    ev content_block_stop '{"type":"content_block_stop","index":0}'
    ev message_delta '{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":12}}'
    ev message_stop '{"type":"message_stop"}'
} > "$T/live.sse"
serve "sse:$S/text.sse" "slow:$T/live.sse:25"
pic ask 'live first' > /dev/null 2> "$T/askl.err" || fail "ask: $(cat "$T/askl.err")"
SESSL="$DB/$(q "SELECT id FROM pic_session")"
kill "$RP" # started again, so the phone's requests reach this model server
gone "$RP"
remote
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$SESSL"
send {"type":"sync","session":"$SESSL","seq":-1}
expect "running":false
cmd k-live-00000000001 {"type":"command","session":"$SESSL","key":"k-live-00000000001","payload":{"type":"prompt","message":"stream it"}}
expect "type":"live"
expect "status":"answered"
sleep 600
EOS
done_ok $PR live
q "SELECT json_extract(body, '\$[0].text') FROM pic_entry WHERE kind IN ('answer', 'assistant') ORDER BY seq DESC LIMIT 1" | tr -d '\n' > "$T/final.txt"
case "$(cat "$T/final.txt")" in "one two three four five six yyy"*"y é end.") ;; *) fail "live: the reply: $(head -c 80 "$T/final.txt")" ;; esac
grep '^<- {"type":"live"' "$T/ph1.run" | sed 's/^<- //' > "$T/live.lines"
{ printf '['; paste -sd, "$T/live.lines"; printf ']'; } > "$T/live.json"
lq() { "$SQLITE3" :memory: "WITH l(k, v) AS (SELECT key, value FROM json_each(readfile('$T/live.json'))) $1"; }
[ "$(lq 'SELECT count(*) FROM l')" -ge 4 ] || fail "live: values: $(lq 'SELECT count(*) FROM l')"
[ "$(lq "SELECT count(*) FROM l WHERE json_extract(v, '\$.session') != '$SESSL'")" = 0 ] || fail "live: session"
[ "$(lq "SELECT count(*) FROM l a JOIN l b ON b.k = a.k + 1 WHERE json_extract(b.v, '\$.payload.rev') <= json_extract(a.v, '\$.payload.rev')")" = 0 ] ||
    fail "live: rev does not rise: $(lq "SELECT group_concat(json_extract(v, '\$.payload.rev')) FROM l")"
[ "$(lq "SELECT count(*) FROM l WHERE substr(CAST(readfile('$T/final.txt') AS TEXT), json_extract(v, '\$.payload.offset') + 1,
    length(json_extract(v, '\$.payload.text'))) != json_extract(v, '\$.payload.text')")" = 0 ] || fail "live: a value is not the reply's text"
[ "$(lq "SELECT max(length(CAST(json_extract(v, '\$.payload.text') AS BLOB))) <= 8192 AND max(json_extract(v, '\$.payload.offset')) > 0 FROM l")" = 1 ] ||
    fail "live: not the last 8 KiB: $(lq "SELECT group_concat(json_extract(v, '\$.payload.offset')) FROM l")"
[ "$(lq "SELECT count(DISTINCT json_extract(v, '\$.payload.text')) = count(*) FROM l")" = 1 ] || fail "live: a value sent twice"
reply=$(grep -n '"type":"message_end","seq":[0-9]*,"message":{"role":"assistant"' "$T/ph1.run" | tail -1)
[ "$(grep '"type":"message_end"' "$T/ph1.run" | grep -c 'y é end\.')" = 1 ] || fail "live: the committed reply came more than once"
case "$reply" in *'y é end.'*) ;; *) fail "live: the committed reply is not last: $reply" ;; esac
lastlive=$(grep -n '^<- {"type":"live"' "$T/ph1.run" | tail -1 | cut -d: -f1)
[ "$lastlive" -lt "${reply%%:*}" ] || fail "live: a value after the committed reply"
rseq=$(printf '%s' "$reply" | sed 's/.*"seq":\([0-9]*\),"key".*/\1/')
[ "$(lq "SELECT count(*) FROM l WHERE json_extract(v, '\$.seq') >= $rseq")" = 0 ] || fail "live: a value not behind the reply ($rseq)"
ls "$(dirname "$DB")/$(basename "$DB").pic-leases/"*.live > /dev/null 2>&1 && fail "live: the file outlived the reply"
printf 'PASS: the reply streams to the phone as live values: rev rising, the last 8 KiB, gone when it is committed\n'
kill "$spid" 2> /dev/null

# Notifications: a phone's subscription, sealed in its row, gets one line when a request ends (the
# conversation's title, the reply's first line), as its notify and remote.notify allow, and none
# while the page is showing; a push service that says the subscription is gone ends it.
spid=
serve "sse:$S/text.sse"
pic ask 'push first' > /dev/null 2> "$T/askp.err" || fail "ask: $(cat "$T/askp.err")"
SIDP=$(q "SELECT id FROM pic_session")
SESSP="$DB/$SIDP"
kill "$RP"
gone "$RP"
remote
mkdir "$T/plog"
"$SERVER" "$T/pport" "$T/plog" 300 status:201:- status:201:- status:201:- status:410:- status:201:- &
bg $!
i=0; until [ -s "$T/pport" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "push service did not start"; sleep 0.05; done
EP="http://127.0.0.1:$(cat "$T/pport")/push/ph1"
pushes() { ls "$T/plog" | grep -c '\.req$' || true; }
none_for() { # MS: no push arrives for that long
    sleep "$1"
    [ "$(pushes)" = "$2" ] || fail "push: $(pushes) pushes, not $2"
}
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$SESSP"
send {"type":"push","payload":{"subscription":{"endpoint":"https://10.0.0.1/x","keys":{"p256dh":"AAAA","auth":"AAAA"}}}}
expect "code":"bad_message"
send $("$PHONE" "$T/ph1" pushkeys "$EP")
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "push: subscribe"
"$PIC" remote devices --json | grep -qF '"name":"Phone One","pairedMs"' || fail "push: devices"
"$PIC" remote devices --json | grep -F '"notify":"all"' > /dev/null || fail "push: notify: $("$PIC" remote devices --json)"
uq "SELECT sealed FROM picu_remote_device" | grep -qF 'push/ph1' && fail "push: the subscription is not sealed"
# A request at the terminal ends: one push, its line decrypted as the phone's browser does.
pic ask --session "$SIDP" 'from the desk' > /dev/null 2> "$T/askp2.err" || fail "ask: $(cat "$T/askp2.err")"
await "$T/plog/1.req" 'Content-Length'
"$PHONE" "$T/ph1" pushread "$T/plog/1.req" > "$T/push1.json" || fail "push: does not open"
WSB=$(basename "$WS")
[ "$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/push1.json'), '\$.v') || '|' || json_extract(readfile('$T/push1.json'), '\$.title') || '|' ||
    json_extract(readfile('$T/push1.json'), '\$.body') || '|' || json_extract(readfile('$T/push1.json'), '\$.session')")" = "1|$WSB|Hello, \"world\"|$SESSP" ] ||
    fail "push: plaintext: $(cat "$T/push1.json")"
[ "$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/push1.json'), '\$.seq') = (SELECT 0)")" = 0 ] || fail "push: no seq"
grep -qF 'TTL: 3600' "$T/plog/1.req" && grep -qF 'Urgency: normal' "$T/plog/1.req" && grep -q '^Topic: [A-Za-z0-9_-]\{22\}' "$T/plog/1.req" &&
    grep -qF 'Authorization: vapid t=' "$T/plog/1.req" || fail "push: headers: $(head -12 "$T/plog/1.req")"
grep -aqF 'from the desk' "$T/plog/1.req" && fail "push: the prompt reached the push service"
printf 'PASS: a request that ends sends the phone one sealed line: the title, the reply'"'"'s first line, the conversation\n'
# notify remote: a request at the terminal sends nothing; one from the phone does.
script "$T/ph1" <<EOS
send $("$PHONE" "$T/ph1" pushkeys "$EP" remote)
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "push: remote"
pic ask --session "$SIDP" 'desk again' > /dev/null 2> "$T/askp3.err" || fail "ask: $(cat "$T/askp3.err")"
none_for 1.5 1
script "$T/ph1" <<EOS
cmd k-push-00000000001 {"type":"command","session":"$SESSP","key":"k-push-00000000001","payload":{"type":"prompt","message":"from the phone"}}
expect "command":"prompt","success":true
EOS
done_ok $PR "push: phone prompt"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-push-00000000001'" answered
await "$T/plog/2.req" 'Content-Length'
"$PHONE" "$T/ph1" pushread "$T/plog/2.req" | grep -qF '"body":"Hello, \"world\""' || fail "push: remote: $("$PHONE" "$T/ph1" pushread "$T/plog/2.req")"
printf 'PASS: a phone that asks only for its own requests is not sent the terminal'"'"'s\n'
# remote.notify off: nothing; the page showing: nothing; hidden again: a push.
"$PIC" settings remote.notify off > /dev/null
script "$T/ph1" <<EOS
cmd k-push-00000000002 {"type":"command","session":"$SESSP","key":"k-push-00000000002","payload":{"type":"prompt","message":"muted"}}
expect "command":"prompt","success":true
EOS
done_ok $PR "push: off"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-push-00000000002'" answered
none_for 1.5 2
"$PIC" settings remote.notify all > /dev/null
script "$T/ph1" <<EOS
send {"type":"presence","payload":{"visible":true}}
cmd k-push-00000000003 {"type":"command","session":"$SESSP","key":"k-push-00000000003","payload":{"type":"prompt","message":"looking"}}
expect "command":"prompt","success":true
waitfor $T/go-hidden
send {"type":"presence","payload":{"visible":false}}
cmd k-push-00000000004 {"type":"command","session":"$SESSP","key":"k-push-00000000004","payload":{"type":"prompt","message":"away"}}
expect "command":"prompt","success":true
EOS
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-push-00000000003'" answered
none_for 1.5 2
touch "$T/go-hidden"
done_ok $PR "push: presence"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-push-00000000004'" answered
await "$T/plog/3.req" 'Content-Length'
printf 'PASS: no notification while remote.notify is off or the page is showing; one once it is hidden\n'
# The push service answers 410: the subscription is gone from the row, and nothing more is sent.
script "$T/ph1" <<EOS
cmd k-push-00000000005 {"type":"command","session":"$SESSP","key":"k-push-00000000005","payload":{"type":"prompt","message":"gone"}}
expect "command":"prompt","success":true
EOS
done_ok $PR "push: gone"
await "$T/plog/4.req" 'Content-Length'
await "$RO" 'notifications to Phone One ended'
"$PIC" remote devices --json | grep -qF '"notify":"' && fail "push: gone: still subscribed: $("$PIC" remote devices --json)"
script "$T/ph1" <<EOS
cmd k-push-00000000006 {"type":"command","session":"$SESSP","key":"k-push-00000000006","payload":{"type":"prompt","message":"after"}}
expect "command":"prompt","success":true
EOS
done_ok $PR "push: after gone"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-push-00000000006'" answered
none_for 1.5 4
printf 'PASS: a subscription the push service says is gone ends; nothing more is sent to it\n'
kill "$spid" 2> /dev/null
DB=$SAVE_DB WS=$SAVE_WS LOG=$SAVE_LOG spid=$SAVE_SPID PIC_MODELS_FILE=$SAVE_MODELS

# Unpaired from the phone: its row goes, and its channel at the relay.
script "$T/ph4" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
send {"type":"unpair"}
sleep 3000
EOS
gone $PR
[ "$rc" = 4 ] || fail "unpair from the phone: exit $rc: $(cat "$T/ph4.run")"
[ "$(uq "SELECT count(*) FROM picu_remote_device")" = 1 ] || fail "unpair from the phone: rows"
state | grep -qF 'channels 1 ' || fail "unpair from the phone: relay channels: $(state)"
printf 'PASS: a phone that forgets this computer is unpaired, its channel deleted\n'

# Unpaired at the terminal, no passphrase asked: the running pic remote tells the phone, ends its
# session and deletes its channel; the phone cannot come back.
script "$T/ph1" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
mark go-unpair
expect {"type":"unpaired"}
sleep 3000
EOS
i=0; until [ -e "$T/ph1/go-unpair" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "unpair: $(cat "$T/ph1.run")"; sleep 0.05; done
env -u PIC_TEST_PASSPHRASE "$PIC" remote unpair "$(printf %.8s "$DEV1")" < /dev/null > "$T/unpair.out" 2> "$T/unpair.err" ||
    fail "unpair: $(cat "$T/unpair.err")"
gone $PR
[ "$rc" = 4 ] || fail "unpair: phone exit $rc: $(cat "$T/ph1.run")"
await "$RO" 'Phone One was unpaired'
[ "$(uq "SELECT count(*) FROM picu_remote_device")" = 0 ] || fail "unpair: rows"
state | grep -qF 'channels 0 ' || fail "unpair: relay channels: $(state)"
script "$T/ph1" <<EOS
nosession 3000
EOS
gone $PR
[ "$rc" = 4 ] || fail "unpair: the phone came back: exit $rc: $(cat "$T/ph1.run")"
printf 'PASS: unpaired at the terminal: the phone is told, its session and channel end, it cannot return\n'

# SIGTERM: pic remote says it stopped and exits 0, and nothing is left to clean up.
kill "$RP"
gone "$RP"
[ "$rc" = 0 ] || fail "stop: exit $rc"
grep -qF 'pic remote: stopped' "$RO" || fail "stop: $(cat "$RO")"
"$PIC" remote reset > "$T/reset.out" 2> "$T/reset.err" || fail "reset: $(cat "$T/reset.err")"
[ "$(uq "SELECT count(*) FROM picu_remote_key")" = 0 ] || fail "reset: keys"
state | grep -qF 'mailboxes 0 ' || fail "reset: relay: $(state)"
printf 'PASS: pic remote stops on SIGTERM; reset deletes the keys and the mailbox\n'

# ---- pairing against a reconnect, a second phone and odd names; a session that ignores bye ----
codes_match() { # PHONE_OUT WHAT: the phone's code is the one pic showed
    await "$1" 'code '
    want=$(sed -n 's/^code //p' "$1")
    grep -qF "\"code\":\"$want\"" "$PO" || fail "$2: the codes differ: $(cat "$PO") / $want"
}
refuse() { # PHONE_OUT WHAT: answer no; the phone hears it under the keys it made
    echo n >&3
    gone $PH
    [ "$rc" = 3 ] || fail "$2: phone exit $rc: $(cat "$1")"
    gone $PP
    exec 3>&-
}
# The phone sends its first message again after it has the second (its stream reconnected): pic
# answers with the second it made, and does not make new keys the phone never sees.
offer
phone_pair "$T/pr1" "Phone Resend" resend
await "$PO" '"type":"code"'
codes_match "$T/pr1.out" resend
refuse "$T/pr1.out" resend
printf 'PASS: a first message sent again gets the same answer, and the pairing goes on\n'

# A second phone that scanned the same code posts its first message mid-pairing: it is ignored.
offer
phone_pair "$T/pr2" "Phone First" rival
await "$PO" '"type":"code"'
codes_match "$T/pr2.out" rival
grep -qF '"name":"Phone First"' "$PO" || fail "rival: name: $(cat "$PO")"
grep -qF 'Rival' "$PO" && fail "rival: the second phone was heard: $(cat "$PO")"
refuse "$T/pr2.out" rival
printf 'PASS: a second phone'"'"'s first message cannot take over a pairing under way\n'

# A second first message whose channel is 12 bytes leaves the paired phone's channel as it was.
offer
phone_pair "$T/pr3" "Phone Chan" rival-badchan
await "$PO" '"type":"code"'
echo y >&3
gone $PH
[ "$rc" = 0 ] || fail "short channel: phone exit $rc: $(cat "$T/pr3.out")"
gone $PP
exec 3>&-
chan=$(sed -n 's/^channel //p' "$T/pr3.out")
[ "$(curl -s -o /dev/null -w '%{http_code}' -X POST "$BASE/_test/channel?$chan")" = 204 ] ||
    fail "short channel: the phone's channel $chan is not at the relay"
printf 'PASS: the device channel is the paired phone'"'"'s; a short one in a second message changes nothing\n'

# A name with C1 and bidi controls is shown with them replaced, and quoted at the terminal.
offer
phone_pair "$T/pr4" 'Odd‮Name\u0085⁦x'
await "$PO" '"type":"code"'
grep -qF '"name":"Odd?Name??x"' "$PO" || fail "name: $(cat "$PO")"
refuse "$T/pr4.out" name
if [ -n "${DRIVE:-}" ]; then
    # At the terminal: a y typed before the question is not its answer, and the name is quoted.
    mkfifo "$T/pr5.in"
    "$DRIVE" "$T/pr5.tx" 200 60 "$PIC" remote pair < "$T/pr5.in" > "$T/pr5.drv" 2>&1 &
    DP=$!
    bg $DP
    exec 4> "$T/pr5.in"
    printf '%s\n' 'expect notifications only reach' 'send y\r' >&4
    await "$T/pr5.tx" 'notifications only reach'
    URL=$(grep -ao "$BASE/#p1\.[A-Za-z0-9_-]*" "$T/pr5.tx" | awk '{ if (length($0) > length(u)) u = $0 } END { print u }')
    phone_pair "$T/pr5" 'Odd‏Name'
    printf '%s\n' 'expect [y/N]' 'wait 1000' 'send n\r' 'wait 500' >&4
    exec 4>&-
    gone $PH
    [ "$rc" = 3 ] || fail "typeahead: phone exit $rc: $(cat "$T/pr5.out")"
    gone $DP
    grep -aqF 'Pair "Odd?Name"? It should show' "$T/pr5.tx" || fail "name: prompt: $(cat "$T/pr5.tx")"
fi
printf 'PASS: a name'"'"'s control and bidi characters are replaced, and the prompt quotes it\n'

# A phone that ignores bye (asked to start again) loses its session after the grace.
export PIC_TEST_RC_REKEY_MS=1500
remote
unset PIC_TEST_RC_REKEY_MS
export FAKE_PHONE_IGNORE_BYE=1
script "$T/pr3" <<EOS
expect "type":"pong"
expect "type":"bye"
sleep 3500
send {"type":"ping"}
sleep 1500
EOS
unset FAKE_PHONE_IGNORE_BYE
done_ok $PR "bye ignored"
sed -n '/"type":"bye"/,$p' "$T/pr3.run" | grep -qx reset || fail "bye ignored: the session lived on: $(cat "$T/pr3.run")"
kill "$RP"
gone "$RP"
"$PIC" remote reset > "$T/reset2.out" 2> "$T/reset2.err" || fail "reset: $(cat "$T/reset2.err")"
printf 'PASS: a phone that ignores bye loses its session: its next record is answered with a reset\n'

# /rc in the terminal interface: the list, then p pairs a phone (asking for the store's passphrase
# first, the pairing running as pic remote pair --pipe with the key handed down), Esc cancels a
# pairing, a number then y unpairs, R then y resets. Driven on a pseudo-terminal.
if [ -n "${DRIVE:-}" ]; then
    TX="$T/tui.tx"
    mkfifo "$T/tui.in"
    env -u PIC_TEST_PASSPHRASE PIC_TEST_RC="-|testmac.local|1" "$DRIVE" "$TX" 220 70 \
        "$PIC" --db "$DB" --workspace "$WS" --model fake/m < "$T/tui.in" > "$T/tui.out" 2>&1 &
    TP=$!
    bg $TP
    exec 4> "$T/tui.in"
    say() { printf '%s\n' "$@" >&4; }
    plain() { perl -pe 's/\e\][^\a]*\a//g; s/\e\[[0-9;?]*[HJK]/\n/g; s/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$TX"; }
    tx() { # PATTERN: wait for the fixed string in the screen's text (30 s)
        i=0
        until plain | grep -qF -- "$1"; do
            i=$((i + 1))
            [ "$i" -lt 300 ] || fail "tui: never saw $1: $(plain | grep -v '^\s*$' | tail -15)"
            kill -0 "$TP" 2> /dev/null || fail "tui: the driver ended: $(cat "$T"/tui*.out): $(plain | grep -v '^\s*$' | tail -15)"
            sleep 0.1
        done
    }
    say 'expect fake/m' 'send /rc\r' 'expect unlock the credential store to list them'
    tx 'unlock the credential store to list them'
    # The store is locked in this process: p asks for the passphrase (and, once, whether to stop
    # asking: no), then pairs.
    say 'send p' 'expect /rc goes on once it opens' 'send remote-test-pass\r' 'expect Stop asking for this passphrase?' \
        'send n' 'expect Scan this with your phone' \
        'expect pair from the Home Screen' # the line after the address: the address is all there
    tx 'pair from the Home Screen'
    URL=$(plain | grep -o "$BASE/#p1\.[A-Za-z0-9_-]*" | awk '{ if (length($0) > length(u)) u = $0 } END { print u }')
    [ -n "$URL" ] || fail "tui pair: no address on the page"
    phone_pair "$T/pht" "Phone TUI"
    await "$T/pht.out" 'code '
    code=$(sed -n 's/^code //p' "$T/pht.out")
    say "expect Pair \"Phone TUI\"? It should show $code. [y/N]" 'send y' 'expect Paired Phone TUI. Run pic remote'
    tx 'Paired Phone TUI. Run pic remote'
    gone $PH
    [ "$rc" = 0 ] || fail "tui pair: phone exit $rc: $(cat "$T/pht.out")"
    grep -qx paired "$T/pht.out" || fail "tui pair: phone: $(cat "$T/pht.out")"
    [ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "tui pair: rows"
    say 'expect Phones paired through the relay' 'expect 1-1 then y unpairs one'
    tx 'Phone TUI, never seen'
    printf 'PASS: /rc pairs a phone: the passphrase, the QR code and address, the code, a yes, the phone listed\n'
    # p, then Esc before any phone answers: the offer ends and nothing is paired.
    say 'send p' 'expect Scan this with your phone' 'send \e' 'expect Pairing cancelled.' 'expect p: pair a phone'
    tx 'Pairing cancelled.'
    [ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "tui cancel: rows"
    printf 'PASS: Esc cancels a pairing in /rc\n'
    # 1 then n keeps it; 1 then y unpairs it.
    say 'send 1' 'expect Unpair Phone TUI? [y/N]' 'send n' 'wait 300' 'send 1' 'expect Unpair Phone TUI? [y/N]' 'send y' \
        'expect Unpaired Phone TUI.'
    tx 'Unpaired Phone TUI.'
    [ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 0 ] || fail "tui unpair: rows"
    printf 'PASS: a number then y unpairs a phone in /rc; n keeps it\n'
    say 'send R' 'expect Reset remote control' 'send y' 'expect Reset: every phone unpaired'
    tx 'Reset: every phone unpaired'
    [ "$(uq 'SELECT count(*) FROM picu_remote_key')" = 0 ] || fail "tui reset: keys"
    state | grep -qF 'mailboxes 0 ' || fail "tui reset: relay: $(state)"
    say 'send \e' 'wait 300' 'send \x04\x04'
    exec 4>&-
    gone $TP
    [ "$rc" = 0 ] || fail "tui: driver exit $rc: $(cat "$T/tui.out")"
    printf 'PASS: R then y resets remote control from /rc, the mailbox deleted\n'
fi

# Remote control from the Mac and the phone at once: /rc turns it on (pic remote detached, the key
# handed down, it outlives the interface), a phone's prompt shows in the interface marked with the
# phone's name, a message typed meanwhile steers it through the inbox, a pic remote that dies of a
# signal is started again, and it keeps running after the interface exits.
if [ -n "${DRIVE:-}" ]; then
    offer
    phone_pair "$T/phv" "Phone V2"
    await "$PO" '"type":"code"'
    echo y >&3
    gone $PH
    [ "$rc" = 0 ] || fail "v2 pair: phone exit $rc: $(cat "$T/phv.out")"
    gone $PP
    exec 3>&-
    serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse"
    pic ask 'mac question' > /dev/null 2> "$T/ask3.err" || fail "ask: $(cat "$T/ask3.err")"
    SID2=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
    SESS2="$DB/$SID2"
    TX="$T/tui2.tx"
    mkfifo "$T/tui2.in"
    env -u PIC_TEST_PASSPHRASE PIC_TEST_RC="-|testmac.local|1" "$DRIVE" "$TX" 220 70 \
        "$PIC" --db "$DB" --workspace "$WS" --model fake/m -c < "$T/tui2.in" > "$T/tui2.out" 2>&1 &
    TP=$!
    bg $TP
    exec 4> "$T/tui2.in"
    say 'expect fake/m' 'send /rc\r' 'expect /rc goes on once it opens' 'send remote-test-pass\r' \
        'expect Remote control is on: connected'
    tx 'Remote control is on: connected'
    "$PIC" remote status --json > "$T/v2status.json"
    RCP=$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/v2status.json'), '\$.pid')")
    TUIP=$(ps -axo pid=,ppid= | awk -v p="$TP" '$2 == p { print $1 }')
    [ -n "$RCP" ] && [ "$(ps -o ppid= -p "$RCP" | tr -d ' ')" = "$TUIP" ] || fail "v2: pic remote $RCP is not the interface's ($TUIP)"
    bg "$RCP"
    [ "$(ps -o pgid= -p "$RCP" | tr -d ' ')" = "$RCP" ] || fail "v2: pic remote is not in a session of its own"
    printf 'PASS: /rc turns remote control on: pic remote runs detached, connected, with the key handed down\n'
    say 'send \e' 'wait 300'
    script "$T/phv" <<EOF2
cmd k-v2-prompt-000001 {"type":"command","session":"$SESS2","key":"k-v2-prompt-000001","payload":{"type":"prompt","message":"hello from the phone"}}
expect "command":"prompt","success":true
EOF2
    done_ok $PR "v2 prompt"
    say 'expect from Phone V2: hello from the phone' 'expect world'
    tx 'from Phone V2: hello from the phone'
    until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-v2-prompt-000001'" answered
    tx 'world'
    printf 'PASS: a prompt from the phone shows in the interface, marked with the phone'"'"'s name, and its reply\n'
    # The phone starts a request that waits; a line typed in the interface meanwhile steers it.
    rm -f "$WS/started" "$WS/release"
    script "$T/phv" <<EOF2
cmd k-v2-prompt-000002 {"type":"command","session":"$SESS2","key":"k-v2-prompt-000002","payload":{"type":"prompt","message":"hold from the phone"}}
expect "command":"prompt","success":true
EOF2
    done_ok $PR "v2 hold"
    i=0; until [ -e "$WS/started" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "v2 hold: did not start"; sleep 0.05; done
    say 'expect A request from elsewhere is running here' 'send steer from the mac\r'
    until_sql "SELECT count(*) FROM pic_inbox WHERE json_extract(command, '\$.message') = 'steer from the mac'" 1
    touch "$WS/release"
    until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-v2-prompt-000002'" answered
    [ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body = 'steer from the mac'")" = 1 ] || fail "v2 steer: entries"
    [ "$(q "SELECT count(*) FROM pic_submission")" = 3 ] || fail "v2 steer: the line started a request of its own"
    printf 'PASS: a line typed in the interface while the phone'"'"'s request runs steers it through the inbox\n'
    # Killed: the interface starts it again. (The driver reads the screen only while it waits.)
    say 'expect pic remote ended (signal 9); starting it again'
    kill -9 "$RCP"
    i=0
    until "$PIC" remote status --json > "$T/v2status.json" && grep -qF '"state":"connected"' "$T/v2status.json" &&
        ! grep -qF "\"pid\":$RCP," "$T/v2status.json"; do
        i=$((i + 1))
        [ "$i" -lt 300 ] || fail "v2 restart: $(cat "$T/v2status.json"): $(plain | grep -v "^\s*$" | tail -12)"
        sleep 0.1
    done
    RCP2=$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/v2status.json'), '\$.pid')")
    bg "$RCP2"
    tx 'pic remote ended (signal 9); starting it again'
    printf 'PASS: a pic remote killed while the interface runs is started again\n'
    say 'send \x04\x04'
    exec 4>&-
    gone $TP
    [ "$rc" = 0 ] || fail "v2: driver exit $rc: $(cat "$T/tui2.out")"
    kill -0 "$RCP2" 2> /dev/null || fail "v2: pic remote ended with the interface"
    "$PIC" remote stop > "$T/v2stop.out" 2>&1 || fail "v2 stop: $(cat "$T/v2stop.out")"
    "$PIC" remote status > "$T/v2status.out"
    grep -qF 'pic remote is not running' "$T/v2status.out" || fail "v2 stop: $(cat "$T/v2status.out")"
    printf 'PASS: pic remote outlives the interface; pic remote stop ends it\n'
fi