Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

113 KB
Raw Blame
import { render, waitFor } from '@testing-library/react';
import { act } from 'react';
import { Provider } from 'react-redux';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import * as chatService from '../../services/chatService';
import { threadApi } from '../../services/api/threadApi';
import { socketService } from '../../services/socketService';
import { store } from '../../store';
import {
  beginInferenceTurn,
  clearAllChatRuntime,
  findPendingDelegationContext,
  registerParallelRequest,
  resetSessionTokenUsage,
  setPendingPlanReviewForThread,
  setStreamingAssistantForThread,
  streamDeltaReceived,
} from '../../store/chatRuntimeSlice';
import { pendingFollowupAdded } from '../../store/queueSlice';
import { setStatusForUser } from '../../store/socketSlice';
import {
  clearAllThreads,
  loadThreads,
  setActiveThread,
  setSelectedThread,
} from '../../store/threadSlice';
import ChatRuntimeProvider from '../ChatRuntimeProvider';
import { clearAllProactiveThreadPins } from '../proactiveThreadPins';

vi.mock('../../services/chatService', async () => {
  const actual = await vi.importActual<typeof chatService>('../../services/chatService');
  return {
    ...actual,
    subscribeChatEvents: vi.fn(),
    subscribeQueueEvents: vi.fn(() => () => {}),
    subscribeSuggestionEvents: vi.fn(() => () => {}),
  };
});

vi.mock('../../services/api/threadApi', () => ({
  threadApi: {
    createNewThread: vi.fn(),
    getThreads: vi.fn(),
    getThreadMessages: vi.fn(),
    appendMessage: vi.fn(),
    generateTitleIfNeeded: vi.fn(),
    updateMessage: vi.fn(),
    deleteThread: vi.fn(),
    purge: vi.fn(),
    getTurnState: vi.fn(),
    listRuns: vi.fn(),
  },
}));

vi.mock('../../services/socketService', () => ({
  socketService: { subscribeThread: vi.fn(() => Promise.resolve(true)) },
}));

vi.mock('../../hooks/usageRefresh', () => ({ requestUsageRefresh: vi.fn() }));

const mockRefetchSnapshot = vi.fn();
vi.mock('../../hooks/useRefetchSnapshotOnTurnEnd', () => ({
  useRefetchSnapshotOnTurnEnd: () => ({ refetch: mockRefetchSnapshot }),
}));

function renderProvider(): chatService.ChatEventListeners {
  let captured: chatService.ChatEventListeners = {};
  vi.mocked(chatService.subscribeChatEvents).mockImplementation(listeners => {
    captured = listeners;
    return () => {};
  });

  // Mark the pending user's socket as connected so the subscribe effect fires.
  store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));

  render(
    <Provider store={store}>
      <ChatRuntimeProvider>
        <div />
      </ChatRuntimeProvider>
    </Provider>
  );

  return captured;
}

function resetRuntimeState() {
  // Reset chatRuntime + thread slices to clean state by dispatching a thread
  // selection that clears ambient state.
  store.dispatch(clearAllThreads());
  store.dispatch(clearAllChatRuntime());
  // `clearAllChatRuntime` intentionally preserves cumulative session token
  // usage; reset it here so usage-recording tests stay isolated regardless of
  // run order.
  store.dispatch(resetSessionTokenUsage());
  store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));
  // Pins live at module scope, so clear them between tests or a pinned voice
  // surface would leak into the next test.
  clearAllProactiveThreadPins();
}

describe('ChatRuntimeProvider — dedupe, proactive resolution, mid-turn invariants', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    resetRuntimeState();
    vi.mocked(threadApi.appendMessage).mockImplementation(async (_tid, msg) => msg);
    vi.mocked(threadApi.getThreadMessages).mockResolvedValue({ messages: [] } as unknown as Awaited<
      ReturnType<typeof threadApi.getThreadMessages>
    >);
    vi.mocked(threadApi.getThreads).mockResolvedValue({ threads: [], count: 0 });
    vi.mocked(threadApi.getTurnState).mockResolvedValue(null);
    vi.mocked(threadApi.listRuns).mockResolvedValue([]);
    vi.mocked(threadApi.generateTitleIfNeeded).mockResolvedValue({
      id: 'tid',
      title: 'new',
    } as never);
  });

  describe('dedupe', () => {
    it('stops completed-turn snapshot polling when the provider unmounts', async () => {
      vi.useFakeTimers();
      let listeners: chatService.ChatEventListeners = {};
      vi.mocked(chatService.subscribeChatEvents).mockImplementation(value => {
        listeners = value;
        return () => {};
      });
      store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));
      const view = render(
        <Provider store={store}>
          <ChatRuntimeProvider>
            <div />
          </ChatRuntimeProvider>
        </Provider>
      );
      try {
        await act(async () => {
          listeners.onDone?.({
            thread_id: 'unmounted-snapshot',
            request_id: 'unmounted-request',
            full_response: 'Delivered reply',
            total_input_tokens: 0,
            total_output_tokens: 0,
          });
        });
        expect(threadApi.getTurnState).toHaveBeenCalledWith('unmounted-snapshot');
        view.unmount();
        const callsBeforeUnmount = vi.mocked(threadApi.getTurnState).mock.calls.length;
        await act(async () => {
          await vi.advanceTimersByTimeAsync(2_000);
        });
        expect(threadApi.getTurnState).toHaveBeenCalledTimes(callsBeforeUnmount);
      } finally {
        view.unmount();
        vi.useRealTimers();
      }
    });

    it('finds pending spawn and async delegation tool rows', () => {
      const entries = [
        { id: 'ignored', name: 'search', round: 0, status: 'running' },
        {
          id: 'spawn',
          name: 'spawn_subagent',
          round: 0,
          status: 'running',
          argsBuffer: '{"prompt":"Archive preferences."}',
        },
      ] as Parameters<typeof findPendingDelegationContext>[0];

      expect(findPendingDelegationContext(entries, 0)).toEqual({
        sourceToolName: 'spawn_subagent',
        prompt: 'Archive preferences.',
        spawnEntryId: 'spawn',
      });

      expect(
        findPendingDelegationContext(
          [{ id: 'sync', name: 'spawn_subagent', round: 1, status: 'running' }] as Parameters<
            typeof findPendingDelegationContext
          >[0],
          1
        )
      ).toMatchObject({ sourceToolName: 'spawn_subagent', spawnEntryId: 'sync' });
    });

    it('drops duplicate tool_call events with the same thread/request/round/tool', () => {
      const listeners = renderProvider();

      const event: chatService.ChatToolCallEvent = {
        thread_id: 't1',
        request_id: 'r1',
        round: 0,
        tool_name: 'search',
        skill_id: 'notion',
        args: {},
        tool_call_id: 'call-1',
      };

      act(() => {
        listeners.onToolCall?.(event);
        listeners.onToolCall?.(event);
      });

      const timeline = store.getState().chatRuntime.toolTimelineByThread['t1'] ?? [];
      expect(timeline).toHaveLength(1);
      expect(timeline[0]?.name).toBe('search');
      expect(timeline[0]?.status).toBe('running');
    });

    it('attaches the tool_result output to the timeline row as its result', () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onToolCall?.({
          thread_id: 't-res',
          request_id: 'r1',
          round: 0,
          tool_name: 'web_search',
          skill_id: 'web_channel',
          args: {},
          tool_call_id: 'call-res',
        });
        listeners.onToolResult?.({
          thread_id: 't-res',
          request_id: 'r1',
          round: 0,
          tool_name: 'web_search',
          skill_id: 'web_channel',
          output: 'Top hit: openhuman.dev',
          success: true,
          tool_call_id: 'call-res',
        });
      });

      const row = store.getState().chatRuntime.toolTimelineByThread['t-res']?.[0];
      expect(row?.status).toBe('success');
      expect(row?.result).toBe('Top hit: openhuman.dev');
    });

    it('leaves result unset when the tool_result carries no output text', () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onToolCall?.({
          thread_id: 't-res2',
          request_id: 'r1',
          round: 0,
          tool_name: 'web_search',
          skill_id: 'web_channel',
          args: {},
          tool_call_id: 'call-res2',
        });
        listeners.onToolResult?.({
          thread_id: 't-res2',
          request_id: 'r1',
          round: 0,
          tool_name: 'web_search',
          skill_id: 'web_channel',
          output: '',
          success: true,
          tool_call_id: 'call-res2',
        });
      });

      const row = store.getState().chatRuntime.toolTimelineByThread['t-res2']?.[0];
      expect(row?.status).toBe('success');
      expect(row?.result).toBeUndefined();
    });

    it('collapses a spawn_subagent tool-call row into the subagent row', () => {
      const listeners = renderProvider();

      act(() => {
        // Parent invokes the delegation tool — creates a "spawn_subagent" row.
        listeners.onToolCall?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          tool_name: 'spawn_subagent',
          skill_id: 'orchestration',
          args: {},
          tool_call_id: 'call-spawn',
        });
        // The delegation prompt streams in as the tool's args JSON.
        listeners.onToolArgsDelta?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          tool_call_id: 'call-spawn',
          tool_name: 'spawn_subagent',
          delta: '{"prompt":"Research Q3 revenue."}',
        });
        // The child spawns — should REPLACE the tool-call row, not add a second.
        listeners.onSubagentSpawned?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          tool_name: 'researcher',
          skill_id: 'sub-1',
          message: 'spawned',
          subagent: { mode: 'typed' },
        });
      });

      const timeline = store.getState().chatRuntime.toolTimelineByThread['t1'] ?? [];
      expect(timeline).toHaveLength(1);
      expect(timeline[0]?.name).toBe('subagent:researcher');
      // The parent's delegation prompt is carried onto the subagent so the
      // drawer can open the conversation with it.
      expect(timeline[0]?.subagent?.prompt).toContain('Research Q3 revenue');
    });

    it('collapses a spawn_subagent tool-call row into the subagent row', () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onToolCall?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          tool_name: 'spawn_subagent',
          skill_id: 'orchestration',
          args: {},
          tool_call_id: 'call-spawn-async',
        });
        listeners.onToolArgsDelta?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          tool_call_id: 'call-spawn-async',
          tool_name: 'spawn_subagent',
          delta: '{"prompt":"Archive these preferences."}',
        });
        listeners.onSubagentSpawned?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          tool_name: 'archivist',
          skill_id: 'sub-async-1',
          message: 'spawned',
          subagent: { mode: 'async' },
        });
      });

      const timeline = store.getState().chatRuntime.toolTimelineByThread['t1'] ?? [];
      expect(timeline).toHaveLength(1);
      expect(timeline[0]?.name).toBe('subagent:archivist');
      expect(timeline[0]?.sourceToolName).toBe('spawn_subagent');
      expect(timeline[0]?.subagent?.prompt).toContain('Archive these preferences');
    });

    it('appends streamed subagent text & thinking deltas to the subagent transcript', () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onSubagentSpawned?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          tool_name: 'researcher',
          skill_id: 'sub-1',
          message: 'spawned',
          subagent: { mode: 'typed' },
        });
        listeners.onSubagentThinkingDelta?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          delta: 'let me think',
          subagent: { task_id: 'sub-1', agent_id: 'researcher', child_iteration: 1 },
        });
        listeners.onSubagentTextDelta?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          delta: 'the answer',
          subagent: { task_id: 'sub-1', agent_id: 'researcher', child_iteration: 1 },
        });
      });

      const row = (store.getState().chatRuntime.toolTimelineByThread['t1'] ?? []).find(
        e => e.subagent?.taskId === 'sub-1'
      );
      expect(row?.subagent?.transcript).toEqual([
        { kind: 'thinking', iteration: 1, text: 'let me think' },
        { kind: 'text', iteration: 1, text: 'the answer' },
      ]);
    });

    it('ignores subagent deltas missing task/agent/delta', () => {
      const listeners = renderProvider();
      act(() => {
        listeners.onSubagentSpawned?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          tool_name: 'researcher',
          skill_id: 'sub-1',
          message: 'spawned',
          subagent: { mode: 'typed' },
        });
        // No agent_id → dropped.
        listeners.onSubagentTextDelta?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          delta: 'x',
          subagent: { task_id: 'sub-1' },
        });
      });
      const row = (store.getState().chatRuntime.toolTimelineByThread['t1'] ?? []).find(
        e => e.subagent?.taskId === 'sub-1'
      );
      expect(row?.subagent?.transcript).toEqual([]);
    });

    it('routes a parallel (forked) turn into its own lane, leaving the primary stream untouched', async () => {
      const listeners = renderProvider();

      // Primary turn streams on the thread.
      act(() => {
        listeners.onTextDelta?.({
          thread_id: 't-par',
          request_id: 'primary',
          round: 0,
          delta: 'P',
        });
      });
      // A parallel turn is registered and streams concurrently on the SAME thread.
      act(() => {
        store.dispatch(registerParallelRequest({ threadId: 't-par', requestId: 'branch' }));
        listeners.onTextDelta?.({
          thread_id: 't-par',
          request_id: 'branch',
          round: 0,
          delta: 'B1',
        });
        listeners.onTextDelta?.({
          thread_id: 't-par',
          request_id: 'branch',
          round: 0,
          delta: 'B2',
        });
      });

      // Deltas are coalesced per frame (`chatDeltaCoalescer`); wait for the flush.
      await waitFor(() =>
        expect(
          store.getState().chatRuntime.parallelStreamsByThread['t-par']?.['branch']?.content
        ).toBe('B1B2')
      );
      const mid = store.getState().chatRuntime;
      // Primary stream is not clobbered by the parallel branch.
      expect(mid.streamingAssistantByThread['t-par']?.content).toBe('P');
      expect(mid.parallelStreamsByThread['t-par']?.['branch']?.content).toBe('B1B2');

      // The parallel turn's chat_done resolves ONLY its lane; the primary
      // stream and its (still-running) state survive.
      act(() => {
        listeners.onDone?.({
          thread_id: 't-par',
          request_id: 'branch',
          full_response: 'branch done',
          total_input_tokens: 0,
          total_output_tokens: 0,
          segment_total: 0,
        });
      });

      const after = store.getState().chatRuntime;
      expect(after.parallelStreamsByThread['t-par']).toBeUndefined();
      expect(after.parallelRequestThreads['branch']).toBeUndefined();
      expect(after.streamingAssistantByThread['t-par']?.content).toBe('P');
    });

    it('marks a failed parallel turn for the assistant-ui error card', async () => {
      const listeners = renderProvider();
      act(() => {
        store.dispatch(registerParallelRequest({ threadId: 't-par', requestId: 'branch-error' }));
        listeners.onError?.({
          thread_id: 't-par',
          request_id: 'branch-error',
          message: 'The provider refused this turn.',
          error_type: 'provider_error',
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          't-par',
          expect.objectContaining({
            content: 'The provider refused this turn.',
            extraMetadata: expect.objectContaining({
              chatError: expect.objectContaining({ errorType: 'provider_error' }),
            }),
          })
        )
      );
      expect(store.getState().chatRuntime.parallelRequestThreads['branch-error']).toBeUndefined();
    });

    describe('chat_error copy_key rendering', () => {
      const failParallel = (
        requestId: string,
        extra: { copy_key?: string; copy_params?: Record<string, unknown> }
      ) => {
        const listeners = renderProvider();
        act(() => {
          store.dispatch(registerParallelRequest({ threadId: 't-copy', requestId }));
          listeners.onError?.({
            thread_id: 't-copy',
            request_id: requestId,
            message: 'core english message',
            error_type: 'rate_limited',
            ...extra,
          });
        });
      };

      it('renders a known copy_key from the locale table with its params', async () => {
        failParallel('copy-known', {
          copy_key: 'chat_error.rate_limited',
          copy_params: { retry_after_secs: 30, detail: 'quota hit' },
        });
        await waitFor(() =>
          expect(threadApi.appendMessage).toHaveBeenCalledWith(
            't-copy',
            expect.objectContaining({
              content:
                'Your AI provider is rate-limiting requests. This is a transient upstream limit, not a thread-level block. You can retry in this thread. Try again in 30 seconds.\n\n> quota hit',
            })
          )
        );
      });

      it('falls back to message for an unknown copy_key', async () => {
        failParallel('copy-unknown', { copy_key: 'chat_error.from_a_newer_core' });
        await waitFor(() =>
          expect(threadApi.appendMessage).toHaveBeenCalledWith(
            't-copy',
            expect.objectContaining({ content: 'core english message' })
          )
        );
      });

      it('falls back to message when copy_key is missing', async () => {
        failParallel('copy-missing', {});
        await waitFor(() =>
          expect(threadApi.appendMessage).toHaveBeenCalledWith(
            't-copy',
            expect.objectContaining({ content: 'core english message' })
          )
        );
      });
    });

    it('bumps the heartbeat counter only for the primary turn, never a parallel branch (#4282)', () => {
      const listeners = renderProvider();

      // Primary turn's heartbeat advances the thread's liveness counter.
      act(() => {
        listeners.onInferenceHeartbeat?.({ thread_id: 't-par', request_id: 'primary' });
      });
      expect(store.getState().chatRuntime.inferenceHeartbeatByThread['t-par']).toBe(1);

      // A registered parallel branch's heartbeat must NOT rearm the primary
      // silence timer — otherwise a sibling would mask a stalled primary turn.
      act(() => {
        store.dispatch(registerParallelRequest({ threadId: 't-par', requestId: 'branch' }));
        listeners.onInferenceHeartbeat?.({ thread_id: 't-par', request_id: 'branch' });
        listeners.onInferenceHeartbeat?.({ thread_id: 't-par', request_id: 'branch' });
      });
      expect(store.getState().chatRuntime.inferenceHeartbeatByThread['t-par']).toBe(1);

      // The primary turn keeps beating independently.
      act(() => {
        listeners.onInferenceHeartbeat?.({ thread_id: 't-par', request_id: 'primary' });
      });
      expect(store.getState().chatRuntime.inferenceHeartbeatByThread['t-par']).toBe(2);
    });

    it('shows a primary turn compacting until its next iteration starts', () => {
      const listeners = renderProvider();
      const phase = () => store.getState().chatRuntime.inferenceStatusByThread['t-cmp']?.phase;

      act(() => {
        listeners.onContextCompacting?.({ thread_id: 't-cmp', request_id: 'primary', round: 1 });
      });
      expect(phase()).toBe('compacting');

      act(() => {
        listeners.onIterationStart?.({
          thread_id: 't-cmp',
          request_id: 'primary',
          round: 1,
          message: 'Iteration 1/200',
        });
      });
      expect(phase()).toBe('thinking');
    });

    it('ignores a superseded turn compacting', () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onInferenceStart?.({ thread_id: 't-cmp-old', request_id: 'newer' });
        listeners.onContextCompacting?.({ thread_id: 't-cmp-old', request_id: 'older', round: 1 });
      });
      expect(store.getState().chatRuntime.inferenceStatusByThread['t-cmp-old']?.phase).toBe(
        'thinking'
      );
    });

    it('ignores a parallel branch compacting', () => {
      const listeners = renderProvider();

      act(() => {
        store.dispatch(registerParallelRequest({ threadId: 't-cmp-par', requestId: 'branch' }));
        listeners.onContextCompacting?.({ thread_id: 't-cmp-par', request_id: 'branch', round: 1 });
      });
      expect(store.getState().chatRuntime.inferenceStatusByThread['t-cmp-par']).toBeUndefined();
    });

    it('drops duplicate chat_done events with the same thread/request', async () => {
      const listeners = renderProvider();

      const doneEvent: chatService.ChatDoneEvent = {
        thread_id: 't-done',
        request_id: 'r-done',
        full_response: 'hello',
        total_input_tokens: 5,
        total_output_tokens: 7,
        segment_total: 1,
      };

      act(() => {
        listeners.onDone?.(doneEvent);
        listeners.onDone?.(doneEvent);
      });

      // Usage recorded exactly once despite duplicate dispatch.
      const usage = store.getState().chatRuntime.sessionTokenUsage;
      expect(usage.inputTokens).toBe(5);
      expect(usage.outputTokens).toBe(7);
      expect(usage.turns).toBe(1);

      // Snapshot refetch fired exactly once on the first chat_done — issue #924.
      await waitFor(() => expect(mockRefetchSnapshot).toHaveBeenCalledTimes(1));
    });

    it('persists a core-initiated (system) turn under the id the core already wrote (#5933)', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onDone?.({
          thread_id: 't-sys',
          request_id: 'bgdeliver-1',
          client_id: 'system',
          full_response: 'Same two issues as before',
        });
      });

      // The same `agent:<run_id>` id the core persisted, so the idempotent
      // store collapses this append onto its own row instead
      // of keeping a second copy of the reply.
      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          't-sys',
          expect.objectContaining({
            id: 'agent:bgdeliver-1',
            sender: 'agent',
            content: 'Same two issues as before',
            extraMetadata: expect.objectContaining({ requestId: 'bgdeliver-1' }),
          })
        )
      );
    });

    it('persists a core-initiated (system) turn failure under the same core id', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onError?.({
          thread_id: 't-sys-err',
          request_id: 'bgdeliver-2',
          client_id: 'system',
          message: 'Run failed: boom',
          error_type: 'inference',
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          't-sys-err',
          expect.objectContaining({ id: 'agent:bgdeliver-2', sender: 'agent' })
        )
      );
    });

    it('persists a second core failure with identical text under its own id (#5933)', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onError?.({
          thread_id: 't-sys-err-dup',
          request_id: 'bgdeliver-a',
          client_id: 'system',
          message: 'Run failed: boom',
          error_type: 'inference',
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          't-sys-err-dup',
          expect.objectContaining({ id: 'agent:bgdeliver-a' })
        )
      );

      // Same thread, same failure text, a different run. The core persisted
      // this one as `agent:bgdeliver-b`; deduping on the last row's content
      // would read the previous run's row as this one and drop the new
      // failure from the cache entirely.
      act(() => {
        listeners.onError?.({
          thread_id: 't-sys-err-dup',
          request_id: 'bgdeliver-b',
          client_id: 'system',
          message: 'Run failed: boom',
          error_type: 'inference',
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          't-sys-err-dup',
          expect.objectContaining({ id: 'agent:bgdeliver-b', sender: 'agent' })
        )
      );
      expect(threadApi.appendMessage).toHaveBeenCalledTimes(2);
    });

    it('still suppresses a repeat of the same core failure event', async () => {
      const listeners = renderProvider();
      const fire = () =>
        act(() => {
          listeners.onError?.({
            thread_id: 't-sys-err-same',
            request_id: 'bgdeliver-c',
            client_id: 'system',
            message: 'Run failed: boom',
            error_type: 'inference',
          });
        });

      fire();
      await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(1));

      // The row is in the cache under `agent:bgdeliver-c` now, so the id check
      // recognises the redelivery. Trading the content check for an id check
      // must not turn a duplicate event into a duplicate append.
      fire();
      await act(async () => {
        await Promise.resolve();
      });
      expect(threadApi.appendMessage).toHaveBeenCalledTimes(1);
    });

    it('mirrors the core id on an interactive chat_done so the two writers collapse (#6034)', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onDone?.({ thread_id: 't-user', request_id: 'r-user', full_response: 'hi' });
      });

      // The core stores an unsegmented reply before announcing it, so this
      // append must carry the same `agent:<request_id>` id — otherwise the
      // thread ends up with the core's row AND ours, which is #5933 again.
      await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(1));
      const [, persisted] = vi.mocked(threadApi.appendMessage).mock.calls[0];
      expect(persisted.id).toBe('agent:r-user');
      expect(persisted.sender).toBe('agent');
    });

    it('surfaces a user-visible error when neither writer stored the reply (#6034)', async () => {
      vi.mocked(threadApi.appendMessage).mockRejectedValueOnce(new Error('rpc timeout'));
      // The refetch succeeds but the row is genuinely not there — the case
      // where the core write failed too. A console line is not enough here:
      // the user is looking at a finished turn with no answer.
      vi.mocked(threadApi.getThreadMessages).mockResolvedValueOnce({
        messages: [],
      } as unknown as Awaited<ReturnType<typeof threadApi.getThreadMessages>>);

      const listeners = renderProvider();
      act(() => {
        listeners.onDone?.({
          thread_id: 't-gone',
          request_id: 'r-gone',
          full_response: 'an answer nobody stored',
        });
      });

      await waitFor(() =>
        expect(
          Object.values(store.getState().userErrors.byId).some(
            e => e.kind === 'reply_delivery_failed'
          )
        ).toBe(true)
      );
    });

    it('keeps a generated id for a segmented chat_done (the core left those rows to us)', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onDone?.({
          thread_id: 't-seg',
          request_id: 'r-seg',
          full_response: 'one two',
          segment_total: 2,
        });
      });

      // Segments are the client's rows to write, several of them under one
      // request id, so a shared deterministic id would make them collapse onto
      // each other and lose all but the first.
      await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(1));
      const [, persisted] = vi.mocked(threadApi.appendMessage).mock.calls[0];
      expect(persisted.id).not.toBe('agent:r-seg');
    });

    it('re-reads the thread when the append fails, so the core row still renders (#6034)', async () => {
      vi.mocked(threadApi.appendMessage).mockRejectedValueOnce(new Error('rpc timeout'));
      vi.mocked(threadApi.getThreadMessages).mockResolvedValueOnce({
        messages: [
          {
            id: 'agent:r-lost',
            content: 'the answer the core stored',
            type: 'text',
            sender: 'agent',
            createdAt: new Date().toISOString(),
            extraMetadata: {},
          },
        ],
      } as unknown as Awaited<ReturnType<typeof threadApi.getThreadMessages>>);

      const listeners = renderProvider();

      act(() => {
        listeners.onDone?.({
          thread_id: 't-lost',
          request_id: 'r-lost',
          full_response: 'the answer the core stored',
        });
      });

      // The failed append used to end the story with a debug log and no
      // assistant row. Re-reading the thread is what brings the core's copy
      // into the cache without the user having to ask again.
      await waitFor(() => expect(threadApi.getThreadMessages).toHaveBeenCalledWith('t-lost'));
      await waitFor(() =>
        expect(
          (store.getState().thread.messagesByThreadId['t-lost'] ?? []).some(
            m => m.id === 'agent:r-lost'
          )
        ).toBe(true)
      );
    });

    it('stores a parked plan review from the plan_review_request event', () => {
      const listeners = renderProvider();
      act(() => {
        listeners.onPlanReviewRequest?.({
          thread_id: 't-plan',
          request_id: 'pr-1',
          message: 'Ship the release',
          args: { steps: ['build', 'verify'] },
        });
      });
      const review = store.getState().chatRuntime.pendingPlanReviewByThread['t-plan'];
      expect(review).toEqual({
        requestId: 'pr-1',
        summary: 'Ship the release',
        steps: ['build', 'verify'],
      });
    });

    it('clears a parked plan review when its decision event arrives', () => {
      const listeners = renderProvider();
      act(() => {
        listeners.onPlanReviewRequest?.({
          thread_id: 't-plan-decided',
          request_id: 'pr-decided',
          message: 'Ship the release',
          args: { steps: ['build'] },
        });
      });
      expect(
        store.getState().chatRuntime.pendingPlanReviewByThread['t-plan-decided']?.requestId
      ).toBe('pr-decided');

      act(() => {
        listeners.onPlanReviewDecided?.({
          thread_id: 't-plan-decided',
          request_id: 'pr-decided',
          message: 'reject',
          cancel_reason: 'cancelled',
        });
      });

      expect(
        store.getState().chatRuntime.pendingPlanReviewByThread['t-plan-decided']
      ).toBeUndefined();
    });

    it('clears a parked plan review when the turn ends or errors', () => {
      const listeners = renderProvider();
      const park = () =>
        store.dispatch(
          setPendingPlanReviewForThread({
            threadId: 't-plan',
            review: { requestId: 'pr-1', summary: 'Plan', steps: ['a'] },
          })
        );

      // chat_done clears the (possibly expired) parked review.
      park();
      act(() => {
        listeners.onDone?.({
          thread_id: 't-plan',
          request_id: 'r-plan',
          full_response: 'done',
          total_input_tokens: 1,
          total_output_tokens: 1,
          segment_total: 1,
        });
      });
      expect(store.getState().chatRuntime.pendingPlanReviewByThread['t-plan']).toBeUndefined();

      // chat_error also clears it (cancelled/errored parked turn).
      park();
      act(() => {
        listeners.onError?.({
          thread_id: 't-plan',
          request_id: 'r-plan',
          message: 'boom',
          error_type: 'inference',
        });
      });
      expect(store.getState().chatRuntime.pendingPlanReviewByThread['t-plan']).toBeUndefined();
    });

    it('reloads a runner-persisted queued upload without appending a duplicate', async () => {
      const listeners = renderProvider();
      const parts = [
        {
          kind: 'file' as const,
          fileName: 'archive.zip',
          caption: null,
          media: {
            kind: 'document' as const,
            url: 'data:application/zip;name=archive.zip;base64,AQID',
            contentType: null,
            fileName: 'archive.zip',
            sizeBytes: null,
            codec: null,
            durationMs: null,
            height: null,
            localCachePath: null,
            path: null,
            platformMessageId: null,
            transcribed: false,
            width: null,
          },
        },
      ];
      const stagedParts = [
        { ...parts[0], media: { ...parts[0].media, url: null, opaqueId: 'opaque-upload' } },
      ];
      store.dispatch(
        pendingFollowupAdded({
          threadId: 't-upload',
          message: {
            id: 'queued-upload',
            content: '',
            type: 'text',
            extraMetadata: { attachmentNames: ['archive.zip'], attachmentKinds: ['file'] },
            sender: 'user',
            createdAt: '2026-01-01T00:00:00.000Z',
          },
          text: '',
          requestId: 'r-upload',
          attachments: stagedParts,
        })
      );
      expect(
        JSON.stringify(store.getState().queue.pendingFollowupsByThread['t-upload'])
      ).not.toContain('base64');
      vi.mocked(threadApi.getThreadMessages).mockResolvedValueOnce({
        messages: [
          {
            id: 'user:r-upload',
            content: 'look',
            type: 'text',
            extraMetadata: {},
            sender: 'user',
            createdAt: '2026-01-01T00:00:00.000Z',
            attachments: stagedParts,
          },
        ],
      } as never);
      await act(async () => {
        listeners.onDone?.({
          thread_id: 't-upload',
          request_id: 'r-upload',
          full_response: 'done',
          total_input_tokens: 1,
          total_output_tokens: 1,
        });
      });
      await waitFor(() => expect(threadApi.getThreadMessages).toHaveBeenCalledWith('t-upload'));
      expect(
        vi
          .mocked(threadApi.appendMessage)
          .mock.calls.some(([, message]) => message.sender === 'user')
      ).toBe(false);
      const persisted = store
        .getState()
        .thread.messagesByThreadId['t-upload'].find(message => message.id === 'user:r-upload');
      expect(persisted?.content).toBe('look');
      expect(JSON.stringify(persisted?.attachments)).toContain('opaque-upload');
      expect(JSON.stringify(persisted)).not.toMatch(/base64|\[(ATTACHMENT|IMAGE|FILE):/i);
      expect(store.getState().queue.pendingFollowupsByThread['t-upload']).toBeUndefined();
    });

    it('keeps a follow-up pending until its own terminal event reloads the persisted row', async () => {
      const listeners = renderProvider();
      store.dispatch(
        pendingFollowupAdded({
          threadId: 't-fup',
          message: {
            id: 'f1',
            content: 'queued follow-up text',
            type: 'text',
            extraMetadata: {},
            sender: 'user',
            createdAt: '2026-01-01T00:00:00.000Z',
          },
          text: 'queued follow-up text',
          requestId: 'r-fup',
        })
      );

      await act(async () => {
        listeners.onDone?.({
          thread_id: 't-fup',
          request_id: 'r-current',
          full_response: 'assistant reply',
          total_input_tokens: 1,
          total_output_tokens: 1,
        });
      });
      expect(store.getState().queue.pendingFollowupsByThread['t-fup']).toHaveLength(1);
      expect(
        vi
          .mocked(threadApi.appendMessage)
          .mock.calls.some(([, message]) => message.sender === 'user')
      ).toBe(false);

      await act(async () => {
        listeners.onDone?.({
          thread_id: 't-fup',
          request_id: 'r-fup',
          full_response: 'queued reply',
          total_input_tokens: 1,
          total_output_tokens: 1,
        });
      });
      await waitFor(() => expect(threadApi.getThreadMessages).toHaveBeenCalledWith('t-fup'));
      expect(store.getState().queue.pendingFollowupsByThread['t-fup']).toBeUndefined();
    });

    it('retains a queued follow-up if its terminal history reload fails', async () => {
      const listeners = renderProvider();
      store.dispatch(
        pendingFollowupAdded({
          threadId: 't-fup-failed-reload',
          message: {
            id: 'f1',
            content: 'queued follow-up text',
            type: 'text',
            extraMetadata: {},
            sender: 'user',
            createdAt: '2026-01-01T00:00:00.000Z',
          },
          text: 'queued follow-up text',
          requestId: 'r-fup-failed-reload',
        })
      );
      vi.mocked(threadApi.getThreadMessages).mockRejectedValueOnce(new Error('reload failed'));

      await act(async () => {
        listeners.onDone?.({
          thread_id: 't-fup-failed-reload',
          request_id: 'r-fup-failed-reload',
          full_response: 'queued reply',
          total_input_tokens: 1,
          total_output_tokens: 1,
        });
      });

      expect(store.getState().queue.pendingFollowupsByThread['t-fup-failed-reload']).toHaveLength(
        1
      );
    });

    it('stamps the assistant answer with the producing turn requestId on chat_done', async () => {
      const listeners = renderProvider();

      await act(async () => {
        listeners.onDone?.({
          thread_id: 't-rid',
          request_id: 'req-abc',
          full_response: 'the answer',
          total_input_tokens: 1,
          total_output_tokens: 1,
        });
      });

      // The persisted answer carries requestId in extraMetadata so the timeline
      // projection can group it with its per-turn process trail (Phase 4).
      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          't-rid',
          expect.objectContaining({
            content: 'the answer',
            sender: 'agent',
            extraMetadata: expect.objectContaining({ requestId: 'req-abc' }),
          })
        )
      );
    });

    it('processes tool_call for different rounds as distinct events', () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onToolCall?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 0,
          tool_name: 'search',
          skill_id: 'notion',
          args: {},
          tool_call_id: 'call-1',
        });
        listeners.onToolCall?.({
          thread_id: 't1',
          request_id: 'r1',
          round: 1,
          tool_name: 'search',
          skill_id: 'notion',
          args: {},
          tool_call_id: 'call-2',
        });
      });

      const timeline = store.getState().chatRuntime.toolTimelineByThread['t1'] ?? [];
      expect(timeline).toHaveLength(2);
      expect(timeline.map(e => e.round)).toEqual([0, 1]);
    });
  });

  describe('proactive thread resolution', () => {
    it('reuses the selected thread when it is fresh (no messages)', async () => {
      store.dispatch(
        loadThreads.fulfilled(
          { threads: [{ id: 'visible-thread', title: 'x', messageCount: 0 }] as never, count: 1 },
          'req-id',
          undefined
        )
      );
      store.dispatch(setSelectedThread('visible-thread'));
      const listeners = renderProvider();

      await act(async () => {
        listeners.onProactiveMessage?.({
          thread_id: 'proactive:worker-1',
          request_id: 'req-p1',
          full_response: 'ping',
        });
      });

      // createNewThread must NOT be invoked when a fresh visible thread exists.
      expect(threadApi.createNewThread).not.toHaveBeenCalled();
      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          'visible-thread',
          expect.objectContaining({ content: 'ping', sender: 'agent' })
        )
      );
    });

    it('opens a new thread instead of interrupting a selected thread that has messages (#3713)', async () => {
      vi.mocked(threadApi.createNewThread).mockResolvedValue({
        id: 'fresh-thread',
        title: 'new',
      } as never);
      vi.mocked(threadApi.getThreads).mockResolvedValue({
        threads: [{ id: 'fresh-thread', title: 'new' }] as never,
        count: 1,
      });

      // The user is mid-conversation: the selected thread already holds
      // messages, so a proactive morning brief / scheduled-job update must
      // NOT be injected into it.
      store.dispatch(
        loadThreads.fulfilled(
          { threads: [{ id: 'busy-thread', title: 'chat', messageCount: 4 }] as never, count: 1 },
          'req-id',
          undefined
        )
      );
      store.dispatch(setSelectedThread('busy-thread'));
      const listeners = renderProvider();

      await act(async () => {
        listeners.onProactiveMessage?.({
          thread_id: 'proactive:morning_briefing',
          request_id: 'req-mb',
          full_response: "good morning! here's your briefing",
        });
      });

      // The active conversation must be left untouched; delivery goes to a
      // dedicated new thread.
      await waitFor(() => expect(threadApi.createNewThread).toHaveBeenCalledTimes(1));
      expect(threadApi.appendMessage).toHaveBeenCalledWith(
        'fresh-thread',
        expect.objectContaining({ content: "good morning! here's your briefing" })
      );
      expect(threadApi.appendMessage).not.toHaveBeenCalledWith('busy-thread', expect.anything());
    });

    it('treats a selected thread with unknown metadata as occupied and opens a new thread', async () => {
      vi.mocked(threadApi.createNewThread).mockResolvedValue({
        id: 'fresh-thread',
        title: 'new',
      } as never);
      vi.mocked(threadApi.getThreads).mockResolvedValue({
        threads: [{ id: 'fresh-thread', title: 'new' }] as never,
        count: 1,
      });

      // Only a rehydrated selection is present — the thread list hasn't loaded,
      // so its message metadata is unknown. We must NOT assume it is fresh
      // (it could already hold a server-side conversation). See #3713.
      store.dispatch(setSelectedThread('rehydrated-thread'));
      const listeners = renderProvider();

      await act(async () => {
        listeners.onProactiveMessage?.({
          thread_id: 'proactive:morning_briefing',
          request_id: 'req-unknown',
          full_response: 'briefing',
        });
      });

      await waitFor(() => expect(threadApi.createNewThread).toHaveBeenCalledTimes(1));
      expect(threadApi.appendMessage).toHaveBeenCalledWith(
        'fresh-thread',
        expect.objectContaining({ content: 'briefing' })
      );
      expect(threadApi.appendMessage).not.toHaveBeenCalledWith(
        'rehydrated-thread',
        expect.anything()
      );
    });

    it('delivers an origin-bound cron reply into its own thread under the core row id', async () => {
      // The user is chatting in another thread; the reminder belongs to the
      // thread that asked for it, which the core already persisted under
      // `agent:<request_id>`.
      store.dispatch(
        loadThreads.fulfilled(
          {
            threads: [
              { id: 'asking-thread', title: 'reminders', messageCount: 2 },
              { id: 'other-thread', title: 'chat', messageCount: 5 },
            ] as never,
            count: 2,
          },
          'req-id',
          undefined
        )
      );
      store.dispatch(setSelectedThread('other-thread'));
      const listeners = renderProvider();

      await act(async () => {
        listeners.onProactiveMessage?.({
          thread_id: 'asking-thread',
          request_id: 'cron:job-1:run-1',
          full_response: 'time to drink water',
          persisted_message_id: 'agent:cron:job-1:run-1',
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          'asking-thread',
          expect.objectContaining({ id: 'agent:cron:job-1:run-1', content: 'time to drink water' })
        )
      );
      expect(threadApi.createNewThread).not.toHaveBeenCalled();
      expect(store.getState().thread.selectedThreadId).toBe('other-thread');
    });

    it('generates its own id for a real-thread proactive message the core did not persist', async () => {
      store.dispatch(
        loadThreads.fulfilled(
          { threads: [{ id: 'real-thread', title: 'x', messageCount: 2 }] as never, count: 1 },
          'req-id',
          undefined
        )
      );
      store.dispatch(setSelectedThread('real-thread'));
      const listeners = renderProvider();

      await act(async () => {
        listeners.onProactiveMessage?.({
          thread_id: 'real-thread',
          request_id: 'turn-1',
          full_response: 'first',
        });
      });

      await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalled());
      const sent = vi.mocked(threadApi.appendMessage).mock.calls.at(-1)?.[1] as { id: string };
      expect(sent.id).not.toBe('agent:turn-1');
    });

    it('creates a new thread when no visible thread exists for proactive handoff', async () => {
      vi.mocked(threadApi.createNewThread).mockResolvedValue({
        id: 'created-thread',
        title: 'new',
      } as never);
      vi.mocked(threadApi.getThreads).mockResolvedValue({
        threads: [{ id: 'created-thread', title: 'new' }] as never,
        count: 1,
      });

      const listeners = renderProvider();

      await act(async () => {
        listeners.onProactiveMessage?.({
          thread_id: 'proactive:worker-2',
          request_id: 'req-p2',
          full_response: 'bootstrap msg',
        });
      });

      await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalled());
      expect(threadApi.createNewThread).toHaveBeenCalledTimes(1);
      expect(threadApi.appendMessage).toHaveBeenCalledWith(
        'created-thread',
        expect.objectContaining({ content: 'bootstrap msg' })
      );
    });

    it('deduplicates identical proactive messages from the same sender', async () => {
      store.dispatch(
        loadThreads.fulfilled(
          { threads: [{ id: 'visible-thread', title: 'x' }] as never, count: 1 },
          'req-id',
          undefined
        )
      );
      store.dispatch(setSelectedThread('visible-thread'));
      const listeners = renderProvider();

      const event: chatService.ProactiveMessageEvent = {
        thread_id: 'proactive:worker-3',
        request_id: 'req-dup',
        full_response: 'ping',
      };

      await act(async () => {
        listeners.onProactiveMessage?.(event);
        listeners.onProactiveMessage?.(event);
      });

      await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(1));
    });

    it('pins the realtime voice surface to one thread across turns', async () => {
      // The realtime voice session delivers every deferred turn as a
      // `proactive:voice` message. They all belong to ONE ongoing conversation,
      // so they must land in a single thread — not spawn a fresh "Chat …" thread
      // per turn. Turn 1 reuses the fresh selected thread and pins it; the pin
      // then keeps turns 2 and 3 in that thread even though it now holds
      // messages (which the fresh-or-create rule would otherwise treat as
      // occupied, creating a new thread each time).
      store.dispatch(
        loadThreads.fulfilled(
          { threads: [{ id: 'voice-thread', title: 'voice', messageCount: 0 }] as never, count: 1 },
          'req-id',
          undefined
        )
      );
      store.dispatch(setSelectedThread('voice-thread'));
      const listeners = renderProvider();

      await act(async () => {
        listeners.onProactiveMessage?.({
          thread_id: 'proactive:voice',
          request_id: 'voice-1',
          full_response: 'here is your inbox summary',
        });
        listeners.onProactiveMessage?.({
          thread_id: 'proactive:voice',
          request_id: 'voice-2',
          full_response: 'here is your calendar',
        });
        listeners.onProactiveMessage?.({
          thread_id: 'proactive:voice',
          request_id: 'voice-3',
          full_response: 'and the weather',
        });
      });

      await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(3));
      // No new thread was ever created, and every turn landed in the one thread.
      expect(threadApi.createNewThread).not.toHaveBeenCalled();
      for (const call of vi.mocked(threadApi.appendMessage).mock.calls) {
        expect(call[0]).toBe('voice-thread');
      }
    });

    it('pins the voice surface through the create path when no fresh thread exists', async () => {
      vi.mocked(threadApi.createNewThread).mockResolvedValue({
        id: 'voice-thread',
        title: 'new',
      } as never);
      vi.mocked(threadApi.getThreads).mockResolvedValue({
        threads: [{ id: 'voice-thread', title: 'new' }] as never,
        count: 1,
      });

      // The user is mid-conversation, so turn 1 opens a dedicated thread rather
      // than interrupting the busy one (#3713) — then PINS it, so turn 2 reuses
      // that same thread instead of creating another.
      store.dispatch(
        loadThreads.fulfilled(
          { threads: [{ id: 'busy-thread', title: 'chat', messageCount: 4 }] as never, count: 1 },
          'req-id',
          undefined
        )
      );
      store.dispatch(setSelectedThread('busy-thread'));
      const listeners = renderProvider();

      await act(async () => {
        listeners.onProactiveMessage?.({
          thread_id: 'proactive:voice',
          request_id: 'voice-1',
          full_response: 'first voice answer',
        });
        listeners.onProactiveMessage?.({
          thread_id: 'proactive:voice',
          request_id: 'voice-2',
          full_response: 'second voice answer',
        });
      });

      await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(2));
      // Exactly ONE thread created for the whole voice session; the busy thread
      // is never touched.
      expect(threadApi.createNewThread).toHaveBeenCalledTimes(1);
      for (const call of vi.mocked(threadApi.appendMessage).mock.calls) {
        expect(call[0]).toBe('voice-thread');
      }
      expect(threadApi.appendMessage).not.toHaveBeenCalledWith('busy-thread', expect.anything());
    });

    it('re-resolves the voice surface when its pinned thread was deleted', async () => {
      store.dispatch(
        loadThreads.fulfilled(
          { threads: [{ id: 'voice-thread', title: 'voice', messageCount: 0 }] as never, count: 1 },
          'req-id',
          undefined
        )
      );
      store.dispatch(setSelectedThread('voice-thread'));
      const listeners = renderProvider();

      // Turn 1 pins the fresh selected thread.
      await act(async () => {
        listeners.onProactiveMessage?.({
          thread_id: 'proactive:voice',
          request_id: 'voice-1',
          full_response: 'first',
        });
      });
      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith('voice-thread', expect.anything())
      );

      // The pinned thread is deleted. A later voice turn must NOT deliver into
      // the dead thread — it drops the stale pin and opens a new one.
      vi.mocked(threadApi.createNewThread).mockResolvedValue({
        id: 'voice-thread-2',
        title: 'new',
      } as never);
      vi.mocked(threadApi.getThreads).mockResolvedValue({
        threads: [{ id: 'voice-thread-2', title: 'new' }] as never,
        count: 1,
      });
      store.dispatch(clearAllThreads());

      await act(async () => {
        listeners.onProactiveMessage?.({
          thread_id: 'proactive:voice',
          request_id: 'voice-2',
          full_response: 'second',
        });
      });

      await waitFor(() => expect(threadApi.createNewThread).toHaveBeenCalledTimes(1));
      expect(threadApi.appendMessage).toHaveBeenCalledWith('voice-thread-2', expect.anything());
    });
  });

  describe('socket reconnect recovery (#6034)', () => {
    it('rejoins the rooms of interrupted threads and re-reads them once the socket returns', async () => {
      vi.mocked(threadApi.getThreadMessages).mockResolvedValue({
        messages: [],
      } as unknown as Awaited<ReturnType<typeof threadApi.getThreadMessages>>);

      renderProvider();

      // A turn is in flight on a thread the user is not looking at.
      act(() => {
        store.dispatch(setActiveThread('t-away'));
      });
      vi.mocked(threadApi.getThreadMessages).mockClear();
      vi.mocked(socketService.subscribeThread).mockClear();

      // The socket drops. The provider clears every active marker so the
      // composer unlocks, which is also what erases the list the reconnect
      // handler would have re-subscribed from.
      act(() => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));
      });
      expect(store.getState().thread.activeThreadIds).toEqual({});

      act(() => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));
      });

      // Rejoin the room, so a turn still running can still reach us under the
      // new client_id, and re-read the thread, so a turn that finished during
      // the gap is not invisible until the thread is reselected.
      await waitFor(() => expect(socketService.subscribeThread).toHaveBeenCalledWith('t-away'));
      await waitFor(() => expect(threadApi.getThreadMessages).toHaveBeenCalledWith('t-away'));
    });

    it('retries a thread whose room join never emitted, on the next connection', async () => {
      vi.mocked(threadApi.getThreadMessages).mockResolvedValue({
        messages: [],
      } as unknown as Awaited<ReturnType<typeof threadApi.getThreadMessages>>);
      // The socket dropped again between `connected` and this effect, so the
      // emit never went out. Forgetting the thread here would strand it until
      // the user reselected it.
      vi.mocked(socketService.subscribeThread).mockResolvedValueOnce(false);

      renderProvider();
      act(() => {
        store.dispatch(setActiveThread('t-flaky'));
      });
      act(() => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));
      });
      act(() => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));
      });
      await waitFor(() => expect(socketService.subscribeThread).toHaveBeenCalledWith('t-flaky'));

      vi.mocked(socketService.subscribeThread).mockClear();
      vi.mocked(socketService.subscribeThread).mockResolvedValue(true);

      // Second reconnect: the thread is still pending, so it is retried.
      act(() => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));
      });
      act(() => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));
      });
      await waitFor(() => expect(socketService.subscribeThread).toHaveBeenCalledWith('t-flaky'));
    });

    it('rehydrates the in-flight turn snapshot for an interrupted thread', async () => {
      // A socket drop takes ~3s to heal (socket.io reconnectionDelay 2000 +
      // handshake). `thread:<id>` has NO member for that whole window, and
      // `emit_web_channel_event` is fire-and-forget — every progress frame and
      // even the terminal `chat_done` emitted in the gap is dropped for good.
      //
      // Re-reading persisted messages is not enough: it recovers the final
      // text but not the turn's live state, so a turn STILL running after the
      // reconnect repaints nothing and the thread sits silent until the user
      // reselects it or restarts the app. The core already persists that state
      // and `fetchAndHydrateTurnState` already reads it — the thread-switch
      // path (`Conversations.tsx`) dispatches it alongside `loadThreadMessages`.
      // The reconnect path must do the same.
      vi.mocked(threadApi.getThreadMessages).mockResolvedValue({
        messages: [],
      } as unknown as Awaited<ReturnType<typeof threadApi.getThreadMessages>>);

      renderProvider();
      act(() => {
        store.dispatch(setActiveThread('t-inflight'));
      });
      vi.mocked(threadApi.getTurnState).mockClear();

      act(() => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));
      });
      act(() => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));
      });

      await waitFor(() => expect(socketService.subscribeThread).toHaveBeenCalledWith('t-inflight'));
      await waitFor(() => expect(threadApi.getTurnState).toHaveBeenCalledWith('t-inflight'));
    });

    it('does nothing on a connect with no interrupted threads', async () => {
      renderProvider();
      vi.mocked(socketService.subscribeThread).mockClear();

      act(() => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));
      });
      act(() => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));
      });

      // A blip with nothing in flight must not re-read every thread the user
      // has ever opened.
      expect(socketService.subscribeThread).not.toHaveBeenCalled();
    });
  });

  describe('mid-turn streaming invariants', () => {
    it('reconciles missing segment events from chat_done.full_response', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onSegment?.({
          thread_id: 't-segmented',
          request_id: 'r-segmented',
          full_response: 'Part one.',
          segment_index: 0,
          segment_total: 2,
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          't-segmented',
          expect.objectContaining({ content: 'Part one.', sender: 'agent' })
        )
      );

      act(() => {
        listeners.onDone?.({
          thread_id: 't-segmented',
          request_id: 'r-segmented',
          full_response: 'Part one.\n\nPart two.',
          total_input_tokens: 10,
          total_output_tokens: 20,
          segment_total: 2,
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          't-segmented',
          expect.objectContaining({ content: 'Part one.\n\nPart two.', sender: 'agent' })
        )
      );
      expect(threadApi.appendMessage).toHaveBeenCalledTimes(2);
    });

    it('does not duplicate chat_done.full_response when all segments arrived', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onSegment?.({
          thread_id: 't-complete',
          request_id: 'r-complete',
          full_response: 'Part one.\n\n',
          segment_index: 0,
          segment_total: 2,
        });
        listeners.onSegment?.({
          thread_id: 't-complete',
          request_id: 'r-complete',
          full_response: 'Part two.',
          segment_index: 1,
          segment_total: 2,
        });
      });

      await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(2));

      act(() => {
        listeners.onDone?.({
          thread_id: 't-complete',
          request_id: 'r-complete',
          full_response: 'Part one.\n\nPart two.',
          total_input_tokens: 10,
          total_output_tokens: 20,
          segment_total: 2,
        });
      });

      await waitFor(() => expect(mockRefetchSnapshot).toHaveBeenCalledTimes(1));
      expect(threadApi.appendMessage).toHaveBeenCalledTimes(2);
    });

    it('does not reconcile when all segments arrived even if full_response differs (trim/joiner)', async () => {
      // Regression: the server's segmenter trims each segment and joins with
      // "\n\n", while chat_done.full_response is the raw LLM text. A strict
      // byte-equality check used to fire reconciliation on every multi-segment
      // turn — once we have all expected segment_index values, delivery is
      // complete regardless of full_response content.
      const listeners = renderProvider();

      act(() => {
        listeners.onSegment?.({
          thread_id: 't-trim',
          request_id: 'r-trim',
          full_response: 'Hello.',
          segment_index: 0,
          segment_total: 2,
        });
        listeners.onSegment?.({
          thread_id: 't-trim',
          request_id: 'r-trim',
          full_response: 'World.',
          segment_index: 1,
          segment_total: 2,
        });
      });

      await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(2));

      act(() => {
        listeners.onDone?.({
          thread_id: 't-trim',
          request_id: 'r-trim',
          // Raw LLM output: leading/trailing whitespace + paragraph break.
          // segments.join('') === 'Hello.World.' !== full_response, but
          // delivery is still complete.
          full_response: '\nHello.\n\nWorld.\n',
          total_input_tokens: 10,
          total_output_tokens: 20,
          segment_total: 2,
        });
      });

      await waitFor(() => expect(mockRefetchSnapshot).toHaveBeenCalledTimes(1));
      expect(threadApi.appendMessage).toHaveBeenCalledTimes(2);
    });

    it('reconciles when a segment is missing', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onSegment?.({
          thread_id: 't-missing',
          request_id: 'r-missing',
          full_response: 'Part one.',
          segment_index: 0,
          segment_total: 2,
        });
        // segment_index 1 never arrives.
      });

      await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(1));

      act(() => {
        listeners.onDone?.({
          thread_id: 't-missing',
          request_id: 'r-missing',
          full_response: 'Part one.\n\nPart two.',
          total_input_tokens: 10,
          total_output_tokens: 20,
          segment_total: 2,
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          't-missing',
          expect.objectContaining({ content: 'Part one.\n\nPart two.', sender: 'agent' })
        )
      );
      expect(threadApi.appendMessage).toHaveBeenCalledTimes(2);
    });

    it('expires stale segment delivery state before chat_done reconciliation', async () => {
      const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(1_000);
      const listeners = renderProvider();

      try {
        act(() => {
          listeners.onSegment?.({
            thread_id: 't-stale',
            request_id: 'r-stale',
            full_response: 'Stale segment.',
            segment_index: 0,
            segment_total: 1,
          });
        });

        await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(1));
        nowSpy.mockReturnValue(1_000 + 5 * 60 * 1000 + 1);

        act(() => {
          listeners.onDone?.({
            thread_id: 't-stale',
            request_id: 'r-stale',
            full_response: 'Stale segment.',
            total_input_tokens: 10,
            total_output_tokens: 20,
            segment_total: 1,
          });
        });

        await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(2));
      } finally {
        nowSpy.mockRestore();
      }
    });

    it('accumulates text_delta chunks within the same request_id', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onTextDelta?.({ thread_id: 't-mid', request_id: 'r1', round: 0, delta: 'Hel' });
        listeners.onTextDelta?.({ thread_id: 't-mid', request_id: 'r1', round: 0, delta: 'lo!' });
      });

      await waitFor(() =>
        expect(store.getState().chatRuntime.streamingAssistantByThread['t-mid']).toBeDefined()
      );
      const streaming = store.getState().chatRuntime.streamingAssistantByThread['t-mid'];
      expect(streaming?.requestId).toBe('r1');
      expect(streaming?.content).toBe('Hello!');
    });

    it('replaces streaming state when request_id changes mid-turn', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onTextDelta?.({ thread_id: 't-mid', request_id: 'r1', round: 0, delta: 'aaa' });
        listeners.onTextDelta?.({ thread_id: 't-mid', request_id: 'r2', round: 0, delta: 'bbb' });
      });

      await waitFor(() =>
        expect(store.getState().chatRuntime.streamingAssistantByThread['t-mid']?.requestId).toBe(
          'r2'
        )
      );
      const streaming = store.getState().chatRuntime.streamingAssistantByThread['t-mid'];
      expect(streaming?.requestId).toBe('r2');
      expect(streaming?.content).toBe('bbb');
    });

    // Narration is NOT promoted to a chat message. It used to be persisted via
    // `addInferenceResponse({ isInterim: true })`, which gave it a lifetime no
    // other progress signal has — thinking is wiped at `chat_done` and tool rows
    // collapse, but narration bubbles stayed in the thread forever, between the
    // question and the answer that superseded them. It reaches the UI through
    // the processing transcript instead (written by `streamDeltaReceived`, and
    // persisted core-side as `TranscriptItem::Narration`), which the inline rail
    // and the Agent Process Source panel both render.
    it('records interim narration in the transcript, not as a message, and clears the preview', async () => {
      const listeners = renderProvider();

      // Round-0 narration streams into the live preview…
      act(() => {
        listeners.onTextDelta?.({
          thread_id: 't-interim',
          request_id: 'r1',
          round: 0,
          delta: 'Let me check your calendar first.',
        });
      });
      await waitFor(() =>
        expect(store.getState().chatRuntime.streamingAssistantByThread['t-interim']?.content).toBe(
          'Let me check your calendar first.'
        )
      );
      // …and is already captured as a narration transcript item by the delta
      // reducer — this is what the rail renders.
      expect(store.getState().chatRuntime.processingByThread['t-interim']).toEqual([
        expect.objectContaining({ kind: 'narration', text: 'Let me check your calendar first.' }),
      ]);

      // …then a tool call closes the round → interim flush.
      act(() => {
        listeners.onInterim?.({
          thread_id: 't-interim',
          request_id: 'r1',
          round: 0,
          full_response: 'Let me check your calendar first.',
        });
      });

      // No message is appended for narration.
      expect(threadApi.appendMessage).not.toHaveBeenCalled();
      // The preview is still cleared, so the rail and the preview don't both
      // show the same text for the duration of the tool call.
      expect(store.getState().chatRuntime.streamingAssistantByThread['t-interim']?.content).toBe(
        ''
      );
    });

    // The round dedup key outlives the message-promotion it was written for:
    // it now guards the streaming-preview reset. A replayed frame must not wipe
    // text the agent streamed AFTER the original flush.
    it('dedupes a re-delivered interim event by round', () => {
      const listeners = renderProvider();
      const streamingContent = () =>
        store.getState().chatRuntime.streamingAssistantByThread['t-interim-dup']?.content;

      act(() => {
        listeners.onTextDelta?.({
          thread_id: 't-interim-dup',
          request_id: 'r1',
          round: 1,
          delta: 'Working on it now — pulling the data.',
        });
        listeners.onInterim?.({
          thread_id: 't-interim-dup',
          request_id: 'r1',
          round: 1,
          full_response: 'Working on it now — pulling the data.',
        });
      });
      // First delivery flushes the round and clears the preview.
      expect(streamingContent()).toBe('');

      act(() => {
        // The agent streams the next chunk…
        listeners.onTextDelta?.({
          thread_id: 't-interim-dup',
          request_id: 'r1',
          round: 1,
          delta: 'Here is what I found.',
        });
        // …and a reconnect/replay re-delivers the SAME round.
        listeners.onInterim?.({
          thread_id: 't-interim-dup',
          request_id: 'r1',
          round: 1,
          full_response: 'Working on it now — pulling the data.',
        });
      });

      // Deduped: the replay is ignored, so the newer text survives. Without the
      // guard the preview would have been cleared a second time.
      expect(streamingContent()).toBe('Here is what I found.');
      // And narration still never becomes a message, on either delivery.
      expect(threadApi.appendMessage).not.toHaveBeenCalled();
    });

    it('sets inference status to thinking on inference_start and clears it on chat_done', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onInferenceStart?.({ thread_id: 't-inv', request_id: 'r1' });
      });
      expect(store.getState().chatRuntime.inferenceStatusByThread['t-inv']?.phase).toBe('thinking');

      act(() => {
        listeners.onDone?.({
          thread_id: 't-inv',
          request_id: 'r1',
          full_response: '',
          total_input_tokens: 0,
          total_output_tokens: 0,
        });
      });
      // Cleared by `turnSettled`, once the reply is persisted — not before, so
      // the status line does not vanish ahead of the reply that replaces it.
      await waitFor(() =>
        expect(store.getState().chatRuntime.inferenceStatusByThread['t-inv']).toBeUndefined()
      );
      expect(store.getState().chatRuntime.streamingAssistantByThread['t-inv']).toBeUndefined();
    });

    it('cancels an unresolved tool row when the completed snapshot cannot be loaded', async () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onToolCall?.({
          thread_id: 't-inv',
          request_id: 'r1',
          round: 0,
          tool_name: 'search',
          skill_id: 'notion',
          args: {},
          tool_call_id: 'call-1',
        });
      });
      expect(store.getState().chatRuntime.toolTimelineByThread['t-inv']?.[0]?.status).toBe(
        'running'
      );

      act(() => {
        listeners.onDone?.({
          thread_id: 't-inv',
          request_id: 'r1',
          full_response: '',
          total_input_tokens: 0,
          total_output_tokens: 0,
        });
      });

      // The core drains every queued progress event before `chat_done`, so a
      // row with no result by now has none. If the completed snapshot cannot
      // be loaded, it has no remaining event driver and must not pulse as
      // `running`; this still does not invent a successful tool outcome.
      await waitFor(() => {
        const timeline = store.getState().chatRuntime.toolTimelineByThread['t-inv'] ?? [];
        expect(timeline).toHaveLength(1);
        expect(timeline[0]?.status).toBe('cancelled');
      });
    });

    it('keeps two id-less calls of one tool in a round apart by seq, still deduping a redelivery', () => {
      const listeners = renderProvider();
      const call = (seq: number) => ({
        thread_id: 't-seq',
        request_id: 'r1',
        seq,
        round: 1,
        tool_name: 'shell',
        skill_id: 'web_channel',
        args: {},
      });

      act(() => {
        listeners.onToolCall?.(call(3));
        listeners.onToolCall?.(call(5));
        // Socket redelivery of the first frame.
        listeners.onToolCall?.(call(3));
      });

      expect(store.getState().chatRuntime.toolTimelineByThread['t-seq']).toHaveLength(2);
    });

    it('drops a redelivered text delta by seq instead of appending it twice', async () => {
      const listeners = renderProvider();
      const delta = (seq: number, text: string) => ({
        thread_id: 't-delta',
        request_id: 'r1',
        seq,
        round: 1,
        delta: text,
      });

      act(() => {
        listeners.onTextDelta?.(delta(1, 'Hel'));
        listeners.onTextDelta?.(delta(2, 'lo'));
        listeners.onTextDelta?.(delta(1, 'Hel'));
        listeners.onThinkingDelta?.(delta(2, 'lo'));
        listeners.onTextDelta?.(delta(3, '!'));
      });

      // Deltas are coalesced per frame (`chatDeltaCoalescer`); wait for the flush.
      await waitFor(() =>
        expect(store.getState().chatRuntime.streamingAssistantByThread['t-delta']?.content).toBe(
          'Hello!'
        )
      );
    });

    it('transitions running tool-timeline rows to error on chat_error', () => {
      const listeners = renderProvider();

      act(() => {
        listeners.onToolCall?.({
          thread_id: 't-err',
          request_id: 'r1',
          round: 0,
          tool_name: 'search',
          skill_id: 'notion',
          args: {},
          tool_call_id: 'call-err',
        });
      });

      act(() => {
        listeners.onError?.({
          thread_id: 't-err',
          request_id: 'r1',
          message: 'timeout',
          error_type: 'timeout',
        });
      });

      const timeline = store.getState().chatRuntime.toolTimelineByThread['t-err'] ?? [];
      expect(timeline[0]?.status).toBe('error');
      expect(store.getState().chatRuntime.inferenceStatusByThread['t-err']).toBeUndefined();
    });

    it('keeps a queued follow-up live when the previous turn error arrives late', async () => {
      const listeners = renderProvider();
      const threadId = 't-late-error';
      act(() => {
        store.dispatch(beginInferenceTurn({ threadId }));
        store.dispatch(setActiveThread(threadId));
        listeners.onInferenceStart?.({ thread_id: threadId, request_id: 'new' });
        store.dispatch(
          setStreamingAssistantForThread({
            threadId,
            streaming: { content: 'new answer', thinking: '', requestId: 'new' },
          })
        );
        listeners.onError?.({
          thread_id: threadId,
          request_id: 'old',
          message: 'Earlier turn failed',
          error_type: 'inference',
        });
      });

      const state = store.getState();
      expect(state.chatRuntime.liveRequestIdByThread[threadId]).toBe('new');
      expect(state.chatRuntime.inferenceTurnLifecycleByThread[threadId]).toBe('streaming');
      expect(state.chatRuntime.streamingAssistantByThread[threadId]?.content).toBe('new answer');
      expect(state.thread.activeThreadIds[threadId]).toBe(true);
      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          threadId,
          expect.objectContaining({ content: 'Earlier turn failed' })
        )
      );
    });

    it('forwards the server-provided inference error message verbatim', async () => {
      const listeners = renderProvider();
      // Transport-level failures yield no provider `error.message` body, so
      // `with_provider_detail()` in web_errors.rs returns just the friendly
      // generic message with no raw URL appended — the FE forwards it as-is
      // (backend owns sanitization; see web_errors_tests.rs).
      const serverMessage =
        'Something went wrong. Please try again.\nThis error has been reported. You can also report it on Discord.\n<openhuman-link path="community/discord-report">Report on Discord</openhuman-link>';

      act(() => {
        listeners.onError?.({
          thread_id: 't-err-sanitized',
          request_id: 'r1',
          message: serverMessage,
          error_type: 'inference',
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          't-err-sanitized',
          expect.objectContaining({ sender: 'agent', content: serverMessage })
        )
      );
    });

    it('does not append a duplicate error bubble when the previous message already matches', async () => {
      const listeners = renderProvider();
      const repeated = 'Your AI provider is temporarily unavailable. Please try again later.';

      act(() => {
        listeners.onError?.({
          thread_id: 't-err-dedupe',
          request_id: 'r1',
          message: repeated,
          error_type: 'inference',
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          't-err-dedupe',
          expect.objectContaining({ content: repeated })
        )
      );

      act(() => {
        listeners.onError?.({
          thread_id: 't-err-dedupe',
          request_id: 'r2',
          message: repeated,
          error_type: 'inference',
        });
      });

      await waitFor(() => {
        const matchingCalls = vi
          .mocked(threadApi.appendMessage)
          .mock.calls.filter(
            call =>
              call[0] === 't-err-dedupe' &&
              typeof call[1]?.content === 'string' &&
              call[1].content.includes(repeated)
          );
        expect(matchingCalls).toHaveLength(1);
      });
    });
  });

  // Live subagent activity (#1122) — the parent thread surfaces a
  // subagent's child iterations and tool calls as they happen, then
  // settles to the final-run statistics on completion. The asserts here
  // are the contract the ToolTimelineBlock UI relies on; if a refactor
  // moves the subagent state somewhere else this test is the canary.
  describe('live subagent activity (#1122)', () => {
    it('builds a live subagent block from spawned → iteration → tool call → done', () => {
      const listeners = renderProvider();
      const threadId = 'tsa';

      act(() => {
        listeners.onSubagentSpawned?.({
          thread_id: threadId,
          request_id: 'r1',
          tool_name: 'researcher',
          skill_id: 'sub-1',
          message: 'spawned',
          round: 1,
          subagent: { mode: 'typed', dedicated_thread: false, prompt_chars: 42 },
        });
      });

      let timeline = store.getState().chatRuntime.toolTimelineByThread[threadId] ?? [];
      expect(timeline).toHaveLength(1);
      expect(timeline[0]?.subagent).toMatchObject({
        agentId: 'researcher',
        taskId: 'sub-1',
        mode: 'typed',
        dedicatedThread: false,
        toolCalls: [],
      });

      act(() => {
        listeners.onSubagentIterationStart?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 1,
          tool_name: 'researcher',
          skill_id: 'sub-1',
          message: 'iter',
          subagent: {
            agent_id: 'researcher',
            task_id: 'sub-1',
            child_iteration: 1,
            child_max_iterations: 5,
          },
        });
        listeners.onSubagentToolCall?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 1,
          tool_name: 'web_search',
          skill_id: 'sub-1',
          tool_call_id: 'cc-1',
          subagent: { agent_id: 'researcher', task_id: 'sub-1', child_iteration: 1 },
        });
        // Duplicate child tool_call must not double-append.
        listeners.onSubagentToolCall?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 1,
          tool_name: 'web_search',
          skill_id: 'sub-1',
          tool_call_id: 'cc-1',
          subagent: { agent_id: 'researcher', task_id: 'sub-1', child_iteration: 1 },
        });
      });

      timeline = store.getState().chatRuntime.toolTimelineByThread[threadId] ?? [];
      expect(timeline[0]?.subagent?.childIteration).toBe(1);
      expect(timeline[0]?.subagent?.childMaxIterations).toBe(5);
      expect(timeline[0]?.subagent?.toolCalls).toEqual([
        { callId: 'cc-1', toolName: 'web_search', status: 'running', iteration: 1 },
      ]);

      act(() => {
        listeners.onSubagentToolResult?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 1,
          tool_name: 'web_search',
          skill_id: 'sub-1',
          tool_call_id: 'cc-1',
          success: true,
          subagent: {
            agent_id: 'researcher',
            task_id: 'sub-1',
            child_iteration: 1,
            elapsed_ms: 312,
            output_chars: 1280,
          },
        });
        listeners.onSubagentDone?.({
          thread_id: threadId,
          request_id: 'r1',
          tool_name: 'researcher',
          skill_id: 'sub-1',
          message: 'done',
          success: true,
          round: 1,
          subagent: { iterations: 2, elapsed_ms: 4200, output_chars: 980 },
        });
      });

      timeline = store.getState().chatRuntime.toolTimelineByThread[threadId] ?? [];
      expect(timeline[0]?.status).toBe('success');
      expect(timeline[0]?.subagent?.toolCalls[0]).toMatchObject({
        status: 'success',
        elapsedMs: 312,
        outputChars: 1280,
      });
      expect(timeline[0]?.subagent).toMatchObject({
        iterations: 2,
        elapsedMs: 4200,
        outputChars: 980,
      });
    });

    it('stores the structured failure on a failed subagent tool call (#4459)', () => {
      const listeners = renderProvider();
      const threadId = 'tsa-fail';

      act(() => {
        listeners.onSubagentSpawned?.({
          thread_id: threadId,
          request_id: 'r1',
          tool_name: 'researcher',
          skill_id: 'sub-1',
          message: 'spawned',
          round: 1,
          subagent: { mode: 'typed', dedicated_thread: false, prompt_chars: 42 },
        });
        listeners.onSubagentToolCall?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 1,
          tool_name: 'shell',
          skill_id: 'sub-1',
          tool_call_id: 'cc-1',
          subagent: { agent_id: 'researcher', task_id: 'sub-1', child_iteration: 1 },
        });
      });

      act(() => {
        listeners.onSubagentToolResult?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 1,
          tool_name: 'shell',
          skill_id: 'sub-1',
          tool_call_id: 'cc-1',
          success: false,
          failure: {
            class: 'denied',
            category: 'user_declined',
            cause_plain: 'You declined this action.',
            next_action: 'Ask again if you change your mind.',
            recoverable: false,
          },
          subagent: { agent_id: 'researcher', task_id: 'sub-1', child_iteration: 1, elapsed_ms: 5 },
        });
      });

      const timeline = store.getState().chatRuntime.toolTimelineByThread[threadId] ?? [];
      const call = timeline[0]?.subagent?.toolCalls[0];
      expect(call).toMatchObject({ callId: 'cc-1', status: 'error' });
      // The structured why/next survives live rather than being dropped until a
      // snapshot reload (#4459).
      expect(call?.failure).toMatchObject({
        class: 'denied',
        category: 'user_declined',
        recoverable: false,
        causePlain: 'You declined this action.',
        nextAction: 'Ask again if you change your mind.',
      });
      // The rendered live path uses `subagent.transcript`, so the failure must
      // also land on the transcript tool item, not just the fallback list.
      const transcriptTool = timeline[0]?.subagent?.transcript?.find(
        i => i.kind === 'tool' && i.callId === 'cc-1'
      );
      expect(transcriptTool).toMatchObject({
        status: 'error',
        failure: { class: 'denied', category: 'user_declined' },
      });
    });

    it('ignores subagent_tool_call events that arrive before subagent_spawned', () => {
      const listeners = renderProvider();
      const threadId = 'tsa-orphan';

      act(() => {
        listeners.onSubagentToolCall?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 1,
          tool_name: 'web_search',
          skill_id: 'sub-missing',
          tool_call_id: 'cc-1',
          subagent: { agent_id: 'researcher', task_id: 'sub-missing', child_iteration: 1 },
        });
      });

      // No row was created — the orphan child tool call is dropped rather
      // than synthesising a partial subagent row from incomplete data.
      const timeline = store.getState().chatRuntime.toolTimelineByThread[threadId] ?? [];
      expect(timeline).toHaveLength(0);
    });

    // Regression: the Flows canvas copilot delegates to the `workflow_builder`
    // subagent, which can emit 50+ progress events. The progress channel is
    // bounded and `try_send`s, so under that volume the `subagent_spawned`/
    // `subagent_tool_call` events that create the timeline row can be dropped
    // before `subagent_tool_result` arrives. Proposal extraction must not be
    // gated on that timeline row existing, or the Accept/Reject
    // `WorkflowProposalCard` silently never renders.
    it('surfaces a workflow proposal from a delegated subagent even with no matching timeline row', () => {
      const listeners = renderProvider();
      const threadId = 'tsa-no-row';

      act(() => {
        listeners.onSubagentToolResult?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 1,
          tool_name: 'revise_workflow',
          skill_id: 'sub-missing',
          tool_call_id: 'cc-1',
          success: true,
          output: JSON.stringify({
            type: 'workflow_proposal',
            name: 'Notify on new signup',
            graph: { nodes: [], edges: [] },
            require_approval: true,
            summary: { trigger: 'signup.created', steps: [] },
          }),
          // No `subagent` block and no prior `onSubagentSpawned`/`onSubagentToolCall`
          // — so no timeline row exists for this call, mirroring the drop.
        });
      });

      // No timeline row was ever created for this call.
      const timeline = store.getState().chatRuntime.toolTimelineByThread[threadId] ?? [];
      expect(timeline).toHaveLength(0);

      // The proposal still reaches the parent thread so the Accept/Reject
      // card renders.
      const proposal = store.getState().chatRuntime.pendingWorkflowProposalsByThread[threadId];
      expect(proposal).toMatchObject({
        name: 'Notify on new signup',
        requireApproval: true,
        summary: { trigger: 'signup.created' },
      });
    });

    // Regression (#4876 fallout): `edit_workflow` is the prompt-preferred way
    // to iterate on an existing draft, and returns the identical
    // `{ type: "workflow_proposal", ... }` payload as `propose_workflow` /
    // `revise_workflow`. Proposal recognition is content-based (on the
    // payload's `type`), not gated on a fixed tool-name allowlist, so this
    // must surface a proposal exactly like the other two tools do — a
    // name-based allowlist previously dropped it silently.
    it('surfaces a workflow proposal from the main-agent edit_workflow tool', () => {
      const listeners = renderProvider();
      const threadId = 't-edit-workflow';

      act(() => {
        listeners.onToolCall?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 0,
          tool_name: 'edit_workflow',
          skill_id: 'flows',
          args: {},
          tool_call_id: 'call-edit-1',
        });
        listeners.onToolResult?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 0,
          tool_name: 'edit_workflow',
          skill_id: 'flows',
          success: true,
          output: JSON.stringify({
            type: 'workflow_proposal',
            name: 'Digest patch',
            graph: { nodes: [], edges: [] },
            require_approval: true,
            draft_id: 'draft-42',
            summary: { trigger: 'manual', steps: [] },
          }),
          tool_call_id: 'call-edit-1',
        });
      });

      const proposal = store.getState().chatRuntime.pendingWorkflowProposalsByThread[threadId];
      expect(proposal).toMatchObject({ name: 'Digest patch', requireApproval: true });
    });

    // Any future tool that returns `{ type: "workflow_proposal" }` must be
    // recognised too — the gate is the payload shape, not a tool-name list.
    it('surfaces a workflow proposal from an unrecognised future tool name', () => {
      const listeners = renderProvider();
      const threadId = 't-future-tool';

      act(() => {
        listeners.onToolCall?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 0,
          tool_name: 'some_future_builder_tool',
          skill_id: 'flows',
          args: {},
          tool_call_id: 'call-future-1',
        });
        listeners.onToolResult?.({
          thread_id: threadId,
          request_id: 'r1',
          round: 0,
          tool_name: 'some_future_builder_tool',
          skill_id: 'flows',
          success: true,
          output: JSON.stringify({
            type: 'workflow_proposal',
            name: 'Future proposal',
            graph: { nodes: [], edges: [] },
            require_approval: true,
            summary: { trigger: 'manual', steps: [] },
          }),
          tool_call_id: 'call-future-1',
        });
      });

      const proposal = store.getState().chatRuntime.pendingWorkflowProposalsByThread[threadId];
      expect(proposal).toMatchObject({ name: 'Future proposal' });
    });
  });

  // Regression: on Windows users report being "locked out" of the composer
  // after sleep/wake or a network flap — the in-flight turn's `chat_done`
  // never arrives on the new socket, so `activeThreadId` and the
  // `started`/`streaming` lifecycle stay set and the textarea remains
  // disabled. The reconcile effect releases them on disconnect so the
  // composer becomes typeable again immediately.
  describe('socket-disconnect reconciliation (#WindowsLockout)', () => {
    it('clears activeThreadId and in-flight lifecycle when the socket drops mid-turn', async () => {
      const threadId = 't-disconnect';
      renderProvider();

      await act(async () => {
        const { setActiveThread } = await import('../../store/threadSlice');
        const { beginInferenceTurn, setInferenceStatusForThread } =
          await import('../../store/chatRuntimeSlice');
        store.dispatch(setActiveThread(threadId));
        store.dispatch(beginInferenceTurn({ threadId }));
        store.dispatch(
          setInferenceStatusForThread({
            threadId,
            status: { phase: 'thinking', iteration: 1, maxIterations: 10 },
          })
        );
      });

      expect(store.getState().thread.activeThreadIds[threadId]).toBe(true);
      expect(store.getState().chatRuntime.inferenceTurnLifecycleByThread[threadId]).toBe('started');

      await act(async () => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));
      });

      await waitFor(() => {
        expect(store.getState().thread.activeThreadIds[threadId]).toBeUndefined();
        expect(
          store.getState().chatRuntime.inferenceTurnLifecycleByThread[threadId]
        ).toBeUndefined();
        expect(store.getState().chatRuntime.inferenceStatusByThread[threadId]).toBeUndefined();
      });
    });

    it('preserves streamingAssistant text so the partial reply stays visible after disconnect', async () => {
      const threadId = 't-disconnect-streaming';
      renderProvider();

      await act(async () => {
        const { setActiveThread } = await import('../../store/threadSlice');
        const { beginInferenceTurn, setStreamingAssistantForThread } =
          await import('../../store/chatRuntimeSlice');
        store.dispatch(setActiveThread(threadId));
        store.dispatch(beginInferenceTurn({ threadId }));
        store.dispatch(
          setStreamingAssistantForThread({
            threadId,
            streaming: { requestId: 'req-1', content: 'Hello there, partial', thinking: '' },
          })
        );
      });

      await act(async () => {
        store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));
      });

      await waitFor(() => {
        expect(store.getState().thread.activeThreadIds[threadId]).toBeUndefined();
      });
      expect(store.getState().chatRuntime.streamingAssistantByThread[threadId]).toMatchObject({
        content: 'Hello there, partial',
      });
    });
  });

  // Error classifier full set — Batch-5 coverage (#1506, pr#1566).
  //
  // Every error_type — including the generic 'inference' fallback — carries a
  // user-friendly `message` from classify_inference_error() in web_errors.rs,
  // which is forwarded directly so the user sees the real reason (for
  // 'inference' that message is a friendly summary plus the sanitized upstream
  // provider error as a `> quote` block). An empty server message is stored
  // as an empty error row for assistant-ui's ErrorState fallback. 'cancelled'
  // produces no error row.
  describe('inference error classifier — full type set', () => {
    it.each([
      ['rate_limited', 'You have been rate limited. Please try again later.'],
      ['auth_error', 'Authentication failed. Please reconnect your account.'],
      ['budget_exhausted', 'Your usage budget has been exhausted.'],
      ['context_overflow', 'The conversation is too long. Please start a new thread.'],
      ['timeout', 'The request timed out. Please try again.'],
      ['network', 'A network error occurred. Please check your connection.'],
      ['tool_error', 'A tool call failed during this request.'],
      ['provider_error', 'The AI provider returned an error.'],
      ['model_unavailable', 'The selected model is currently unavailable.'],
      [
        'payload_too_large',
        'Your message or attachment is too large for this model. Shorten it or remove the attachment — or start a new thread.',
      ],
    ] as const)('forwards server message for error_type %s', async (error_type, serverMessage) => {
      const listeners = renderProvider();
      const threadId = `t-${error_type}`;

      act(() => {
        listeners.onError?.({
          thread_id: threadId,
          request_id: 'r1',
          message: serverMessage,
          error_type,
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          threadId,
          expect.objectContaining({ content: serverMessage, sender: 'agent' })
        )
      );
    });

    it('surfaces the server inference message (friendly summary + sanitized provider detail)', async () => {
      const listeners = renderProvider();
      const threadId = 't-inference-detail';
      // Shape produced by web_errors.rs `with_provider_detail(generic, err)`:
      // the friendly summary, then the real upstream reason as a `> quote`
      // block (already secret-scrubbed and length-capped server-side).
      const serverMessage =
        'Something went wrong. Please try again.\n\n> Project `proj_x` does not have access to model `gpt-5.5`.';

      act(() => {
        listeners.onError?.({
          thread_id: threadId,
          request_id: 'r1',
          message: serverMessage,
          error_type: 'inference',
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          threadId,
          expect.objectContaining({ content: serverMessage, sender: 'agent' })
        )
      );
    });

    it('stores an empty error row for assistant-ui when an inference error has no message', async () => {
      const listeners = renderProvider();
      const threadId = 't-inference-empty';

      act(() => {
        listeners.onError?.({
          thread_id: threadId,
          request_id: 'r1',
          message: '',
          error_type: 'inference',
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          threadId,
          expect.objectContaining({
            content: '',
            sender: 'agent',
            extraMetadata: expect.objectContaining({
              chatError: expect.objectContaining({ errorType: 'inference' }),
            }),
          })
        )
      );
    });

    it('produces no error bubble for cancelled turns', async () => {
      const listeners = renderProvider();
      const threadId = 't-cancelled';

      act(() => {
        listeners.onError?.({
          thread_id: threadId,
          request_id: 'r1',
          message: 'request cancelled by user',
          error_type: 'cancelled',
        });
      });

      // Give a tick for any async work to complete.
      await new Promise(resolve => setTimeout(resolve, 50));
      expect(threadApi.appendMessage).not.toHaveBeenCalledWith(
        threadId,
        expect.objectContaining({ sender: 'agent' })
      );
    });

    it('stores an empty error row for other error types without a message', async () => {
      const listeners = renderProvider();
      const threadId = 't-empty-msg';

      act(() => {
        listeners.onError?.({
          thread_id: threadId,
          request_id: 'r1',
          message: '',
          error_type: 'network',
        });
      });

      await waitFor(() =>
        expect(threadApi.appendMessage).toHaveBeenCalledWith(
          threadId,
          expect.objectContaining({
            content: '',
            sender: 'agent',
            extraMetadata: expect.objectContaining({
              chatError: expect.objectContaining({ errorType: 'network' }),
            }),
          })
        )
      );
    });
  });
});

describe('ChatRuntimeProvider — chat_cancelled (wire-contract.md)', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    resetRuntimeState();
  });

  afterEach(() => {
    resetRuntimeState();
  });

  // `chat_cancelled` is the core-authoritative sibling of the local Stop path
  // in `Conversations.tsx`; the core keeps emitting `chat_error{error_type:
  // "cancelled"}` alongside it for one release (asserted above to append no
  // message), so this dedupes on `request_id` against whatever the local
  // path already persisted.
  it('persists the live partial as a stopped reply, tagged with cancel_reason', async () => {
    const listeners = renderProvider();
    const threadId = 't-chat-cancelled';

    act(() => {
      store.dispatch(
        setStreamingAssistantForThread({
          threadId,
          streaming: { content: 'partial before supersede', thinking: '', requestId: 'r-sup' },
        })
      );
    });

    act(() => {
      listeners.onCancelled?.({
        thread_id: threadId,
        request_id: 'r-sup',
        cancel_reason: 'superseded',
        superseded_by: 'r-next',
      });
    });

    await waitFor(() =>
      expect(threadApi.appendMessage).toHaveBeenCalledWith(
        threadId,
        expect.objectContaining({
          sender: 'agent',
          content: 'partial before supersede',
          extraMetadata: expect.objectContaining({
            stopped: true,
            cancelReason: 'superseded',
            supersededBy: 'r-next',
            requestId: 'r-sup',
          }),
        })
      )
    );
  });

  it('keeps the partial when the core sends cancelled chat_error before chat_cancelled', async () => {
    const listeners = renderProvider();
    const threadId = 't-stop-event-order';

    act(() => {
      store.dispatch(
        setStreamingAssistantForThread({
          threadId,
          streaming: { content: 'answer so far', thinking: '', requestId: 'r-stop' },
        })
      );
      listeners.onError?.({
        thread_id: threadId,
        request_id: 'r-stop',
        message: 'Cancelled',
        error_type: 'cancelled',
      });
      listeners.onCancelled?.({
        thread_id: threadId,
        request_id: 'r-stop',
        cancel_reason: 'user_stop',
      });
    });

    await waitFor(() =>
      expect(threadApi.appendMessage).toHaveBeenCalledWith(
        threadId,
        expect.objectContaining({
          content: 'answer so far',
          extraMetadata: expect.objectContaining({
            stopped: true,
            cancelReason: 'user_stop',
            requestId: 'r-stop',
          }),
        })
      )
    );
    expect(threadApi.appendMessage).toHaveBeenCalledTimes(1);
  });

  it('anchors a stopped turn whose output was only processing activity', async () => {
    const listeners = renderProvider();
    const threadId = 't-processing-stop';

    act(() => {
      store.dispatch(
        streamDeltaReceived({
          threadId,
          requestId: 'r-thinking',
          round: 1,
          delta: 'considering the request',
          channel: 'thinking',
          at: Date.now(),
        })
      );
      listeners.onError?.({
        thread_id: threadId,
        request_id: 'r-thinking',
        message: 'Cancelled',
        error_type: 'cancelled',
      });
      listeners.onCancelled?.({
        thread_id: threadId,
        request_id: 'r-thinking',
        cancel_reason: 'user_stop',
      });
    });

    await waitFor(() =>
      expect(threadApi.appendMessage).toHaveBeenCalledWith(
        threadId,
        expect.objectContaining({
          content: '',
          extraMetadata: expect.objectContaining({ stopped: true, requestId: 'r-thinking' }),
        })
      )
    );
    await waitFor(() =>
      expect(store.getState().chatRuntime.settledTurnsByThread[threadId]?.['r-thinking']).toEqual(
        expect.objectContaining({
          transcript: expect.arrayContaining([
            expect.objectContaining({ kind: 'thinking', text: 'considering the request' }),
          ]),
        })
      )
    );
  });

  it('stops a parallel branch without clearing the primary turn', async () => {
    const listeners = renderProvider();
    const threadId = 't-parallel-stop';

    act(() => {
      store.dispatch(registerParallelRequest({ threadId, requestId: 'r-branch' }));
      store.dispatch(
        setStreamingAssistantForThread({
          threadId,
          streaming: { content: 'primary continues', thinking: '', requestId: 'r-primary' },
        })
      );
      store.dispatch(
        streamDeltaReceived({
          threadId,
          requestId: 'r-branch',
          round: 1,
          delta: 'branch partial',
          channel: 'content',
        })
      );
      listeners.onError?.({
        thread_id: threadId,
        request_id: 'r-branch',
        message: 'Cancelled',
        error_type: 'cancelled',
      });
      listeners.onCancelled?.({
        thread_id: threadId,
        request_id: 'r-branch',
        cancel_reason: 'user_stop',
      });
    });

    await waitFor(() =>
      expect(threadApi.appendMessage).toHaveBeenCalledWith(
        threadId,
        expect.objectContaining({ content: 'branch partial' })
      )
    );
    await waitFor(() =>
      expect(store.getState().chatRuntime.parallelRequestThreads['r-branch']).toBeUndefined()
    );
    expect(store.getState().chatRuntime.streamingAssistantByThread[threadId]?.content).toBe(
      'primary continues'
    );
  });

  it('persists a repeated chat_cancelled event only once for the same request', async () => {
    const listeners = renderProvider();
    const threadId = 't-chat-cancelled-dedupe';

    act(() => {
      store.dispatch(
        setStreamingAssistantForThread({
          threadId,
          streaming: { content: 'save this once', thinking: '', requestId: 'r-dup' },
        })
      );
    });

    act(() => {
      const event = {
        thread_id: threadId,
        request_id: 'r-dup',
        cancel_reason: 'user_stop',
      } as const;
      listeners.onCancelled?.(event);
      listeners.onCancelled?.(event);
    });

    await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(1));
    expect(threadApi.appendMessage).toHaveBeenCalledWith(
      threadId,
      expect.objectContaining({
        content: 'save this once',
        extraMetadata: expect.objectContaining({ stopped: true, requestId: 'r-dup' }),
      })
    );
  });

  it('produces no message when nothing streamed (no partial to save)', async () => {
    const listeners = renderProvider();
    const threadId = 't-chat-cancelled-empty';

    act(() => {
      listeners.onCancelled?.({
        thread_id: threadId,
        request_id: 'r-empty',
        cancel_reason: 'user_stop',
      });
    });

    await new Promise(resolve => setTimeout(resolve, 50));
    expect(threadApi.appendMessage).not.toHaveBeenCalledWith(
      threadId,
      expect.objectContaining({ sender: 'agent' })
    );
  });
});

describe('ChatRuntimeProvider — skill tool-chain latency (#4273 AC3)', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    resetRuntimeState();
    vi.mocked(threadApi.appendMessage).mockImplementation(async (_tid, msg) => msg);
    vi.mocked(threadApi.getThreads).mockResolvedValue({ threads: [], count: 0 });
    vi.mocked(threadApi.getTurnState).mockResolvedValue(null);
    vi.mocked(threadApi.listRuns).mockResolvedValue([]);
    vi.mocked(threadApi.generateTitleIfNeeded).mockResolvedValue({
      id: 'tid',
      title: 'new',
    } as never);
  });

  afterEach(() => {
    // Restore the console.warn spy + real timers in shared cleanup so a failing
    // assertion can't leave a mocked console for the next test (PR #4288).
    vi.useRealTimers();
    vi.restoreAllMocks();
  });

  const toolCall = (thread: string): chatService.ChatToolCallEvent => ({
    thread_id: thread,
    request_id: 'r1',
    round: 0,
    tool_name: 'composio_execute',
    skill_id: 'gmail',
    args: {},
    tool_call_id: `${thread}-call-1`,
  });

  const done = (thread: string): chatService.ChatDoneEvent =>
    ({
      thread_id: thread,
      request_id: 'r1',
      full_response: '',
      total_input_tokens: 0,
      total_output_tokens: 0,
    }) as chatService.ChatDoneEvent;

  it('warns when a tool chain overruns the 60s target', () => {
    const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
    const listeners = renderProvider();

    vi.useFakeTimers();
    try {
      vi.setSystemTime(new Date('2026-06-29T00:00:00.000Z'));
      act(() => {
        listeners.onToolCall?.(toolCall('t-slow'));
      });
      // 61s later — past the 60s budget.
      vi.setSystemTime(new Date('2026-06-29T00:01:01.000Z'));
      act(() => {
        listeners.onDone?.(done('t-slow'));
      });
    } finally {
      vi.useRealTimers();
    }

    expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('[skill-latency]'));
    expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('exceeds the 60000ms target'));
  });

  it('does not warn for a chain that completes within the target', () => {
    const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
    const listeners = renderProvider();

    vi.useFakeTimers();
    try {
      vi.setSystemTime(new Date('2026-06-29T00:00:00.000Z'));
      act(() => {
        listeners.onToolCall?.(toolCall('t-fast'));
      });
      vi.setSystemTime(new Date('2026-06-29T00:00:02.000Z')); // 2s
      act(() => {
        listeners.onDone?.(done('t-fast'));
      });
    } finally {
      vi.useRealTimers();
    }

    expect(warnSpy.mock.calls.some(args => String(args[0]).includes('[skill-latency]'))).toBe(
      false
    );
  });

  it('dispatches openhuman:session-expired window event on session_expired chat error (#5868)', () => {
    const listeners = renderProvider();
    const received: Event[] = [];
    const handler = (e: Event) => received.push(e);
    window.addEventListener('openhuman:session-expired', handler);

    act(() => {
      listeners.onError?.({
        thread_id: 't-sess',
        request_id: 'r1',
        error_type: 'session_expired',
        message: 'Your OpenHuman session has expired. Please sign in again to continue.',
      } as chatService.ChatErrorEvent);
    });

    window.removeEventListener('openhuman:session-expired', handler);
    expect(received).toHaveLength(1);
    expect((received[0] as CustomEvent).detail?.source).toBe('chat-error');
    // The reason is the load-bearing half, not decoration. `CoreStateProvider`
    // defaults a reason-less `openhuman:session-expired` to `confirmed`, which
    // SKIPS `confirmSessionTokenGone()` and runs the destructive
    // `clearSession()`. The core reaches this error type through
    // `is_session_expired_message`, which also matches the local guards
    // "no backend session token" and "session jwt required" — the transient
    // pre-profile-load signals #2758 exists to corroborate rather than trust.
    // Dropping this field silently reintroduces that bug through a new door,
    // so it is asserted here, at the dispatch, where the value is decided.
    expect((received[0] as CustomEvent).detail?.reason).toBe('unconfirmed');
  });

  it('does not dispatch openhuman:session-expired for non-session error types', () => {
    const listeners = renderProvider();
    const received: Event[] = [];
    const handler = (e: Event) => received.push(e);
    window.addEventListener('openhuman:session-expired', handler);

    act(() => {
      listeners.onError?.({
        thread_id: 't-inf',
        request_id: 'r1',
        error_type: 'inference',
        message: 'Something went wrong.',
      } as chatService.ChatErrorEvent);
    });

    window.removeEventListener('openhuman:session-expired', handler);
    expect(received).toHaveLength(0);
  });

  it('closes the latency window on chat_error without warning', () => {
    const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
    const listeners = renderProvider();

    act(() => {
      listeners.onToolCall?.(toolCall('t-err'));
    });
    expect(() => {
      act(() => {
        listeners.onError?.({
          thread_id: 't-err',
          request_id: 'r1',
          error_type: 'provider_error',
          message: 'boom',
        } as chatService.ChatErrorEvent);
      });
    }).not.toThrow();

    // Error path logs structured latency but never emits the overrun warning.
    expect(warnSpy.mock.calls.some(args => String(args[0]).includes('[skill-latency]'))).toBe(
      false
    );
  });
});

// Regression: an async sub-agent's approval card (`detached`) was routed to the
// parent thread and then wiped by the parent turn's `chat_done`, though its
// gate was still parked — every async `image_agent` approval expired unseen.
describe('ChatRuntimeProvider — detached sub-agent approvals', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    resetRuntimeState();
    vi.mocked(threadApi.appendMessage).mockImplementation(async (_tid, msg) => msg);
    vi.mocked(threadApi.getThreads).mockResolvedValue({ threads: [], count: 0 });
    vi.mocked(threadApi.getTurnState).mockResolvedValue(null);
    vi.mocked(threadApi.listRuns).mockResolvedValue([]);
  });

  const done = (threadId: string) => ({
    thread_id: threadId,
    request_id: 'parent-turn',
    full_response: 'I asked the image agent to make it.',
    total_input_tokens: 0,
    total_output_tokens: 0,
    segment_total: 0,
  });

  it('keeps a detached card across the parent turn end and clears it on its decision', () => {
    const listeners = renderProvider();
    act(() => {
      listeners.onApprovalRequest?.({
        thread_id: 't-sub',
        request_id: 'appr-sub',
        tool_name: 'media_generate_image',
        message: 'Run `media_generate_image` — a red fox',
        detached: true,
      });
    });
    act(() => {
      listeners.onDone?.(done('t-sub'));
    });
    expect(store.getState().chatRuntime.pendingApprovalByThread['t-sub']?.requestId).toBe(
      'appr-sub'
    );

    act(() => {
      listeners.onApprovalDecided?.({
        thread_id: 't-sub',
        request_id: 'appr-sub',
        message: 'approve_once',
      });
    });
    expect(store.getState().chatRuntime.pendingApprovalByThread['t-sub']).toBeUndefined();
  });

  it('keeps a second detached card on the thread answerable instead of replacing the first', () => {
    const listeners = renderProvider();
    act(() => {
      listeners.onApprovalRequest?.({
        thread_id: 't-sub',
        request_id: 'appr-a',
        tool_name: 'media_generate_image',
        message: 'Run `media_generate_image`',
        detached: true,
      });
      listeners.onApprovalRequest?.({
        thread_id: 't-sub',
        request_id: 'appr-b',
        tool_name: 'media_generate_video',
        message: 'Run `media_generate_video`',
        detached: true,
      });
    });
    const runtime = () => store.getState().chatRuntime;
    expect(runtime().pendingApprovalByThread['t-sub']?.requestId).toBe('appr-a');

    // The first is answered elsewhere; the second takes its place.
    act(() => {
      listeners.onApprovalDecided?.({
        thread_id: 't-sub',
        request_id: 'appr-a',
        message: 'approve_once',
      });
    });
    expect(runtime().pendingApprovalByThread['t-sub']?.requestId).toBe('appr-b');
    act(() => {
      listeners.onApprovalDecided?.({ thread_id: 't-sub', request_id: 'appr-b', message: 'deny' });
    });
    expect(runtime().pendingApprovalByThread['t-sub']).toBeUndefined();
  });

  it('drops a detached card on a socket drop and rejoins its thread for the core replay', async () => {
    const listeners = renderProvider();
    act(() => {
      listeners.onApprovalRequest?.({
        thread_id: 't-sub',
        request_id: 'appr-sub',
        tool_name: 'media_generate_image',
        message: 'Run `media_generate_image`',
        detached: true,
      });
    });
    // The parent turn is long settled: nothing is in flight on the thread.
    act(() => {
      listeners.onDone?.(done('t-sub'));
    });
    vi.mocked(socketService.subscribeThread).mockClear();

    // The core restarts: its waiter and route for `appr-sub` are gone.
    act(() => {
      store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));
    });
    expect(store.getState().chatRuntime.pendingApprovalByThread['t-sub']).toBeUndefined();
    act(() => {
      store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));
    });
    // The rejoin is what makes the core replay any park it still holds.
    await waitFor(() => expect(socketService.subscribeThread).toHaveBeenCalledWith('t-sub'));
  });

  it('still clears an in-turn card when its turn ends', () => {
    const listeners = renderProvider();
    act(() => {
      listeners.onApprovalRequest?.({
        thread_id: 't-main',
        request_id: 'appr-main',
        tool_name: 'shell',
        message: 'Run `shell` — ls',
      });
    });
    act(() => {
      listeners.onDone?.(done('t-main'));
    });
    expect(store.getState().chatRuntime.pendingApprovalByThread['t-main']).toBeUndefined();
  });
});