Skip to content
pi-c Artifact [a7bc868a63]
Login

Artifact [a7bc868a63]

Artifact a7bc868a6357166f2f99cb41e4d076bb0d6ff4eed4bbc4573e4ee72356009428:


#!/bin/sh
# Remote control journal migrations, new conversations, skills/commands, folders, and workspaces.
# Usage: test/pic/remote_folders.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-folders.XXXXXX")
export HOME="$T/home"
. "$here/remote_lib.sh"

init_paired 1

serve "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"
cur=$(q "SELECT value FROM pic_meta WHERE key='schema_version'")
remote

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

# A phone's prompt naming a skill or a prompt template reaches the model expanded, as pic ask
# expands it: in a conversation it continues and in one it starts, and the journal keeps the
# expanded text. An unknown /name is sent as typed, as Pi's.
W2_DB=$DB W2_WS=$WS W2_LOG=$LOG W2_MODELS=$PIC_MODELS_FILE W2_SPID=$spid
spid=
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse"
cp "$T/models1.json" "$T/models1.keep" # the file pic remote's runs read: this server, for now
cp "$PIC_MODELS_FILE" "$T/models1.json"
mkdir -p "$HOME/.pic/skills/bellard" "$HOME/.pic/prompts"
printf -- '---\nname: bellard\ndescription: Small and exact\n---\n\n# Bellard\nKeep it small.\n' > "$HOME/.pic/skills/bellard/SKILL.md"
printf -- '---\ndescription: Review a change\n---\nReview $1 with care.\n' > "$HOME/.pic/prompts/review.md"
pic ask 'skills here' > /dev/null 2> "$T/ask4.err" || fail "ask: $(cat "$T/ask4.err")"
W4=$DB
SESSK="$DB/$(q "SELECT id FROM pic_session")"
sleep 1.5 # pic remote reads the registry again within a second of a change
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "id":"$W4"
send {"type":"sync","session":"$SESSK","seq":-1}
expect "running":false
cmd k-skill-0000000001 {"type":"command","session":"$SESSK","key":"k-skill-0000000001","payload":{"type":"prompt","message":"/skill:bellard check this"}}
expect "command":"prompt","success":true
seen :k-skill-0000000001","status":"answered"
cmd k-skill-0000000002 {"type":"command","session":"+$W4","key":"k-skill-0000000002","payload":{"type":"prompt","message":"/review the diff"}}
expect "key":"k-skill-0000000002","session":"$W4/
EOS
done_ok $PR "skill"
# The / menu's list (#125): get_commands, answered as pic --mode rpc answers it, for a conversation
# and for a workspace before one is made there: the person's and that workspace's (not another's,
# and not an untrusted project's), each name, description and hint without control characters and
# cut at 200 bytes on a character, with an ellipsis; nothing is made.
mkdir -p "$W2_WS/.pic/prompts" "$WS/.pic/prompts"
printf -- '---\ndescription: From elsewhere\n---\nElsewhere.\n' > "$W2_WS/.pic/prompts/elsewhere.md"
printf -- '---\ndescription: Not trusted\n---\nNo.\n' > "$WS/.pic/prompts/untrusted.md"
"$PIC" --workspace "$W2_WS" trust yes > /dev/null 2>&1 || fail "commands: trusting another workspace"
"$PIC" --workspace "$WS" trust no > /dev/null 2>&1 || fail "commands: not trusting this one"
lpad=$(i=0; while [ $i -lt 300 ]; do printf 'é'; i=$((i + 1)); done)
printf -- '---\ndescription: a\007b\033]0;x\007c\342\200\256%s\n---\nLong.\n' "$lpad" > "$HOME/.pic/prompts/long.md"
LWANT="ab]0;xc$(printf '%s' "$lpad" | head -c 190)…"
script "$T/ph1" <<EOS
cmd k-commands-000001 {"type":"command","session":"$SESSK","key":"k-commands-000001","payload":{"type":"get_commands"}}
expect "key":"k-commands-000001","payload":{"type":"response","command":"get_commands","success":true,"data":{"commands":[
seen {"name":"review","description":"Review a change","source":"prompt"
seen {"name":"skill:bellard","description":"Small and exact","source":"skill"
cmd k-commands-000002 {"type":"command","session":"+$W4","key":"k-commands-000002","payload":{"type":"get_commands"}}
expect "key":"k-commands-000002","payload":{"type":"response","command":"get_commands","success":true,"data":{"commands":[
EOS
done_ok $PR "commands"
grep -F '"key":"k-commands-000002"' "$T/ph1.run" | grep -qF '"name":"skill:bellard"' || fail "commands: +W: $(grep -F k-commands-000002 "$T/ph1.run" | cut -c1-300)"
grep -F '"key":"k-commands-000001"' "$T/ph1.run" | sed 's/^<- //' > "$T/commands.json"
cq() { # WHAT [WHERE]: of the commands the phone got
    "$SQLITE3" :memory: "SELECT $1 FROM json_each(json(readfile('$T/commands.json')), '\$.payload.data.commands') ${2:+WHERE $2}"
}
[ "$(cq "count(*)" | head -1)" -ge 3 ] || fail "commands: $(cut -c1-300 "$T/commands.json")"
[ "$(cq "json_extract(value, '\$.description')" "json_extract(value, '\$.name') = 'long'")" = "$LWANT" ] ||
    fail "commands: the long description: $(cq "json_extract(value, '\$.description')" "json_extract(value, '\$.name') = 'long'")"
[ "$(cq "max(length(CAST(json_extract(value, '\$.description') AS BLOB)))")" -le 200 ] || fail "commands: a description over 200 bytes"
grep -qF 'elsewhere' "$T/commands.json" && fail "commands: another workspace's command"
grep -qF 'untrusted' "$T/commands.json" && fail "commands: an untrusted project's command"
grep -qF '\u001b' "$T/commands.json" && fail "commands: a control character reached the phone"
[ -e "$WS/.pic/journal.sqlite" ] && fail "commands: +W made a journal"
rm -rf "$W2_WS/.pic/prompts" "$WS/.pic/prompts" "$HOME/.pic/prompts/long.md"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-skill-0000000002'" answered
grep -qF "<skill name=\\\"bellard\\\" location=\\\"$HOME/.pic/skills/bellard/SKILL.md\\\">\\nReferences are relative to $HOME/.pic/skills/bellard.\\n\\n# Bellard\\nKeep it small.\\n</skill>\\n\\ncheck this" "$LOG/2.req" ||
    fail "skill: the model got $(grep -o '"messages".*' "$LOG/2.req" | cut -c1-300)"
grep -qF '/skill:bellard' "$LOG/2.req" && fail "skill: the command reached the model as typed"
grep -qF 'Review the with care.' "$LOG/3.req" || fail "template: the model got $(grep -o '"messages".*' "$LOG/3.req" | cut -c1-300)"
[ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body LIKE '<skill name=\"bellard\"%check this'")" = 1 ] ||
    fail "skill: the journal does not keep the expanded text: $(q "SELECT body FROM pic_entry WHERE kind = 'user'")"
script "$T/ph1" <<EOS
send {"type":"sync","session":"$SESSK","seq":-1}
expect "running":false
cmd k-skill-0000000003 {"type":"command","session":"$SESSK","key":"k-skill-0000000003","payload":{"type":"prompt","message":"/nosuch x"}}
expect "command":"prompt","success":true
seen :k-skill-0000000003","status":"answered"
EOS
done_ok $PR "unknown template"
grep -qF '"/nosuch x"' "$LOG/4.req" || fail "unknown: the model got $(grep -o '"messages".*' "$LOG/4.req" | cut -c1-300)"
rm -rf "$HOME/.pic/skills/bellard" "$HOME/.pic/prompts/review.md"
mv -f "$T/models1.keep" "$T/models1.json"
kill "$spid" 2> /dev/null
DB=$W2_DB WS=$W2_WS LOG=$W2_LOG PIC_MODELS_FILE=$W2_MODELS spid=$W2_SPID
printf 'PASS: a phone prompt naming a skill or a template reaches the model expanded, in a conversation and a new one\n'

# A phone starts a conversation in a folder pic has not run in yet, among the immediate subfolders
# of remote.folders (unset: the folders holding the workspaces pic knows, never the home folder or
# above it, nor a temporary one), and its journal is made then, as running pic there makes it. A
# hidden folder, a link out of the folder, a path through .. and anything else are never offered
# and never made; a folder that becomes a workspace is listed as one.
W5_DB=$DB W5_WS=$WS W5_LOG=$LOG W5_MODELS=$PIC_MODELS_FILE W5_SPID=$spid
spid=
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse"
sed 's/"models":\[{"id":"m"}\]/"models":[{"id":"m"},{"id":"m2","reasoning":true}]/' "$PIC_MODELS_FILE" > "$T/models-f.json"
export PIC_MODELS_FILE="$T/models-f.json"
cp "$T/models1.json" "$T/models1.keep" # the file pic remote's runs read: this server, for now
cp "$PIC_MODELS_FILE" "$T/models1.json"
RT=$(cd "$T" && pwd -P)
mkdir -p "$T/proj/alpha" "$T/proj/beta" "$T/proj/.hidden" "$T/outside" "$T/other/gamma"
ln -s "$T/outside" "$T/proj/away"
ln -s "$T/proj/beta" "$T/proj/beta-too"
"$PIC" --workspace "$T/proj/alpha" check > /dev/null 2>&1 || fail "folders: check in alpha"
"$PIC" settings defaultModel fake/m > /dev/null # a new journal's first request: no conversation to take a model from
sleep 1.5 # pic remote reads the registry again within a second of a change
folders() { # NAME: the folders of the last sessions the phone got, one id a line, in NAME.ids
    grep -F '"folders":[' "$T/ph1.run" | tail -1 | sed 's/^<- //' > "$T/$1.json"
    "$SQLITE3" :memory: "SELECT json_extract(value, '\$.id') || ' ' || json_extract(value, '\$.name') || ' ' ||
        json_extract(value, '\$.root') FROM json_each(json(readfile('$T/$1.json')), '\$.payload.folders')" > "$T/$1.ids"
}
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "folders":[
EOS
done_ok $PR "folders"
folders fl1
grep -qxF "$RT/proj/beta beta $RT/proj" "$T/fl1.ids" || fail "folders: beta not offered: $(cat "$T/fl1.ids")"
[ "$(grep -c "^$RT/proj/" "$T/fl1.ids")" = 1 ] || fail "folders: more than beta under proj: $(cat "$T/fl1.ids")"
grep -qF "$RT/outside" "$T/fl1.ids" && fail "folders: a link out offered: $(cat "$T/fl1.ids")"
grep -q "^$RT/[^/ ]* " "$T/fl1.ids" && fail "folders: the home folder's own folder offered: $(cat "$T/fl1.ids")"
# Before anything is made there (#123): a folder's models, levels and keys, with the model a new
# conversation there starts on (the saved default: the folder has no request to take one from); a
# choice that is not one is refused, and no journal is made.
script "$T/ph1" <<EOS
cmd k-choice-models-01 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-models-01","payload":{"type":"get_available_models"}}
expect "key":"k-choice-models-01","payload":{"type":"response","command":"get_available_models","success":true,"data":{"models":[
seen "model":{"id":"m","name":"m","api":"anthropic-messages","provider":"fake"
seen "thinkingLevel":null,"missing":[
cmd k-choice-levels-01 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-levels-01","payload":{"type":"get_available_thinking_levels"}}
expect "command":"get_available_thinking_levels","success":true,"data":{"levels":["off"],"model":{"provider":"fake","id":"m"}}
cmd k-choice-levels-02 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-levels-02","payload":{"type":"get_available_thinking_levels","provider":"fake","modelId":"m2"}}
expect "key":"k-choice-levels-02","payload":{"id":null,"type":"response","command":"get_available_thinking_levels","success":true,"data":{"levels":["off",
cmd k-choice-levels-03 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-levels-03","payload":{"type":"get_available_thinking_levels","provider":"fake","modelId":"nope"}}
expect "key":"k-choice-levels-03","payload":{"type":"response","command":"get_available_thinking_levels","success":false,"error":"Model not found: fake/nope"}
cmd k-choice-levels-04 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-levels-04","payload":{"type":"get_available_thinking_levels","provider":"fake"}}
expect {"type":"error","key":"k-choice-levels-04","payload":{"code":"bad_command","message":"provider and modelId must be strings"}}
cmd k-choice-creds-001 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-creds-001","payload":{"type":"get_credentials"}}
expect "command":"get_credentials","success":true,"data":{"credentials":[
cmd k-choice-stats-001 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-stats-001","payload":{"type":"get_session_stats"}}
expect {"type":"error","key":"k-choice-stats-001","payload":{"code":"bad_command"
cmd k-choice-bad-00001 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-bad-00001","payload":{"type":"prompt","message":"x","provider":"fake","modelId":"nope"}}
expect "key":"k-choice-bad-00001","payload":{"type":"response","command":"prompt","success":false,"error":"Model not found: fake/nope"}
cmd k-choice-bad-00002 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-bad-00002","payload":{"type":"prompt","message":"x","thinkingLevel":"loud"}}
expect "error":"Invalid thinking level: loud
cmd k-choice-bad-00006 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-bad-00006","payload":{"type":"prompt","message":"x","thinkingLevel":"low"}}
expect "error":"thinking level low is not supported by fake/m (supported: off)"
cmd k-choice-bad-00003 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-bad-00003","payload":{"type":"prompt","message":"x","provider":"fake","modelId":"m","credential":"nosuch"}}
expect "error":"fake has no key named \"nosuch\""
cmd k-choice-bad-00004 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-bad-00004","payload":{"type":"prompt","message":"x","credential":"env"}}
expect {"type":"error","key":"k-choice-bad-00004","payload":{"code":"bad_command","message":"a credential is chosen with its model: send provider and modelId with it"}}
cmd k-choice-bad-00005 {"type":"command","session":"+$RT/proj/beta","key":"k-choice-bad-00005","payload":{"type":"prompt","message":"x","provider":"fake"}}
expect {"type":"error","key":"k-choice-bad-00005","payload":{"code":"bad_command","message":"provider and modelId must be strings"}}
EOS
done_ok $PR "choices for a folder"
grep -F '"key":"k-choice-levels-02"' "$T/ph1.run" | grep -F '"high"' | grep -qF '"model":{"provider":"fake","id":"m2"}' || fail "choices: m2's levels: $(grep -F k-choice-levels-02 "$T/ph1.run" | cut -c1-300)"
[ -e "$RT/proj/beta/.pic" ] && fail "choices: a refused choice made beta's journal"
script "$T/ph1" <<EOS
send {"type":"command","session":"+$RT/proj/../outside","key":"k-folder-00000001","payload":{"type":"prompt","message":"x"}}
expect {"type":"error","key":"k-folder-00000001","payload":{"code":"no_session"
send {"type":"command","session":"+$RT/outside","key":"k-folder-00000002","payload":{"type":"prompt","message":"x"}}
expect {"type":"error","key":"k-folder-00000002","payload":{"code":"no_session"
send {"type":"command","session":"+$RT/proj/away","key":"k-folder-00000003","payload":{"type":"prompt","message":"x"}}
expect {"type":"error","key":"k-folder-00000003","payload":{"code":"no_session"
send {"type":"command","session":"+$RT/proj/.hidden","key":"k-folder-00000004","payload":{"type":"prompt","message":"x"}}
expect {"type":"error","key":"k-folder-00000004","payload":{"code":"no_session"
cmd k-folder-00000005 {"type":"command","session":"+$RT/proj/beta","key":"k-folder-00000005","payload":{"type":"prompt","message":"in a new folder"}}
expect "key":"k-folder-00000005","session":"$RT/proj/beta/.pic/journal.sqlite/
EOS
done_ok $PR "a new folder"
BJ="$RT/proj/beta/.pic/journal.sqlite"
for d in "$RT/outside" "$RT/proj/away" "$RT/proj/.hidden"; do [ -e "$d/.pic" ] && fail "folders: made $d/.pic"; done
i=0
until [ "$("$SQLITE3" -cmd ".timeout 10000" "$BJ" "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-folder-00000005'" 2> /dev/null)" = answered ]; do
    i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "folders: the request in beta: $("$SQLITE3" "$BJ" 'SELECT status, error FROM pic_submission' 2>&1)"; sleep 0.05
done
[ "$(cat "$RT/proj/beta/.pic/.gitignore")" = '*' ] || fail "folders: beta's .pic does not ignore itself"
[ "$(uq "SELECT count(*) FROM picu_workspace WHERE path = '$RT/proj/beta'")" = 1 ] || fail "folders: beta is not registered"
sleep 1.5
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "folders":[
send {"type":"command","session":"+$RT/proj/beta","key":"k-folder-00000005","payload":{"type":"prompt","message":"in a new folder"}}
expect "key":"k-folder-00000005","session":"$RT/proj/beta/.pic/journal.sqlite/
EOS
done_ok $PR "folders again"
[ "$("$SQLITE3" -cmd ".timeout 10000" "$BJ" "SELECT count(*) FROM pic_submission")" = 1 ] || fail "folders: the key again started another request"
grep -F '"folders":[' "$T/ph1.run" | tail -1 | grep -qF "\"id\":\"$BJ\",\"workspace\":\"$RT/proj/beta\"" ||
    fail "folders: beta is not a workspace now: $(grep -F '"folders":[' "$T/ph1.run" | tail -1)"
folders fl2
grep -qF "$RT/proj/beta" "$T/fl2.ids" && fail "folders: beta is still a folder: $(cat "$T/fl2.ids")"
# A new conversation in a workspace on the phone's choice (#123): the workspace's models say what one
# starts on (its last request's model); the prompt's model, level and key are its first request's,
# and its key again, even with another choice, starts nothing more. The key is an extra one of the
# provider's while the provider's own key is the one a request goes with by default, so the next
# request, with nothing chosen, going on with it is the conversation keeping its key. A model chosen
# without a level gets one it thinks at, not the workspace's last; a key of another provider is not
# the model's.
printf '%s\n' "$ANTHROPIC_API_KEY" | "$PIC" auth login fake --api-key > /dev/null 2> "$T/second.err" || fail "choices: fake's own key: $(cat "$T/second.err")"
printf '%s\n' "$ANTHROPIC_API_KEY" | "$PIC" auth login fake --api-key --as second > /dev/null 2> "$T/second.err" || fail "choices: a second key: $(cat "$T/second.err")"
printf '%s\n' "$ANTHROPIC_API_KEY" | "$PIC" auth login anthropic --api-key --as other > /dev/null 2> "$T/second.err" || fail "choices: another provider's key: $(cat "$T/second.err")"
script "$T/ph1" <<EOS
cmd k-choice-models-02 {"type":"command","session":"+$BJ","key":"k-choice-models-02","payload":{"type":"get_available_models"}}
expect "key":"k-choice-models-02","payload":{"type":"response","command":"get_available_models","success":true
seen "model":{"id":"m","name":"m","api":"anthropic-messages","provider":"fake"
cmd k-choice-bad-00007 {"type":"command","session":"+$BJ","key":"k-choice-bad-00007","payload":{"type":"prompt","message":"x","provider":"fake","modelId":"m","credential":"other"}}
expect "error":"fake has no key named \"other\""
cmd k-choice-bad-00008 {"type":"command","session":"+$BJ","key":"k-choice-bad-00008","payload":{"type":"prompt","message":"x","provider":"fake/m","modelId":"m2"}}
expect "error":"Model not found: fake/m/m2"
cmd k-choice-new-00001 {"type":"command","session":"+$BJ","key":"k-choice-new-00001","payload":{"type":"prompt","message":"on my choice","provider":"fake","modelId":"m2","thinkingLevel":"high","credential":"second"}}
expect "key":"k-choice-new-00001","session":"$BJ/
send {"type":"command","session":"+$BJ","key":"k-choice-new-00001","payload":{"type":"prompt","message":"on my choice","provider":"fake","modelId":"m","thinkingLevel":"off"}}
waitcount "key":"k-choice-new-00001","session":"$BJ/ 2
EOS
done_ok $PR "a choice for a new conversation"
bq() { "$SQLITE3" -cmd ".timeout 10000" "$BJ" "$1"; }
answered() { # KEY: wait for the phone's request under KEY to be answered
    i=0
    until [ "$(bq "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:$1'" 2> /dev/null)" = answered ]; do
        i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "choices: $1: $(bq 'SELECT request_key, status, error FROM pic_submission' 2>&1)"; sleep 0.05
    done
}
ran_on() { # KEY: the model, level and key its request went with
    bq "SELECT u.model || ' ' || coalesce(u.thinking, '') || ' ' || coalesce((SELECT group_concat(DISTINCT g.credential) FROM pic_generation g
        WHERE g.submission_id = u.id), '') FROM pic_submission u WHERE u.request_key LIKE 'rc:%:$1'"
}
answered k-choice-new-00001
[ "$(bq "SELECT count(*) FROM pic_submission WHERE request_key LIKE 'rc:%:k-choice-new-00001'")" = 1 ] || fail "choices: requests: $(bq 'SELECT request_key FROM pic_submission')"
[ "$(ran_on k-choice-new-00001)" = 'fake/m2 high fake:second' ] || fail "choices: the first request: $(ran_on k-choice-new-00001)"
[ "$(bq "SELECT count(*) FROM pic_submission WHERE request_key LIKE 'rc:%:k-choice-bad-%'")" = 0 ] || fail "choices: a refused prompt was admitted"
NEWC=$(bq "SELECT session_id FROM pic_submission WHERE request_key LIKE 'rc:%:k-choice-new-00001'")
script "$T/ph1" <<EOS
cmd k-choice-next-0001 {"type":"command","session":"$BJ/$NEWC","key":"k-choice-next-0001","payload":{"type":"prompt","message":"and then"}}
expect "key":"k-choice-next-0001","session":"$BJ/$NEWC","payload":{"type":"response","command":"prompt","success":true
cmd k-choice-clamp-001 {"type":"command","session":"+$BJ","key":"k-choice-clamp-001","payload":{"type":"prompt","message":"plain","provider":"fake","modelId":"m"}}
expect "key":"k-choice-clamp-001","session":"$BJ/
EOS
done_ok $PR "a choice carries on"
answered k-choice-next-0001
[ "$(ran_on k-choice-next-0001)" = 'fake/m2 high fake:second' ] || fail "choices: the next request: $(ran_on k-choice-next-0001)"
answered k-choice-clamp-001
[ "$(ran_on k-choice-clamp-001)" = 'fake/m off fake' ] || fail "choices: a model chosen without a level: $(ran_on k-choice-clamp-001)"
"$PIC" auth logout fake:second > /dev/null 2>&1 || fail "choices: removing the second key"
# the conversation's key gone: its next prompt is refused, never sent on another key, nothing admitted
script "$T/ph1" <<EOS
cmd k-choice-gone-0001 {"type":"command","session":"$BJ/$NEWC","key":"k-choice-gone-0001","payload":{"type":"prompt","message":"once more"}}
expect "key":"k-choice-gone-0001","payload":{"type":"response","command":"prompt","success":false,"error":"The key \"second\" this conversation went with is gone from fake: choose another with set_credential."}}
EOS
done_ok $PR "a conversation's key gone"
[ "$(bq "SELECT count(*) FROM pic_submission WHERE request_key LIKE 'rc:%:k-choice-gone-0001'")" = 0 ] || fail "choices: a prompt was admitted without its conversation's key"
"$PIC" auth logout fake > /dev/null 2>&1 || fail "choices: removing fake's own key"
"$PIC" auth logout anthropic:other > /dev/null 2>&1 || fail "choices: removing anthropic's key"
printf 'PASS: a phone chooses the model, level and key of a new conversation, which keeps them; models and keys answer for a workspace or folder; a bad choice makes nothing\n'
"$PIC" settings remote.folders "$T/other" > /dev/null || fail "folders: the setting"
sleep 1.5
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "folders":[
EOS
done_ok $PR "the setting"
folders fl3
[ "$(cat "$T/fl3.ids")" = "$RT/other/gamma gamma $RT/other" ] || fail "folders: remote.folders: $(cat "$T/fl3.ids")"
"$PIC" settings --unset remote.folders > /dev/null || fail "folders: unset"
"$PIC" settings --unset defaultModel > /dev/null
mv -f "$T/models1.keep" "$T/models1.json"
kill "$spid" 2> /dev/null
DB=$W5_DB WS=$W5_WS LOG=$W5_LOG PIC_MODELS_FILE=$W5_MODELS spid=$W5_SPID
printf 'PASS: a phone starts a conversation in a subfolder of remote.folders, its journal made then; nothing outside is offered or made\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