The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
/**
* Smoke render tests for Conversations.tsx — covers new lines added in #1123
* (welcome-lock removal: unconditional sidebar, label filter, effectiveShowSidebar,
* quota usage pills, etc.).
*
* These tests intentionally do not test complex user interactions; they verify
* that the key JSX branches render without crashing, driving coverage of the
* previously-blocked lines that are now always rendered.
*/
import { combineReducers, configureStore } from '@reduxjs/toolkit';
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Provider } from 'react-redux';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { SidebarSlotOutlet, SidebarSlotProvider } from '../../components/layout/shell/SidebarSlot';
import { draftStorageKey } from '../../features/conversations/hooks/useThreadDraft';
import { threadApi } from '../../services/api/threadApi';
import {
chatCancel,
chatRemoveQueueItem,
chatSend,
chatSendWithAck,
} from '../../services/chatService';
import { CoreRpcError } from '../../services/coreRpcClient';
import chatRuntimeReducer, {
beginInferenceTurn,
bumpInferenceHeartbeatForThread,
markInferenceTurnStreaming,
setInferenceStatusForThread,
setPendingPlanReviewForThread,
setStreamingAssistantForThread,
setToolTimelineForThread,
setWorkflowProposalForThread,
} from '../../store/chatRuntimeSlice';
import layoutReducer from '../../store/layoutSlice';
import queueReducer, { queueItemQueued } from '../../store/queueSlice';
import runModeReducer from '../../store/runModeSlice';
import socketReducer from '../../store/socketSlice';
import themeReducer from '../../store/themeSlice';
import threadGoalReducer from '../../store/threadGoalSlice';
import threadReducer, { setSelectedThread } from '../../store/threadSlice';
import threadTodosReducer from '../../store/threadTodosSlice';
import { userScopedStorage } from '../../store/userScopedStorage';
import type { Thread, ThreadMessage } from '../../types/thread';
// ── Hoisted mock state ─────────────────────────────────────────────────────
const { mockGetThreads, mockGetThreadMessages, mockUseUsageState } = vi.hoisted(() => ({
mockGetThreads: vi.fn().mockResolvedValue({ threads: [], count: 0 }),
mockGetThreadMessages: vi.fn().mockResolvedValue({ messages: [], count: 0 }),
mockUseUsageState: vi.fn(() => ({
teamUsage: null as null | {
cycleBudgetUsd: number;
remainingUsd: number;
cycleSpentUsd: number;
cycleEndsAt: string | null;
},
currentPlan: null,
currentTier: 'FREE' as 'FREE' | 'BASIC' | 'PRO',
isFreeTier: true,
usagePct: 0,
isNearLimit: false,
isAtLimit: false,
isBudgetExhausted: false,
shouldShowBudgetCompletedMessage: false,
isLoading: false,
refresh: vi.fn(),
})),
}));
// ── Module mocks ───────────────────────────────────────────────────────────
// The chat mascot context is absent in this harness (no provider) unless a test
// installs one, which is how the Tiny-click → live voice path is exercised.
const { mascotContext } = vi.hoisted(() => ({
mascotContext: { current: undefined as undefined | { expandWithVoice: () => void } },
}));
vi.mock('../../features/human/chatMascot', async importOriginal => ({
...(await importOriginal<typeof import('../../features/human/chatMascot')>()),
useChatMascotOptional: () => mascotContext.current,
}));
vi.mock('../../services/chatService', () => ({
chatCancel: vi.fn().mockResolvedValue({ accepted: true, turnCancelled: true }),
chatClearQueue: vi.fn().mockResolvedValue(0),
chatRemoveQueueItem: vi.fn().mockResolvedValue(true),
chatSend: vi.fn().mockResolvedValue(undefined),
chatSendWithAck: vi.fn().mockResolvedValue({ requestId: 'request-test', queuedAttachments: [] }),
subscribeChatEvents: vi.fn(() => () => {}),
useRustChat: vi.fn(() => true),
}));
const { mockGetClientConfig, mockUpdateRuntimeSettings } = vi.hoisted(() => ({
mockGetClientConfig: vi.fn(() => Promise.resolve({ result: {} })),
mockUpdateRuntimeSettings: vi.fn(() => Promise.resolve({})),
}));
vi.mock('../../utils/tauriCommands/config', async importOriginal => ({
...(await importOriginal<typeof import('../../utils/tauriCommands/config')>()),
openhumanGetClientConfig: mockGetClientConfig,
openhumanUpdateRuntimeSettings: mockUpdateRuntimeSettings,
}));
vi.mock('../../services/api/threadApi', () => ({
threadApi: {
createNewThread: vi.fn().mockResolvedValue({ id: 'new-thread', labels: [] }),
getThreads: mockGetThreads,
getThreadMessages: mockGetThreadMessages,
getTurnState: vi.fn().mockResolvedValue(null),
getTurnStateHistory: vi.fn().mockResolvedValue([]),
getDerivedTranscript: vi
.fn()
.mockResolvedValue({
threadId: 'none',
items: [],
total: 0,
hasMore: false,
hasTranscript: false,
}),
appendMessage: vi.fn(async (_threadId: string, message: ThreadMessage) => message),
deleteThread: vi.fn().mockResolvedValue({ deleted: true }),
generateTitleIfNeeded: vi.fn().mockResolvedValue({}),
updateMessage: vi.fn().mockResolvedValue({}),
purge: vi.fn().mockResolvedValue({}),
updateLabels: vi.fn().mockResolvedValue({}),
updateTitle: vi.fn().mockResolvedValue({}),
persistReaction: vi.fn().mockResolvedValue({}),
},
}));
vi.mock('../../hooks/useUsageState', () => ({ useUsageState: mockUseUsageState }));
// coreState/store: getCoreStateSnapshot used by selectSocketStatus.
vi.mock('../../lib/coreState/store', () => ({
getCoreStateSnapshot: vi.fn(() => ({
isBootstrapping: false,
isReady: true,
snapshot: {
auth: { isAuthenticated: false, userId: null, user: null, profileId: null },
sessionToken: null,
currentUser: null,
onboardingCompleted: true,
chatOnboardingCompleted: true,
analyticsEnabled: false,
localState: {},
runtime: {},
},
})),
isWelcomeLocked: vi.fn(() => false),
setCoreStateSnapshot: vi.fn(),
}));
// ── Helpers ────────────────────────────────────────────────────────────────
function buildStore(preload: Record<string, unknown> = {}) {
return configureStore({
reducer: combineReducers({
thread: threadReducer,
layout: layoutReducer,
socket: socketReducer,
chatRuntime: chatRuntimeReducer,
queue: queueReducer,
theme: themeReducer,
threadTodos: threadTodosReducer,
threadGoal: threadGoalReducer,
runMode: runModeReducer,
}),
preloadedState: preload as never,
});
}
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: 't-1',
title: 'Test thread',
chatId: null,
isActive: false,
messageCount: 0,
lastMessageAt: '2026-01-01T00:00:00.000Z',
createdAt: '2026-01-01T00:00:00.000Z',
labels: ['general'],
...overrides,
};
}
async function renderConversations(preload: Record<string, unknown> = {}) {
const store = buildStore(preload);
const { default: Conversations } = await import('../../features/conversations/Conversations');
render(
<Provider store={store}>
<MemoryRouter initialEntries={['/conversations']}>
{/* The thread sidebar is projected into the root sidebar slot, so the
page needs a provider + outlet for that portal to mount in tests. */}
<SidebarSlotProvider>
<SidebarSlotOutlet />
<Conversations />
</SidebarSlotProvider>
</MemoryRouter>
</Provider>
);
return store;
}
async function renderConversationsRoute(route: string, preload: Record<string, unknown> = {}) {
const store = buildStore(preload);
const { default: Conversations } = await import('../../features/conversations/Conversations');
render(
<Provider store={store}>
<MemoryRouter initialEntries={[route]}>
<SidebarSlotProvider>
<SidebarSlotOutlet />
<Routes>
<Route
path="/chat/:threadId?"
element={
<>
<LocationProbe />
<Conversations />
</>
}
/>
</Routes>
</SidebarSlotProvider>
</MemoryRouter>
</Provider>
);
return store;
}
async function renderEmbeddedConversationsRoute(
route: string,
preload: Record<string, unknown> = {}
) {
const store = buildStore(preload);
const { default: Conversations } = await import('../../features/conversations/Conversations');
render(
<Provider store={store}>
<MemoryRouter initialEntries={[route]}>
<SidebarSlotProvider>
<SidebarSlotOutlet />
<Routes>
<Route
path="/human"
element={
<>
<LocationProbe />
<Conversations variant="sidebar" composer="mic-cloud" projectThreadList />
</>
}
/>
</Routes>
</SidebarSlotProvider>
</MemoryRouter>
</Provider>
);
return store;
}
function LocationProbe() {
const location = useLocation();
return <span data-testid="route-path">{location.pathname}</span>;
}
/** The thread sidebar is always projected now (no toggle); just flush effects. */
async function openSidebar() {
await act(async () => {});
}
// Default empty state
const emptyThreadState = {
threads: [],
selectedThreadId: null,
selectionIntentVersion: 0,
activeThreadIds: {},
welcomeThreadId: null,
messagesByThreadId: {},
messages: [],
isLoadingThreads: false,
isLoadingMessages: false,
messagesError: null,
};
function selectedThreadState(thread: Thread) {
return {
...emptyThreadState,
threads: [thread],
selectedThreadId: thread.id,
messagesByThreadId: { [thread.id]: [] },
messages: [],
};
}
function socketState(status: 'connected' | 'disconnected') {
return {
byUser: { __pending__: { status, socketId: status === 'connected' ? 'socket-1' : null } },
};
}
async function renderSelectedConversation(
options: { isAtLimit?: boolean; socketStatus?: 'connected' | 'disconnected' } = {}
) {
const thread = makeThread({ id: 'send-thread', title: 'Send Thread' });
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });
mockUseUsageState.mockReturnValue({
teamUsage: null,
currentPlan: null,
currentTier: 'FREE' as const,
isFreeTier: true,
usagePct: options.isAtLimit ? 1 : 0,
isNearLimit: Boolean(options.isAtLimit),
isAtLimit: Boolean(options.isAtLimit),
isBudgetExhausted: false,
shouldShowBudgetCompletedMessage: false,
isLoading: false,
refresh: vi.fn(),
});
let renderedStore: ReturnType<typeof buildStore> | undefined;
await act(async () => {
renderedStore = await renderConversations({
thread: selectedThreadState(thread),
socket: socketState(options.socketStatus ?? 'connected'),
});
});
const textarea = await screen.findByRole('textbox', { name: 'Message input' });
return { store: renderedStore, textarea, thread };
}
async function submitComposerText(textarea: HTMLElement, text: string) {
await act(async () => {
setComposerText(textarea, text);
});
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
}
function setComposerText(textarea: HTMLElement, text: string) {
textarea.textContent = text;
fireEvent.input(textarea, { data: text, inputType: 'insertText' });
}
/**
* Drive one IME composition the way a browser does: keystrokes arrive as `input`
* events carrying the PRE-EDIT text with `isComposing` set, then the commit lands
* on `compositionend`.
*
* `fireEvent.input` builds an `InputEvent` from these props, so `isComposing` is a
* real property on the native event rather than something the handler has to be
* told about.
*/
function typeImePreEdits(textarea: HTMLElement, preEdits: string[]) {
for (const preEdit of preEdits) {
textarea.textContent = preEdit;
fireEvent.input(textarea, {
data: preEdit,
inputType: 'insertCompositionText',
isComposing: true,
});
}
}
function commitIme(textarea: HTMLElement, committed: string) {
textarea.textContent = committed;
fireEvent.compositionEnd(textarea, { data: committed });
}
// ── Tests ──────────────────────────────────────────────────────────────────
describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {
beforeEach(() => {
vi.clearAllMocks();
window.localStorage.clear();
mockGetClientConfig.mockResolvedValue({ result: {} });
mockUpdateRuntimeSettings.mockResolvedValue({});
// Reset the mock to defaults for each test
mockGetThreads.mockResolvedValue({ threads: [], count: 0 });
mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });
mockUseUsageState.mockReturnValue({
teamUsage: null,
currentPlan: null,
currentTier: 'FREE' as const,
isFreeTier: true,
usagePct: 0.0,
isNearLimit: false,
isAtLimit: false,
isBudgetExhausted: false,
shouldShowBudgetCompletedMessage: false,
isLoading: false,
refresh: vi.fn(),
});
});
// Covers the page-mode sidebar (TwoPanelLayout, id `chat`) once opened. The
// General/Tasks filter chips were removed, and so was the thread
// search; the section header's "new conversation" affordance is now the stable
// top-of-sidebar control.
it('renders the sidebar thread list chrome in page mode', async () => {
await act(async () => {
await renderConversations({ thread: emptyThreadState });
});
await openSidebar();
expect(screen.getByTestId('new-thread-button')).toBeInTheDocument();
expect(screen.queryByTestId('chat-thread-search-input')).not.toBeInTheDocument();
expect(screen.queryByRole('tab', { name: 'General' })).not.toBeInTheDocument();
});
// Covers the empty branch — with the filter chips gone the list always shows
// the generic empty message when no (General-bucket) threads exist.
it('shows the empty message when there are no threads', async () => {
await act(async () => {
await renderConversations({ thread: emptyThreadState });
});
// Sidebar is hidden by default — open it first.
await openSidebar();
expect(screen.getByText('No threads yet')).toBeInTheDocument();
});
// Covers lines 1002-1004, 1007, 1011-1012, 1014: thread list items rendered unconditionally
it('renders thread list items when threads are pre-loaded', async () => {
const threads = [
makeThread({ id: 't-1', title: 'Thread Alpha' }),
makeThread({ id: 't-2', title: 'Thread Beta' }),
];
// Return the threads from the API so the useEffect loadThreads picks them up
mockGetThreads.mockResolvedValue({ threads, count: 2 });
await act(async () => {
await renderConversations({ thread: emptyThreadState });
});
// Sidebar is hidden by default — open it first.
await openSidebar();
// Wait for loadThreads to complete and the thread list to render.
// Use getAllByText because the title may appear in both the sidebar list
// and the conversation header (both are rendered).
await waitFor(() => {
expect(screen.getAllByText('Thread Alpha').length).toBeGreaterThan(0);
});
expect(screen.getAllByText('Thread Beta').length).toBeGreaterThan(0);
});
it('falls back to /chat when the routed thread id is missing', async () => {
mockGetThreads.mockResolvedValue({
threads: [makeThread({ id: 't-1', title: 'Thread Alpha' })],
count: 1,
});
await act(async () => {
await renderConversationsRoute('/chat/missing-thread', { thread: emptyThreadState });
});
await waitFor(() => {
expect(screen.getByTestId('route-path')).toHaveTextContent('/chat');
});
expect(threadApi.createNewThread).not.toHaveBeenCalled();
});
it('updates the route when selecting sidebar threads by click or keyboard', async () => {
const threads = [
makeThread({ id: 't-1', title: 'Thread Alpha' }),
makeThread({ id: 't-2', title: 'Thread Beta' }),
];
mockGetThreads.mockResolvedValue({ threads, count: 2 });
await act(async () => {
await renderConversationsRoute('/chat', { thread: emptyThreadState });
});
await openSidebar();
const alphaRow = await screen.findByRole('button', { name: /Thread Alpha/ });
await act(async () => {
fireEvent.click(alphaRow);
});
await waitFor(() => {
expect(screen.getByTestId('route-path')).toHaveTextContent('/chat/t-1');
});
const betaRow = await screen.findByRole('button', { name: /Thread Beta/ });
betaRow.focus();
await userEvent.keyboard('{Enter}');
await waitFor(() => {
expect(screen.getByTestId('route-path')).toHaveTextContent('/chat/t-2');
});
});
it('does not push chat routes when embedded chat creates a thread', async () => {
mockGetThreads.mockResolvedValue({ threads: [], count: 0 });
await act(async () => {
await renderEmbeddedConversationsRoute('/human', { thread: emptyThreadState });
});
await waitFor(() => {
expect(threadApi.createNewThread).toHaveBeenCalled();
});
expect(screen.getByTestId('route-path')).toHaveTextContent('/human');
});
it('does not push chat routes when embedded chat selects a thread', async () => {
const threads = [makeThread({ id: 't-1', title: 'Thread Alpha' })];
mockGetThreads.mockResolvedValue({ threads, count: 1 });
await act(async () => {
await renderEmbeddedConversationsRoute('/human', { thread: emptyThreadState });
});
await openSidebar();
const alphaRow = await screen.findByRole('button', { name: /Thread Alpha/ });
await act(async () => {
fireEvent.click(alphaRow);
});
expect(screen.getByTestId('route-path')).toHaveTextContent('/human');
});
// Covers line 1083: messagesError branch renders error state
it('renders the error icon section when loadThreadMessages rejects', async () => {
// Make loadThreadMessages always fail so messagesError is set in the store
mockGetThreadMessages.mockRejectedValue(new Error('Network error'));
// Return one thread so the component selects it and loads messages
const thread = makeThread({ id: 't-2', title: 'Error Thread' });
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
await act(async () => {
await renderConversations({ thread: emptyThreadState });
});
// After the failed load, messagesError is set in state — the error branch renders.
// This covers line 1083 (the error container div).
await waitFor(() => {
// The error branch renders "Failed to load messages" static text
expect(screen.getByText('Failed to load messages')).toBeInTheDocument();
});
});
it('renders assistant messages as unframed text when the appearance preference is enabled', async () => {
const thread = makeThread({ id: 'view-mode-thread', title: 'View Mode Thread' });
const messages: ThreadMessage[] = [
{
id: 'm-user',
sender: 'user',
type: 'text',
content: 'Can you summarize this?',
extraMetadata: {},
createdAt: '2026-01-01T00:00:00.000Z',
},
{
id: 'm-agent',
sender: 'agent',
type: 'text',
content: 'Long agent output\n\nwith enough structure to prefer a text view.',
extraMetadata: {},
createdAt: '2026-01-01T00:01:00.000Z',
},
];
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
mockGetThreadMessages.mockResolvedValue({ messages, count: messages.length });
await act(async () => {
await renderConversations({
thread: {
...selectedThreadState(thread),
messagesByThreadId: { [thread.id]: messages },
messages,
},
socket: socketState('connected'),
theme: { mode: 'system', tabBarLabels: 'hover', fontSize: 'medium' },
});
});
expect(document.querySelector('[data-slot="aui_assistant-message-content"]')).toHaveTextContent(
'Long agent output with enough structure to prefer a text view.'
);
expect(screen.getByText('Can you summarize this?')).toBeInTheDocument();
// Message rows must retain their measured layout/paint while off-screen.
// `content-visibility:auto` plus a guessed intrinsic height makes WebKit
// reveal/re-size rows as they cross the viewport, producing scroll flicker.
const assistantRoot = screen.getByTestId('agent-message');
const userRoot = document.querySelector('[data-slot="aui_user-message-root"]');
expect(assistantRoot.className).not.toContain('content-visibility');
expect(userRoot?.className).not.toContain('content-visibility');
expect(assistantRoot.className).not.toContain('contain-intrinsic-size');
expect(userRoot?.className).not.toContain('contain-intrinsic-size');
});
it("renders a past turn's process trail above the answer it produced (Phase 5)", async () => {
const thread = makeThread({ id: 'multi-turn-thread', title: 'Multi Turn' });
// Two turns: req-1 (older) and req-2 (latest). Only the older turn has a
// hydrated past-turn timeline (the latest renders as the live anchor).
const messages: ThreadMessage[] = [
{
id: 'u1',
sender: 'user',
type: 'text',
content: 'first question',
extraMetadata: { requestId: 'req-1' },
createdAt: '2026-01-01T00:00:00.000Z',
},
{
id: 'a1',
sender: 'agent',
type: 'text',
content: 'first answer',
extraMetadata: { requestId: 'req-1' },
createdAt: '2026-01-01T00:01:00.000Z',
},
{
id: 'u2',
sender: 'user',
type: 'text',
content: 'second question',
extraMetadata: { requestId: 'req-2' },
createdAt: '2026-01-01T00:02:00.000Z',
},
{
id: 'a2',
sender: 'agent',
type: 'text',
content: 'second answer',
extraMetadata: { requestId: 'req-2' },
createdAt: '2026-01-01T00:03:00.000Z',
},
];
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
mockGetThreadMessages.mockResolvedValue({ messages, count: messages.length });
vi.mocked(threadApi.getDerivedTranscript).mockResolvedValueOnce({
threadId: thread.id,
items: [
{ kind: 'toolCall', callId: 'tc-1', name: 'read_file', status: 'success' },
{ kind: 'turnBoundary', requestId: 'req-1' },
],
total: 2,
hasMore: false,
hasTranscript: true,
});
await act(async () => {
await renderConversations({
thread: {
...selectedThreadState(thread),
messagesByThreadId: { [thread.id]: messages },
messages,
},
socket: socketState('connected'),
});
});
// The past turn's core transcript is projected into one settled activity
// group. Open it before checking the contained tool card.
fireEvent.click(await screen.findByRole('button', { name: '1 tool call' }));
expect(await screen.findByTestId('assistant-ui-tool-call')).toHaveTextContent('Read file');
});
it('keeps assistant message copy available through assistant-ui', async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } });
const thread = makeThread({ id: 'bubble-mode-thread', title: 'Bubble Mode Thread' });
const agentContent =
'First assistant paragraph with enough text to render.\n\nSecond assistant paragraph stays in bubbles.';
const messages: ThreadMessage[] = [
{
id: 'm-agent-bubble',
sender: 'agent',
type: 'text',
content: agentContent,
extraMetadata: {
citations: [
{
id: 'cite-1',
key: 'memory-key',
namespace: 'personal',
snippet: 'Remembered preference',
timestamp: '2026-01-01T00:00:00.000Z',
score: 0.91,
},
],
myReactions: ['👍'],
},
createdAt: '2026-01-01T00:01:00.000Z',
},
];
vi.mocked(threadApi.updateMessage).mockImplementation(
async (_threadId, _messageId, extraMetadata) =>
({ ...messages[0], extraMetadata }) as ThreadMessage
);
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
mockGetThreadMessages.mockResolvedValue({ messages, count: messages.length });
await act(async () => {
await renderConversations({
thread: {
...selectedThreadState(thread),
messagesByThreadId: { [thread.id]: messages },
messages,
},
socket: socketState('connected'),
theme: { mode: 'system', tabBarLabels: 'hover', fontSize: 'medium' },
});
});
expect(
screen.getByText('First assistant paragraph with enough text to render.')
).toBeInTheDocument();
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Copy' }));
});
expect(writeText).toHaveBeenCalledWith(agentContent);
});
// Covers line 247: if (cancelled) return — the non-cancelled path through loadThreads callback
it('selects first thread after loadThreads resolves (non-cancelled path)', async () => {
const threads = [makeThread({ id: 't-1', title: 'First Thread' })];
mockGetThreads.mockResolvedValue({ threads, count: 1 });
let resolvedStore: ReturnType<typeof buildStore> | undefined;
await act(async () => {
resolvedStore = await renderConversations({ thread: emptyThreadState });
});
// After loadThreads resolves and cancelled=false, the first thread is selected.
// This exercises line 247 (the if (cancelled) return check runs and is false).
await waitFor(() => {
const state = resolvedStore?.getState() as { thread: { selectedThreadId: string | null } };
expect(state.thread.selectedThreadId).toBe('t-1');
});
});
it('keeps an explicit sidebar selection made while initial thread loading is pending', async () => {
const threads = [
makeThread({ id: 't-1', title: 'Initial Thread' }),
makeThread({ id: 't-2', title: 'Explicitly Selected Thread' }),
];
let resolveThreads: ((value: { threads: Thread[]; count: number }) => void) | undefined;
mockGetThreads.mockImplementation(
() =>
new Promise(resolve => {
resolveThreads = resolve;
})
);
let store: ReturnType<typeof buildStore> | undefined;
await act(async () => {
store = await renderConversations({
thread: {
...emptyThreadState,
threads,
selectedThreadId: 't-1',
messagesByThreadId: { 't-1': [], 't-2': [] },
},
});
});
await waitFor(() => expect(mockGetThreads).toHaveBeenCalled());
fireEvent.click(screen.getByTestId('thread-row-t-2'));
expect(store?.getState().thread.selectedThreadId).toBe('t-2');
await act(async () => {
resolveThreads?.({ threads, count: threads.length });
});
expect(store?.getState().thread.selectedThreadId).toBe('t-2');
expect(
screen.getByTestId('thread-row-t-2').closest('[data-slot="aui_thread-list-item"]')
).toHaveAttribute('data-active');
});
// Sidebar "New thread" button was removed in the composer flattening refactor.
// The "+ New" header button (tested below) is the remaining create-thread entry point.
it('clicking "+ New" header button calls handleCreateNewThread', async () => {
// Need a selected thread so the header renders
const threads = [makeThread({ id: 't-1', title: 'Header Thread' })];
mockGetThreads.mockResolvedValue({ threads, count: 1 });
await act(async () => {
await renderConversations({ thread: emptyThreadState });
});
// Wait for thread to be selected so the header with "+ New" button renders
await waitFor(() => {
expect(screen.getByTitle('New thread (/new)')).toBeInTheDocument();
});
const headerNewBtn = screen.getByTitle('New thread (/new)');
await act(async () => {
fireEvent.click(headerNewBtn);
});
// createNewThread was called — verifies line 1061 callback executed
expect(threadApi.createNewThread).toHaveBeenCalled();
});
// Covers lines 981, 982: e.stopPropagation() and setDeleteModal(...) inside delete onClick
it('clicking delete button on a thread opens the delete modal', async () => {
const threads = [makeThread({ id: 't-del', title: 'Deletable Thread' })];
mockGetThreads.mockResolvedValue({ threads, count: 1 });
await act(async () => {
await renderConversations({ thread: emptyThreadState });
});
// Sidebar is hidden by default — open it first.
await openSidebar();
// Wait for the thread to appear in the sidebar
await waitFor(() => {
expect(screen.getAllByText('Deletable Thread').length).toBeGreaterThan(0);
});
await userEvent.click(screen.getByRole('button', { name: 'More options' }));
await userEvent.click(await screen.findByRole('menuitem', { name: 'Delete' }));
// The modal should now be open — "Are you sure you want to delete" text
// This verifies lines 981, 982, 985 inside the delete onClick callback executed
expect(screen.getByText(/Are you sure you want to delete/i)).toBeInTheDocument();
});
it('replaces the route when deleting the currently-routed thread', async () => {
const thread = makeThread({ id: 't-del', title: 'Deletable Thread' });
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
await act(async () => {
await renderConversationsRoute('/chat/t-del', { thread: selectedThreadState(thread) });
});
await openSidebar();
await userEvent.click(await screen.findByRole('button', { name: 'More options' }));
await userEvent.click(await screen.findByRole('menuitem', { name: 'Delete' }));
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
});
await waitFor(() => expect(threadApi.deleteThread).toHaveBeenCalledWith('t-del'));
expect(screen.getByTestId('route-path')).toHaveTextContent('/chat');
});
it('handles /new from the composer without a selected thread or sending chat text', async () => {
mockGetThreads.mockReturnValue(new Promise(() => {}));
await act(async () => {
await renderConversations({ thread: emptyThreadState, socket: socketState('connected') });
});
const textarea = await screen.findByRole('textbox', { name: 'Message input' });
vi.mocked(threadApi.createNewThread).mockClear();
vi.mocked(chatSend).mockClear();
await submitComposerText(textarea, '/new');
await waitFor(() => {
expect(threadApi.createNewThread).toHaveBeenCalled();
});
expect(chatSend).not.toHaveBeenCalled();
expect(textarea).toHaveTextContent('');
});
it('blocks the send when the account is over budget (no rate-limit modal anymore)', async () => {
const { textarea } = await renderSelectedConversation({ isAtLimit: true });
await submitComposerText(textarea, 'hello at limit');
// Backend PR #790 removed the rate-limit modal; over-budget now surfaces
// only the inline send-error (which clears as soon as the user keeps
// typing). The contract we still care about: chatSend is suppressed.
expect(chatSend).not.toHaveBeenCalled();
});
it('loads the thinking level from config, persists a new pick and sends it', async () => {
mockGetClientConfig.mockResolvedValue({ result: { reasoning_effort: 'low' } });
const { textarea, thread } = await renderSelectedConversation();
const picker = (await screen.findByTestId('composer-reasoning-effort')) as HTMLSelectElement;
await waitFor(() => expect(picker.value).toBe('low'));
fireEvent.change(picker, { target: { value: 'high' } });
expect(mockUpdateRuntimeSettings).toHaveBeenCalledWith({ reasoning_effort: 'high' });
await submitComposerText(textarea, 'think hard');
await waitFor(() => {
expect(chatSend).toHaveBeenCalledWith(
expect.objectContaining({ threadId: thread.id, reasoningEffort: 'high' })
);
});
fireEvent.change(picker, { target: { value: 'default' } });
expect(mockUpdateRuntimeSettings).toHaveBeenLastCalledWith({ reasoning_effort: '' });
});
it('remembers the thinking level per model and sends that model its own level', async () => {
mockGetClientConfig.mockResolvedValue({
result: {
reasoning_effort: 'low',
default_model: 'deep-model',
reasoning_effort_by_model: { 'deep-model': 'xhigh' },
},
});
const { textarea, thread } = await renderSelectedConversation();
const picker = (await screen.findByTestId('composer-reasoning-effort')) as HTMLSelectElement;
await waitFor(() => expect(picker.value).toBe('xhigh'));
fireEvent.change(picker, { target: { value: 'medium' } });
expect(mockUpdateRuntimeSettings).toHaveBeenCalledWith({
reasoning_effort: 'medium',
reasoning_effort_model: 'deep-model',
});
await submitComposerText(textarea, 'think a bit');
await waitFor(() => {
expect(chatSend).toHaveBeenCalledWith(
expect.objectContaining({ threadId: thread.id, reasoningEffort: 'medium' })
);
});
// Dropping the model's own level falls back to the global one.
fireEvent.change(picker, { target: { value: 'default' } });
expect(mockUpdateRuntimeSettings).toHaveBeenLastCalledWith({
reasoning_effort: '',
reasoning_effort_model: 'deep-model',
});
await waitFor(() => expect(picker.value).toBe('low'));
});
it('recalls the last prompt with ArrowUp and switches the placeholder while running', async () => {
let finishChatSend: (() => void) | undefined;
vi.mocked(chatSend).mockImplementationOnce(
() =>
new Promise<string | undefined>(resolve => {
finishChatSend = () => resolve(undefined);
})
);
const { textarea } = await renderSelectedConversation();
await submitComposerText(textarea, 'recall me later');
await waitFor(() => expect(chatSend).toHaveBeenCalled());
// The turn is in flight: typed text would queue, and the placeholder says so.
await waitFor(() => expect(screen.getByText('Queue a follow-up…')).toBeInTheDocument());
await act(async () => {
fireEvent.keyDown(textarea, { key: 'ArrowUp' });
});
await waitFor(() => expect(textarea.textContent).toBe('recall me later'));
await act(async () => finishChatSend?.());
});
it('persists a local user message and sends through chat service for valid input', async () => {
const { textarea, thread } = await renderSelectedConversation();
await submitComposerText(textarea, ' hello cloud ');
await waitFor(() => {
expect(threadApi.appendMessage).toHaveBeenCalledWith(
thread.id,
expect.objectContaining({ content: 'hello cloud', sender: 'user', type: 'text' }),
[]
);
});
expect(chatSend).toHaveBeenCalledWith(
expect.objectContaining({
threadId: thread.id,
message: 'hello cloud',
locale: 'en',
reasoningEffort: 'default',
})
);
expect(vi.mocked(chatSend).mock.calls[0][0]).not.toHaveProperty('model');
});
it('blocks duplicate sends while the first send is still pending', async () => {
let resolveSend: (() => void) | undefined;
vi.mocked(chatSend).mockImplementationOnce(
() =>
new Promise<string | undefined>(resolve => {
resolveSend = () => resolve(undefined);
})
);
const { textarea, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'slow backend');
});
await waitFor(() => {
expect(textarea).toHaveTextContent('slow backend');
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
const sendButton = screen.getByRole('button', { name: 'Send message' });
await act(async () => {
fireEvent.click(sendButton);
fireEvent.click(sendButton);
fireEvent.click(sendButton);
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
expect(threadApi.appendMessage).toHaveBeenCalledTimes(1);
expect(chatSend).toHaveBeenCalledWith(
expect.objectContaining({
threadId: thread.id,
message: 'slow backend',
locale: 'en',
reasoningEffort: 'default',
})
);
expect(vi.mocked(chatSend).mock.calls[0][0]).not.toHaveProperty('model');
// The send cleared the composer; with an empty composer mid-send the Send
// button morphs into the Stop button, so there is no Send affordance left
// to fire a duplicate send.
const stopButton = screen.getByRole('button', { name: 'Stop generating' });
expect(stopButton).toBeInTheDocument();
expect(stopButton).toHaveClass(
'bg-primary-500',
'text-content-inverted',
'hover:bg-primary-600'
);
expect(screen.queryByRole('button', { name: 'Send message' })).not.toBeInTheDocument();
resolveSend?.();
});
// #5763. The DOM->store bridge on the composer fired on every `input`, and an
// IME emits one per keystroke carrying the PRE-EDIT text. In a browser the
// resulting store write re-renders the editor and cancels the composition, so
// `nihao` + Enter committed as `n ni nihao 你好`. jsdom has no real Lexical
// composition to cancel, so what it shows instead is the other half of the same
// fault: the committed text never arrives and the last pre-edit stands. Either
// way the composer must end up holding what the user committed.
it('does not push the pre-edit into the composer while an IME composition runs', async () => {
const { textarea } = await renderSelectedConversation();
await act(async () => {
typeImePreEdits(textarea, ['n', 'ni', 'nihao']);
});
// Nothing was committed, so the composer must still be empty. Before the fix
// each pre-edit keystroke was written straight into the store, which is the
// write that cancels the composition in a real browser (#5763).
await waitFor(() => {
expect(screen.queryByRole('button', { name: 'Send message' })).toBeNull();
});
});
it('takes the committed IME text when the composition ends', async () => {
const { textarea, thread } = await renderSelectedConversation();
await act(async () => {
typeImePreEdits(textarea, ['n', 'ni', 'nihao']);
commitIme(textarea, '你好');
});
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
expect(chatSend).toHaveBeenCalledWith(
expect.objectContaining({ threadId: thread.id, message: '你好' })
);
});
// The store write is deferred by a microtask, so a fast typist can open the
// NEXT composition before it runs. #5764 (@ligjn) named that hazard: the stale
// write rebuilds the editor mid-composition and cancels it, which is #5763 one
// composition later. The gate is therefore re-checked inside the microtask.
it('drops a deferred store write once the next composition has begun', async () => {
const { textarea, thread } = await renderSelectedConversation();
await act(async () => {
fireEvent.compositionStart(textarea);
typeImePreEdits(textarea, ['n', 'ni', 'nihao']);
commitIme(textarea, '你好');
// Still inside the same task, so the write queued by `commitIme` has not
// run yet — and the user has already started composing the next word.
fireEvent.compositionStart(textarea);
});
// The stale write was dropped: nothing reached the store while a
// composition is open.
expect(screen.queryByRole('button', { name: 'Send message' })).toBeNull();
// Nothing was lost either — the next commit reads the whole DOM.
await act(async () => {
typeImePreEdits(textarea, ['你好sh', '你好shi']);
commitIme(textarea, '你好世界');
});
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
expect(chatSend).toHaveBeenCalledWith(
expect.objectContaining({ threadId: thread.id, message: '你好世界' })
);
});
// A cancelled composition (Escape, or clicking away) still fires
// `compositionend`, but the finalized DOM is legitimately empty. The store
// must end up empty too rather than holding the last pre-edit.
it('does not resurrect the pre-edit when a composition is cancelled', async () => {
const { textarea } = await renderSelectedConversation();
await act(async () => {
fireEvent.compositionStart(textarea);
typeImePreEdits(textarea, ['n', 'ni', 'nihao']);
commitIme(textarea, '');
});
await waitFor(() => {
expect(screen.queryByRole('button', { name: 'Send message' })).toBeNull();
});
// The gate reopened, so ordinary typing after the cancellation still syncs.
await act(async () => {
setComposerText(textarea, 'after cancel');
});
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
});
// The gate keys on `isComposing`, so ordinary typing must be untouched. This is
// the property the 22 existing composer tests depend on: in jsdom the bridge is
// the only path from a synthetic `input` to the store.
it('still syncs ordinary typing, which carries no composition flag', async () => {
const { textarea, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'plain text');
});
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
expect(chatSend).toHaveBeenCalledWith(
expect.objectContaining({ threadId: thread.id, message: 'plain text' })
);
});
it('cancels the in-flight generation when the in-composer Stop button is clicked', async () => {
let resolveSend: (() => void) | undefined;
vi.mocked(chatSend).mockImplementationOnce(
() =>
new Promise<string | undefined>(resolve => {
resolveSend = () => resolve(undefined);
})
);
const { textarea, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'cancel me');
});
const sendButton = screen.getByRole('button', { name: 'Send message' });
await act(async () => {
fireEvent.click(sendButton);
});
// Empty composer + in-flight turn -> the Send button became the Stop button.
const stopButton = await screen.findByRole('button', { name: 'Stop generating' });
await act(async () => {
fireEvent.click(stopButton);
});
expect(chatCancel).toHaveBeenCalledWith(thread.id);
resolveSend?.();
});
it('keeps a footer Cancel control in the mic-cloud composer while generating', async () => {
const thread = makeThread({ id: 'mic-cancel-thread', title: 'Mic' });
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });
const { default: Conversations } = await import('../../features/conversations/Conversations');
const store = buildStore({
thread: selectedThreadState(thread),
socket: socketState('connected'),
});
await act(async () => {
render(
<Provider store={store}>
<MemoryRouter initialEntries={['/conversations']}>
<SidebarSlotProvider>
<SidebarSlotOutlet />
<Conversations composer="mic-cloud" />
</SidebarSlotProvider>
</MemoryRouter>
</Provider>
);
});
// Drive an in-flight turn so `isSending` is true. The mic-cloud composer has
// no in-box Stop button, so the footer Cancel control is the cancel path.
await act(async () => {
store.dispatch(beginInferenceTurn({ threadId: thread.id }));
});
const cancelButtons = await screen.findAllByRole('button', { name: 'Cancel' });
const footerCancel = cancelButtons.find(
b => b.getAttribute('data-analytics-id') === 'chat-cancel-generation'
);
expect(footerCancel).toBeTruthy();
await act(async () => {
fireEvent.click(footerCancel as HTMLElement);
});
expect(chatCancel).toHaveBeenCalledWith(thread.id);
});
// ── #4862: Stop-response + ESC-to-interrupt & re-edit ────────────────────
// Render a selected thread with an in-flight streaming turn (active + a
// partial assistant reply already streamed), so the in-composer Stop button
// is visible and ESC has a turn to interrupt.
async function renderStreamingConversation(
opts: { userPrompt?: string; streamingContent?: string } = {}
) {
const thread = makeThread({ id: 'stream-thread', title: 'Streaming' });
const messages: ThreadMessage[] = opts.userPrompt
? [
{
id: 'u-1',
sender: 'user',
type: 'text',
content: opts.userPrompt,
extraMetadata: {},
createdAt: '2026-01-01T00:00:00.000Z',
},
]
: [];
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
mockGetThreadMessages.mockResolvedValue({ messages, count: messages.length });
let store: ReturnType<typeof buildStore> | undefined;
await act(async () => {
store = await renderConversations({
thread: {
...selectedThreadState(thread),
messagesByThreadId: { [thread.id]: messages },
messages,
// Marks the thread's turn as in-flight so the composer stays editable
// (`allowParallelSend`) and `selectedThreadActive` is true.
activeThreadIds: { [thread.id]: true },
},
socket: socketState('connected'),
});
});
await act(async () => {
store!.dispatch(beginInferenceTurn({ threadId: thread.id }));
store!.dispatch(markInferenceTurnStreaming({ threadId: thread.id }));
store!.dispatch(
setStreamingAssistantForThread({
threadId: thread.id,
streaming: {
requestId: 'req-stream-1',
content: opts.streamingContent ?? 'partial answer so far',
thinking: '',
},
})
);
});
return { store: store!, thread };
}
it('requests cancellation without persisting the partial before core confirmation (#4862)', async () => {
const { thread } = await renderStreamingConversation({ streamingContent: 'half a thought' });
const stopButton = await screen.findByRole('button', { name: 'Stop generating' });
await act(async () => {
fireEvent.click(stopButton);
});
expect(chatCancel).toHaveBeenCalledWith(thread.id);
// Persistence belongs to ChatRuntimeProvider.onCancelled after the core
// confirms the turn that actually stopped. The click path must not write
// early because a rejected cancellation can still produce a final reply.
await act(async () => {
await Promise.resolve();
});
expect(threadApi.appendMessage).not.toHaveBeenCalled();
});
it('does not persist a stopped message when nothing has streamed yet (#4862)', async () => {
const { thread } = await renderStreamingConversation({ streamingContent: ' ' });
const stopButton = await screen.findByRole('button', { name: 'Stop generating' });
await act(async () => {
fireEvent.click(stopButton);
});
expect(chatCancel).toHaveBeenCalledWith(thread.id);
// Whitespace-only partial → nothing worth preserving, so no message append.
expect(threadApi.appendMessage).not.toHaveBeenCalled();
});
it('does not persist a stopped reply when the cancel is rejected (#4862)', async () => {
// Socket down / RPC rejected → chatCancel resolves not-accepted. The original
// turn may keep running and append its own final response, so we must NOT
// leave a misleading partial bubble behind.
vi.mocked(chatCancel).mockResolvedValueOnce({ accepted: false, turnCancelled: false });
const { thread } = await renderStreamingConversation({ streamingContent: 'half a thought' });
const stopButton = await screen.findByRole('button', { name: 'Stop generating' });
await act(async () => {
fireEvent.click(stopButton);
});
expect(chatCancel).toHaveBeenCalledWith(thread.id);
// Give the cancel promise a tick to resolve; no stopped message should land.
await act(async () => {
await Promise.resolve();
});
expect(threadApi.appendMessage).not.toHaveBeenCalled();
});
it('settles a phantom running state when the core has no turn to cancel', async () => {
// The core accepted the Stop but had nothing in flight for the thread (the
// turn's terminal event was lost, or the marker was never a real turn). No
// `cancelled` chat_error will ever arrive, so the composer must leave the
// generating state on its own instead of offering a Stop that can't work.
vi.mocked(chatCancel).mockResolvedValueOnce({ accepted: true, turnCancelled: false });
const { thread, store } = await renderStreamingConversation({
streamingContent: 'half a thought',
});
const stopButton = await screen.findByRole('button', { name: 'Stop generating' });
await act(async () => {
fireEvent.click(stopButton);
});
await act(async () => {
await Promise.resolve();
});
expect(chatCancel).toHaveBeenCalledWith(thread.id);
expect(store.getState().thread.activeThreadIds[thread.id]).toBeUndefined();
expect(store.getState().chatRuntime.streamingAssistantByThread[thread.id]).toBeUndefined();
expect(screen.queryByRole('button', { name: 'Stop generating' })).toBeNull();
// Nothing was cancelled, so no partial is persisted as a stopped reply.
expect(threadApi.appendMessage).not.toHaveBeenCalled();
});
it('re-issues a Stop pressed before the core had registered the turn', async () => {
// The send RPC is still in flight, so the core has no turn yet and the
// first cancel finds nothing. Once the RPC returns the turn exists, and the
// Stop must be sent again rather than letting the turn run to completion.
let resolveSend: (() => void) | undefined;
vi.mocked(chatSend).mockImplementationOnce(
() =>
new Promise<string | undefined>(resolve => {
resolveSend = () => resolve('req-late');
})
);
vi.mocked(chatCancel)
.mockResolvedValueOnce({ accepted: true, turnCancelled: false })
.mockResolvedValueOnce({ accepted: true, turnCancelled: true });
const { textarea, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'stop me early');
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
const stopButton = await screen.findByRole('button', { name: 'Stop generating' });
await act(async () => {
fireEvent.click(stopButton);
});
await act(async () => {
await Promise.resolve();
});
expect(chatCancel).toHaveBeenCalledTimes(1);
await act(async () => {
resolveSend?.();
await Promise.resolve();
});
expect(chatCancel).toHaveBeenCalledTimes(2);
expect(chatCancel).toHaveBeenNthCalledWith(2, thread.id);
});
it.each([
['the cancel event never arrives', { accepted: true, turnCancelled: true }],
['the cancel RPC fails', { accepted: false, turnCancelled: false }],
])('settles the running state after a Stop when %s', async (_label, outcome) => {
vi.mocked(chatCancel).mockResolvedValueOnce(outcome);
const { thread, store } = await renderStreamingConversation({
streamingContent: 'half a thought',
});
const stopButton = await screen.findByRole('button', { name: 'Stop generating' });
vi.useFakeTimers();
try {
await act(async () => {
fireEvent.click(stopButton);
await Promise.resolve();
});
// Still waiting on the core's confirmation.
expect(store.getState().chatRuntime.inferenceTurnLifecycleByThread[thread.id]).toBe(
'streaming'
);
await act(async () => {
vi.advanceTimersByTime(5_000);
});
} finally {
vi.useRealTimers();
}
expect(chatCancel).toHaveBeenCalledWith(thread.id);
expect(store.getState().chatRuntime.inferenceTurnLifecycleByThread[thread.id]).toBeUndefined();
expect(store.getState().thread.activeThreadIds[thread.id]).toBeUndefined();
expect(screen.queryByRole('button', { name: 'Stop generating' })).toBeNull();
});
it('does not locally persist a partial across repeated Stop clicks (#4862)', async () => {
const { thread } = await renderStreamingConversation({ streamingContent: 'half a thought' });
const stopButton = await screen.findByRole('button', { name: 'Stop generating' });
// Two rapid Stop clicks before the cancel event clears the live stream.
await act(async () => {
fireEvent.click(stopButton);
fireEvent.click(stopButton);
});
expect(chatCancel).toHaveBeenCalledTimes(2);
expect(chatCancel).toHaveBeenNthCalledWith(1, thread.id);
expect(chatCancel).toHaveBeenNthCalledWith(2, thread.id);
await act(async () => {
await Promise.resolve();
});
expect(threadApi.appendMessage).not.toHaveBeenCalled();
});
it('interrupts the stream and restores the last prompt into the composer on ESC (#4862)', async () => {
const { thread } = await renderStreamingConversation({
userPrompt: 'my original question',
streamingContent: 'streaming so far',
});
const textarea = await screen.findByRole('textbox', { name: 'Message input' });
expect(textarea).toHaveTextContent('');
await act(async () => {
fireEvent.keyDown(textarea, { key: 'Escape' });
});
// The turn is cancelled and the user's prompt is re-hydrated for editing.
expect(chatCancel).toHaveBeenCalledWith(thread.id);
await waitFor(() => {
expect(textarea).toHaveTextContent('my original question');
});
});
it('does not clobber a typed follow-up when ESC is pressed with a non-empty composer (#4862)', async () => {
const { thread } = await renderStreamingConversation({
userPrompt: 'my original question',
streamingContent: 'streaming so far',
});
const textarea = await screen.findByRole('textbox', { name: 'Message input' });
await act(async () => {
setComposerText(textarea, 'a fresh follow-up');
});
await act(async () => {
fireEvent.keyDown(textarea, { key: 'Escape' });
});
// Interrupt still fires, but the in-progress follow-up text is left intact.
expect(chatCancel).toHaveBeenCalledWith(thread.id);
expect(textarea).toHaveTextContent('a fresh follow-up');
});
it('renders a stopped partial reply as markdown with a Stopped marker (#4862, #7729)', async () => {
const thread = makeThread({ id: 'stopped-marker-thread', title: 'Stopped' });
const messages: ThreadMessage[] = [
{
id: 'u',
sender: 'user',
type: 'text',
content: 'go',
extraMetadata: {},
createdAt: '2026-01-01T00:00:00.000Z',
},
{
id: 'a',
sender: 'agent',
type: 'text',
content: [
'## Verification',
'First paragraph.',
'Second paragraph.',
'| Check | Result |\n|---|---|\n| npm test | pass |',
].join('\n\n'),
extraMetadata: { stopped: true },
createdAt: '2026-01-01T00:01:00.000Z',
},
];
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
mockGetThreadMessages.mockResolvedValue({ messages, count: messages.length });
await act(async () => {
await renderConversations({
thread: {
...selectedThreadState(thread),
messagesByThreadId: { [thread.id]: messages },
messages,
},
socket: socketState('connected'),
});
});
const marker = screen.getByTestId('stopped-marker');
expect(marker).toHaveTextContent('Stopped');
// The partial keeps its structure instead of one flattened paragraph, and
// renders once: the marker holds only the reason and actions.
expect(screen.getByRole('heading', { level: 2, name: 'Verification' })).toBeInTheDocument();
expect(screen.getByText('First paragraph.').tagName).toBe('P');
expect(screen.getByText('Second paragraph.').tagName).toBe('P');
expect(screen.getByRole('table')).toHaveTextContent('npm test');
expect(marker).not.toHaveTextContent('First paragraph.');
});
it('shows no Stop button while the thread is idle (#4862)', async () => {
await renderSelectedConversation();
expect(screen.queryByRole('button', { name: 'Stop generating' })).not.toBeInTheDocument();
// An idle thread with an empty composer gives the primary slot to the
// Human-page shortcut rather than a Send button that would refuse the
// click; Send returns as soon as there is something to send, which
// `queues via the Send button while a turn streams` covers. What #4862
// pins here is the absence of Stop.
expect(screen.getByTestId('composer-human-mode')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Send message' })).not.toBeInTheDocument();
});
it('clicking Tiny in the idle composer starts live voice on the mascot stage', async () => {
const expandWithVoice = vi.fn();
mascotContext.current = { expandWithVoice };
try {
await renderSelectedConversation();
await act(async () => {
fireEvent.click(screen.getByTestId('composer-human-mode'));
});
expect(expandWithVoice).toHaveBeenCalledTimes(1);
} finally {
mascotContext.current = undefined;
}
});
it('releases the pending-send lock when appendMessage rejects with a generic error', async () => {
vi.mocked(threadApi.appendMessage).mockRejectedValueOnce(new Error('disk full'));
const { textarea } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'will fail locally');
});
const sendButton = screen.getByRole('button', { name: 'Send message' });
await act(async () => {
fireEvent.click(sendButton);
});
// chatSend never runs because the local append failed first.
await waitFor(() => {
expect(threadApi.appendMessage).toHaveBeenCalledTimes(1);
});
expect(chatSend).not.toHaveBeenCalled();
// Pending guard released: the user can re-enter text and the send button
// enables again.
await act(async () => {
setComposerText(textarea, 'retry');
});
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
});
it('releases the pending-send lock when appendMessage hits a stale-thread error', async () => {
vi.mocked(threadApi.appendMessage).mockRejectedValueOnce(
new CoreRpcError('thread missing', 'thread_not_found')
);
const { textarea } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'stale thread send');
});
const sendButton = screen.getByRole('button', { name: 'Send message' });
await act(async () => {
fireEvent.click(sendButton);
});
await waitFor(() => {
expect(threadApi.appendMessage).toHaveBeenCalledTimes(1);
});
expect(chatSend).not.toHaveBeenCalled();
// Stale-thread branch silently clears the guard; typing must re-enable Send.
await act(async () => {
setComposerText(textarea, 'retry');
});
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
});
it('warns but keeps the turn when the 120s silence window elapses', async () => {
// Regression: the watchdog used to clear the runtime and drop the thread
// from the active set after 120s of silence, killing a turn that was still
// reasoning or running a long tool. Silence now only warns; the turn stays
// live and Stop remains the way to end it.
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
const { textarea, store, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'hang the backend');
});
const sendButton = screen.getByRole('button', { name: 'Send message' });
await act(async () => {
fireEvent.click(sendButton);
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
// Fast-forward past the 120s silence window with no inference signals.
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000);
});
const warning = await screen.findByTestId('chat-stall-warning');
expect(warning).toHaveAttribute('data-chat-stall-phase', 'thinking');
expect(warning).toHaveTextContent('Still thinking');
expect(screen.queryByTestId('chat-send-error')).toBeNull();
expect(store!.getState().thread.activeThreadIds[thread.id]).toBe(true);
expect(threadApi.getTurnState).toHaveBeenCalledWith(thread.id);
// The next signal clears the warning — the turn was alive all along.
await act(async () => {
store!.dispatch(bumpInferenceHeartbeatForThread({ threadId: thread.id }));
});
await waitFor(() => {
expect(screen.queryByTestId('chat-stall-warning')).toBeNull();
});
} finally {
vi.useRealTimers();
}
});
// A snapshot describing a turn that is still running, as the core would have
// persisted it at its last flush boundary.
function inFlightSnapshot(lifecycle: 'started' | 'streaming' = 'streaming') {
return {
threadId: 'send-thread',
requestId: 'req-inherited-1',
lifecycle,
iteration: 15,
maxIterations: 50,
phase: 'thinking' as const,
streamingText: '',
thinking: '',
toolTimeline: [],
startedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
}
it('arms the silence timer for a turn inherited through hydration', async () => {
// Regression: `armSilenceTimer` was only called on the local send path, so
// a client that reloaded or reconnected mid-turn hydrated a live-looking
// "Thinking…" pill with no watchdog behind it. If the terminal event was
// then missed the pill never cleared — observed sitting on "Thinking… (15)"
// 25 minutes after the turn had ended.
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.mocked(threadApi.getTurnState).mockResolvedValue(inFlightSnapshot());
try {
const { store } = await renderSelectedConversation();
// Hydration produced a live turn — without this the test could pass by
// asserting a timeout on a thread that was never rendered as running.
await waitFor(() => {
expect(store?.getState().chatRuntime.inferenceStatusByThread['send-thread']).toBeDefined();
});
expect(screen.queryByTestId('chat-send-error')).toBeNull();
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000);
});
// Warned, not torn down: the core still reports the turn running.
expect(await screen.findByTestId('chat-stall-warning')).toBeInTheDocument();
expect(screen.queryByTestId('chat-send-error')).toBeNull();
expect(store?.getState().chatRuntime.inferenceStatusByThread['send-thread']).toBeDefined();
} finally {
vi.mocked(threadApi.getTurnState).mockResolvedValue(null);
vi.useRealTimers();
}
});
it.each(['interrupted', 'completed'] as const)(
'does not arm the silence timer for a %s snapshot',
async lifecycle => {
// A terminal snapshot has no live driver. Arming here would fire a
// spurious silence warning on a thread that has already settled.
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.mocked(threadApi.getTurnState).mockResolvedValue({ ...inFlightSnapshot(), lifecycle });
try {
const { store } = await renderSelectedConversation();
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000);
});
expect(screen.queryByTestId('chat-send-error')).toBeNull();
expect(screen.queryByTestId('chat-stall-warning')).toBeNull();
expect(
store?.getState().chatRuntime.inferenceStatusByThread['send-thread']
).toBeUndefined();
} finally {
vi.mocked(threadApi.getTurnState).mockResolvedValue(null);
vi.useRealTimers();
}
}
);
it('rearms an inherited silence timer on a heartbeat', async () => {
// #4270: a silent reasoning phase emits only heartbeats. A hydrated timer
// must take part in the rearm effect exactly as a locally-armed one does,
// or a genuinely live inherited turn trips the watchdog mid-run.
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.mocked(threadApi.getTurnState).mockResolvedValue(inFlightSnapshot());
try {
const { store } = await renderSelectedConversation();
await waitFor(() => {
expect(store?.getState().chatRuntime.inferenceStatusByThread['send-thread']).toBeDefined();
});
await act(async () => {
await vi.advanceTimersByTimeAsync(80_000);
});
await act(async () => {
store?.dispatch(bumpInferenceHeartbeatForThread({ threadId: 'send-thread' }));
});
await act(async () => {
await vi.advanceTimersByTimeAsync(80_000);
});
// 160s since hydration, but only 80s since the beat — still armed.
expect(screen.queryByTestId('chat-stall-warning')).toBeNull();
// Control: the timer was rearmed, NOT cancelled. Without this, the
// assertion above would pass just as well if the heartbeat had cleared
// the timer outright.
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000);
});
expect(await screen.findByTestId('chat-stall-warning')).toBeInTheDocument();
} finally {
vi.mocked(threadApi.getTurnState).mockResolvedValue(null);
vi.useRealTimers();
}
});
it('arms the silence timer for a prefill turn that has no iteration yet', async () => {
// The hydration reducer writes `inferenceStatusByThread` only when
// `iteration > 0 && maxIterations > 0` and deletes it otherwise, so a turn
// that is genuinely running but has not reported its first iteration —
// initial prefill — hydrates with no status entry. Keying the arming
// decision on that entry alone left exactly this turn unwatched. The
// lifecycle is written regardless of iteration, so it still identifies it.
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.mocked(threadApi.getTurnState).mockResolvedValue({
...inFlightSnapshot('started'),
iteration: 0,
maxIterations: 0,
});
try {
const { store } = await renderSelectedConversation();
// Precondition that makes this test meaningful: hydration produced a live
// lifecycle but NO status entry. If this ever flips, the test is no
// longer covering the prefill gap it was written for.
await waitFor(() => {
expect(store?.getState().chatRuntime.inferenceTurnLifecycleByThread['send-thread']).toBe(
'started'
);
});
expect(store?.getState().chatRuntime.inferenceStatusByThread['send-thread']).toBeUndefined();
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000);
});
expect(await screen.findByTestId('chat-stall-warning')).toBeInTheDocument();
} finally {
vi.mocked(threadApi.getTurnState).mockResolvedValue(null);
vi.useRealTimers();
}
});
it('does not schedule a silence timer once the page has unmounted', async () => {
// The send path awaits `addMessageLocal` before arming, so an unmount that
// lands inside that await runs the cleanup — which finds nothing — and the
// continuation would then schedule a timer no cleanup can ever reach.
// Nothing can rearm it either, so it would survive to clear shared runtime
// state for a turn that may still be live.
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.mocked(threadApi.getTurnState).mockResolvedValue(inFlightSnapshot());
try {
const { store } = await renderSelectedConversation();
await waitFor(() => {
expect(store?.getState().chatRuntime.inferenceStatusByThread['send-thread']).toBeDefined();
});
// Tear down, then let hydration's own effects settle. Any arming that
// happens after this point is arming onto a dead instance.
await act(async () => {
cleanup();
});
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000);
});
expect(store?.getState().chatRuntime.inferenceStatusByThread['send-thread']).toBeDefined();
} finally {
vi.mocked(threadApi.getTurnState).mockResolvedValue(null);
vi.useRealTimers();
}
});
it('does not fire an armed silence timer after the page unmounts', async () => {
// The timer's callback outlives this component: it dispatches
// `clearRuntimeForThread` / `clearThreadInferenceActive` into the shared
// store. Left armed past teardown it would wipe the runtime of a turn that
// is still in flight, up to 120s after the user navigated away.
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.mocked(threadApi.getTurnState).mockResolvedValue(inFlightSnapshot());
try {
const { store } = await renderSelectedConversation();
// Prove a timer was actually armed, so this cannot pass by unmounting a
// page that never had one.
await waitFor(() => {
expect(store?.getState().chatRuntime.inferenceStatusByThread['send-thread']).toBeDefined();
});
await act(async () => {
cleanup();
});
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000);
});
// Still present: the cleanup cleared the timer, so nothing dispatched.
expect(store?.getState().chatRuntime.inferenceStatusByThread['send-thread']).toBeDefined();
} finally {
vi.mocked(threadApi.getTurnState).mockResolvedValue(null);
vi.useRealTimers();
}
});
it('rearms the silence timer on sub-agent tool-timeline updates', async () => {
// Regression: when a delegated sub-agent (`Research`, `Tools Agent`,
// …) is running, the parent thread's `inferenceStatusByThread` and
// `streamingAssistantByThread` references can stay put while
// `toolTimelineByThread` ticks. The rearm effect must watch that timeline —
// otherwise a long sub-agent loop
// trips the 120s silence warning even though the user can see tools
// firing in the timeline.
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
const { textarea, store, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'kick off a sub-agent loop');
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
// Two-thirds of the way through the safety window, the parent
// status is already in `subagent` phase and a delegated tool
// posts a timeline update. After the fix this re-arms the timer.
await act(async () => {
await vi.advanceTimersByTimeAsync(80_000);
});
await act(async () => {
store!.dispatch(
setInferenceStatusForThread({
threadId: thread.id,
status: { phase: 'subagent', iteration: 1, maxIterations: 8 },
})
);
store!.dispatch(
setToolTimelineForThread({
threadId: thread.id,
entries: [{ id: 'tl-1', name: 'web_fetch', round: 1, seq: 0, status: 'running' }],
})
);
});
// Advance another 80s (total elapsed 160s, well past the 120s
// window). The tool-timeline dispatch should have re-armed the
// timer at the 80s mark, so the silence timer is now at 80s of
// its fresh 120s budget and has NOT fired — the thread therefore
// shows no silence warning.
await act(async () => {
await vi.advanceTimersByTimeAsync(80_000);
});
expect(screen.queryByTestId('chat-stall-warning')).toBeNull();
expect(store!.getState().thread.activeThreadIds[thread.id]).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('rearms the silence timer on inference heartbeat beats during a silent reasoning phase (#4270)', async () => {
// Repro for #4270: a long prefill on a large context, or a reasoning-tier
// model that buffers `reasoning_content` server-side, streams NO status /
// text / tool / board signal for minutes. The core now emits a periodic
// `inference_heartbeat`; the rearm effect must treat it as liveness so the
// 120s silence timer never false-fires while the turn is genuinely working.
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
const { textarea, store, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'summarize a big codebase in reasoning mode');
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
// 200s elapse in 20s steps — only a heartbeat each step, nothing else.
// Without the #4270 fix the 120s timer would fire around the 6th step.
for (let i = 0; i < 10; i++) {
await act(async () => {
await vi.advanceTimersByTimeAsync(20_000);
});
await act(async () => {
store!.dispatch(bumpInferenceHeartbeatForThread({ threadId: thread.id }));
});
}
// The beats kept rearming the timer → no warning, turn still active.
expect(screen.queryByTestId('chat-stall-warning')).toBeNull();
expect(store!.getState().thread.activeThreadIds[thread.id]).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('surfaces a warning when heartbeats stop, without killing the turn (#4270)', async () => {
// The heartbeat is the liveness signal, so a real connectivity drop
// (core/socket dead → no more beats) must still be surfaced after 120s —
// as a warning. The turn is not cleared: the core may still be working,
// and Stop is how the user ends it.
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
const { textarea, store, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'task whose connection dies');
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
// A couple of early beats, then silence (the socket died).
await act(async () => {
await vi.advanceTimersByTimeAsync(20_000);
});
await act(async () => {
store!.dispatch(bumpInferenceHeartbeatForThread({ threadId: thread.id }));
});
// No more beats for a full 120s window → the warning appears, and the
// thread stays active.
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000);
});
expect(await screen.findByTestId('chat-stall-warning')).toBeInTheDocument();
expect(store!.getState().thread.activeThreadIds[thread.id]).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('warns the turn may be stuck when nothing is running past the window', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
const { textarea, store, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'run a slow shell loop');
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
await act(async () => {
store!.dispatch(
setInferenceStatusForThread({
threadId: thread.id,
status: { phase: 'tool_use', iteration: 2, maxIterations: 8 },
})
);
});
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000);
});
const warning = await screen.findByTestId('chat-stall-warning');
expect(warning).toHaveAttribute('data-chat-stall-phase', 'tool_use');
expect(warning).toHaveTextContent('No new output for');
expect(store!.getState().thread.activeThreadIds[thread.id]).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('names a still-running tool instead of warning the turn is stuck', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
const { textarea, store, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'run a slow shell loop');
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
await act(async () => {
store!.dispatch(
setInferenceStatusForThread({
threadId: thread.id,
status: { phase: 'tool_use', iteration: 2, maxIterations: 8 },
})
);
});
await act(async () => {
store!.dispatch(
setToolTimelineForThread({
threadId: thread.id,
entries: [
{
id: 'tl-shell',
name: 'shell',
round: 2,
seq: 0,
status: 'running',
argsBuffer: '{"command":"cargo build"}',
},
// A detached run from an earlier turn, hydrated from the run
// ledger after this turn's call: issued later, still running,
// but not this turn's work.
{
id: 'subagent:run-old',
name: 'subagent:researcher',
round: 0,
seq: 1,
status: 'running',
sourceToolName: 'run_ledger',
},
],
})
);
});
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000);
});
const warning = await screen.findByTestId('chat-stall-warning');
expect(warning).toHaveAttribute('data-chat-stall-phase', 'tool_use');
expect(warning).toHaveAttribute('data-chat-stall-state', 'tool');
expect(warning).toHaveTextContent('Running command.');
expect(warning).not.toHaveTextContent('may be stuck');
expect(store!.getState().thread.activeThreadIds[thread.id]).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('settles quietly when the core reports the silent turn already completed', async () => {
// The one case the watchdog may clear local state: the core says the turn
// is over, so its terminal event was lost. Nothing live is discarded, and
// no warning is shown for a turn that finished.
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
const { textarea, store, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'turn whose done event is lost');
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
expect(store!.getState().thread.activeThreadIds[thread.id]).toBe(true);
vi.mocked(threadApi.getTurnState).mockResolvedValue({
threadId: thread.id,
requestId: 'req-done',
lifecycle: 'completed',
iteration: 3,
maxIterations: 8,
phase: 'thinking' as const,
streamingText: '',
thinking: '',
toolTimeline: [],
startedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
});
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000);
});
await waitFor(() => {
expect(store!.getState().thread.activeThreadIds[thread.id]).toBeFalsy();
});
expect(screen.queryByTestId('chat-stall-warning')).toBeNull();
expect(screen.queryByTestId('chat-send-error')).toBeNull();
} finally {
vi.mocked(threadApi.getTurnState).mockResolvedValue(null);
vi.useRealTimers();
}
});
it('does NOT rearm the silence timer on an unrelated thread’s updates', async () => {
// Regression for the per-thread dependency scoping: the rearm effect must
// react only to the SENDING thread's slices. A different thread churning
// (background triage, another conversation) must not keep the foreground
// turn's 120s timer alive — otherwise a truly silent send never warns.
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
const { textarea, store } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'send on the foreground thread');
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
// Churn an UNRELATED thread the whole time the foreground send is open.
// None of these dispatches target the sending thread ('send-thread'),
// so they must not rearm its timer.
await act(async () => {
await vi.advanceTimersByTimeAsync(80_000);
});
await act(async () => {
store!.dispatch(
setInferenceStatusForThread({
threadId: 'some-other-thread',
status: { phase: 'subagent', iteration: 3, maxIterations: 8 },
})
);
store!.dispatch(
setToolTimelineForThread({
threadId: 'some-other-thread',
entries: [{ id: 'other-1', name: 'web_fetch', round: 1, seq: 0, status: 'running' }],
})
);
});
// Cross the original 120s deadline (80s + 50s = 130s). Because the
// unrelated-thread churn did NOT rearm, the silence warning fires.
await act(async () => {
await vi.advanceTimersByTimeAsync(50_000);
});
expect(await screen.findByTestId('chat-stall-warning')).toBeInTheDocument();
} finally {
vi.useRealTimers();
}
});
it('releases the pending-send lock when chatSend rejects', async () => {
vi.mocked(chatSend).mockRejectedValueOnce(new Error('emit failed'));
const { textarea } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'doomed send');
});
await waitFor(() => {
expect(textarea).toHaveTextContent('doomed send');
});
const sendButton = screen.getByRole('button', { name: 'Send message' });
await act(async () => {
fireEvent.click(sendButton);
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledTimes(1);
});
// After the failed send, typing again should leave the composer enabled so
// the user can retry — proves the pending guard was released.
await act(async () => {
setComposerText(textarea, 'retry send');
});
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
});
it('restores the draft when saving the prompt locally fails', async () => {
vi.mocked(threadApi.appendMessage).mockRejectedValueOnce(new Error('disk full'));
const { textarea } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'do not lose me');
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalled());
expect(chatSend).not.toHaveBeenCalled();
await waitFor(() => expect(textarea).toHaveTextContent('do not lose me'));
});
it('gives a failed draft back to its own thread after the user switched away', async () => {
const saveDraft = vi.spyOn(userScopedStorage, 'setItem').mockResolvedValue(undefined);
let rejectPersist!: (reason: unknown) => void;
vi.mocked(threadApi.appendMessage).mockReturnValueOnce(
new Promise((_resolve, reject) => {
rejectPersist = reject;
})
);
const { store, textarea, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'draft for the first thread');
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalled());
await act(async () => {
store!.dispatch(setSelectedThread('another-thread'));
});
await act(async () => {
rejectPersist(new Error('disk full'));
});
const composer = await screen.findByRole('textbox', { name: 'Message input' });
expect(composer).not.toHaveTextContent('draft for the first thread');
await waitFor(() =>
expect(saveDraft).toHaveBeenCalledWith(
draftStorageKey(thread.id),
'draft for the first thread'
)
);
saveDraft.mockRestore();
});
it('sends with Enter when the composer is not composing text', async () => {
const { textarea, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'enter send');
});
await waitFor(() => {
expect(textarea).toHaveTextContent('enter send');
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
await act(async () => {
fireEvent.keyDown(textarea, { key: 'Enter' });
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledWith(
expect.objectContaining({
threadId: thread.id,
message: 'enter send',
locale: 'en',
reasoningEffort: 'default',
})
);
expect(vi.mocked(chatSend).mock.calls[0][0]).not.toHaveProperty('model');
});
});
it('does not send while an IME composition key event is confirming text', async () => {
const { textarea } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, '你好');
});
await waitFor(() => {
expect(textarea).toHaveTextContent('你好');
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
await act(async () => {
const event = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true });
Object.defineProperty(event, 'isComposing', { value: true });
textarea.dispatchEvent(event);
});
expect(chatSend).not.toHaveBeenCalled();
expect(textarea).toHaveTextContent('你好');
});
it('does not send for legacy IME keyCode 229 events', async () => {
const { textarea } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, 'かな');
});
await waitFor(() => {
expect(textarea).toHaveTextContent('かな');
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
await act(async () => {
fireEvent.keyDown(textarea, { key: 'Enter', keyCode: 229 });
});
expect(chatSend).not.toHaveBeenCalled();
expect(textarea).toHaveTextContent('かな');
});
it('does not send while composition is active even if keydown lacks IME flags', async () => {
const { textarea, thread } = await renderSelectedConversation();
await act(async () => {
setComposerText(textarea, '안녕');
});
await waitFor(() => {
expect(textarea).toHaveTextContent('안녕');
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
await act(async () => {
fireEvent.compositionStart(textarea);
fireEvent.keyDown(textarea, { key: 'Enter' });
});
expect(chatSend).not.toHaveBeenCalled();
expect(textarea).toHaveTextContent('안녕');
await act(async () => {
fireEvent.compositionEnd(textarea);
fireEvent.keyDown(textarea, { key: 'Enter' });
});
await waitFor(() => {
expect(chatSend).toHaveBeenCalledWith(
expect.objectContaining({
threadId: thread.id,
message: '안녕',
locale: 'en',
reasoningEffort: 'default',
})
);
expect(vi.mocked(chatSend).mock.calls[0][0]).not.toHaveProperty('model');
});
});
// The General/Tasks filter chips were removed — the thread list is now fixed
// to the General bucket with no in-sidebar bucket switcher. Task/worker
// threads have a dedicated surface.
it('does not render the removed bucket filter tabs', async () => {
await act(async () => {
await renderConversations({ thread: emptyThreadState });
});
// Sidebar is hidden by default — open it first.
await openSidebar();
expect(screen.queryByRole('tab', { name: 'General' })).not.toBeInTheDocument();
expect(screen.queryByRole('tab', { name: 'Tasks' })).not.toBeInTheDocument();
});
});
// #1624 — When a worker thread is the active selection, the header surfaces
// a "back to <parent title>" button that navigates the user back to the
// parent conversation. Covers the `selectedThreadParent` derivation and the
// click handler that dispatches setSelectedThread + loadThreadMessages.
describe('Conversations — active-thread restore across in-app navigation', () => {
beforeEach(() => {
vi.clearAllMocks();
mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });
});
it('restores a non-General active session on remount instead of spawning a new chat', async () => {
const taskThread = makeThread({
id: 'task-active-1',
title: 'Active task session',
labels: ['tasks'],
});
// Only the (hidden) task session exists — pre-fix this falls through to
// handleCreateNewThread and replaces the active session with a new chat.
mockGetThreads.mockResolvedValue({ threads: [taskThread], count: 1 });
let store: ReturnType<typeof buildStore> | undefined;
await act(async () => {
store = await renderConversations({
thread: {
...emptyThreadState,
threads: [taskThread],
selectedThreadId: 'task-active-1',
messagesByThreadId: { 'task-active-1': [] },
},
});
});
await waitFor(() => {
expect(store!.getState().thread.selectedThreadId).toBe('task-active-1');
});
expect(threadApi.createNewThread).not.toHaveBeenCalled();
expect(mockGetThreadMessages).toHaveBeenCalledWith('task-active-1');
});
it('keeps the General-only sidebar while restoring a non-General session', async () => {
const taskThread = makeThread({
id: 'task-active-2',
title: 'Restored task',
labels: ['tasks'],
});
mockGetThreads.mockResolvedValue({ threads: [taskThread], count: 1 });
await act(async () => {
await renderConversations({
thread: {
...emptyThreadState,
threads: [taskThread],
selectedThreadId: 'task-active-2',
messagesByThreadId: { 'task-active-2': [] },
},
});
});
await waitFor(() => {
expect(threadApi.createNewThread).not.toHaveBeenCalled();
});
// Main removed the visible General/Tasks chips; restoring a
// task session should not reintroduce that tab UI.
await openSidebar();
expect(screen.queryByRole('tab', { name: 'Tasks' })).not.toBeInTheDocument();
});
it('reuses an empty General thread when there is no active selection', async () => {
// Fresh session (no persisted selection) keeps main's new-window behaviour:
// reuse an existing empty General thread rather than spawning duplicates.
const threads = [makeThread({ id: 'g-1', title: 'Recent general' })];
mockGetThreads.mockResolvedValue({ threads, count: 1 });
let store: ReturnType<typeof buildStore> | undefined;
await act(async () => {
store = await renderConversations({ thread: emptyThreadState });
});
await waitFor(() => {
expect(store!.getState().thread.selectedThreadId).toBe('g-1');
});
expect(threadApi.createNewThread).not.toHaveBeenCalled();
});
it('opens a new chat for a genuinely fresh session with no threads', async () => {
mockGetThreads.mockResolvedValue({ threads: [], count: 0 });
await act(async () => {
await renderConversations({ thread: emptyThreadState });
});
await waitFor(() => {
expect(threadApi.createNewThread).toHaveBeenCalled();
});
});
});
describe('Conversations — queued follow-ups while a turn streams', () => {
// Reset shared mock call history + defaults per test so `toHaveBeenCalledWith`
// assertions reflect only the current case (not bleed from an earlier one).
beforeEach(() => {
vi.clearAllMocks();
mockGetThreads.mockResolvedValue({ threads: [], count: 0 });
mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });
vi.mocked(chatSend).mockResolvedValue(undefined);
vi.mocked(chatRemoveQueueItem).mockResolvedValue(true);
});
// A selected thread that is actively streaming (`activeThreadIds`) keeps the
// composer open for follow-up queueing — the placeholder flips to the
// follow-up hint and a plain-Enter / Send submission queues a follow-up.
async function renderStreamingConversation() {
const thread = makeThread({ id: 'fup-thread', title: 'FUP Thread' });
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });
let store: ReturnType<typeof buildStore> | undefined;
await act(async () => {
store = await renderConversations({
thread: { ...selectedThreadState(thread), activeThreadIds: { [thread.id]: true } },
socket: socketState('connected'),
});
});
const textarea = await screen.findByRole('textbox', { name: 'Message input' });
return { store, textarea, thread };
}
// What the core emits once it accepts a follow-up into the run queue.
function coreQueues(store: ReturnType<typeof buildStore> | undefined, id: string, text: string) {
act(() => {
store?.dispatch(
queueItemQueued({ threadId: 'fup-thread', item: { id, text_preview: text } })
);
});
}
it('queues a plain-Enter submission as a follow-up and keeps it for the transcript', async () => {
const { store, textarea } = await renderStreamingConversation();
await act(async () => {
setComposerText(textarea, 'and the pricing?');
});
await act(async () => {
fireEvent.keyDown(textarea, { key: 'Enter' });
});
await waitFor(() => {
expect(chatSendWithAck).toHaveBeenCalledWith(
expect.objectContaining({ queueMode: 'followup' })
);
});
await waitFor(() =>
expect(
store?.getState().queue.pendingFollowupsByThread['fup-thread']?.map(p => p.preview)
).toEqual(['and the pricing?'])
);
});
it('queues via the Send button while a turn streams', async () => {
const { textarea } = await renderStreamingConversation();
await act(async () => {
setComposerText(textarea, 'one more thing');
});
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
await waitFor(() => {
expect(chatSendWithAck).toHaveBeenCalledWith(
expect.objectContaining({ queueMode: 'followup' })
);
});
});
it("lists the core's queued items above the composer", async () => {
const { store } = await renderStreamingConversation();
expect(screen.queryByTestId('queued-followups')).not.toBeInTheDocument();
coreQueues(store, 'q1', 'and the pricing?');
const strip = await screen.findByTestId('queued-followups');
expect(within(strip).getByText('and the pricing?')).toBeInTheDocument();
});
it('removes a queued item through the core', async () => {
const { store } = await renderStreamingConversation();
coreQueues(store, 'q1', 'dismiss me');
const strip = await screen.findByTestId('queued-followups');
await act(async () => {
fireEvent.click(
within(strip).getByRole('button', { name: 'Remove "dismiss me" from the queue' })
);
});
await waitFor(() => expect(chatRemoveQueueItem).toHaveBeenCalledWith('fup-thread', 'q1'));
await waitFor(() => expect(screen.queryByTestId('queued-followups')).not.toBeInTheDocument());
});
it('keeps the queued item when the core does not confirm the removal', async () => {
vi.mocked(chatRemoveQueueItem).mockResolvedValueOnce(false);
const { store } = await renderStreamingConversation();
coreQueues(store, 'q1', 'still queued');
const strip = await screen.findByTestId('queued-followups');
await act(async () => {
fireEvent.click(
within(strip).getByRole('button', { name: 'Remove "still queued" from the queue' })
);
});
await waitFor(() => expect(chatRemoveQueueItem).toHaveBeenCalledWith('fup-thread', 'q1'));
// The core still holds it and will send it, so it stays on screen.
expect(
within(screen.getByTestId('queued-followups')).getByText('still queued')
).toBeInTheDocument();
});
it('keeps the draft intact when the follow-up send fails', async () => {
vi.mocked(chatSendWithAck).mockRejectedValueOnce(new Error('send boom'));
const { store, textarea } = await renderStreamingConversation();
await act(async () => {
setComposerText(textarea, 'keep me on failure');
});
await act(async () => {
fireEvent.keyDown(textarea, { key: 'Enter' });
});
// Send rejected → nothing recorded for the transcript, and the composer
// keeps the user's text so they can retry instead of silently losing it.
await waitFor(() => expect(chatSendWithAck).toHaveBeenCalled());
expect(store?.getState().queue.pendingFollowupsByThread['fup-thread']).toBeUndefined();
expect(textarea).toHaveTextContent('keep me on failure');
});
});
describe('Conversations — external-transfer disclosure card removed', () => {
beforeEach(() => {
vi.clearAllMocks();
window.localStorage.clear();
mockGetThreads.mockResolvedValue({ threads: [], count: 0 });
mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });
});
it('never renders a "Leaving your device" card', async () => {
const thread = makeThread({ id: 't-sel' });
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
await act(async () => {
await renderConversations({
thread: selectedThreadState(thread),
socket: socketState('connected'),
});
});
expect(screen.queryByText('Leaving your device')).toBeNull();
});
});
/**
* The two turn gates the agent parks on. Both used to render only inside the
* legacy voice-mode panel, which `/chat` never mounted, so a parked plan review
* hung the turn with nothing to decide, and a `propose_workflow` draft lost its
* only route to `flows_create`. They are now rendered from the shared
* `agentGateCards` fragment, which the assistant-ui composer header carries.
*/
describe('Conversations — turn gates on the assistant-ui surface', () => {
beforeEach(() => {
vi.clearAllMocks();
window.localStorage.clear();
mockGetThreads.mockResolvedValue({ threads: [], count: 0 });
mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });
});
async function renderGatedConversation() {
const thread = makeThread({ id: 'gate-thread', title: 'Gate Thread' });
mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });
mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });
let store: ReturnType<typeof buildStore> | undefined;
await act(async () => {
store = await renderConversations({
thread: selectedThreadState(thread),
socket: socketState('connected'),
});
});
// The default composer is 'text', so this is the assistant-ui panel — the
// legacy panel is not in the tree at all.
expect(screen.getByTestId('chat-message-input')).toBeInTheDocument();
return { thread, store: store! };
}
it('surfaces a parked plan review above the assistant-ui composer', async () => {
const { thread, store } = await renderGatedConversation();
await act(async () => {
store.dispatch(
setPendingPlanReviewForThread({
threadId: thread.id,
review: {
requestId: 'plan-req-1',
summary: 'Refactor the billing module',
steps: ['Read the invoices module', 'Extract the tax helper'],
},
})
);
});
const card = await screen.findByTestId('plan-review-card');
expect(card).toBeInTheDocument();
expect(within(card).getByText('Refactor the billing module')).toBeInTheDocument();
expect(within(card).getByText('Extract the tax helper')).toBeInTheDocument();
});
it('surfaces a drafted workflow proposal above the assistant-ui composer', async () => {
const { thread, store } = await renderGatedConversation();
await act(async () => {
store.dispatch(
setWorkflowProposalForThread({
threadId: thread.id,
proposal: {
name: 'Morning digest',
graph: { nodes: [], edges: [] },
requireApproval: false,
summary: {
trigger: 'schedule: 0 9 * * *',
steps: [{ kind: 'agent', name: 'Summarize inbox' }],
},
},
})
);
});
const card = await screen.findByTestId('workflow-proposal-card');
expect(card).toBeInTheDocument();
expect(within(card).getByText('Morning digest')).toBeInTheDocument();
});
it('keeps half-typed plan feedback across an unrelated host re-render', async () => {
const { thread, store } = await renderGatedConversation();
await act(async () => {
store.dispatch(
setPendingPlanReviewForThread({
threadId: thread.id,
review: { requestId: 'plan-req-2', summary: 'Ship it', steps: [] },
})
);
});
// The feedback textarea is revealed by the "Revise" decision button
// (`PlanReviewCardCore` in `aui/PlanReviewPart.tsx`) rather than shown
// unconditionally, unlike the old `PlanReviewCard.tsx` this replaced.
await act(async () => {
fireEvent.click(screen.getByText('Revise'));
});
const feedback = await screen.findByTestId('plan-review-feedback');
await act(async () => {
fireEvent.change(feedback, { target: { value: 'use the staging bucket' } });
});
expect(screen.getByTestId('plan-review-feedback')).toHaveValue('use the staging bucket');
// Any unrelated re-render of Conversations rebuilds the composer-header
// node. The header is rendered by component type (`thread.tsx`), so a
// header component that closes over that node changes type every render and
// React remounts the whole subtree — silently wiping this textarea.
await act(async () => {
store.dispatch(bumpInferenceHeartbeatForThread({ threadId: thread.id }));
store.dispatch(
setStreamingAssistantForThread({
threadId: thread.id,
streaming: { requestId: 'req-x', content: 'thinking out loud', thinking: '' },
})
);
});
expect(screen.getByTestId('plan-review-feedback')).toHaveValue('use the staging bucket');
});
});