Skip to content
pi-c Artifact [f4dac8f8ee]
Login

Artifact [f4dac8f8ee]

Artifact f4dac8f8ee1d040b597bad09335fa705a6057577479f75f5543d77e90b1a1407:


#!/bin/sh
# Remote control sessions, sync, streaming, prompts, steering, aborts, controls, and trash.
# Usage: test/pic/remote_session.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-session.XXXXXX")
export HOME="$T/home"
. "$here/remote_lib.sh"

init_paired 2

# Connections: first ask, prompt, steer (hold + reply + followUp), abort (hold), cut (hold + reply), crash 1 & 2 (hold + reply + followUp each)
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'

# Version hello: pic's first message on each confirmed session carries protocol version and build;
# an older phone answering hello with error/unknown_type gets no error back, and a mismatched
# protocol or build string with quotes encodes cleanly.
VER=$("$PIC" --version | awk '{print $2}')
[ -n "$VER" ] || fail "hello: no pic --version"
script "$T/ph1" <<EOS
expect {"type":"hello","payload":{"protocol":1,"build":"$VER"}}
send {"type":"error","payload":{"code":"unknown_type"}}
send {"type":"ping"}
expect {"type":"pong"}
expectnot "unknown_type" 500
newsession
expect {"type":"hello","payload":{"protocol":1,"build":"$VER"}}
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR hello
first_down=$(grep '^<- ' "$T/ph1.run" | head -1)
want="<- {\"type\":\"hello\",\"payload\":{\"protocol\":1,\"build\":\"$VER\"}}"
[ "$first_down" = "$want" ] ||
    fail "hello: first message down was not hello: $first_down"
[ "$(grep -cF -- "$want" "$T/ph1.run")" = 2 ] ||
    fail "hello: expected hello on both sessions: $(cat "$T/ph1.run")"
kill "$RP"
gone "$RP"
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_RC_PROTOCOL=2 PIC_TEST_RC_BUILD='2026-12-01 "rc"' "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
script "$T/ph1" <<EOS
expect {"type":"hello","payload":{"protocol":2,"build":"2026-12-01 \"rc\""}}
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR hello-mismatch
first_down=$(grep '^<- ' "$T/ph1.run" | head -1)
[ "$first_down" = '<- {"type":"hello","payload":{"protocol":2,"build":"2026-12-01 \"rc\""}}' ] ||
    fail "hello-mismatch: first message down: $first_down"
kill "$RP"
gone "$RP"
export PIC_TEST_RC_SEEN_MS=200
remote
unset PIC_TEST_RC_SEEN_MS
printf 'PASS: version hello: protocol and build first on every session, error ignored, mismatched version encoded\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'

# 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'


# 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, last heard from it [0-9]+ s ago, (last record [0-9]+ s ago|no record yet); 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'

# 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"
seen {"provider":"openrouter","env":"OPENROUTER_API_KEY","fix":["pic auth login openrouter --command 'COMMAND THAT PRINTS THE KEY'","pic auth login openrouter --api-key"]}
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"
seen "missing":[
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"
for k in models creds; do # each provider pic remote has no key for, with the fix; never one it has
    grep -F "\"key\":\"k-ctl-$k-" "$T/ph1.run" | grep -F '"success":true' | head -1 | sed 's/^<- //' > "$T/missing-$k.json"
    [ "$("$SQLITE3" :memory: "SELECT count(*) FROM json_each(json(readfile('$T/missing-$k.json')), '\$.payload.data.missing')
        WHERE json_extract(value, '\$.provider') = 'openrouter'")" = 1 ] || fail "controls: $k: no openrouter in missing: $(cat "$T/missing-$k.json")"
    [ "$("$SQLITE3" :memory: "SELECT count(*) FROM json_each(json(readfile('$T/missing-$k.json')), '\$.payload.data.missing')
        WHERE json_extract(value, '\$.provider') IN ('anthropic', 'fake')")" = 0 ] || fail "controls: $k: a provider with a key is missing"
done
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; the providers pic remote has no key for, with the fix; marks say where earlier requests start; the status names the phone and its conversation\n'

# Lists carry each conversation's start (created_ms) as startedMs, unchanged by later messages
# (#114). Archiving from the phone takes it out of the lists until it is unarchived; a list asked
# with archived includes it, marked (#112).
CREATED=$(q "SELECT created_ms FROM pic_session WHERE id = '$SIDC'")
[ "$CREATED" != "$(q "SELECT updated_ms FROM pic_session WHERE id = '$SIDC'")" ] || fail "startedMs: no later message"
script "$T/ph1" <<EOS
send {"type":"sessions","payload":{"workspace":"$DB"}}
expect "session":"$SESSC","name":"named from the phone","workspace":
seen "startedMs":$CREATED
cmd k-arc-000000000001 {"type":"command","session":"$SESSC","key":"k-arc-000000000001","payload":{"type":"archive_session"}}
expect "command":"archive_session","success":true,"data":{"session":"$SESSC","archived":true,"archivedMs":
send {"type":"sessions","payload":{"workspace":"$DB"}}
expect {"type":"sessions","payload":{"workspace":"$DB","sessions":[]}}
send {"type":"sessions","payload":{"workspace":"$DB","archived":true}}
expect "archived":true
cmd k-arc-000000000002 {"type":"command","session":"$SESSC","key":"k-arc-000000000002","payload":{"type":"unarchive_session"}}
expect "command":"unarchive_session","success":true,"data":{"session":"$SESSC","archived":false,"archivedMs":null}
send {"type":"sessions"}
expect "type":"sessions","payload":{"sessions":[
EOS
done_ok $PR "archive from the phone"
grep '"type":"sessions","payload":{"sessions":\[' "$T/ph1.run" | tail -1 | grep -qF "\"session\":\"$SESSC\"" || fail "unarchive: not in the list"
grep '"type":"sessions","payload":{"sessions":\[' "$T/ph1.run" | tail -1 | grep -qF "\"startedMs\":$CREATED" || fail "startedMs: not in the global list"
[ "$(q "SELECT count(*) FROM pic_archive")" = 0 ] || fail "unarchive: row left"
printf 'PASS: lists carry startedMs; a phone archives a conversation out of its lists and back\n'

# Deleted conversations from the phone (#108): a list asked with trash includes the deleted ones,
# marked with when; restore_session brings one back and purge_session empties one for good, which
# the lists then leave out.
pic submit throwaway-1 "throwaway turn" > /dev/null 2> "$T/askt.err" || fail "submit: $(cat "$T/askt.err")"
pic cancel throwaway-1 > /dev/null 2>&1 || fail "cancel"
TID=$(q "SELECT session_id FROM pic_submission WHERE request_key = 'throwaway-1'")
TSESS="$DB/$TID"
script "$T/ph1" <<EOS
cmd k-trash-0000000001 {"type":"command","session":"$TSESS","key":"k-trash-0000000001","payload":{"type":"delete_session"}}
expect "command":"delete_session","success":true
send {"type":"sessions","payload":{"workspace":"$DB","trash":true}}
expect "deleted":true,"deletedMs":
send {"type":"sessions","payload":{"trash":true}}
expect "type":"sessions","payload":{"sessions":[
cmd k-trash-0000000002 {"type":"command","session":"$TSESS","key":"k-trash-0000000002","payload":{"type":"restore_session"}}
expect "command":"restore_session","success":true
cmd k-trash-0000000003 {"type":"command","session":"$TSESS","key":"k-trash-0000000003","payload":{"type":"purge_session"}}
expect "command":"purge_session","success":false,"error":"Delete it first"
cmd k-trash-0000000004 {"type":"command","session":"$TSESS","key":"k-trash-0000000004","payload":{"type":"delete_session"}}
expect "command":"delete_session","success":true
cmd k-trash-0000000005 {"type":"command","session":"$TSESS","key":"k-trash-0000000005","payload":{"type":"purge_session"}}
expect "command":"purge_session","success":true
send {"type":"sessions","payload":{"workspace":"$DB","trash":true}}
expect "type":"sessions","payload":{"workspace":"$DB","sessions":[
EOS
done_ok $PR "trash from the phone"
# the list goes again on each change: one of them, before the purge, shows it deleted
grep '"type":"sessions","payload":{"sessions":\[' "$T/ph1.run" | grep -F "\"session\":\"$TSESS\"" | grep -qF '"deleted":true,"deletedMs":' ||
    fail "trash: not in the global list with trash: $(grep '"type":"sessions","payload":{"sessions"' "$T/ph1.run" | head -c 600)"
grep "\"workspace\":\"$DB\",\"sessions\":" "$T/ph1.run" | tail -1 | grep -qF "$TSESS" && fail "purge: still listed"
[ -n "$(q "SELECT purged_ms FROM pic_trash WHERE session_id = '$TID'")" ] || fail "purge: not purged"
pic check > /dev/null || fail "purge: integrity"
printf 'PASS: a phone lists deleted conversations, restores one, and purges one for good\n'

# A deleted conversation that was archived first is in the lists asked with trash, global and for
# its workspace, both flags kept; archived alone and a plain list leave it out; restored, it is
# archived again (#117).
pic submit throwaway-2 "archived then deleted" > /dev/null 2> "$T/askt.err" || fail "submit: $(cat "$T/askt.err")"
pic cancel throwaway-2 > /dev/null 2>&1 || fail "cancel"
AID=$(q "SELECT session_id FROM pic_submission WHERE request_key = 'throwaway-2'")
ASESS="$DB/$AID"
script "$T/ph1" <<EOS
cmd k-arcdel-000000001 {"type":"command","session":"$ASESS","key":"k-arcdel-000000001","payload":{"type":"archive_session"}}
expect "command":"archive_session","success":true
cmd k-arcdel-000000002 {"type":"command","session":"$ASESS","key":"k-arcdel-000000002","payload":{"type":"delete_session"}}
expect "command":"delete_session","success":true
send {"type":"sessions","payload":{"workspace":"$DB","trash":true}}
expect "workspace":"$DB","sessions":[
send {"type":"sessions","payload":{"workspace":"$DB","archived":true}}
expect "workspace":"$DB","sessions":[
send {"type":"sessions","payload":{"workspace":"$DB"}}
expect "workspace":"$DB","sessions":[
send {"type":"sessions","payload":{"trash":true}}
expect "type":"sessions","payload":{"sessions":[
mark arcdel-lists
cmd k-arcdel-000000003 {"type":"command","session":"$ASESS","key":"k-arcdel-000000003","payload":{"type":"restore_session"}}
expect "command":"restore_session","success":true
send {"type":"sessions","payload":{"workspace":"$DB","archived":true}}
expect "workspace":"$DB","sessions":[
send {"type":"sessions","payload":{"workspace":"$DB"}}
expect "workspace":"$DB","sessions":[
EOS
done_ok $PR "archived then deleted"
wl() { grep "\"workspace\":\"$DB\",\"sessions\":" "$T/ph1.run" | sed -n "$1p"; }
row() { printf '%s\n' "$1" | grep -o "{\"session\":\"$ASESS\"[^}]*}"; }
r=$(row "$(wl 1)")
[ -n "$r" ] || fail "#117: a trash list of the workspace leaves out a deleted, archived conversation: $(wl 1 | head -c 400)"
printf '%s' "$r" | grep -qF '"archived":true' && printf '%s' "$r" | grep -qF '"deleted":true' || fail "#117: flags: $r"
[ -z "$(row "$(wl 2)")" ] || fail "#117: archived alone lists a deleted conversation"
[ -z "$(row "$(wl 3)")" ] || fail "#117: a plain list shows a deleted conversation"
g=$(grep '"type":"sessions","payload":{"sessions":\[' "$T/ph1.run" | grep -F "\"session\":\"$ASESS\"" | head -1)
[ -n "$g" ] || fail "#117: no global trash list has the deleted, archived conversation"
printf '%s' "$(row "$g")" | grep -qF '"archived":true' || fail "#117: global flags: $(row "$g")"
r=$(row "$(wl 4)")
[ -n "$r" ] && printf '%s' "$r" | grep -qF '"archived":true' && ! printf '%s' "$r" | grep -qF '"deleted":true' ||
    fail "#117: restored, not archived again: $(wl 4 | head -c 400)"
[ -z "$(row "$(wl 5)")" ] || fail "#117: restored to archived, yet in a plain list"
printf 'PASS: a deleted conversation that was archived is in the trash lists, global and per workspace, and archived again once restored\n'