Skip to content
pi-c Artifact [478867f96d]
Login

Artifact [478867f96d]

Artifact 478867f96d073800d7bc56aa4157a240f97b3763ec5a0d30038358e6aaae9ef8:


#!/bin/sh
# Remote control forking, origins and read-only helpers, and TUI /rc integration.
# Usage: test/pic/remote_fork.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-fork.XXXXXX")
export HOME="$T/home"
. "$here/remote_lib.sh"

init_paired 1

serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/bash_out.sse" "sse:$S/bash_hold.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")
pic ask --session "$SID" 'second question' > /dev/null 2> "$T/ask2.err" || fail "ask 2: $(cat "$T/ask2.err")"
SESS="$DB/$SID"
remote

# fork_session (pic's own): a new conversation from the end of this one, or from an entry that ends a
# turn, answered with its W/C; listed next as a phone's; a resend of the key gets the same
# conversation and makes no second one; the key with another command is refused; a point that is
# not one is the response's error. While a request runs, the end is where its last finished request
# ended, and an entry of the running request is refused.
FHEAD=$(q "SELECT head_seq FROM pic_session WHERE id = '$SID'")
FSUB=$(q "SELECT min(id) FROM pic_submission WHERE session_id = '$SID'")
FAT=$(q "SELECT max(seq) FROM pic_entry WHERE submission_id = $FSUB")
FUSER=$(q "SELECT min(seq) FROM pic_entry WHERE submission_id = $FSUB AND kind = 'user'")
FWANT=$FHEAD # the end before the held request
script "$T/ph1" <<EOS
cmd k-fork-00000000001 {"type":"command","session":"$SESS","key":"k-fork-00000000001","payload":{"type":"fork_session"}}
expect "command":"fork_session","success":true,"data":{"session":"$DB/
send {"type":"command","session":"$SESS","key":"k-fork-00000000001","payload":{"type":"fork_session"}}
waitcount "key":"k-fork-00000000001","payload":{"id":null,"type":"response","command":"fork_session","success":true 2
send {"type":"command","session":"$SESS","key":"k-fork-00000000001","payload":{"type":"fork_session","at":$FAT}}
expect {"type":"error","key":"k-fork-00000000001","payload":{"code":"refused","message":"that key was used to fork another point or conversation"}}
cmd k-fork-00000000002 {"type":"command","session":"$SESS","key":"k-fork-00000000002","payload":{"type":"fork_session","at":$FAT}}
expect "command":"fork_session","success":true,"data":{"session":"$DB/
cmd k-fork-00000000003 {"type":"command","session":"$SESS","key":"k-fork-00000000003","payload":{"type":"fork_session","at":$FUSER}}
expect "command":"fork_session","success":false,"error":"entry $FUSER is not a point to fork from: it must be on this conversation and end a turn"
cmd k-fork-00000000004 {"type":"command","session":"$SESS","key":"k-fork-00000000004","payload":{"type":"fork_session","at":"x"}}
expect {"type":"error","key":"k-fork-00000000004","payload":{"code":"bad_command"
EOS
done_ok $PR "fork"
F1=$(sed -n 's/.*"key":"k-fork-00000000001".*"command":"fork_session","success":true,"data":{"session":"[^"]*\/\([0-9a-f]*\)".*/\1/p' "$T/ph1.run" | sort -u)
F2=$(sed -n 's/.*"key":"k-fork-00000000002".*"command":"fork_session","success":true,"data":{"session":"[^"]*\/\([0-9a-f]*\)".*/\1/p' "$T/ph1.run" | sort -u)
[ -n "$F1" ] && [ "$(printf '%s\n' "$F1" | wc -l)" -eq 1 ] || fail "fork: the resend named another conversation: [$F1] $(grep k-fork-00000000001 "$T/ph1.run")"
grep -qF "\"data\":{\"session\":\"$DB/$F1\",\"at\":$FHEAD}" "$T/ph1.run" || fail "fork: at the end: $(grep k-fork-00000000001 "$T/ph1.run")"
grep -qF "\"data\":{\"session\":\"$DB/$F2\",\"at\":$FAT}" "$T/ph1.run" || fail "fork: at $FAT: $(grep k-fork-00000000002 "$T/ph1.run")"
[ "$(q "SELECT count(*) FROM pic_session WHERE forked_from = '$SID'")" = 2 ] || fail "fork: forks: $(q "SELECT id, head_seq FROM pic_session WHERE forked_from = '$SID'")"
[ "$(q "SELECT head_seq FROM pic_session WHERE id = '$F1'")" = "$FHEAD" ] || fail "fork: head of $F1"
[ "$(q "SELECT head_seq FROM pic_session WHERE id = '$F2'")" = "$FAT" ] || fail "fork: head of $F2"
[ "$(q "SELECT origin FROM pic_session_origin WHERE session_id = '$F1'")" = phone ] || fail "fork: origin $(q "SELECT * FROM pic_session_origin WHERE session_id = '$F1'")"
script "$T/ph1" <<EOS
send {"type":"sessions"}
seen "session":"$DB/$F1"
seen "session":"$DB/$F2"
EOS
done_ok $PR "fork: listed"
# A fork reads as its path does (#124): a sync of it shows the entries it shares with the
# conversation it came from and marks its head, with earlier requests to page back to; a fetch
# pages back over them; pic attach shows them too.
script "$T/ph1" <<EOS
send {"type":"sync","session":"$DB/$F2","seq":-1}
expect "text":"first question"
expect {"type":"sync","session":"$DB/$F2","seq":$FAT,
send {"type":"sync","session":"$DB/$F1","seq":-1}
expect {"type":"sync","session":"$DB/$F1","seq":$FHEAD,
send {"type":"fetch","session":"$DB/$F1","key":"k-fork-fetch-00001","payload":{"before":$FHEAD,"limit":200}}
expect "key":"k-fork-fetch-00001","payload":{"done":true,"more":false}}
EOS
done_ok $PR "fork: followed"
grep -F '"key":"k-fork-fetch-00001"' "$T/ph1.run" | grep -qF '"text":"first question"' || fail "fork: the fetch did not page back over the shared entries: $(grep -F k-fork-fetch "$T/ph1.run" | cut -c1-200)"
grep -F "{\"type\":\"sync\",\"session\":\"$DB/$F1\",\"seq\":$FHEAD," "$T/ph1.run" | grep -qF '"earlier":' || fail "fork: the mark has no earlier: $(grep -F "$F1" "$T/ph1.run" | tail -2)"
"$PIC" --db "$DB" attach --session "$F2" --no-follow > "$T/fattach.out" 2> "$T/fattach.err" || fail "fork: attach: $(cat "$T/fattach.err")"
grep -qF '"text":"first question"' "$T/fattach.out" || fail "fork: pic attach shows nothing of the fork: $(head -c 300 "$T/fattach.out")"
grep -F '"type":"agent_start"' "$T/fattach.out" | grep -qF "\"conversation\":\"$F2\"" || fail "fork: a shared request is not named as the fork's: $(grep -F agent_start "$T/fattach.out" | head -2)"
grep -F '"type":"agent_start"' "$T/fattach.out" | grep -qF "\"conversation\":\"$SID\"" && fail "fork: a shared request is named as the source's"
# A fork with a request of its own reads its shared entries, then its own; a fork of it reads both.
script "$T/ph1" <<EOS
cmd k-fork-own-000001 {"type":"command","session":"$DB/$F2","key":"k-fork-own-000001","payload":{"type":"prompt","message":"in the fork"}}
expect "command":"prompt","success":true
EOS
done_ok $PR "fork: its own request"
until_sql "SELECT status || ' ' || coalesce(error, '') FROM pic_submission WHERE request_key LIKE 'rc:%:k-fork-own-000001'" 'answered '
script "$T/ph1" <<EOS
cmd k-fork-00000000008 {"type":"command","session":"$DB/$F2","key":"k-fork-00000000008","payload":{"type":"fork_session"}}
expect "command":"fork_session","success":true,"data":{"session":"$DB/
EOS
done_ok $PR "fork: a fork of a fork"
F3=$(sed -n 's/.*"key":"k-fork-00000000008".*"data":{"session":"[^"]*\/\([0-9a-f]*\)".*/\1/p' "$T/ph1.run" | head -1)
F2HEAD=$(q "SELECT head_seq FROM pic_session WHERE id = '$F2'")
[ "$(q "SELECT head_seq FROM pic_session WHERE id = '$F3'")" = "$F2HEAD" ] || fail "fork of a fork: head"
for f in "$F2" "$F3"; do
    script "$T/ph1" <<EOS
send {"type":"sync","session":"$DB/$f","seq":0}
expect "text":"first question"
expect "text":"in the fork"
expect {"type":"sync","session":"$DB/$f","seq":$F2HEAD,
EOS
    done_ok $PR "fork: $f followed whole"
done
# A fork of a fork is titled by the first prompt on its path until it has a name or a prompt of its
# own: the source's first, whether the fork between has requests of its own (F3, of F2) or none (F4, of F1).
script "$T/ph1" <<EOS
cmd k-fork-00000000009 {"type":"command","session":"$DB/$F1","key":"k-fork-00000000009","payload":{"type":"fork_session"}}
expect "key":"k-fork-00000000009","payload":{"id":null,"type":"response","command":"fork_session","success":true
EOS
done_ok $PR "fork: a fork of a fork with nothing of its own"
F4=$(sed -n 's/.*"key":"k-fork-00000000009".*"data":{"session":"[^"]*\/\([0-9a-f]*\)".*/\1/p' "$T/ph1.run" | head -1)
script "$T/ph1" <<EOS
send {"type":"sessions","payload":{"workspace":"$DB"}}
expect "session":"$DB/$F4"
EOS
done_ok $PR "fork: titles"
grep -F '{"type":"sessions","payload":{"workspace":"'"$DB"'"' "$T/ph1.run" | tail -1 | sed 's/^<- //' > "$T/ftitles.json"
ftitle() { "$SQLITE3" :memory: "SELECT coalesce(json_extract(value, '\$.title'), '') FROM json_each(json(readfile('$T/ftitles.json')), '\$.payload.sessions') WHERE json_extract(value, '\$.session') = '$DB/$1'"; }
[ "$(ftitle "$F3")" = 'first question' ] || fail "fork: a fork of a fork with requests between: title [$(ftitle "$F3")]"
[ "$(ftitle "$F4")" = 'first question' ] || fail "fork: a fork of a fork: title [$(ftitle "$F4")]"
[ "$(ftitle "$F2")" = 'in the fork' ] || fail "fork: a fork with its own prompt: title [$(ftitle "$F2")]"
hold
HSUB=$(q "SELECT max(id) FROM pic_submission WHERE session_id = '$SID'")
HUSER=$(q "SELECT min(seq) FROM pic_entry WHERE submission_id = $HSUB")
# its first command's result ends a turn: only its request still running keeps it from being the end
HTOOL=$(q "SELECT max(seq) FROM pic_entry WHERE submission_id = $HSUB AND kind = 'tool_result'")
[ -n "$HTOOL" ] || fail "fork: the held request has no result yet: $(q "SELECT seq, kind FROM pic_entry WHERE submission_id = $HSUB")"
# pic fork at the terminal skips the running request as the phone does: a fork never shares one
FC=$(pic fork "$SID" 2> "$T/fcli.err") || fail "fork: pic fork while running: $(cat "$T/fcli.err")"
[ "$(q "SELECT head_seq FROM pic_session WHERE id = '$FC'")" = "$FWANT" ] || fail "fork: pic fork took the running request: head $(q "SELECT head_seq FROM pic_session WHERE id = '$FC'"), not $FWANT"
"$PIC" --db "$DB" attach --session "$FC" --no-follow > "$T/fcattach.out" 2> "$T/fcattach.err" || fail "fork: attach: $(cat "$T/fcattach.err")"
HKEY=$(q "SELECT request_key FROM pic_submission WHERE id = $HSUB")
grep -qF "\"request\":\"$HKEY\"" "$T/fcattach.out" && fail "fork: attach shows the source's running request: $(grep -F "$HKEY" "$T/fcattach.out" | head -2)"
grep -qF '"type":"agent_start"' "$T/fcattach.out" || fail "fork: attach shows nothing: $(head -c 200 "$T/fcattach.out")"
if pic fork "$SID" --at "$HTOOL" > /dev/null 2> "$T/fcli2.err"; then fail "fork: pic fork --at an entry of the running request"; fi
grep -qF "entry $HTOOL is in the request still running" "$T/fcli2.err" || fail "fork: pic fork --at: $(cat "$T/fcli2.err")"
script "$T/ph1" <<EOS
cmd k-fork-00000000005 {"type":"command","session":"$SESS","key":"k-fork-00000000005","payload":{"type":"fork_session"}}
expect "command":"fork_session","success":true,"data":{"session":"$DB/
cmd k-fork-00000000006 {"type":"command","session":"$SESS","key":"k-fork-00000000006","payload":{"type":"fork_session","at":$HUSER}}
expect "command":"fork_session","success":false,"error":"entry $HUSER is in the request still running: fork from an earlier entry, or once it ends"
cmd k-fork-00000000007 {"type":"command","session":"$SESS","key":"k-fork-00000000007","payload":{"type":"fork_session","at":$HTOOL}}
expect "command":"fork_session","success":false,"error":"entry $HTOOL is in the request still running: fork from an earlier entry, or once it ends"
cmd k-fork-abort-00001 {"type":"command","session":"$SESS","key":"k-fork-abort-00001","payload":{"type":"abort"}}
expect "key":"k-fork-abort-00001","payload":{"type":"response","command":"abort","success":true
EOS
done_ok $PR "fork: running"
gone $HP
F5=$(sed -n 's/.*"key":"k-fork-00000000005".*"data":{"session":"[^"]*\/\([0-9a-f]*\)".*/\1/p' "$T/ph1.run" | head -1)
[ "$(q "SELECT head_seq FROM pic_session WHERE id = '$F5'")" = "$FWANT" ] ||
    fail "fork: while running: head $(q "SELECT head_seq FROM pic_session WHERE id = '$F5'"), not $FWANT ($(q "SELECT seq, submission_id, kind FROM pic_entry ORDER BY seq DESC LIMIT 6"))"
"$PIC" --db "$DB" check > /dev/null || fail "fork: integrity"
printf 'PASS: the phone forks a conversation at its end or at an entry, once per key, and while a request runs\n'

# 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")"
# get_state's helpers (pic's own, as its asks are): the parent's helpers, newest first, each its
# W/C, title and state, absent for none; a helper is followed like any conversation, though the
# list leaves it out.
hl() { "$SQLITE3" :memory: "SELECT $1 FROM json_each(json_extract(CAST(readfile('$T/helpers.json') AS TEXT), '\$.payload.data.helpers'))"; }
H1=$(q "SELECT session_id FROM pic_submission WHERE content = 'helper 1'")
script "$T/ph1" <<EOS
cmd k-helpers-0000000001 {"type":"command","session":"$DB/$PSID","key":"k-helpers-0000000001","payload":{"type":"get_state"}}
expect "key":"k-helpers-0000000001","payload":{"type":"response","command":"get_state","success":true
cmd k-helpers-0000000002 {"type":"command","session":"$DB/$H1","key":"k-helpers-0000000002","payload":{"type":"get_state"}}
expect "key":"k-helpers-0000000002","payload":{"type":"response","command":"get_state","success":true
send {"type":"sync","session":"$DB/$H1","seq":-1,"key":"k-follow-helper-0001"}
expect "text":"helper 1"
expect {"type":"sync","session":"$DB/$H1"
EOS
done_ok $PR "get_state's helpers"
grep -F '"key":"k-helpers-0000000002"' "$T/ph1.run" | tail -1 | grep -qF '"helpers"' && fail "get_state: a helper with none has helpers"
grep -F '"key":"k-helpers-0000000001"' "$T/ph1.run" | tail -1 | sed 's/^<- //' > "$T/helpers.json"
[ "$(hl "count(*)")" = 3 ] || fail "get_state's helpers: $(cat "$T/helpers.json")"
[ "$(hl "json_extract(value, '\$.title') || ':' || json_extract(value, '\$.state')" | LC_ALL=C sort | tr '\n' '|')" = \
    "helper 1:running|helper 2:running|helper:idle|" ] || fail "get_state's helpers: titles and states: $(cat "$T/helpers.json")"
[ "$(hl "min(json_extract(value, '\$.session') LIKE '$DB/%')")" = 1 ] ||
    fail "get_state's helpers: sessions: $(cat "$T/helpers.json")"
[ "$(hl "json_extract(value, '\$.title')" | tail -1)" = helper ] ||
    fail "get_state's helpers: not newest first: $(cat "$T/helpers.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"
script "$T/ph1" <<EOS
cmd k-helpers-0000000003 {"type":"command","session":"$DB/$PSID","key":"k-helpers-0000000003","payload":{"type":"get_state"}}
expect "key":"k-helpers-0000000003","payload":{"type":"response","command":"get_state","success":true
EOS
done_ok $PR "get_state's helpers after"
grep -F '"key":"k-helpers-0000000003"' "$T/ph1.run" | tail -1 | sed 's/^<- //' > "$T/helpers.json"
[ "$(hl "count(*)")" = 3 ] && [ "$(hl "max(json_extract(value, '\$.running'))")" = 0 ] || fail "get_state's helpers: after they ended: $(cat "$T/helpers.json")"
# A helper is followed, not driven: pic remote allows only read-only get_* commands on it.
NH1=$(q "SELECT count(*) FROM pic_submission WHERE session_id = '$H1'")
NSES=$(q "SELECT count(*) FROM pic_session")
script "$T/ph1" <<EOS
cmd k-helpers-ro-000001 {"type":"command","session":"$DB/$H1","key":"k-helpers-ro-000001","payload":{"type":"prompt","message":"go on"}}
expect "key":"k-helpers-ro-000001","payload":{"code":"bad_command"
cmd k-helpers-ro-000002 {"type":"command","session":"$DB/$H1","key":"k-helpers-ro-000002","payload":{"type":"abort"}}
expect "key":"k-helpers-ro-000002","payload":{"code":"bad_command"
cmd k-helpers-ro-000003 {"type":"command","session":"$DB/$H1","key":"k-helpers-ro-000003","payload":{"type":"archive_session"}}
expect "key":"k-helpers-ro-000003","payload":{"code":"bad_command"
cmd k-helpers-ro-000004 {"type":"command","session":"$DB/$H1","key":"k-helpers-ro-000004","payload":{"type":"delete_session"}}
expect "key":"k-helpers-ro-000004","payload":{"code":"bad_command"
cmd k-helpers-ro-000005 {"type":"command","session":"$DB/$H1","key":"k-helpers-ro-000005","payload":{"type":"fork_session"}}
expect "key":"k-helpers-ro-000005","payload":{"code":"bad_command"
cmd k-helpers-ro-000006 {"type":"command","session":"$DB/$H1","key":"k-helpers-ro-000006","payload":{"type":"answer","id":"ask-1","value":"yes"}}
expect "key":"k-helpers-ro-000006","payload":{"code":"bad_command"
cmd k-helpers-ro-000007 {"type":"command","session":"$DB/$H1","key":"k-helpers-ro-000007","payload":{"type":"pause_wakes"}}
expect "key":"k-helpers-ro-000007","payload":{"code":"bad_command"
EOS
done_ok $PR "a helper is read-only"
[ "$(q "SELECT count(*) FROM pic_submission WHERE session_id = '$H1'")" = "$NH1" ] || fail "helpers: a prompt from the phone was taken"
[ "$(q "SELECT count(*) FROM pic_archive WHERE session_id = '$H1'")" = 0 ] || fail "helpers: archived"
[ "$(q "SELECT count(*) FROM pic_trash WHERE session_id = '$H1'")" = 0 ] || fail "helpers: deleted"
[ "$(q "SELECT count(*) FROM pic_session")" = "$NSES" ] || fail "helpers: forked"
printf 'PASS: pic remote refuses mutating commands (prompt, abort, archive, delete, fork) on a helper\n'
# 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"
script "$T/ph1" <<EOS
cmd k-helpers-0000000004 {"type":"command","session":"$DB/$PSID","key":"k-helpers-0000000004","payload":{"type":"get_state"}}
expect "key":"k-helpers-0000000004","payload":{"type":"response","command":"get_state","success":true
EOS
done_ok $PR "get_state's helpers, no origins"
grep -F '"key":"k-helpers-0000000004"' "$T/ph1.run" | tail -1 | grep -qF '"helpers"' && fail "get_state: helpers with no record of origins"
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'
printf 'PASS: get_state lists a conversation'"'"'s helpers, running or ended, newest first, and the phone follows one\n'
kill "$spid" 2> /dev/null
DB=$SAVE_DB WS=$SAVE_WS LOG=$SAVE_LOG spid=$SAVE_SPID PIC_MODELS_FILE=$SAVE_MODELS

kill "$RP"
gone "$RP"
"$PIC" remote reset > /dev/null

# /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 Turn remote control off? [y/N]' 'send y' '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