Skip to content
pi-c Artifact [c381fd0415]
Login

Artifact [c381fd0415]

Artifact c381fd0415342526590b669a1767f14e4a496d16f5a81f4210f6e3e2db7d5d07:


// 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"); it forgets the computer when
// DIR/unpair appears. 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 { Connection, MemoryStore, pair } from "relay-protocol/client.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 conn = new Connection(deps, pairing, (e) => {
    if (e.kind === "error") errors.push(`${e.code} ${e.message ?? ""}`);
  });
  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.earlier === 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.earlier !== undefined) die(`earlier: still more before the first request: ${again.earlier}`);
  say(`earlier ${latest} ${again.entries.length}`);
  if (errors.length) die(`errors: ${errors.join("; ")}`);

  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));
}