Skip to content
pi-c Artifact [6c134c0736]
Login

Artifact [6c134c0736]

Artifact 6c134c07365479e29a8295a336036496769e1675db5e5aa029d6a0e2d86aa378:


#!/bin/sh
# Remote control against the REAL relay Worker (docs/design/remote-protocol.md, section 6) under
# wrangler dev, local only: the Worker listens on 127.0.0.1, with an invite var, state in the
# private temp dir and no account credentials in the environment. Nothing here contacts any other
# host. Cases: pairing with the C phone (test/pic/fake_phone.c) through the Worker; pic remote
# serving it (sessions, ping); then the phone page's own TypeScript protocol module
# (pic-relay src/protocol, test/pic/remote-interop-phone.ts) as the phone: pair, list, follow,
# prompt with a scripted model, unpair. Skips (exit 0) without node, the relay checkout or its
# wrangler, and with --no-faults. Usage: test/pic/remote-interop.sh [--no-faults]
# Env: PIC, PHONE, SERVER (required), SQLITE3, PIC_RELAY_DIR (default $HOME/pic-relay),
# PIC_INTEROP_DEADLINE (seconds the whole run may take, default 420).
set -eu
# The release build has no PIC_TEST_PASSPHRASE: remote.sh covers it without a terminal.
[ "${1:-}" = --no-faults ] && { printf 'SKIP: remote-interop: the release build takes the passphrase only from a terminal\n'; exit 0; }
RELAY_DIR=${PIC_RELAY_DIR:-$HOME/pic-relay} # before HOME is replaced
command -v node > /dev/null 2>&1 || { printf 'SKIP: remote-interop: no node\n'; exit 0; }
[ -d "$RELAY_DIR/src/worker" ] || { printf 'SKIP: remote-interop: no relay checkout at %s\n' "$RELAY_DIR"; exit 0; }
[ -x "$RELAY_DIR/node_modules/.bin/wrangler" ] || { printf 'SKIP: remote-interop: no wrangler in %s/node_modules\n' "$RELAY_DIR"; exit 0; }
RELAY_DIR=$(cd "$RELAY_DIR" && pwd)
# The real node, ahead of any version manager's shim, which reads its config from HOME.
NODE=$(node -p process.execPath) || { printf 'SKIP: remote-interop: node does not run\n'; exit 0; }
PATH=$(dirname "$NODE"):$PATH
PIC=${PIC:?set PIC to the pic binary}
PHONE=${PHONE:?set PHONE to the fake_phone binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
SQLITE3=${SQLITE3:-sqlite3}
DEADLINE=${PIC_INTEROP_DEADLINE:-420}
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-interop.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME/.pic"
unset PIC_KEY_FD CF_API_TOKEN CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID
export ANTHROPIC_API_KEY=pic-interop-test-key PIC_PI_EXPORT=0 WRANGLER_SEND_METRICS=false
export PIC_TEST_PASSPHRASE=interop-test-pass
INVITE=interop-invite
pids=
wpid=
cleanup() {
    for p in $pids; do kill "$p" 2> /dev/null || true; done
    if [ -n "$wpid" ]; then # wrangler stops workerd; the control pipe ends it if wrangler is killed
        kill "$wpid" 2> /dev/null || true
        i=0
        while kill -0 "$wpid" 2> /dev/null && [ "$i" -lt 40 ]; do i=$((i + 1)); sleep 0.1; done
        kill -9 "$wpid" 2> /dev/null || true
    fi
    if [ -n "${PIC_INTEROP_KEEP:-}" ]; then printf 'kept %s\n' "$T" >&2; else rm -rf -- "$T"; fi
}
trap cleanup EXIT HUP INT TERM
fail() {
    printf 'FAIL: %s\n' "$*" >&2
    for f in "$T"/*.out "$T"/*.err "$T"/*/*.out; do [ -s "$f" ] && { printf -- '--- %s\n' "$f" >&2; tail -20 "$f" >&2; }; done
    exit 1
}
bg() { pids="$pids $1"; }
await() { # FILE PATTERN [TRIES]: wait for the fixed string PATTERN in FILE (50 ms a try, 30 s by default)
    i=0
    until grep -qF -- "$2" "$1" 2> /dev/null; do
        i=$((i + 1))
        [ "$i" -lt "${3:-600}" ] || fail "timed out waiting for $2 in $1"
        sleep 0.05
    done
}
exists() { # FILE: wait up to 30 s for it
    i=0
    until [ -e "$1" ]; do
        i=$((i + 1))
        [ "$i" -lt "${2:-600}" ] || fail "timed out waiting for $1"
        sleep 0.05
    done
}
gone() { rc=0; wait "$1" || rc=$?; }
uq() { "$SQLITE3" "$HOME/.pic/pic.sqlite" "$1"; }

# ---- the Worker, under wrangler dev ----------------------------------------------------------
# A copy of the relay's sources and a trimmed config, so wrangler writes nothing into the checkout.
W=$T/worker
mkdir -p "$W" "$T/wrhome"
cp -R "$RELAY_DIR/src" "$RELAY_DIR/dist" "$W/"
ln -s "$RELAY_DIR/node_modules" "$W/node_modules"
cat > "$W/wrangler.toml" <<'TOML'
name = "pic-relay-interop"
main = "src/worker/index.ts"
compatibility_date = "2026-11-01"
send_metrics = false

[assets]
directory = "dist/page"
binding = "ASSETS"
run_worker_first = true

[[durable_objects.bindings]]
name = "MAILBOX"
class_name = "Mailbox"

[[durable_objects.bindings]]
name = "GATE"
class_name = "Gate"

[[migrations]]
tag = "v1"
new_sqlite_classes = ["Mailbox", "Gate"]
TOML
freeport() { node -e 'const s=require("net").createServer().listen(0,"127.0.0.1",()=>{console.log(s.address().port);s.close()})'; }
PORT=$(freeport)
IPORT=$(freeport)
worker() { # wrangler dev on PORT, its state in $T/wrstate (a restart keeps the mailboxes, as storage does)
    (cd "$W" && exec env HOME="$T/wrhome" XDG_CONFIG_HOME="$T/wrhome" "$RELAY_DIR/node_modules/.bin/wrangler" dev \
        --config "$W/wrangler.toml" --local --ip 127.0.0.1 --port "$PORT" --inspector-port "$IPORT" \
        --persist-to "$T/wrstate" --log-level error --var "PIC_INVITE:$INVITE" --var MAILBOX_DAILY_CAP:1000 \
        < /dev/null >> "$T/wrangler.out" 2>> "$T/wrangler.err") &
    wpid=$!
}
worker
# The run's own deadline: it ends with this script, or when DEADLINE seconds have passed.
me=$$
(
    n=0
    while [ "$n" -lt "$DEADLINE" ] && kill -0 "$me" 2> /dev/null; do n=$((n + 1)); sleep 1; done
    kill "$wpid" "$me" 2> /dev/null || true
) > /dev/null 2>&1 &
bg $!
BASE=http://127.0.0.1:$PORT
worker_up() {
    i=0
    until [ "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/" 2> /dev/null || true)" != 000 ]; do
        i=$((i + 1))
        kill -0 "$wpid" 2> /dev/null || fail "wrangler dev exited"
        [ "$i" -lt 1200 ] || fail "the Worker did not start"
        sleep 0.05
    done
}
worker_up
"$PIC" settings remote.relay "$BASE" > /dev/null
printf 'relay: the real Worker under wrangler dev at %s\n' "$BASE"

# Without the invite the Worker refuses a new mailbox with 403 and pic names the setting.
if "$PIC" remote pair --pipe < /dev/null > "$T/noinv.out" 2> "$T/noinv.err"; then fail "invite: paired without one"; fi
grep -qF 'remote.invite' "$T/noinv.err" || fail "invite: message: $(cat "$T/noinv.err")"
"$PIC" settings remote.invite "$INVITE" > /dev/null
printf 'PASS: the Worker refuses a mailbox without the invite; pic names the setting\n'

np=0
offer() { # start pic remote pair --pipe; its output in $PO, its stdin the fifo (fd 3), the offer in URL
    np=$((np + 1))
    PO="$T/pair$np.out"
    PI="$T/pair$np.in"
    mkfifo "$PI"
    "$PIC" remote pair --pipe < "$PI" > "$PO" 2> "$T/pair$np.err" &
    PP=$!
    bg $PP
    exec 3> "$PI"
    await "$PO" '"type":"offer"'
    URL=$(sed -n 's/.*"url":"\([^"]*\)".*/\1/p' "$PO" | head -1)
    [ -n "$URL" ] || fail "offer: no address in $(cat "$PO")"
    case "$URL" in "$BASE/#p1."*) ;; *) fail "offer: address $URL" ;; esac
}

# ---- (a) pairing with the C phone ------------------------------------------------------------
offer
mkdir "$T/ph1"
"$PHONE" "$T/ph1" pair "$URL" "Phone One" > "$T/ph1.out" 2>&1 &
PH=$!
bg $PH
await "$PO" '"type":"code"'
await "$T/ph1.out" 'code '
want=$(sed -n 's/^code //p' "$T/ph1.out")
grep -qF "\"code\":\"$want\"" "$PO" || fail "pair: the codes differ: $(cat "$PO") / $want"
grep -qF '"name":"Phone One"' "$PO" || fail "pair: name: $(cat "$PO")"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 0 ] || fail "pair: a row before the yes"
echo y >&3
gone $PH
[ "$rc" = 0 ] || fail "pair: phone exit $rc"
grep -qx paired "$T/ph1.out" || fail "pair: phone: $(cat "$T/ph1.out")"
gone $PP
exec 3>&-
[ "$rc" = 0 ] || fail "pair: pic exit $rc"
grep -qF '"type":"paired"' "$PO" || fail "pair: pic did not print paired: $(cat "$PO")"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "pair: rows"
printf 'PASS: pairing through the Worker: matching codes, a yes, the phone paired, one device row\n'

# ---- a conversation for the phones to see ----------------------------------------------------
mkdir "$T/log1" "$T/ws"
"$SERVER" "$T/port.srv" "$T/log1" "$DEADLINE" "sse:$S/text.sse" &
bg $!
i=0
while [ ! -s "$T/port.srv" ]; do
    i=$((i + 1))
    [ "$i" -lt 600 ] || fail "server did not start"
    sleep 0.05
done
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"m"}]}}}' \
    "$(cat "$T/port.srv")" > "$T/models.json"
export PIC_MODELS_FILE="$T/models.json"
"$PIC" settings defaultModel fake/m > /dev/null # a prompt from the phone names no model
"$PIC" --workspace "$T/ws" --model fake/m ask 'first question' > "$T/ask.out" 2> "$T/ask.err" || fail "ask: $(cat "$T/ask.err")"
[ "$(uq 'SELECT count(*) FROM picu_workspace')" = 1 ] || fail "ask: the workspace is not registered"

serve() { # start pic remote; its output in $T/remote.out
    "$PIC" remote < /dev/null > "$T/remote.out" 2> "$T/remote.err" &
    RP=$!
    bg $RP
    await "$T/remote.out" 'device'
}
unserve() { kill "$RP" 2> /dev/null || true; gone "$RP"; }

# ---- (b) pic remote serving the C phone ------------------------------------------------------
serve
cat > "$T/ph1.script" <<'SCRIPT'
send {"type":"sessions"}
expect "type":"sessions"
send {"type":"ping"}
expect "type":"pong"
SCRIPT
rc=0
"$PHONE" "$T/ph1" run < "$T/ph1.script" > "$T/ph1run.out" 2>&1 || rc=$?
[ "$rc" = 0 ] || fail "serve: phone exit $rc"
grep -qF 'first question' "$T/ph1run.out" || grep -qF "$T/ws" "$T/ph1run.out" || fail "serve: the sessions reply names no conversation: $(cat "$T/ph1run.out")"
printf 'PASS: pic remote through the Worker: a sessions reply and a pong for the C phone\n'
unserve

# ---- (c) the page's own protocol module as the phone -----------------------------------------
DRV=$T/driver
mkdir "$DRV"
PIC_RELAY_DIR=$RELAY_DIR node --input-type=module -e '
import { createRequire } from "node:module";
const { build } = createRequire(process.env.PIC_RELAY_DIR + "/package.json")("esbuild");
await build({ entryPoints: [process.argv[1]], bundle: true, platform: "node", format: "esm", outfile: process.argv[2],
  alias: { "relay-protocol": process.env.PIC_RELAY_DIR + "/src/protocol" }, logLevel: "warning" });
' "$here/remote-interop-phone.ts" "$DRV/phone.mjs" || fail "bundling the page's protocol module"
offer
node "$DRV/phone.mjs" "$BASE" "$URL" "Page Phone, Safari" "$DRV" > "$T/page.out" 2> "$T/page.err" &
PG=$!
bg $PG
exists "$DRV/code"
await "$PO" '"type":"code"'
want=$(cat "$DRV/code") # the page shows six digits; pic prints them in two groups of three
want="$(printf %s "$want" | cut -c1-3) $(printf %s "$want" | cut -c4-6)"
grep -qF "\"code\":\"$want\"" "$PO" || fail "page pair: the codes differ: $(cat "$PO") / $want"
grep -qF '"name":"Page Phone, Safari"' "$PO" || fail "page pair: name: $(cat "$PO")"
echo y >&3
exists "$DRV/paired"
gone $PP
exec 3>&-
[ "$rc" = 0 ] || fail "page pair: pic exit $rc"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 2 ] || fail "page pair: rows"
printf 'PASS: the page module pairs with pic: matching codes, a yes, two device rows\n'
serve
await "$T/page.out" 'followed' 900
await "$T/page.out" 'prompted' 900
touch "$DRV/unpair"
gone $PG
[ "$rc" = 0 ] || fail "page phone: exit $rc"
printf 'PASS: the page module: opened a session, listed, followed (sync) and prompted the scripted model\n'
i=0
until [ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ]; do
    i=$((i + 1))
    [ "$i" -lt 200 ] || fail "unpair: the device row is still there"
    sleep 0.05
done
printf 'PASS: the page module unpairs and pic deletes the device row\n'
unserve

# ---- (d) the real Worker restarted, and pic remote killed, under a prompt ---------------------
# The C phone follows the conversation and prompts; the Worker is stopped and started again (its
# storage kept, its held records lost: a gap) and pic remote is killed and started again. The
# prompt is one request, and the phone's copy is what a fresh sync gets.
serve
SESS=$(printf '%s/%s' "$("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT journal FROM picu_workspace")" \
    "$("$SQLITE3" "$("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT journal FROM picu_workspace")" "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")")
cat > "$T/ph1.soak" <<SCRIPT
send {"type":"sync","session":"$SESS","seq":0}
expect {"type":"sync","session":"$SESS"
cmd soak-worker-000001 {"type":"command","session":"$SESS","key":"soak-worker-000001","payload":{"type":"prompt","message":"across a restart"}}
mark sent
waitfor go
seen "key":"soak-worker-000001"
seen soak-worker-000001","status":"answered"
sleep 3000
replica $T/live.rep
SCRIPT
rm -f "$T/ph1/sent" "$T/ph1/go"
FAKE_PHONE_PING_MS=2000 "$PHONE" "$T/ph1" run < "$T/ph1.soak" > "$T/ph1soak.out" 2>&1 &
PS=$!
bg $PS
exists "$T/ph1/sent"
kill "$wpid"
i=0
while kill -0 "$wpid" 2> /dev/null && [ "$i" -lt 100 ]; do i=$((i + 1)); sleep 0.1; done
kill -9 "$wpid" 2> /dev/null || true
worker
worker_up
kill -9 "$RP"
gone "$RP"
serve
touch "$T/ph1/go"
gone $PS
[ "$rc" = 0 ] || fail "worker soak: phone exit $rc"
J=$("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT journal FROM picu_workspace")
[ "$("$SQLITE3" "$J" "SELECT count(*) || ' ' || group_concat(status) FROM pic_submission WHERE request_key LIKE 'rc:%:soak-worker-000001'")" = "1 answered" ] ||
    fail "worker soak: $("$SQLITE3" "$J" "SELECT request_key, status FROM pic_submission")"
printf 'send {"type":"sync","session":"%s","seq":0}\nexpect {"type":"sync","session":"%s"\nsleep 1000\nreplica %s\n' \
    "$SESS" "$SESS" "$T/fresh.rep" | "$PHONE" "$T/ph1" run > "$T/fresh.out" 2>&1 || fail "worker soak: fresh sync"
cmp -s "$T/live.rep" "$T/fresh.rep" || fail "worker soak: the copy differs: $(diff "$T/live.rep" "$T/fresh.rep" | head)"
printf 'PASS: the real Worker restarted and pic remote killed under a prompt: one request, every event in order\n'
unserve