Cotton code
752 lines · 38.9 KB · TypeScriptRaw
/** * Cotton Calling's signalling (12 Nov 2026): a call placed on the caller's * object, the ring handed to the callee's object, the room deciding every * state, and what the caller can and cannot learn. Every number is synthetic. */import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { acquaint, bearer, call, deadline, fakes, join, kept, open, refusedSocket, register, rung, settle, signUp, socket, TOPIC, type Fakes, type Started } from "./calling.ts";// Each test signs several people up, and each sign-up lays a whole personal kit.vi.setConfig({ testTimeout: 30_000 });let world: Fakes;let n = 0;/** A fresh synthetic number for each person in each test. */const number = (): string => `+91900000${String(9000 + ++n).padStart(4, "0")}`;beforeEach(() => {  world = fakes();});afterEach(() => {  vi.restoreAllMocks();});const TOKEN_A = "a".repeat(64);const TOKEN_B1 = "b1".repeat(32);const TOKEN_B2 = "b2".repeat(32);/** Two people with Cotton, the callee's one phone registered for VoIP pushes. */async function pair(): Promise<{ aNumber: string; bNumber: string; a: string; b: string }> {  const aNumber = number();  const bNumber = number();  const a = await signUp(aNumber, "a-phone");  const b = await signUp(bNumber, "b-phone");  await register(b, TOKEN_B1);  await acquaint(b, aNumber);  return { aNumber, bNumber, a, b };}/** A rung call: the caller's socket and the callee phone's, joined and ringing. */async function ringing(video = false) {  const people = await pair();  const started = await call(people.a, people.bNumber, video);  const caller = await socket(started.credential);  await caller.next({ t: "state", state: "ringing_out" });  await rung(world, started.room);  const joined = await join(people.b, started.room);  expect(joined.status, JSON.stringify(joined.body)).toBe(200);  const callee = await socket(joined.body.credential);  await callee.next({ t: "state", state: "ringing_in" });  return { ...people, started, caller, callee, joined: joined.body };}describe("an answered call", () => {  it("rings the callee's phone by VoIP push, hands it the caller's offer, relays the answer and goes live", async () => {    const people = await pair();    const started = await call(people.a, people.bNumber, true);    expect(started.room).toMatch(/^[0-9a-f]{32}$/);    expect(started.credential.startsWith(`ccr_${started.room}_`)).toBe(true);    expect(started.ringFor).toBe(45);    // What the phone's core reads: who it is in the room, and the room's mode.    expect((started as unknown as { me: string; mode: string })).toMatchObject({ me: "caller", mode: "p2p" });    const caller = await socket(started.credential);    await caller.next({ t: "state", state: "ringing_out" });    // The caller's offer and candidates go before anyone answers: held for the phone that accepts.    caller.send({ t: "signal", kind: "offer", sdp: "v=0 synthetic-offer" });    caller.send({ t: "signal", kind: "ice", candidate: "candidate:1 synthetic", mid: "0", mline: 0 });    const [push] = await rung(world, started.room);    expect(push!.token).toBe(TOKEN_B1);    // No number reaches Apple: the room and whether it is video, nothing else.    expect(push!.body).toEqual({ room: started.room, video: true });    expect(push!.verified).toBe(true);    expect(push!.headers).toMatchObject({ "apns-topic": `${TOPIC}.voip`, "apns-push-type": "voip", "apns-priority": "10", "apns-expiration": "0" });    const joined = await join(people.b, started.room);    expect(joined.status).toBe(200);    expect(joined.body).toMatchObject({ room: started.room, from: people.aNumber, video: true });    expect((joined.body as unknown as { me: string }).me).toBe(joined.body.member);    const callee = await socket(joined.body.credential);    await callee.next({ t: "state", state: "ringing_in" });    // The caller never hears a device ring: that would say the number has Cotton.    expect(caller.states()).toEqual(["ringing_out"]);    callee.send({ t: "accept" });    await caller.next({ t: "state", state: "connecting" });    await callee.next({ t: "state", state: "connecting" });    expect(await callee.next({ t: "signal", kind: "offer" })).toEqual({ t: "signal", from: "caller", kind: "offer", sdp: "v=0 synthetic-offer" });    expect(await callee.next({ t: "signal", kind: "ice" })).toEqual({ t: "signal", from: "caller", kind: "ice", candidate: "candidate:1 synthetic", mid: "0", mline: 0 });    callee.send({ t: "signal", kind: "answer", sdp: "v=0 synthetic-answer" });    expect(await caller.next({ t: "signal", kind: "answer" })).toEqual({ t: "signal", from: "m1", kind: "answer", sdp: "v=0 synthetic-answer" });    callee.send({ t: "signal", kind: "ice", candidate: "candidate:2 synthetic", mid: "0", mline: 0 });    await caller.next({ t: "signal", kind: "ice", candidate: "candidate:2 synthetic" });    caller.send({ t: "media", state: "connected" });    await caller.next({ t: "state", state: "live" });    await callee.next({ t: "state", state: "live" });    caller.send({ t: "ping" });    await caller.next({ t: "pong" });    caller.send({ t: "end" });    expect(await caller.ended()).toBe("hung_up");    expect(await callee.ended()).toBe("remote_hung_up");    // A finished call leaves nothing in its room, and its credential opens nothing.    expect(await kept(started.room)).toBe(0);    expect(await refusedSocket(started.credential)).toBe(410);    // An answered call's other phones had nothing to stop: no stop push after the end.    expect(world.stopsFor(started.room)).toEqual([]);  });  it("ends for the callee as hung_up and for the caller as remote_hung_up when the callee hangs up", async () => {    const { caller, callee } = await ringing();    callee.send({ t: "accept" });    await caller.next({ t: "state", state: "connecting" });    callee.send({ t: "media", state: "connected" });    await caller.next({ t: "state", state: "live" });    callee.send({ t: "end" });    expect(await callee.ended()).toBe("hung_up");    expect(await caller.ended()).toBe("remote_hung_up");  });  it("hangs up over HTTP when a phone's socket is down", async () => {    const { a, started, caller, callee } = await ringing();    callee.send({ t: "accept" });    await caller.next({ t: "state", state: "connecting" });    const res = await open("POST", `/v1/calls/${started.room}/end`, {}, bearer(a));    expect(res.status).toBe(200);    expect(await caller.ended()).toBe("hung_up");    expect(await callee.ended()).toBe("remote_hung_up");  });  it("fails a call that never connects in 30 s", async () => {    const { started, caller, callee } = await ringing();    callee.send({ t: "accept" });    await caller.next({ t: "state", state: "connecting" });    await deadline(started.room);    expect(await caller.ended()).toBe("failed");    expect(await callee.ended()).toBe("failed");  });  it("fails a call whose media fails while connecting", async () => {    const { caller, callee } = await ringing();    callee.send({ t: "accept" });    await caller.next({ t: "state", state: "connecting" });    caller.send({ t: "media", state: "failed" });    expect(await caller.ended()).toBe("failed");    expect(await callee.ended()).toBe("failed");  });});describe("a call nobody takes", () => {  it("is declined from the ringing phone", async () => {    const { started, caller, callee } = await ringing();    callee.send({ t: "decline" });    expect(await caller.ended()).toBe("declined");    expect(await callee.ended()).toBe("declined");    expect(await kept(started.room)).toBe(0);  });  it("is declined over HTTP by a phone that never joined", async () => {    const people = await pair();    const started = await call(people.a, people.bNumber);    const caller = await socket(started.credential);    await rung(world, started.room);    const res = await open("POST", `/v1/calls/${started.room}/decline`, {}, bearer(people.b));    expect(res.status).toBe(200);    expect(await caller.ended()).toBe("declined");  });  it("is busy when the phone says so", async () => {    const { caller, callee } = await ringing();    callee.send({ t: "busy" });    expect(await caller.ended()).toBe("busy");    expect(await callee.ended()).toBe("busy");  });  it("goes unanswered after 45 s: the caller hears no answer, the phone a missed call and a stop push", async () => {    const { started, caller, callee } = await ringing();    await deadline(started.room);    expect(await caller.ended()).toBe("no_answer");    expect(await callee.ended()).toBe("missed");    await vi.waitFor(() => expect(world.stopsFor(started.room).map((p) => [p.token, p.body.stop])).toEqual([[TOKEN_B1, "missed"]]));    expect(await kept(started.room)).toBe(0);  });  it("is cancelled by the caller before it is answered", async () => {    const { b, started, caller, callee } = await ringing();    caller.send({ t: "end" });    expect(await caller.ended()).toBe("cancelled");    expect(await callee.ended()).toBe("cancelled");    await vi.waitFor(() => expect(world.stopsFor(started.room).map((p) => p.body.stop)).toEqual(["cancelled"]));    // The ring is gone from the callee's object: joining now finds nothing.    expect((await join(b, started.room)).status).toBe(404);  });});describe("what the caller can learn", () => {  /** A call's whole story as the caller sees it: the answer's keys, the states, the end. */  async function seen(credential: string, to: string): Promise<{ keys: string[]; states: unknown[]; ended: unknown; room: string }> {    const started = await call(credential, to);    const caller = await socket(started.credential);    await caller.next({ t: "state", state: "ringing_out" });    await settle();    await deadline(started.room);    const ended = await caller.ended();    return { keys: Object.keys(started).sort(), states: caller.states(), ended, room: started.room };  }  it("is the same for a number with no Cotton, a callee with no phone rung, a callee who never accepted the caller, a blocked caller and a ring over the callee's limit", async () => {    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    // No Cotton at all.    const unknown = await seen(a, number());    // Cotton, but no phone with a push token.    const offlineNumber = number();    await acquaint(await signUp(offlineNumber, "off-phone"), aNumber);    const offline = await seen(a, offlineNumber);    // Cotton and a phone, but the caller is none of theirs (src/chat/gate.ts): never rung.    const strangerNumber = number();    await register(await signUp(strangerNumber, "stranger-phone"), TOKEN_B1);    const stranger = await seen(a, strangerNumber);    expect(world.ringsFor(stranger.room)).toEqual([]);    // Cotton and a phone, but the caller is blocked.    const blockerNumber = number();    const blocker = await signUp(blockerNumber, "blocker-phone");    await register(blocker, TOKEN_B2);    await acquaint(blocker, aNumber);    expect((await open("POST", "/v1/calls/block", { number: aNumber }, bearer(blocker))).status).toBe(200);    expect((await open<{ blocked: boolean }>("GET", `/v1/calls/blocked?number=${encodeURIComponent(aNumber)}`, undefined, bearer(blocker))).body).toEqual({ blocked: true });    const blocked = await seen(a, blockerNumber);    expect(world.ringsFor(blocked.room)).toEqual([]);    for (const story of [unknown, offline, stranger, blocked]) {      expect({ keys: story.keys, states: story.states, ended: story.ended }).toEqual({ keys: ["credential", "iceServers", "me", "members", "mode", "ringFor", "room", "ttl"], states: ["ringing_out"], ended: "no_answer" });    }    expect(world.pushes).toEqual([]);    // Unblocked, the same caller rings.    expect((await open("POST", "/v1/calls/unblock", { number: aNumber }, bearer(blocker))).status).toBe(200);    const again = await call(a, blockerNumber);    await rung(world, again.room);  });  it("is the same when the callee's object drops a caller over five rings in ten minutes", async () => {    const people = await pair();    const rooms: Started[] = [];    for (let i = 0; i < 5; i += 1) {      const started = await call(people.a, people.bNumber);      await rung(world, started.room);      rooms.push(started);    }    const sixth = await call(people.a, people.bNumber);    const caller = await socket(sixth.credential);    await settle();    expect(world.ringsFor(sixth.room)).toEqual([]);    await deadline(sixth.room);    expect(await caller.ended()).toBe("no_answer");    expect(caller.states()).toEqual(["ringing_out"]);  });  it("refuses a phone's own thirty-first start in the hour, which says nothing about whom it called", async () => {    const a = await signUp(number(), "busy-phone");    // Each number rung counts: six calls of the same five make the thirty (five new numbers, the hour's all: src/chat/gate.ts).    const five = Array.from({ length: 5 }, number);    for (let i = 0; i < 6; i++) expect((await open("POST", "/v1/calls", { to: five }, bearer(a))).status).toBe(200);    const refused = await open<{ code: string }>("POST", "/v1/calls", { to: five[0] }, bearer(a));    expect(refused.status).toBe(429);    expect(refused.body.code).toBe("too_many_calls");  });  it("refuses a number that is not one, and a call from no signed-in phone", async () => {    const a = await signUp(number(), "a-phone");    expect((await open<{ code: string }>("POST", "/v1/calls", { to: "12345" }, bearer(a))).body.code).toBe("bad_number");    expect((await open("POST", "/v1/calls", { to: number() })).status).toBe(401);  });});describe("two phones on the callee's number", () => {  it("ring together; the first to accept takes the call and the other stops ringing", async () => {    const people = await pair();    const second = await signUp(people.bNumber, "b-tablet");    await register(second, TOKEN_B2, false);    const started = await call(people.a, people.bNumber);    const caller = await socket(started.credential);    const pushes = await rung(world, started.room, 2);    expect(pushes.map((p) => p.token).sort()).toEqual([TOKEN_B1, TOKEN_B2].sort());    const one = await socket((await join(people.b, started.room)).body.credential);    const two = await socket((await join(second, started.room)).body.credential);    await one.next({ t: "state", state: "ringing_in" });    await two.next({ t: "state", state: "ringing_in" });    one.send({ t: "accept" });    await caller.next({ t: "state", state: "connecting" });    expect(await two.ended()).toBe("answered_elsewhere");    // Its socket is closed: a phone that did not accept has no place in the call.    await vi.waitFor(() => expect(two.closed).toBe(true));    await vi.waitFor(() => expect(world.stopsFor(started.room).map((p) => [p.token, p.body.stop])).toEqual([[TOKEN_B2, "answered_elsewhere"]]));    expect((await join(second, started.room)).status).toBe(404);    caller.send({ t: "media", state: "connected" });    await one.next({ t: "state", state: "live" });    one.send({ t: "end" });    expect(await caller.ended()).toBe("remote_hung_up");  });  it("stop ringing everywhere when one declines", async () => {    const people = await pair();    const second = await signUp(people.bNumber, "b-tablet");    await register(second, TOKEN_B2);    const started = await call(people.a, people.bNumber);    const caller = await socket(started.credential);    await rung(world, started.room, 2);    const one = await socket((await join(people.b, started.room)).body.credential);    const two = await socket((await join(second, started.room)).body.credential);    await two.next({ t: "state", state: "ringing_in" });    one.send({ t: "decline" });    expect(await caller.ended()).toBe("declined");    expect(await two.ended()).toBe("declined_elsewhere");    await vi.waitFor(() => expect(world.stopsFor(started.room).map((p) => [p.token, p.body.stop])).toEqual([[TOKEN_B2, "declined_elsewhere"]]));  });});describe("a call that drops", () => {  async function live() {    const ringed = await ringing();    ringed.callee.send({ t: "accept" });    await ringed.caller.next({ t: "state", state: "connecting" });    ringed.callee.send({ t: "media", state: "connected" });    await ringed.caller.next({ t: "state", state: "live" });    return ringed;  }  it("reconnects when the media comes back, and is lost when it does not in 30 s", async () => {    const { started, caller, callee } = await live();    caller.send({ t: "media", state: "disconnected" });    await callee.next({ t: "state", state: "reconnecting" });    caller.send({ t: "signal", kind: "restart", sdp: "v=0 synthetic-restart" });    await callee.next({ t: "signal", kind: "restart" });    caller.send({ t: "media", state: "connected" });    await vi.waitFor(() => expect(callee.states().filter((s) => s === "live").length).toBe(2));    callee.send({ t: "media", state: "disconnected" });    await vi.waitFor(() => expect(caller.states().filter((s) => s === "reconnecting").length).toBe(2));    await deadline(started.room);    expect(await caller.ended()).toBe("lost");    expect(await callee.ended()).toBe("lost");    expect(await kept(started.room)).toBe(0);  });  it("holds the call while a phone's socket comes back with the same credential", async () => {    const { started, caller, callee } = await live();    caller.ws.close(1001, "network change");    await callee.next({ t: "state", state: "reconnecting" });    const back = await socket(started.credential);    await back.next({ t: "state", state: "live" });    await vi.waitFor(() => expect(callee.states().filter((s) => s === "live").length).toBe(2));    back.send({ t: "end" });    expect(await callee.ended()).toBe("remote_hung_up");  });});describe("a phone's push token", () => {  it("is refused when it is not a token or not for Cotton Calling", async () => {    const a = await signUp(number(), "a-phone");    expect((await open<{ code: string }>("POST", "/v1/calls/device", { platform: "ios", token: "not hex", topic: TOPIC }, bearer(a))).body.code).toBe("bad_token");    expect((await open<{ code: string }>("POST", "/v1/calls/device", { platform: "ios", token: TOKEN_A, topic: "com.example.other" }, bearer(a))).body.code).toBe("bad_topic");  });  it("is taken for Cotton Chat, which places and takes calls now", async () => {    const a = await signUp(number(), "a-phone");    for (const topic of ["com.cottondb.messages", "com.cottondb.messages.dev"]) {      expect((await open("POST", "/v1/calls/device", { platform: "ios", token: TOKEN_A, topic }, bearer(a))).status).toBe(200);    }  });  it("goes when its phone signs out, and when Apple says it is gone", async () => {    const people = await pair();    const second = await signUp(people.bNumber, "b-tablet");    await register(second, TOKEN_B2);    world.refuse.set(TOKEN_B2, { status: 410 });    const first = await call(people.a, people.bNumber);    await rung(world, first.room, 2);    await settle();    // The gone token is not pushed again.    const next = await call(people.a, people.bNumber);    await rung(world, next.room);    await settle();    expect(world.ringsFor(next.room).map((p) => p.token)).toEqual([TOKEN_B1]);    expect((await open("POST", "/v1/sign-out", undefined, bearer(people.b))).status).toBe(200);    const after = await call(people.a, people.bNumber);    await settle();    expect(world.ringsFor(after.room)).toEqual([]);  });  it("is replaced by the same phone's newer token and dropped by its DELETE", async () => {    const people = await pair();    await register(people.b, TOKEN_B2);    const one = await call(people.a, people.bNumber);    expect((await rung(world, one.room)).map((p) => p.token)).toEqual([TOKEN_B2]);    expect((await open("DELETE", "/v1/calls/device", undefined, bearer(people.b))).status).toBe(200);    const two = await call(people.a, people.bNumber);    await settle();    expect(world.ringsFor(two.room)).toEqual([]);  });});describe("the ICE servers", () => {  it("are STUN alone on a Worker with no relay configured", async () => {    const a = await signUp(number(), "a-phone");    const res = await open("GET", "/v1/calls/ice", undefined, bearer(a));    expect(res.status).toBe(200);    expect(res.body).toEqual({ iceServers: [{ urls: ["stun:stun.cloudflare.com:3478"] }], ttl: 3600, relay: false });  });});describe("who is calling, on the ring", () => {  it("is sealed for the rung phone's own chat key: the phone reads the caller at once, the push service reads nothing", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    await register(b.credential, TOKEN_B1);    const started = await call(a, b.number, true);    const [push] = await rung(world, started.room);    const body = push!.body as { room: string; video: boolean; box: string };    expect({ room: body.room, video: body.video }).toEqual({ room: started.room, video: true });    expect(body.box.startsWith("c1:")).toBe(true);    expect(JSON.stringify(push)).not.toContain(aNumber);    expect(await b.open(body.box)).toEqual({ v: 1, ring: started.room, from: aNumber, video: true });  });});// 21 Nov 2026: the Android chat walk's second emulator never rang, its push token never having come.describe("a phone with no push token", () => {  it("is rung over its open chat socket, naming the caller sealed, joins, and is stopped over it", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    const chat = await b.socket();    const started = await call(a, b.number, true);    await vi.waitFor(() => expect(chat.frames.some((f) => f.t === "ring" && f.kind === "ring")).toBe(true), { timeout: 3000, interval: 20 });    const frame = chat.frames.find((f) => f.t === "ring" && f.kind === "ring") as { room: string; video: string; box: string };    expect({ room: frame.room, video: frame.video }).toEqual({ room: started.room, video: "1" });    expect(await b.open(frame.box)).toEqual({ v: 1, ring: started.room, from: aNumber, video: true });    expect(world.pushes).toHaveLength(0);    // It joins as a pushed phone does.    const joined = await join(b.credential, started.room);    expect(joined.status, JSON.stringify(joined.body)).toBe(200);    expect(joined.body.from).toBe(aNumber);    // The caller cancels: the phone that never answered is told over the socket.    const other = await chatPhone(number(), "c-phone");    await acquaint(other.credential, aNumber);    const otherSocket = await other.socket();    const second = await call(a, other.number);    await vi.waitFor(() => expect(otherSocket.frames.some((f) => f.t === "ring" && f.kind === "ring")).toBe(true), { timeout: 3000, interval: 20 });    const caller = await socket(second.credential);    caller.send({ t: "end" });    await vi.waitFor(() => expect(otherSocket.frames).toContainEqual(expect.objectContaining({ t: "ring", kind: "stop", room: second.room })), { timeout: 3000, interval: 20 });  });  it("is not rung when it has no socket open either (nothing to ring)", async () => {    const { chatPhone } = await import("./chat.ts");    const a = await signUp(number(), "a-phone");    const b = await chatPhone(number(), "b-phone");    const started = await call(a, b.number);    await settle();    expect(world.pushes).toHaveLength(0);    expect((await join(b.credential, started.room)).status).toBe(404);  });});// CALLS FIX 1 and 2 (27 Nov 2026): a ring handed to a socket is not proof the phone rang. The new ways// (ack or push, a late socket rung, a missed call kept for the phone) are spoken only to a phone that SAID it speaks// them when its socket opened ({ t: "hello", can: ["ring_ack"] }); any other phone sees exactly what main did.describe("a ring over the socket is proven by the phone's ack", () => {  const VOIP = "c".repeat(64);  type Frames = { frames: Record<string, unknown>[]; send(frame: Record<string, unknown>): void };  const ringFrame = (s: Frames, room: string) => s.frames.find((f) => f.t === "ring" && f.kind === "ring" && f.room === room) as { room: string; box: string } | undefined;  const missedFrame = (s: Frames, room: string) => s.frames.find((f) => f.t === "ring" && f.kind === "missed" && f.room === room) as { stop: string; box: string; at: number; ended: number } | undefined;  /** A phone of this build: its socket says what it speaks as it opens. */  async function speaking<S extends Frames & { ws: WebSocket }>(phone: { socket(): Promise<S> }): Promise<S> {    const chat = await phone.socket();    chat.send({ t: "hello", can: ["ring_ack"] });    await settle();    return chat;  }  it("an older build that never says hello is rung over its socket only, as on main: no push, no ring when it opens late, no missed call kept", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    await register(b.credential, VOIP);    const chat = await b.socket();    const started = await call(a, b.number);    await vi.waitFor(() => expect(ringFrame(chat, started.room)).toBeTruthy(), { timeout: 3000, interval: 20 });    await new Promise((resolve) => setTimeout(resolve, 3000));    expect(world.ringsFor(started.room)).toHaveLength(0);    // Unanswered: the stop is main's, with no box, and nothing is kept to tell it again.    await deadline(started.room);    await vi.waitFor(() => expect(chat.frames).toContainEqual(expect.objectContaining({ t: "ring", kind: "stop", room: started.room })), { timeout: 3000, interval: 20 });    const stop = chat.frames.find((f) => f.t === "ring" && f.kind === "stop") as Record<string, unknown>;    expect(stop.box).toBeUndefined();    expect((chat.frames.find((f) => f.t === "ring" && f.kind === "ring") as Record<string, unknown>).at).toBeUndefined();    const again = await b.socket();    await settle();    expect(again.frames.some((f) => f.t === "ring" && f.room === started.room)).toBe(false);  });  it("a phone that speaks it and never acks the frame is pushed too, after about 2 s", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    await register(b.credential, VOIP);    const chat = await speaking(b);    const started = await call(a, b.number);    await vi.waitFor(() => expect(ringFrame(chat, started.room)).toBeTruthy(), { timeout: 3000, interval: 20 });    expect(world.ringsFor(started.room)).toHaveLength(0);    await vi.waitFor(() => expect(world.ringsFor(started.room)).toHaveLength(1), { timeout: 4000, interval: 50 });  });  it("is not pushed when the phone acks the frame", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    await register(b.credential, VOIP);    const chat = await speaking(b);    const started = await call(a, b.number);    await vi.waitFor(() => expect(ringFrame(chat, started.room)).toBeTruthy(), { timeout: 3000, interval: 20 });    chat.send({ t: "ring_ack", room: started.room });    await new Promise((resolve) => setTimeout(resolve, 3000));    expect(world.ringsFor(started.room)).toHaveLength(0);  });  it("rings a phone that opens its socket while the ring is still live, for the rest of it, and lets it join", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    (await speaking(b)).ws.close();    const started = await call(a, b.number);    await settle();    // Launched late: the socket opens 38 s into the ring, as on the walk.    const before = Date.now();    const chat = await speaking(b);    await vi.waitFor(() => expect(ringFrame(chat, started.room)).toBeTruthy(), { timeout: 3000, interval: 20 });    expect(await b.open(ringFrame(chat, started.room)!.box)).toEqual({ v: 1, ring: started.room, from: aNumber, video: false });    // When the ring began, as the object kept it, so the late phone's row starts there (CALLS FIX 3).    expect(Number((ringFrame(chat, started.room) as unknown as { at: string }).at)).toBeLessThanOrEqual(before);    const joined = await join(b.credential, started.room);    expect(joined.status, JSON.stringify(joined.body)).toBe(200);  });  it("a phone offline through the whole call is given the missed call when it comes back: an accepted push is not proof", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    await register(b.credential, VOIP);    (await speaking(b)).ws.close();    await settle();    const before = Date.now();    const started = await call(a, b.number);    await rung(world, started.room);    await deadline(started.room);    // The stop push names the caller, sealed, and the ring's times; Apple accepted it, and it never arrived.    await vi.waitFor(() => expect(world.stopsFor(started.room)).toHaveLength(1));    const stop = world.stopsFor(started.room)[0]!.body as { stop: string; box: string; at: number; ended: number };    expect(stop.stop).toBe("missed");    expect(await b.open(stop.box)).toEqual({ v: 1, ring: started.room, from: aNumber, video: false });    expect(stop.at).toBeGreaterThanOrEqual(before);    expect(stop.ended).toBeGreaterThanOrEqual(stop.at);    // Back: its socket says hello and is given the missed call, as a missed call, with the same times.    const back = await speaking(b);    await vi.waitFor(() => expect(missedFrame(back, started.room)).toBeTruthy(), { timeout: 3000, interval: 20 });    expect(Number(missedFrame(back, started.room)!.at)).toBe(stop.at);    expect(ringFrame(back, started.room)).toBeUndefined();  });  it("a missed call is kept for a phone until it acks it: given at each hello, then no more", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    (await speaking(b)).ws.close();    await settle();    // No push token and no socket: nothing rings, and the room still tells this object the ring ended.    const started = await call(a, b.number);    await settle();    await deadline(started.room);    await settle();    const first = await speaking(b);    await vi.waitFor(() => expect(missedFrame(first, started.room)).toBeTruthy(), { timeout: 3000, interval: 20 });    expect(await b.open(missedFrame(first, started.room)!.box)).toEqual({ v: 1, ring: started.room, from: aNumber, video: false });    expect(ringFrame(first, started.room)).toBeUndefined();    first.ws.close();    // Not acked (the socket closed first): given again.    const second = await speaking(b);    await vi.waitFor(() => expect(missedFrame(second, started.room)).toBeTruthy(), { timeout: 3000, interval: 20 });    second.send({ t: "ring_ack", room: started.room });    await settle();    const third = await speaking(b);    expect(third.frames.some((f) => f.t === "ring" && f.room === started.room)).toBe(false);  });  it("a stop that came by push is acked over HTTP, and the missed call is not given again", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    await register(b.credential, VOIP);    (await speaking(b)).ws.close();    const started = await call(a, b.number);    await rung(world, started.room);    await deadline(started.room);    await vi.waitFor(() => expect(world.stopsFor(started.room)).toHaveLength(1));    const acked = await open("POST", "/v1/calls/ack", { room: started.room }, bearer(b.credential));    expect(acked.status, JSON.stringify(acked.body)).toBe(200);    const later = await speaking(b);    expect(later.frames.some((f) => f.t === "ring" && f.room === started.room)).toBe(false);  });  it("a phone that speaks it and never acked the ring's frame is pushed the stop as well, so the ring it was pushed ends", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    await register(b.credential, VOIP);    const chat = await speaking(b);    const started = await call(a, b.number);    await vi.waitFor(() => expect(world.ringsFor(started.room)).toHaveLength(1), { timeout: 4000, interval: 50 });    await deadline(started.room);    await vi.waitFor(() => expect(chat.frames).toContainEqual(expect.objectContaining({ t: "ring", kind: "stop", room: started.room })), { timeout: 3000, interval: 20 });    await vi.waitFor(() => expect(world.stopsFor(started.room)).toHaveLength(1));  });  it("a person with one old phone and one new: each is rung its own way, and only the new one is kept a missed call", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const bNumber = number();    const old = await chatPhone(bNumber, "b-old");    await acquaint(old.credential, aNumber);    const fresh = await chatPhone(bNumber, "b-new");    const oldSocket = await old.socket();    const freshSocket = await speaking(fresh);    const started = await call(a, bNumber);    await vi.waitFor(() => expect(ringFrame(oldSocket, started.room) && ringFrame(freshSocket, started.room)).toBeTruthy(), { timeout: 3000, interval: 20 });    await deadline(started.room);    await vi.waitFor(() => expect(oldSocket.frames).toContainEqual(expect.objectContaining({ t: "ring", kind: "stop", room: started.room })), { timeout: 3000, interval: 20 });    await vi.waitFor(() => expect(freshSocket.frames).toContainEqual(expect.objectContaining({ t: "ring", kind: "stop", room: started.room })), { timeout: 3000, interval: 20 });    // The old phone's stop is main's: no box, no times. The new one's names the caller and when.    const oldStop = oldSocket.frames.find((f) => f.t === "ring" && f.kind === "stop") as Record<string, unknown>;    expect(oldStop.box).toBeUndefined();    expect(oldStop.at).toBeUndefined();    const freshStop = freshSocket.frames.find((f) => f.t === "ring" && f.kind === "stop") as Record<string, string>;    expect(await fresh.open(freshStop.box!)).toEqual({ v: 1, ring: started.room, from: aNumber, video: false });    // Later: the old phone is given nothing; the new one (which never acked) is given the missed call.    const oldLater = await old.socket();    await settle();    expect(oldLater.frames.some((f) => f.t === "ring" && f.room === started.room)).toBe(false);    const freshLater = await speaking(fresh);    await vi.waitFor(() => expect(missedFrame(freshLater, started.room)).toBeTruthy(), { timeout: 3000, interval: 20 });  });  it("a ring waiting for its ack when the object restarted is pushed by the alarm", async () => {    const { chatPhone } = await import("./chat.ts");    const { env, runInDurableObject, runDurableObjectAlarm } = await import("cloudflare:test");    const { directory } = await import("../src/directory.ts");    const b = await chatPhone(number(), "b-phone");    await register(b.credential, VOIP);    const stub = env.BUSINESS.get(env.BUSINESS.idFromName((await directory(env).lookup(b.number))!));    // What a restart leaves: the ring row, the phone waiting since a moment ago, and no timer in memory to push it.    const room = crypto.randomUUID().replace(/-/g, "");    await runInDurableObject(stub, async (_object, state) => {      const device = state.storage.sql.exec<{ device_id: string }>("SELECT device_id FROM call_device").one().device_id;      state.storage.sql.exec(        "INSERT INTO call_ring (room, member, devices, video, from_number, created_at, group_id, acked, waiting) VALUES (?, 'm1', ?, 0, '+15550100009', ?, NULL, '[]', ?)",        room, JSON.stringify([device]), Date.now(), JSON.stringify([{ id: device, at: Date.now() - 1 }]),      );      await state.storage.setAlarm(Date.now());    });    expect(world.ringsFor(room)).toHaveLength(0);    await runDurableObjectAlarm(stub);    await vi.waitFor(() => expect(world.ringsFor(room)).toHaveLength(1), { timeout: 3000, interval: 20 });    const left = await runInDurableObject(stub, (_object, state) => state.storage.sql.exec<{ waiting: string }>("SELECT waiting FROM call_ring WHERE room = ?", room).one().waiting);    expect(left).toBe("[]");  });  it("a phone signed out of calls collects no more missed calls", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    await register(b.credential, VOIP);    (await speaking(b)).ws.close();    const gone = await open("DELETE", "/v1/calls/device", undefined, bearer(b.credential));    expect(gone.status).toBe(200);    const started = await call(a, b.number);    await settle();    await deadline(started.room);    await settle();    // Even when it later comes back and says hello: nothing was kept for it while it was out.    const later = await speaking(b);    await settle();    expect(later.frames.some((f) => f.t === "ring" && f.room === started.room)).toBe(false);  });  it("never leaves a missed call for a ring this phone answered", async () => {    const { chatPhone } = await import("./chat.ts");    const aNumber = number();    const a = await signUp(aNumber, "a-phone");    const b = await chatPhone(number(), "b-phone");    await acquaint(b.credential, aNumber);    const chat = await speaking(b);    const started = await call(a, b.number);    await vi.waitFor(() => expect(ringFrame(chat, started.room)).toBeTruthy(), { timeout: 3000, interval: 20 });    chat.send({ t: "ring_ack", room: started.room });    const joined = await join(b.credential, started.room);    expect(joined.status).toBe(200);    const caller = await socket(started.credential);    const callee = await socket(joined.body.credential);    await callee.next({ t: "state", state: "ringing_in" });    callee.send({ t: "accept" });    await caller.next({ t: "state", state: "connecting" });    callee.send({ t: "media", state: "connected" });    await caller.next({ t: "state", state: "live" });    caller.send({ t: "end" });    await settle();    const later = await speaking(b);    expect(later.frames.some((f) => f.t === "ring" && f.room === started.room)).toBe(false);  });});