Artifact 9090aeb0edaa7db0176f07a79e020a8f8f8c2b719c436c74f3eab2b02c96ae0c:
- File
docs/dev/remote.md
— part of check-in
[fc9d35af55]
at
2026-11-23 19:01:49
on branch rc-pairing
— Pair a device from a paired phone; unpair one or all from a phone or the computer
A paired phone asks pic remote for an offer (pair_offer), shows it to the new device, and approves the six digits that device shows (pair_approve); pic remote enrols it only on that approval, over the approving phone's own session. Phones can list devices and unpair one or every device; pic remote unpair --all does the same at the computer; remote.phonePairing off turns it off. /rc and pic remote pair share the offer code with pic remote, and pic remote pair takes y as one key. Protocol amendment with the security argument in docs/design/remote-protocol.md. (user: dmestas, size: 11208) [annotate] [blame] [check-ins using]
# Remote control: the relay side The wire contract is [the remote protocol](../design/remote-protocol.md), with its Amendments. This page is the invariants in `src/remote.c`. The user's view is [remote control](../manual/remote-control.md); the inbox it writes to is [the inbox](inbox.md). ## State Two tables in `~/.pic/pic.sqlite`, both sealed with the credential store's key: | Table | Holds | Sealing AAD | |---|---|---| | `picu_remote_key` | pic's static key, the mailbox id and owner token, by `name` | `remote-key:NAME` | | `picu_remote_device` | one paired phone: `id`, sealed JSON, `paired_ms`, `seen_ms` | `remote-device:HEX` | The device JSON is `{"name","static","channel","push"}`; `push` is `null` or `{"endpoint","p256dh","auth","notify"}`, rewritten in place (the row's `sealed` alone) when the phone sends `push` or the push service ends the subscription. The VAPID key is the `vapid` row of `picu_remote_key`, made with the others at the first pairing. Unpair deletes a device row and needs no key. Reset deletes both tables' rows in one transaction, then the mailbox at the relay (best effort; the relay drops an unused mailbox after 90 days). ## The passphrase rule `pic remote` unlocks the store from its own source at every start (`rmt_unlock_fresh`): it locks first and never takes a key from a parent. A key in the Keychain or the key file opens it with no prompt, so launchd can start it; a passphrase store asks on the terminal, and with no terminal it exits. When the store has no key yet it refuses and tells the user to pair first. ## Process model One loop and one stream thread. The thread reads the relay's up stream and writes whole records to a pipe; it never touches SQLite. The loop owns the database, the sessions and the lane posts. A session is confirmed by the first message that verifies. Nothing is persisted but rows: no cursor, no session. A restart reconnects and each phone resyncs from its own cursor. `pic remote` takes no lease and writes no journal rows except inbox rows and keyed admissions. One per user: `~/.pic/remote.lock`. It writes `~/.pic/remote.status` (JSON: pid, state, relay, devices, attempts, the next try, the last error; replaced by a rename) when the stream's state changes and every 5 s; `pic remote status` trusts it only while the lock is held, and `pic remote stop` sends SIGTERM to its pid. ## Started by /rc The interface forks `pic remote --detached` in a session of its own, stdin `/dev/null`, output appended to `~/.pic/remote.log`, the master key on a pipe it inherits (`PIC_KEY_FD`, `pic_cred_handoff`). `--detached` takes that key instead of asking; without it the passphrase rule above holds. The interface reaps it; one that died of a signal (not TERM, INT or HUP) is started again after 1 s, doubling to 30, the count reset after a minute's run. It is not stopped when the interface exits. ## The connection | Constant | Value | Why | |---|---|---| | `RMT_IDLE_S` | 45 | no byte for this long: the stream is dead (the relay comments every 15 s) | | `RMT_BACKOFF_MAX_MS` | 60000 | the reconnect wait doubles from 1 s to this, a fifth either way | | `RMT_JUMP_MS` | 10000 | a tick this late, or the wall clock this far ahead of the monotonic one: a sleep or a stop | On a jump the loop sets the stream's `kick` (the thread drops the connection at its next byte, or cuts its wait short) and restamps every lane's queue, so what waited is posted rather than dropped as 30 s stale. A relay that does not answer at the start is waited for on the same schedule; a refusal (an HTTP status) ends `pic remote`. ## The reply as it streams The pic that runs a request publishes each reply's text in `<journal>.pic-leases/ID.live` (`pic_live_begin`, `pic_live_text`, `pic_live_end` in `src/store.c`, called around `provider->reply` in `src/loop.c` and from `pic_ev_delta`): the file is made at the first text with the line `pic-live 1 SEQ` (the journal's last entry when the reply began), the text is appended as it arrives (thinking is not), and the file is removed when the reply ends, before it is committed. A new reply is a new file (a new inode); one a dead process left is removed by the next reply's begin. It is not durable and nothing recovers it. `pic remote` reads it for each phone whose follow's last mark said a request runs, each tick, at most every 250 ms, and only when nothing waits on that phone's lane, so a value never queues behind another. It reads what grew, keeps the last 8 KiB on a character boundary (a character cut off at the end waits), counts the characters it dropped for `offset`, and sends `live` with the head's `seq` when the text grew and that `seq` is not behind an event the follow sent. `rev` is one counter for the process. Because the file goes before the commit and a tick runs the follow pass before the live read, no value follows the committed reply. ## Notifications A request is announced when it ends while `pic remote` watches its journal: one admitted when the journal was first read, or one above the highest id then (`push_cut`), each once (`push_told`). The check runs when the journal's `data_version` changes, in one read transaction with the move of `push_cut` to just below the oldest request still admitted. A request that asked no model (no `pic_generation` row: a command the user ran) or was imported (`import-` key) is not announced. "Phone-caused" is a request key `rc:...` or an inbox row from `remote:...` delivered into it. Each device with a subscription gets one push unless its notify or `remote.notify` excludes the request, its confirmed session's last `presence` was visible, a 429 asked it to wait, or its conversation had one in the last 30 s (per device). The plaintext is built in the loop; a pusher thread, started at the first push, sends it with `pic_webpush_send` on its own connection and hands the outcome back, so a slow push service holds up nothing: no transaction, no lane, no request. The loop applies outcomes: 404 or 410 ends the subscription, as do three 400s or 403s in a row; 429 holds the device for its `Retry-After` (60 s without one, a day at most); 413 sends once more with the line cut to 40 characters. Nothing else is sent again. At most 32 wait; more are dropped. ## The interface follows its conversation While none of its own requests runs, the interface keeps `pic attach --from end --format json` on its conversation and feeds its events to the same handler as its own child's, so a request from the phone shows. It is killed (SIGKILL: it only reads) before a request starts there, and started again after from the end, so nothing shows twice. While such a request runs, a line typed goes to it with `pic send steer` and Esc on an empty editor with `pic send abort`. User message events carry `origin` (the inbox row's sender, or `remote:DEVICE` for a phone's admitted prompt), which the interface shows as `from NAME:` using `pic remote devices --json`. ## Every command commits before it answers | Command | Commit | |---|---| | `steer`, `follow_up`, `abort` | an inbox row, key `rc:DEVICE:KEY`, sender `remote:DEVICE` | | `prompt`, conversation idle | keyed admission (`pic submit KEY`), then `pic run` in a `setsid` child holding the handed-down key (`PIC_KEY_FD`), so the request outlives `pic remote` | | `prompt`, request running | the inbox, as a steer would | | `get_state`, `get_messages` | answered from the journal; no row | Retrying a key returns the first answer. A kill before the commit means the phone retries; a kill after it means the retry is recognised: delivered once either way. ## The pairing channel pic deletes the pairing channel P only after the relay says the phone is reading it: `Pic-Peer: 1` on the post of `paired`, or a peer event that it came back, at most 30 s after posting. When the relay sends no `Pic-Peer`, 2 s. Deleting sooner loses `paired` for a phone that was reconnecting. ## Pairing from a paired phone `/rc`'s offer and a phone's share one module (`rmt_offer_*`): the secret, the pairing channel, the one handshake an offer admits, and the order of the device row, its channel and `paired`. `pic remote pair` asks the terminal; `pic remote` asks the phone that sent `pair_offer`, and holds at most one offer (`st->offer`), owned by that device's index. Its pairing channel's stream is a second stream thread writing to the loop's own pipe; every event is written whole under `rmt_pipe_mu`, and the loop tells the two streams apart by channel (the mailbox stream's is all zeros). An ended offer's thread is told to quit and lets go of its heap stream itself (`refs`); its late events name a channel the loop no longer knows and are dropped. The last word is waited for without blocking the loop, as above, in `rmt_offer_tick`. The approval is checked in the loop, never in the thread: from the asking device's confirmed session, once the new device has sent `pair_ready`, and with its six digits, compared in constant time. Anything else is `no_offer`, or, for wrong digits, the end of the offer. A device row added by `pic remote` itself does not change its own `data_version`, so it reads the table again at once. `unpair_device` and `unpair_all` go through `rmt_unpair_device`, as the terminal's unpair does. ## Tests - `test/pic/fake_relay.c` is a loopback relay implementing protocol section 6 without limits; `test/pic/fake_phone.c` plays the phone with the dev build's initiator. `test/pic/remote.sh` runs `pic remote` against them, including kill-and-restart crash cases. - `test/pic/remote-interop.sh` runs the real Worker from `~/pic-relay` under `wrangler dev` with the page's protocol module driven from Node, which also holds a push subscription at a loopback push service, watches a slow reply's live text grow and clear when the reply is committed, and gets one push that opens with the reply's first line. It is skipped when node, wrangler or the checkout is absent. - `test/pic/remote-soak.sh` kills and restarts the test relay (its mailboxes kept in a state file, event ids from the clock, as the Worker's) and `pic remote`, drops the network, silences every stream and stops `pic remote` past its idle timeout, under a run of prompts from the phone; then each prompt is one request and the phone's copy equals a fresh sync. The replies stream slowly: the phone's live values are each the committed reply's text at their offset, rev rises within one `pic remote` process and none follows its reply; and the phone's push subscription gets a sealed push naming the conversation for all but two of the requests (those ending while `pic remote` is killed or stopped may be missed), none announced twice. `remote-interop.sh` ends with the same check across a restart of the real Worker. - `PIC_TEST_PAIR_TTL` (seconds) shortens a pairing offer, and `PIC_TEST_RC_IDLE` (seconds) the dead stream's timeout, for tests only. `PIC_TEST_RC_PUSH_HTTP` lets a subscription name the test push service on loopback (`test/pic/fake_server.c`), and `PIC_TEST_RC_PUSH_GAP_MS` shortens the 30 s between notifications; `fake_phone pushkeys` subscribes and `fake_phone pushread` decrypts a push as the browser would.