#!/bin/sh
# The terminal interface when a reply is refused for its key, on a
# pseudo-terminal against a fake server: the swap prompt offers what fits the
# failure (another key with the cost of an uncached re-send, another model, a
# wait for a limit, a new login for a refused key, Esc to stop); s retries
# with the other key and the journal records which key each reply used; w
# waits instead of asking again; l opens the login; Esc stops; nothing is
# sent again until a choice; the footer names the key and warns of a dead
# one; /key (/auth) lists the keys with their state. --no-faults (the release
# build): skipped, since the keys are stored with PIC_TEST_PASSPHRASE, which
# only the dev build reads.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
DRIVE=${DRIVE:?set DRIVE to the pty_drive binary}
SQLITE3=${SQLITE3:-sqlite3}
if [ "${1:-}" = --no-faults ]; then
printf 'SKIP: keyprompt needs the dev build (PIC_TEST_PASSPHRASE)\n'
exit 0
fi
S=$(cd "$(dirname "$0")/../pic/streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-keyprompt.XXXXXX")
T=$(cd "$T" && pwd -P)
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null || :; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
mkdir "$T/ws" "$T/log" "$T/home"
for v in $(env | sed -nE 's/^([A-Za-z0-9_]*_(API_KEY|TOKEN))=.*/\1/p'); do unset "$v"; done
unset PIC_TEST_PASSPHRASE
PASS="pic-keyprompt-pass-$$"
K1="pic-keyprompt-one-$$"
K2="pic-keyprompt-two-$$"
export HOME="$T/home" PIC_MODELS_FILE="$T/models.json" PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0 T
export PIC_NO_NATIVE_CLIPBOARD=1
printf '{"type":"error","error":{"type":"billing_error","message":"Your credit balance is too low to access the Anthropic API."}}' > "$T/billing.json"
printf '{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}' > "$T/auth.json"
printf '{"type":"error","error":{"type":"rate_limit_error","message":"rate limited"}}' > "$T/rate.json"
# 1 out of credit, 2 the swap's reply, 3 limited for 15 minutes, 4 refused, then replies
"$SERVER" "$T/port" "$T/log" 120 "status:402:$T/billing.json" "sse:$S/text.sse" "head:429:$T/rate.json:retry-after: 900" \
"status:401:$T/auth.json" "sse:$S/text.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server"; sleep 0.05; done
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$FAKE_API_KEY","models":[{"id":"m","contextWindow":200000,"cost":{"input":3,"output":15}}]},"anthropic":{"baseUrl":"http://127.0.0.1:%s"}}}' \
"$(cat "$T/port")" "$(cat "$T/port")" > "$T/models.json"
printf '%s\n' "$K1" | PIC_TEST_PASSPHRASE="$PASS" "$PIC" --db "$T/j" --workspace "$T/ws" login fake > /dev/null 2> "$T/login.err" ||
fail "login: $(cat "$T/login.err")"
printf '%s\n' "$K2" | PIC_TEST_PASSPHRASE="$PASS" "$PIC" --db "$T/j" --workspace "$T/ws" auth login fake --as second > /dev/null 2> "$T/login.err" ||
fail "login --as: $(cat "$T/login.err")"
for k in "$K1" "$K2"; do # anthropic has two keys too, for a model named by its bare claude- id
printf '%s\n' "$k" | PIC_TEST_PASSPHRASE="$PASS" "$PIC" --db "$T/j" --workspace "$T/ws" auth login anthropic --api-key \
$([ "$k" = "$K2" ] && echo --as work) > /dev/null 2> "$T/login.err" || fail "login anthropic: $(cat "$T/login.err")"
done
requests() { ls "$T/log" | wc -l | tr -d ' '; }
sent_key() { sed -n 's/^x-api-key: //p' "$T/log/$1.req" | tr -d '\r'; }
drive() { # NAME: pic on a pseudo-terminal, the script on stdin
name=$1
shift
"$DRIVE" "$T/$name.tx" 100 30 "$PIC" --tui-mode regular --db "$T/j" --workspace "$T/ws" --model fake/m "$@" ||
fail "$name: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$name.tx" | grep -v '^\s*$' | tail -12)"
}
drive prompt --key default <<EOF
expect pic fake/m
send hello\r
expect Passphrase for pic's credential store:
send $PASS\r
expect Stop asking for this passphrase?
send n
expect The key "default" is out of credit. Nothing was lost.
expect s retry with "second"
expect m another model
expect esc stop
waitfile \$T/log/1.req
wait 500
send s
expect Requests to fake use the key "second" now.
expect Hello, "world"
expect key second
expect ! out of credit: default
send again\r
expect Limited until
expect w wait and continue
expect m another model
send w
expect Waiting until
wait 800
send \e
expect interrupted request dropped
send third\r
expect fake refused the key "second" (HTTP 401).
expect l log in again
expect m another model
send l
expect API key "second" for fake:
send \e
wait 300
send \e
expect interrupted request dropped
send /key\r
expect Auth
expect API key ยท ! out of credit since
expect refused since
send \e
wait 200
send \x04\x04
expect pic: conversation
EOF
grep -aq 's switch key' "$T/prompt.tx" && fail "prompt: offered a key that is out of credit"
[ "$(requests)" = 4 ] || fail "prompt: $(requests) requests (a refusal was sent again without a choice)"
[ "$(sent_key 1)" = "$K1" ] && [ "$(sent_key 2)" = "$K2" ] || fail "prompt: s did not retry with the other key"
[ "$("$SQLITE3" "$T/j" "SELECT group_concat(state || ':' || coalesce(credential, '-'), ',') FROM (SELECT * FROM pic_generation ORDER BY id)")" = \
"failed:fake,done:fake:second,failed:fake:second,failed:fake:second" ] ||
fail "journal: $("$SQLITE3" "$T/j" "SELECT state, credential FROM pic_generation ORDER BY id")"
[ "$("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT value FROM picu_setting WHERE key = 'activeKey:fake'")" = second ] || fail "s: not active"
"$PIC" --db "$T/j" --workspace "$T/ws" check > /dev/null || fail "journal integrity"
! grep -aqF -- "$K1" "$T/prompt.tx" && ! grep -aqF -- "$K2" "$T/prompt.tx" || fail "a key reached the screen"
printf 'PASS: the swap prompt: s retries with the other key, w waits, l opens the login, Esc stops; never on its own\n'
printf 'PASS: the footer names the key and warns of a dead one; /key lists the keys with their state\n'
# The key the prompt offers: the one whose request was answered last, before one never checked,
# never one whose last request failed (here Anthropic's usage limit, which once read as nothing).
kill "$spid" 2>/dev/null || :
wait "$spid" 2>/dev/null || :
rm -rf "$T/log" "$T/port"
mkdir "$T/log"
regain=$(perl -MPOSIX=strftime -e 'print strftime("%Y-%m-%d", gmtime(time + 9 * 86400))')
printf '{"type":"error","error":{"type":"invalid_request_error","message":"You have reached your specified API usage limits. You will regain access on %s at 00:00 UTC."}}' \
"$regain" > "$T/usage.json"
# 1 default's usage limit, 2 good's reply, 3 last's spent credit, 4 good's reply after s
"$SERVER" "$T/port" "$T/log" 120 "status:400:$T/usage.json" "sse:$S/text.sse" "status:402:$T/billing.json" "sse:$S/text.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server"; sleep 0.05; done
printf '{"providers":{"spare":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$SPARE_API_KEY","models":[{"id":"m","contextWindow":200000,"cost":{"input":3,"output":15}}]}}}' \
"$(cat "$T/port")" > "$T/models.json"
for k in default fresh good last; do
printf 'pic-keyprompt-%s-%s\n' "$k" "$$" | PIC_TEST_PASSPHRASE="$PASS" "$PIC" --db "$T/j2" --workspace "$T/ws" auth login spare \
--api-key $([ "$k" = default ] || echo "--as $k") > /dev/null 2> "$T/login.err" || fail "login spare $k: $(cat "$T/login.err")"
done
for k in default good; do
PIC_TEST_PASSPHRASE="$PASS" "$PIC" --db "$T/j2" --workspace "$T/ws" --model spare/m --key "$k" -p x > /dev/null 2> "$T/$k.err" < /dev/null || :
done
grep -q 'The key "default" for spare is limited until' "$T/default.err" || fail "usage limit: $(cat "$T/default.err")"
PIC_TEST_PASSPHRASE="$PASS" "$PIC" --db "$T/j2" --workspace "$T/ws" auth use spare last > /dev/null || fail "auth use last"
"$DRIVE" "$T/order.tx" 100 30 "$PIC" --tui-mode regular --db "$T/j2" --workspace "$T/ws" --model spare/m <<EOF ||
expect pic spare/m
send hello\r
expect Passphrase for pic's credential store:
send $PASS\r
expect The key "last" is out of credit. Nothing was lost.
expect s retry with "good"
expect esc stop
waitfile \$T/log/3.req
wait 300
send s
expect Requests to spare use the key "good" now.
expect Hello, "world"
send \x04\x04
expect pic: conversation
EOF
fail "order: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/order.tx" | grep -v '^\s*$' | tail -12)"
[ "$(requests)" = 4 ] || fail "order: $(requests) requests"
[ "$(sent_key 4)" = "pic-keyprompt-good-$$" ] || fail "order: s did not retry with the key that answered last"
! grep -aq 'retry with "default"' "$T/order.tx" && ! grep -aq 'retry with "fresh"' "$T/order.tx" || fail "order: offered the wrong key"
printf 'PASS: the prompt offers the key that answered last, never one whose last request failed\n'
# A limit that lifts days away: no w; the prompt says when the key is back. (default is limited
# for nine days in j2's table from the run above.)
kill "$spid" 2>/dev/null || :
wait "$spid" 2>/dev/null || :
rm -rf "$T/log" "$T/port"
mkdir "$T/log"
"$SERVER" "$T/port" "$T/log" 120 "status:400:$T/usage.json" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server"; sleep 0.05; done
printf '{"providers":{"spare":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$SPARE_API_KEY","models":[{"id":"m","contextWindow":200000,"cost":{"input":3,"output":15}}]}}}' \
"$(cat "$T/port")" > "$T/models.json"
PIC_TEST_PASSPHRASE="$PASS" "$PIC" --db "$T/j2" --workspace "$T/ws" auth use spare default > /dev/null || fail "auth use default"
"$DRIVE" "$T/far.tx" 100 30 "$PIC" --tui-mode regular --db "$T/j2" --workspace "$T/ws" --model spare/m <<EOF ||
expect pic spare/m
send hello\r
expect Passphrase for pic's credential store:
send $PASS\r
expect Limited until
expect this key is back 20
send \x04\x04
expect pic: conversation
EOF
fail "far: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/far.tx" | grep -v '^\s*$' | tail -12)"
! grep -aq 'wait and continue' "$T/far.tx" || fail "far: offered w for a limit days away"
printf 'PASS: a limit days away offers no w and says when the key is back\n'
# A model named by its bare claude- id: the footer and /key find its provider (anthropic).
"$DRIVE" "$T/bare.tx" 100 30 "$PIC" --tui-mode regular --db "$T/j" --workspace "$T/ws" --model claude-sonnet-4-5 <<EOF ||
expect claude-sonnet-4-5
expect key default
send \x04\x04
EOF
fail "bare: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/bare.tx" | grep -v '^\s*$' | tail -8)"
printf 'PASS: the footer finds the provider of a bare claude- model id\n'