Artifact f82575d64d4b475adf19ccaa7dc0f7d6393935329fd34c68ca35eb68037f0a2d:
- File
test/pic/remote-interop-phone.ts
— 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: 7546) [annotate] [blame] [check-ins using]
// The phone for test/pic/remote-interop.sh: the relay page's own protocol module (pic-relay, // src/protocol) pairing with and driving a real pic remote through the real Worker. Bundled by the // script with esbuild; "relay-protocol" is $PIC_RELAY_DIR/src/protocol. // Usage: node phone.mjs ORIGIN OFFER_URL NAME DIR // Env: PIC_PHONE_PUSH, a file holding the `push` message `fake_phone pushkeys` prints: the page's // push subscription (a PushPort) is that message's. // It writes DIR/code when the pairing code is up and DIR/paired once paired, and prints one line per // step ("opened", "listed", "followed", "live N", "prompted", "added link", "added code"); it forgets // the computer when DIR/unpair appears. Added: as a paired phone it asks pic for an offer, a second // device pairs with its link (then a third with a typed code, through the Worker's box), this phone // approves the six digits that device shows, the device opens a session, and this phone unpairs it. While the prompt's reply streams it samples the replica's live text: each value // must be the start of the committed reply, and the committed reply must clear it ("live N cleared"). import { readFileSync, writeFileSync, existsSync } from "node:fs"; import { type ClientEvent, Connection, MemoryStore, pair } from "relay-protocol/client.js"; import { formatCode, linkOf, makeCode, offerFromCode, offerOf, sealOffer, storeBox } from "relay-protocol/code.js"; const [origin, link, name, dir] = process.argv.slice(2) as [string, string, string, string]; const say = (s: string) => process.stdout.write(s + "\n"); const die = (s: string): never => { process.stderr.write(`phone: ${s}\n`); process.exit(1); }; setTimeout(() => die("deadline"), 150_000).unref(); function until<T>(f: () => T | undefined | null | false, ms: number, what: string): Promise<T> { return new Promise((resolve, reject) => { const t0 = Date.now(); const tick = () => { const v = f(); if (v) return resolve(v); if (Date.now() - t0 > ms) return reject(new Error(`timed out waiting for ${what}`)); setTimeout(tick, 25); }; tick(); }); } const store = new MemoryStore(); const subscription = process.env.PIC_PHONE_PUSH ? (JSON.parse(readFileSync(process.env.PIC_PHONE_PUSH, "utf8")).payload.subscription as { endpoint: string; keys: { p256dh: string; auth: string }; }) : null; const deps = { fetch: (u: string, i?: RequestInit) => fetch(u, i), origin, store, push: { current: async () => subscription } }; try { const pairing = await pair(deps, link, name, (s) => { if (s.step === "code") writeFileSync(`${dir}/code`, s.code); if (s.step === "failed") process.stderr.write(`pair failed: ${s.reason}\n`); }); writeFileSync(`${dir}/paired`, pairing.picName); say(`paired ${pairing.picName}`); const errors: string[] = []; const evs: ClientEvent[] = []; const conn = new Connection(deps, pairing, (e) => { if (e.kind === "error") errors.push(`${e.code} ${e.message ?? ""}`); evs.push(e); }); await conn.start(); await until(() => conn.phase === "open", 40_000, "an open session"); say("opened"); conn.setVisible(false); // a page in the background is the one pic notifies await until(() => conn.sessions.length >= 1, 20_000, "the conversation list"); const info = conn.sessions[0]!; say(`listed ${conn.sessions.length} ${info.session}`); conn.follow(info.session); const replica = await until(() => (conn.replica?.synced ? conn.replica : null), 20_000, "the first mark"); const types = replica.entries.map((e) => e.event.type); if (!types.includes("agent_end")) die(`sync: no agent_end in ${JSON.stringify(types)}`); say(`followed ${replica.cursor} ${types.join(",")}`); const before = replica.entries.length; const seen: string[] = []; // each distinct live value the replica held, in order const sample = setInterval(() => { const l = replica.live; if (l && l.offset === 0 && seen.at(-1) !== l.text) seen.push(l.text); }, 10); const cmd = conn.say(info.session, "second question"); await until(() => cmd.response !== undefined || cmd.error, 30_000, "the prompt's answer"); if (cmd.error) die(`prompt refused: ${JSON.stringify(cmd.error)}`); await until(() => replica.entries.length > before && replica.entries.at(-1)?.event.type === "agent_end", 40_000, "the reply's events"); clearInterval(sample); const final = replica.entries.map((e) => e.event as { type: string; message?: { role?: string; content?: { text?: string }[] } }) .filter((e) => e.type === "message_end" && e.message?.role === "assistant").at(-1)?.message?.content?.[0]?.text ?? ""; if (seen.length < 2) die(`live: ${seen.length} values seen for a slow reply`); const bad = seen.find((t) => !final.startsWith(t)); if (bad !== undefined) die(`live: ${JSON.stringify(bad)} is not the start of ${JSON.stringify(final)}`); if (seen.some((t, i) => i > 0 && t.length <= seen[i - 1]!.length)) die(`live: the text did not grow: ${JSON.stringify(seen)}`); if (replica.live !== null) die(`live: still held after the committed reply: ${JSON.stringify(replica.live)}`); say(`live ${seen.length} cleared`); say(`prompted ${replica.entries.slice(before).map((e) => e.event.type).join(",")}`); if (errors.length) die(`errors: ${errors.join("; ")}`); const find = <K extends ClientEvent["kind"]>(from: number, kind: K) => evs.slice(from).find((e): e is Extract<ClientEvent, { kind: K }> => e.kind === kind); for (const via of ["link", "code"] as const) { const from = evs.length; conn.askOffer(); const offer = await until(() => find(from, "pair_offer"), 20_000, "pair_offer"); let link = offer.url; if (via === "code") { const code = makeCode(); const sealed = await sealOffer(code, offerOf(link)!); const rd = { fetch: deps.fetch, origin }; if (!(await storeBox(rd, pairing.mailbox, pairing.channelToken, sealed.id, sealed.box, offer.expires - Date.now() / 1000))) die("code: the relay did not take the box"); const got = await offerFromCode(rd, formatCode(code).toLowerCase()); if (!("offer" in got)) die(`code: ${got.error}`); link = linkOf(origin, got.offer); } let shown = ""; const store2 = new MemoryStore(); const deps2 = { ...deps, store: store2, push: { current: async () => null } }; const paired2 = pair(deps2, link, `Added by ${via}`, (s) => { if (s.step === "code") shown = s.code; }); const req = await until(() => find(from, "pair_request"), 30_000, "pair_request"); await until(() => shown, 10_000, "the new device's code"); if (req.code !== shown || req.name !== `Added by ${via}`) die(`${via}: the approving phone shows ${req.name} ${req.code}, the new device ${shown}`); conn.approve(req.code); const p2 = await paired2; const end = await until(() => find(from, "pair_end"), 20_000, "pair_end"); if (end.result !== "paired" || !end.device) die(`${via}: pair_end ${JSON.stringify(end)}`); const c2 = new Connection(deps2, p2, () => {}); await c2.start(); await until(() => c2.phase === "open", 40_000, `${via}: the new device's session`); conn.unpairDevice(end.device); await until(() => c2.phase === "unpaired", 20_000, `${via}: the new device told it is unpaired`); say(`added ${via}`); } await until(() => existsSync(`${dir}/unpair`), 60_000, "the go-ahead to unpair"); await conn.forget(); say("forgotten"); process.exit(0); } catch (e) { die(String((e as Error)?.message ?? e)); }