Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

103 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { LiveCallState } from "../shared/wire.ts";
import {
  ATTACH_TIMEOUT_MS, CLOSE_TIMEOUT_MS, CONSENT_SETTLE_MS, DELEGATION_SETTLE_MS, FISH_ATTACH_TIMEOUT_MS, GOODBYE_MS, IDLE_CHECK_MS, PROGRESS_INTERVAL_MS,
  LIVE_FISH_NEEDS_APP, LIVE_ELEVENLABS_NEEDS_APP, LIVE_GEMINI_NEEDS_APP, LiveCallBusyError, LiveCallController, LiveCallSignedOutError, type LiveActivity, type LiveCallDeps, type LiveSocket,
} from "./live-call-controller.ts";
import { rmSync } from "node:fs";
import { LIVE_COPY } from "../shared/live-approval.ts";
import { DATA_DIR } from "./config.ts";
import { recordLiveCall } from "./live-call-record.ts";
import { flushLaterSaves } from "./save-batch.ts";
import { LIVE_CUSTOM_REFUSAL } from "./live-access.ts";
import { LIVE_NEEDS_AZURE, LIVE_NEEDS_KEY, LiveSessionError, type LiveEndpoint } from "./live-call.ts";
import { FishRelays, FISH_AGENT_VOICE } from "./live-fish.ts";
import type { LiveElevenLabsSession, LiveFishSessionToken, LiveGeminiSession } from "../shared/wire.ts";
import { addHeldSecretScrubber, HELD_SECRET_MASK, redactSecretsInText } from "./redact.ts";
import type { RequestAuth } from "./request-auth.ts";
import { Store, type Message, type StoreChange } from "./store.ts";

class FakeSocket implements LiveSocket {
  readyState = 0;
  url: string;
  key: string;
  sent: Array<Record<string, unknown>> = [];
  onopen: ((event: unknown) => void) | null = null;
  onmessage: ((event: { data: unknown }) => void) | null = null;
  onclose: ((event: unknown) => void) | null = null;
  onerror: ((event: unknown) => void) | null = null;
  constructor(url: string, key: string) { this.url = url; this.key = key; }
  send(data: string) { this.sent.push(JSON.parse(data) as Record<string, unknown>); }
  close() { if (this.readyState === 3) return; this.readyState = 3; this.onclose?.({}); }
  open() { this.readyState = 1; this.onopen?.({}); }
  receive(event: Record<string, unknown>) { this.onmessage?.({ data: JSON.stringify(event) }); }
  refuse() { this.onerror?.({}); this.readyState = 3; }
  drop() { this.readyState = 3; this.onclose?.({}); }
  appends(kind: string) { return this.sent.filter((e) => e.type === `session.${kind}.append`); }
}

const owner: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };
const BOT = { botId: "bot1", botName: "Ada", threadId: "t1" };
const ENDPOINT: LiveEndpoint = { provider: "openai", apiBase: "https://api.openai.com/v1", model: "gpt-live-1" };
const CODEX_ENDPOINT: LiveEndpoint = { provider: "codex", apiBase: "", model: "" };

function setup(overrides: Partial<LiveCallDeps> = {}) {
  const listeners = new Set<(change: StoreChange) => void>();
  const sockets: FakeSocket[] = [];
  const frames: Array<LiveCallState | null> = [];
  const logs: string[] = [];
  let activity: LiveActivity = "idle";
  const settings: ReturnType<LiveCallDeps["settings"]> = { key: "sk-test", endpoint: ENDPOINT, voice: "sol", readTypedReplies: true, idleMinutes: 5 };
  const queue = new Set<string>();
  let messageCounter = 0;
  const deps: LiveCallDeps = {
    store: { onChange: (listener) => { listeners.add(listener); return () => listeners.delete(listener); } },
    send: vi.fn(async () => ({ kind: "started" as const, messageId: `m${++messageCounter}` })),
    respond: vi.fn(async () => ({ ok: true as const })),
    queued: vi.fn((_botId: string, _threadId: string, queueId: string) => queue.has(queueId)),
    activity: () => activity,
    broadcast: (frame) => frames.push(frame.call),
    settings: () => settings,
    azureRefusal: vi.fn(() => null),
    fishRefusal: vi.fn(() => null),
    geminiRefusal: vi.fn(() => null),
    elevenlabsRefusal: vi.fn(() => null),
    createSession: vi.fn(async () => ({ sessionId: "sess_1", sdp: "answer-sdp" })),
    openSocket: (url, key) => { const socket = new FakeSocket(url, key); sockets.push(socket); return socket; },
    attachUrl: (id) => `ws://fake/${id}/attach`,
    speakable: (text) => text.split(/(?<=[.!?])\s+/).filter(Boolean),
    log: (line) => logs.push(line),
    now: () => Date.now(),
    ...overrides,
  };
  const controller = new LiveCallController(deps);
  const emit = (change: StoreChange) => { for (const listener of Array.from(listeners)) listener(change); };
  const message = (m: Partial<Message> & { id: string }) => emit({ type: "message", threadId: "t1", message: { role: "bot", kind: "text", ...m } as Message });
  const patch = (m: Partial<Message> & { id: string }) => emit({ type: "message.patch", threadId: "t1", message: { role: "bot", kind: "text", ...m } as Message });
  const setActivity = (next: LiveActivity) => { activity = next; emit({ type: "bot", botId: "bot1" }); };
  const start = async () => {
    const result = await controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "offer-sdp" });
    sockets.at(-1)!.open();
    return result;
  };
  return { controller, deps, sockets, frames, logs, settings, queue, listeners, emit, message, patch, setActivity, start, socket: () => sockets.at(-1)! };
}

beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());

describe("LiveCallController lifecycle", () => {
  it("creates the session with the key and voice, attaches the sideband and goes live", async () => {
    const t = setup();
    const result = await t.controller.start({ auth: owner, ...BOT, client: "ios", sdp: "offer-sdp" });
    expect(t.deps.createSession).toHaveBeenCalledWith({ key: "sk-test", endpoint: ENDPOINT, sdp: "offer-sdp", botId: "bot1", threadId: "t1", voice: "sol" });
    expect(result.sdp).toBe("answer-sdp");
    expect(result.call).toMatchObject({ botId: "bot1", threadId: "t1", client: "ios", voice: "sol", status: "connecting" });
    expect(t.socket().url).toBe("ws://fake/sess_1/attach");
    expect(t.socket().key).toBe("sk-test");
    t.socket().open();
    expect(t.controller.current()?.status).toBe("live");
    expect(t.frames.map((f) => f?.status)).toEqual(["connecting", "live"]);
  });

  it("uses Codex without an API key and refuses a phone before starting the session", async () => {
    const socket = new FakeSocket("", "");
    const codexProgress = vi.fn();
    socket.open();
    const t = setup({
      settings: () => ({ provider: "codex", key: "", endpoint: CODEX_ENDPOINT, voice: "marin", readTypedReplies: true, idleMinutes: 5 }),
      codexRefusal: (_auth, client) => client === "desktop" ? null : "Desktop only.",
      createSession: vi.fn(async () => ({ sessionId: "codex-session", sdp: "answer-sdp", socket })),
      openSocket: vi.fn(),
      codexProgress,
    });
    await expect(t.controller.start({ auth: owner, ...BOT, client: "ios", sdp: "offer-sdp" })).rejects.toMatchObject({ status: 403 });
    expect(t.deps.createSession).not.toHaveBeenCalled();
    const result = await t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "offer-sdp" });
    expect(result.call.status).toBe("live");
    expect(t.frames.map((frame) => frame?.status)).toEqual(["connecting", "live"]);
    expect(t.deps.openSocket).not.toHaveBeenCalled();
    expect(t.deps.createSession).toHaveBeenCalledWith({ key: "", endpoint: CODEX_ENDPOINT, sdp: "offer-sdp", botId: "bot1", threadId: "t1", voice: "juniper" });
    socket.receive({ type: "session.input_transcript.delta", delta: "Calculate 17 times 23", start_ms: 10, end_ms: 20 });
    socket.receive({ type: "session.delegation.created", delegation: { target: "client", id: "codex-1" }, offset_ms: 20 });
    await vi.advanceTimersByTimeAsync(DELEGATION_SETTLE_MS);
    expect(t.deps.send).toHaveBeenCalledWith(expect.objectContaining({ botId: BOT.botId, threadId: BOT.threadId, text: "Calculate 17 times 23" }));
    t.message({ id: "progress", kind: "activity", tool: { name: "Bash", spoken: "Checked the numbers" } });
    await vi.advanceTimersByTimeAsync(0);
    expect(codexProgress).toHaveBeenNthCalledWith(1, { kind: "live.codex.progress", callId: result.call.callId, text: `For progress questions only. ${LIVE_COPY.working}` });
    expect(codexProgress).toHaveBeenNthCalledWith(2, { kind: "live.codex.progress", callId: result.call.callId, text: `For progress questions only. ${LIVE_COPY.progress("Checked the numbers")}` });
    expect(socket.appends("thinking")).toEqual([]);
    t.message({ id: "approval", kind: "options", card: { title: "Approval needed", subtitle: "echo hello", options: ["Allow", "Deny"], requestId: "r1", tool: "Bash" } });
    await vi.advanceTimersByTimeAsync(0);
    socket.receive({ type: "session.input_transcript.delta", delta: "yes", start_ms: 2000, end_ms: 2100 });
    socket.receive({ type: "session.delegation.created", delegation: { target: "client", id: "codex-2" }, offset_ms: 2100 });
    await vi.advanceTimersByTimeAsync(CONSENT_SETTLE_MS + DELEGATION_SETTLE_MS);
    expect(t.deps.respond).not.toHaveBeenCalled();
    expect(t.deps.send).toHaveBeenCalledTimes(1);
    await t.controller.shutdown();
    expect(socket.sent.at(-1)).toMatchObject({ type: "session.close" });
    expect(socket.readyState).toBe(3);
    expect(t.controller.current()).toBeNull();
  });

  it("speaks in the called bot's own Live voice; a bot without one keeps the app's", async () => {
    const voices: Record<string, string> = { bot1: "cedar" };
    const own = setup({ botVoice: (botId) => voices[botId] });
    const started = await own.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" });
    expect(own.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ botId: "bot1", voice: "cedar" }));
    expect(started.call.voice).toBe("cedar");
    const other = setup({ botVoice: (botId) => voices[botId] });
    await other.controller.start({ auth: owner, ...BOT, botId: "bot2", client: "desktop", sdp: "a" });
    expect(other.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ botId: "bot2", voice: "sol" }));
  });

  it.each(["nuri", "juni", "flitz", "brise", "sillage", "nira", "harema", "shida", "noeul"])("starts the called bot's session in %s instead of the app's voice", async (voice) => {
    const t = setup({ botVoice: () => voice });
    const started = await t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" });
    expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ voice }));
    expect(started.call.voice).toBe(voice);
    await t.controller.shutdown();
  });

  it("uses the app's voice when the bot's own is not a GPT-Live voice", async () => {
    const t = setup({ botVoice: () => "Kore" });
    await t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" });
    expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ voice: "sol" }));
  });

  it("refuses a second call while one is active, before creating a session", async () => {
    const t = setup();
    const first = t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" });
    await expect(t.controller.start({ auth: owner, ...BOT, client: "ios", sdp: "b" })).rejects.toBeInstanceOf(LiveCallBusyError);
    await first;
    expect(t.deps.createSession).toHaveBeenCalledTimes(1);
  });

  it("asks every client for the person's own key when none is set, never for a plan", async () => {
    for (const input of [{ client: "desktop" }, { client: "web" }, { client: "ios" }, { client: "android" }, { client: "ios", device: "phone-1" }] as const) {
      const t = setup();
      t.settings.key = " ";
      const refused = t.controller.start({ auth: owner, ...BOT, ...input, sdp: "a" });
      await expect(refused, JSON.stringify(input)).rejects.toMatchObject({ status: 409, message: LIVE_NEEDS_KEY });
      expect(t.deps.createSession).not.toHaveBeenCalled();
      expect(t.controller.current()).toBeNull();
    }
    expect(LIVE_NEEDS_KEY).toBe("Live calls use your own OpenAI key. Add it in Settings → AI → Other services.");
  });

  it("refuses an Azure call whose setup is incomplete with the setup message, before reaching Azure", async () => {
    const t = setup();
    t.settings.endpoint = null;
    t.settings.provider = "azure";
    t.settings.setupProblem = LIVE_NEEDS_AZURE;
    await expect(t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" })).rejects.toMatchObject({ status: 409, message: LIVE_NEEDS_AZURE });
    expect(t.deps.createSession).not.toHaveBeenCalled();
    expect(t.controller.current()).toBeNull();
  });

  it("creates and attaches an Azure call on the Azure endpoint it started with, even if settings change mid-call", async () => {
    const azure: LiveEndpoint = { provider: "azure", apiBase: "https://res.openai.azure.com/openai/v1", model: "live-dep" };
    const attachUrl = vi.fn((id: string, endpoint: LiveEndpoint) => `${endpoint.apiBase}/live/sessions/${id}/attach`);
    const t = setup({ attachUrl });
    t.settings.endpoint = azure;
    const pending = t.controller.start({ auth: owner, ...BOT, client: "web", sdp: "offer-sdp" });
    t.settings.endpoint = ENDPOINT;
    await pending;
    expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ endpoint: azure }));
    expect(attachUrl).toHaveBeenCalledWith("sess_1", azure);
    expect(t.socket().url).toBe("https://res.openai.azure.com/openai/v1/live/sessions/sess_1/attach");
    t.socket().open();
    expect(t.controller.current()).toMatchObject({ status: "live" });
  });

  describe("with Azure chosen", () => {
    const AZURE: LiveEndpoint = { provider: "azure", apiBase: "https://res.openai.azure.com/openai/v1", model: "live-dep" };
    const REFUSED = "only an admin, in these words";
    const member: RequestAuth = { kind: "loopback", scopes: ["client"], trust: "service" };
    const azure = (overrides: Partial<LiveCallDeps> = {}) => {
      const t = setup(overrides);
      t.settings.endpoint = AZURE;
      t.settings.provider = "azure";
      return t;
    };

    it("asks who is calling, with their own sign-in, and goes ahead when they may", async () => {
      const t = azure();
      await t.controller.start({ auth: owner, ...BOT, client: "web", sdp: "a" });
      expect(t.deps.azureRefusal).toHaveBeenCalledWith(owner);
      expect(t.deps.createSession).toHaveBeenCalledOnce();
    });

    it("refuses with the reason as a 403, never a setup prompt, before any session, socket or line is taken", async () => {
      const t = azure({ azureRefusal: () => REFUSED });
      await expect(t.controller.start({ auth: member, ...BOT, client: "ios", sdp: "a" })).rejects.toMatchObject({ status: 403, message: REFUSED });
      expect(t.deps.createSession).not.toHaveBeenCalled();
      expect(t.sockets).toHaveLength(0);
      expect(t.frames).toEqual([]);
      expect(t.controller.current()).toBeNull();
      expect(t.logs.join("\n")).toContain("[live] call refused bot=bot1 client=ios provider=azure");
    });

    it("refuses a person who may not call even while Azure is not set up yet, rather than sending them to set it up", async () => {
      const t = azure({ azureRefusal: () => REFUSED });
      t.settings.endpoint = null;
      t.settings.key = "";
      t.settings.setupProblem = LIVE_NEEDS_AZURE;
      await expect(t.controller.start({ auth: member, ...BOT, client: "web", sdp: "a" })).rejects.toMatchObject({ status: 403, message: REFUSED });
    });

    it("asks too when only the endpoint says Azure, so no reading of the settings slips past it", async () => {
      const t = azure({ azureRefusal: () => REFUSED });
      delete t.settings.provider;
      await expect(t.controller.start({ auth: member, ...BOT, client: "web", sdp: "a" })).rejects.toMatchObject({ status: 403 });
      expect(t.deps.createSession).not.toHaveBeenCalled();
    });

    it("tells a refused caller nothing about a call already running", async () => {
      let asked = 0;
      const t = azure({ azureRefusal: () => (asked++ === 0 ? null : REFUSED) });
      await t.start();
      const second = t.controller.start({ auth: member, ...BOT, client: "web", sdp: "a" });
      await expect(second).rejects.toMatchObject({ status: 403, message: REFUSED });
      await expect(second).rejects.not.toBeInstanceOf(LiveCallBusyError);
    });

  });

  describe("with a custom endpoint chosen", () => {
    const CUSTOM: LiveEndpoint = { provider: "custom", apiBase: "https://gateway.example.com/v1", model: "gpt-live-1" };
    const member: RequestAuth = { kind: "loopback", scopes: ["client"], trust: "service" };
    const custom = (overrides: Partial<LiveCallDeps> = {}) => {
      const t = setup(overrides);
      t.settings.endpoint = CUSTOM;
      t.settings.provider = "custom";
      return t;
    };

    it("holds the call to Azure's limit, in the custom endpoint's own words, and starts it like OpenAI when allowed", async () => {
      const refused = custom({ azureRefusal: () => "Azure's words" });
      await expect(refused.controller.start({ auth: member, ...BOT, client: "web", sdp: "a" })).rejects.toMatchObject({ status: 403, message: LIVE_CUSTOM_REFUSAL });
      expect(refused.deps.createSession).not.toHaveBeenCalled();
      const t = custom();
      await t.controller.start({ auth: owner, ...BOT, client: "web", sdp: "a" });
      expect(t.deps.azureRefusal).toHaveBeenCalledWith(owner);
      expect(t.deps.fishRefusal).not.toHaveBeenCalled();
      expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ endpoint: CUSTOM }));
    });
  });

  describe("with Fish Audio chosen", () => {
    const FISH: LiveEndpoint = { provider: "fish", apiBase: "https://api.fish.audio/v1/agent", model: "agent_1" };
    const REFUSED = "only an admin, in these words";
    const member: RequestAuth = { kind: "loopback", scopes: ["client"], trust: "service" };
    const TOKEN: LiveFishSessionToken = {
      transport: "livekit", session_id: "fish_1", expires_at: "2026-11-11T00:00:00Z", max_duration_seconds: 900, livekit_url: "wss://lk.example", token: "jwt",
    };
    const fish = (overrides: Partial<LiveCallDeps> = {}) => {
      const relays = new FishRelays();
      const endSession = vi.fn(async () => true);
      let relayToken = "";
      const t = setup({
        createSession: vi.fn(async () => {
          relayToken = relays.open(TOKEN.session_id, endSession).token;
          return { sessionId: TOKEN.session_id, fish: { type: "fish" as const, session: TOKEN, relayToken } };
        }),
        openSocket: (url) => relays.socket(url),
        attachUrl: (id) => id,
        ...overrides,
      });
      t.settings.endpoint = FISH;
      t.settings.provider = "fish";
      const relay = () => relays.find(TOKEN.session_id, relayToken)!;
      return { ...t, relays, endSession, relay };
    };

    it("asks who is calling, starts with no SDP, and answers with Fish's session and the relay's token", async () => {
      const t = fish();
      const started = await t.controller.start({ auth: owner, ...BOT, client: "web" });
      expect(t.deps.fishRefusal).toHaveBeenCalledWith(owner);
      expect(t.deps.azureRefusal).not.toHaveBeenCalled();
      expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ endpoint: FISH, sdp: "", voice: FISH_AGENT_VOICE }));
      expect(started.sdp).toBeUndefined();
      expect(started.fish).toEqual({ type: "fish", session: TOKEN, relayToken: expect.stringMatching(/^[\w-]{43}$/) });
      expect(started.call).toMatchObject({ status: "connecting", voice: FISH_AGENT_VOICE });
    });

    it("refuses with the reason as a 403 before any session is taken, even while Fish is not set up", async () => {
      const t = fish({ fishRefusal: () => REFUSED });
      t.settings.endpoint = null;
      await expect(t.controller.start({ auth: member, ...BOT, client: "web" })).rejects.toMatchObject({ status: 403, message: REFUSED });
      expect(t.deps.createSession).not.toHaveBeenCalled();
      expect(t.logs.join("\n")).toContain("[live] call refused bot=bot1 client=web provider=fish");
    });

    it("sends a phone to the desktop app or a browser", async () => {
      for (const client of ["ios", "android"] as const) {
        const t = fish();
        await expect(t.controller.start({ auth: owner, ...BOT, client })).rejects.toMatchObject({ status: 400, message: LIVE_FISH_NEEDS_APP });
        expect(t.deps.createSession).not.toHaveBeenCalled();
      }
    });

    it("never calls Fish with a key saved for another provider", async () => {
      const t = fish();
      t.settings.endpoint = ENDPOINT;
      await expect(t.controller.start({ auth: owner, ...BOT, client: "web" })).rejects.toMatchObject({ status: 409 });
      expect(t.deps.createSession).not.toHaveBeenCalled();
    });

    it("waits longer for the client to join, then gives up and ends Fish's session", async () => {
      const t = fish();
      await t.controller.start({ auth: owner, ...BOT, client: "web" });
      await vi.advanceTimersByTimeAsync(ATTACH_TIMEOUT_MS + 1);
      expect(t.controller.current()?.status).toBe("connecting");
      await vi.advanceTimersByTimeAsync(FISH_ATTACH_TIMEOUT_MS - ATTACH_TIMEOUT_MS);
      expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost", error: "The call could not connect to Fish Audio." });
      expect(t.endSession).toHaveBeenCalledOnce();
    });

    it("takes a request heard by the client to the bot and returns the answer to the delegate call", async () => {
      const t = fish();
      await t.controller.start({ auth: owner, ...BOT, client: "web" });
      const callId = t.controller.current()!.callId;
      t.relay().receive([{ type: "connected" }]);
      expect(t.controller.current()?.status).toBe("live");
      t.relay().receive([{ type: "heard", text: "check my mail", startMs: 100, endMs: 900 }, { type: "delegate", id: "call_1", atMs: 950 }]);
      await vi.advanceTimersByTimeAsync(DELEGATION_SETTLE_MS + 1);
      expect(t.deps.send).toHaveBeenCalledWith({ auth: owner, botId: "bot1", threadId: "t1", text: "check my mail", callId });
      t.message({ id: "b1", text: "You have two new emails.", requestMessageId: "m1" });
      t.patch({ id: "b1", text: "You have two new emails.", requestMessageId: "m1", turnTerminal: true, turnSucceeded: true });
      await vi.advanceTimersByTimeAsync(0);
      const { commands } = await t.relay().poll(0);
      expect(commands).toContainEqual({ type: "append", kind: "commentary", content: "You have two new emails.", delegationId: "call_1" });
    });

    it("on End tells the client to hang up, ends Fish's session and records the call", async () => {
      const t = fish();
      await t.controller.start({ auth: owner, ...BOT, client: "web" });
      const relay = t.relay();
      relay.receive([{ type: "connected" }]);
      const waiting = relay.poll(10_000);
      await t.controller.end(t.controller.current()!.callId);
      expect(await waiting).toMatchObject({ commands: [{ type: "close" }] });
      expect(t.endSession).toHaveBeenCalledOnce();
      expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "hung-up" });
      expect(t.relays.find(TOKEN.session_id, "x")).toBeNull();
    });

    it("ends the call when Fish ends the session", async () => {
      const t = fish();
      await t.controller.start({ auth: owner, ...BOT, client: "web" });
      t.relay().receive([{ type: "connected" }, { type: "ended", reason: "conversation_timeout" }]);
      expect(t.frames.at(-1)).toMatchObject({ status: "ended" });
      expect(t.controller.current()).toBeNull();
    });
  });

  it("refuses a call through OpenAI or Azure that brings no audio offer, before any session", async () => {
    const t = setup();
    await expect(t.controller.start({ auth: owner, ...BOT, client: "web" })).rejects.toMatchObject({ status: 400 });
    expect(t.deps.createSession).not.toHaveBeenCalled();
    expect(t.controller.current()).toBeNull();
  });

  it("asks nothing of the Azure limit for a call through OpenAI", async () => {
    const t = setup({ azureRefusal: vi.fn(() => "never asked") });
    await t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" });
    expect(t.deps.azureRefusal).not.toHaveBeenCalled();
    expect(t.deps.createSession).toHaveBeenCalledOnce();
  });

  it("starts a phone's call with no plan at all once a key exists, through the companion or by the phone's own client", async () => {
    for (const input of [{ client: "ios", device: "phone-1" }, { client: "android", device: "phone-2" }, { client: "ios" }, { client: "android" }] as const) {
      const t = setup();
      const { call } = await t.controller.start({ auth: owner, ...BOT, ...input, sdp: "offer-sdp" });
      expect(call, JSON.stringify(input)).toMatchObject({ client: input.client, status: "connecting" });
      expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ key: "sk-test" }));
      t.socket().open();
      expect(t.controller.current()).toMatchObject({ callId: call.callId, status: "live" });
    }
  });

  it("frees the slot when OpenAI refuses the session", async () => {
    const t = setup({ createSession: vi.fn().mockRejectedValueOnce(new LiveSessionError("nope", 502)).mockResolvedValue({ sessionId: "sess_2", sdp: "x" }) });
    await expect(t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" })).rejects.toBeInstanceOf(LiveSessionError);
    expect(t.controller.current()).toBeNull();
    await expect(t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" })).resolves.toBeTruthy();
  });

  it("ends with sideband-lost when attach is refused", async () => {
    const t = setup();
    await t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" });
    t.socket().refuse();
    expect(t.controller.current()).toBeNull();
    expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost" });
    expect(t.logs.some((line) => line.startsWith("[live] call ended") && line.includes("end=sideband-lost"))).toBe(true);
  });

  it("ends with sideband-lost and leaves no timer when the sideband cannot be opened", async () => {
    const t = setup({ openSocket: () => { throw new Error("bad url"); } });
    const result = await t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" });
    expect(result.call).toMatchObject({ status: "ended", endReason: "sideband-lost" });
    expect(t.controller.current()).toBeNull();
    expect(t.listeners.size).toBe(0);
    expect(vi.getTimerCount()).toBe(0);
  });

  it("sends one session.close when asked to hang up twice", async () => {
    const t = setup();
    const { call } = await t.start();
    const first = t.controller.end(call.callId);
    const second = t.controller.end(call.callId);
    expect(t.socket().sent.filter((e) => e.type === "session.close")).toHaveLength(1);
    t.socket().receive({ type: "session.closed", reason: "close_requested" });
    await expect(first).resolves.toMatchObject({ status: "ended", endReason: "hung-up" });
    await expect(second).resolves.toMatchObject({ status: "ended", endReason: "hung-up" });
  });

  it.each(["request", "approval"])("does not dispatch a settled spoken %s after hang-up", async (kind) => {
    const t = setup();
    const { call } = await t.start();
    if (kind === "approval") {
      t.message({ id: "approval", kind: "options", card: { title: "Approval needed", subtitle: "delete build", options: ["Allow", "Deny"], requestId: "r1", tool: "Bash" } });
      await vi.advanceTimersByTimeAsync(0);
    }
    t.socket().receive({ type: "session.input_transcript.delta", delta: kind === "approval" ? "yes" : "delete build", start_ms: 100, end_ms: 200 });
    t.socket().receive({ type: "session.delegation.created", offset_ms: 250, delegation: { id: "late", target: "client" } });
    const ending = t.controller.end(call.callId);
    await vi.advanceTimersByTimeAsync(CONSENT_SETTLE_MS + 1);
    expect(t.controller.current()?.status).toBe("ending");
    expect(t.deps.send).not.toHaveBeenCalled();
    expect(t.deps.respond).not.toHaveBeenCalled();
    t.socket().receive({ type: "session.closed", reason: "close_requested" });
    await ending;
  });

  it("ends with sideband-lost when attach never opens", async () => {
    const t = setup();
    await t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" });
    await vi.advanceTimersByTimeAsync(ATTACH_TIMEOUT_MS + 1);
    expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost" });
  });

  it("ends with sideband-lost when the sideband drops mid-call", async () => {
    const t = setup();
    await t.start();
    t.socket().drop();
    expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost" });
  });

  it("hangs up gracefully: session.close, then session.closed", async () => {
    const t = setup();
    const { call } = await t.start();
    const ending = t.controller.end(call.callId);
    expect(t.socket().sent.at(-1)).toMatchObject({ type: "session.close" });
    expect(t.frames.at(-1)?.status).toBe("ending");
    t.socket().receive({ type: "session.closed", reason: "close_requested", usage: { seconds: 61 } });
    await expect(ending).resolves.toMatchObject({ status: "ended", endReason: "hung-up" });
    expect(t.logs.at(-1)).toContain("seconds=61");
  });

  it("finishes a hang-up after 5 s without session.closed", async () => {
    const t = setup();
    const { call } = await t.start();
    const ending = t.controller.end(call.callId);
    await vi.advanceTimersByTimeAsync(CLOSE_TIMEOUT_MS + 1);
    await expect(ending).resolves.toMatchObject({ status: "ended", endReason: "hung-up" });
  });

  it("returns null when asked to end an unknown call", async () => {
    const t = setup();
    await t.start();
    await expect(t.controller.end("other")).resolves.toBeNull();
  });

  it("maps OpenAI's close reasons", async () => {
    const t = setup();
    await t.start();
    t.socket().receive({ type: "session.closed", reason: "expired", usage: { seconds: 3600 } });
    expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "expired" });
  });

  it("hangs up after the idle minutes without speech or work", async () => {
    const t = setup();
    await t.start();
    await vi.advanceTimersByTimeAsync(4 * 60_000);
    t.socket().receive({ type: "session.input_transcript.delta", delta: "hi", start_ms: 1, end_ms: 2 });
    await vi.advanceTimersByTimeAsync(4 * 60_000);
    expect(t.socket().sent.some((e) => e.type === "session.close")).toBe(false);
    await vi.advanceTimersByTimeAsync(60_000 + IDLE_CHECK_MS);
    expect(t.socket().sent.at(-1)).toMatchObject({ type: "session.close" });
    t.socket().receive({ type: "session.closed", reason: "close_requested" });
    expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "idle" });
  });

  it("keeps a standby call live while paused, then applies the app idle hang-up", async () => {
    const t = setup();
    t.settings.idleMinutes = 1;
    const { call } = await t.start();
    t.socket().receive({ type: "session.paused" });
    expect(t.controller.current()).toMatchObject({ callId: call.callId, status: "live" });
    await vi.advanceTimersByTimeAsync(60_000);
    expect(t.socket().sent.at(-1)).toMatchObject({ type: "session.close" });
    t.socket().receive({ type: "session.closed", reason: "close_requested" });
    expect(t.frames.at(-1)).toMatchObject({ callId: call.callId, status: "ended", endReason: "idle" });
  });

  it("does not hang up while the bot works, but does while an approval waits", async () => {
    const t = setup();
    await t.start();
    t.setActivity("working");
    await vi.advanceTimersByTimeAsync(10 * 60_000);
    expect(t.socket().sent.some((e) => e.type === "session.close")).toBe(false);
    t.setActivity("waiting");
    await vi.advanceTimersByTimeAsync(5 * 60_000 + IDLE_CHECK_MS);
    expect(t.socket().sent.some((e) => e.type === "session.close")).toBe(true);
  });

  it("ends the call when the thread is deleted", async () => {
    const t = setup();
    await t.start();
    t.emit({ type: "thread.deleted", threadId: "t1" });
    await vi.advanceTimersByTimeAsync(0);
    expect(t.socket().sent.at(-1)).toMatchObject({ type: "session.close" });
    await vi.advanceTimersByTimeAsync(CLOSE_TIMEOUT_MS + 1);
    expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "deleted" });
    expect(t.listeners.size).toBe(0);
  });

  it("shutdown closes the session and clears every timer", async () => {
    const t = setup();
    await t.start();
    await t.controller.shutdown();
    expect(t.socket().sent.at(-1)).toMatchObject({ type: "session.close" });
    expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "shutdown" });
    expect(vi.getTimerCount()).toBe(0);
  });

  describe("with Gemini chosen", () => {
    const GEMINI: LiveEndpoint = { provider: "gemini", apiBase: "https://generativelanguage.googleapis.com/v1beta", model: "gemini-3.8-live" };
    const SESSION: LiveGeminiSession = {
      session_id: "gemini_1", token: "auth_tokens/abc", model: "models/gemini-3.8-live", expires_at: "2026-11-14T00:01:00Z",
      ws_url: "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained",
    };
    const gemini = (overrides: Partial<LiveCallDeps> = {}) => {
      const relays = new FishRelays();
      let relayToken = "";
      const t = setup({
        createSession: vi.fn(async () => {
          relayToken = relays.open(SESSION.session_id, async () => undefined).token;
          return { sessionId: SESSION.session_id, gemini: { type: "gemini" as const, session: SESSION, relayToken } };
        }),
        openSocket: (url) => relays.socket(url),
        attachUrl: (id) => id,
        ...overrides,
      });
      t.settings.endpoint = GEMINI;
      t.settings.provider = "gemini";
      const relay = () => relays.find(SESSION.session_id, relayToken)!;
      return { ...t, relays, relay };
    };

    it("asks who is calling, starts with no SDP, and answers with Gemini's token and the relay's token", async () => {
      const t = gemini();
      const started = await t.controller.start({ auth: owner, ...BOT, client: "web" });
      expect(t.deps.geminiRefusal).toHaveBeenCalledWith(owner);
      expect(t.deps.fishRefusal).not.toHaveBeenCalled();
      expect(t.deps.azureRefusal).not.toHaveBeenCalled();
      expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ endpoint: GEMINI, sdp: "" }));
      expect(started.sdp).toBeUndefined();
      expect(started.fish).toBeUndefined();
      expect(started.gemini).toEqual({ type: "gemini", session: SESSION, relayToken: expect.stringMatching(/^[\w-]{43}$/) });
      expect(started).not.toHaveProperty("sessionId");
    });

    it("starts in the Gemini voice chosen for Gemini calls, never the GPT-Live one", async () => {
      const t = gemini();
      Object.assign(t.settings, { voice: "cedar", geminiVoice: "Charon" });
      await t.controller.start({ auth: owner, ...BOT, client: "web" });
      expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ voice: "Charon" }));
      const plain = gemini();
      Object.assign(plain.settings, { voice: "cedar" });
      await plain.controller.start({ auth: owner, ...BOT, client: "web" });
      expect(plain.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ voice: "Puck" }));
    });

    it("speaks in the called bot's own Gemini voice, and the app's when the bot's is GPT-Live's", async () => {
      const voices: Record<string, string> = { bot1: "Kore", bot2: "cedar" };
      const t = gemini({ botVoice: (botId) => voices[botId] });
      Object.assign(t.settings, { geminiVoice: "Charon" });
      await t.controller.start({ auth: owner, ...BOT, client: "web" });
      expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ voice: "Kore" }));
      const other = gemini({ botVoice: (botId) => voices[botId] });
      Object.assign(other.settings, { geminiVoice: "Charon" });
      await other.controller.start({ auth: owner, ...BOT, botId: "bot2", client: "web" });
      expect(other.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ voice: "Charon" }));
    });

    it("refuses with the reason as a 403 before any session is taken", async () => {
      const t = gemini({ geminiRefusal: () => "not you" });
      await expect(t.controller.start({ auth: owner, ...BOT, client: "web" })).rejects.toMatchObject({ status: 403, message: "not you" });
      expect(t.deps.createSession).not.toHaveBeenCalled();
    });

    it("sends a phone to the desktop app or a browser", async () => {
      for (const client of ["ios", "android"] as const) {
        const t = gemini();
        await expect(t.controller.start({ auth: owner, ...BOT, client })).rejects.toMatchObject({ status: 400, message: LIVE_GEMINI_NEEDS_APP });
        expect(t.deps.createSession).not.toHaveBeenCalled();
      }
    });

    it("lets a phone app that runs Gemini's session itself start the call", async () => {
      for (const client of ["ios", "android"] as const) {
        const t = gemini();
        const started = await t.controller.start({ auth: owner, ...BOT, client, relays: ["gemini"] });
        expect(started.gemini?.type).toBe("gemini");
        expect(t.deps.createSession).toHaveBeenCalledTimes(1);
      }
    });

    it("never calls Gemini with a key saved for another provider", async () => {
      const t = gemini();
      t.settings.endpoint = { provider: "fish", apiBase: "https://api.fish.audio/v1/agent", model: "agent_1" };
      await expect(t.controller.start({ auth: owner, ...BOT, client: "web" })).rejects.toMatchObject({ status: 409 });
      expect(t.deps.createSession).not.toHaveBeenCalled();
    });

    it("waits as long as for Fish Audio for the client to join, then says Gemini could not connect", async () => {
      const t = gemini();
      await t.controller.start({ auth: owner, ...BOT, client: "web" });
      await vi.advanceTimersByTimeAsync(FISH_ATTACH_TIMEOUT_MS + 1);
      expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost", error: "The call could not connect to Gemini." });
    });

    it("takes a request heard by the client to the bot and returns the answer to the delegate call", async () => {
      const t = gemini();
      await t.controller.start({ auth: owner, ...BOT, client: "web" });
      const callId = t.controller.current()!.callId;
      t.relay().receive([{ type: "connected" }]);
      expect(t.controller.current()?.status).toBe("live");
      t.relay().receive([{ type: "heard", text: "check my mail", startMs: 100, endMs: 900 }, { type: "delegate", id: "fc_1", atMs: 950 }]);
      await vi.advanceTimersByTimeAsync(DELEGATION_SETTLE_MS + 1);
      expect(t.deps.send).toHaveBeenCalledWith({ auth: owner, botId: "bot1", threadId: "t1", text: "check my mail", callId });
      t.message({ id: "b1", text: "You have two new emails.", requestMessageId: "m1" });
      t.patch({ id: "b1", text: "You have two new emails.", requestMessageId: "m1", turnTerminal: true, turnSucceeded: true });
      await vi.advanceTimersByTimeAsync(0);
      const { commands } = await t.relay().poll(0);
      expect(commands).toContainEqual({ type: "append", kind: "commentary", content: "You have two new emails.", delegationId: "fc_1" });
    });
  });

  describe("with ElevenLabs chosen", () => {
    const ELEVENLABS: LiveEndpoint = { provider: "elevenlabs", apiBase: "https://api.elevenlabs.io/v1/convai", model: "agent_1" };
    const SESSION: LiveElevenLabsSession = {
      session_id: "elevenlabs_1", signed_url: "wss://api.elevenlabs.io/v1/convai/conversation?agent_id=agent_1&conversation_signature=s",
      instructions: "Be brief.", expires_at: "2026-11-14T00:01:00Z",
    };
    const elevenlabs = (overrides: Partial<LiveCallDeps> = {}) => {
      const relays = new FishRelays();
      let relayToken = "";
      const t = setup({
        createSession: vi.fn(async () => {
          relayToken = relays.open(SESSION.session_id, async () => undefined).token;
          return { sessionId: SESSION.session_id, elevenlabs: { type: "elevenlabs" as const, session: SESSION, relayToken } };
        }),
        openSocket: (url) => relays.socket(url),
        attachUrl: (id) => id,
        ...overrides,
      });
      t.settings.endpoint = ELEVENLABS;
      t.settings.provider = "elevenlabs";
      const relay = () => relays.find(SESSION.session_id, relayToken)!;
      return { ...t, relay };
    };

    it("asks who is calling, starts with no SDP, and answers with the signed URL and the relay's token", async () => {
      const t = elevenlabs();
      const started = await t.controller.start({ auth: owner, ...BOT, client: "web" });
      expect(t.deps.elevenlabsRefusal).toHaveBeenCalledWith(owner);
      expect(t.deps.geminiRefusal).not.toHaveBeenCalled();
      expect(t.deps.fishRefusal).not.toHaveBeenCalled();
      expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ endpoint: ELEVENLABS, sdp: "", voice: FISH_AGENT_VOICE }));
      expect(started.sdp).toBeUndefined();
      expect(started.gemini).toBeUndefined();
      expect(started.elevenlabs).toEqual({ type: "elevenlabs", session: SESSION, relayToken: expect.stringMatching(/^[\w-]{43}$/) });
    });

    it("refuses with the reason as a 403 before any session is taken", async () => {
      const t = elevenlabs({ elevenlabsRefusal: () => "not you" });
      await expect(t.controller.start({ auth: owner, ...BOT, client: "web" })).rejects.toMatchObject({ status: 403, message: "not you" });
      expect(t.deps.createSession).not.toHaveBeenCalled();
    });

    it("sends a phone to the desktop app or a browser", async () => {
      for (const client of ["ios", "android"] as const) {
        const t = elevenlabs();
        await expect(t.controller.start({ auth: owner, ...BOT, client })).rejects.toMatchObject({ status: 400, message: LIVE_ELEVENLABS_NEEDS_APP });
        expect(t.deps.createSession).not.toHaveBeenCalled();
      }
    });

    it("never calls ElevenLabs with a key saved for another provider", async () => {
      const t = elevenlabs();
      t.settings.endpoint = { provider: "gemini", apiBase: "https://generativelanguage.googleapis.com/v1beta", model: "m" };
      await expect(t.controller.start({ auth: owner, ...BOT, client: "web" })).rejects.toMatchObject({ status: 409 });
      expect(t.deps.createSession).not.toHaveBeenCalled();
    });

    it("waits as long as for Fish Audio for the client to join, then says ElevenLabs could not connect", async () => {
      const t = elevenlabs();
      await t.controller.start({ auth: owner, ...BOT, client: "web" });
      await vi.advanceTimersByTimeAsync(FISH_ATTACH_TIMEOUT_MS + 1);
      expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost", error: "The call could not connect to ElevenLabs." });
    });

    it("takes a request heard by the client to the bot and returns the answer to the delegate call", async () => {
      const t = elevenlabs();
      await t.controller.start({ auth: owner, ...BOT, client: "web" });
      const callId = t.controller.current()!.callId;
      t.relay().receive([{ type: "connected" }, { type: "heard", text: "check my mail", startMs: 100, endMs: 900 }, { type: "delegate", id: "tc_1", atMs: 950 }]);
      await vi.advanceTimersByTimeAsync(DELEGATION_SETTLE_MS + 1);
      expect(t.deps.send).toHaveBeenCalledWith({ auth: owner, botId: "bot1", threadId: "t1", text: "check my mail", callId });
      t.message({ id: "b1", text: "You have two new emails.", requestMessageId: "m1" });
      t.patch({ id: "b1", text: "You have two new emails.", requestMessageId: "m1", turnTerminal: true, turnSucceeded: true });
      await vi.advanceTimersByTimeAsync(0);
      const { commands } = await t.relay().poll(0);
      expect(commands).toContainEqual({ type: "append", kind: "commentary", content: "You have two new emails.", delegationId: "tc_1" });
    });
  });

  describe("a start cancelled while the provider creates the session", () => {
    function pendingSession(socket?: LiveSocket) {
      type Session = { sessionId: string; sdp: string; socket?: LiveSocket };
      let resolve!: (value: Session) => void;
      const createSession = vi.fn(() => new Promise<Session>((done) => { resolve = done; }));
      return { createSession, answer: () => resolve({ sessionId: "sess_9", sdp: "answer-sdp", socket }) };
    }

    it("closes the session it created through the sideband", async () => {
      const pending = pendingSession();
      const t = setup({ createSession: pending.createSession });
      const starting = t.controller.start({ auth: owner, ...BOT, client: "ios", sdp: "offer-sdp" });
      const callId = t.controller.current()!.callId;
      await t.controller.end(callId);
      pending.answer();
      await expect(starting).rejects.toMatchObject({ status: 503 });
      const orphan = t.socket();
      expect(orphan.url).toBe("ws://fake/sess_9/attach");
      expect(orphan.key).toBe("sk-test");
      orphan.open();
      expect(orphan.sent).toEqual([expect.objectContaining({ type: "session.close" })]);
      expect(orphan.readyState).toBe(3);
      expect(vi.getTimerCount()).toBe(0);
    });

    it("gives up on a sideband that never opens, leaving no timer behind", async () => {
      const pending = pendingSession();
      const t = setup({ createSession: pending.createSession });
      const starting = t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "offer-sdp" });
      await t.controller.shutdown();
      pending.answer();
      await expect(starting).rejects.toMatchObject({ status: 503 });
      await vi.advanceTimersByTimeAsync(ATTACH_TIMEOUT_MS + 1);
      expect(t.socket().readyState).toBe(3);
      expect(t.socket().sent).toEqual([]);
      expect(vi.getTimerCount()).toBe(0);
    });

    it("closes an already-open Codex socket returned after shutdown", async () => {
      const socket = new FakeSocket("", "");
      socket.open();
      const pending = pendingSession(socket);
      const t = setup({ createSession: pending.createSession, codexRefusal: () => null, openSocket: vi.fn() });
      t.settings.provider = "codex";
      t.settings.endpoint = CODEX_ENDPOINT;
      t.settings.key = "";
      const starting = t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "offer-sdp" });
      await t.controller.shutdown();
      pending.answer();
      await expect(starting).rejects.toMatchObject({ status: 503 });
      expect(socket.readyState).toBe(3);
      expect(t.deps.openSocket).not.toHaveBeenCalled();
      expect(vi.getTimerCount()).toBe(0);
    });
  });

  it("frees the slot when setting up the call fails after the session exists", async () => {
    let fail = true;
    const t = setup({ activity: () => { if (fail) throw new Error("no such bot"); return "idle"; } });
    await expect(t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" })).rejects.toThrow("no such bot");
    expect(t.controller.current()).toBeNull();
    expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "error" });
    const orphan = t.socket();
    expect(orphan.url).toBe("ws://fake/sess_1/attach");
    orphan.open();
    expect(orphan.sent).toEqual([expect.objectContaining({ type: "session.close" })]);
    expect(orphan.readyState).toBe(3);
    expect(vi.getTimerCount()).toBe(0);
    fail = false;
    await expect(t.start()).resolves.toBeTruthy();
  });

  it("survives a failing relay step or broadcast and counts it, without crashing the harness", async () => {
    let failing = false;
    const boom = (what: string) => { if (failing) throw new Error(what); };
    const t = setup({
      speakable: () => { throw new Error("tts prep broke"); },
      activity: () => { boom("no such bot"); return "idle"; },
      broadcast: () => boom("sse down"),
    });
    await t.start();
    failing = true;
    t.message({ id: "u1", role: "user", kind: "text", text: "hi", sendId: "s1" });
    t.patch({ id: "b1", text: "Hello.", requestMessageId: "u1", turnTerminal: true });
    t.emit({ type: "bot", botId: "bot1" });
    await vi.advanceTimersByTimeAsync(IDLE_CHECK_MS + 1);
    expect(t.controller.current()?.status).toBe("live");
    t.socket().receive({ type: "session.closed", reason: "close_requested" });
    expect(t.controller.current()).toBeNull();
    expect(t.logs.at(-1)).toMatch(/errors=internal,internal,internal,broadcast$/);
  });

  describe("a call bound to the phone or sign-in that started it", () => {
    const fromPhone = (t: ReturnType<typeof setup>, device = "phone-1") =>
      t.controller.start({ auth: owner, device, ...BOT, client: "ios", sdp: "offer-sdp" });

    it("ends at once, and says why, when that phone is unpaired", async () => {
      const t = setup();
      await fromPhone(t);
      t.socket().open();
      const ending = t.controller.deviceRevoked("phone-1");
      expect(ending).toMatchObject({ status: "ending" });
      expect(t.socket().appends("commentary")).toEqual([expect.objectContaining({ content: LIVE_COPY.unpaired })]);
      expect(t.socket().sent.at(-1)).toMatchObject({ type: "session.close" });
      t.socket().receive({ type: "session.closed", reason: "close_requested" });
      expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "signed-out", error: LIVE_COPY.unpaired });
      expect(t.logs.at(-1)).toContain("end=signed-out");
    });

    it("ends a call that is still connecting to OpenAI", async () => {
      const t = setup();
      await fromPhone(t);
      t.controller.deviceRevoked("phone-1");
      expect(t.controller.current()).toBeNull();
      expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "signed-out" });
    });

    it("leaves a call from another phone, or from the computer, alone", async () => {
      const t = setup();
      await fromPhone(t, "phone-2");
      t.socket().open();
      expect(t.controller.deviceRevoked("phone-1")).toBeNull();
      expect(t.controller.current()?.status).toBe("live");
      await t.controller.shutdown();

      const desktop = setup();
      await desktop.start();
      expect(desktop.controller.deviceRevoked("phone-1")).toBeNull();
      expect(desktop.controller.current()?.status).toBe("live");
    });

    it("refuses a call from a phone that was already unpaired, before creating a session", async () => {
      const t = setup();
      t.controller.deviceRevoked("phone-1");
      await expect(fromPhone(t)).rejects.toBeInstanceOf(LiveCallSignedOutError);
      expect(t.deps.createSession).not.toHaveBeenCalled();
      await expect(fromPhone(t, "phone-2")).resolves.toBeTruthy();
    });

    it("ends at once when the sign-in that started it is revoked", async () => {
      const t = setup();
      const session = { id: "s1", tokenHash: "x".repeat(64), label: "Safari on Mac", scopes: ["admin" as const], createdAt: 0, lastSeenAt: 0, expiresAt: 0 };
      await t.controller.start({ auth: { kind: "session", session, via: "cookie", scopes: ["admin"] }, ...BOT, client: "desktop", sdp: "offer-sdp" });
      t.socket().open();
      expect(t.controller.sessionRevoked("s2")).toBeNull();
      expect(t.controller.sessionRevoked("s1")).toMatchObject({ status: "ending" });
      expect(t.socket().appends("commentary")).toEqual([expect.objectContaining({ content: LIVE_COPY.signedOut })]);
      t.socket().receive({ type: "session.closed", reason: "close_requested" });
      expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "signed-out", error: LIVE_COPY.signedOut });
    });
  });

  it("skips mirrored audio without parsing it and never logs speech", async () => {
    const t = setup();
    await t.start();
    t.socket().onmessage?.({ data: `{"type":"session.input_audio.append","audio":"${"A".repeat(50_000)}"}` });
    t.socket().receive({ type: "session.input_transcript.delta", delta: "my secret plan", start_ms: 1, end_ms: 2 });
    await t.controller.shutdown();
    expect(t.logs.join("\n")).not.toContain("secret");
  });
});

describe("LiveCallController relay", () => {
  async function live(overrides: Partial<LiveCallDeps> = {}) {
    const t = setup(overrides);
    await t.start();
    return t;
  }
  const hear = (t: ReturnType<typeof setup>, text: string, at: number, until = at + 100) =>
    t.socket().receive({ type: "session.input_transcript.delta", delta: text, start_ms: at, end_ms: until });
  const delegate = async (t: ReturnType<typeof setup>, id: string, offset: number) => {
    t.socket().receive({ type: "session.delegation.created", offset_ms: offset, delegation: { id, target: "client", type: "delegation" } });
    await vi.advanceTimersByTimeAsync(DELEGATION_SETTLE_MS + 1);
  };

  describe("when the sign-in that started the call ends", () => {
    const signedOut = (t: ReturnType<typeof setup>) => t.socket().appends("commentary").filter((e) => e.content === LIVE_COPY.signedOut);

    it("says so once and hangs up instead of retrying a request", async () => {
      const t = await live({ send: vi.fn(async () => { throw new LiveCallSignedOutError(); }) });
      hear(t, "what is on my calendar", 100);
      await delegate(t, "del_1", 400);
      expect(signedOut(t)).toEqual([expect.objectContaining({ delegation_id: "del_1" })]);
      expect(t.socket().appends("commentary").some((e) => String(e.content).includes("could not be sent"))).toBe(false);
      expect(t.socket().sent.at(-1)).toMatchObject({ type: "session.close" });
      hear(t, "and tomorrow", 2_000);
      await delegate(t, "del_2", 2_300);
      expect(signedOut(t)).toHaveLength(1);
      expect(t.socket().appends("commentary").some((e) => String(e.content).includes("could not be sent"))).toBe(false);
      expect(t.socket().sent.filter((e) => e.type === "session.close")).toHaveLength(1);
      t.socket().receive({ type: "session.closed", reason: "close_requested" });
      expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "signed-out", error: LIVE_COPY.signedOut });
      expect(t.logs.at(-1)).toContain("end=signed-out");
      expect(t.logs.at(-1)).toContain("errors=signed-out");
    });

    it("hangs up when a spoken decision is refused for the same reason", async () => {
      const t = await live({ respond: vi.fn(async () => { throw new LiveCallSignedOutError(); }) });
      t.message({ id: "c1", kind: "options", card: { title: "Approval needed", subtitle: "ls", options: ["Allow", "Deny"], requestId: "r1", tool: "Bash" } });
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "yes", 5_000);
      await delegate(t, "del_2", 5_100);
      expect(signedOut(t)).toEqual([expect.objectContaining({ delegation_id: "del_2" })]);
      expect(t.socket().appends("commentary").some((e) => String(e.content).includes("could not be saved"))).toBe(false);
      expect(t.socket().sent.at(-1)).toMatchObject({ type: "session.close" });
    });

    it("hangs up when a spoken answer to a question is refused for the same reason", async () => {
      const t = await live({ respond: vi.fn(async () => { throw new LiveCallSignedOutError(); }) });
      t.message({ id: "q1", kind: "options", card: { title: "A question", subtitle: "Which account?", options: [], requestId: "r7" } });
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "savings", 5_000);
      await delegate(t, "del_2", 5_100);
      expect(signedOut(t)).toHaveLength(1);
      expect(t.socket().sent.at(-1)).toMatchObject({ type: "session.close" });
    });

    it("hangs up at the next idle check even while the person keeps talking", async () => {
      let signedIn = true;
      const t = await live({ signedIn: () => signedIn });
      hear(t, "hello", 100);
      await vi.advanceTimersByTimeAsync(IDLE_CHECK_MS);
      expect(t.socket().sent.some((e) => e.type === "session.close")).toBe(false);
      signedIn = false;
      hear(t, "still here", 20_000);
      await vi.advanceTimersByTimeAsync(IDLE_CHECK_MS);
      expect(signedOut(t)).toEqual([expect.objectContaining({ delegation_id: null })]);
      expect(t.socket().sent.at(-1)).toMatchObject({ type: "session.close" });
    });
  });

  describe("a spoken request to hang up", () => {
    const closes = (t: ReturnType<typeof setup>) => t.socket().sent.filter((e) => e.type === "session.close");

    it("says goodbye, then ends the call the way the End button does", async () => {
      const t = await live();
      hear(t, "okay, thanks, you can hang up now.", 100);
      await delegate(t, "del_1", 400);
      expect(t.deps.send).not.toHaveBeenCalled();
      expect(t.socket().appends("instructions").at(-1)).toMatchObject({ delegation_id: "del_1", content: LIVE_COPY.goodbye });
      expect(closes(t)).toHaveLength(0);
      hear(t, "wait", 1_000);
      await delegate(t, "del_2", 1_200);
      expect(t.deps.send).not.toHaveBeenCalled();
      await vi.advanceTimersByTimeAsync(GOODBYE_MS);
      expect(closes(t)).toHaveLength(1);
      t.socket().receive({ type: "session.closed", reason: "close_requested" });
      expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "hung-up" });
      expect(t.controller.current()).toBeNull();
    });

    it("says nothing about a request that fails to send after the goodbye", async () => {
      let fail: (error: Error) => void = () => {};
      const t = await live({ send: vi.fn(() => new Promise<never>((_resolve, reject) => { fail = reject; })) });
      hear(t, "check my mail", 100);
      await delegate(t, "del_1", 400);
      hear(t, "hang up", 1_000);
      await delegate(t, "del_2", 1_200);
      fail(new Error("offline"));
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("commentary")).toHaveLength(0);
    });

    it("never says an answer is missing when the bot stops during the goodbye", async () => {
      const t = await live();
      hear(t, "check my mail", 100);
      await delegate(t, "del_1", 400);
      t.setActivity("working");
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "hang up", 2_000);
      await delegate(t, "del_2", 2_200);
      t.setActivity("idle");
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("commentary").map((e) => e.content)).not.toContain(LIVE_COPY.noAnswer);
    });

    it("keeps the call for anything that is not a clear request to hang up", async () => {
      for (const text of ["don't hang up", "how do I end the call?", "hang up the poster in my room", "end the call with Sam on my calendar", "bye"]) {
        const t = await live();
        hear(t, text, 100);
        await delegate(t, "del_1", 400);
        expect(vi.mocked(t.deps.send).mock.calls.map(([input]) => input.text), text).toEqual([text]);
        await vi.advanceTimersByTimeAsync(GOODBYE_MS + CLOSE_TIMEOUT_MS);
        expect(closes(t), text).toHaveLength(0);
        expect(t.controller.current()?.status, text).toBe("live");
      }
    });

    it("never hangs up on the voice's own words heard back through a speaker", async () => {
      const t = await live();
      t.socket().receive({ type: "session.output_transcript.delta", delta: "Should I hang up?", start_ms: 1_000, end_ms: 2_000 });
      hear(t, "hang up", 1_200, 1_400);
      await delegate(t, "del_1", 1_500);
      await vi.advanceTimersByTimeAsync(GOODBYE_MS + CLOSE_TIMEOUT_MS);
      expect(closes(t)).toHaveLength(0);
      expect(t.socket().appends("instructions").some((e) => e.content === LIVE_COPY.goodbye)).toBe(false);
    });

    it("keeps the call when the words before \"hang up\" were heard over the voice", async () => {
      const t = await live();
      t.socket().receive({ type: "session.output_transcript.delta", delta: "Here is what I found.", start_ms: 1_000, end_ms: 2_000 });
      hear(t, "don't", 1_200, 1_400);
      hear(t, "hang up", 2_100, 2_300);
      await delegate(t, "del_1", 2_500);
      await vi.advanceTimersByTimeAsync(GOODBYE_MS + CLOSE_TIMEOUT_MS);
      expect(closes(t)).toHaveLength(0);
      expect(t.socket().appends("instructions").some((e) => e.content === LIVE_COPY.goodbye)).toBe(false);
    });

    it("speaks no more of the bot's answers once the goodbye starts", async () => {
      const t = await live();
      hear(t, "check my mail", 100);
      await delegate(t, "del_1", 300);
      hear(t, "okay, thanks, you can hang up now.", 1_000);
      await delegate(t, "del_2", 1_200);
      t.patch({ id: "b1", text: "You have two new emails.", requestMessageId: "m1", turnTerminal: true });
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("instructions").at(-1)).toMatchObject({ content: LIVE_COPY.goodbye });
      expect(t.socket().appends("commentary")).toHaveLength(0);
    });

    it("keeps the real end reason when the call drops during the goodbye", async () => {
      const t = await live();
      hear(t, "hang up", 100);
      await delegate(t, "del_1", 400);
      t.socket().drop();
      expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost" });
      await vi.advanceTimersByTimeAsync(GOODBYE_MS);
      expect(closes(t)).toHaveLength(0);
    });
  });

  it("sends the words since the last request to the bot, as the call's starter", async () => {
    const t = await live();
    const callId = t.controller.current()!.callId;
    hear(t, "what is on ", 100);
    hear(t, "my calendar", 200);
    await delegate(t, "del_1", 400);
    expect(t.deps.send).toHaveBeenCalledWith({ auth: owner, botId: "bot1", threadId: "t1", text: "what is on my calendar", callId });
    expect(t.socket().appends("thinking").at(-1)).toMatchObject({ delegation_id: "del_1", content: expect.stringContaining("You are working on the request") });
  });

  it("tags every spoken request with the call's id, however the harness took it", async () => {
    const t = await live();
    const callId = t.controller.current()!.callId;
    vi.mocked(t.deps.send)
      .mockResolvedValueOnce({ kind: "started", messageId: "m1" })
      .mockResolvedValueOnce({ kind: "steered", messageId: "m2" })
      .mockResolvedValueOnce({ kind: "queued", queueId: "q1" });
    hear(t, "check the build", 100);
    await delegate(t, "del_1", 300);
    hear(t, "and the tests", 2_000);
    await delegate(t, "del_2", 2_300);
    hear(t, "then deploy", 4_000);
    await delegate(t, "del_3", 4_300);
    expect(vi.mocked(t.deps.send).mock.calls.map(([input]) => [input.text, input.callId])).toEqual([
      ["check the build", callId],
      ["and the tests", callId],
      ["then deploy", callId],
    ]);
  });

  it("gives the next call an id of its own", async () => {
    const t = await live();
    const first = t.controller.current()!.callId;
    t.socket().drop();
    await t.start();
    const second = t.controller.current()!.callId;
    expect(second).not.toBe(first);
    hear(t, "hello again", 100);
    await delegate(t, "del_1", 300);
    expect(vi.mocked(t.deps.send).mock.calls.at(-1)![0].callId).toBe(second);
  });

  it("asks to repeat when nothing was heard", async () => {
    const t = await live();
    await delegate(t, "del_1", 400);
    expect(t.deps.send).not.toHaveBeenCalled();
    expect(t.socket().appends("instructions").at(-1)).toMatchObject({ delegation_id: "del_1", content: expect.stringContaining("not heard clearly") });
  });

  it("ignores delegations aimed at OpenAI's own tools", async () => {
    const t = await live();
    hear(t, "hello", 100);
    t.socket().receive({ type: "session.delegation.created", offset_ms: 300, delegation: { id: "d", target: "responses" } });
    await vi.advanceTimersByTimeAsync(DELEGATION_SETTLE_MS + 1);
    expect(t.deps.send).not.toHaveBeenCalled();
  });

  it("speaks only the turn's final answer, in the delegation it answers", async () => {
    const t = await live();
    hear(t, "check my mail", 100);
    await delegate(t, "del_1", 300);
    t.message({ id: "b1", text: "Let me look.", requestMessageId: "m1" });
    t.message({ id: "a1", kind: "activity", tool: { name: "gmail", spoken: "Reading your inbox" } });
    t.message({ id: "b2", text: "You have two new emails. One is from Sam.", requestMessageId: "m1" });
    t.patch({ id: "b2", text: "You have two new emails. One is from Sam.", requestMessageId: "m1", turnTerminal: true });
    t.patch({ id: "b2", text: "You have two new emails. One is from Sam.", requestMessageId: "m1", turnTerminal: true, turnSucceeded: true });
    await vi.advanceTimersByTimeAsync(0);
    const commentary = t.socket().appends("commentary");
    expect(commentary).toHaveLength(1);
    expect(commentary[0]).toMatchObject({ delegation_id: "del_1", content: "You have two new emails. One is from Sam." });
    expect(t.socket().appends("thinking").some((e) => String(e.content).includes("Reading your inbox"))).toBe(true);
    expect(JSON.stringify(t.socket().sent)).not.toContain("Let me look.");
  });

  it("rate-limits progress to one every 4 s", async () => {
    const t = await live();
    t.message({ id: "a1", kind: "activity", tool: { name: "x", spoken: "Step one" } });
    t.message({ id: "a2", kind: "activity", tool: { name: "x", spoken: "Step two" } });
    await vi.advanceTimersByTimeAsync(PROGRESS_INTERVAL_MS + 1);
    t.message({ id: "a3", kind: "activity", tool: { name: "x", spoken: "Step three" } });
    await vi.advanceTimersByTimeAsync(0);
    const progress = t.socket().appends("thinking").map((e) => String(e.content));
    expect(progress.filter((c) => c.startsWith("Progress:"))).toEqual(["Progress: Step one", "Progress: Step three"]);
  });

  it("says the result is in the chat when the turn ends without text", async () => {
    const t = await live();
    hear(t, "do it", 100);
    await delegate(t, "del_1", 300);
    // store listeners run in a microtask: flush between the two changes
    t.setActivity("working");
    await vi.advanceTimersByTimeAsync(0);
    t.setActivity("idle");
    await vi.advanceTimersByTimeAsync(0);
    expect(t.socket().appends("commentary").at(-1)).toMatchObject({ content: "I'm done. The result, or what went wrong, is in the chat." });
  });

  describe("a spoken request that waits in the queue", () => {
    const noAnswer = (t: ReturnType<typeof setup>) => t.socket().appends("commentary").filter((e) => e.content === LIVE_COPY.noAnswer);
    const queueNext = (t: ReturnType<typeof setup>, queueId: string) =>
      vi.mocked(t.deps.send).mockImplementationOnce(async () => {
        t.queue.add(queueId);
        return { kind: "queued", queueId };
      });

    it("is answered once it is delivered, with no missing-answer line", async () => {
      const t = await live();
      t.setActivity("working");
      queueNext(t, "q1");
      hear(t, "and then the weather", 100);
      await delegate(t, "del_1", 300);
      t.setActivity("idle");
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("commentary")).toHaveLength(0);
      t.queue.delete("q1");
      t.message({ id: "m9", role: "user", kind: "text", text: "and then the weather", via: "call", queueId: "q1" });
      t.setActivity("working");
      t.patch({ id: "b9", text: "Sunny.", requestMessageId: "m9", turnTerminal: true });
      await vi.advanceTimersByTimeAsync(0);
      t.setActivity("idle");
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("commentary")).toEqual([expect.objectContaining({ delegation_id: "del_1", content: "Sunny." })]);
    });

    it("still holds the missing-answer line back while it waits", async () => {
      const t = await live();
      hear(t, "do it", 100);
      await delegate(t, "del_1", 300);
      t.setActivity("working");
      await vi.advanceTimersByTimeAsync(0);
      queueNext(t, "q1");
      hear(t, "and then the weather", 2_000);
      await delegate(t, "del_2", 2_200);
      t.setActivity("idle");
      await vi.advanceTimersByTimeAsync(0);
      expect(noAnswer(t)).toHaveLength(0);
      expect(t.deps.queued).toHaveBeenCalledWith("bot1", "t1", "q1");
    });

    it("answers a drained batch of spoken lines once, without saying the result is in the chat", async () => {
      const t = await live();
      t.setActivity("working");
      await vi.advanceTimersByTimeAsync(0);
      queueNext(t, "q1");
      hear(t, "what is the weather", 100);
      await delegate(t, "del_1", 300);
      queueNext(t, "q2");
      hear(t, "and tomorrow", 2_000);
      await delegate(t, "del_2", 2_200);
      t.queue.clear();
      t.message({ id: "m1", role: "user", kind: "text", text: "what is the weather", via: "call", queueId: "q1" });
      t.message({ id: "m2", role: "user", kind: "text", text: "and tomorrow", via: "call", queueId: "q2" });
      t.patch({ id: "b1", text: "Sunny today and tomorrow.", requestMessageId: "m2", turnTerminal: true });
      await vi.advanceTimersByTimeAsync(0);
      t.setActivity("idle");
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("commentary")).toEqual([expect.objectContaining({ delegation_id: "del_2", content: "Sunny today and tomorrow." })]);
    });

    it("answers aloud a drained batch that holds a spoken line, even when a typed line came last", async () => {
      const t = await live();
      t.settings.readTypedReplies = false;
      t.setActivity("working");
      await vi.advanceTimersByTimeAsync(0);
      queueNext(t, "q1");
      hear(t, "what is the weather", 100);
      await delegate(t, "del_1", 300);
      t.queue.clear();
      t.message({ id: "m1", role: "user", kind: "text", text: "what is the weather", via: "call", queueId: "q1" });
      t.message({ id: "m2", role: "user", kind: "text", text: "in Utrecht", sendId: "s2", queueId: "q2" });
      t.patch({ id: "b1", text: "Sunny in Utrecht.", requestMessageId: "m2", turnTerminal: true });
      await vi.advanceTimersByTimeAsync(0);
      t.setActivity("idle");
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("commentary")).toEqual([expect.objectContaining({ delegation_id: "del_1", content: "Sunny in Utrecht." })]);
    });

    it("holds nothing back once it left the queue without being delivered", async () => {
      const t = await live();
      t.setActivity("working");
      queueNext(t, "q1");
      hear(t, "and then the weather", 100);
      await delegate(t, "del_1", 300);
      t.queue.delete("q1");
      t.setActivity("idle");
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "do it", 2_000);
      await delegate(t, "del_2", 2_200);
      t.setActivity("working");
      await vi.advanceTimersByTimeAsync(0);
      t.setActivity("idle");
      await vi.advanceTimersByTimeAsync(0);
      expect(noAnswer(t)).toEqual([expect.objectContaining({ delegation_id: "del_2" })]);
    });
  });

  describe("status notes while the bot works", () => {
    const notes = (t: ReturnType<typeof setup>) =>
      t.socket().appends("thinking").filter((e) => String(e.content).startsWith("Status note"));

    it("tells the voice every 30 s how long the bot has worked and what its last step was", async () => {
      const t = await live();
      t.setActivity("working");
      await vi.advanceTimersByTimeAsync(0);
      t.message({ id: "a1", kind: "activity", tool: { name: "mcp__team-notes__describe_database", summary: "Admin/Instruction" } });
      t.message({ id: "a2", kind: "activity", tool: { name: "mcp__team-notes__query_database", summary: "SELECT secrets FROM /Users/someone" } });
      await vi.advanceTimersByTimeAsync(29_000);
      expect(notes(t)).toHaveLength(0);
      await vi.advanceTimersByTimeAsync(2_000);
      expect(notes(t)).toHaveLength(1);
      const note = String(notes(t)[0].content);
      expect(note).toContain("you are still working on it");
      expect(note).toContain("2 steps");
      expect(note).toContain("team notes: query database");
      expect(note).not.toMatch(/secrets|\/Users/);
      expect(notes(t)[0].delegation_id).toBeNull();
      await vi.advanceTimersByTimeAsync(15_000);
      expect(notes(t)).toHaveLength(1);
      await vi.advanceTimersByTimeAsync(15_000);
      expect(notes(t)).toHaveLength(2);
      expect(String(notes(t)[1].content)).toContain("1 minute");
    });

    it("stops when the bot is done, and sends none while it waits for an answer", async () => {
      const t = await live();
      t.setActivity("working");
      await vi.advanceTimersByTimeAsync(31_000);
      expect(notes(t)).toHaveLength(1);
      t.setActivity("idle");
      await vi.advanceTimersByTimeAsync(0);
      await vi.advanceTimersByTimeAsync(90_000);
      expect(notes(t)).toHaveLength(1);
      t.setActivity("waiting");
      await vi.advanceTimersByTimeAsync(0);
      await vi.advanceTimersByTimeAsync(90_000);
      expect(notes(t)).toHaveLength(1);
    });

    it("counts a new piece of work from zero", async () => {
      const t = await live();
      t.setActivity("working");
      await vi.advanceTimersByTimeAsync(0);
      t.message({ id: "a1", kind: "activity", tool: { name: "Bash" } });
      await vi.advanceTimersByTimeAsync(31_000);
      t.setActivity("idle");
      await vi.advanceTimersByTimeAsync(0);
      t.setActivity("working");
      // notes ride on the 15 s idle tick: the next one lands 30–45 s after the work began
      await vi.advanceTimersByTimeAsync(46_000);
      const last = String(notes(t).at(-1)?.content);
      expect(last).toContain("0 steps");
      expect(last).not.toContain("run a command");
    });
  });

  it("says nothing when a message is typed, then reads the bot's answer once, with what was typed", async () => {
    const t = await live();
    const before = t.socket().sent.length;
    t.message({ id: "u1", role: "user", kind: "text", text: "kun je mij verstaan", sendId: "s1" });
    await vi.advanceTimersByTimeAsync(0);
    expect(t.socket().sent.length).toBe(before);
    t.patch({ id: "b1", text: "Ja, ik kan je verstaan.", requestMessageId: "u1", turnTerminal: true });
    await vi.advanceTimersByTimeAsync(0);
    const commentary = t.socket().appends("commentary");
    expect(commentary).toHaveLength(1);
    expect(commentary[0]).toMatchObject({ delegation_id: null, content: expect.stringContaining("kun je mij verstaan") });
    expect(commentary[0].content).toContain("Ja, ik kan je verstaan.");
    expect(t.socket().appends("thinking")).toHaveLength(0);
  });

  it("sends OpenAI nothing about a typed exchange when reading typed replies is off", async () => {
    const t = await live();
    t.settings.readTypedReplies = false;
    const before = t.socket().sent.length;
    t.message({ id: "u1", role: "user", kind: "text", text: "also book a table", sendId: "s1" });
    t.setActivity("working");
    await vi.advanceTimersByTimeAsync(0);
    t.message({ id: "a1", kind: "activity", tool: { name: "mcp__resy__book", spoken: "Booking at Luigi's" } });
    await vi.advanceTimersByTimeAsync(31_000 + IDLE_CHECK_MS);
    t.patch({ id: "b1", text: "Booked for eight.", requestMessageId: "u1", turnTerminal: true });
    t.setActivity("idle");
    await vi.advanceTimersByTimeAsync(0);
    expect(t.socket().sent.slice(before)).toEqual([]);
  });

  it("keeps telling the voice about work on a spoken request when typed replies are off", async () => {
    const t = await live();
    t.settings.readTypedReplies = false;
    hear(t, "check my mail", 100);
    await delegate(t, "del_1", 300);
    t.setActivity("working");
    await vi.advanceTimersByTimeAsync(0);
    t.message({ id: "a1", kind: "activity", tool: { name: "gmail", spoken: "Reading your inbox" } });
    await vi.advanceTimersByTimeAsync(31_000 + IDLE_CHECK_MS);
    const thinking = t.socket().appends("thinking").map((e) => String(e.content));
    expect(thinking).toContain("Progress: Reading your inbox");
    expect(thinking.some((c) => c.startsWith("Status note"))).toBe(true);
  });

  it("never relays a peer bot's line, or the answer to it, as something the person typed", async () => {
    const t = await live();
    const before = t.socket().sent.length;
    t.message({ id: "p1", role: "user", kind: "text", text: "[aside from Bo] the invoice is paid", aside: true, peerAsk: { botId: "bo", name: "Bo" } });
    t.message({ id: "p2", role: "user", kind: "text", text: "Bo asks: is the report ready?", peerAsk: { botId: "bo", name: "Bo" } });
    await vi.advanceTimersByTimeAsync(0);
    t.patch({ id: "b1", text: "Noted, thanks.", requestMessageId: "p1", turnTerminal: true });
    t.patch({ id: "b2", text: "Yes, it is in the shared folder.", requestMessageId: "p2", turnTerminal: true });
    await vi.advanceTimersByTimeAsync(0);
    expect(t.socket().sent.length).toBe(before);
    t.settings.readTypedReplies = false;
    t.message({ id: "p3", role: "user", kind: "text", text: "Bo asks: and the invoice?", peerAsk: { botId: "bo", name: "Bo" } });
    await vi.advanceTimersByTimeAsync(0);
    t.patch({ id: "b3", text: "Paid yesterday.", requestMessageId: "p3", turnTerminal: true });
    await vi.advanceTimersByTimeAsync(0);
    expect(t.socket().sent.length).toBe(before);
  });

  it("relays only a line the caller typed in a client", async () => {
    const t = await live();
    const before = t.socket().sent.length;
    const lines: Array<Partial<Message>> = [
      { sendId: "s1", sender: { name: "[email protected]", id: "p_sam" } },
      {},
      { sendId: "s3", via: "api" },
    ];
    lines.forEach((line, index) => t.message({ id: `u${index}`, role: "user", kind: "text", text: `line ${index}`, ...line }));
    await vi.advanceTimersByTimeAsync(0);
    lines.forEach((_, index) => t.patch({ id: `b${index}`, text: `Answer ${index}.`, requestMessageId: `u${index}`, turnTerminal: true }));
    await vi.advanceTimersByTimeAsync(0);
    expect(t.socket().sent.slice(before)).toEqual([]);

    t.message({ id: "u9", role: "user", kind: "text", text: "and mine", sendId: "s9" });
    await vi.advanceTimersByTimeAsync(0);
    t.patch({ id: "b9", text: "Done.", requestMessageId: "u9", turnTerminal: true });
    await vi.advanceTimersByTimeAsync(0);
    expect(t.socket().appends("commentary")).toEqual([expect.objectContaining({ content: expect.stringContaining("and mine") })]);
  });

  it("never reads a line a worker relayed into the call's chat back as the caller's own", async () => {
    const t = await live();
    const before = t.socket().sent.length;
    t.message({ id: "r1", role: "user", kind: "text", text: "Ada asks: is the report ready?", sendId: "slackjob_report_1", relayed: true });
    await vi.advanceTimersByTimeAsync(0);
    t.patch({ id: "b1", text: "Yes, it is in the shared folder.", requestMessageId: "r1", turnTerminal: true });
    await vi.advanceTimersByTimeAsync(0);
    expect(t.socket().sent.slice(before)).toEqual([]);
  });

  it("knows a signed-in caller's own lines by who sent them", async () => {
    const t = setup({ personKey: (auth) => (auth.kind === "session" ? "p_me" : undefined) });
    const session = { id: "s1", tokenHash: "x".repeat(64), label: "Safari", scopes: ["admin" as const], createdAt: 0, lastSeenAt: 0, expiresAt: 0 };
    await t.controller.start({ auth: { kind: "session", session, via: "cookie", scopes: ["admin"] }, ...BOT, client: "desktop", sdp: "offer-sdp" });
    t.socket().open();
    t.message({ id: "u1", role: "user", kind: "text", text: "from the owner's desk", sendId: "s1" });
    t.message({ id: "u2", role: "user", kind: "text", text: "from me", sendId: "s2", sender: { name: "[email protected]", id: "p_me" } });
    await vi.advanceTimersByTimeAsync(0);
    t.patch({ id: "b1", text: "One.", requestMessageId: "u1", turnTerminal: true });
    t.patch({ id: "b2", text: "Two.", requestMessageId: "u2", turnTerminal: true });
    await vi.advanceTimersByTimeAsync(0);
    const said = t.socket().appends("commentary").map((e) => String(e.content));
    expect(said).toHaveLength(1);
    expect(said[0]).toContain("from me");
  });

  it("keeps a typed message's idle clock running like speech", async () => {
    const t = await live();
    await vi.advanceTimersByTimeAsync(4 * 60_000);
    t.message({ id: "u1", role: "user", kind: "text", text: "still there?" });
    await vi.advanceTimersByTimeAsync(4 * 60_000);
    expect(t.socket().sent.some((e) => e.type === "session.close")).toBe(false);
  });

  describe("approvals", () => {
    const approval = (extra: Partial<Message["card"]> = {}) => ({
      id: "c1", kind: "options" as const,
      card: { title: "Approval needed", subtitle: "rm -rf build", options: ["Allow", "Deny"], requestId: "r1", tool: "Bash", ...extra },
    });

    it("reads the request and decides on a clear spoken yes", async () => {
      const t = await live();
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("instructions").at(-1)).toMatchObject({ content: expect.stringContaining("I want to run a command. rm -rf build. May I?") });
      hear(t, "yes go ahead", 5_000);
      await delegate(t, "del_2", 5_200);
      expect(t.deps.respond).toHaveBeenCalledWith({ auth: owner, threadId: "t1", requestId: "r1", behavior: "allow", message: undefined });
      expect(t.deps.send).not.toHaveBeenCalled();
      expect(t.socket().appends("commentary").at(-1)).toMatchObject({ content: "Thanks, I'll go ahead." });
    });

    it("denies with the call's reason", async () => {
      const t = await live();
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "no", 5_000);
      await delegate(t, "del_2", 5_100);
      expect(t.deps.respond).toHaveBeenCalledWith(expect.objectContaining({ behavior: "deny", message: "Denied by the user, on a live call." }));
    });

    it("asks again when the answer is not a clear yes or no", async () => {
      const t = await live();
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "hmm what does that do", 5_000);
      await delegate(t, "del_2", 5_200);
      expect(t.deps.respond).not.toHaveBeenCalled();
      expect(t.socket().appends("instructions").at(-1)).toMatchObject({ content: expect.stringContaining("not a clear yes or no") });
    });

    it.each(["yes, but do not delete it", "yes — wait, no", "yes, what does that delete?"])("never grants an ambiguous spoken decision: %s", async (said) => {
      const t = await live();
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      hear(t, said, 5_000);
      await vi.advanceTimersByTimeAsync(CONSENT_SETTLE_MS + 1);
      await delegate(t, "del_ambiguous", 5_200);
      expect(t.deps.respond).not.toHaveBeenCalled();
      expect(t.socket().appends("instructions").at(-1)).toMatchObject({ content: LIVE_COPY.notClear });
    });

    it("says nothing about a failed save once the person asked to hang up", async () => {
      let finish: (result: { ok: false; error: string }) => void = () => {};
      const t = await live({ respond: vi.fn(() => new Promise<{ ok: false; error: string }>((resolve) => { finish = resolve; })) });
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "yes go ahead", 5_000);
      await delegate(t, "del_2", 5_200);
      expect(t.deps.respond).toHaveBeenCalled();
      hear(t, "hang up", 6_000);
      await delegate(t, "del_3", 6_200);
      finish({ ok: false, error: "disk full" });
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("commentary").map((e) => e.content)).not.toContain(LIVE_COPY.saveFailed("disk full"));
    });

    it("grants nothing heard after the person asked to hang up", async () => {
      const t = await live();
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "hang up", 5_000);
      await delegate(t, "del_2", 5_200);
      hear(t, "yes", 5_400);
      await vi.advanceTimersByTimeAsync(CONSENT_SETTLE_MS + 1);
      expect(t.deps.respond).not.toHaveBeenCalled();
    });

    it("accepts a yes heard in a quiet moment, without a delegation", async () => {
      const t = await live();
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "yes", 5_000);
      await vi.advanceTimersByTimeAsync(CONSENT_SETTLE_MS + 1);
      expect(t.deps.respond).toHaveBeenCalledWith(expect.objectContaining({ behavior: "allow" }));
    });

    // The voice's own opener comes back through a phone's speaker as input, and "okay…" is a hedge, not a yes.
    describe("on the open microphone of a Live call", () => {
      const speak = (t: ReturnType<typeof setup>, text: string, at: number, until: number) =>
        t.socket().receive({ type: "session.output_transcript.delta", delta: text, start_ms: at, end_ms: until });

      it("never takes a hedging okay heard in a quiet moment as a yes", async () => {
        const t = await live();
        t.message(approval());
        await vi.advanceTimersByTimeAsync(0);
        hear(t, "okay", 5_000);
        await vi.advanceTimersByTimeAsync(CONSENT_SETTLE_MS + 1);
        hear(t, " wait, what does it delete", 7_000);
        await vi.advanceTimersByTimeAsync(CONSENT_SETTLE_MS + 1);
        expect(t.deps.respond).not.toHaveBeenCalled();
      });

      it("asks again when a delegated answer is only a hedge", async () => {
        const t = await live();
        t.message(approval());
        await vi.advanceTimersByTimeAsync(0);
        hear(t, "okay", 5_000);
        await delegate(t, "del_2", 5_100);
        expect(t.deps.respond).not.toHaveBeenCalled();
        expect(t.socket().appends("instructions").at(-1)).toMatchObject({ delegation_id: "del_2", content: LIVE_COPY.notClear });
      });

      it("does not take the voice's own words, heard back, for the person's answer", async () => {
        const t = await live();
        t.message(approval());
        await vi.advanceTimersByTimeAsync(0);
        speak(t, "Okay, I need your permission to run a command. May I?", 4_000, 6_000);
        hear(t, "Okay I need your permission to run a command", 4_100, 5_900);
        await vi.advanceTimersByTimeAsync(CONSENT_SETTLE_MS + 1);
        expect(t.deps.respond).not.toHaveBeenCalled();
        hear(t, "no", 7_000);
        await delegate(t, "del_2", 7_200);
        expect(t.deps.respond).toHaveBeenCalledWith(expect.objectContaining({ behavior: "deny" }));
      });

      it("asks for a clear answer when all it heard was the voice itself", async () => {
        const t = await live();
        t.message(approval());
        await vi.advanceTimersByTimeAsync(0);
        speak(t, "May I run it?", 4_000, 5_000);
        hear(t, "may I run it", 4_100, 4_900);
        await delegate(t, "del_2", 5_000);
        expect(t.deps.respond).not.toHaveBeenCalled();
        expect(t.socket().appends("instructions").at(-1)).toMatchObject({ delegation_id: "del_2", content: LIVE_COPY.notClear });
      });

      it("still takes a clear yes after a hedge", async () => {
        const t = await live();
        t.message(approval());
        await vi.advanceTimersByTimeAsync(0);
        hear(t, "okay, yes", 5_000);
        await vi.advanceTimersByTimeAsync(CONSENT_SETTLE_MS + 1);
        expect(t.deps.respond).toHaveBeenCalledWith(expect.objectContaining({ behavior: "allow" }));
      });
    });

    it("does not ask to repeat a yes the quiet window already decided when its delegation arrives late", async () => {
      const t = await live();
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "yes", 5_000);
      await vi.advanceTimersByTimeAsync(CONSENT_SETTLE_MS + 1);
      expect(t.deps.respond).toHaveBeenCalledTimes(1);
      t.patch({ ...approval({ answered: "allow" }) });
      await delegate(t, "del_2", 5_300);
      expect(t.socket().appends("instructions").some((e) => String(e.content).includes("not heard clearly"))).toBe(false);
      expect(t.socket().appends("thinking").at(-1)).toMatchObject({ delegation_id: "del_2", content: "Thanks, I'll go ahead." });
      expect(t.deps.send).not.toHaveBeenCalled();
      await delegate(t, "del_3", 20_000);
      expect(t.socket().appends("instructions").at(-1)).toMatchObject({ delegation_id: "del_3", content: expect.stringContaining("not heard clearly") });
    });

    it("lets the user try again when saving the decision fails", async () => {
      const t = await live({ respond: vi.fn().mockResolvedValueOnce({ ok: false, error: "The bot is not running." }).mockResolvedValue({ ok: true }) });
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "yes", 5_000);
      await delegate(t, "del_2", 5_100);
      expect(t.socket().appends("commentary").at(-1)).toMatchObject({ content: expect.stringContaining("could not be saved") });
      hear(t, "yes", 9_000);
      await delegate(t, "del_3", 9_100);
      expect(t.deps.respond).toHaveBeenCalledTimes(2);
    });

    it("lets the user try again when saving the decision throws", async () => {
      const t = await live({ respond: vi.fn().mockRejectedValueOnce(new Error("store offline")).mockResolvedValue({ ok: true }) });
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "yes", 5_000);
      await delegate(t, "del_2", 5_100);
      expect(t.socket().appends("commentary").at(-1)).toMatchObject({ content: "The decision could not be saved. Ask the user to try again." });
      hear(t, "yes", 9_000);
      await delegate(t, "del_3", 9_100);
      expect(t.deps.respond).toHaveBeenCalledTimes(2);
      expect(t.controller.current()?.status).toBe("live");
    });

    it("stays quiet when a tap on screen settled the card just before the spoken decision", async () => {
      let t!: ReturnType<typeof setup>;
      const respond = vi.fn(async () => {
        t.patch({ ...approval({ answered: "allow" }) });
        return { ok: false as const, error: "The request is no longer open." };
      });
      t = await live({ respond });
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      hear(t, "yes", 5_000);
      await delegate(t, "del_2", 5_100);
      expect(respond).toHaveBeenCalledTimes(1);
      const said = t.socket().appends("commentary").map((e) => String(e.content));
      expect(said).toEqual(["Thanks, I'll go ahead."]);
      expect(t.controller.current()?.status).toBe("live");
    });

    it("forgets an approval answered in the chat", async () => {
      const t = await live();
      t.message(approval());
      await vi.advanceTimersByTimeAsync(0);
      t.patch({ ...approval({ answered: "allow" }) });
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("thinking").at(-1)).toMatchObject({ content: expect.stringContaining("answered that request in the chat") });
      hear(t, "yes and also check the logs", 8_000);
      await delegate(t, "del_2", 8_100);
      expect(t.deps.respond).not.toHaveBeenCalled();
      expect(t.deps.send).toHaveBeenCalledWith(expect.objectContaining({ text: "yes and also check the logs" }));
    });

    it("sends harness reviews to the screen and never decides them by voice", async () => {
      const t = await live();
      t.message(approval({ tool: "stage_skill", title: "Enable the invoice skill", skillRequest: { action: "create" } as never }));
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("instructions").at(-1)).toMatchObject({ content: expect.stringContaining("you need their decision in the chat") });
      hear(t, "yes", 5_000);
      await delegate(t, "del_2", 5_100);
      expect(t.deps.respond).not.toHaveBeenCalled();
    });

    it("points the person at the chat when the bot needs an app connected", async () => {
      const t = await live();
      const connector = { slug: "gmail", label: "Gmail", description: "Read mail", status: "required" as const, resumeKey: "k1" };
      t.message({ id: "k1", kind: "connector", connector });
      t.patch({ id: "k1", kind: "connector", connector: { ...connector, status: "authorizing" } });
      await vi.advanceTimersByTimeAsync(0);
      const said = t.socket().appends("instructions").map((e) => String(e.content));
      expect(said).toHaveLength(1);
      expect(said[0]).toContain("Gmail");
      expect(said[0]).toContain("in the chat");
      t.message({ id: "k2", kind: "connector", connector: { ...connector, label: "Slack", status: "connected" } });
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("instructions")).toHaveLength(1);
    });

    it("points at the chat for a credential, and never asks for it aloud", async () => {
      const t = await live();
      const secret = { target: "openaiImageApiKey", label: "OpenAI image key", description: "", placeholder: "sk-", helpUrl: "", requestKey: "r1" } as never;
      t.message({ id: "k1", kind: "secret", secret });
      t.message({ id: "k2", kind: "secret", secret: { ...(secret as object), requestKey: "r2", superseded: true } as never });
      await vi.advanceTimersByTimeAsync(0);
      const said = t.socket().appends("instructions").map((e) => String(e.content));
      expect(said).toHaveLength(1);
      expect(said[0]).toContain("OpenAI image key");
      expect(said[0]).toMatch(/never ask .*aloud/i);
    });

    it("answers a bot question with the next request", async () => {
      const t = await live();
      t.message({ id: "q1", kind: "options", card: { title: "Your bot has a question", subtitle: "Which account?", options: ["Main", "Savings"], requestId: "r7" } });
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("instructions").at(-1)).toMatchObject({ content: expect.stringContaining("Which account?") });
      hear(t, "savings", 5_000);
      await delegate(t, "del_2", 5_100);
      expect(t.deps.respond).toHaveBeenCalledWith({ auth: owner, threadId: "t1", requestId: "r7", behavior: "answer", message: "savings", callId: t.controller.current()!.callId });
      expect(t.deps.send).not.toHaveBeenCalled();
    });

    it("leaves the voice's own question, heard back, out of the answer", async () => {
      const t = await live();
      t.message({ id: "q1", kind: "options", card: { title: "Your bot has a question", subtitle: "Which account?", options: ["Main", "Savings"], requestId: "r7" } });
      await vi.advanceTimersByTimeAsync(0);
      t.socket().receive({ type: "session.output_transcript.delta", delta: "Which account? Main or Savings?", start_ms: 4_000, end_ms: 6_000 });
      hear(t, "which account main or savings ", 4_100, 5_900);
      hear(t, "savings", 7_000);
      await delegate(t, "del_2", 7_100);
      expect(t.deps.respond).toHaveBeenCalledWith({ auth: owner, threadId: "t1", requestId: "r7", behavior: "answer", message: "savings", callId: t.controller.current()!.callId });
    });

    it("keeps an answer said over the voice", async () => {
      const t = await live();
      t.message({ id: "q1", kind: "options", card: { title: "Your bot has a question", subtitle: "Which account?", options: ["Main", "Savings"], requestId: "r7" } });
      await vi.advanceTimersByTimeAsync(0);
      t.socket().receive({ type: "session.output_transcript.delta", delta: "Which account? Main or Savings?", start_ms: 4_000, end_ms: 6_000 });
      hear(t, "savings", 5_000, 5_500);
      await delegate(t, "del_2", 5_600);
      expect(t.deps.respond).toHaveBeenCalledWith({ auth: owner, threadId: "t1", requestId: "r7", behavior: "answer", message: "savings", callId: t.controller.current()!.callId });
    });

    it("announces a second approval after the first one settles", async () => {
      const t = await live();
      t.message(approval());
      t.message({ ...approval({ requestId: "r2", subtitle: "ls" }), id: "c2" });
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("instructions")).toHaveLength(1);
      hear(t, "yes", 5_000);
      await delegate(t, "del_2", 5_100);
      t.patch({ ...approval({ answered: "allow" }) });
      await vi.advanceTimersByTimeAsync(0);
      expect(t.socket().appends("instructions").at(-1)).toMatchObject({ content: expect.stringContaining("ls") });
    });
  });
});

describe("LiveCallController record", () => {
  const recorded = (t: ReturnType<typeof setup>) => vi.mocked(t.deps.recordCall!).mock.calls.map(([input]) => input);

  it("records a call that went live once, with OpenAI's usage seconds and nothing said on it", async () => {
    const t = setup({ recordCall: vi.fn() });
    const { call } = await t.start();
    t.socket().receive({ type: "session.input_transcript.delta", delta: "what is on my calendar", start_ms: 100, end_ms: 900 });
    const ending = t.controller.end(call.callId);
    t.socket().receive({ type: "session.closed", reason: "close_requested", usage: { seconds: 61.4 } });
    await ending;
    await t.controller.shutdown();
    expect(recorded(t)).toEqual([{
      threadId: "t1",
      botName: "Ada",
      record: { callId: call.callId, botId: "bot1", client: "desktop", startedAt: call.startedAt, endedAt: expect.any(Number), seconds: 61, endReason: "hung-up" },
    }]);
    expect(recorded(t)[0]!.record.endedAt).toBeGreaterThanOrEqual(call.startedAt);
    expect(JSON.stringify(recorded(t))).not.toContain("calendar");
  });

  it("keeps what the bot said aloud, one line per stretch of speech, and still nothing the person said", async () => {
    const t = setup({ recordCall: vi.fn() });
    await t.start();
    t.socket().receive({ type: "session.input_transcript.delta", delta: "what is on my calendar", start_ms: 100, end_ms: 900 });
    t.socket().receive({ type: "session.output_transcript.delta", delta: "You have two ", start_ms: 1_000, end_ms: 1_500 });
    t.socket().receive({ type: "session.output_transcript.delta", delta: "meetings.", start_ms: 1_500, end_ms: 2_000 });
    t.socket().receive({ type: "session.input_transcript.delta", delta: "thanks bye", start_ms: 4_000, end_ms: 4_600 });
    t.socket().receive({ type: "session.output_transcript.delta", delta: "Bye!", start_ms: 5_000, end_ms: 5_400 });
    t.socket().drop();
    const record = recorded(t)[0]!.record;
    expect(record.spoken).toEqual([{ at: expect.any(Number), text: "You have two meetings." }, { at: expect.any(Number), text: "Bye!" }]);
    expect(JSON.stringify(record)).not.toContain("calendar");
    expect(JSON.stringify(record)).not.toContain("thanks");
  });

  it("masks a held code the bot read aloud when it is said, so it stays masked after the code is forgotten", async () => {
    const code = "Q7XK-24LM";
    const forget = addHeldSecretScrubber((text) => text.replaceAll(code, HELD_SECRET_MASK));
    const t = setup({ recordCall: vi.fn() });
    try {
      await t.start();
      t.socket().receive({ type: "session.output_transcript.delta", delta: "Your code is Q7XK", start_ms: 1_000, end_ms: 1_500 });
      t.socket().receive({ type: "session.output_transcript.delta", delta: "-24LM.", start_ms: 1_500, end_ms: 2_000 });
    } finally {
      forget();
    }
    t.socket().drop();
    const record = recorded(t)[0]!.record;
    expect(record.spoken).toEqual([{ at: expect.any(Number), text: `Your code is ${HELD_SECRET_MASK}.` }]);
    expect(JSON.stringify(record)).not.toContain("24LM");
  });

  it("masks a held code said across a pause, which splits it over two lines", async () => {
    const code = "Q7XK-24LM";
    const forget = addHeldSecretScrubber((text) => text.replaceAll(code, HELD_SECRET_MASK));
    const t = setup({ recordCall: vi.fn() });
    try {
      await t.start();
      t.socket().receive({ type: "session.output_transcript.delta", delta: "Your code is Q7XK", start_ms: 1_000, end_ms: 1_500 });
      t.socket().receive({ type: "session.output_transcript.delta", delta: "-24", start_ms: 3_000, end_ms: 3_200 });
      t.socket().receive({ type: "session.output_transcript.delta", delta: "LM.", start_ms: 3_200, end_ms: 3_500 });
    } finally {
      forget();
    }
    t.socket().drop();
    const record = recorded(t)[0]!.record;
    expect(record.spoken).toEqual([{ at: expect.any(Number), text: `Your code is ${HELD_SECRET_MASK}.` }]);
    expect(JSON.stringify(record)).not.toContain("Q7XK");
  });

  it("masks a held code said across two pauses, which splits it over three lines", async () => {
    const code = "731942";
    const forget = addHeldSecretScrubber((text) => text.replaceAll(code, HELD_SECRET_MASK));
    const t = setup({ recordCall: vi.fn() });
    try {
      await t.start();
      t.socket().receive({ type: "session.output_transcript.delta", delta: "Your code is 73", start_ms: 1_000, end_ms: 1_500 });
      t.socket().receive({ type: "session.output_transcript.delta", delta: "19", start_ms: 3_000, end_ms: 3_200 });
      t.socket().receive({ type: "session.output_transcript.delta", delta: "42.", start_ms: 5_000, end_ms: 5_300 });
    } finally {
      forget();
    }
    t.socket().drop();
    const record = recorded(t)[0]!.record;
    expect(record.spoken).toEqual([{ at: expect.any(Number), text: `Your code is ${HELD_SECRET_MASK}.` }]);
    expect(record.spoken?.map((line) => line.text).join(" ")).not.toMatch(/73|19|42/);
  });

  it("masks a held code split at a pause when the line after it is long", async () => {
    const code = "731942";
    const forget = addHeldSecretScrubber((text) => text.replaceAll(code, HELD_SECRET_MASK));
    const t = setup({ recordCall: vi.fn() });
    try {
      await t.start();
      t.socket().receive({ type: "session.output_transcript.delta", delta: "Your code is 73", start_ms: 1_000, end_ms: 1_500 });
      t.socket().receive({ type: "session.output_transcript.delta", delta: `1942${".".repeat(508)}`, start_ms: 3_000, end_ms: 3_500 });
    } finally {
      forget();
    }
    t.socket().drop();
    const record = recorded(t)[0]!.record;
    expect(record.spoken).toEqual([{ at: expect.any(Number), text: `Your code is ${HELD_SECRET_MASK}${".".repeat(508)}` }]);
  });

  it("stores the call row with a held code masked after the code stops being held", async () => {
    rmSync(DATA_DIR, { recursive: true, force: true });
    const selection = () => ({ instanceId: "claude", model: "claude-sonnet-5" });
    const store = new Store(selection);
    const bot = store.createBot({}, { seedMessages: false });
    const t = setup({ recordCall: (input) => recordLiveCall({ chatExists: () => true, appendMessage: (_threadId, message) => store.appendMessage(bot.threadId, message) }, input) });
    const forget = addHeldSecretScrubber((text) => text.replaceAll("731942", HELD_SECRET_MASK));
    try {
      await t.start();
      t.socket().receive({ type: "session.output_transcript.delta", delta: "Your code is 7319", start_ms: 1_000, end_ms: 1_500 });
      t.socket().receive({ type: "session.output_transcript.delta", delta: "42.", start_ms: 3_000, end_ms: 3_300 });
    } finally {
      forget();
    }
    t.socket().drop();
    flushLaterSaves();
    const row = new Store(selection).messagesFor(bot.threadId).find((message) => message.kind === "call");
    expect(row?.call?.spoken).toEqual([{ at: expect.any(Number), text: `Your code is ${HELD_SECRET_MASK}.` }]);
    expect(JSON.stringify(row?.call?.spoken)).not.toContain("7319");
  });

  it("leaves a credential shape whole until the record is redacted, so a key split across deltas is masked in full", async () => {
    const t = setup({ recordCall: vi.fn() });
    await t.start();
    t.socket().receive({ type: "session.output_transcript.delta", delta: "Set service_key=Q7XK", start_ms: 1_000, end_ms: 1_500 });
    t.socket().receive({ type: "session.output_transcript.delta", delta: "-24LM now.", start_ms: 1_500, end_ms: 2_000 });
    t.socket().drop();
    const spoken = recorded(t)[0]!.record.spoken!.map((line) => redactSecretsInText(line.text));
    expect(spoken).toEqual(["Set service_key=«redacted 9 chars» now."]);
  });

  it("counts wall-clock seconds when OpenAI sent none", async () => {
    const t = setup({ recordCall: vi.fn() });
    await t.start();
    await vi.advanceTimersByTimeAsync(95_400);
    t.socket().drop();
    expect(recorded(t)).toEqual([expect.objectContaining({ record: expect.objectContaining({ seconds: 95, endReason: "sideband-lost" }) })]);
  });

  it("records nothing for a call that never went live", async () => {
    const t = setup({ recordCall: vi.fn() });
    await t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" });
    t.socket().refuse();
    expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost" });
    expect(t.deps.recordCall).not.toHaveBeenCalled();
  });

  it("records a call the harness shut down", async () => {
    const t = setup({ recordCall: vi.fn() });
    await t.start();
    await t.controller.shutdown();
    expect(recorded(t)).toEqual([expect.objectContaining({ record: expect.objectContaining({ endReason: "shutdown" }) })]);
  });

  it("ends the call cleanly, and counts it, when writing the record fails", async () => {
    const t = setup({ recordCall: vi.fn(() => { throw new Error("disk full"); }) });
    await t.start();
    t.socket().drop();
    expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost" });
    expect(t.controller.current()).toBeNull();
    expect(t.logs.at(-1)).toContain("errors=record");
    await expect(t.start()).resolves.toBeTruthy();
  });
});