Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

51.3 KB
Raw Blame
import { readFileSync } from 'node:fs';
import {
  THREAD_REOPEN_OP_TIMEOUT_MS,
  type ThreadEvent,
  type ThreadInfo,
  type ThreadServerFrame,
} from '@inkeep/open-knowledge-core/acp/thread-protocol';
import { toast } from 'sonner';
import { describe, expect, test, vi } from 'vitest';
import fixture from '../../../../../test-support/fixtures/codex-legacy-warning-envelopes.json' with {
  type: 'json',
};
import { AgentThreadClient, ThreadChannelUnavailableError } from './thread-client';

describe('archived history subscription failures', () => {
  const info: ThreadInfo = {
    threadId: 'history-load',
    agent: { id: 'a', name: 'A', source: 'custom' },
    title: 'History',
    status: 'exited',
    createdAt: 1,
    lastActivityAt: 1,
    lastSeq: 0,
    modes: null,
    configOptions: null,
    archived: true,
  };

  function openHistory() {
    const client = new AgentThreadClient();
    const sent: Array<Record<string, unknown>> = [];
    const internals = client as unknown as { ws: unknown };
    internals.ws = {
      readyState: 1,
      send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),
    };
    const frame = (value: ThreadServerFrame) => client.receiveServerFrame(JSON.stringify(value));
    frame({ op: 'threads', threads: [info] });
    client.openArchivedThread(info.threadId);
    return { client, sent, frame };
  }

  test('a failed subscription closes the loading tab and can be retried from history', () => {
    const error = vi.spyOn(toast, 'error').mockImplementation(() => 'toast');
    const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
    try {
      const { client, sent, frame } = openHistory();
      frame({ op: 'error', code: 'internal', message: 'internal error', threadId: info.threadId });

      expect(client.getOpenTabs()).toEqual([]);
      expect(client.getThread(info.threadId)?.events).toEqual([]);
      expect(error).toHaveBeenCalledWith(
        'Chat history could not be loaded. Try opening the chat again from Chat history.',
      );
      expect(warning).toHaveBeenCalledWith(
        '[agent-threads] server error frame:',
        'internal',
        'internal error',
      );
      client.openArchivedThread(info.threadId);
      expect(client.getOpenTabs()).toEqual([info]);
      expect(sent.filter((value) => value.op === 'subscribe')).toHaveLength(2);
      expect(sent).toContainEqual({ op: 'unsubscribe', threadId: info.threadId });
    } finally {
      error.mockRestore();
      warning.mockRestore();
    }
  });

  test.each(['before opening', 'after opening'])(
    'delayed terminal frames %s do not replace the archived transcript',
    (timing) => {
      const { client, sent, frame } = openHistory();
      const message: ThreadEvent = { kind: 'user_message', content: 'original message', ts: 1 };
      const exited: ThreadEvent = { kind: 'status', status: 'exited', ts: 2 };
      const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
      try {
        frame({ op: 'info', info: { ...info, archived: false, status: 'ready' } });
        frame({ op: 'events', threadId: info.threadId, fromSeq: 0, events: [message] });
        frame({ op: 'info', info: { ...info, lastSeq: 1 } });
        if (timing === 'before opening') {
          frame({ op: 'event', threadId: info.threadId, seq: 1, event: exited });
        }

        client.openArchivedThread(info.threadId);
        if (timing === 'after opening') {
          frame({ op: 'event', threadId: info.threadId, seq: 1, event: exited });
        }

        expect(sent.at(-1)).toEqual({ op: 'subscribe', threadId: info.threadId, sinceSeq: 0 });
        expect(client.getThread(info.threadId)?.events).toEqual([]);
        frame({
          op: 'subscribed',
          threadId: info.threadId,
          fromSeq: 0,
          info: { ...info, lastSeq: 1 },
        });
        frame({ op: 'events', threadId: info.threadId, fromSeq: 0, events: [message, exited] });
        expect(client.getThread(info.threadId)?.events).toEqual([message, exited]);
      } finally {
        warning.mockRestore();
      }
    },
  );

  test('a non-subscription error preserves a completely replayed transcript', () => {
    const error = vi.spyOn(toast, 'error').mockImplementation(() => 'toast');
    const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
    try {
      const { client, frame } = openHistory();
      frame({ op: 'subscribed', threadId: info.threadId, fromSeq: 0, info });
      const event: ThreadEvent = { kind: 'user_message', content: 'kept', ts: 1 };
      frame({ op: 'events', threadId: info.threadId, fromSeq: 0, events: [event] });
      frame({ op: 'error', code: 'internal', message: 'rename failed', threadId: info.threadId });

      expect(client.getOpenTabs()).toEqual([info]);
      expect(client.getThread(info.threadId)?.events).toEqual([event]);
      expect(error).not.toHaveBeenCalled();
    } finally {
      error.mockRestore();
      warning.mockRestore();
    }
  });
});

describe('AgentThreadClient store snapshots', () => {
  test('getThreads returns a referentially stable snapshot until the store changes', () => {
    const client = new AgentThreadClient();
    const first = client.getThreads();
    expect(client.getThreads()).toBe(first);
    expect(client.getThreads()).toBe(first);
  });

  test('getConnectionStatus is idle before any URL is set', () => {
    expect(new AgentThreadClient().getConnectionStatus()).toBe('idle');
  });

  test('the thread scope publishes project retargets without treating reconnects as a new scope', () => {
    class FakeSocket {
      static OPEN = 1;
      readyState = 0;
      close(): void {}
    }
    vi.stubGlobal('WebSocket', FakeSocket);
    try {
      const client = new AgentThreadClient();
      const listener = vi.fn();
      client.subscribe(listener);

      client.setUrl('ws://project-a/collab/thread');
      expect(client.getThreadScope()).toBe('ws://project-a/collab/thread');
      const retargetNotifications = listener.mock.calls.length;

      client.setUrl('ws://project-a/collab/thread');
      expect(listener).toHaveBeenCalledTimes(retargetNotifications);

      client.setUrl('ws://project-b/collab/thread');
      expect(client.getThreadScope()).toBe('ws://project-b/collab/thread');
      expect(listener.mock.calls.length).toBeGreaterThan(retargetNotifications);
    } finally {
      vi.unstubAllGlobals();
    }
  });

  test('retargeting clears the previous project roster before the next socket opens', () => {
    class FakeSocket {
      static OPEN = 1;
      static instances: FakeSocket[] = [];
      readyState = 0;
      sent: string[] = [];
      constructor() {
        FakeSocket.instances.push(this);
      }
      close(): void {}
      send(frame: string): void {
        this.sent.push(frame);
      }
    }
    vi.stubGlobal('WebSocket', FakeSocket);
    try {
      const client = new AgentThreadClient();
      const archived: ThreadInfo = {
        threadId: 'project-a-archive',
        agent: { id: 'a', name: 'A', source: 'custom' },
        title: 'Project A',
        status: 'exited',
        createdAt: 1,
        lastActivityAt: 1,
        modes: null,
        configOptions: null,
        lastSeq: -1,
        archived: true,
      };
      client.setUrl('ws://project-a/collab/thread');
      client.receiveServerFrame(JSON.stringify({ op: 'threads', threads: [archived] }));
      expect(client.getThreads()).toEqual([archived]);

      client.setUrl('ws://project-b/collab/thread');
      expect(client.getThreads()).toEqual([]);
      expect(client.getOpenTabs()).toEqual([]);
      const projectBSocket = FakeSocket.instances.at(-1);
      if (projectBSocket === undefined) throw new Error('project B socket was not created');
      projectBSocket.readyState = FakeSocket.OPEN;
      client.openArchivedThread(archived.threadId);
      expect(projectBSocket.sent).toEqual([]);
      expect(client.getOpenTabs()).toEqual([]);
    } finally {
      vi.unstubAllGlobals();
    }
  });

  test('retargeting away and back preserves unread activity', () => {
    class FakeSocket {
      static OPEN = 1;
      readyState = 0;
      close(): void {}
    }
    vi.stubGlobal('WebSocket', FakeSocket);
    try {
      const client = new AgentThreadClient();
      const original: ThreadInfo = {
        threadId: 'project-a-thread',
        agent: { id: 'a', name: 'A', source: 'custom' },
        title: 'Project A',
        status: 'ready',
        createdAt: 1,
        lastActivityAt: 1,
        modes: null,
        configOptions: null,
        lastSeq: -1,
      };
      client.setUrl('ws://project-a/collab/thread');
      client.receiveServerFrame(JSON.stringify({ op: 'threads', threads: [original] }));
      expect(client.getThreadUnread(original.threadId)).toBe(false);

      client.setUrl('ws://project-b/collab/thread');
      client.setUrl('ws://project-a/collab/thread');
      client.receiveServerFrame(
        JSON.stringify({ op: 'threads', threads: [{ ...original, lastActivityAt: 2 }] }),
      );

      expect(client.getThreadUnread(original.threadId)).toBe(true);
    } finally {
      vi.unstubAllGlobals();
    }
  });
});

describe('initial roster attribution (agents-panel reload absorb)', () => {
  const info = (threadId: string): ThreadInfo => ({
    threadId,
    agent: { id: 'a', name: 'A', source: 'custom' },
    title: threadId,
    status: 'ready',
    createdAt: 1,
    lastActivityAt: 1,
    modes: null,
    configOptions: null,
    lastSeq: -1,
  });

  function makeClient(): { client: AgentThreadClient; frame: (f: ThreadServerFrame) => void } {
    const client = new AgentThreadClient();
    const internals = client as unknown as { handleFrame: (f: ThreadServerFrame) => void };
    return { client, frame: (f) => internals.handleFrame.call(client, f) };
  }

  class FakeSocket {
    static OPEN = 1;
    readyState = 0;
    onopen: (() => void) | null = null;
    onmessage: ((event: { data: unknown }) => void) | null = null;
    onclose: (() => void) | null = null;
    onerror: (() => void) | null = null;
    send(_raw: string): void {}
    close(): void {}
    open(): void {
      this.readyState = FakeSocket.OPEN;
      this.onopen?.();
    }
  }

  test('a fresh client has recorded no roster', () => {
    expect(makeClient().client.getInitialRosterThreadIds()).toBeNull();
  });

  test('the first threads frame records its thread ids once', () => {
    const { client, frame } = makeClient();
    frame({ op: 'threads', threads: [info('t1'), info('t2')] });

    const roster = client.getInitialRosterThreadIds();
    expect(roster).not.toBeNull();
    expect([...(roster as ReadonlySet<string>)].sort()).toEqual(['t1', 't2']);
  });

  test('a later threads frame does not re-record the roster', () => {
    const { client, frame } = makeClient();
    frame({ op: 'threads', threads: [info('t1')] });
    const roster = client.getInitialRosterThreadIds();

    frame({ op: 'threads', threads: [info('t1'), info('t9')] });

    expect(client.getInitialRosterThreadIds()).toBe(roster);
    expect(client.getInitialRosterThreadIds()?.has('t9')).toBe(false);
  });

  test('a second threads frame after an empty first roster does not re-record', () => {
    const { client, frame } = makeClient();
    frame({ op: 'threads', threads: [] });
    const roster = client.getInitialRosterThreadIds();

    frame({ op: 'threads', threads: [info('t1')] });

    expect(client.getInitialRosterThreadIds()).toBe(roster);
    expect(client.getInitialRosterThreadIds()?.size).toBe(0);
  });

  test('created and resumed pushes never record a roster', () => {
    const { client, frame } = makeClient();
    frame({ op: 'created', reqId: 'r1', info: info('t1') });
    expect(client.getInitialRosterThreadIds()).toBeNull();

    frame({ op: 'resumed', reqId: 'r2', info: info('t1') });
    expect(client.getInitialRosterThreadIds()).toBeNull();
  });

  test('an empty first roster records an empty set, not null', () => {
    const { client, frame } = makeClient();
    frame({ op: 'threads', threads: [] });

    const roster = client.getInitialRosterThreadIds();
    expect(roster).not.toBeNull();
    expect(roster?.size).toBe(0);
  });

  test('retargeting setUrl resets the roster so the next session records its own', () => {
    vi.stubGlobal('WebSocket', FakeSocket);
    try {
      const client = new AgentThreadClient();
      const internals = client as unknown as { handleFrame: (f: ThreadServerFrame) => void };
      const frame = (f: ThreadServerFrame) => internals.handleFrame.call(client, f);

      client.setUrl('ws://session-a');
      frame({ op: 'threads', threads: [info('a1'), info('a2')] });
      expect(client.getInitialRosterThreadIds()).not.toBeNull();

      client.setUrl('ws://session-b');
      frame({ op: 'threads', threads: [info('b1')] });

      const roster = client.getInitialRosterThreadIds();
      expect([...(roster ?? [])]).toEqual(['b1']);
      expect(['b1'].every((id) => roster?.has(id) === true)).toBe(true);
    } finally {
      vi.unstubAllGlobals();
    }
  });

  test('a same-session reconnect keeps the roster — the drop is not a retarget', async () => {
    vi.useFakeTimers();
    vi.stubGlobal('WebSocket', FakeSocket);
    try {
      const client = new AgentThreadClient();
      const internals = client as unknown as {
        handleFrame: (f: ThreadServerFrame) => void;
        ws: FakeSocket | null;
      };
      const frame = (f: ThreadServerFrame) => internals.handleFrame.call(client, f);

      client.setUrl('ws://session-a');
      internals.ws?.open();
      frame({ op: 'threads', threads: [info('t1'), info('t2')] });
      const roster = client.getInitialRosterThreadIds();
      expect(roster).not.toBeNull();

      internals.ws?.onclose?.();
      await vi.runAllTimersAsync();
      internals.ws?.open();
      frame({ op: 'threads', threads: [info('t1'), info('t2')] });

      expect(client.getInitialRosterThreadIds()).toBe(roster);
    } finally {
      vi.useRealTimers();
      vi.unstubAllGlobals();
    }
  });

  test('the first roster capture notifies subscribers even when the roster is empty', () => {
    const { client, frame } = makeClient();
    let notifications = 0;
    client.subscribe(() => {
      notifications += 1;
    });

    frame({ op: 'threads', threads: [] });

    expect(notifications).toBe(1);
    expect(client.getInitialRosterThreadIds()?.size).toBe(0);
  });

  test('the roster records the live population only, excluding archived ids', () => {
    const { client, frame } = makeClient();
    frame({ op: 'threads', threads: [info('t1'), { ...info('t2'), archived: true }] });

    const roster = client.getInitialRosterThreadIds();
    expect([...(roster ?? [])]).toEqual(['t1']);
  });
});

describe('batched event delivery', () => {
  const info: ThreadInfo = {
    threadId: 't1',
    agent: { id: 'a', name: 'A', source: 'custom' },
    title: 'A',
    status: 'ready',
    createdAt: 1,
    lastActivityAt: 1,
    modes: null,
    configOptions: null,
    lastSeq: -1,
  };
  const ev = (i: number): ThreadEvent => ({ kind: 'user_message', content: `m${i}`, ts: i });

  function makeClient(): { client: AgentThreadClient; frame: (f: ThreadServerFrame) => void } {
    const client = new AgentThreadClient();
    const internals = client as unknown as { handleFrame: (f: ThreadServerFrame) => void };
    internals.handleFrame.call(client, { op: 'subscribed', threadId: 't1', fromSeq: 0, info });
    return { client, frame: (f) => internals.handleFrame.call(client, f) };
  }

  test('an events frame appends the batch with a single store notification', () => {
    const { client, frame } = makeClient();
    let notifications = 0;
    client.subscribe(() => {
      notifications += 1;
    });
    frame({ op: 'events', threadId: 't1', fromSeq: 0, events: [ev(0), ev(1), ev(2)] });
    expect(notifications).toBe(1);
    expect(client.getThread('t1')?.events).toHaveLength(3);
    expect(client.getThread('t1')?.lastSeq).toBe(2);
  });

  test('replay overlap dedups by seq: only genuinely new events append', () => {
    const { client, frame } = makeClient();
    frame({ op: 'events', threadId: 't1', fromSeq: 0, events: [ev(0), ev(1), ev(2)] });
    frame({ op: 'events', threadId: 't1', fromSeq: 1, events: [ev(1), ev(2), ev(3)] });
    expect(client.getThread('t1')?.events).toHaveLength(4);
    expect(client.getThread('t1')?.lastSeq).toBe(3);
    let notifications = 0;
    client.subscribe(() => {
      notifications += 1;
    });
    frame({ op: 'events', threadId: 't1', fromSeq: 0, events: [ev(0)] });
    expect(notifications).toBe(0);
    expect(client.getThread('t1')?.events).toHaveLength(4);
  });

  test('single event frames still work (terminal close notice path)', () => {
    const { client, frame } = makeClient();
    frame({ op: 'event', threadId: 't1', seq: 0, event: ev(0) });
    expect(client.getThread('t1')?.events).toHaveLength(1);
    expect(client.getThread('t1')?.lastSeq).toBe(0);
  });

  test('title changes preserve the thread activity timestamp', () => {
    const { client, frame } = makeClient();
    frame({
      op: 'event',
      threadId: 't1',
      seq: 0,
      event: { kind: 'title_changed', title: 'Renamed', ts: 99 },
    });
    expect(client.getThread('t1')?.info).toMatchObject({
      title: 'Renamed',
      lastActivityAt: 1,
    });
  });
});

describe('queue edit settlement', () => {
  const info: ThreadInfo = {
    threadId: 't1',
    agent: { id: 'a', name: 'A', source: 'custom' },
    title: 'A',
    status: 'running',
    createdAt: 1,
    lastActivityAt: 1,
    lastSeq: -1,
  };

  function makeWiredClient(): {
    client: AgentThreadClient;
    sent: Array<Record<string, unknown>>;
    frame: (f: ThreadServerFrame) => void;
  } {
    const client = new AgentThreadClient();
    const sent: Array<Record<string, unknown>> = [];
    const internals = client as unknown as {
      ws: unknown;
      handleFrame: (f: ThreadServerFrame) => void;
    };
    internals.ws = {
      readyState: 1,
      send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),
    };
    const frame = (f: ThreadServerFrame) => internals.handleFrame.call(client, f);
    frame({ op: 'subscribed', threadId: 't1', fromSeq: 0, info });
    return { client, sent, frame };
  }

  test('the ack carrying the reqId settles the edit as applied', async () => {
    const { client, sent, frame } = makeWiredClient();
    const pending = client.editQueued('t1', 'q1', '  sharper text  ');
    const edit = sent.find((f) => f.op === 'queue_edit');
    expect(edit).toMatchObject({ threadId: 't1', id: 'q1', content: 'sharper text' });
    expect(typeof edit?.reqId).toBe('string');

    frame({ op: 'queue_edited', reqId: edit?.reqId as string, threadId: 't1' });
    await expect(pending).resolves.toBeUndefined();
  });

  test('a refusal rejects even when an unrelated info frame for the thread arrived first', async () => {
    const { client, sent, frame } = makeWiredClient();
    const pending = client.editQueued('t1', 'q1', 'too late');
    const reqId = sent.find((f) => f.op === 'queue_edit')?.reqId;
    expect(typeof reqId).toBe('string');

    frame({ op: 'info', info: { ...info, lastActivityAt: 2 } });
    frame({
      op: 'error',
      code: 'not-ready',
      message: 'queued message already dispatched',
      reqId: reqId as string,
      threadId: 't1',
    });
    await expect(pending).rejects.toThrow(/already dispatched/);
  });

  test('info frames — this thread or another — never settle the edit; the ack does', async () => {
    const { client, sent, frame } = makeWiredClient();
    let settled = false;
    const pending = client.editQueued('t1', 'q1', 'sharper text');
    void pending.then(() => {
      settled = true;
    });
    frame({ op: 'info', info: { ...info, threadId: 'other' } });
    frame({ op: 'info', info });
    frame({ op: 'queue_edited', reqId: 'queue-edit-not-mine', threadId: 't1' });
    await Promise.resolve();
    expect(settled).toBe(false);

    frame({
      op: 'queue_edited',
      reqId: sent.find((f) => f.op === 'queue_edit')?.reqId as string,
      threadId: 't1',
    });
    await expect(pending).resolves.toBeUndefined();
  });

  test('an empty edit never reaches the wire', async () => {
    const { client, sent } = makeWiredClient();
    await expect(client.editQueued('t1', 'q1', '   ')).resolves.toBeUndefined();
    expect(sent.some((f) => f.op === 'queue_edit')).toBe(false);
  });

  test('holdQueued sends the park/release frame verbatim', () => {
    const { client, sent } = makeWiredClient();
    client.holdQueued('t1', 'q1', true);
    client.holdQueued('t1', 'q1', false);
    expect(sent.filter((f) => f.op === 'queue_hold')).toEqual([
      { op: 'queue_hold', threadId: 't1', id: 'q1', held: true },
      { op: 'queue_hold', threadId: 't1', id: 'q1', held: false },
    ]);
  });

  test('sendQueuedNow sends the jump-the-line frame verbatim', () => {
    const { client, sent } = makeWiredClient();
    client.sendQueuedNow('t1', 'q1');
    expect(sent.filter((f) => f.op === 'queue_send_now')).toEqual([
      { op: 'queue_send_now', threadId: 't1', id: 'q1' },
    ]);
  });

  test('setChatGrant sends the grant and its direction', () => {
    const { client, sent } = makeWiredClient();
    client.setChatGrant('t1', 'read_only_shell', true);
    client.setChatGrant('t1', 'read_only_shell', false);
    expect(sent.filter((f) => f.op === 'set_chat_grant')).toEqual([
      { op: 'set_chat_grant', threadId: 't1', grant: 'read_only_shell', enabled: true },
      { op: 'set_chat_grant', threadId: 't1', grant: 'read_only_shell', enabled: false },
    ]);
  });
});

describe('retry and sign-in lifecycle', () => {
  const info: ThreadInfo = {
    threadId: 't1',
    agent: { id: 'a', name: 'A', source: 'custom' },
    title: 'A',
    status: 'error',
    createdAt: 1,
    lastActivityAt: 1,
    lastSeq: -1,
  };

  function makeWiredClient(): {
    client: AgentThreadClient;
    sent: Array<Record<string, unknown>>;
    frame: (f: ThreadServerFrame) => void;
  } {
    const client = new AgentThreadClient();
    const sent: Array<Record<string, unknown>> = [];
    const internals = client as unknown as {
      ws: unknown;
      handleFrame: (f: ThreadServerFrame) => void;
    };
    internals.ws = {
      readyState: 1,
      send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),
    };
    const frame = (f: ThreadServerFrame) => internals.handleFrame.call(client, f);
    frame({ op: 'subscribed', threadId: 't1', fromSeq: 0, info });
    return { client, sent, frame };
  }

  const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));

  test('retryThread sends the op and resolves with the retried thread info', async () => {
    const { client, sent, frame } = makeWiredClient();
    const pending = client.retryThread('t1');
    await flush();
    const retry = sent.find((f) => f.op === 'retry');
    expect(retry).toMatchObject({ op: 'retry', threadId: 't1' });
    expect(typeof retry?.reqId).toBe('string');

    const ready: ThreadInfo = { ...info, status: 'ready' };
    frame({ op: 'retried', reqId: retry?.reqId as string, info: ready });
    await expect(pending).resolves.toMatchObject({ status: 'ready' });
  });

  test('a retry the server refuses rejects with its message', async () => {
    const { client, sent, frame } = makeWiredClient();
    const pending = client.retryThread('t1');
    await flush();
    const reqId = sent.find((f) => f.op === 'retry')?.reqId as string;

    frame({
      op: 'error',
      code: 'spawn-failed',
      message: 'harness not installed',
      reqId,
      threadId: 't1',
    });
    await expect(pending).rejects.toThrow(/harness not installed/);
    await expect(pending).rejects.toMatchObject({ code: 'spawn-failed' });
  });

  test('a refused context window change carries the server code to the caller', async () => {
    const { client, sent, frame } = makeWiredClient();
    const pending = client.setContextWindow('t1', 872_000);
    await flush();
    const reqId = sent.find((f) => f.op === 'set_context_window')?.reqId as string;
    expect(reqId).toBeTruthy();

    frame({
      op: 'error',
      code: 'spawn-failed',
      message: 'the agent failed to start',
      reqId,
      threadId: 't1',
    });
    await expect(pending).rejects.toMatchObject({ code: 'spawn-failed' });
  });

  test('an accepted context window change settles with the thread info', async () => {
    const { client, sent, frame } = makeWiredClient();
    const pending = client.setContextWindow('t1', 872_000);
    await flush();
    const reqId = sent.find((f) => f.op === 'set_context_window')?.reqId as string;

    frame({ op: 'context_window_set', reqId, info: { ...info, contextWindow: 872_000 } });
    await expect(pending).resolves.toMatchObject({ contextWindow: 872_000 });
  });

  test('authenticateThread sends the method id and resolves with the signed-in info', async () => {
    const { client, sent, frame } = makeWiredClient();
    const pending = client.authenticateThread('t1', 'test_login');
    await flush();
    const auth = sent.find((f) => f.op === 'authenticate');
    expect(auth).toMatchObject({ op: 'authenticate', threadId: 't1', methodId: 'test_login' });
    expect(String(auth?.reqId)).toMatch(/^authenticate-/);

    const ready: ThreadInfo = { ...info, status: 'ready' };
    frame({ op: 'authenticated', reqId: auth?.reqId as string, info: ready });
    await expect(pending).resolves.toMatchObject({ status: 'ready' });
  });

  test('a refused sign-in rejects with what the agent said', async () => {
    const { client, sent, frame } = makeWiredClient();
    const pending = client.authenticateThread('t1', 'test_login');
    await flush();
    const reqId = sent.find((f) => f.op === 'authenticate')?.reqId as string;

    frame({ op: 'error', code: 'not-ready', message: 'wrong account', reqId, threadId: 't1' });
    await expect(pending).rejects.toThrow(/wrong account/);
  });

  test('a sign-in cut short by the agent stopping rejects with that code', async () => {
    const { client, sent, frame } = makeWiredClient();
    const pending = client.authenticateThread('t1', 'test_login');
    await flush();
    const reqId = sent.find((f) => f.op === 'authenticate')?.reqId as string;

    frame({
      op: 'error',
      code: 'agent-exited',
      message: 'connection closed',
      reqId,
      threadId: 't1',
    });
    await expect(pending).rejects.toMatchObject({ code: 'agent-exited' });
  });

  test('terminalAuthLaunch sends the method id and resolves with the launch the server composed', async () => {
    const { client, sent, frame } = makeWiredClient();
    const pending = client.terminalAuthLaunch('t1', 'cli-login');
    await flush();
    const request = sent.find((f) => f.op === 'terminal_auth_launch');
    expect(request).toMatchObject({
      op: 'terminal_auth_launch',
      threadId: 't1',
      methodId: 'cli-login',
    });
    expect(String(request?.reqId)).toMatch(/^terminal-auth-/);

    const launch = {
      executable: 'auggie',
      args: ['--acp', 'login'],
      env: { AUGGIE_LOGIN_FLOW: 'terminal' },
      pathPrepend: [],
    };
    frame({ op: 'terminal_auth_launch_ready', reqId: request?.reqId as string, launch });
    await expect(pending).resolves.toEqual(launch);
  });

  test('a terminal launch the server refuses rejects with its reason', async () => {
    const { client, sent, frame } = makeWiredClient();
    const pending = client.terminalAuthLaunch('t1', 'missing');
    await flush();
    const reqId = sent.find((f) => f.op === 'terminal_auth_launch')?.reqId as string;

    frame({
      op: 'error',
      code: 'not-ready',
      message: 'this agent offers no terminal sign-in by that name',
      reqId,
      threadId: 't1',
    });
    await expect(pending).rejects.toThrow(/no terminal sign-in by that name/);
  });
});

describe('createThread channel wait', () => {
  test('a malformed created frame rejects the pending launch instead of stranding it', async () => {
    const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
    try {
      const client = new AgentThreadClient();
      const sent: Array<Record<string, unknown>> = [];
      const internals = client as unknown as { ws: unknown };
      internals.ws = {
        readyState: WebSocket.OPEN,
        send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),
      };
      const pending = client.createThread({ agent: { source: 'custom', id: 'agent' } }, (info) => {
        if (info.threadId === '') throw new Error('empty thread');
      });
      await Promise.resolve();
      const reqId = sent.find((frame) => frame.op === 'create')?.reqId;
      expect(typeof reqId).toBe('string');

      expect(() =>
        client.receiveServerFrame(JSON.stringify({ op: 'created', reqId })),
      ).not.toThrow();
      await expect(pending).rejects.toThrow(/invalid created thread info: info/);
    } finally {
      warn.mockRestore();
    }
  });

  test('a malformed created frame with no pending launch names the failing field and thread', () => {
    const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
    try {
      const client = new AgentThreadClient();

      client.receiveServerFrame(
        JSON.stringify({
          op: 'created',
          reqId: 'create-unknown',
          info: {
            threadId: 'thread-bad',
            agent: { source: 'custom', id: 'agent', name: 'Agent' },
            title: 'Agent',
            status: 'ready',
            createdAt: 'yesterday',
            lastActivityAt: 1,
            lastSeq: -1,
          },
        }),
      );

      expect(client.getThread('thread-bad')).toBeNull();
      expect(warn).toHaveBeenCalledWith(
        '[agent-threads] invalid created thread info',
        expect.objectContaining({ field: 'createdAt', threadId: 'thread-bad' }),
      );
    } finally {
      warn.mockRestore();
    }
  });

  test('a created frame with a status this build does not know still starts the thread', async () => {
    const client = new AgentThreadClient();
    const sent: Array<Record<string, unknown>> = [];
    const internals = client as unknown as { ws: unknown };
    internals.ws = {
      readyState: WebSocket.OPEN,
      send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),
    };
    const created = vi.fn();
    const pending = client.createThread({ agent: { source: 'custom', id: 'agent' } }, created);
    await Promise.resolve();
    const reqId = sent.find((frame) => frame.op === 'create')?.reqId;

    client.receiveServerFrame(
      JSON.stringify({
        op: 'created',
        reqId,
        info: {
          threadId: 'thread-1',
          agent: { source: 'custom', id: 'agent', name: 'Agent' },
          title: 'Agent',
          status: 'sleeping',
          createdAt: 1,
          lastActivityAt: 1,
          lastSeq: -1,
        },
      }),
    );

    await expect(pending).resolves.toMatchObject({ threadId: 'thread-1', status: 'sleeping' });
    expect(created).toHaveBeenCalledWith(expect.objectContaining({ threadId: 'thread-1' }));
  });

  test('a creation callback failure still starts and lists the thread the server created', async () => {
    const error = vi.spyOn(console, 'error').mockImplementation(() => {});
    try {
      const client = new AgentThreadClient();
      const sent: Array<Record<string, unknown>> = [];
      const internals = client as unknown as { ws: unknown };
      internals.ws = {
        readyState: WebSocket.OPEN,
        send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),
      };
      const callbackFailure = new Error('creation callback failed');
      const pending = client.createThread({ agent: { source: 'custom', id: 'agent' } }, () => {
        throw callbackFailure;
      });
      await Promise.resolve();
      const reqId = sent.find((frame) => frame.op === 'create')?.reqId;
      expect(typeof reqId).toBe('string');

      expect(() =>
        client.receiveServerFrame(
          JSON.stringify({
            op: 'created',
            reqId,
            info: {
              threadId: 'thread-1',
              agent: { source: 'custom', id: 'agent', name: 'Agent' },
              title: 'Agent',
              status: 'ready',
              createdAt: 1,
              lastActivityAt: 1,
              lastSeq: -1,
            },
          }),
        ),
      ).not.toThrow();
      await expect(pending).resolves.toMatchObject({ threadId: 'thread-1' });
      expect(client.getThread('thread-1')?.info.threadId).toBe('thread-1');
      expect(error).toHaveBeenCalledWith(
        '[agent-threads] created-thread callback failed for',
        'thread-1',
        callbackFailure,
      );
    } finally {
      error.mockRestore();
    }
  });

  test('rejects with ThreadChannelUnavailableError when no URL is ever bound', async () => {
    const client = new AgentThreadClient();
    const waitFor = (
      client as unknown as { waitForOpen: (ms: number) => Promise<void> }
    ).waitForOpen.bind(client);
    await expect(waitFor(30)).rejects.toBeInstanceOf(ThreadChannelUnavailableError);
  });

  test('waitForOpen resolves when the channel opens during the wait', async () => {
    const client = new AgentThreadClient();
    const internals = client as unknown as {
      waitForOpen: (ms: number) => Promise<void>;
      ws: { readyState: number } | null;
      bump: () => void;
    };
    const pending = internals.waitForOpen.call(client, 1_000);
    internals.ws = { readyState: WebSocket.OPEN };
    internals.bump.call(client);
    await expect(pending).resolves.toBeUndefined();
  });
});

describe('store hooks return the useSyncExternalStore subscription value (React Compiler safety)', () => {
  const source = readFileSync(new URL('./thread-client.ts', import.meta.url), 'utf8');

  function hookBody(name: string): string {
    const start = source.indexOf(`export function ${name}(`);
    expect(start).toBeGreaterThanOrEqual(0);
    const open = source.indexOf('{', start);
    let depth = 0;
    for (let i = open; i < source.length; i++) {
      if (source[i] === '{') depth += 1;
      else if (source[i] === '}') {
        depth -= 1;
        if (depth === 0) return source.slice(open, i + 1);
      }
    }
    throw new Error(`unterminated body for ${name}`);
  }

  for (const hook of [
    'useAgentThreads',
    'useAgentThread',
    'useAgentThreadConnection',
    'useAgentThreadScope',
    'useOpenAgentThreadTabs',
  ]) {
    test(`${hook} returns useSyncExternalStore(...) rather than discarding it`, () => {
      const body = hookBody(hook);
      expect(body).toContain('return useSyncExternalStore(');
      expect(body).not.toMatch(/useSyncExternalStore\([^;]*\);\s*return\s+client\.get/);
    });
  }
});

describe('unread affordance (PRD-8021)', () => {
  const info: ThreadInfo = {
    threadId: 't-unread',
    agent: { id: 'a', name: 'A', source: 'custom' },
    title: 'A',
    status: 'ready',
    createdAt: 1,
    lastActivityAt: 100,
    modes: null,
    configOptions: null,
    lastSeq: -1,
  };

  function boot(): {
    client: AgentThreadClient;
    bump: (nextInfo: ThreadInfo) => void;
  } {
    const client = new AgentThreadClient();
    const internals = client as unknown as { handleFrame: (f: ThreadServerFrame) => void };
    internals.handleFrame.call(client, {
      op: 'subscribed',
      threadId: info.threadId,
      fromSeq: 0,
      info,
    });
    return {
      client,
      bump: (nextInfo) =>
        internals.handleFrame.call(client, {
          op: 'info',
          threadId: nextInfo.threadId,
          info: nextInfo,
        }),
    };
  }

  test('a fresh subscription seeds the floor to lastActivityAt — no unread pulse on reload', () => {
    const { client } = boot();
    expect(client.getThreadUnread(info.threadId)).toBe(false);
  });

  test('marks unread only after activity advances past the initial floor', () => {
    const { client, bump } = boot();
    expect(client.getThreadUnread(info.threadId)).toBe(false);
    bump({ ...info, lastActivityAt: 200 });
    expect(client.getThreadUnread(info.threadId)).toBe(true);
    client.markThreadViewed(info.threadId);
    expect(client.getThreadUnread(info.threadId)).toBe(false);
    bump({ ...info, lastActivityAt: 300 });
    expect(client.getThreadUnread(info.threadId)).toBe(true);
  });

  test('a deleted thread receives a fresh read floor if its id reappears', () => {
    const { client, bump } = boot();
    bump({ ...info, lastActivityAt: 200 });
    expect(client.getThreadUnread(info.threadId)).toBe(true);

    client.deleteThread(info.threadId);
    client.receiveServerFrame(
      JSON.stringify({ op: 'threads', threads: [{ ...info, lastActivityAt: 300 }] }),
    );

    expect(client.getThreadUnread(info.threadId)).toBe(false);
  });

  test('closing a thread preserves its read floor when the archived roster re-emits it', () => {
    const { client, bump } = boot();
    bump({ ...info, lastActivityAt: 200 });
    expect(client.getThreadUnread(info.threadId)).toBe(true);

    client.closeThread(info.threadId);
    client.receiveServerFrame(
      JSON.stringify({
        op: 'threads',
        threads: [{ ...info, lastActivityAt: 200, archived: true }],
      }),
    );

    expect(client.getThreadUnread(info.threadId)).toBe(true);
  });

  test('a thread dropped from the roster receives a fresh read floor if its id reappears', () => {
    const { client, bump } = boot();
    bump({ ...info, lastActivityAt: 200 });
    expect(client.getThreadUnread(info.threadId)).toBe(true);

    client.receiveServerFrame(JSON.stringify({ op: 'threads', threads: [] }));
    client.receiveServerFrame(
      JSON.stringify({ op: 'threads', threads: [{ ...info, lastActivityAt: 300 }] }),
    );

    expect(client.getThreadUnread(info.threadId)).toBe(false);
  });

  test('only settled `ready` tabs report unread — a running turn already pulses via its status dot', () => {
    const { client, bump } = boot();
    client.markThreadViewed(info.threadId);
    bump({ ...info, lastActivityAt: 200, status: 'running' });
    expect(client.getThreadUnread(info.threadId)).toBe(false);
    bump({ ...info, lastActivityAt: 200, status: 'ready' });
    expect(client.getThreadUnread(info.threadId)).toBe(true);
  });

  test('unknown thread reports false and never throws', () => {
    const { client } = boot();
    expect(client.getThreadUnread('not-a-thread')).toBe(false);
    client.markThreadViewed('not-a-thread');
    expect(client.getThreadUnread('not-a-thread')).toBe(false);
  });

  test('a redundant markThreadViewed does not bump the store', () => {
    const { client } = boot();
    client.markThreadViewed(info.threadId);
    let notifications = 0;
    client.subscribe(() => {
      notifications += 1;
    });
    client.markThreadViewed(info.threadId);
    expect(notifications).toBe(0);
  });

  test('mark-viewed on ready flip with unchanged activityAt clears unread', () => {
    const { client, bump } = boot();
    bump({ ...info, lastActivityAt: 200 });
    expect(client.getThreadUnread(info.threadId)).toBe(true);
    bump({ ...info, status: 'running', lastActivityAt: 200 });
    client.markThreadViewed(info.threadId);
    expect(client.getThreadUnread(info.threadId)).toBe(false);
    bump({ ...info, status: 'ready', lastActivityAt: 200 });
    client.markThreadViewed(info.threadId);
    expect(client.getThreadUnread(info.threadId)).toBe(false);
  });

  test('markThreadViewed is a no-op while the thread is `running` — no bump storm during streaming', () => {
    const { client, bump } = boot();
    bump({ ...info, status: 'running', lastActivityAt: 200 });
    let notifications = 0;
    client.subscribe(() => {
      notifications += 1;
    });
    for (let i = 1; i <= 5; i++) {
      bump({ ...info, status: 'running', lastActivityAt: 200 + i * 10 });
      client.markThreadViewed(info.threadId);
    }
    expect(notifications).toBe(5);
  });
});

describe('raw frame ingestion', () => {
  const info: ThreadInfo = {
    threadId: 'raw-1',
    agent: { id: 'codex-acp', name: 'Codex', source: 'registry' },
    title: 'Raw',
    status: 'ready',
    createdAt: 1,
    lastActivityAt: 1,
    lastSeq: -1,
  };

  test('a JSON payload lands in the store the same as a parsed frame would', () => {
    const client = new AgentThreadClient();

    client.receiveServerFrame(JSON.stringify({ op: 'info', info }));

    expect(client.getThread('raw-1')?.info.title).toBe('Raw');
  });

  test('an unparseable payload is dropped instead of thrown', () => {
    const client = new AgentThreadClient();
    client.receiveServerFrame(JSON.stringify({ op: 'info', info }));

    expect(() => client.receiveServerFrame('{ not json')).not.toThrow();
    expect(client.getThread('raw-1')?.info.title).toBe('Raw');
  });
});

describe('render-model agent identity', () => {
  const WARNING_TEXT = fixture.candidates[0].update.content.text;

  const infoFor = (agent: {
    id: string;
    name: string;
    source: 'registry' | 'custom';
  }): ThreadInfo =>
    ({
      threadId: 'ident-1',
      agent,
      title: 'Identity',
      status: 'ready',
      createdAt: 1,
      lastActivityAt: 1,
      lastSeq: -1,
    }) satisfies ThreadInfo;

  const warningEvent = (ts: number): ThreadEvent => ({
    kind: 'session_update',
    update: structuredClone(fixture.candidates[0].update) as never,
    ts,
  });

  function subscribed(agent: Parameters<typeof infoFor>[0]): AgentThreadClient {
    const client = new AgentThreadClient();
    client.receiveServerFrame(
      JSON.stringify({ op: 'subscribed', threadId: 'ident-1', fromSeq: 0, info: infoFor(agent) }),
    );
    return client;
  }

  test('a warning on a registry Codex thread reaches the view as runtime status', () => {
    const client = subscribed(fixture.agents.codexRegistry);

    client.receiveServerFrame(
      JSON.stringify({ op: 'event', threadId: 'ident-1', seq: 0, event: warningEvent(1) }),
    );

    expect(client.getThreadModel('ident-1')?.items).toEqual([
      {
        kind: 'agent_notice',
        source: 'codex_legacy',
        severity: 'warning',
        text: WARNING_TEXT,
        seq: 0,
      },
    ]);
  });

  test('the same bytes on another registry agent reach the view as prose', () => {
    const client = subscribed(fixture.agents.claudeRegistry);

    client.receiveServerFrame(
      JSON.stringify({ op: 'event', threadId: 'ident-1', seq: 0, event: warningEvent(1) }),
    );

    const items = client.getThreadModel('ident-1')?.items ?? [];
    expect(items.map((item) => item.kind)).toEqual(['message']);
    expect(items[0]).toMatchObject({ role: 'agent', text: WARNING_TEXT });
  });

  test('a replay that opens above seq 0 still stamps every notice with its wire seq', () => {
    const client = subscribed(fixture.agents.codexRegistry);

    client.receiveServerFrame(
      JSON.stringify({
        op: 'events',
        threadId: 'ident-1',
        fromSeq: 4,
        events: [warningEvent(1), warningEvent(2)],
      }),
    );

    const notices = (client.getThreadModel('ident-1')?.items ?? []).filter(
      (item) => item.kind === 'agent_notice',
    );
    expect(notices.map((item) => (item as { seq: number }).seq)).toEqual([4, 5]);
    const stored = client.getThread('ident-1');
    expect(stored?.lastSeq).toBe(5);
    expect(stored?.events.length).toBe((stored?.lastSeq ?? -1) + 1);
  });

  test('a batched replay and a live arrival of the same events agree', () => {
    const events = [warningEvent(1), warningEvent(2)];

    const live = subscribed(fixture.agents.codexRegistry);
    events.forEach((event, index) => {
      live.receiveServerFrame(
        JSON.stringify({ op: 'event', threadId: 'ident-1', seq: index, event }),
      );
    });

    const replayed = subscribed(fixture.agents.codexRegistry);
    replayed.receiveServerFrame(
      JSON.stringify({ op: 'events', threadId: 'ident-1', fromSeq: 0, events }),
    );

    expect(replayed.getThreadModel('ident-1')?.items).toEqual(
      live.getThreadModel('ident-1')?.items,
    );
    expect(replayed.getThreadModel('ident-1')?.items).toHaveLength(2);
  });
});

describe('a refused resume keeps the archived thread open', () => {
  const archivedInfo: ThreadInfo = {
    threadId: 't1',
    agent: { id: 'a', name: 'A', source: 'custom' },
    title: 'A',
    status: 'exited',
    createdAt: 1,
    lastActivityAt: 1,
    lastSeq: 3,
    archived: true,
    resumable: false,
  };

  const ev = (i: number): ThreadEvent => ({ kind: 'user_message', content: `m${i}`, ts: i });
  const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));

  function openedFromHistory(): {
    client: AgentThreadClient;
    sent: Array<Record<string, unknown>>;
    frame: (f: ThreadServerFrame) => void;
  } {
    const client = new AgentThreadClient();
    const sent: Array<Record<string, unknown>> = [];
    const internals = client as unknown as {
      ws: unknown;
      handleFrame: (f: ThreadServerFrame) => void;
    };
    internals.ws = {
      readyState: 1,
      send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),
    };
    const frame = (f: ThreadServerFrame) => internals.handleFrame.call(client, f);
    frame({ op: 'threads', threads: [archivedInfo] });
    client.openArchivedThread('t1');
    frame({ op: 'subscribed', threadId: 't1', fromSeq: 0, info: archivedInfo });
    frame({ op: 'events', threadId: 't1', fromSeq: 0, events: [ev(0), ev(1), ev(2), ev(3)] });
    return { client, sent, frame };
  }

  test('the tab and its transcript survive the server re-archiving the thread', async () => {
    const { client, sent, frame } = openedFromHistory();
    expect(client.getOpenTabs().map((info) => info.threadId)).toEqual(['t1']);

    const pending = client.resumeThread('t1');
    await flush();
    const reqId = sent.find((f) => f.op === 'resume')?.reqId as string;

    frame({ op: 'info', info: { ...archivedInfo, archived: false, status: 'installing' } });
    frame({ op: 'info', info: { ...archivedInfo, archived: true, status: 'exited' } });
    frame({
      op: 'events',
      threadId: 't1',
      fromSeq: 4,
      events: [
        { kind: 'status', status: 'installing', ts: 4 },
        { kind: 'status', status: 'exited', detail: 'resume failed', ts: 5 },
      ],
    });
    frame({
      op: 'error',
      code: 'resume-unsupported',
      message: "the agent doesn't support resuming",
      reqId,
      threadId: 't1',
    });

    await expect(pending).rejects.toThrow(/resuming/);
    expect(client.getOpenTabs().map((info) => info.threadId)).toEqual(['t1']);
    const state = client.getThread('t1');
    expect(state?.lastSeq).toBe(5);
    expect(state?.events).toHaveLength(6);
    expect(
      state?.events.some(
        (event) => event.kind === 'agent_stderr' && /missing log/.test(event.line),
      ),
    ).toBe(false);
  });

  test('an archive that no resume asked for still closes the tab', () => {
    const { client, frame } = openedFromHistory();
    frame({ op: 'info', info: { ...archivedInfo, archived: false, status: 'ready' } });
    expect(client.getOpenTabs().map((info) => info.threadId)).toEqual(['t1']);

    frame({ op: 'info', info: { ...archivedInfo, archived: true, status: 'exited' } });
    expect(client.getOpenTabs()).toEqual([]);
  });

  test('a late archive still finds the guard up after the client has given up waiting', async () => {
    vi.useFakeTimers();
    try {
      const { client, frame } = openedFromHistory();
      const settled = client.resumeThread('t1').then(
        () => null,
        (err: Error) => err,
      );
      await vi.advanceTimersByTimeAsync(0);
      frame({ op: 'info', info: { ...archivedInfo, archived: false, status: 'installing' } });

      await vi.advanceTimersByTimeAsync(THREAD_REOPEN_OP_TIMEOUT_MS + 1);
      expect((await settled)?.message).toMatch(/timed out/);

      frame({ op: 'info', info: { ...archivedInfo, archived: true, status: 'exited' } });
      expect(client.getOpenTabs().map((info) => info.threadId)).toEqual(['t1']);
    } finally {
      vi.useRealTimers();
    }
  });

  test('a resume that timed out locally still lets a later refusal bring the guard down', async () => {
    vi.useFakeTimers();
    try {
      const { client, sent, frame } = openedFromHistory();
      const settled = client.resumeThread('t1').then(
        () => null,
        (err: Error) => err,
      );
      await vi.advanceTimersByTimeAsync(0);
      const reqId = sent.find((f) => f.op === 'resume')?.reqId as string;
      frame({ op: 'info', info: { ...archivedInfo, archived: false, status: 'installing' } });

      await vi.advanceTimersByTimeAsync(THREAD_REOPEN_OP_TIMEOUT_MS + 1);
      expect((await settled)?.message).toMatch(/timed out/);

      frame({
        op: 'error',
        code: 'resume-unsupported',
        message: "the agent doesn't support resuming",
        reqId,
        threadId: 't1',
      });
      frame({ op: 'info', info: { ...archivedInfo, archived: true, status: 'exited' } });
      expect(client.getOpenTabs()).toEqual([]);
    } finally {
      vi.useRealTimers();
    }
  });

  test('a socket that drops mid-resume leaves no guard behind for the next archive', async () => {
    const { client, frame } = openedFromHistory();
    const settled = client.resumeThread('t1').then(
      () => null,
      (err: Error) => err,
    );
    await flush();
    frame({ op: 'info', info: { ...archivedInfo, archived: false, status: 'installing' } });

    (client as unknown as { url: string | null }).url = 'ws://example.invalid';
    client.setUrl(null);
    expect(await settled).toBeInstanceOf(ThreadChannelUnavailableError);

    frame({ op: 'info', info: { ...archivedInfo, archived: true, status: 'exited' } });
    expect(client.getOpenTabs()).toEqual([]);
  });

  test('an archive arriving after the server answered the resume still closes the tab', async () => {
    const { client, sent, frame } = openedFromHistory();
    const pending = client.resumeThread('t1');
    await flush();
    const reqId = sent.find((f) => f.op === 'resume')?.reqId as string;

    frame({ op: 'info', info: { ...archivedInfo, archived: false, status: 'installing' } });
    frame({
      op: 'error',
      code: 'resume-unsupported',
      message: "the agent doesn't support resuming",
      reqId,
      threadId: 't1',
    });
    await expect(pending).rejects.toThrow(/resuming/);

    frame({ op: 'info', info: { ...archivedInfo, archived: false, status: 'ready' } });
    frame({ op: 'info', info: { ...archivedInfo, archived: true, status: 'exited' } });
    expect(client.getOpenTabs()).toEqual([]);
  });
});

describe('what the server says about resuming', () => {
  const archivedInfo: ThreadInfo = {
    threadId: 't1',
    agent: { id: 'a', name: 'A', source: 'custom' },
    title: 'A',
    status: 'exited',
    createdAt: 1,
    lastActivityAt: 1,
    lastSeq: -1,
    archived: true,
  };

  function makeClient(): { client: AgentThreadClient; frame: (f: ThreadServerFrame) => void } {
    const client = new AgentThreadClient();
    const internals = client as unknown as {
      ws: unknown;
      handleFrame: (f: ThreadServerFrame) => void;
    };
    internals.ws = { readyState: 1, send: () => {} };
    return { client, frame: (f) => internals.handleFrame.call(client, f) };
  }

  test('a thread the server calls unresumable reads back that way without anyone asking', () => {
    const { client, frame } = makeClient();
    frame({ op: 'threads', threads: [{ ...archivedInfo, resumable: false }] });
    expect(client.getThread('t1')?.info.resumable).toBe(false);
  });

  test('a thread that opens a session reads back as resumable again', () => {
    const { client, frame } = makeClient();
    frame({ op: 'threads', threads: [{ ...archivedInfo, archived: false, resumable: false }] });
    expect(client.getThread('t1')?.info.resumable).toBe(false);

    frame({
      op: 'info',
      info: { ...archivedInfo, archived: false, status: 'ready', resumable: true },
    });
    expect(client.getThread('t1')?.info.resumable).toBe(true);
  });
});