Skip to content
pi-c Artifact [89f3ce863e]
Login

Artifact [89f3ce863e]

Artifact 89f3ce863e611c1eabd7fc8b5da4607bdf39acc47ac67f5e92526be61cad4892:


#!/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, images from the phone, and notifications to a test push
# service. Pairing from a paired phone: its approval, a rival, a wrong code, another phone's
# approval, the setting, and unpairing one device or every device from a phone, and every device at
# the terminal.
# 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
export PIC_NO_NATIVE_CLIPBOARD=1 # /rc copies its link: never the real clipboard
# Every wait below is for an event, a record or a state, with a deadline only a failure waits out:
# 120 s at 50 ms a try, here and in the phone and the pty driver (PIC_TEST_SLOW), since the suite
# runs beside others on a loaded machine.
TRIES=2400
export PIC_TEST_SLOW=1
pids=
cleanup() {
    exec 2> /dev/null # the shell's notes on the jobs it kills
    "$PIC" remote stop > /dev/null 2>&1 || : # one /rc started, detached, if a case failed before stopping it
    for p in $pids; do kill -9 "$p" 2>/dev/null || true; done
    rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
# and a pic remote this run starts ends by itself (dev builds) should the run be killed before cleanup
export PIC_TEST_RC_DEADLINE_S=1800
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, 120 s by default)
    i=0
    until grep -qF -- "$2" "$1" 2>/dev/null; do
        i=$((i + 1))
        [ "$i" -lt "${3:-$TRIES}" ] || fail "timed out waiting for $2 in $1"
        sleep 0.05
    done
}
gone() { # PID: wait for it to exit; its status in rc
    rc=0
    wait "$1" || rc=$?
}
uq() { "$SQLITE3" -cmd ".timeout 10000" "$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
# The conversations here are a person's (PIC_ORIGIN), and their workspaces under $T are listed: the
# temporary directories pic remote leaves out are, for this run, $T/tmp alone (a dev build's seam).
export PIC_ORIGIN=person PIC_TEST_RC_TEMP="$T/tmp"
# 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" 3600 test-invite > "$T/relay.out" 2> "$T/relay.err" &
bg $!
i=0
while [ ! -s "$T/relay.port" ]; do
    i=$((i + 1))
    [ "$i" -lt $TRIES ] || 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" 3600 "$@" &
    spid=$!
    bg $spid
    i=0
    while [ ! -s "$T/sport$n" ]; do
        i=$((i + 1))
        [ "$i" -lt $TRIES ] || 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" -cmd ".timeout 10000" "$DB" "$1"; }
until_sql() { # SQL VALUE: wait up to 120 s for the query to print VALUE
    i=0
    until [ "$(q "$1")" = "$2" ]; do
        i=$((i + 1))
        [ "$i" -lt $TRIES ] || 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"
export PIC_TEST_RC_SEEN_MS=200 # a connected phone's "last seen" is written again after 0.2 s, not 30
remote
unset PIC_TEST_RC_SEEN_MS
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")"
grep -qF '"session":"'"$SESS"'",' "$T/ph1.run" && grep -F '"session":"'"$SESS"'",' "$T/ph1.run" |
    grep -qF '"title":"first question","preview":"Hello, \"world\"","state":"idle"' ||
    fail "list: title, preview, state: $(grep -F '"type":"sessions"' "$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'

# A phone connected all along is seen now, not when its session began.
if [ "$FAULTS" = 1 ]; then
    script "$T/ph1" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
mark go-seen
waitfor at-seen
sleep 300
send {"type":"ping"}
expect {"type":"pong"}
EOS
    i=0; until [ -e "$T/ph1/go-seen" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "seen: $(cat "$T/ph1.run")"; sleep 0.05; done
    uq "UPDATE picu_remote_device SET seen_ms = 1000"
    touch "$T/ph1/at-seen" # the next ping is 0.3 s on, past PIC_TEST_RC_SEEN_MS
    done_ok $PR seen
    [ "$(uq "SELECT count(*) FROM picu_remote_device WHERE seen_ms > 1000")" -ge 1 ] || fail "seen: a connected phone's last seen did not move"
    printf 'PASS: a connected phone'"'"'s last seen follows its messages\n'
fi

# Replayed and reordered records are dropped before decryption and change nothing.
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "type":"sessions"
replay
send {"type":"ping"}
expect {"type":"pong"}
swapsend {"type":"sessions"}
expect {"type":"pong"}
send {"type":"ping"}
expect {"type":"pong"}
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'

# Records a confirmed session cannot open, three in a row, reset it, so the phone makes a new one
# instead of waiting; a stream that keeps its keepalive while records stop is opened again once a
# phone on screen has been quiet that long (PIC_TEST_RC_QUIET_MS); and each line of the log says
# when, and why it reconnected, dropped or reset. (The phone takes a reset 5 s after its handshake.)
if [ "$FAULTS" = 1 ]; then
    kill "$RP"
    gone "$RP"
    nr=$((nr + 1))
    RO="$T/remote$nr.out"
    PIC_TEST_RC_QUIET_MS=1500 PIC_TEST_RC_STALL_MS=1500 PIC_TEST_RC_STALL_FILE="$T/stall" PIC_TEST_RC_PAGE=2 \
        PIC_TEST_RC_SLOW_PHASE="Phone One's command get_wakes:4000" \
        "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
    RP=$!
    bg $RP
    await "$RO" 'pic remote: connected'
    script "$T/ph1" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
sleep 5500
garble 3
expectreset
send {"type":"ping"}
expect {"type":"pong"}
EOS
    done_ok $PR garble
    [ "$(grep -c '^session$' "$T/ph1.run")" -ge 2 ] || fail "garble: no new session: $(cat "$T/ph1.run")"
    cat "$RO" "$T/remote$nr.err" > "$T/garble.log"
    grep -qF 'did not open (2 in a row)' "$T/garble.log" || fail "garble: no drop line: $(cat "$T/garble.log")"
    grep -qF '3 records in a row did not open' "$T/garble.log" || fail "garble: no reset line: $(cat "$T/garble.log")"
    printf 'PASS: records a session cannot open, three in a row, reset it, and the phone starts a new one\n'

    script "$T/ph1" <<EOS
send {"type":"presence","payload":{"visible":true}}
send {"type":"ping"}
expect {"type":"pong"}
mark go-deaf
waitfor at-deaf
send {"type":"ping"}
expect {"type":"pong"}
EOS
    i=0; until [ -e "$T/ph1/go-deaf" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "deaf: $(cat "$T/ph1.run")"; sleep 0.05; done
    ctl deaf
    touch "$T/ph1/at-deaf"
    done_ok $PR deaf
    cat "$RO" "$T/remote$nr.err" > "$T/deaf.log"
    grep -qF 'reconnecting' "$T/deaf.log" || fail "deaf: no reconnect line: $(cat "$T/deaf.log")"
    grep -qF 'the stream ended (asked to reconnect)' "$T/deaf.log" || fail "deaf: no reason: $(cat "$T/deaf.log")"
    stamp='^[0-9]\{4\}-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]Z pic remote: '
    [ "$(grep -vc "$stamp" "$T/deaf.log")" = 0 ] || fail "log: a line without its time: $(grep -v "$stamp" "$T/deaf.log")"
    printf 'PASS: a stream that brings keepalives but no records is opened again; each log line has its time\n'

    # Another pic holding the journal's write lock (a loop round, a running request) does not stop
    # pic remote: a command that must write is answered busy at once, and everything else goes on.
    rm -f "$T/hold.in"
    mkfifo "$T/hold.in"
    "$SQLITE3" "$DB" < "$T/hold.in" > "$T/hold.out" 2>&1 &
    HOLD=$!
    bg $HOLD
    exec 4> "$T/hold.in"
    printf 'BEGIN IMMEDIATE; UPDATE pic_session SET updated_ms = updated_ms;\nSELECT 1;\n' >&4
    await "$T/hold.out" 1
    t0=$(date +%s)
    script "$T/ph1" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
send {"type":"command","session":"$SESS","key":"k-held-0000000001","payload":{"type":"follow_up","message":"held"}}
expect "code":"busy"
send {"type":"sync","session":"$SESS","seq":-1}
expect {"type":"sync","session":"$SESS"
send {"type":"ping"}
expect {"type":"pong"}
EOS
    done_ok $PR held
    t1=$(date +%s)
    printf 'COMMIT;\n' >&4
    exec 4>&-
    gone $HOLD
    grep -qF 'busy on the computer' "$T/ph1.run" || fail "held: $(cat "$T/ph1.run")"
    [ $((t1 - t0)) -lt 15 ] || fail "held: the phone waited $((t1 - t0)) s"
    # held for the whole script, a loop that waited on the lock would be stuck seconds on end; a
    # second's hiccup on a loaded machine (the stall seam is 1.5 s here) is not that
    if grep -Eq '(moving again after|stuck for) ([5-9]|[1-9][0-9]+) s' "$RO"; then fail "held: the loop stalled: $(grep -F stall "$RO")"; fi
    printf 'PASS: a journal another pic is writing: a command is answered busy and pic remote goes on\n'

    # A long history goes a page at a time (PIC_TEST_RC_PAGE=2 entries), each page with its mark,
    # and arrives whole: every entry once, in order.
    script "$T/ph1" <<EOS
send {"type":"sync","session":"$SESS","seq":0}
expect "type":"agent_end"
sleep 2000
EOS
    done_ok $PR pages
    last=$(q "SELECT max(e.seq) FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = '$SID'")
    marks=$(grep -c '^<- {"type":"sync","session":"'"$SESS"'"' "$T/ph1.run")
    [ "$marks" -ge 2 ] || fail "pages: $marks marks: $(cat "$T/ph1.run")"
    grep -qF '"type":"sync","session":"'"$SESS"'","seq":'"$last"',' "$T/ph1.run" || fail "pages: no mark at $last: $(grep '"type":"sync"' "$T/ph1.run")"
    seqs=$(grep -o '"payload":{"type":"message_end","seq":[0-9]*' "$T/ph1.run" | grep -o '[0-9]*$')
    [ "$(printf '%s\n' "$seqs" | sort -n | uniq -d)" = "" ] || fail "pages: an entry twice"
    [ "$(printf '%s\n' "$seqs" | sort -n)" = "$seqs" ] || fail "pages: out of order"
    [ "$(printf '%s\n' "$seqs" | wc -l | tr -d ' ')" = "$(q "SELECT count(*) FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = '$SID' AND e.kind IN ('user', 'assistant', 'answer')")" ] ||
        fail "pages: messages: $seqs"
    printf 'PASS: a long history goes in pages, each with its mark, every message once and in order\n'

    # A loop that does not come back is logged by the watchdog, and pic remote status says stalled;
    # once it moves again, both say so.
    touch "$T/stall"
    await "$RO" 'stalled: the loop has been stuck'
    i=0
    until PIC_TEST_RC_STALL_MS=1500 "$PIC" remote status > "$T/stalled.out" 2>&1 && grep -qF 'stalled for' "$T/stalled.out"; do
        i=$((i + 1))
        [ "$i" -lt "$TRIES" ] || fail "stall: status: $(cat "$T/stalled.out")"
        sleep 0.05
    done
    rm -f "$T/stall"
    await "$RO" 'the loop is moving again'
    i=0
    until PIC_TEST_RC_STALL_MS=1500 "$PIC" remote status > "$T/stalled.out" 2>&1 && grep -qF ': connected' "$T/stalled.out"; do
        i=$((i + 1))
        [ "$i" -lt "$TRIES" ] || fail "stall: status after: $(cat "$T/stalled.out")"
        sleep 0.05
    done
    printf 'PASS: a stuck loop is logged with what it was doing, and status says stalled until it moves\n'

    # A stall inside a named phase (PIC_TEST_RC_SLOW_PHASE sleeps in it) is logged with that phase,
    # the phone and the command, and how long ago the phase began.
    script "$T/ph1" <<EOS
cmd k-wakes-000000001 {"type":"command","session":"$SESS","key":"k-wakes-000000001","payload":{"type":"get_wakes"}}
expect "command":"get_wakes"
EOS
    done_ok $PR "slow phase"
    grep -q "stalled: the loop has been stuck for [0-9]* s; its last phase, named [0-9]* s ago: answering Phone One's command get_wakes" "$RO" ||
        fail "slow phase: $(grep stalled "$RO")"
    printf 'PASS: a stall is logged with the phase it is in, the phone and the command, and since when\n'
    kill "$RP"
    gone "$RP"
    remote
fi

# 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
seen :k-prompt-000000001","status":"answered"
waitcount "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 $TRIES ] || 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"
waitcount "key":"k-steer-0000000001","payload":{"type":"response","command":"steer","success":true 1
waitcount "message":{"role":"user","content":[{"type":"text","text":"steer from the phone"}]},"origin":"remote:$DEV1B"} 2
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 $TRIES ] || 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 $TRIES ] || 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 $TRIES ] || 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 -qE "pic remote is running \(pid $RP\): connected to $BASE, stream open since [0-9]{2}:[0-9]{2}:[0-9]{2}, 0 recycles; 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 newer pic installed over a running pic remote: status says it is older, pic remote restart
# starts the new one in its place (the same pid), and on its own it does so once the file has kept
# still and nothing is under way; a phone is served again after.
kill "$RP"
gone "$RP"
mkdir -p "$T/bin"
cp "$PIC" "$T/bin/pic"
install_new() { cp "$PIC" "$T/bin/pic.new" && mv -f "$T/bin/pic.new" "$T/bin/pic"; } # a new file, as an install makes
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_RC_SETTLE_MS=600000 "$T/bin/pic" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
"$PIC" remote status --json > "$T/stale0.json"
grep -qF '"stale":false' "$T/stale0.json" || fail "stale: a fresh one: $(cat "$T/stale0.json")"
install_new
"$PIC" remote status --json > "$T/stale1.json"
grep -qF '"stale":true' "$T/stale1.json" || fail "stale: after the install: $(cat "$T/stale1.json")"
"$PIC" remote status > "$T/stale1.out"
grep -qF 'older pic than the one installed now: pic remote restart' "$T/stale1.out" || fail "stale: status: $(cat "$T/stale1.out")"
"$PIC" remote restart > "$T/restart.out" 2>&1 || fail "restart: $(cat "$T/restart.out")"
grep -qF 'pic remote: restarted' "$T/restart.out" || fail "restart: $(cat "$T/restart.out")"
grep -qF 'pic remote: asked to restart' "$RO" || fail "restart: what it said: $(cat "$RO")"
"$PIC" remote status --json > "$T/stale2.json"
grep -qF '"stale":false' "$T/stale2.json" && grep -qF "\"pid\":$RP," "$T/stale2.json" || fail "restart: status: $(cat "$T/stale2.json")"
kill "$RP"
gone "$RP"
nr=$((nr + 1))
RO="$T/remote$nr.out"
"$T/bin/pic" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
install_new
await "$RO" 'pic remote: a newer pic was installed; starting /'
i=0
until [ "$(grep -c 'pic remote: connected' "$RO")" -ge 2 ]; do
    i=$((i + 1))
    [ "$i" -lt $TRIES ] || fail "restart: the new one did not connect: $(cat "$RO" "$T/remote$nr.err")"
    sleep 0.05
done
"$PIC" remote status --json > "$T/stale3.json"
grep -qF "\"pid\":$RP," "$T/stale3.json" && grep -qF '"stale":false' "$T/stale3.json" || fail "restart: status: $(cat "$T/stale3.json")"
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$SESS"
EOS
done_ok $PR "after the restart"
kill "$RP"
gone "$RP"
remote
printf 'PASS: a newer pic installed over pic remote: status says it is older; it restarts itself when quiet, or on pic remote restart, and serves again\n'

# A newer pic waiting to migrate a journal pic remote has open (an older pic remote: the seam
# PIC_TEST_HOLDER_SCHEMA): it lets go of the journal, the migration goes ahead instead of failing,
# and it serves the workspace again after.
kill "$RP"
gone "$RP"
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_HOLDER_SCHEMA=18 "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
cur=$(q "SELECT value FROM pic_meta WHERE key='schema_version'")
q "DROP TABLE pic_verdict; UPDATE pic_meta SET value='18' WHERE key='schema_version'"
pic check > /dev/null 2> "$T/yield.err" || fail "yield: not migrated: $(cat "$T/yield.err")"
[ "$(q "SELECT value FROM pic_meta WHERE key='schema_version'")" = "$cur" ] || fail "yield: version not $cur"
await "$RO" "pic remote: let go of "
await "$RO" "pic remote: serving "
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$SESS"
EOS
done_ok $PR "after the migration"
kill "$RP"
gone "$RP"
remote
printf 'PASS: pic remote lets go of a journal a newer pic waits to migrate, and serves it again after\n'

# The relay ends every stream after a while: a clean end of one that lasted (30 s; the seam makes it
# 1 s here, and the relay ends them after 1.5 s) is a recycle, reconnected at once with no line and
# no attempt counted, and pic remote status says when the stream opened and how many recycles. A
# stream that comes back after more than 10 s is logged.
kill "$RP"
gone "$RP"
export PIC_TEST_RC_RECYCLE_MS=1000
remote
unset PIC_TEST_RC_RECYCLE_MS
ctl 'life?1500'
i=0
until "$PIC" remote status --json > "$T/recycle.json" && [ "$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/recycle.json'), '\$.recycles') >= 2")" = 1 ]; do
    i=$((i + 1)); [ "$i" -lt 300 ] || fail "recycle: $(cat "$T/recycle.json")"; sleep 0.1
done
ctl 'life?0'
grep -qF 'the stream ended' "$RO" && fail "recycle: logged: $(grep -F 'the stream ended' "$RO")"
[ "$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/recycle.json'), '\$.attempts')")" = 0 ] || fail "recycle: attempts: $(cat "$T/recycle.json")"
await "$HOME/.pic/remote.status" '"state":"connected"'
"$PIC" remote status --json | grep -qE '"streamOpenedAt":"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z"' || fail "recycle: opened: $("$PIC" remote status --json)"
"$PIC" remote status | grep -qE 'connected to .*, stream open since [0-9]{2}:[0-9]{2}:[0-9]{2}, [0-9]+ recycles;' || fail "recycle: status: $("$PIC" remote status)"
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$SESS"
EOS
done_ok $PR "recycle: the phone"
ctl 'down?11000'
await "$RO" 'the stream reopened '
grep -E '^[0-9]{4}-[0-9]{2}-[0-9]{2}.*pic remote: the stream reopened [0-9.]+ s after it ended' "$RO" > /dev/null || fail "recycle: slow: $(grep -F 'reopened' "$RO")"
grep -qF 'the stream ended' "$RO" || fail "recycle: the cut stream was not logged"
kill "$RP"
gone "$RP"
remote
printf 'PASS: a stream the relay ends after it lasted is reconnected quietly and counted; a slow way back is logged\n'

# A workspace an older pic last used and no pic has open: pic remote updates its journal itself when
# it starts, and serves it, with nothing for the phone to press.
kill "$RP"
gone "$RP"
q "DROP TABLE pic_verdict; UPDATE pic_meta SET value='18' WHERE key='schema_version'"
remote
WSR=$(cd "$WS" && pwd -P)
await "$RO" "pic remote: updated $DB"
[ "$(q "SELECT value FROM pic_meta WHERE key='schema_version'")" = "$cur" ] || fail "update at start: version not $cur"
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$SESS"
EOS
done_ok $PR "update at start"
grep -F '"unavailable":' "$T/ph1.run" | tail -1 | grep -qF '"unavailable":[]' || fail "update at start: still unavailable"
printf 'PASS: pic remote updates a journal an older pic last used when it starts, with no one asking\n'

# One an older pic has open (it holds the journal lock, and says nothing of itself): listed with a
# plain reason and no fix; that pic is never stopped, and the journal is not touched under it. When
# it lets go, pic remote updates the journal and serves it again; a phone's repair, which an older
# page may still send, then answers that it is done.
kill "$RP"
gone "$RP"
q "DROP TABLE pic_verdict; UPDATE pic_meta SET value='18' WHERE key='schema_version'"
rm -f "$T/held" "$T/release"
perl -e 'use Fcntl qw(:flock); open(my $f, ">>", $ARGV[0]) or die; flock($f, LOCK_SH) or die; open(my $g, ">", $ARGV[1]); close $g; sleep 1 while !-e $ARGV[2]' \
    "$DB.pic-lock" "$T/held" "$T/release" &
older=$!
bg $older
i=0
while [ ! -e "$T/held" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "held: the older pic did not start"; sleep 0.05; done
remote
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect {"workspace":"$WSR","reason":"open in an older pic; it updates when that pic closes","name":"$(basename "$WS")"}
send {"type":"repair","key":"k-repair-00000001","payload":{"workspace":"$T/nowhere"}}
expect {"type":"error","key":"k-repair-00000001","payload":{"code":"no_session"
send {"type":"repair","key":"k-repair-00000002","payload":{"workspace":"$WSR"}}
expect {"type":"repair","key":"k-repair-00000002","payload":{"workspace":"$WSR","ok":false,"message":"open in an older pic; it updates when that pic closes"}}
EOS
done_ok $PR "held by an older pic"
grep -qF '"fix"' "$T/ph1.run" && fail "held: a fix was offered: $(grep -F '"fix"' "$T/ph1.run")"
sleep 2
kill -0 "$older" 2>/dev/null || fail "held: the older pic was stopped"
[ "$(q "SELECT value FROM pic_meta WHERE key='schema_version'")" = 18 ] || fail "held: the journal was changed under the older pic"
script "$T/ph1" <<EOS
send {"type":"sessions"}
seen "reason":"open in an older pic; it updates when that pic closes"
mark listed-held
expect "session":"$SESS"
send {"type":"repair","key":"k-repair-00000003","payload":{"workspace":"$WSR"}}
expect {"type":"repair","key":"k-repair-00000003","payload":{"workspace":"$WSR","ok":true,"message":"
EOS
i=0
while [ ! -e "$T/ph1/listed-held" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "held: the phone did not list it"; sleep 0.05; done
touch "$T/release"
gone "$older"
done_ok $PR "the older pic closed"
await "$RO" "pic remote: updated $DB"
[ "$(q "SELECT value FROM pic_meta WHERE key='schema_version'")" = "$cur" ] || fail "held: version not $cur after the older pic closed"
printf 'PASS: an older pic holding a journal is left alone; the phone reads why in plain words, with no fix; pic remote updates it once that pic closes\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"
[ "$(q "SELECT origin FROM pic_session_origin WHERE session_id = '$NEW'")" = phone ] || fail "new conversation: origin $(q "SELECT origin FROM pic_session_origin WHERE session_id = '$NEW'")"
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'

# The phone's workspace list: a workspace whose directory is gone is not listed and its row is
# forgotten; a row naming the user database is mended to the workspace's own journal, or not
# listed; a file that is no journal is not listed; a journal at an older schema is updated and
# listed; two workspaces of one name are told apart by their parent's.
for d in "$T/a/proj" "$T/b/proj" "$T/nojournal"; do
    mkdir -p "$d"
    "$PIC" --workspace "$d" check > /dev/null 2>&1 || fail "workspaces: check in $d"
done
mkdir -p "$T/mend" "$T/old" "$T/home2"
for d in "$T/mend" "$T/old"; do # journals pic remote has not seen yet
    HOME="$T/home2" "$PIC" --workspace "$d" check > /dev/null 2>&1 || fail "workspaces: check in $d"
done
mkdir -p "$T/userdb-only" "$T/notj/.pic"
"$SQLITE3" -cmd ".timeout 10000" "$T/notj/.pic/journal.sqlite" "CREATE TABLE t(x)"
"$SQLITE3" -cmd ".timeout 10000" "$T/old/.pic/journal.sqlite" "UPDATE pic_meta SET value = '17' WHERE key = 'schema_version'"
rm -f "$T/nojournal/.pic/journal.sqlite"
RT=$(cd "$T" && pwd -P) # the registry keeps real paths
uq "INSERT INTO picu_workspace VALUES('$RT/gone/ws3', '$RT/gone/ws3/.pic/journal.sqlite', 1);
    INSERT OR REPLACE INTO picu_workspace VALUES('$RT/userdb-only', '$HOME/.pic/pic.sqlite', 2);
    INSERT OR REPLACE INTO picu_workspace VALUES('$RT/notj', '$RT/notj/.pic/journal.sqlite', 3);
    INSERT OR REPLACE INTO picu_workspace VALUES('$RT/mend', '$HOME/.pic/pic.sqlite', 4);
    INSERT OR REPLACE INTO picu_workspace VALUES('$RT/old', '$RT/old/.pic/journal.sqlite', 5)"
sleep 1.5 # pic remote reads the registry again within a second of a change
script "$T/ph1" <<EOS
send {"type":"sessions"}
seen "workspace":"$RT/old","name":"old"
seen "workspace":"$RT/a/proj","name":"a/proj"
EOS
done_ok $PR "workspace list"
last=$(grep -F '"unavailable":' "$T/ph1.run" | tail -1)
for want in "\"id\":\"$RT/mend/.pic/journal.sqlite\",\"workspace\":\"$RT/mend\",\"name\":\"mend\"" \
    "\"workspace\":\"$RT/a/proj\",\"name\":\"a/proj\"" "\"workspace\":\"$RT/b/proj\",\"name\":\"b/proj\""; do
    case $last in *"$want"*) ;; *) fail "workspaces: no $want in $last" ;; esac
done
for gone_ws in "$RT/gone/ws3" "$RT/userdb-only\"" "$RT/notj\"" "$RT/nojournal\"" "schema 18" "pic.sqlite"; do
    case $last in *"$gone_ws"*) fail "workspaces: $gone_ws is listed: $last" ;; esac
done
[ "$(uq "SELECT count(*) FROM picu_workspace WHERE path IN ('$RT/gone/ws3', '$RT/nojournal')")" = 0 ] || fail "workspaces: gone rows kept"
[ "$(uq "SELECT journal FROM picu_workspace WHERE path = '$RT/mend'")" = "$RT/mend/.pic/journal.sqlite" ] || fail "workspaces: not mended"
[ "$("$SQLITE3" "$T/old/.pic/journal.sqlite" "SELECT value FROM pic_meta WHERE key = 'schema_version'")" = "$cur" ] || fail "workspaces: old not updated"
case $last in *"\"workspace\":\"$RT/old\",\"reason\""*) fail "workspaces: old is unavailable: $last" ;; esac
printf 'PASS: the workspace list leaves out and forgets workspaces that are gone, mends or hides rows naming the user database, hides non-journals, updates an old journal, and tells two of one name apart\n'

# pic run with --db naming the user database (what registered it as a workspace's journal) is
# refused: the user database gains no journal tables and no workspace row.
mkdir "$T/ctxlike"
if (cd "$T/ctxlike" && "$PIC" --db "$HOME/.pic/pic.sqlite" usage --lapse > "$T/udb.out" 2> "$T/udb.err"); then
    fail "userdb as journal: ran: $(cat "$T/udb.out")"
fi
grep -qF "is pic's user database, not a journal" "$T/udb.err" || fail "userdb as journal: $(cat "$T/udb.err")"
[ "$(uq "SELECT count(*) FROM sqlite_master WHERE name LIKE 'pic\\_%' ESCAPE '\\'")" = 0 ] || fail "userdb as journal: journal tables made"
[ "$(uq "SELECT count(*) FROM picu_workspace WHERE path = '$T/ctxlike' OR journal = '$HOME/.pic/pic.sqlite'")" = 0 ] ||
    fail "userdb as journal: registered"
printf 'PASS: --db naming the user database is refused: no journal tables, no workspace row\n'
kill "$spid" 2> /dev/null
DB=$SAVE_DB WS=$SAVE_WS LOG=$SAVE_LOG spid=$SAVE_SPID PIC_MODELS_FILE=$SAVE_MODELS

# A large journal written while phones are served: 60 conversations over 50,000 entries, the most
# recent of them holding nearly all, and a worker adding entries all along. Each part of the list
# is built again only when its journal changes, with work that does not grow with the entries (its
# statements' steps: a walk of pic_entry would take millions; the clock of a loaded machine is no
# measure), and the loop keeps answering pings.
kill "$RP"
gone "$RP"
mkdir "$T/bigws"
BIG="$T/big.sqlite"
"$PIC" --db "$BIG" --workspace "$T/bigws" check > /dev/null 2>&1 || fail "big: check"
pad=$(head -c 600 /dev/zero | tr '\0' x)
"$SQLITE3" "$BIG" "BEGIN;
  INSERT INTO pic_session(id, created_ms, updated_ms) SELECT printf('b%04d', value), 1, 1 FROM generate_series(1, 60);
  INSERT INTO pic_submission(id, request_key, content, status, session_id)
    SELECT value, 'big-' || value, 'question ' || value, 'answered', printf('b%04d', value) FROM generate_series(1, 60);
  INSERT INTO pic_entry(submission_id, kind, body) SELECT 1 + (value % 59), 'user', 'early $pad' FROM generate_series(1, 2000);
  INSERT INTO pic_entry(submission_id, kind, body) SELECT 60, iif(value % 2, 'user', 'assistant'),
    iif(value % 2, 'late $pad', json_array(json_object('type', 'text', 'text', 'late $pad'))) FROM generate_series(1, 48000);
  INSERT INTO pic_generation(submission_id, turn, attempt, state, entry_seq, usage)
    SELECT 60, seq, 1, 'done', seq, json_object('input_tokens', 1000, 'output_tokens', 10, 'attribution', '$pad$pad$pad')
    FROM pic_entry WHERE submission_id = 60 AND kind = 'assistant';
  COMMIT" || fail "big: rows"
[ "$("$SQLITE3" "$BIG" "SELECT count(*) FROM pic_entry WHERE submission_id = 60")" -ge 48000 ] || fail "big: entries"
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_RC_LIST_TIMES=1 PIC_TEST_RC_MESSAGE_STEPS=1 "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
( i=0; while [ $i -lt 60 ] && [ ! -e "$T/big.stop" ]; do
    "$SQLITE3" -cmd ".timeout 10000" "$BIG" "INSERT INTO pic_entry(submission_id, kind, body) VALUES(60, 'user', 'more')" 2> /dev/null
    sleep 0.05; i=$((i + 1)); done ) &
bg $!
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$BIG/b0060"
send {"type":"ping"}
expect {"type":"pong"}
sleep 1000
send {"type":"ping"}
expect {"type":"pong"}
sleep 1000
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "big journal"
touch "$T/big.stop"
await "$RO" "pic remote: listed $BIG in "
heavy=$(sed -n "s|^pic remote: listed $BIG in [0-9]* ms, \([0-9]*\) steps\$|\1|p" "$RO" | awk '$1 >= 100000' | head -3)
[ -z "$heavy" ] || fail "big: list parts took $heavy steps: $(grep -F 'listed' "$RO" | tail -5)"
grep -q "^pic remote: listed $BIG in [0-9]* ms, [0-9]* steps\$" "$RO" || fail "big: no step count: $(grep -F listed "$RO")"
# A phone's questions about its 48,000-entry conversation read only the newest of it: each takes
# work far below what reading the conversation whole would (the steps its statements ran), and the
# loop answers a ping right after.
BS="$BIG/b0060"
script "$T/ph1" <<EOS
cmd k-big-state-000001 {"type":"command","session":"$BS","key":"k-big-state-000001","payload":{"type":"get_state"}}
expect "command":"get_state","success":true
cmd k-big-stats-000001 {"type":"command","session":"$BS","key":"k-big-stats-000001","payload":{"type":"get_session_stats"}}
expect "command":"get_session_stats","success":true
cmd k-big-msgs-0000001 {"type":"command","session":"$BS","key":"k-big-msgs-0000001","payload":{"type":"get_messages"}}
expect "command":"get_messages","success":true
cmd k-big-wakes-000001 {"type":"command","session":"$BS","key":"k-big-wakes-000001","payload":{"type":"get_wakes"}}
expect "command":"get_wakes"
send {"type":"ping"}
expect {"type":"pong"}
send {"type":"sync","session":"$BS","seq":-1,"key":"k-big-sync-0000001"}
expect {"type":"sync","session":"$BS"
EOS
done_ok $PR "big: questions"
for what in "command get_state" "command get_session_stats" "command get_messages" "command get_wakes" "sync"; do
    n=$(sed -n "s|^pic remote: answered $what in \([0-9]*\) steps\$|\1|p" "$RO" | sort -n | tail -1)
    [ -n "$n" ] || fail "big: no step count for $what: $(grep -F answered "$RO" | tail -8)"
    [ "$n" -lt 2000000 ] || fail "big: $what took $n steps: $(grep -F answered "$RO" | tail -8)"
    printf '  %s: %s steps\n' "$what" "$n"
done
[ "$(grep -c "listed $BIG in " "$RO")" -ge 2 ] || fail "big: built once only, though the journal changed: $(grep -F listed "$RO")"
printf 'PASS: a large journal written all along: each list part a bounded amount of work, built again only on a change; the loop keeps answering (%s parts, at most %s steps)\n' \
    "$(grep -c "listed $BIG in " "$RO")" "$(sed -n "s|^pic remote: listed $BIG in [0-9]* ms, \([0-9]*\) steps\$|\1|p" "$RO" | sort -n | tail -1)"
# Out of time (a budget of 0 ms, a dev build's seam): the part is given up, said once, and the
# phone is still answered at once.
kill "$RP"
gone "$RP"
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_RC_LIST_BUDGET_MS=0 "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "type":"sessions"
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "big journal, no time"
await "$RO" "pic remote: listing $BIG took over"
[ "$(grep -c "listing $BIG took over" "$RO")" = 1 ] || fail "big: said more than once: $(grep -F 'took over' "$RO")"
printf 'PASS: a list part out of time is given up and said once; the phone is still answered\n'
kill "$RP"
gone "$RP"
remote

# Only what a person drives is listed. A conversation records what started it: a person (here, as
# PIC_ORIGIN says), a pic from inside another's tool call (an agent, its parent that conversation),
# or a pic with no one at a terminal (headless). The phone lists the person's alone, with how many
# helpers it has running, and no workspace under a temporary directory.
SAVE_DB=$DB SAVE_WS=$WS SAVE_LOG=$LOG SAVE_SPID=$spid SAVE_MODELS=$PIC_MODELS_FILE
spid=
sed 's/touch started; i=0; while \[ ! -e release \] \&\& \[ $i -lt 1200 \]; do sleep 0.05; i=$((i+1)); done; echo held/sh child.sh/' \
    "$S/bash_hold.sse" > "$T/child.sse"
grep -qF 'sh child.sh' "$T/child.sse" || fail "origin: child.sse"
serve "sse:$T/child.sse" "sse:$S/text.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/text.sse"
printf '"%s" --db "%s" --workspace "%s" --model fake/m ask helper > child.out 2>&1\n' "$PIC" "$DB" "$WS" > "$WS/child.sh"
pic ask 'the parent' > /dev/null 2> "$T/askp.err" || fail "origin: parent: $(cat "$T/askp.err")"
PSID=$(q "SELECT id FROM pic_session WHERE id IN (SELECT session_id FROM pic_submission WHERE id = 1)")
RDB="$(cd "$(dirname "$DB")" && pwd -P)/$(basename "$DB")"
[ "$(q "SELECT origin FROM pic_session_origin WHERE session_id = '$PSID'")" = person ] || fail "origin: parent $(q "SELECT * FROM pic_session_origin")"
[ "$(q "SELECT origin || ' ' || parent FROM pic_session_origin WHERE session_id != '$PSID'")" = "agent $RDB/$PSID" ] ||
    fail "origin: child $(q "SELECT * FROM pic_session_origin") $(cat "$WS/child.out")"
env -u PIC_ORIGIN "$PIC" --db "$DB" --workspace "$WS" --model fake/m ask headless < /dev/null > /dev/null 2> "$T/askh.err" ||
    fail "origin: headless: $(cat "$T/askh.err")"
HSID=$(q "SELECT session_id FROM pic_submission ORDER BY id DESC LIMIT 1")
[ "$(q "SELECT origin FROM pic_session_origin WHERE session_id = '$HSID'")" = headless ] || fail "origin: headless $(q "SELECT * FROM pic_session_origin")"
rm -f "$WS/started" "$WS/release"
for k in 1 2; do
    PIC_ORIGIN=agent PIC_PARENT="$RDB/$PSID" "$PIC" --db "$DB" --workspace "$WS" --model fake/m ask "helper $k" > /dev/null 2>&1 &
    bg $!
done
until_sql "SELECT count(*) FROM pic_submission u JOIN pic_session_origin o ON o.session_id = u.session_id WHERE o.parent = '$RDB/$PSID' AND u.status = 'admitted'" 2
mkdir -p "$T/tmp/3f9a1c07" "$T/tmpx"
"$PIC" --workspace "$T/tmp/3f9a1c07" check > /dev/null 2>&1 || fail "origin: check in a temporary directory"
"$PIC" --workspace "$T/tmpx" check > /dev/null 2>&1 || fail "origin: check beside it"
RT=$(cd "$T" && pwd -P)
sleep 1.5 # pic remote reads the registry again within a second of a change
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "helpers":2
EOS
done_ok $PR "helpers"
grep -F '"helpers":2' "$T/ph1.run" | tail -1 | sed 's/^<- //' > "$T/last.json"
[ "$("$SQLITE3" :memory: "SELECT json_extract(value, '\$.helpers') FROM json_each(json_extract(CAST(readfile('$T/last.json') AS TEXT),
    '\$.payload.sessions')) WHERE json_extract(value, '\$.session') = '$DB/$PSID'")" = 2 ] || fail "helpers: not on the parent: $(cat "$T/last.json")"
for id in $(q "SELECT id FROM pic_session WHERE id != '$PSID'"); do
    grep -qF "/$id\"" "$T/last.json" && fail "helpers: $id is listed: $(cat "$T/last.json")"
done
grep -qF "$RT/tmp/3f9a1c07" "$T/last.json" && fail "temporary: listed: $(cat "$T/last.json")"
grep -qF "\"workspace\":\"$RT/tmpx\"" "$T/last.json" || fail "temporary: its neighbour is not listed: $(cat "$T/last.json")"
touch "$WS/release"
until_sql "SELECT count(*) FROM pic_submission WHERE status = 'admitted'" 0
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$DB/$PSID"
EOS
done_ok $PR "helpers done"
grep -F "\"session\":\"$DB/$PSID\"" "$T/ph1.run" | tail -1 | grep -qF '"helpers"' && fail "helpers: still counted after they ended"
# A journal only older pics have opened has no record of origins: its conversations are a person's.
q "DROP TABLE pic_session_origin"
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$DB/$HSID"
EOS
done_ok $PR "no origins"
pic check > /dev/null || fail "origin: integrity"
[ "$(q "SELECT count(*) FROM pic_session_origin")" = 0 ] || fail "origin: the table is not made again on open"
printf 'PASS: the phone lists the conversations a person drives, with their running helpers counted, and no workspace under a temporary directory; with no record of origins, every conversation\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
# Controls from the phone: the models and levels it can pick, a model and level for the next
# request (held by pic remote, then recorded by the request), the conversation's stats, its name,
# deleting it and undoing that, compaction (answered once, the same answer to its key again); a mark says where a sync starts to
# show five more requests; the status file names the phone and what it follows.
spid=
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" \
    "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse"
for k in 1 2 3 4 5 6 7; do
    if [ "$k" = 1 ]; then pic ask "turn $k" > /dev/null 2> "$T/askc.err" || fail "ask: $(cat "$T/askc.err")"
    else pic ask --session "$(q 'SELECT id FROM pic_session')" "turn $k" > /dev/null 2> "$T/askc.err" || fail "ask $k: $(cat "$T/askc.err")"; fi
done
SIDC=$(q "SELECT id FROM pic_session")
SESSC="$DB/$SIDC"
sed 's/"models":\[{"id":"m"}\]/"models":[{"id":"m"},{"id":"m2","reasoning":true}]/' "$PIC_MODELS_FILE" > "$T/models-c.json"
export PIC_MODELS_FILE="$T/models-c.json"
E2=$(q "SELECT min(seq) - 1 FROM pic_entry WHERE submission_id = (SELECT min(id) + 1 FROM pic_submission)")
pic profiles set quick --model fake/m --thinking low > /dev/null 2> "$T/prof.err" || fail "profile: $(cat "$T/prof.err")"
kill "$RP"
gone "$RP"
remote
script "$T/ph1" <<EOS
send {"type":"sync","session":"$SESSC","seq":-1}
expect {"type":"sync","session":"$SESSC","seq":
seen "payload":{"running":false,"earlier":$E2}
send {"type":"sync","session":"$SESSC","seq":$E2}
expect "text":"turn 2"
seen "payload":{"running":false,"earlier":0}
send {"type":"sync","session":"$SESSC","seq":0}
expect "text":"turn 1"
expect "payload":{"running":false}}
cmd k-ctl-models-00001 {"type":"command","session":"$SESSC","key":"k-ctl-models-00001","payload":{"type":"get_available_models","id":"am"}}
expect "id":"m2"
cmd k-ctl-levels-00001 {"type":"command","session":"$SESSC","key":"k-ctl-levels-00001","payload":{"type":"get_available_thinking_levels"}}
expect "command":"get_available_thinking_levels","success":true,"data":{"levels":[
cmd k-ctl-setmod-00001 {"type":"command","session":"$SESSC","key":"k-ctl-setmod-00001","payload":{"type":"set_model","provider":"fake","modelId":"m2"}}
expect "command":"set_model","success":true,"data":{"id":"m2"
cmd k-ctl-badmod-00001 {"type":"command","session":"$SESSC","key":"k-ctl-badmod-00001","payload":{"type":"set_model","provider":"fake","modelId":"nope"}}
expect "error":"Model not found: fake/nope"
cmd k-ctl-level-000001 {"type":"command","session":"$SESSC","key":"k-ctl-level-000001","payload":{"type":"set_thinking_level","level":"high"}}
expect "command":"set_thinking_level","success":true
cmd k-ctl-badlvl-00001 {"type":"command","session":"$SESSC","key":"k-ctl-badlvl-00001","payload":{"type":"set_thinking_level","level":"loud"}}
expect "error":"Invalid thinking level: loud
cmd k-ctl-state-000001 {"type":"command","session":"$SESSC","key":"k-ctl-state-000001","payload":{"type":"get_state"}}
expect "model":{"provider":"fake","id":"m2"},"thinkingLevel":"high"
cmd k-ctl-stats-000001 {"type":"command","session":"$SESSC","key":"k-ctl-stats-000001","payload":{"type":"get_session_stats"}}
expect "command":"get_session_stats","success":true,"data":{"sessionId":"$SIDC","userMessages":7
cmd k-ctl-name-0000001 {"type":"command","session":"$SESSC","key":"k-ctl-name-0000001","payload":{"type":"set_session_name","name":"  named from the phone "}}
expect "command":"set_session_name","success":true
cmd k-ctl-name-0000002 {"type":"command","session":"$SESSC","key":"k-ctl-name-0000002","payload":{"type":"set_session_name","name":"  "}}
expect "error":"Session name cannot be empty"
cmd k-ctl-delete-00001 {"type":"command","session":"$SESSC","key":"k-ctl-delete-00001","payload":{"type":"delete_session"}}
expect "key":"k-ctl-delete-00001","payload":{"type":"response","command":"delete_session","success":true}}
send {"type":"sessions","payload":{"workspace":"$DB"}}
expect {"type":"sessions","payload":{"workspace":"$DB","sessions":[]}}
cmd k-ctl-restore-0001 {"type":"command","session":"$SESSC","key":"k-ctl-restore-0001","payload":{"type":"restore_session"}}
expect "key":"k-ctl-restore-0001","payload":{"type":"response","command":"restore_session","success":true}}
send {"type":"sessions","payload":{"workspace":"$DB"}}
expect {"type":"sessions","payload":{"workspace":"$DB","sessions":[{"session":"$SESSC"
cmd k-ctl-compact-0001 {"type":"command","session":"$SESSC","key":"k-ctl-compact-0001","payload":{"type":"compact"}}
expect "key":"k-ctl-compact-0001","payload":{"type":"response","command":"compact"
send {"type":"command","session":"$SESSC","key":"k-ctl-compact-0001","payload":{"type":"compact"}}
waitcount "key":"k-ctl-compact-0001","payload":{"type":"response","command":"compact" 2
mark go-status
waitfor go-status-done
cmd k-ctl-prompt-00001 {"type":"command","session":"$SESSC","key":"k-ctl-prompt-00001","payload":{"type":"prompt","message":"on the chosen model"}}
seen "command":"prompt","success":true
seen :k-ctl-prompt-00001","status":"answered"
cmd k-ctl-state-000002 {"type":"command","session":"$SESSC","key":"k-ctl-state-000002","payload":{"type":"get_state"}}
expect "model":{"provider":"fake","id":"m2"},"thinkingLevel":"high"
cmd k-ctl-creds-000001 {"type":"command","session":"$SESSC","key":"k-ctl-creds-000001","payload":{"type":"get_credentials"}}
expect "command":"get_credentials","success":true,"data":{"credentials":[
seen "provider":"fake","label":"env","kind":"env"
cmd k-ctl-setkey-00001 {"type":"command","session":"$SESSC","key":"k-ctl-setkey-00001","payload":{"type":"set_credential","provider":"fake","label":"env"}}
expect "command":"set_credential","success":true,"data":{"provider":"fake","label":"env","persist":false}
cmd k-ctl-badkey-00001 {"type":"command","session":"$SESSC","key":"k-ctl-badkey-00001","payload":{"type":"set_credential","provider":"fake","label":"nosuch"}}
expect "error":"fake has no key named \"nosuch\""
cmd k-ctl-state-000003 {"type":"command","session":"$SESSC","key":"k-ctl-state-000003","payload":{"type":"get_state"}}
expect "credential":"fake:env"
cmd k-ctl-profs-000001 {"type":"command","session":"$SESSC","key":"k-ctl-profs-000001","payload":{"type":"get_profiles"}}
expect "profiles":[{"name":"quick","model":"fake/m","credential":null,"thinking":"low"}]
cmd k-ctl-setprof-0001 {"type":"command","session":"$SESSC","key":"k-ctl-setprof-0001","payload":{"type":"set_model","profile":"quick"}}
expect "command":"set_model","success":true,"data":{"id":"m"
cmd k-ctl-state-000004 {"type":"command","session":"$SESSC","key":"k-ctl-state-000004","payload":{"type":"get_state"}}
expect "model":{"provider":"fake","id":"m"},"thinkingLevel":"low"
EOS
i=0
until [ -e "$T/ph1/go-status" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "controls: $(cat "$T/ph1.run")"; sleep 0.05; done
i=0
until "$PIC" remote status --json > /dev/null && grep -qF "\"phones\":[{\"name\":\"Phone One\",\"session\":\"$SESSC\",\"visible\"" "$HOME/.pic/remote.status"; do
    i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "controls: the status file: $(cat "$HOME/.pic/remote.status")"; sleep 0.05
done
"$PIC" remote status --json | grep -qF "\"session\":\"$SESSC\"" || fail "controls: status --json: $("$PIC" remote status --json)"
touch "$T/ph1/go-status-done"
done_ok $PR controls
[ "$(q "SELECT name FROM pic_session WHERE id = '$SIDC'")" = 'named from the phone' ] || fail "controls: name: $(q 'SELECT name FROM pic_session')"
[ "$(q "SELECT model || ' ' || thinking FROM pic_submission WHERE request_key LIKE 'rc:%:k-ctl-prompt-00001'")" = 'fake/m2 high' ] ||
    fail "controls: the request's model: $(q "SELECT model, thinking FROM pic_submission WHERE request_key LIKE 'rc:%'")"
[ "$(q "SELECT model FROM pic_submission WHERE request_key NOT LIKE 'rc:%' ORDER BY id DESC LIMIT 1")" = fake/m ] || fail "controls: earlier requests"
! grep -aqF "$ANTHROPIC_API_KEY" "$T/ph1.run" || fail "controls: a key reached the phone"
printf 'PASS: controls from the phone: models and levels, a choice the next request records, stats, the name, delete and undo, compaction once; the keys with their state and a key for the conversation, never a key itself; profiles; marks say where earlier requests start; the status names the phone and its conversation\n'
kill "$spid" 2> /dev/null
export PIC_MODELS_FILE="$T/models$n.json"

# Images from the phone: pic says it takes them; a prompt with an image is admitted with it (the
# model gets it, the journal keeps it as a pasted one); the phone's events carry each image without
# its bytes, which it asks for by entry and index; a steer carries its image through the inbox; an
# image over several records arrives whole, and pic acknowledges what it read, so the relay is not
# left holding it; a new conversation starts with one; and what is not an image is refused.
spid=
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse"
sed 's/{"id":"m"}/{"id":"m","input":["text","image"]}/' "$PIC_MODELS_FILE" > "$T/models-see.json"
export PIC_MODELS_FILE="$T/models-see.json"
pic ask 'image first' > /dev/null 2> "$T/aski.err" || fail "ask: $(cat "$T/aski.err")"
SIDI=$(q "SELECT id FROM pic_session")
SESSI="$DB/$SIDI"
kill "$RP"
gone "$RP"
remote
PNG_B64='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=='
GIF_B64='R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "features":["images","asks"]
send {"type":"sync","session":"$SESSI","seq":-1}
expect "running":false
cmd k-img-bad-00000001 {"type":"command","session":"$SESSI","key":"k-img-bad-00000001","payload":{"type":"prompt","message":"not one","images":[{"type":"image","data":"aGVsbG8=","mimeType":"image/png"}]}}
expect {"type":"error","key":"k-img-bad-00000001","payload":{"code":"bad_command"
cmd k-img-0000000000001 {"type":"command","session":"$SESSI","key":"k-img-0000000000001","payload":{"type":"prompt","message":"look at this","images":[{"type":"image","data":"$PNG_B64","mimeType":"image/png"}]}}
expect {"type":"text","text":"look at this"},{"type":"image","mimeType":"image/png","index":0,"bytes":70}]
seen "command":"prompt","success":true
seen :k-img-0000000000001","status":"answered"
sleep 300
EOS
done_ok $PR "image prompt"
grep -qF "$PNG_B64" "$LOG/2.req" || fail "image prompt: the model did not get the image"
ISEQ=$(q "SELECT seq FROM pic_entry WHERE kind = 'user' AND body = 'look at this'")
[ -n "$ISEQ" ] || fail "image prompt: no entry"
[ "$(q "SELECT count(*) FROM pic_attachment a JOIN pic_image i ON i.hash = a.image WHERE a.entry_seq = $ISEQ AND i.mime = 'image/png' AND i.width = 1")" = 1 ] ||
    fail "image prompt: attachments: $(q 'SELECT entry_seq, queued_id, ordinal FROM pic_attachment')"
[ "$(q "SELECT count(*) FROM pic_submission WHERE request_key LIKE 'rc:%:k-img-bad-00000001'")" = 0 ] || fail "bad image: admitted"
grep '^<- ' "$T/ph1.run" | grep -qF "$PNG_B64" && fail "image prompt: an event carried the image's bytes"
script "$T/ph1" <<EOS
send {"type":"image","session":"$SESSI","seq":$ISEQ,"payload":{"index":0}}
expect {"type":"image","session":"$SESSI","seq":$ISEQ,"payload":{"index":0,"mimeType":"image/png","data":"$PNG_B64"}}
send {"type":"image","session":"$SESSI","seq":$ISEQ,"payload":{"index":3}}
expect "payload":{"index":3,"error":"no_image"}
send {"type":"image","session":"$SESSI","seq":1,"payload":{"index":0}}
expect "payload":{"index":0,"error":"no_image"}
EOS
done_ok $PR "image fetch"
"$PIC" --db "$DB" attach --session "$SIDI" --no-follow > "$T/attachi.out" 2> "$T/attachi.err" || fail "attach: $(cat "$T/attachi.err")"
grep -qF '{"type":"text","text":"look at this"},{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]' "$T/attachi.out" ||
    fail "attach: the image is not in the user message: $(grep -F 'look at this' "$T/attachi.out" | head -c 400)"
printf 'PASS: a prompt from the phone with an image: the model gets it, the journal keeps it; events name it, the phone asks for its bytes; not an image is refused\n'

rm -f "$WS/started" "$WS/release"
pic ask --session "$SIDI" 'hold on' > "$T/holdi.out" 2> "$T/holdi.err" &
HP=$!
bg $HP
i=0
until [ -e "$WS/started" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "hold: did not start: $(cat "$T/holdi.err")"; sleep 0.05; done
script "$T/ph1" <<EOS
send {"type":"sync","session":"$SESSI","seq":-1}
expect "running":true
cmd k-img-steer-000001 {"type":"command","session":"$SESSI","key":"k-img-steer-000001","payload":{"type":"prompt","message":"and this","streamingBehavior":"steer","images":[{"type":"image","data":"$GIF_B64","mimeType":"image/gif"}]}}
expect {"type":"ack","key":"k-img-steer-000001"
mark go-release
expect "status":"answered"
EOS
i=0
until [ -e "$T/ph1/go-release" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "image steer: no ack: $(cat "$T/ph1.run")"; sleep 0.05; done
touch "$WS/release"
done_ok $PR "image steer"
gone $HP
grep -qF "$GIF_B64" "$LOG/4.req" || fail "image steer: the model did not get the image"
[ "$(q "SELECT count(*) FROM pic_attachment a JOIN pic_entry e ON e.seq = a.entry_seq WHERE e.body = 'and this'")" = 1 ] ||
    fail "image steer: attachments: $(q 'SELECT entry_seq, queued_id, ordinal FROM pic_attachment')"
printf 'PASS: a steer from the phone with an image reaches the running request with it\n'

# Over 300 KB: about thirty records, posted while pic reads; it acknowledges them as it goes.
B64CMD=$(command -v base64)
{ printf '%s' "$PNG_B64" | "$B64CMD" -d 2> /dev/null || printf '%s' "$PNG_B64" | "$B64CMD" -D; } > "$T/dot.png"
{ cat "$T/dot.png"; head -c 320000 /dev/zero | tr '\0' 'x'; } > "$T/big.png"
printf '{"type":"command","session":"%s","key":"k-img-big-00000001","payload":{"type":"prompt","message":"big one","images":[{"type":"image","data":"%s","mimeType":"image/png"}]}}\n' \
    "$SESSI" "$("$B64CMD" < "$T/big.png" | tr -d '\n')" > "$T/big.json"
script "$T/ph1" <<EOS
cmdfile k-img-big-00000001 $T/big.json
expect "key":"k-img-big-00000001","session":"$SESSI","payload":{"type":"response","command":"prompt","success":true
EOS
done_ok $PR "big image"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-img-big-00000001'" answered
[ "$(q "SELECT i.sz FROM pic_attachment a JOIN pic_image i ON i.hash = a.image JOIN pic_entry e ON e.seq = a.entry_seq WHERE e.body = 'big one'")" = "$(wc -c < "$T/big.png" | tr -d ' ')" ] ||
    fail "big image: stored: $(q 'SELECT a.entry_seq, i.sz FROM pic_attachment a JOIN pic_image i ON i.hash = a.image')"
i=0
until state | grep -qF ' up 0"'; do
    i=$((i + 1))
    [ "$i" -lt $TRIES ] || fail "big image: the relay still holds what pic read: $(state)"
    sleep 0.05
done
printf 'PASS: an image over many records arrives whole, and pic acknowledges what it read\n'

W3=$DB
script "$T/ph1" <<EOS
cmd k-img-new-00000001 {"type":"command","session":"+$W3","key":"k-img-new-00000001","payload":{"type":"prompt","message":"","images":[{"type":"image","data":"$PNG_B64","mimeType":"image/png"}]}}
expect "key":"k-img-new-00000001","session":"$W3/
EOS
done_ok $PR "image new conversation"
grep -F '"key":"k-img-new-00000001"' "$T/ph1.run" | grep -qF '"command":"prompt","success":true' || fail "image new conversation: $(cat "$T/ph1.run")"
[ "$(q "SELECT count(*) FROM pic_attachment a JOIN pic_entry e ON e.seq = a.entry_seq JOIN pic_submission u ON u.id = e.submission_id
    WHERE u.request_key LIKE 'rc:%:k-img-new-00000001'")" = 1 ] || fail "image new conversation: attachments"
printf 'PASS: a new conversation from the phone starts with an image and no text\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" 3600 status:201:- status:201:- status:201:- status:410:- status:201:- &
bg $!
i=0; until [ -s "$T/pport" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || 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"
# The title is the conversation's: its first prompt's first line, as no name was given.
[ "$("$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|push first|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'
# Loops with the terminal closed (docs/design/wakes.md): pic remote fires a due loop and starts its
# request; the phone sees how many loops a conversation has, lists them and pauses, resumes and
# stops one; one of another conversation is refused; a loop that comes to need a person is one
# notification.
mkdir "$T/plog2"
"$SERVER" "$T/pport2" "$T/plog2" 300 status:201:- status:201:- status:201:- status:201:- status:201:- &
bg $!
i=0; until [ -s "$T/pport2" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "push service 2 did not start"; sleep 0.05; done
EP2="http://127.0.0.1:$(cat "$T/pport2")/push/ph1"
script "$T/ph1" <<EOS
send $("$PHONE" "$T/ph1" pushkeys "$EP2")
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "loops: subscribe"
pic loop 5m loop from the remote > "$T/loop.out" 2>&1 || fail "loops: create: $(cat "$T/loop.out")"
SIDL=$(q "SELECT session_id FROM pic_wake")
SESSL="$DB/$SIDL"
until_sql "SELECT status FROM pic_submission WHERE request_key = 'inbox:wake:1:1'" answered
await "$T/plog2/1.req" 'Content-Length'
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "title":"loop from the remote","preview":"Hello, \\"world\\"","state":"idle","workspaceName":"$(basename "$WS")","loops":1}
cmd k-loop-list-000001 {"type":"command","session":"$SESSL","key":"k-loop-list-000001","payload":{"type":"get_wakes"}}
expect "command":"get_wakes","success":true,"data":{"wakes":[{"id":1,"name":"L1","kind":"loop"
cmd k-loop-pause-00001 {"type":"command","session":"$SESSL","key":"k-loop-pause-00001","payload":{"type":"pause_wake","id":"L1"}}
expect "state":"paused","why":"paused from a phone"
cmd k-loop-other-00001 {"type":"command","session":"$SESSP","key":"k-loop-other-00001","payload":{"type":"stop_wake","id":"L1"}}
expect "error":"no loop L1 in this conversation"
cmd k-loop-resume-0001 {"type":"command","session":"$SESSL","key":"k-loop-resume-0001","payload":{"type":"resume_wake","id":"L1"}}
expect "command":"resume_wake","success":true,"data":{"wakes":[{"id":1,"name":"L1","kind":"loop"
EOS
done_ok $PR "loops: phone"
[ "$(q "SELECT state FROM pic_wake")" = active ] || fail "loops: resume: $(q 'SELECT state, why FROM pic_wake')"
q "UPDATE pic_wake SET state = 'needs', why = 'its message was refused: a test', updated_ms = updated_ms + 1000"
await "$T/plog2/2.req" 'Content-Length'
"$PHONE" "$T/ph1" pushread "$T/plog2/2.req" | grep -qF '"body":"Loop L1 needs you: its message was refused: a test"' ||
    fail "loops: push: $("$PHONE" "$T/ph1" pushread "$T/plog2/2.req")"
# a loop the model asked for: the phone starts it
q "UPDATE pic_wake SET state = 'needs', why = 'waiting for your OK', options = json_set(coalesce(options, '{}'), '\$.approval', 'asked')"
script "$T/ph1" <<EOS
cmd k-loop-approve-001 {"type":"command","session":"$SESSL","key":"k-loop-approve-001","payload":{"type":"approve_wake","id":"L1"}}
expect "command":"approve_wake","success":true,"data":{"wakes":[{"id":1,"name":"L1","kind":"loop"
EOS
done_ok $PR "loops: approve"
[ "$(q "SELECT state, json_extract(options, '\$.approval') FROM pic_wake")" = "active|approved" ] || fail "loops: approve: $(q 'SELECT state, options FROM pic_wake')"
script "$T/ph1" <<EOS
cmd k-loop-stop-000001 {"type":"command","session":"$SESSL","key":"k-loop-stop-000001","payload":{"type":"stop_wake","id":"L1"}}
expect "command":"stop_wake","success":true,"data":{"wakes":[],"nowMs":
cmd k-loop-stop-000002 {"type":"command","session":"$SESSL","key":"k-loop-stop-000002","payload":{"type":"stop_wake","id":"L1"}}
expect "command":"stop_wake","success":true
EOS
done_ok $PR "loops: stop"
sleep 1.5
[ "$(ls "$T/plog2" | grep -c '\.req$')" = 2 ] || fail "loops: $(ls "$T/plog2") pushes, not 2"
pic check > /dev/null || fail "loops: integrity"
printf 'PASS: pic remote fires loops with the terminal closed; the phone lists, pauses, resumes and stops them; one that needs you is a notification\n'
# Asks (docs/dev/asks.md): a question the conversation waits on reaches the phone as an ask record
# and one notification in pic's own words; the list counts it and marks the row attention;
# get_state carries it. The phone answers with the command answer under the key ask-ID: an answer
# that is not one is bad_command, the first answer is answered and a resend of its key gets the
# same, a later one already_answered with the one that stands; every phone hears ask_settled with
# who answered. A question that expires unanswered is ask_settled as expired.
NOW=$(($(date +%s) * 1000))
AID=askaskaskaskaskaskask1
q "INSERT INTO pic_ask(id, ask_key, session_id, kind, title, spec, created_ms, expires_ms, state, version) VALUES('$AID', 'test:1', '$SIDL', 'select', 'Which branch?', '{\"options\":[{\"label\":\"main\",\"default\":true},{\"label\":\"dev\"}]}', $NOW, $NOW + 600000, 'open', (SELECT coalesce(max(version), 0) + 1 FROM pic_ask))"
await "$T/plog2/3.req" 'Content-Length'
"$PHONE" "$T/ph1" pushread "$T/plog2/3.req" | grep -qF '"body":"loop from the remote needs your answer"' ||
    fail "asks: push: $("$PHONE" "$T/ph1" pushread "$T/plog2/3.req")"
script "$T/ph1" <<EOS
seen {"type":"ask","session":"$SESSL","payload":{"id":"$AID","kind":"select","title":"Which branch?"
seen "options":[{"label":"main","default":true},{"label":"dev"}]
send {"type":"sessions"}
expect "state":"attention","workspaceName":"$(basename "$WS")","asks":1}
cmd k-ask-state-000001 {"type":"command","session":"$SESSL","key":"k-ask-state-000001","payload":{"type":"get_state"}}
expect "asks":[{"id":"$AID",
send {"type":"command","session":"$SESSL","key":"k-ask-answer-00000","payload":{"type":"answer","id":"nosuchquestionatall000","value":"dev"}}
expect "command":"answer","success":false,"error":"no such question in this conversation"
send {"type":"command","session":"$SESSL","key":"k-ask-answer-00001","payload":{"type":"answer","id":"$AID","value":"other"}}
expect "command":"answer","success":false,"error":"a select is answered with one of its labels"
send {"type":"command","session":"$SESSL","key":"k-ask-answer-00002","payload":{"type":"answer","id":"$AID","value":"$(printf 'z%.0s' $(seq 1 4001))"}}
expect "code":"bad_command"
send {"type":"command","session":"$SESSL","key":"ask-$AID","payload":{"type":"answer","id":"$AID","value":"dev"}}
expect "command":"answer","success":true,"data":{"result":"answered","id":"$AID","value":"dev","by":{"kind":"phone","device":"Phone One","deviceId":"remote:$DEV1B"}}
send {"type":"command","session":"$SESSL","key":"ask-$AID","payload":{"type":"answer","id":"$AID","value":"dev"}}
expect "command":"answer","success":true,"data":{"result":"answered","id":"$AID","value":"dev","by":{"kind":"phone","device":"Phone One","deviceId":"remote:$DEV1B"}}
send {"type":"command","session":"$SESSL","key":"k-ask-answer-00003","payload":{"type":"answer","id":"$AID","value":"main"}}
expect "data":{"result":"already_answered","id":"$AID","value":"dev","by":{"kind":"phone","device":"Phone One","deviceId":"remote:$DEV1B"}}
seen {"type":"ask_settled","session":"$SESSL","payload":{"id":"$AID","value":"dev","by":{"kind":"phone","device":"Phone One","deviceId":"remote:$DEV1B"}}}
EOS
done_ok $PR "asks: phone"
[ "$(q "SELECT state, answer, answered_by LIKE 'remote:%' FROM pic_ask WHERE id = '$AID'")" = 'answered|"dev"|1' ] || fail "asks: row: $(q "SELECT * FROM pic_ask WHERE id = '$AID'")"
NOW=$(($(date +%s) * 1000))
q "INSERT INTO pic_ask(id, ask_key, session_id, kind, title, created_ms, expires_ms, state, version) VALUES('askaskaskaskaskaskask2', 'test:2', '$SIDL', 'confirm', 'Soon gone?', $NOW, $NOW + 2000, 'open', (SELECT max(version) + 1 FROM pic_ask))"
script "$T/ph1" <<EOS
seen {"type":"ask_settled","session":"$SESSL","payload":{"id":"askaskaskaskaskaskask2","value":null,"by":{"kind":"expired","device":null,"deviceId":null}}}
EOS
done_ok $PR "asks: expired"
sleep 1.5
[ "$(ls "$T/plog2" | grep -c '\.req$')" = 4 ] || fail "asks: $(ls "$T/plog2") pushes, not 4"
printf 'PASS: a question reaches the phone as an ask and a notification, is counted in the list and in get_state, and is answered once from the phone; every phone hears how it settled\n'
# The asks fixture, test/pic/remote-asks.json: every ask, answer, response, ask_settled and get_state
# part a phone sees about a question, as pic wrote them to the phone above. pic-relay copies the
# file byte for byte, so its page is tested against pic's own records. Ids, times, the journal's
# path, the conversation's id and the device's id are fixed in it. PIC_UPDATE_FIXTURES=1 rewrites it.
FXD=$here/remote-asks.json
FXN=$(($(date +%s) * 1000))
FXC1=fxconfirmyes0000000001 FXC2=fxconfirmno00000000002 FXS=fxselect00000000000003 FXI=fxinput000000000000004
FXD0=fxdismiss0000000000005 FXX=fxexpire00000000000006 FXW=fxcancel00000000000007
for id in $FXC1 $FXC2 $FXS $FXI $FXD0 $FXX $FXW; do [ "${#id}" = 22 ] || fail "asks fixture: $id is not 22 characters"; done
q "INSERT INTO pic_submission(request_key, content, status, session_id) VALUES('fx:run', '{}', 'answered', '$SIDL')"
FXSUB=$(q "SELECT id FROM pic_submission WHERE request_key = 'fx:run'")
fx_ask() { # ID KIND TITLE BODY SPEC EXPIRES STATE
    q "INSERT INTO pic_ask(id, ask_key, session_id, submission_id, kind, title, body, spec, created_ms, expires_ms, state, version) VALUES('$1', 'test:fx:$1', '$SIDL', $FXSUB, '$2', '$3', $4, $5, $FXN, $6, '${7:-open}', (SELECT coalesce(max(version), 0) + 1 FROM pic_ask))"
}
fx_ask $FXC1 confirm 'Delete the build folder?' "'It holds 212 files from the last build.'" NULL $((FXN + 600000))
fx_ask $FXC2 confirm 'Run the migration now?' NULL NULL $((FXN + 600000))
fx_ask $FXS select 'notes.txt already exists' NULL "'{\"options\":[{\"label\":\"Overwrite\",\"destructive\":true},{\"label\":\"Keep both\",\"default\":true},{\"label\":\"Skip\"}]}'" $((FXN + 600000))
fx_ask $FXI input 'Name the branch' "'Short, lower case.'" "'{\"placeholder\":\"feature/login\"}'" $((FXN + 600000))
fx_ask $FXD0 input 'Any notes for the release?' NULL NULL $((FXN + 600000))
fxcmd() { # NAME ID VALUE: the answer command, in a variable named FXCMD_NAME
    eval "FXCMD_$1='{\"type\":\"command\",\"session\":\"$SESSL\",\"key\":\"fx-answer-$1-0000001\",\"payload\":{\"type\":\"answer\",\"id\":\"$2\",\"value\":$3}}'"
}
fxcmd yes $FXC1 true
fxcmd no $FXC2 false
fxcmd again $FXC2 true
fxcmd select $FXS '"Keep both"'
fxcmd text $FXI '"feature/login"'
fxcmd dismiss $FXD0 null
fxcmd late $FXX true
script "$T/ph1" <<EOS
seen {"type":"ask","session":"$SESSL","payload":{"id":"$FXC1",
seen {"type":"ask","session":"$SESSL","payload":{"id":"$FXS",
seen {"type":"ask","session":"$SESSL","payload":{"id":"$FXI",
send {"type":"sessions"}
expect "state":"attention","workspaceName":"$(basename "$WS")","asks":5}
cmd fx-answer-yes-0000001 $FXCMD_yes
expect "command":"answer","success":true,"data":{"result":"answered","id":"$FXC1"
cmd fx-answer-no-0000001 $FXCMD_no
expect "command":"answer","success":true,"data":{"result":"answered","id":"$FXC2"
cmd fx-answer-again-0000001 $FXCMD_again
expect "command":"answer","success":true,"data":{"result":"already_answered","id":"$FXC2"
cmd fx-answer-select-0000001 $FXCMD_select
expect "command":"answer","success":true,"data":{"result":"answered","id":"$FXS"
mark go-fx-answered
waitfor go-fx-flipped
cmd fx-get-state-0000001 {"type":"command","session":"$SESSL","key":"fx-get-state-0000001","payload":{"type":"get_state"}}
expect "command":"get_state","success":true
EOS
i=0; until [ -e "$T/ph1/go-fx-answered" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "asks fixture: $(cat "$T/ph1.run")"; sleep 0.05; done
q "UPDATE pic_submission SET status = 'admitted' WHERE id = $FXSUB" # a run still waiting: settled asks are told in get_state
: > "$T/ph1/go-fx-flipped"
done_ok $PR "asks fixture: answers"
cp "$T/ph1.run" "$T/fx-a.run"
script "$T/ph1" <<EOS
cmd fx-answer-text-0000001 $FXCMD_text
expect "command":"answer","success":true,"data":{"result":"answered","id":"$FXI"
cmd fx-answer-dismiss-0000001 $FXCMD_dismiss
expect "command":"answer","success":true,"data":{"result":"answered","id":"$FXD0"
mark go-fx-up
waitfor go-fx-told
seen {"type":"ask_settled","session":"$SESSL","payload":{"id":"$FXW",
seen {"type":"ask_settled","session":"$SESSL","payload":{"id":"$FXX",
cmd fx-answer-late-0000001 $FXCMD_late
expect "command":"answer","success":true,"data":{"result":"expired","id":"$FXX"
EOS
i=0; until [ -e "$T/ph1/go-fx-up" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "asks fixture: $(cat "$T/ph1.run")"; sleep 0.05; done
q "UPDATE pic_submission SET status = 'answered' WHERE id = $FXSUB"
FXN2=$(($(date +%s) * 1000))
fx_ask $FXX confirm 'Still want the old build?' NULL NULL $((FXN2 + 2000))
fx_ask $FXW confirm 'Stop the watcher?' NULL NULL $((FXN + 600000)) withdrawn
: > "$T/ph1/go-fx-told"
done_ok $PR "asks fixture: settled"
cp "$T/ph1.run" "$T/fx-b.run"
fxpick() { # TEXT [TEXT]: the first message either run received that has both, as pic sent it
    cat "$T/fx-a.run" "$T/fx-b.run" | grep -F -- "$1" | grep -F -- "${2:-<-}" | head -1 | sed -e 's/^<- //' -e "s/'/''/g"
}
fxask() { fxpick '{"type":"ask","session":"'"$SESSL"'","payload":{"id":"'"$1"'"'; }
fxsettled() { fxpick '{"type":"ask_settled","session":"'"$SESSL"'","payload":{"id":"'"$1"'"'; }
fxresp() { fxpick '"key":"fx-answer-'"$1"'-0000001"' '"command":"answer"'; }
fxcmdq() { eval "printf '%s' \"\$FXCMD_$1\"" | sed "s/'/''/g"; }
"$SQLITE3" :memory: > "$T/asks.raw" <<EOS
SELECT json_pretty(json_object(
  'ask', json_object('confirm', json('$(fxask $FXC1)'), 'select', json('$(fxask $FXS)'), 'input', json('$(fxask $FXI)')),
  'answer', json_object('confirm_true', json('$(fxcmdq yes)'), 'confirm_false', json('$(fxcmdq no)'), 'select', json('$(fxcmdq select)'),
      'input', json('$(fxcmdq text)'), 'dismiss', json('$(fxcmdq dismiss)')),
  'response', json_object('answered', json('$(fxresp yes)'), 'already_answered', json('$(fxresp again)'), 'expired', json('$(fxresp late)')),
  'ask_settled', json_object('answered', json('$(fxsettled $FXC1)'), 'dismissed', json('$(fxsettled $FXD0)'),
      'expired', json('$(fxsettled $FXX)'), 'cancelled', json('$(fxsettled $FXW)')),
  'get_state', (SELECT json_object('asks', json_extract(value, '\$.payload.data.asks'), 'settledAsks', json_extract(value, '\$.payload.data.settledAsks'))
      FROM json_each('[' || '$(fxpick '"key":"fx-get-state-0000001"' '"command":"get_state"')' || ']')),
  'sessions_row', (SELECT json(value) FROM json_each(json_extract('$(fxpick '"type":"sessions"' '"asks":5}')', '\$.payload.sessions'))
      WHERE json_extract(value, '\$.session') = '$SESSL')));
EOS
sed -e "s|$DB|/home/me/.pic/pic.sqlite|g" -e "s|$SIDL|7c1e4a90|g" -e "s|$DEV1B|AAECAwQFBgcICQoLDA0ODw|g" \
    -e "s|$(basename "$WS")|project|g" -e "s|$FXN|1800000000000|g" -e "s|$FXN2|1800000000000|g" -e "s|$((FXN + 600000))|1800000600000|g" \
    -e "s|$((FXN2 + 2000))|1800000002000|g" -e 's|"/[^"]*/project"|"/home/me/project"|' -e 's|"lastMs": [0-9]*|"lastMs": 1800000000000|' "$T/asks.raw" > "$T/asks.json"
[ -z "${PIC_UPDATE_FIXTURES:-}" ] || cp "$T/asks.json" "$FXD"
cmp -s "$T/asks.json" "$FXD" || fail "asks fixture: pic's records differ from test/pic/remote-asks.json (PIC_UPDATE_FIXTURES=1 rewrites it): $(diff "$FXD" "$T/asks.json" 2>&1 | head -30)"
printf 'PASS: the records a phone sees about a question are the ones in test/pic/remote-asks.json\n'
kill "$spid" 2> /dev/null
DB=$SAVE_DB WS=$SAVE_WS LOG=$SAVE_LOG spid=$SAVE_SPID PIC_MODELS_FILE=$SAVE_MODELS

# ---- pairing from a paired phone (protocol, Amendments) -----------------------------------------
phone_offer() { # the URL in DIR.run's last pair_offer
    await "$1.run" '"type":"pair_offer"'
    URL=$(sed -n 's/.*"type":"pair_offer".*"url":"\([^"]*\)".*/\1/p' "$1.run" | tail -1)
    [ -n "$URL" ] || fail "phone offer: no address: $(cat "$1.run")"
}
rows=$(uq "SELECT count(*) FROM picu_remote_device")

# A paired phone asks for an offer, a new device pairs with it, both show the same six digits, and
# the paired phone's approval pairs it: nobody at the computer. A replay of the approval's record
# does nothing.
script "$T/ph1" <<EOS
send {"type":"devices"}
expect "type":"devices"
send {"type":"pair_offer"}
expect "type":"pair_offer"
expect "type":"pair_request"
send {"type":"pair_approve","payload":{"code":"\$CODE"}}
expect "result":"paired"
expect "name":"Phone Five"
replay
expectnot "type":"error" 2000
EOS
A=$PR
phone_offer "$T/ph1"
case "$URL" in "$BASE/#p1."*) ;; *) fail "phone offer: address $URL" ;; esac
phone_pair "$T/ph5" "Phone Five"
await "$T/ph5.out" 'code '
await "$T/ph1.run" '"type":"pair_request"'
c5=$(sed -n 's/^code //p' "$T/ph5.out" | tr -d ' ')
grep -qF "\"name\":\"Phone Five\",\"code\":\"$c5\"" "$T/ph1.run" || fail "phone pairing: the codes differ: $c5 / $(grep pair_request "$T/ph1.run")"
gone $PH
[ "$rc" = 0 ] || fail "phone pairing: new device exit $rc: $(cat "$T/ph5.out")"
done_ok $A "phone pairing: approver"
[ "$(uq "SELECT count(*) FROM picu_remote_device")" = $((rows + 1)) ] || fail "phone pairing: rows"
await "$RO" 'Phone One paired Phone Five'
DEV5B=$(sed -n 's/.*"result":"paired".*"device":"\([^"]*\)".*/\1/p' "$T/ph1.run" | head -1)
[ -n "$DEV5B" ] || fail "phone pairing: no device id: $(grep pair_end "$T/ph1.run")"
script "$T/ph5" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "phone pairing: the new device's session"
printf 'PASS: a paired phone adds a device: the same six digits on both, its approval pairs it, a replay does nothing\n'

# A rival used the offer first: the approving phone shows the rival's name and digits, the owner's
# device gets no answer, and a no from the phone pairs nobody.
script "$T/ph1" <<EOS
send {"type":"pair_offer"}
expect "type":"pair_offer"
expect "name":"Rival"
mark go-rival
waitfor go-deny
send {"type":"pair_deny"}
expect "result":"refused"
EOS
A=$PR
phone_offer "$T/ph1"
phone_pair "$T/rv" "Rival"
RV=$PH
i=0; until [ -e "$T/ph1/go-rival" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "rival: $(cat "$T/ph1.run")"; sleep 0.05; done
phone_pair "$T/own" "Owner's Phone"
gone $PH
[ "$rc" = 6 ] || fail "rival: the owner's device was answered: exit $rc: $(cat "$T/own.out")"
touch "$T/ph1/go-deny"
gone $RV
[ "$rc" = 3 ] || fail "rival: exit $rc: $(cat "$T/rv.out")"
done_ok $A "rival: approver"
[ "$(uq "SELECT count(*) FROM picu_remote_device")" = $((rows + 1)) ] || fail "rival: rows"
printf 'PASS: a rival that used the offer first shows its own name and digits on the approving phone; no pairs nobody\n'

# One try: an approval with other digits refuses the offer, and the right digits after it change
# nothing. Another paired phone cannot approve, nor can it take a second offer meanwhile.
script "$T/ph1" <<EOS
send {"type":"pair_offer"}
expect "type":"pair_offer"
expect "type":"pair_request"
mark go-asked
waitfor go-wrong
send {"type":"pair_approve","payload":{"code":"999999x"}}
expect "result":"refused"
send {"type":"pair_approve","payload":{"code":"\$CODE"}}
expect "code":"no_offer"
EOS
A=$PR
phone_offer "$T/ph1"
phone_pair "$T/ph7" "Phone Seven"
await "$T/ph7.out" 'code '
i=0; until [ -e "$T/ph1/go-asked" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "one try: $(cat "$T/ph1.run")"; sleep 0.05; done
c7=$(sed -n 's/^code //p' "$T/ph7.out" | tr -d ' ')
P1=$A
script "$T/ph4" <<EOS
send {"type":"pair_approve","payload":{"code":"$c7"}}
expect "code":"no_offer"
send {"type":"pair_offer"}
expect "result":"busy"
EOS
done_ok $PR "another phone's approval"
[ "$(uq "SELECT count(*) FROM picu_remote_device")" = $((rows + 1)) ] || fail "another phone's approval: rows"
touch "$T/ph1/go-wrong"
gone $PH
[ "$rc" = 3 ] || fail "one try: exit $rc: $(cat "$T/ph7.out")"
done_ok $P1 "one try: approver"
[ "$(uq "SELECT count(*) FROM picu_remote_device")" = $((rows + 1)) ] || fail "one try: rows"
printf 'PASS: only the asking phone approves, once: other digits refuse, a later approval and a rival phone change nothing\n'

# remote.phonePairing off: no offer.
"$PIC" settings remote.phonePairing off > /dev/null
script "$T/ph1" <<EOS
send {"type":"pair_offer"}
expect "result":"off"
EOS
done_ok $PR "phone pairing off"
"$PIC" settings remote.phonePairing on > /dev/null
printf 'PASS: remote.phonePairing off: a phone cannot add a device\n'

# A phone unpairs another: the list is sent again, and the unpaired device cannot come back.
script "$T/ph1" <<EOS
send {"type":"devices"}
expect "Phone Five"
send {"type":"unpair_device","payload":{"device":"$DEV5B"}}
expect "type":"devices"
EOS
done_ok $PR "unpair another"
[ "$(uq "SELECT count(*) FROM picu_remote_device")" = "$rows" ] || fail "unpair another: rows"
grep '"type":"devices"' "$T/ph1.run" | tail -1 | grep -qF 'Phone Five' && fail "unpair another: still listed"
await "$RO" 'Phone One unpaired Phone Five'
script "$T/ph5" <<EOS
awaitgone
EOS
gone $PR
[ "$rc" = 4 ] || fail "unpair another: it came back: exit $rc: $(cat "$T/ph5.run")"
printf 'PASS: a phone unpairs another; it cannot connect again, and the device list follows\n'

# 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"}
awaitgone
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"}
awaitgone
EOS
i=0; until [ -e "$T/ph1/go-unpair" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || 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
awaitgone
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'

# Unpair every device from a phone: one paired at the terminal adds another, which unpairs both.
term_pair() { # DIR NAME: pair at the terminal, with a yes
    offer
    phone_pair "$1" "$2"
    await "$PO" '"type":"code"'
    echo y >&3
    gone $PH
    [ "$rc" = 0 ] || fail "pair $2: phone exit $rc: $(cat "$1.out")"
    gone $PP
    exec 3>&-
}
term_pair "$T/ph9" "Phone Nine"
await "$RO" 'serving Phone Nine'
script "$T/ph9" <<EOS
send {"type":"pair_offer"}
expect "type":"pair_offer"
expect "type":"pair_request"
send {"type":"pair_approve","payload":{"code":"\$CODE"}}
expect "result":"paired"
expect {"type":"unpaired"}
awaitgone
EOS
P9=$PR
phone_offer "$T/ph9"
phone_pair "$T/ph10" "Phone Ten"
gone $PH
[ "$rc" = 0 ] || fail "unpair all: pairing: exit $rc: $(cat "$T/ph10.out")"
script "$T/ph10" <<EOS
send {"type":"unpair_all"}
expect {"type":"unpaired"}
awaitgone
EOS
gone $PR
[ "$rc" = 4 ] || fail "unpair all: the asking phone: exit $rc: $(cat "$T/ph10.run")"
gone $P9
[ "$rc" = 4 ] || fail "unpair all: the other phone: exit $rc: $(cat "$T/ph9.run")"
[ "$(uq "SELECT count(*) FROM picu_remote_device")" = 0 ] || fail "unpair all: rows"
state | grep -qF 'channels 0 ' || fail "unpair all: relay channels: $(state)"
await "$RO" 'Phone Ten unpaired every device'
printf 'PASS: a phone unpairs every device, itself included: each is told, every row and channel goes\n'

# And at the computer: pic remote unpair --all, no passphrase.
term_pair "$T/ph11" "Phone Eleven"
await "$RO" 'serving Phone Eleven'
env -u PIC_TEST_PASSPHRASE "$PIC" remote unpair --all < /dev/null > "$T/unpairall.out" 2> "$T/unpairall.err" ||
    fail "unpair --all: $(cat "$T/unpairall.err")"
grep -qx 'unpaired 1 device' "$T/unpairall.out" || fail "unpair --all: $(cat "$T/unpairall.out")"
await "$RO" 'Phone Eleven was unpaired'
[ "$(uq "SELECT count(*) FROM picu_remote_device")" = 0 ] || fail "unpair --all: rows"
[ "$(uq "SELECT count(*) FROM picu_remote_key")" = 3 ] || fail "unpair --all: the keys went too"
printf 'PASS: pic remote unpair --all unpairs every phone and keeps the keys\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")"
# Reset while one runs (no phone is paired now, so it waits for one): it is stopped first, not left
# serving keys that are gone.
"$PIC" remote > "$T/rwait.out" 2> "$T/rwait.err" &
RP=$!
bg $RP
await "$T/rwait.out" 'waiting'
"$PIC" remote reset > "$T/reset.out" 2> "$T/reset.err" || fail "reset: $(cat "$T/reset.err")"
gone "$RP"
[ "$rc" = 0 ] || fail "reset: the running pic remote: exit $rc"
"$PIC" remote status | grep -qF 'is not running' || fail "reset: status: $("$PIC" remote status)"
[ "$(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 stops a running one and 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 add your other devices' 'send y\r' >&4
    await "$T/pr5.tx" 'add your other devices'
    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 any other key does not' 'wait 1000' 'send n' '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
send {"type":"ping"}
expect "type":"pong"
expect "type":"bye"
sleep 3500
send {"type":"ping"}
expectreset
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"
printf 'PASS: a phone that ignores bye loses its session: its next record is answered with a reset\n'

# Reset with a phone connected: the running pic remote tells it, as unpair does, before it stops
# and the mailbox goes; the phone says it was unpaired, not that the relay lost its pairing.
remote
script "$T/pr3" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
mark go-reset
expect {"type":"unpaired"}
awaitgone
EOS
i=0; until [ -e "$T/pr3/go-reset" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "reset: $(cat "$T/pr3.run")"; sleep 0.05; done
"$PIC" remote reset > "$T/reset2.out" 2> "$T/reset2.err" || fail "reset: $(cat "$T/reset2.err")"
gone $PR
[ "$rc" = 4 ] && grep -qF '<- {"type":"unpaired"}' "$T/pr3.run" || fail "reset: the phone was not told: exit $rc: $(cat "$T/pr3.run")"
gone "$RP"
printf 'PASS: reset tells a connected phone it is unpaired before the mailbox goes\n'

# /rc in the terminal interface: with no phone paired it pairs one at once (asking for the store's
# passphrase first, the pairing running as pic remote pair --pipe with the key handed down), and
# remote control goes on; s turns it off, p then 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 (120 s)
        i=0
        until plain | grep -qF -- "$1"; do
            i=$((i + 1))
            [ "$i" -lt $((TRIES / 2)) ] || 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*$' | grep -v '▀' | tail -15)"
            sleep 0.1
        done
    }
    # The store is locked in this process: /rc asks for the passphrase (and, once, whether to stop
    # asking: no), then pairs.
    say 'expect fake/m' 'send /rc\r' 'expect /rc goes on once it opens' 'send remote-test-pass\r' \
        'expect Stop asking for this passphrase?' 'send n' 'expect Scan this with the phone' \
        'expect check its six digits here' # the line after the address: the address is all there
    tx 'check its six digits here'
    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.' 'expect ● Remote control is on'
    tx 'Paired Phone TUI.'
    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 'send d' 'expect 1 then y: unpair' 'expect Phone TUI, ' 'send \e' 'expect d devices'
    say 'send s' 'expect ○ Remote control is off'
    tx '○ Remote control is off'
    "$PIC" remote status > "$T/tuistatus.out"
    grep -qF 'pic remote is not running' "$T/tuistatus.out" || fail "tui s: $(cat "$T/tuistatus.out")"
    printf 'PASS: /rc with no phone pairs one: the passphrase, the QR code and address, the code, a yes, remote on, 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 the phone' 'send \e' 'expect Pairing cancelled.' 'expect s turn on'
    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 d' 'expect Paired phones' '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 \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'
    tx '● Remote control is on'
    "$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 opens this conversation, on screen: the footer names it.
    script "$T/phv" <<EOF2
send {"type":"presence","payload":{"visible":true}}
send {"type":"sync","session":"$SESS2","seq":-1}
expect "type":"sync"
EOF2
    done_ok $PR "v2 watch"
    say 'expect Phone V2 watching'
    tx 'Phone V2 watching' # the footer's cells that changed: "Phone V2 watching"
    printf 'PASS: the footer names the phone that has this conversation open\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 $TRIES ] || 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 $((TRIES / 2)) ] || 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'
    # Opened again, the conversation still says which messages a phone sent.
    "$DRIVE" "$T/tui3.tx" 220 70 "$PIC" --db "$DB" --workspace "$WS" --model fake/m -c > "$T/tui3.out" 2>&1 <<'EOF3' ||
expect hold from the phone
wait 300
send \x04\x04
EOF3
        fail "reopened: $(cat "$T/tui3.out")"
    perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/tui3.tx" | grep -q 'from [^:]*: hello from the phone' ||
        fail "reopened: the phone's prompt is not marked: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/tui3.tx" | grep -F 'hello from the phone')"
    perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/tui3.tx" | grep -q 'from [^:]*: mac question' && fail "reopened: the terminal's prompt marked"
    printf 'PASS: a conversation opened again marks the messages a phone sent\n'
fi