Skip to content
pi-c Artifact [f798a27c22]
Login

Artifact [f798a27c22]

Artifact f798a27c2201ab404d67e20637770a9ababd12574037e92182d31e22e26e961c:


// 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. PIC_PHONE_IMAGE, a PNG file: after the prompt
// it sends one more with that image, then asks pic for the image back by the reference in the
// message's event ("image N back"). Over 1 MiB, it needs both readers to acknowledge as they read.
// 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").
// PIC_PHONE_JUST_PAIRED: once paired, it only opens a session and prints the link states it showed.
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}`);
  if (process.env.PIC_PHONE_JUST_PAIRED) {
    // Paired while pic remote runs: what the page says from here until a session opens, each state
    // once, and how long it took ("states A,B,C in N ms"). A page that says "never" tells a person
    // to start pic remote, which is running.
    const c = new Connection(deps, pairing, () => {});
    const states: string[] = [];
    const t0 = Date.now();
    const look = setInterval(() => {
      const st = c.link().state;
      if (states[states.length - 1] !== st) states.push(st);
    }, 20);
    await c.start();
    await until(() => c.phase === "open", 60_000, "an open session after pairing");
    clearInterval(look);
    say(`states ${states.join(",")} in ${Date.now() - t0} ms`);
    process.exit(0);
  }

  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 (process.env.PIC_PHONE_IMAGE) {
    if (!conn.features.has("images")) die("images: pic did not say it takes them");
    const data = readFileSync(process.env.PIC_PHONE_IMAGE).toString("base64");
    const from = replica.entries.length;
    const icmd = conn.say(info.session, "what is in this", [{ type: "image", data, mimeType: "image/png" }]);
    await until(() => icmd.response !== undefined || icmd.error, 60_000, "the image prompt's answer");
    if (icmd.error) die(`image prompt refused: ${JSON.stringify(icmd.error)}`);
    type Part = { type?: string; index?: number; bytes?: number; data?: string };
    const msg = await until(
      () => replica.entries.slice(from).find((e) => e.event.type === "message_end" && (e.event as { message?: { role?: string } }).message?.role === "user"),
      40_000,
      "the image message",
    );
    const part = ((msg.event as { message: { content: Part[] } }).message.content ?? []).find((c) => c.type === "image");
    if (!part || part.data !== undefined || typeof part.index !== "number") die(`image: the event's part: ${JSON.stringify(part)}`);
    await until(() => replica.entries.length > from && replica.entries.at(-1)?.event.type === "agent_end", 40_000, "the image request's end");
    const back = await conn.image(info.session, msg.seq, part!.index!, part!.bytes ?? 0);
    if (!("data" in back) || back.data !== data || back.mimeType !== "image/png") die(`image: back: ${"error" in back ? back.error : back.data.length}`);
    say(`image ${data.length} back`);
  }

  // Controls: a level for the next request, in order with what is typed; questions answered from
  // the journal, never kept for later; the conversation's stats.
  const level = conn.command(info.session, { type: "set_thinking_level", level: "off" });
  await until(() => level.response, 20_000, "set_thinking_level's answer");
  const state = conn.query(info.session, { type: "get_state" });
  const stats = conn.query(info.session, { type: "get_session_stats" });
  await until(() => state.response && stats.response, 20_000, "the questions' answers");
  const sd = (state.response as { data?: { thinkingLevel?: string; model?: { id?: string } } }).data;
  if (sd?.thinkingLevel !== "off" || typeof sd.model?.id !== "string") die(`get_state: ${JSON.stringify(state.response)}`);
  const td = (stats.response as { data?: { userMessages?: number; tokens?: { total?: number } } }).data;
  if (!(td?.userMessages! >= 2) || !(td.tokens?.total! > 0)) die(`get_session_stats: ${JSON.stringify(stats.response)}`);
  if (conn.commands.has(state.key)) die("a question was kept after its answer");
  say(`controls ${sd.model.id} ${sd.thinkingLevel} ${td.userMessages}`);

  // History: opened again, the conversation shows its latest request and says where the earlier
  // one starts; loading it keeps every event once, the first question included.
  conn.unfollow();
  conn.follow(info.session);
  const again = await until(() => (conn.replica?.synced ? conn.replica : null), 20_000, "the mark after following again");
  if (again.earlierPage === undefined) die("follow: no earlier point for a conversation of two requests");
  const latest = again.entries.length;
  if (!conn.loadEarlier()) die("loadEarlier refused");
  await until(() => again.synced && again.entries.length > latest, 20_000, "the earlier request");
  const texts = again.entries.map((e) => JSON.stringify(e.event));
  if (!texts.some((t) => t.includes("first question"))) die(`earlier: no first question in ${texts.length} events`);
  if (new Set(again.entries.map((e, i) => `${e.seq}:${texts[i]}`)).size !== again.entries.length) die("earlier: an event twice");
  if (again.earlierPage !== undefined) die(`earlier: still more before the first request: ${JSON.stringify(again.earlierPage)}`);
  say(`earlier ${latest} ${again.entries.length}`);
  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));
}