Skip to content
pi-c Artifact [1fbcad489d]
Login

Artifact [1fbcad489d]

Artifact 1fbcad489d6024a2066496313d2f26b7a6d5e812e3859457df194816a03af884:


#!/bin/sh
# Remote control Web Push notifications, loops, asks, asks fixture, and permissions.
# Usage: test/pic/remote_notify.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-notify.XXXXXX")
export HOME="$T/home"
. "$here/remote_lib.sh"

init_paired 1

# Notifications: a phone's subscription, sealed in its row, gets one line when a request ends (the
# conversation's title, the reply's first line), as its notify and remote.notify allow, and none
# while the page is showing; a push service that says the subscription is gone ends it. pic
# remote's look at the user database is slowed (2.5 s each), so remote.notify is seen as it is when
# a request ends, never as a look made before had it.
spid=
serve "sse:$S/text.sse"
pic ask 'push first' > /dev/null 2> "$T/askp.err" || fail "ask: $(cat "$T/askp.err")"
SIDP=$(q "SELECT id FROM pic_session")
SESSP="$DB/$SIDP"
export PIC_TEST_RC_JOB_MS="reading the paired devices and workspaces:2500"
remote
unset PIC_TEST_RC_JOB_MS
mkdir "$T/plog"
"$SERVER" "$T/pport" "$T/plog" 3600 status:201:- status:201:- status:201:- status:410:- status:201:- &
bg $!
i=0; until [ -s "$T/pport" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "push service did not start"; sleep 0.05; done
EP="http://127.0.0.1:$(cat "$T/pport")/push/ph1"
pushes() { ls "$T/plog" | grep -c '\.req$' || true; }
# Every request of this run's journals over, and pic remote past their ends: a request an earlier
# case left running (its provider gone, retrying) would otherwise end here and be notified too.
settle() {
    for f in "$T"/*.sqlite $(find "$T" -path '*/.pic/journal.sqlite' 2> /dev/null); do
        i=0
        while :; do
            running=$("$SQLITE3" -cmd ".timeout 10000" "$f" "SELECT count(*) FROM pic_submission WHERE status = 'admitted'" 2> /dev/null || :)
            [ -z "$running" ] || [ "$running" = 0 ] && break
            i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "settle: $f still runs a request"; sleep 0.05
        done
    done
    sleep 2
}
settle
none_for() { # MS: no push arrives for that long
    sleep "$1"
    [ "$(pushes)" = "$2" ] || fail "push: $(pushes) pushes, not $2"
}
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$SESSP"
send {"type":"push","payload":{"subscription":{"endpoint":"https://10.0.0.1/x","keys":{"p256dh":"AAAA","auth":"AAAA"}}}}
expect "code":"bad_message"
send $("$PHONE" "$T/ph1" pushkeys "$EP")
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "push: subscribe"
"$PIC" remote devices --json | grep -qF '"name":"Phone One","pairedMs"' || fail "push: devices"
i=0 # the row is written by a job of the user database, after the pong
until "$PIC" remote devices --json | grep -F '"notify":"all"' > /dev/null; do
    i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "push: notify: $("$PIC" remote devices --json)"; sleep 0.05
done
uq "SELECT sealed FROM picu_remote_device" | grep -qF 'push/ph1' && fail "push: the subscription is not sealed"
# A request at the terminal ends: one push, its line decrypted as the phone's browser does.
pic ask --session "$SIDP" 'from the desk' > /dev/null 2> "$T/askp2.err" || fail "ask: $(cat "$T/askp2.err")"
await "$T/plog/1.req" 'Content-Length'
"$PHONE" "$T/ph1" pushread "$T/plog/1.req" > "$T/push1.json" || fail "push: does not open"
# The title is the conversation's: its first prompt's first line, as no name was given.
[ "$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/push1.json'), '\$.v') || '|' || json_extract(readfile('$T/push1.json'), '\$.title') || '|' ||
    json_extract(readfile('$T/push1.json'), '\$.body') || '|' || json_extract(readfile('$T/push1.json'), '\$.session')")" = "1|push first|Hello, \"world\"|$SESSP" ] ||
    fail "push: plaintext: $(cat "$T/push1.json")"
[ "$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/push1.json'), '\$.seq') = (SELECT 0)")" = 0 ] || fail "push: no seq"
grep -qF 'TTL: 3600' "$T/plog/1.req" && grep -qF 'Urgency: normal' "$T/plog/1.req" && grep -q '^Topic: [A-Za-z0-9_-]\{22\}' "$T/plog/1.req" &&
    grep -qF 'Authorization: vapid t=' "$T/plog/1.req" || fail "push: headers: $(head -12 "$T/plog/1.req")"
grep -aqF 'from the desk' "$T/plog/1.req" && fail "push: the prompt reached the push service"
printf 'PASS: a request that ends sends the phone one sealed line: the title, the reply'"'"'s first line, the conversation\n'
# notify remote: a request at the terminal sends nothing; one from the phone does. The choice holds
# from the message on, even while another process holds the user database past pic remote's write
# of it (here 6 s): the write is tried again, the choice never put back.
rm -f "$T/uhold.in"
mkfifo "$T/uhold.in"
"$SQLITE3" "$HOME/.pic/pic.sqlite" < "$T/uhold.in" > "$T/uhold.out" 2>&1 &
UHOLD=$!
bg $UHOLD
exec 5> "$T/uhold.in"
printf 'BEGIN IMMEDIATE; UPDATE picu_setting SET updated_ms = updated_ms;\nSELECT 1;\n' >&5
await "$T/uhold.out" 1
script "$T/ph1" <<EOS
send $("$PHONE" "$T/ph1" pushkeys "$EP" remote)
send {"type":"ping"}
expect {"type":"pong"}
sleep 6000
EOS
done_ok $PR "push: remote"
printf 'COMMIT;\n' >&5
exec 5>&-
gone $UHOLD
pic ask --session "$SIDP" 'desk again' > /dev/null 2> "$T/askp3.err" || fail "ask: $(cat "$T/askp3.err")"
none_for 1.5 1
script "$T/ph1" <<EOS
cmd k-push-00000000001 {"type":"command","session":"$SESSP","key":"k-push-00000000001","payload":{"type":"prompt","message":"from the phone"}}
expect "command":"prompt","success":true
EOS
done_ok $PR "push: phone prompt"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-push-00000000001'" answered
await "$T/plog/2.req" 'Content-Length'
"$PHONE" "$T/ph1" pushread "$T/plog/2.req" | grep -qF '"body":"Hello, \"world\""' || fail "push: remote: $("$PHONE" "$T/ph1" pushread "$T/plog/2.req")"
printf 'PASS: a phone that asks only for its own requests is not sent the terminal'"'"'s\n'
# remote.notify off: nothing; the page showing: nothing; hidden again: a push.
"$PIC" settings remote.notify off > /dev/null
script "$T/ph1" <<EOS
cmd k-push-00000000002 {"type":"command","session":"$SESSP","key":"k-push-00000000002","payload":{"type":"prompt","message":"muted"}}
expect "command":"prompt","success":true
EOS
done_ok $PR "push: off"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-push-00000000002'" answered
none_for 1.5 2
"$PIC" settings remote.notify all > /dev/null
script "$T/ph1" <<EOS
send {"type":"presence","payload":{"visible":true}}
cmd k-push-00000000003 {"type":"command","session":"$SESSP","key":"k-push-00000000003","payload":{"type":"prompt","message":"looking"}}
expect "command":"prompt","success":true
waitfor $T/go-hidden
send {"type":"presence","payload":{"visible":false}}
cmd k-push-00000000004 {"type":"command","session":"$SESSP","key":"k-push-00000000004","payload":{"type":"prompt","message":"away"}}
expect "command":"prompt","success":true
EOS
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-push-00000000003'" answered
none_for 1.5 2
touch "$T/go-hidden"
done_ok $PR "push: presence"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-push-00000000004'" answered
await "$T/plog/3.req" 'Content-Length'
printf 'PASS: no notification while remote.notify is off or the page is showing; one once it is hidden\n'
# The push service answers 410: the subscription is gone from the row, and nothing more is sent.
script "$T/ph1" <<EOS
cmd k-push-00000000005 {"type":"command","session":"$SESSP","key":"k-push-00000000005","payload":{"type":"prompt","message":"gone"}}
expect "command":"prompt","success":true
EOS
done_ok $PR "push: gone"
await "$T/plog/4.req" 'Content-Length'
await "$RO" 'notifications to Phone One ended'
i=0 # its row rewritten by a job of the user database
while "$PIC" remote devices --json | grep -qF '"notify":"'; do
    i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "push: gone: still subscribed: $("$PIC" remote devices --json)"; sleep 0.05
done
script "$T/ph1" <<EOS
cmd k-push-00000000006 {"type":"command","session":"$SESSP","key":"k-push-00000000006","payload":{"type":"prompt","message":"after"}}
expect "command":"prompt","success":true
EOS
done_ok $PR "push: after gone"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-push-00000000006'" answered
none_for 1.5 4
printf 'PASS: a subscription the push service says is gone ends; nothing more is sent to it\n'
# Loops with the terminal closed (docs/design/wakes.md): pic remote fires a due loop and starts its
# request; the phone sees how many loops a conversation has, lists them and pauses, resumes and
# stops one; one of another conversation is refused; a loop that comes to need a person is one
# notification.
mkdir "$T/plog2"
"$SERVER" "$T/pport2" "$T/plog2" 300 status:201:- status:201:- status:201:- status:201:- status:201:- &
bg $!
i=0; until [ -s "$T/pport2" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "push service 2 did not start"; sleep 0.05; done
EP2="http://127.0.0.1:$(cat "$T/pport2")/push/ph1"
script "$T/ph1" <<EOS
send $("$PHONE" "$T/ph1" pushkeys "$EP2")
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "loops: subscribe"
pic loop 5m loop from the remote > "$T/loop.out" 2>&1 || fail "loops: create: $(cat "$T/loop.out")"
SIDL=$(q "SELECT session_id FROM pic_wake")
SESSL="$DB/$SIDL"
until_sql "SELECT status FROM pic_submission WHERE request_key = 'inbox:wake:1:1'" answered
await "$T/plog2/1.req" 'Content-Length'
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "title":"loop from the remote","preview":"Hello, \\"world\\"","state":"idle","workspaceName":"$(basename "$WS")","loops":1}
cmd k-loop-list-000001 {"type":"command","session":"$SESSL","key":"k-loop-list-000001","payload":{"type":"get_wakes"}}
expect "command":"get_wakes","success":true,"data":{"wakes":[{"id":1,"name":"L1","kind":"loop"
cmd k-loop-pause-00001 {"type":"command","session":"$SESSL","key":"k-loop-pause-00001","payload":{"type":"pause_wake","id":"L1"}}
expect "state":"paused","why":"paused from a phone"
cmd k-loop-other-00001 {"type":"command","session":"$SESSP","key":"k-loop-other-00001","payload":{"type":"stop_wake","id":"L1"}}
expect "error":"no loop L1 in this conversation"
cmd k-loop-resume-0001 {"type":"command","session":"$SESSL","key":"k-loop-resume-0001","payload":{"type":"resume_wake","id":"L1"}}
expect "command":"resume_wake","success":true,"data":{"wakes":[{"id":1,"name":"L1","kind":"loop"
EOS
done_ok $PR "loops: phone"
[ "$(q "SELECT state FROM pic_wake")" = active ] || fail "loops: resume: $(q 'SELECT state, why FROM pic_wake')"
q "UPDATE pic_wake SET state = 'needs', why = 'its message was refused: a test', updated_ms = updated_ms + 1000"
await "$T/plog2/2.req" 'Content-Length'
"$PHONE" "$T/ph1" pushread "$T/plog2/2.req" | grep -qF '"body":"Loop L1 needs you: its message was refused: a test"' ||
    fail "loops: push: $("$PHONE" "$T/ph1" pushread "$T/plog2/2.req")"
# a loop the model asked for: the phone starts it
q "UPDATE pic_wake SET state = 'needs', why = 'waiting for your OK', options = json_set(coalesce(options, '{}'), '\$.approval', 'asked')"
script "$T/ph1" <<EOS
cmd k-loop-approve-001 {"type":"command","session":"$SESSL","key":"k-loop-approve-001","payload":{"type":"approve_wake","id":"L1"}}
expect "command":"approve_wake","success":true,"data":{"wakes":[{"id":1,"name":"L1","kind":"loop"
EOS
done_ok $PR "loops: approve"
[ "$(q "SELECT state, json_extract(options, '\$.approval') FROM pic_wake")" = "active|approved" ] || fail "loops: approve: $(q 'SELECT state, options FROM pic_wake')"
script "$T/ph1" <<EOS
cmd k-loop-stop-000001 {"type":"command","session":"$SESSL","key":"k-loop-stop-000001","payload":{"type":"stop_wake","id":"L1"}}
expect "command":"stop_wake","success":true,"data":{"wakes":[],"nowMs":
cmd k-loop-stop-000002 {"type":"command","session":"$SESSL","key":"k-loop-stop-000002","payload":{"type":"stop_wake","id":"L1"}}
expect "command":"stop_wake","success":true
EOS
done_ok $PR "loops: stop"
sleep 1.5
[ "$(ls "$T/plog2" | grep -c '\.req$')" = 2 ] || fail "loops: $(ls "$T/plog2") pushes, not 2"
pic check > /dev/null || fail "loops: integrity"
printf 'PASS: pic remote fires loops with the terminal closed; the phone lists, pauses, resumes and stops them; one that needs you is a notification\n'
# Asks (docs/dev/asks.md): a question the conversation waits on reaches the phone as an ask record
# and one notification in pic's own words; the list counts it and marks the row attention;
# get_state carries it. The phone answers with the command answer under the key ask-ID: an answer
# that is not one is bad_command, the first answer is answered and a resend of its key gets the
# same, a later one already_answered with the one that stands; every phone hears ask_settled with
# who answered. A question that expires unanswered is ask_settled as expired.
NOW=$(($(date +%s) * 1000))
AID=askaskaskaskaskaskask1
q "INSERT INTO pic_ask(id, ask_key, session_id, kind, title, spec, created_ms, expires_ms, state, version) VALUES('$AID', 'test:1', '$SIDL', 'select', 'Which branch?', '{\"options\":[{\"label\":\"main\",\"default\":true},{\"label\":\"dev\"}]}', $NOW, $NOW + 600000, 'open', (SELECT coalesce(max(version), 0) + 1 FROM pic_ask))"
await "$T/plog2/3.req" 'Content-Length'
"$PHONE" "$T/ph1" pushread "$T/plog2/3.req" | grep -qF '"body":"loop from the remote needs your answer"' ||
    fail "asks: push: $("$PHONE" "$T/ph1" pushread "$T/plog2/3.req")"
script "$T/ph1" <<EOS
seen {"type":"ask","session":"$SESSL","payload":{"id":"$AID","kind":"select","title":"Which branch?"
seen "options":[{"label":"main","default":true},{"label":"dev"}]
send {"type":"sessions"}
expect "state":"attention","workspaceName":"$(basename "$WS")","asks":1}
cmd k-ask-state-000001 {"type":"command","session":"$SESSL","key":"k-ask-state-000001","payload":{"type":"get_state"}}
expect "asks":[{"id":"$AID",
send {"type":"command","session":"$SESSL","key":"k-ask-answer-00000","payload":{"type":"answer","id":"nosuchquestionatall000","value":"dev"}}
expect "command":"answer","success":false,"error":"no such question in this conversation"
send {"type":"command","session":"$SESSL","key":"k-ask-answer-00001","payload":{"type":"answer","id":"$AID","value":"other"}}
expect "command":"answer","success":false,"error":"a select is answered with one of its labels"
send {"type":"command","session":"$SESSL","key":"k-ask-answer-00002","payload":{"type":"answer","id":"$AID","value":"$(printf 'z%.0s' $(seq 1 4001))"}}
expect "code":"bad_command"
send {"type":"command","session":"$SESSL","key":"ask-$AID","payload":{"type":"answer","id":"$AID","value":"dev"}}
expect "command":"answer","success":true,"data":{"result":"answered","id":"$AID","value":"dev","by":{"kind":"phone","device":"Phone One","deviceId":"remote:$DEV1B"}}
send {"type":"command","session":"$SESSL","key":"ask-$AID","payload":{"type":"answer","id":"$AID","value":"dev"}}
expect "command":"answer","success":true,"data":{"result":"answered","id":"$AID","value":"dev","by":{"kind":"phone","device":"Phone One","deviceId":"remote:$DEV1B"}}
send {"type":"command","session":"$SESSL","key":"k-ask-answer-00003","payload":{"type":"answer","id":"$AID","value":"main"}}
expect "data":{"result":"already_answered","id":"$AID","value":"dev","by":{"kind":"phone","device":"Phone One","deviceId":"remote:$DEV1B"}}
seen {"type":"ask_settled","session":"$SESSL","payload":{"id":"$AID","value":"dev","by":{"kind":"phone","device":"Phone One","deviceId":"remote:$DEV1B"}}}
EOS
done_ok $PR "asks: phone"
[ "$(q "SELECT state, answer, answered_by LIKE 'remote:%' FROM pic_ask WHERE id = '$AID'")" = 'answered|"dev"|1' ] || fail "asks: row: $(q "SELECT * FROM pic_ask WHERE id = '$AID'")"
NOW=$(($(date +%s) * 1000))
q "INSERT INTO pic_ask(id, ask_key, session_id, kind, title, created_ms, expires_ms, state, version) VALUES('askaskaskaskaskaskask2', 'test:2', '$SIDL', 'confirm', 'Soon gone?', $NOW, $NOW + 2000, 'open', (SELECT max(version) + 1 FROM pic_ask))"
script "$T/ph1" <<EOS
seen {"type":"ask_settled","session":"$SESSL","payload":{"id":"askaskaskaskaskaskask2","value":null,"by":{"kind":"expired","device":null,"deviceId":null}}}
EOS
done_ok $PR "asks: expired"
sleep 1.5
[ "$(ls "$T/plog2" | grep -c '\.req$')" = 4 ] || fail "asks: $(ls "$T/plog2") pushes, not 4"
printf 'PASS: a question reaches the phone as an ask and a notification, is counted in the list and in get_state, and is answered once from the phone; every phone hears how it settled\n'
# The asks fixture, test/pic/remote-asks.json: the records a phone sees about a question, as pic
# wrote them to the phone above (one record a line, nothing reformatted). pic-relay copies the file
# byte for byte, so its page is tested against pic's own records. Ids, times, the journal's path, the
# conversation's id and the device's id are fixed in it. PIC_UPDATE_FIXTURES=1 rewrites it.
FXD=$here/remote-asks.json
FXN=$(($(date +%s) * 1000))
FXC1=fxconfirmyes0000000001 FXC2=fxconfirmno00000000002 FXS=fxselect00000000000003 FXI=fxinput000000000000004
FXD0=fxdismiss0000000000005 FXX=fxexpire00000000000006 FXW=fxcancel00000000000007 FXK=fxwakeloop000000000008
FXT=fxterminal000000000009 FXA=fxattach00000000000010 FXR=fxrpc00000000000000011 FXG=fxunknown0000000000012
for id in $FXC1 $FXC2 $FXS $FXI $FXD0 $FXX $FXW $FXK $FXT $FXA $FXR $FXG; do [ "${#id}" = 22 ] || fail "asks fixture: $id is not 22 characters"; done
q "INSERT INTO pic_submission(request_key, content, status, session_id) VALUES('fx:run', '{}', 'answered', '$SIDL')"
FXSUB=$(q "SELECT id FROM pic_submission WHERE request_key = 'fx:run'")
fx_ask() { # ID KIND TITLE BODY SPEC EXPIRES [STATE [ANSWER BY [KEY]]]: ANSWER is JSON text
    fxa=NULL fxms=NULL
    [ -z "${8:-}" ] || { fxa="'$8'"; fxms=$FXN; }
    q "INSERT INTO pic_ask(id, ask_key, session_id, submission_id, kind, title, body, spec, created_ms, expires_ms, state, answer, answered_by, answered_ms, version) VALUES('$1', '${10:-test:fx:$1}', '$SIDL', $FXSUB, '$2', '$3', $4, $5, $FXN, $6, '${7:-open}', $fxa, ${9:-NULL}, $fxms, (SELECT coalesce(max(version), 0) + 1 FROM pic_ask))"
}
fx_ask $FXC1 confirm 'Delete the build folder?' "'It holds 212 files from the last build.'" NULL $((FXN + 600000))
fx_ask $FXC2 confirm 'Run the migration now?' NULL NULL $((FXN + 600000))
fx_ask $FXS select 'notes.txt already exists' NULL "'{\"options\":[{\"label\":\"Overwrite\",\"destructive\":true},{\"label\":\"Keep both\",\"default\":true},{\"label\":\"Skip\"}]}'" $((FXN + 600000))
fx_ask $FXI input 'Name the branch' "'Short, lower case.'" "'{\"placeholder\":\"feature/login\"}'" $((FXN + 600000))
fx_ask $FXD0 input 'Any notes for the release?' NULL NULL $((FXN + 600000))
WAKEID=$(q "SELECT id FROM pic_wake LIMIT 1")
[ -n "$WAKEID" ] || fail "asks fixture: no loop for a question to name"
fx_ask $FXK confirm 'Start loop L1, every 5m?' "'Look again at the deploy.'" NULL $((FXN + 600000)) open "" "" "wake:$WAKEID:fx"
fxcmd() { # NAME ID VALUE: the answer, in FXUP_NAME, and as a command in FXCMD_NAME
    eval "FXUP_$1='{\"type\":\"answer\",\"id\":\"$2\",\"value\":$3}'"
    eval "FXCMD_$1='{\"type\":\"command\",\"session\":\"$SESSL\",\"key\":\"fx-answer-$1-0000001\",\"payload\":{\"type\":\"answer\",\"id\":\"$2\",\"value\":$3}}'"
}
fxcmd yes $FXC1 true
fxcmd no $FXC2 false
fxcmd again $FXC2 true
fxcmd select $FXS '"Keep both"'
fxcmd badlabel $FXS '"Everything"'
fxcmd badwake $FXK null
fxcmd nosuch $FXG true
fxcmd text $FXI '"feature/login"'
fxcmd dismiss $FXD0 null
fxcmd late $FXX true
fxcmd after $FXT '"Skip"'
script "$T/ph1" <<EOS
seen {"type":"ask","session":"$SESSL","payload":{"id":"$FXC1",
seen {"type":"ask","session":"$SESSL","payload":{"id":"$FXK",
seen {"type":"ask","session":"$SESSL","payload":{"id":"$FXS",
seen {"type":"ask","session":"$SESSL","payload":{"id":"$FXI",
send {"type":"sessions"}
expect "state":"attention","workspaceName":"$(basename "$WS")","asks":6}
cmd fx-answer-yes-0000001 $FXCMD_yes
expect "command":"answer","success":true,"data":{"result":"answered","id":"$FXC1","value":true,"by":{"kind":"phone"
cmd fx-answer-no-0000001 $FXCMD_no
expect "command":"answer","success":true,"data":{"result":"answered","id":"$FXC2","value":false,"by":{"kind":"phone"
cmd fx-answer-again-0000001 $FXCMD_again
expect "command":"answer","success":true,"data":{"result":"already_answered","id":"$FXC2","value":false,"by":{"kind":"phone"
cmd fx-answer-badlabel-0000001 $FXCMD_badlabel
expect "command":"answer","success":false,"error":"a select is answered with one of its labels"
cmd fx-answer-badwake-0000001 $FXCMD_badwake
expect "command":"answer","success":false,"error":"a loop or goal is approved (true) or declined (false)"
cmd fx-answer-nosuch-0000001 $FXCMD_nosuch
expect "command":"answer","success":false,"error":"no such question in this conversation"
cmd fx-answer-select-0000001 $FXCMD_select
expect "command":"answer","success":true,"data":{"result":"answered","id":"$FXS"
count "key":"fx-answer-yes-0000001" 1
mark go-fx-answered
waitfor go-fx-flipped
cmd fx-get-state-0000001 {"type":"command","session":"$SESSL","key":"fx-get-state-0000001","payload":{"type":"get_state"}}
expect "command":"get_state","success":true
EOS
i=0; until [ -e "$T/ph1/go-fx-answered" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "asks fixture: $(cat "$T/ph1.run")"; sleep 0.05; done
q "UPDATE pic_submission SET status = 'admitted' WHERE id = $FXSUB" # a run still waiting: settled asks are told in get_state
: > "$T/ph1/go-fx-flipped"
done_ok $PR "asks fixture: answers"
cp "$T/ph1.run" "$T/fx-a.run"
script "$T/ph1" <<EOS
cmd fx-answer-text-0000001 $FXCMD_text
expect "command":"answer","success":true,"data":{"result":"answered","id":"$FXI"
cmd fx-answer-dismiss-0000001 $FXCMD_dismiss
expect "command":"answer","success":true,"data":{"result":"answered","id":"$FXD0"
mark go-fx-up
waitfor go-fx-told
seen {"type":"ask_settled","session":"$SESSL","payload":{"id":"$FXW",
seen {"type":"ask_settled","session":"$SESSL","payload":{"id":"$FXX",
seen {"type":"ask_settled","session":"$SESSL","payload":{"id":"$FXT",
seen {"type":"ask_settled","session":"$SESSL","payload":{"id":"$FXA",
seen {"type":"ask_settled","session":"$SESSL","payload":{"id":"$FXR",
cmd fx-answer-late-0000001 $FXCMD_late
expect "command":"answer","success":true,"data":{"result":"expired","id":"$FXX"
cmd fx-answer-after-0000001 $FXCMD_after
expect "command":"answer","success":true,"data":{"result":"already_answered","id":"$FXT"
EOS
i=0; until [ -e "$T/ph1/go-fx-up" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "asks fixture: $(cat "$T/ph1.run")"; sleep 0.05; done
q "UPDATE pic_submission SET status = 'answered' WHERE id = $FXSUB"
FXN2=$(($(date +%s) * 1000))
fx_ask $FXX confirm 'Still want the old build?' NULL NULL $((FXN2 + 2000))
fx_ask $FXW confirm 'Stop the watcher?' NULL NULL $((FXN + 600000)) withdrawn
fx_ask $FXT select 'Which tests should run?' NULL "'{\"options\":[{\"label\":\"Unit\"},{\"label\":\"Skip\"}]}'" $((FXN + 600000)) answered '"Unit"' "'terminal'"
fx_ask $FXA input 'Which branch?' NULL NULL $((FXN + 600000)) answered '"release/2.1"' "'attach'"
fx_ask $FXR confirm 'Push to origin?' NULL NULL $((FXN + 600000)) answered true "'rpc'"
: > "$T/ph1/go-fx-told"
done_ok $PR "asks fixture: settled"
cp "$T/ph1.run" "$T/fx-b.run"
cat "$T/fx-a.run" "$T/fx-b.run" | grep '^<- ' | sed 's/^<- //' > "$T/fx-all"
fxpick() { # TEXT [TEXT]: the first message the phone received that has both, as pic sent it
    grep -F -- "$1" "$T/fx-all" | grep -F -- "${2:-{}" | head -1
}
fxline() { # TEXT [TEXT] [PATH]: that message, or its PATH, a line of the file, with no comma
    local_m=$(fxpick "$1" "${2:-}")
    [ -n "$local_m" ] || fail "asks fixture: no message with $1 $2"
    if [ -n "${3:-}" ]; then "$SQLITE3" :memory: "SELECT json_extract(readfile('/dev/stdin'), '$3')" <<EOM
$local_m
EOM
    else printf '%s\n' "$local_m"; fi
}
fxask() { fxline '{"type":"ask","session":"'"$SESSL"'","payload":{"id":"'"$1"'"'; }
fxsettled() { fxline '{"type":"ask_settled","session":"'"$SESSL"'","payload":{"id":"'"$1"'"'; }
fxresp() { fxline '"key":"fx-answer-'"$1"'-0000001"' '"command":"answer"' '$.payload'; }
fxup() { eval "printf '%s\n' \"\$FXUP_$1\""; }
fxjoin() { # sed: a comma after each line but the last
    sed '$!s/$/,/' | sed 's/^/    /'
}
{
    printf '{\n  "about": "pic'"'"'s questions as they cross the relay (docs/design/remote-protocol.md, Questions), one record a line, as pic builds them. down: what a phone is sent (ask, ask_settled); up: what it sends (answer, under the key ask-ID); responses: pic'"'"'s response to an answer, nulls kept; state: get_state'"'"'s asks and settledAsks. Made by test/pic/remote_notify.sh from a running pic remote.",\n'
    printf '  "down": [\n'
    { fxask $FXC1; fxask $FXK; fxask $FXS; fxask $FXI
      fxsettled $FXC1; fxsettled $FXS; fxsettled $FXT; fxsettled $FXA; fxsettled $FXR; fxsettled $FXD0; fxsettled $FXX; fxsettled $FXW; } | fxjoin
    printf '  ],\n  "up": [\n'
    { fxup yes; fxup no; fxup select; fxup text; fxup dismiss; fxup badlabel; fxup badwake; } | fxjoin
    printf '  ],\n  "responses": [\n'
    { fxresp yes; fxresp again; fxresp late; fxresp after; fxresp dismiss; fxresp badlabel; fxresp badwake; fxresp nosuch; } | fxjoin
    printf '  ],\n  "state": '
    fxstate=$(fxline '"key":"fx-get-state-0000001"' '"command":"get_state"' '$.payload.data' | sed "s/'/''/g")
    "$SQLITE3" :memory: "SELECT json_object('asks', json_extract('$fxstate', '\$.asks'), 'settledAsks', json_extract('$fxstate', '\$.settledAsks'))"
    printf '}\n'
} > "$T/asks.raw"
sed -e "s|$DB|/Users/me/.pic/journal.db|g" -e "s|$SIDL|c1a0b7e4|g" -e "s|$DEV1B|AAECAwQFBgcICQoLDA0ODw|g" \
    -e "s|$FXN2|1795665600000|g" -e "s|$FXN|1795665600000|g" -e "s|$((FXN + 600000))|1795669200000|g" -e "s|$((FXN2 + 2000))|1795665602000|g" "$T/asks.raw" > "$T/asks.json"
[ -z "${PIC_UPDATE_FIXTURES:-}" ] || { mkdir -p "$(dirname "$FXD")" && cp "$T/asks.json" "$FXD"; }
cmp -s "$T/asks.json" "$FXD" || fail "asks fixture: pic's records differ from test/pic/remote-asks.json (PIC_UPDATE_FIXTURES=1 rewrites it): $(diff "$FXD" "$T/asks.json" 2>&1 | head -30)"
printf 'PASS: the records a phone sees about a question are the ones in test/pic/remote-asks.json\n'
# Permission modes (docs/manual/permissions.md): the phone sets a conversation's mode with
# set_permission_mode, committed before the answer; the list and get_state carry permissionMode
# (the list only when it is not allow); a mode that is not one is refused. A call waiting on the
# mode is an ask like any other: the phone answers "Allow for this conversation" under ask-ID.
NOW=$(($(date +%s) * 1000))
PID1=permpermpermpermperm01
q "INSERT INTO pic_ask(id, ask_key, session_id, kind, title, body, spec, created_ms, expires_ms, state, version) VALUES('$PID1', 'perm:999999', '$SIDL', 'select', 'Allow bash: make deploy?', 'make deploy', '{\"options\":[{\"label\":\"Allow\"},{\"label\":\"Allow for this conversation\"},{\"label\":\"Deny\"}]}', $NOW, $NOW + 600000, 'open', (SELECT coalesce(max(version), 0) + 1 FROM pic_ask))"
script "$T/ph1" <<EOS
cmd k-perm-set-0000001 {"type":"command","session":"$SESSL","key":"k-perm-set-0000001","payload":{"type":"set_permission_mode","mode":"ask-all"}}
expect "command":"set_permission_mode","success":true,"data":{"permissionMode":"ask-all","allowed":[]}
cmd k-perm-set-0000002 {"type":"command","session":"$SESSL","key":"k-perm-set-0000002","payload":{"type":"set_permission_mode","mode":"sometimes"}}
expect "command":"set_permission_mode","success":false,"error":"a permission mode is allow, ask-edits, ask-all or read-only"
cmd k-perm-state-00001 {"type":"command","session":"$SESSL","key":"k-perm-state-00001","payload":{"type":"get_state"}}
expect "permissionMode":"ask-all"
send {"type":"sessions"}
expect "permissionMode":"ask-all"
seen {"type":"ask","session":"$SESSL","payload":{"id":"$PID1","kind":"select","title":"Allow bash: make deploy?"
send {"type":"command","session":"$SESSL","key":"ask-$PID1","payload":{"type":"answer","id":"$PID1","value":"Allow for this conversation"}}
expect "command":"answer","success":true,"data":{"result":"answered","id":"$PID1","value":"Allow for this conversation"
cmd k-perm-set-0000003 {"type":"command","session":"$SESSL","key":"k-perm-set-0000003","payload":{"type":"set_permission_mode","mode":"allow"}}
expect "command":"set_permission_mode","success":true,"data":{"permissionMode":"allow","allowed":[]}
EOS
done_ok $PR "permissions: phone"
# a resend of the first key after the mode was changed elsewhere (this journal holds the fixture's
# made-up rows, so a full pic would refuse it: the change is written as set_permission_mode writes it)
# gets the first answer, and changes nothing
q "UPDATE pic_permission SET mode = 'read-only' WHERE session_id = '$SIDL'"
script "$T/ph1" <<EOS
cmd k-perm-set-0000001 {"type":"command","session":"$SESSL","key":"k-perm-set-0000001","payload":{"type":"set_permission_mode","mode":"ask-all"}}
expect "command":"set_permission_mode","success":true,"data":{"permissionMode":"ask-all","allowed":[]}
EOS
done_ok $PR "permissions: resend"
[ "$(q "SELECT mode FROM pic_permission WHERE session_id = '$SIDL'")" = read-only ] || fail "permissions: the resend changed it: $(q 'SELECT * FROM pic_permission')"
q "UPDATE pic_permission SET mode = 'allow' WHERE session_id = '$SIDL'"
[ "$(q "SELECT mode FROM pic_permission WHERE session_id = '$SIDL'")" = allow ] || fail "permissions: the row: $(q 'SELECT * FROM pic_permission')"
[ "$(q "SELECT state, answer FROM pic_ask WHERE id = '$PID1'")" = 'answered|"Allow for this conversation"' ] || fail "permissions: the ask: $(q "SELECT * FROM pic_ask WHERE id = '$PID1'")"
printf 'PASS: the phone sets a conversation'"'"'s permission mode, sees it in the list and get_state, and answers a call that asks\n'
kill "$spid" 2> /dev/null