Skip to content

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

fix(chat): restore the composer-adjacent cards on the assistant-ui surface

M3gA-Mind5b2929227f7e
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsx
index 3c1cc21999..3dd93c2bbb 100644
--- a/app/src/features/conversations/Conversations.tsx
+++ b/app/src/features/conversations/Conversations.tsx
@@ -19,6 +19,7 @@ import WorkflowProposalCard from '../../components/chat/WorkflowProposalCard';
import { ConfirmationModal } from '../../components/intelligence/ConfirmationModal';
import { SidebarContent } from '../../components/layout/shell/SidebarSlot';
import { AssistantUiChat } from '../../features/conversations/components/AssistantUiChat';
+import { TranscriptOverlays } from '../../features/conversations/components/aui/TranscriptOverlays';
import { selectBackgroundProcesses } from '../../features/conversations/components/BackgroundProcessesPanel';
import {
ChatThreadView,
@@ -58,6 +59,7 @@ import {
parseMessageImages,
validateAndReadFile,
} from '../../lib/attachments';
+import { useRegisterAction } from '../../lib/commands/useRegisterAction';
import { useT } from '../../lib/i18n/I18nContext';
import { threadApi } from '../../services/api/threadApi';
import { fetchThreadTokenUsage } from '../../services/api/threadUsageApi';
@@ -291,6 +293,28 @@ const Conversations = ({
// (its state now lives inside `ChatThreadView`) so the header badge below
// can still open it without lifting that state back up.
const threadViewRef = useRef<ChatThreadViewHandle>(null);
+ // Disclosure state for the three transcript-local overlays on the
+ // assistant-ui surface. `ChatThreadView` owns an identical trio for the
+ // legacy voice panel, but it is not mounted on `/chat` any more, so the
+ // panels it hosts (background processes, the sub-agent drawer, the Agent
+ // Process Source panel) had no host at all there.
+ const [showBackgroundProcesses, setShowBackgroundProcesses] = useState(false);
+ const [openSubagentTaskId, setOpenSubagentTaskId] = useState<string | null>(null);
+ const [showProcessSource, setShowProcessSource] = useState(false);
+ // The Agent Process Source panel's only trigger is the "View full agent
+ // process source →" link at the foot of `ToolTimelineBlock` — a legacy-panel
+ // component. assistant-ui renders its tool calls as inline cards and has no
+ // equivalent block, so the whole-run view (and the visited-source list, which
+ // exists nowhere else) is reached from the command palette instead.
+ useRegisterAction({
+ id: 'chat.agentProcessSource',
+ label: 'Open agent process source',
+ labelKey: 'conversations.agentTaskInsights.viewProcessSource',
+ group: 'Chat',
+ handler: () => setShowProcessSource(true),
+ enabled: () => selectedThreadId !== null,
+ keywords: ['agent', 'process', 'source', 'timeline', 'run'],
+ });
const [inputMode, setInputMode] = useState<InputMode>('text');
const [replyMode, setReplyMode] = useState<ReplyMode>('text');
const [isRecording, setIsRecording] = useState(false);
@@ -1990,6 +2014,172 @@ const Conversations = ({
</>
);
+ // ── Composer-adjacent surfaces shared by BOTH chat panels ─────────────────
+ //
+ // Every one of these used to be written inline inside `legacyMainPanel`.
+ // The panel choice at the bottom of this component is an *either/or*
+ // (`composer === 'mic-cloud' ? legacyMainPanel : assistantUiMainPanel`), so
+ // when the text chat moved to the assistant-ui `Thread` they stopped
+ // rendering on `/chat` altogether — the send-error banner most damagingly,
+ // since a user whose send is rejected got no feedback of any kind.
+ //
+ // They are defined once here and rendered by both panels: the legacy voice
+ // footer below, and the assistant-ui `ComposerHeader` / `ComposerExtras`
+ // slots (`assistantComposerHeader` / `assistantComposerFooterExtras`). One
+ // definition is the point — a second copy is how they drifted apart before.
+
+ const sendAdvisoryBanner = sendAdvisory ? (
+ <div className="flex items-center justify-between mb-2">
+ <p className="text-xs text-amber-700" data-chat-send-advisory>
+ {sendAdvisory}
+ </p>
+ <button
+ type="button"
+ data-analytics-id="chat-send-advisory-dismiss"
+ onClick={() => setSendAdvisory(null)}
+ className="text-xs text-content-muted hover:text-content-secondary transition-colors ml-2">
+ {t('common.dismiss')}
+ </button>
+ </div>
+ ) : null;
+
+ const sendErrorBanner = displayedSendError ? (
+ <div className="flex items-center justify-between mb-2">
+ <p
+ className="text-xs text-coral-500"
+ data-testid="chat-send-error"
+ data-chat-send-error-code={displayedSendError.code}>
+ {displayedSendError.message}
+ </p>
+ <div className="flex items-center gap-2 shrink-0 ml-2">
+ {(displayedSendError.code === 'stt_not_ready' ||
+ displayedSendError.code === 'voice_transcription' ||
+ displayedSendError.code === 'tts_not_ready' ||
+ displayedSendError.code === 'voice_synthesis') && (
+ <button
+ type="button"
+ data-analytics-id="chat-send-error-setup"
+ onClick={() => {
+ setSendError(null);
+ // STT/TTS provider settings live on the Voice panel
+ // since PR 2; the legacy local-model route was for
+ // back when speech assets were lumped with Ollama.
+ navigate('/settings/voice');
+ }}
+ className="text-xs text-primary-500 hover:text-primary-600 font-medium transition-colors">
+ {t('chat.setup')}
+ </button>
+ )}
+ <button
+ type="button"
+ data-analytics-id="chat-send-error-dismiss"
+ onClick={() => {
+ setSendError(null);
+ dispatch(clearCreateThreadError());
+ }}
+ className="text-xs text-content-muted hover:text-content-secondary transition-colors">
+ {t('common.dismiss')}
+ </button>
+ </div>
+ </div>
+ ) : null;
+
+ // Flow-approval surface (chat): actionable banner(s) for paused tinyflows
+ // runs, pushed via the `flow_approval_request` socket event (issue:
+ // flow-approval surfacing). Not gated on the selected thread — see the hook
+ // call above for why — so every pending request renders regardless of which
+ // thread is open.
+ const flowApprovalDeck =
+ flowApprovalRequests.length > 0 ? (
+ <div className="mb-2 flex flex-col gap-2">
+ {flowApprovalRequests.map(request => (
+ <FlowApprovalRequestCard
+ key={request.request_id}
+ request={request}
+ onResolved={dismissFlowApprovalRequest}
+ />
+ ))}
+ </div>
+ ) : null;
+
+ // Surface in-flight + failed artifact cards above the composer (#2779).
+ // Mirrors the approval-card placement so the user sees the spinner / error
+ // without scrolling. `ready` cards are delegated to the header ChatFilesChip
+ // panel (#3024) so the chat scroll area isn't permanently occupied —
+ // restored decks are listable from the chip on demand.
+ //
+ // The failed-card Retry button re-dispatches the producing tool via
+ // `ai_regenerate` (#3162): the core reloads the persisted creation args and
+ // re-runs generation under the original artifact id, so the card swaps back
+ // to a spinner in place and then to ready/failed via the socket events.
+ const artifactDeckThreadId = selectedThreadId ?? firstActiveThreadId;
+ const liveArtifacts = artifactDeckThreadId
+ ? (artifactsByThread[artifactDeckThreadId] ?? []).filter(a => a.status !== 'ready')
+ : [];
+ const liveArtifactDeck =
+ liveArtifacts.length > 0 && artifactDeckThreadId ? (
+ <div className="mb-2 flex flex-col gap-2">
+ {liveArtifacts.map(artifact => (
+ <ArtifactCard
+ key={artifact.artifactId}
+ artifact={artifact}
+ onRetry={id => {
+ void aiRegenerate(id, artifactDeckThreadId).catch(err => {
+ console.warn('[artifact] regenerate failed:', err);
+ });
+ }}
+ />
+ ))}
+ </div>
+ ) : null;
+
+ const chatFilesChip =
+ (selectedThreadId ?? firstActiveThreadId) ? (
+ <ChatFilesChip threadId={(selectedThreadId ?? firstActiveThreadId) as string} />
+ ) : null;
+
+ // The control that opens the background-processes panel, plus its
+ // running-count / memory-sync badge. Takes its opener because each surface
+ // hosts its own panel: the legacy footer reaches into `ChatThreadView`'s
+ // imperative handle, the assistant-ui footer drives the overlay state above.
+ const renderBackgroundProcessesButton = (onOpen: () => void) =>
+ selectedThreadId ? (
+ <button
+ type="button"
+ data-testid="background-processes-toggle"
+ data-analytics-id="chat-header-background-processes"
+ onClick={onOpen}
+ aria-label={t('conversations.backgroundTasks.title')}
+ title={
+ backgroundProcesses.length > 0
+ ? t('conversations.backgroundTasks.titleWithCount').replace(
+ '{count}',
+ String(backgroundProcesses.length)
+ )
+ : t('conversations.backgroundTasks.title')
+ }
+ className="relative flex h-7 w-7 items-center justify-center rounded-lg text-content-muted transition-colors hover:bg-surface-hover hover:text-content-secondary">
+ <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"
+ />
+ </svg>
+ {runningBackgroundCount > 0 ? (
+ <span className="absolute -right-0.5 -top-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-amber-500 px-0.5 text-[9px] font-semibold leading-none text-content-inverted">
+ {runningBackgroundCount}
+ </span>
+ ) : memorySyncActive ? (
+ <span
+ data-testid="background-activity-dot"
+ className="absolute -right-0.5 -top-0.5 h-2 w-2 animate-pulse rounded-full bg-amber-500"
+ />
+ ) : null}
+ </button>
+ ) : null;
+
// Main chat area (right pane): header, message list, composer.
const legacyMainPanel = (
<div
@@ -2064,20 +2254,7 @@ const Conversations = ({
}>
<>{/* Cycle usage pill moved into ChatComposer toolbar */}</>
- {sendAdvisory && (
- <div className="flex items-center justify-between mb-2">
- <p className="text-xs text-amber-700" data-chat-send-advisory>
- {sendAdvisory}
- </p>
- <button
- type="button"
- data-analytics-id="chat-send-advisory-dismiss"
- onClick={() => setSendAdvisory(null)}
- className="text-xs text-content-muted hover:text-content-secondary transition-colors ml-2">
- {t('common.dismiss')}
- </button>
- </div>
- )}
+ {sendAdvisoryBanner}
{attachError && (
<div className="flex items-center justify-between mb-2">
@@ -2094,45 +2271,7 @@ const Conversations = ({
</div>
)}
- {displayedSendError && (
- <div className="flex items-center justify-between mb-2">
- <p
- className="text-xs text-coral-500"
- data-chat-send-error-code={displayedSendError.code}>
- {displayedSendError.message}
- </p>
- <div className="flex items-center gap-2 shrink-0 ml-2">
- {(displayedSendError.code === 'stt_not_ready' ||
- displayedSendError.code === 'voice_transcription' ||
- displayedSendError.code === 'tts_not_ready' ||
- displayedSendError.code === 'voice_synthesis') && (
- <button
- type="button"
- data-analytics-id="chat-send-error-setup"
- onClick={() => {
- setSendError(null);
- // STT/TTS provider settings live on the Voice panel
- // since PR 2; the legacy local-model route was for
- // back when speech assets were lumped with Ollama.
- navigate('/settings/voice');
- }}
- className="text-xs text-primary-500 hover:text-primary-600 font-medium transition-colors">
- {t('chat.setup')}
- </button>
- )}
- <button
- type="button"
- data-analytics-id="chat-send-error-dismiss"
- onClick={() => {
- setSendError(null);
- dispatch(clearCreateThreadError());
- }}
- className="text-xs text-content-muted hover:text-content-secondary transition-colors">
- {t('common.dismiss')}
- </button>
- </div>
- </div>
- )}
+ {sendErrorBanner}
{(() => {
// Surface a parked ApprovalGate request for the shown thread just
@@ -2168,60 +2307,9 @@ const Conversations = ({
);
})()}
- {/* Flow-approval surface (chat): actionable banner(s) for paused
- tinyflows runs, pushed via the `flow_approval_request` socket
- event (issue: flow-approval surfacing). Not gated on the selected
- thread — see the hook call above for why — so every pending
- request renders regardless of which thread is open. */}
- {flowApprovalRequests.length > 0 && (
- <div className="mb-2 flex flex-col gap-2">
- {flowApprovalRequests.map(request => (
- <FlowApprovalRequestCard
- key={request.request_id}
- request={request}
- onResolved={dismissFlowApprovalRequest}
- />
- ))}
- </div>
- )}
+ {flowApprovalDeck}
- {(() => {
- // Surface in-flight + failed artifact cards above the composer
- // (#2779). Mirrors the approval-card placement so the user sees
- // the spinner / error without scrolling. `ready` cards are
- // delegated to the header ChatFilesChip panel (#3024) so the
- // chat scroll area isn't permanently occupied — restored decks
- // are listable from the chip on demand.
- //
- // The failed-card Retry button re-dispatches the producing tool
- // via `ai_regenerate` (#3162): the core reloads the persisted
- // creation args and re-runs generation under the original
- // artifact id, so the card swaps back to a spinner in place and
- // then to ready/failed via the socket events.
- const artifactThreadId = selectedThreadId ?? firstActiveThreadId;
- const all = artifactThreadId ? (artifactsByThread[artifactThreadId] ?? []) : [];
- const live = all.filter(a => a.status !== 'ready');
- if (live.length === 0) return null;
- return (
- <div className="mb-2 flex flex-col gap-2">
- {live.map(artifact => (
- <ArtifactCard
- key={artifact.artifactId}
- artifact={artifact}
- onRetry={
- artifactThreadId
- ? id => {
- void aiRegenerate(id, artifactThreadId).catch(err => {
- console.warn('[artifact] regenerate failed:', err);
- });
- }
- : undefined
- }
- />
- ))}
- </div>
- );
- })()}
+ {liveArtifactDeck}
{agentGateCards}
@@ -2444,45 +2532,10 @@ const Conversations = ({
{t('chat.agentProfile.reasoning')}
</button>
</div>
- {selectedThreadId && (
- <button
- type="button"
- data-testid="background-processes-toggle"
- data-analytics-id="chat-header-background-processes"
- onClick={() => threadViewRef.current?.openBackgroundProcesses()}
- aria-label={t('conversations.backgroundTasks.title')}
- title={
- backgroundProcesses.length > 0
- ? t('conversations.backgroundTasks.titleWithCount').replace(
- '{count}',
- String(backgroundProcesses.length)
- )
- : t('conversations.backgroundTasks.title')
- }
- className="relative flex h-7 w-7 items-center justify-center rounded-lg text-content-muted transition-colors hover:bg-surface-hover hover:text-content-secondary">
- <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"
- />
- </svg>
- {runningBackgroundCount > 0 ? (
- <span className="absolute -right-0.5 -top-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-amber-500 px-0.5 text-[9px] font-semibold leading-none text-content-inverted">
- {runningBackgroundCount}
- </span>
- ) : memorySyncActive ? (
- <span
- data-testid="background-activity-dot"
- className="absolute -right-0.5 -top-0.5 h-2 w-2 animate-pulse rounded-full bg-amber-500"
- />
- ) : null}
- </button>
- )}
- {(selectedThreadId ?? firstActiveThreadId) && (
- <ChatFilesChip threadId={(selectedThreadId ?? firstActiveThreadId) as string} />
+ {renderBackgroundProcessesButton(() =>
+ threadViewRef.current?.openBackgroundProcesses()
)}
+ {chatFilesChip}
</div>
)}
</div>
@@ -2499,6 +2552,10 @@ const Conversations = ({
(`thread.tsx:385`), and it renders directly above the input — the same
place `legacyMainPanel` put these cards. */}
{agentGateCards}
+ {/* Paused tinyflows runs block the same way a plan gate does — the
+ banner carries the only Approve/Reject affordance — so they belong
+ with the gates, above the transient banners. */}
+ {flowApprovalDeck}
{attachError && (
<div className="rounded-lg border border-coral-200 bg-coral-50 px-3 py-2">
<p className="text-xs text-coral-500" data-chat-send-error-code={attachError.code}>
@@ -2506,6 +2563,12 @@ const Conversations = ({
</p>
</div>
)}
+ {/* A rejected send is the one failure the user cannot diagnose from the
+ transcript: nothing is added to it. Without this the composer simply
+ swallowed the message. */}
+ {sendErrorBanner}
+ {sendAdvisoryBanner}
+ {liveArtifactDeck}
{selectedThreadId && (queuedFollowupsByThread[selectedThreadId]?.length ?? 0) > 0 ? (
<QueuedFollowups
items={queuedFollowupsByThread[selectedThreadId] ?? []}
@@ -2515,6 +2578,16 @@ const Conversations = ({
</>
);
+ // Left-hand controls in the assistant-ui composer toolbar, alongside the
+ // model pill and the thread-goal trigger — the assistant-ui equivalent of
+ // `legacyMainPanel`'s footer row.
+ const assistantComposerFooterExtras = (
+ <>
+ {renderBackgroundProcessesButton(() => setShowBackgroundProcesses(true))}
+ {chatFilesChip}
+ </>
+ );
+
const assistantUiMainPanel = (
<div
className={
@@ -2527,6 +2600,7 @@ const Conversations = ({
model={composerModelOverride ?? resolvedModel ?? CHAT_MODEL_HINT}
modelContextWindow={composerModelContextWindow}
composerHeader={assistantComposerHeader}
+ composerFooterExtras={assistantComposerFooterExtras}
inputValue={inputValue}
onInputValueChange={setInputValue}
onEscape={handleComposerEscape}
@@ -2547,6 +2621,24 @@ const Conversations = ({
setComposerModelContextWindow(contextWindow ?? null);
}}
/>
+ {/* The three transcript-local modals. `ChatThreadView` hosts an identical
+ trio, but it is the legacy panel's transcript and is not mounted here,
+ so on `/chat` the background-processes button had nothing to open and
+ the sub-agent drawer / process-source panel could not be reached at
+ all. Mounted beside the Thread (not inside it) because each is its own
+ overlay, positioned against the viewport. */}
+ <TranscriptOverlays
+ threadId={selectedThreadId ?? null}
+ entries={selectedThreadToolTimeline}
+ transcript={selectedThreadProcessing}
+ backgroundProcesses={backgroundProcesses}
+ showBackgroundProcesses={showBackgroundProcesses}
+ onCloseBackgroundProcesses={() => setShowBackgroundProcesses(false)}
+ openSubagentTaskId={openSubagentTaskId}
+ onOpenSubagent={setOpenSubagentTaskId}
+ showProcessSource={showProcessSource}
+ onCloseProcessSource={() => setShowProcessSource(false)}
+ />
</div>
);
// The realtime/mic-only embed still owns a voice-specific footer. The normal
diff --git a/app/src/features/conversations/components/AssistantUiChat.tsx b/app/src/features/conversations/components/AssistantUiChat.tsx
index f6c7021cd0..bd0a8a9d59 100644
--- a/app/src/features/conversations/components/AssistantUiChat.tsx
+++ b/app/src/features/conversations/components/AssistantUiChat.tsx
@@ -65,6 +65,7 @@ export function AssistantUiChat({
modelContextWindow,
onModelChange,
composerHeader,
+ composerFooterExtras,
inputValue,
onInputValueChange,
onEscape,
@@ -83,6 +84,12 @@ export function AssistantUiChat({
modelContextWindow?: number | null;
onModelChange: (value: string | null, contextWindow?: number | null) => void;
composerHeader?: ReactNode;
+ /**
+ * Host controls for the composer's own toolbar row, beside the model pill —
+ * the assistant-ui equivalent of the legacy panel's footer row (the
+ * background-processes button and the thread files chip).
+ */
+ composerFooterExtras?: ReactNode;
inputValue: string;
onInputValueChange: (value: string) => void;
onEscape?: () => void;
@@ -135,6 +142,11 @@ export function AssistantUiChat({
});
const slashCommands = useSlashCommands();
+ // Read through a ref for the same reason `ComposerHeader` does below: the
+ // slot is rendered by type, so closing over the node would remount the whole
+ // row on every host render.
+ const composerFooterExtrasRef = useRef(composerFooterExtras);
+ composerFooterExtrasRef.current = composerFooterExtras;
const ComposerExtras = useCallback(
() => (
<>
@@ -143,6 +155,7 @@ export function AssistantUiChat({
<ThreadGoalEditorPanel ctl={threadGoal} />
</div>
<ThreadGoalFooterTrigger ctl={threadGoal} />
+ {composerFooterExtrasRef.current}
</>
),
[contextUsage, threadGoal]
diff --git a/app/src/pages/__tests__/Conversations.auiComposerSurfaces.test.tsx b/app/src/pages/__tests__/Conversations.auiComposerSurfaces.test.tsx
new file mode 100644
index 0000000000..6d230e9626
--- /dev/null
+++ b/app/src/pages/__tests__/Conversations.auiComposerSurfaces.test.tsx
@@ -0,0 +1,383 @@
+/**
+ * The composer-adjacent surfaces on the ASSISTANT-UI chat panel.
+ *
+ * `Conversations` picks exactly one main panel — `legacyMainPanel` for the
+ * mic-cloud voice embed, `assistantUiMainPanel` for everything else — so every
+ * card that was written inline inside the legacy panel stopped rendering on
+ * `/chat` when the text chat moved to the assistant-ui `Thread`. These are the
+ * collateral losses from that switch, each asserted on the surface a real user
+ * looks at (the default `composer="text"` render, i.e. the assistant-ui panel):
+ *
+ * - the send-error banner — the worst of them, because a rejected send adds
+ * nothing to the transcript either, so the message simply vanished;
+ * - the flow-approval banner, the only Approve/Reject affordance for a paused
+ * tinyflows run;
+ * - the in-flight / failed artifact deck;
+ * - the background-processes button and the panel it opens.
+ *
+ * Each test fails against the pre-fix component with "unable to find" on the
+ * element it names — that is the regression, not a styling detail.
+ */
+import { combineReducers, configureStore } from '@reduxjs/toolkit';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import { MemoryRouter } from 'react-router-dom';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SidebarSlotOutlet, SidebarSlotProvider } from '../../components/layout/shell/SidebarSlot';
+// Type-only: erased at runtime, so it does not defeat `vi.hoisted`.
+import type { FlowApprovalRequest } from '../../hooks/useFlowApprovalRequests';
+import { chatSend } from '../../services/chatService';
+import agentProfileReducer from '../../store/agentProfileSlice';
+import chatRuntimeReducer, {
+ type ArtifactSnapshot,
+ type ToolTimelineEntry,
+} from '../../store/chatRuntimeSlice';
+import layoutReducer from '../../store/layoutSlice';
+import socketReducer from '../../store/socketSlice';
+import themeReducer from '../../store/themeSlice';
+import threadReducer from '../../store/threadSlice';
+import type { Thread, ThreadMessage } from '../../types/thread';
+
+// ── Hoisted mock state ─────────────────────────────────────────────────────
+
+const { mockGetThreads, mockGetThreadMessages, mockUseUsageState, mockFlowApprovalRequests } =
+ vi.hoisted(() => ({
+ mockGetThreads: vi.fn().mockResolvedValue({ threads: [], count: 0 }),
+ mockGetThreadMessages: vi.fn().mockResolvedValue({ messages: [], count: 0 }),
+ mockUseUsageState: vi.fn(() => ({
+ teamUsage: null,
+ currentPlan: null,
+ currentTier: 'FREE' as const,
+ isFreeTier: true,
+ usagePct: 0,
+ isNearLimit: false,
+ isAtLimit: false,
+ isBudgetExhausted: false,
+ shouldShowBudgetCompletedMessage: false,
+ isLoading: false,
+ refresh: vi.fn(),
+ })),
+ // The real hook subscribes to a socket event; drive the list directly so a
+ // parked flow gate is a fixture rather than a socket dance.
+ mockFlowApprovalRequests: vi.fn(
+ (): { requests: FlowApprovalRequest[]; dismiss: (id: string) => void } => ({
+ requests: [],
+ dismiss: vi.fn(),
+ })
+ ),
+ }));
+
+// ── Module mocks ───────────────────────────────────────────────────────────
+
+vi.mock('../../services/chatService', () => ({
+ chatCancel: vi.fn().mockResolvedValue(true),
+ chatClearQueue: vi.fn().mockResolvedValue(0),
+ chatSend: vi.fn().mockResolvedValue(undefined),
+ aiRegenerate: vi.fn().mockResolvedValue(undefined),
+ subscribeChatEvents: vi.fn(() => () => {}),
+ useRustChat: vi.fn(() => true),
+}));
+
+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,
+ }),
+ getTaskBoard: vi
+ .fn()
+ .mockResolvedValue({ threadId: 't-1', cards: [], updatedAt: '2026-05-04T10:00:00Z' }),
+ putTaskBoard: vi
+ .fn()
+ .mockResolvedValue({ threadId: 't-1', cards: [], updatedAt: '2026-05-04T10:00:00Z' }),
+ decidePlan: vi
+ .fn()
+ .mockResolvedValue({ threadId: 't-1', cards: [], updatedAt: '2026-05-04T10:00:00Z' }),
+ 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('../../services/api/agentProfilesApi', () => {
+ const profiles = {
+ activeProfileId: 'default',
+ profiles: [
+ {
+ id: 'default',
+ name: 'Default',
+ description: 'Default',
+ agentId: 'orchestrator',
+ builtIn: true,
+ },
+ ],
+ };
+ return {
+ agentProfilesApi: {
+ list: vi.fn().mockResolvedValue(profiles),
+ select: vi.fn().mockResolvedValue(profiles),
+ upsert: vi.fn().mockResolvedValue({ activeProfileId: 'default', profiles: [] }),
+ delete: vi.fn().mockResolvedValue({ activeProfileId: 'default', profiles: [] }),
+ },
+ };
+});
+
+vi.mock('../../services/api/openrouterFreeModels', () => ({ applyOpenRouterFreeModels: vi.fn() }));
+
+vi.mock('../../hooks/useUsageState', () => ({ useUsageState: mockUseUsageState }));
+
+vi.mock('../../hooks/useFlowApprovalRequests', () => ({
+ useFlowApprovalRequests: () => mockFlowApprovalRequests(),
+}));
+
+vi.mock('../../components/chat/ChatNewWindowHero', () => ({ default: () => null }));
+
+vi.mock('../../store/socketSelectors', () => ({
+ selectSocketStatus: (state: { socket?: { byUser?: Record<string, { status: string }> } }) =>
+ state.socket?.byUser?.__pending__?.status ?? 'disconnected',
+}));
+
+vi.mock('../../hooks/useStickToBottom', () => ({
+ useStickToBottom: vi.fn(() => ({ containerRef: { current: null }, endRef: { current: null } })),
+}));
+
+vi.mock('../../utils/openUrl', () => ({ openUrl: vi.fn() }));
+
+vi.mock('../../services/coreRpcClient', async orig => {
+ const actual = await orig<typeof import('../../services/coreRpcClient')>();
+ return { ...actual, callCoreRpc: vi.fn().mockResolvedValue({}) };
+});
+
+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 ────────────────────────────────────────────────────────────────
+
+const THREAD_ID = 'aui-thread';
+
+function buildStore(preload: Record<string, unknown> = {}) {
+ return configureStore({
+ reducer: combineReducers({
+ thread: threadReducer,
+ layout: layoutReducer,
+ socket: socketReducer,
+ chatRuntime: chatRuntimeReducer,
+ agentProfiles: agentProfileReducer,
+ theme: themeReducer,
+ }),
+ preloadedState: preload as never,
+ });
+}
+
+function makeThread(): Thread {
+ return {
+ id: THREAD_ID,
+ title: 'AUI Thread',
+ chatId: null,
+ isActive: false,
+ messageCount: 0,
+ lastMessageAt: '2026-01-01T00:00:00.000Z',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ labels: ['general'],
+ };
+}
+
+function threadState(extra: Record<string, unknown> = {}) {
+ return {
+ threads: [makeThread()],
+ selectedThreadId: THREAD_ID,
+ activeThreadIds: {},
+ welcomeThreadId: null,
+ messagesByThreadId: { [THREAD_ID]: [] },
+ messages: [],
+ isLoadingThreads: false,
+ isLoadingMessages: false,
+ messagesError: null,
+ ...extra,
+ };
+}
+
+const connectedSocket = { byUser: { __pending__: { status: 'connected', socketId: 'socket-1' } } };
+
+/**
+ * Render the page the way `/chat` does: `composer` omitted, so the default
+ * `'text'` selects `assistantUiMainPanel`. Nothing here opts into the legacy
+ * panel — that is the point of the suite.
+ */
+async function renderChat(
+ preload: { thread?: Record<string, unknown>; chatRuntime?: Record<string, unknown> } = {}
+) {
+ mockGetThreads.mockResolvedValue({ threads: [makeThread()], count: 1 });
+ mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });
+ // `chatRuntime` has ~20 per-thread maps and the page reads several of them
+ // unguarded, so a partial preload would replace the slice rather than extend
+ // it. Start from the reducer's own initial state.
+ const store = buildStore({
+ thread: preload.thread ?? threadState(),
+ socket: connectedSocket,
+ chatRuntime: {
+ ...chatRuntimeReducer(undefined, { type: '@@test/init' }),
+ ...(preload.chatRuntime ?? {}),
+ },
+ });
+ const { default: Conversations } = await import('../../features/conversations/Conversations');
+
+ await act(async () => {
+ render(
+ <Provider store={store}>
+ <MemoryRouter initialEntries={['/chat']}>
+ <SidebarSlotProvider>
+ <SidebarSlotOutlet />
+ <Conversations />
+ </SidebarSlotProvider>
+ </MemoryRouter>
+ </Provider>
+ );
+ });
+ return store;
+}
+
+function asyncSubagentRow(): ToolTimelineEntry {
+ return {
+ id: 'subagent:sub-1',
+ name: 'subagent:researcher',
+ round: 1,
+ seq: 1,
+ status: 'running',
+ subagent: {
+ taskId: 'sub-1',
+ agentId: 'researcher',
+ displayName: 'Researcher',
+ mode: 'async',
+ prompt: 'Dig up the pricing page',
+ toolCalls: [],
+ },
+ } as ToolTimelineEntry;
+}
+
+function inFlightArtifact(): ArtifactSnapshot {
+ return {
+ artifactId: 'art-1',
+ kind: 'document',
+ title: 'Quarterly summary',
+ status: 'in_progress',
+ updatedAt: 1_767_225_600_000,
+ };
+}
+
+describe('assistant-ui chat surface — composer-adjacent cards', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetThreads.mockResolvedValue({ threads: [], count: 0 });
+ mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });
+ mockFlowApprovalRequests.mockReturnValue({ requests: [], dismiss: vi.fn() });
+ vi.mocked(chatSend).mockResolvedValue(undefined);
+ });
+
+ it('shows the send error when a send is rejected', async () => {
+ // A rejected send writes nothing to the transcript, so this banner is the
+ // ONLY feedback the user gets. Without it the message just disappears.
+ vi.mocked(chatSend).mockRejectedValueOnce(new Error('relay unreachable'));
+ await renderChat();
+
+ const input = await screen.findByRole('textbox', { name: 'Message input' });
+ await act(async () => {
+ input.textContent = 'does this go anywhere?';
+ fireEvent.input(input, { data: 'does this go anywhere?', inputType: 'insertText' });
+ });
+ 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).toHaveBeenCalled());
+ const banner = await screen.findByText(/relay unreachable/);
+ expect(banner).toHaveAttribute('data-chat-send-error-code', 'cloud_send_failed');
+ });
+
+ it('shows a failed thread create as a send error', async () => {
+ // The second half of `deriveChatErrorBanner`: every create path (including
+ // the shell's "New chat", which has no UI of its own) records its failure
+ // on the slice, and this banner is where it surfaces.
+ await renderChat({
+ thread: threadState({ createThreadError: 'threads_create_new timed out after 30000ms' }),
+ });
+
+ const banner = await screen.findByTestId('chat-send-error');
+ expect(banner).toHaveAttribute('data-chat-send-error-code', 'create_thread_failed');
+ });
+
+ it('shows a paused flow run its Approve / Deny banner', async () => {
+ mockFlowApprovalRequests.mockReturnValue({
+ requests: [
+ {
+ request_id: 'req-1',
+ flow_id: 'flow-1',
+ run_id: 'run-1',
+ tool_name: 'http_request',
+ summary: 'POST https://example.test/orders',
+ },
+ ],
+ dismiss: vi.fn(),
+ });
+ await renderChat();
+
+ expect(await screen.findByText('POST https://example.test/orders')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Approve once' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Deny' })).toBeInTheDocument();
+ });
+
+ it('shows an in-flight artifact card', async () => {
+ await renderChat({ chatRuntime: { artifactsByThread: { [THREAD_ID]: [inFlightArtifact()] } } });
+
+ expect(await screen.findByText('Quarterly summary')).toBeInTheDocument();
+ });
+
+ it('opens the background-processes panel from the composer toolbar', async () => {
+ await renderChat({
+ chatRuntime: { toolTimelineByThread: { [THREAD_ID]: [asyncSubagentRow()] } },
+ });
+
+ const toggle = await screen.findByTestId('background-processes-toggle');
+ await act(async () => {
+ fireEvent.click(toggle);
+ });
+
+ // The panel is the only route to the sub-agent drawer on this surface.
+ expect(await screen.findByText('Researcher')).toBeInTheDocument();
+ });
+});