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
feat(chat): wire assistant-ui to real conversation data
Steven Enamakel7cf939f404ee
diff --git a/app/src/components/assistant-ui/thread.tsx b/app/src/components/assistant-ui/thread.tsxindex 61e04628ab..14f6eea0e7 100644--- a/app/src/components/assistant-ui/thread.tsx+++ b/app/src/components/assistant-ui/thread.tsx@@ -45,6 +45,7 @@ import {type ToolCallMessagePartComponent,type Unstable_SlashCommand,unstable_useSlashCommandAdapter,+ useAui,useAuiState,} from '@assistant-ui/react';import { LexicalComposerInput } from '@assistant-ui/react-lexical';@@ -69,7 +70,8 @@ import {type FC,type PropsWithChildren,useContext,- useState,+ useEffect,+ useRef,} from 'react';export type ThreadGroupPart = MessagePrimitive.GroupedParts.GroupPart;@@ -95,10 +97,20 @@ export type ThreadComponents = {* anything else.*/ComposerExtras?: ComponentType | undefined;+ /** Full-width host content immediately above the composer shell. */+ ComposerHeader?: ComponentType | undefined;};export type ThreadProps = {components?: ThreadComponents | undefined;+ /** Host-owned model route used for real sends. */+ model?: string | null | undefined;+ /** Updates the host's composer route and selected model metadata. */+ onModelChange?: ((value: string, contextWindow?: number | null) => void) | undefined;+ /** Host transport error shown in place of an empty welcome state. */+ loadError?: string | null | undefined;+ /** Host-specific Escape behavior (for example cancel + restore prompt). */+ onEscape?: (() => void) | undefined;/*** Commands offered when the composer input starts with `/`. Supplied by the* host because a command's `execute` is host behaviour (`/clear` has to@@ -148,6 +160,10 @@ const ThreadHistorySkeleton: FC = () => (export const Thread: FC<ThreadProps> = ({components = EMPTY_COMPONENTS,+ model = 'hint:chat',+ onModelChange,+ loadError = null,+ onEscape,slashCommands = NO_SLASH_COMMANDS,}) => {const isEmpty = useAuiState(isNewChatView);@@ -155,13 +171,25 @@ export const Thread: FC<ThreadProps> = ({return (<ThreadComponentsContext.Provider value={components}><SlashCommandsContext.Provider value={slashCommands}>- <ThreadRoot isEmpty={isEmpty} />+ <ThreadRoot+ isEmpty={isEmpty}+ model={model}+ onModelChange={onModelChange}+ loadError={loadError}+ onEscape={onEscape}+ /></SlashCommandsContext.Provider></ThreadComponentsContext.Provider>);};-const ThreadRoot: FC<{ isEmpty: boolean }> = ({ isEmpty }) => {+const ThreadRoot: FC<{+ isEmpty: boolean;+ model: string | null;+ onModelChange?: (value: string, contextWindow?: number | null) => void;+ loadError: string | null;+ onEscape?: () => void;+}> = ({ isEmpty, model, onModelChange, loadError, onEscape }) => {const { Welcome = ThreadWelcome } = useContext(ThreadComponentsContext);return (@@ -182,12 +210,21 @@ const ThreadRoot: FC<{ isEmpty: boolean }> = ({ isEmpty }) => {'mx-auto flex w-full max-w-(--thread-max-width) flex-1 flex-col px-4 pt-4',isEmpty && 'justify-center')}>- <AuiIf condition={isNewChatView}>- <Welcome />- </AuiIf>- <AuiIf condition={isHistoryLoadingView}>- <ThreadHistorySkeleton />- </AuiIf>+ {loadError ? (+ <div className="flex flex-1 flex-col items-center justify-center gap-2 text-center">+ <p className="text-sm font-medium text-destructive">Failed to load messages</p>+ <p className="text-muted-foreground max-w-md text-xs">{loadError}</p>+ </div>+ ) : (+ <>+ <AuiIf condition={isNewChatView}>+ <Welcome />+ </AuiIf>+ <AuiIf condition={isHistoryLoadingView}>+ <ThreadHistorySkeleton />+ </AuiIf>+ </>+ )}<div data-slot="aui_message-group" className="mb-14 flex flex-col gap-y-6 empty:hidden"><ThreadPrimitive.Messages>{() => <ThreadMessage />}</ThreadPrimitive.Messages>@@ -200,7 +237,7 @@ const ThreadRoot: FC<{ isEmpty: boolean }> = ({ isEmpty }) => {)}><ThreadScrollToBottom /><ThreadFollowupSuggestions />- <Composer />+ <Composer model={model} onModelChange={onModelChange} onEscape={onEscape} /><AuiIf condition={s => isNewChatView(s) && s.composer.isEmpty}><ThreadSuggestions /></AuiIf>@@ -268,14 +305,26 @@ const ThreadSuggestionItem: FC = () => {);};-const Composer: FC = () => {- const [model, setModel] = useState<string | null>('hint:chat');+const Composer: FC<{+ model: string | null;+ onModelChange?: (value: string, contextWindow?: number | null) => void;+ onEscape?: () => void;+}> = ({ model, onModelChange, onEscape }) => {+ const aui = useAui();const commands = useContext(SlashCommandsContext);const slash = unstable_useSlashCommandAdapter({ commands, fallbackIcon: SlashIcon });+ const inputWrapperRef = useRef<HTMLDivElement>(null);+ const { ComposerHeader } = useContext(ThreadComponentsContext);+ useEffect(() => {+ const textbox = inputWrapperRef.current?.querySelector<HTMLElement>('[contenteditable="true"]');+ textbox?.setAttribute('aria-label', 'Message input');+ return () => textbox?.removeAttribute('aria-label');+ }, []);return (<ComposerPrimitive.Unstable_TriggerPopoverRoot><ComposerPrimitive.Root className="aui-composer-root relative flex w-full flex-col">+ {ComposerHeader ? <ComposerHeader /> : null}<ComposerPrimitive.AttachmentDropzone asChild><divdata-slot="aui_composer-shell"@@ -290,11 +339,36 @@ const Composer: FC = () => {* opens, so a host that wants a plain box still gets one.*/}<LexicalComposerInput+ ref={inputWrapperRef}placeholder="Send a message..."+ onInputCapture={event => {+ const target = event.target;+ if (target instanceof HTMLElement) {+ const text = target.textContent ?? '';+ globalThis.queueMicrotask(() => aui.composer.setText(text));+ }+ }}+ onKeyDownCapture={event => {+ if (event.key === 'Escape' && onEscape) {+ event.preventDefault();+ event.stopPropagation();+ onEscape();+ return;+ }+ const native = event.nativeEvent;+ if (+ native.isComposing ||+ native.keyCode === 229 ||+ ('which' in native && native.which === 229)+ ) {+ event.preventDefault();+ event.stopPropagation();+ }+ }}className="aui-composer-input caret-primary [&_.aui-lexical-placeholder]:text-muted-foreground/60 relative max-h-48 min-h-10 w-full resize-none bg-transparent px-2.5 py-1 text-base leading-6 outline-none [&_.aui-lexical-input]:min-h-lh [&_.aui-lexical-input]:outline-none [&_.aui-lexical-placeholder]:pointer-events-none [&_.aui-lexical-placeholder]:absolute [&_.aui-lexical-placeholder]:top-0 [&_.aui-lexical-placeholder]:right-0 [&_.aui-lexical-placeholder]:left-0 [&_.aui-lexical-placeholder]:truncate [&_.aui-lexical-placeholder]:px-2.5 [&_.aui-lexical-placeholder]:py-1"aria-label="Message input"/>- <ComposerAction model={model} onModelChange={setModel} />+ <ComposerAction model={model} onModelChange={onModelChange} /></div></ComposerPrimitive.AttachmentDropzone>@@ -311,10 +385,10 @@ const ComposerExtrasSlot: FC = () => {return ComposerExtras ? <ComposerExtras /> : null;};-const ComposerAction: FC<{ model: string | null; onModelChange: (value: string) => void }> = ({- model,- onModelChange,-}) => {+const ComposerAction: FC<{+ model: string | null;+ onModelChange?: (value: string, contextWindow?: number | null) => void;+}> = ({ model, onModelChange }) => {return (<div className="aui-composer-action-wrapper relative flex items-center justify-between"><div className="flex min-w-0 items-center gap-1">@@ -505,6 +579,14 @@ const AssistantMessage: FC = () => {<divdata-slot="aui_assistant-message-footer"className={cn('ms-2 flex items-center', ACTION_BAR_HEIGHT)}>+ <AuiIf+ condition={s =>+ s.message.status?.type === 'incomplete' && s.message.status.reason === 'cancelled'+ }>+ <span data-testid="stopped-marker" className="text-muted-foreground text-xs">+ Stopped+ </span>+ </AuiIf><BranchPicker /><AssistantActionBar /></div>diff --git a/app/src/components/chat/ChatComposer.tsx b/app/src/components/chat/ChatComposer.tsxindex fda8a45369..5c36797325 100644--- a/app/src/components/chat/ChatComposer.tsx+++ b/app/src/components/chat/ChatComposer.tsx@@ -107,7 +107,7 @@ export interface ChatComposerProps {mascotDock?: React.ReactNode;/** Per-composer model route selected from the assistant-ui-style control. */modelOverride?: string | null;- onModelOverrideChange?: (value: string) => void;+ onModelOverrideChange?: (value: string, contextWindow?: number | null) => void;}/**diff --git a/app/src/components/chat/ModelQualityPill.tsx b/app/src/components/chat/ModelQualityPill.tsxindex 3b151e4f08..fb67c5f65e 100644--- a/app/src/components/chat/ModelQualityPill.tsx+++ b/app/src/components/chat/ModelQualityPill.tsx@@ -12,7 +12,7 @@ import { Button } from '../ui';interface ModelQualityPillProps {className?: string;value?: string | null;- onValueChange?: (value: string) => void;+ onValueChange?: (value: string, contextWindow?: number | null) => void;}function selectionFromValue(value: string | null | undefined): ProviderModelSelection | null {@@ -119,7 +119,7 @@ export default function ModelQualityPill({initial={initial}onClose={() => setOpen(false)}onSelect={selection => {- onValueChange?.(selectionValue(selection));+ onValueChange?.(selectionValue(selection), selection.contextWindow);setOpen(false);}}/>diff --git a/app/src/components/chat/__tests__/ModelQualityPill.test.tsx b/app/src/components/chat/__tests__/ModelQualityPill.test.tsxindex 5d9c38f439..177530b0ef 100644--- a/app/src/components/chat/__tests__/ModelQualityPill.test.tsx+++ b/app/src/components/chat/__tests__/ModelQualityPill.test.tsx@@ -11,12 +11,6 @@ describe('ModelQualityPill', () => {expect(screen.getByText('OpenHuman')).toBeInTheDocument();});- it('renders quality indicator', () => {- render(<ModelQualityPill />);- // The quality value comes through t('composer.qualityHigh') which returns the key in test- expect(screen.getByText('composer.qualityHigh')).toBeInTheDocument();- });-it('has chevron icon', () => {const { container } = render(<ModelQualityPill />);const svg = container.querySelector('svg');@@ -29,7 +23,7 @@ describe('ModelQualityPill', () => {// Horizontal padding + rounded shape keep the trailing chevron fully// inside the pill instead of flush against its right edge.expect(button).toHaveClass('px-2');- expect(button).toHaveClass('rounded-full');+ expect(button).toHaveClass('rounded-md');// The chevron itself must not shrink/clip when space is tight.const svg = button.querySelector('svg');expect(svg).toHaveClass('shrink-0');diff --git a/app/src/components/settings/panels/ai/ProviderModelPickerDialog.test.tsx b/app/src/components/settings/panels/ai/ProviderModelPickerDialog.test.tsxnew file mode 100644index 0000000000..10510faf4e--- /dev/null+++ b/app/src/components/settings/panels/ai/ProviderModelPickerDialog.test.tsx@@ -0,0 +1,48 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { listProviderModels } from '../../../../services/api/aiSettingsApi';+import { ProviderModelPickerDialog } from './ProviderModelPickerDialog';++vi.mock('../../../../services/api/aiSettingsApi', () => ({ listProviderModels: vi.fn() }));++describe('ProviderModelPickerDialog', () => {+ it('returns the provider-reported context window with a catalog selection', async () => {+ vi.mocked(listProviderModels).mockResolvedValue([+ { id: 'gpt-4o-mini', owned_by: 'openai', context_window: 128_000 },+ ]);+ const onSelect = vi.fn();++ render(+ <ProviderModelPickerDialog+ cloudProviders={[+ {+ id: 'openai',+ slug: 'openai',+ label: 'OpenAI',+ endpoint: 'https://api.openai.com/v1',+ authStyle: 'bearer',+ maskedKey: '••••',+ },+ ]}+ localModels={[]}+ ollamaRunning={false}+ claudeCodeEnabled={false}+ initial={null}+ onClose={() => {}}+ onSelect={onSelect}+ />+ );++ fireEvent.click(await screen.findByRole('button', { name: 'gpt-4o-mini' }));+ fireEvent.click(screen.getByRole('button', { name: 'Use this model' }));++ await waitFor(() =>+ expect(onSelect).toHaveBeenCalledWith({+ source: { kind: 'cloud', providerSlug: 'openai' },+ model: 'gpt-4o-mini',+ contextWindow: 128_000,+ })+ );+ });+});diff --git a/app/src/components/settings/panels/ai/ProviderModelPickerDialog.tsx b/app/src/components/settings/panels/ai/ProviderModelPickerDialog.tsxindex 7116cc92b9..6751262e22 100644--- a/app/src/components/settings/panels/ai/ProviderModelPickerDialog.tsx+++ b/app/src/components/settings/panels/ai/ProviderModelPickerDialog.tsx@@ -16,6 +16,8 @@ import { ProviderSwatch } from './ProviderListRow';export interface ProviderModelSelection {source: CustomDialogSource;model: string;+ /** Provider-reported context window for this exact model, when known. */+ contextWindow?: number | null;}interface ProviderModelPickerDialogProps {@@ -134,7 +136,18 @@ export function ProviderModelPickerDialog({variant="primary"size="sm"disabled={!source || !model.trim()}- onClick={() => source && onSelect({ source, model: model.trim() })}>+ onClick={() => {+ if (!source) return;+ const selectedModel = catalog.find(candidate => candidate.id === model.trim());+ onSelect({+ source,+ model: model.trim(),+ contextWindow:+ selectedModel && (selectedModel.context_window ?? 0) > 0+ ? selectedModel.context_window+ : null,+ });+ }}>Use this model</Button></div>diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsxindex 46741ae180..6c8db3c8f6 100644--- a/app/src/features/conversations/Conversations.tsx+++ b/app/src/features/conversations/Conversations.tsx@@ -452,6 +452,12 @@ const Conversations = ({// A picker choice belongs to this composer session. It overrides the active// profile route for subsequent sends without mutating the shared profile.const [composerModelOverride, setComposerModelOverride] = useState<string | null>(null);+ // `undefined` means no explicit picker selection, so usage-reported context+ // remains authoritative. `null` means the selected model did not report a+ // window, and the meter deliberately shows an unknown limit.+ const [composerModelContextWindow, setComposerModelContextWindow] = useState<+ number | null | undefined+ >(undefined);// Whether the resolved model for the active profile accepts image input.// Managed tiers do; custom/BYOK models only when the user flagged them. Gates// the composer's image-attachment affordance (docs flow regardless). Resolved@@ -1276,6 +1282,7 @@ const Conversations = ({} catch (err) {const msg = err instanceof Error ? err.message : String(err);setSendError(chatSendError('cloud_send_failed', msg));+ setInputValue(normalized);}};@@ -1360,6 +1367,10 @@ const Conversations = ({} catch (err) {const msg = err instanceof Error ? err.message : String(err);setSendError(chatSendError('cloud_send_failed', msg));+ // assistant-ui clears its composer after `onNew` resolves. This path+ // handles the transport error locally, so restore the rejected follow-up+ // explicitly instead of letting the user's draft disappear.+ setInputValue(normalized);}};@@ -1455,7 +1466,12 @@ const Conversations = ({// follow-up vs. fresh turn) is made in exactly one place, and// `handleSendMessage`'s `evaluateComposerSend` block/allow half runs// unchanged. Re-deriving either here is the drift this seam exists to stop.- useChatSurfaceRegistration(selectedThreadId, handleComposerSendRef, handleStopGenerationRef);+ useChatSurfaceRegistration(+ selectedThreadId,+ handleComposerSendRef,+ handleStopGenerationRef,+ true+ );const transcribeAndSendAudio = async (mimeType: string) => {setIsRecording(false);@@ -1627,6 +1643,37 @@ const Conversations = ({};}, [messages, replyMode, rustChat]);+ const handleComposerEscape = useCallback(() => {+ if (!selectedThreadActive) return;+ const composerEmpty = inputValue.trim().length === 0;+ debug(+ '[chat] esc interrupt: thread=%s composerEmpty=%s',+ selectedThreadId ?? 'none',+ composerEmpty+ );+ handleStopGeneration();+ if (composerEmpty) {+ // Restore the last *visible* user prompt (hidden system/injected+ // messages are excluded here to match how the transcript is rendered).+ const lastUserMessage = [...messages]+ .reverse()+ .find(m => m.sender === 'user' && !m.extraMetadata?.hidden);+ const restored = lastUserMessage+ ? parseMessageImages(lastUserMessage.content ?? '').text+ : '';+ if (restored.length > 0) {+ debug('[chat] esc interrupt: restored prompt len=%d', restored.length);+ setInputValue(restored);+ window.requestAnimationFrame(() => {+ const ta = textInputRef.current;+ if (!ta) return;+ ta.focus();+ ta.setSelectionRange(restored.length, restored.length);+ });+ }+ }+ }, [handleStopGeneration, inputValue, messages, selectedThreadActive, selectedThreadId]);+const handleInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {if (isComposingTextRef.current || isImeCompositionKeyEvent(e)) return;@@ -1638,33 +1685,7 @@ const Conversations = ({// default behaviour (blur / no-op).if (e.key === 'Escape' && selectedThreadActive) {e.preventDefault();- const composerEmpty = inputValue.trim().length === 0;- debug(- '[chat] esc interrupt: thread=%s composerEmpty=%s',- selectedThreadId ?? 'none',- composerEmpty- );- handleStopGeneration();- if (composerEmpty) {- // Restore the last *visible* user prompt (hidden system/injected- // messages are excluded here to match how the transcript is rendered).- const lastUserMessage = [...messages]- .reverse()- .find(m => m.sender === 'user' && !m.extraMetadata?.hidden);- const restored = lastUserMessage- ? parseMessageImages(lastUserMessage.content ?? '').text- : '';- if (restored.length > 0) {- debug('[chat] esc interrupt: restored prompt len=%d', restored.length);- setInputValue(restored);- window.requestAnimationFrame(() => {- const ta = textInputRef.current;- if (!ta) return;- ta.focus();- ta.setSelectionRange(restored.length, restored.length);- });- }- }+ handleComposerEscape();return;}@@ -2397,7 +2418,10 @@ const Conversations = ({]}mascotDock={mascotDock}modelOverride={composerModelOverride ?? resolvedModel}- onModelOverrideChange={setComposerModelOverride}+ onModelOverrideChange={(value, contextWindow) => {+ setComposerModelOverride(value);+ setComposerModelContextWindow(contextWindow ?? null);+ }}/></>) : (@@ -2564,9 +2588,65 @@ const Conversations = ({</div>);- // The first assistant-ui migration is intentionally a fresh, local surface.- // Keep the established pane available while follow-up work reconnects its- // OpenHuman-specific features one seam at a time.+ const assistantComposerHeader = (+ <>+ {isNearLimit &&+ !isAtLimit &&+ isFreeTier &&+ shouldShowBanner('conversations-warning', 24 * 60 * 60 * 1000) && (+ <UpsellBanner+ variant="warning"+ title={t('chat.approachingLimit')}+ message={t('chat.approachingLimitMsg').replace(+ '{pct}',+ String(Math.round(usagePct * 100))+ )}+ ctaLabel={t('chat.upgrade')}+ onCtaClick={() => void openUrl(PRICING_URL)}+ dismissible+ onDismiss={() => dismissBanner('conversations-warning')}+ />+ )}+ {teamUsage && shouldShowBudgetCompletedMessage && (+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-coral-200 bg-coral-50 p-3">+ <p className="min-w-0 text-xs text-coral-600">+ {teamUsage.cycleBudgetUsd > 0+ ? `${t('chat.weeklyLimitHit')}${teamUsage.cycleEndsAt ? ` ${t('chat.resets')} ${formatResetTime(teamUsage.cycleEndsAt)}.` : ''} ${t('chat.topUpToContinue')}`+ : t('chat.budgetComplete')}+ </p>+ <div className="flex shrink-0 items-center gap-2">+ <button+ type="button"+ data-analytics-id="chat-budget-openrouter-free"+ disabled={openRouterStatus === 'saving'}+ onClick={() => void handleUseOpenRouterFree()}+ className="rounded-lg border border-coral-300 bg-surface px-3 py-1.5 text-xs font-medium text-coral-700 transition-colors hover:bg-coral-100 disabled:cursor-wait disabled:opacity-70">+ {openRouterStatus === 'saving' ? t('openrouterFree.saving') : t('openrouterFree.cta')}+ </button>+ <button+ type="button"+ data-analytics-id="chat-budget-top-up"+ onClick={() => void openUrl(PRICING_URL)}+ className="rounded-lg bg-coral-500 px-3 py-1.5 text-xs font-medium text-content-inverted transition-colors hover:bg-coral-400">+ {t('chat.topUp')}+ </button>+ </div>+ </div>+ )}+ {openRouterStatus === 'error' && (+ <div className="rounded-lg border border-coral-200 bg-coral-50 px-3 py-2 text-xs text-coral-700">+ {t('openrouterFree.error')}+ </div>+ )}+ {selectedThreadId && (queuedFollowupsByThread[selectedThreadId]?.length ?? 0) > 0 ? (+ <QueuedFollowups+ items={queuedFollowupsByThread[selectedThreadId] ?? []}+ onClear={() => void handleClearQueuedFollowups()}+ />+ ) : null}+ </>+ );+const assistantUiMainPanel = (<divclassName={@@ -2574,11 +2654,25 @@ const Conversations = ({? 'flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden border-l border-line bg-surface': 'flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden'}>- <AssistantUiChat />+ <AssistantUiChat+ threadGoal={threadGoal}+ model={composerModelOverride ?? resolvedModel ?? CHAT_MODEL_HINT}+ modelContextWindow={composerModelContextWindow}+ composerHeader={assistantComposerHeader}+ inputValue={inputValue}+ onInputValueChange={setInputValue}+ onEscape={handleComposerEscape}+ onModelChange={(value, contextWindow) => {+ setComposerModelOverride(value);+ setComposerModelContextWindow(contextWindow ?? null);+ }}+ /></div>);- const renderAssistantUiOnly = true;- const mainPanel = renderAssistantUiOnly ? assistantUiMainPanel : legacyMainPanel;+ // The realtime/mic-only embed still owns a voice-specific footer. The normal+ // text chat is fully assistant-ui; voice keeps its established surface until+ // assistant-ui exposes the equivalent recording controls.+ const mainPanel = composer === 'mic-cloud' ? legacyMainPanel : assistantUiMainPanel;return (<divdiff --git a/app/src/features/conversations/components/AssistantUiChat.tsx b/app/src/features/conversations/components/AssistantUiChat.tsxindex 2623a79061..db2923fbfd 100644--- a/app/src/features/conversations/components/AssistantUiChat.tsx+++ b/app/src/features/conversations/components/AssistantUiChat.tsx@@ -1,119 +1,137 @@import { Thread, type ThreadComponents } from '@/components/assistant-ui/thread';+import { type AssistantState, useAui, useAuiState } from '@assistant-ui/react';+import { type ReactNode, useCallback, useMemo } from 'react';+import { useEffect, useRef } from 'react';++import { useRegisterAction } from '../../../lib/commands/useRegisterAction';+import { useSlashCommands } from '../../../lib/commands/useSlashCommands';+import { AssistantUiRuntimeProvider } from '../../../providers/AssistantUiRuntimeProvider';+import { emptySessionTokenUsage } from '../../../store/chatRuntimeSlice';+import { useAppSelector } from '../../../store/hooks';+import { ChatToolFallback, ChatToolGroup } from './ChatToolParts';+import { contextUsageFromTokenUsage, ContextWindowPill } from './composer/ContextWindowPill';import {- buildSeedMessages,- mockChatModelAdapter,- MockToolFallback,- MockToolGroup,-} from '@/lib/assistantUiMock';-import {- AssistantRuntimeProvider,- CompositeAttachmentAdapter,- SimpleImageAttachmentAdapter,- SimpleTextAttachmentAdapter,- type Unstable_SlashCommand,- useLocalRuntime,-} from '@assistant-ui/react';-import debugFactory from 'debug';-import { useCallback, useMemo, useState } from 'react';+ type ThreadGoalController,+ ThreadGoalEditorPanel,+ ThreadGoalFooterTrigger,+} from './ThreadGoalChip';-import { useT } from '../../../lib/i18n/I18nContext';-import { type ContextUsage, ContextWindowPill } from './composer/ContextWindowPill';-import { GoalSelector } from './composer/GoalSelector';+const EMPTY_TOKEN_USAGE = emptySessionTokenUsage();+const selectComposerText = (state: AssistantState) => state.composer.text;-const debug = debugFactory('openhuman:assistant-ui');+function ComposerTextBridge({+ value,+ onChange,+}: {+ value: string;+ onChange: (value: string) => void;+}) {+ const aui = useAui();+ const composerText = useAuiState(selectComposerText);+ const previousHostValue = useRef(value);-const localAttachmentAdapter = new CompositeAttachmentAdapter([- new SimpleImageAttachmentAdapter(),- new SimpleTextAttachmentAdapter(),-]);+ useEffect(() => {+ // A host-side write (dictation, ESC restore, clear) wins for this pass.+ if (previousHostValue.current !== value) {+ previousHostValue.current = value;+ if (composerText !== value) aui.composer.setText(value);+ return;+ }+ // Otherwise the editor changed and the host draft follows it.+ if (composerText !== value) onChange(composerText);+ }, [aui, composerText, onChange, value]);-/**- * Placeholder accounting, alongside the placeholder transcript.- *- * Shaped as the real thing would be — separate cached and fresh input, because- * a cache read is billed at a fraction of a fresh one and the cost cannot be- * derived from a single token count — so wiring this to live usage is a change- * of source, not of shape.- */-const MOCK_USAGE: ContextUsage = {- used: 24_180,- limit: 200_000,- input: 19_400,- cachedInput: 12_650,- output: 4_780,- costUsd: 0.0412,-};+ return null;+}/**- * The assistant-ui `Thread`, running against an isolated offline runtime.+ * The assistant-ui `Thread`, projected from OpenHuman's Redux transcript.*- * This surface is still a stand-in: `Conversations` renders it instead of the- * legacy pane (`renderAssistantUiOnly`) while the OpenHuman-specific seams are- * reconnected one at a time. Nothing here reaches the core or the backend.- *- * What it shows, though, is the real shape of the surface: the mock turn- * (thinking tokens, tool calls, dispatched subagents, streamed prose), slash- * commands in the composer, the context-window meter and the thread goal. Each- * of those is wired to placeholder state that a later change swaps for a live- * source without touching the components.+ * The runtime is a read-only projection; Redux and the core remain authoritative+ * for messages, streaming and persistence. Composer sends are forwarded through+ * the chat-surface registration owned by `Conversations`, so this uses the same+ * send/cancel path as the legacy composer.*/-export function AssistantUiChat() {- const { t } = useT();- const [goal, setGoal] = useState<string | null>(null);- const [goalDialogOpen, setGoalDialogOpen] = useState(false);+export function AssistantUiChat({+ threadGoal,+ model,+ modelContextWindow,+ onModelChange,+ composerHeader,+ inputValue,+ onInputValueChange,+ onEscape,+}: {+ threadGoal: ThreadGoalController;+ model: string | null;+ modelContextWindow?: number | null;+ onModelChange: (value: string, contextWindow?: number | null) => void;+ composerHeader?: ReactNode;+ inputValue: string;+ onInputValueChange: (value: string) => void;+ onEscape?: () => void;+}) {+ const selectedThreadId = useAppSelector(state => state.thread.selectedThreadId);+ const loadError = useAppSelector(state => state.thread.messagesError);+ const tokenUsage = useAppSelector(state =>+ selectedThreadId+ ? (state.chatRuntime.usageByThread[selectedThreadId] ?? EMPTY_TOKEN_USAGE)+ : EMPTY_TOKEN_USAGE+ );+ const contextUsage = useMemo(+ () => contextUsageFromTokenUsage(tokenUsage, modelContextWindow),+ [modelContextWindow, tokenUsage]+ );+ const openThreadGoal = threadGoal.open;- const initialMessages = useMemo(() => buildSeedMessages(), []);- const runtime = useLocalRuntime(mockChatModelAdapter, {- adapters: { attachments: localAttachmentAdapter },- initialMessages,+ useRegisterAction({+ id: 'chat.goal',+ label: 'Set thread goal',+ labelKey: 'conversations.composer.command.goal',+ group: 'Chat',+ handler: openThreadGoal,+ enabled: () => selectedThreadId !== null,+ keywords: ['goal', 'objective', 'thread goal'],+ slashCommand: { id: 'goal', descriptionKey: 'conversations.composer.command.goal' },});-- const slashCommands: readonly Unstable_SlashCommand[] = useMemo(- () => [- {- id: 'clear',- description: t('conversations.composer.command.clear'),- // A real reset, not a cosmetic one: `reset()` with no argument drops- // the seeded transcript too, so `/clear` leaves an actually empty- // thread rather than restoring the sample conversation.- execute: () => {- debug('[assistant-ui] /clear');- runtime.thread.reset();- },- },- {- id: 'goal',- description: t('conversations.composer.command.goal'),- execute: () => setGoalDialogOpen(true),- },- ],- [runtime, t]- );+ const slashCommands = useSlashCommands();const ComposerExtras = useCallback(() => (<>- <ContextWindowPill usage={MOCK_USAGE} />- <GoalSelector- goal={goal}- onGoalChange={setGoal}- open={goalDialogOpen}- onOpenChange={setGoalDialogOpen}- />+ <ContextWindowPill usage={contextUsage} />+ <div className="absolute right-0 bottom-full left-0 pb-2">+ <ThreadGoalEditorPanel ctl={threadGoal} />+ </div>+ <ThreadGoalFooterTrigger ctl={threadGoal} /></>),- [goal, goalDialogOpen]+ [contextUsage, threadGoal]);+ const ComposerHeader = useCallback(() => <>{composerHeader}</>, [composerHeader]);const components: ThreadComponents = useMemo(- () => ({ ToolFallback: MockToolFallback, ToolGroup: MockToolGroup, ComposerExtras }),- [ComposerExtras]+ () => ({+ ToolFallback: ChatToolFallback,+ ToolGroup: ChatToolGroup,+ ComposerExtras,+ ComposerHeader,+ }),+ [ComposerExtras, ComposerHeader]);return (- <AssistantRuntimeProvider runtime={runtime}>- <Thread components={components} slashCommands={slashCommands} />- </AssistantRuntimeProvider>+ <AssistantUiRuntimeProvider>+ <ComposerTextBridge value={inputValue} onChange={onInputValueChange} />+ <Thread+ components={components}+ model={model}+ onModelChange={onModelChange}+ loadError={loadError}+ onEscape={onEscape}+ slashCommands={slashCommands}+ />+ </AssistantUiRuntimeProvider>);}diff --git a/app/src/features/conversations/components/ChatToolParts.test.tsx b/app/src/features/conversations/components/ChatToolParts.test.tsxnew file mode 100644index 0000000000..c2c131b78d--- /dev/null+++ b/app/src/features/conversations/components/ChatToolParts.test.tsx@@ -0,0 +1,46 @@+import { render, screen } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import type { SubagentActivity } from '../../../store/chatRuntimeSlice';+import { ChatToolFallback, ChatToolGroup } from './ChatToolParts';++const activity: SubagentActivity = {+ taskId: 'sub-1',+ agentId: 'researcher',+ displayName: 'Researcher',+ toolCalls: [],+ transcript: [{ kind: 'thinking', text: 'Checking primary sources.' }],+};++describe('ChatToolParts', () => {+ it('renders a delegation with progress args and no result as running', () => {+ render(+ <ChatToolFallback+ type="tool-call"+ toolName="task"+ toolCallId="sub-1"+ args={{ progress: activity } as never}+ argsText="{}"+ result={undefined}+ status={{ type: 'running' }}+ addResult={() => {}}+ resume={() => {}}+ respondToApproval={() => {}}+ />+ );++ expect(screen.getByText('running')).toBeInTheDocument();+ expect(screen.getByText('Researcher')).toBeInTheDocument();+ expect(screen.getByText('Checking primary sources.')).toBeInTheDocument();+ });++ it('opens a group containing in-flight work on mount', () => {+ render(+ <ChatToolGroup group={{ type: 'group-tool-call', status: { type: 'running' }, indices: [0] }}>+ <span>live delegation</span>+ </ChatToolGroup>+ );++ expect(screen.getByText('live delegation')).toBeVisible();+ });+});diff --git a/app/src/features/conversations/components/ChatToolParts.tsx b/app/src/features/conversations/components/ChatToolParts.tsxnew file mode 100644index 0000000000..69c06ec5fa--- /dev/null+++ b/app/src/features/conversations/components/ChatToolParts.tsx@@ -0,0 +1,109 @@+import type { ToolCallMessagePartComponent } from '@assistant-ui/react';+import { CheckIcon, ChevronDownIcon, Loader2Icon, WorkflowIcon } from 'lucide-react';+import type { FC, PropsWithChildren } from 'react';++import { cn } from '../../../components/assistant-ui/lib/utils';+import type { ThreadGroupPart } from '../../../components/assistant-ui/thread';+import { ToolFallback } from '../../../components/assistant-ui/tool-fallback';+import {+ ToolGroupContent,+ ToolGroupRoot,+ ToolGroupTrigger,+} from '../../../components/assistant-ui/tool-group';+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from '../../../components/assistant-ui/ui/collapsible';+import type { SubagentActivity } from '../../../store/chatRuntimeSlice';+import { SubagentActivityBlock } from './SubagentActivityBlock';++function asSubagentActivity(value: unknown): SubagentActivity | undefined {+ if (!value || typeof value !== 'object') return undefined;+ const candidate = value as Partial<SubagentActivity>;+ if (+ typeof candidate.taskId !== 'string' ||+ typeof candidate.agentId !== 'string' ||+ !Array.isArray(candidate.toolCalls)+ ) {+ return undefined;+ }+ return candidate as SubagentActivity;+}++function readSubagentState(+ args: unknown,+ result: unknown+): { activity: SubagentActivity | undefined; running: boolean } {+ const completed = asSubagentActivity(result);+ if (completed) return { activity: completed, running: false };+ const progress =+ args && typeof args === 'object'+ ? asSubagentActivity((args as { progress?: unknown }).progress)+ : undefined;+ return { activity: progress, running: result === undefined };+}++/** Render a real OpenHuman `task` delegation using the existing activity view. */+export const SubagentCall: ToolCallMessagePartComponent = ({ args, result }) => {+ const { activity, running } = readSubagentState(args, result);+ const description = (args as { description?: string } | undefined)?.description;+ const name =+ activity?.displayName ??+ activity?.agentId ??+ (args as { subagent_type?: string } | undefined)?.subagent_type ??+ 'subagent';++ return (+ <Collapsible+ data-slot="aui_subagent-call"+ defaultOpen+ className={cn(+ 'aui-subagent-call border-border/60 dark:border-muted-foreground/15 rounded-xl border',+ running && 'border-dashed'+ )}>+ <CollapsibleTrigger className="group/subagent text-muted-foreground hover:text-foreground flex w-full items-center gap-2 px-3 py-2 text-sm transition-colors">+ <WorkflowIcon className="size-4 shrink-0" />+ <span className="text-start leading-none">+ Delegated to <b className="text-foreground">{name}</b>+ </span>+ {running ? (+ <span className="bg-muted text-muted-foreground flex shrink-0 items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] leading-none">+ <Loader2Icon className="size-3 animate-spin [animation-duration:0.6s]" />+ running+ </span>+ ) : (+ <span className="text-muted-foreground flex shrink-0 items-center gap-1.5 text-[11px] leading-none">+ <CheckIcon className="size-3.5" />+ {activity?.elapsedMs != null && (+ <span className="tabular-nums">{(activity.elapsedMs / 1000).toFixed(1)}s</span>+ )}+ </span>+ )}+ <ChevronDownIcon className="ml-auto size-4 shrink-0 -rotate-90 transition-transform group-data-[state=open]/subagent:rotate-0" />+ </CollapsibleTrigger>+ <CollapsibleContent className="px-3 pb-3">+ {description && <p className="text-muted-foreground text-xs">{description}</p>}+ {activity && <SubagentActivityBlock subagent={activity} />}+ </CollapsibleContent>+ </Collapsible>+ );+};++/** Route delegations to the rich renderer and ordinary tools to assistant-ui. */+export const ChatToolFallback: ToolCallMessagePartComponent = props =>+ props.toolName === 'task' ? <SubagentCall {...props} /> : <ToolFallback {...props} />;++/** Keep a tool group open while any contained call is still running. */+export const ChatToolGroup: FC<PropsWithChildren<{ group: ThreadGroupPart }>> = ({+ group,+ children,+}) => {+ const running = group.status.type === 'running';+ return (+ <ToolGroupRoot variant="ghost" defaultOpen={running}>+ <ToolGroupTrigger count={group.indices.length} active={running} />+ <ToolGroupContent>{children}</ToolGroupContent>+ </ToolGroupRoot>+ );+};diff --git a/app/src/features/conversations/components/ThreadGoalChip.tsx b/app/src/features/conversations/components/ThreadGoalChip.tsxindex b6c064b494..561b02b012 100644--- a/app/src/features/conversations/components/ThreadGoalChip.tsx+++ b/app/src/features/conversations/components/ThreadGoalChip.tsx@@ -27,7 +27,7 @@ import {const POLL_INTERVAL_MS = 10_000;/** Shared controller returned by {@link useThreadGoal}. */-interface ThreadGoalController {+export interface ThreadGoalController {threadId: string | null;goal: ThreadGoal | null;/** Whether the editor panel (above the composer) is open. */diff --git a/app/src/features/conversations/components/aui/auiThreadState.test.tsx b/app/src/features/conversations/components/aui/auiThreadState.test.tsxindex ece4187b86..b946ec0c4d 100644--- a/app/src/features/conversations/components/aui/auiThreadState.test.tsx+++ b/app/src/features/conversations/components/aui/auiThreadState.test.tsx@@ -3,7 +3,7 @@* must report the ADAPTER's real capabilities when one is.** The capability half is the important one. `useOpenHumanExternalStore`- * implements `onNew` / `onCancel` / `onReload` and neither `onEdit` nor+ * implements `onNew` / `onCancel` and neither `onEdit` nor* `setMessages`, so assistant-ui reports `edit` and `switchToBranch` as false.* The transcript renders no edit composer and no `BranchPickerPrimitive`* because of that, and this test is what would fail the day someone wires andiff --git a/app/src/features/conversations/components/aui/auiThreadState.ts b/app/src/features/conversations/components/aui/auiThreadState.tsindex 008e2eae99..a73587d31d 100644--- a/app/src/features/conversations/components/aui/auiThreadState.ts+++ b/app/src/features/conversations/components/aui/auiThreadState.ts@@ -52,7 +52,7 @@ export function useAuiThreadRunning(): boolean | undefined {/*** The two capabilities the external-store adapter does NOT implement.*- * `useOpenHumanExternalStore` supplies `onNew` / `onCancel` / `onReload` only;+ * `useOpenHumanExternalStore` supplies `onNew` / `onCancel` only;* it implements neither `onEdit` nor `setMessages`, which is what assistant-ui* requires for message editing and for the branch picker. The runtime reports* that faithfully, so this hook is the honest gate for those affordances ratherdiff --git a/app/src/features/conversations/components/composer/ContextWindowPill.test.ts b/app/src/features/conversations/components/composer/ContextWindowPill.test.tsnew file mode 100644index 0000000000..68ec94a652--- /dev/null+++ b/app/src/features/conversations/components/composer/ContextWindowPill.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import { emptySessionTokenUsage } from '../../../../store/chatRuntimeSlice';+import { contextUsageFromTokenUsage } from './ContextWindowPill';++describe('contextUsageFromTokenUsage', () => {+ it('keeps cached input separate from fresh input', () => {+ expect(+ contextUsageFromTokenUsage({+ ...emptySessionTokenUsage(),+ inputTokens: 1_000,+ cachedTokens: 400,+ outputTokens: 250,+ costUsd: 0.02,+ contextWindow: 128_000,+ lastTurnContextUsed: 900,+ })+ ).toEqual({+ used: 900,+ limit: 128_000,+ input: 600,+ cachedInput: 400,+ output: 250,+ costUsd: 0.02,+ });+ });++ it('preserves an unknown context limit as zero', () => {+ expect(contextUsageFromTokenUsage(emptySessionTokenUsage()).limit).toBe(0);+ });++ it('uses the selected model context window instead of stale turn usage', () => {+ const usage = { ...emptySessionTokenUsage(), contextWindow: 200_000 };+ expect(contextUsageFromTokenUsage(usage, 128_000).limit).toBe(128_000);+ expect(contextUsageFromTokenUsage(usage, null).limit).toBe(0);+ });+});diff --git a/app/src/features/conversations/components/composer/ContextWindowPill.tsx b/app/src/features/conversations/components/composer/ContextWindowPill.tsxindex a464ad3bc0..9d1471bd87 100644--- a/app/src/features/conversations/components/composer/ContextWindowPill.tsx+++ b/app/src/features/conversations/components/composer/ContextWindowPill.tsx@@ -7,6 +7,7 @@ import {import { GaugeIcon } from 'lucide-react';import { useT } from '../../../../lib/i18n/I18nContext';+import type { SessionTokenUsage } from '../../../../store/chatRuntimeSlice';/*** Token accounting for the current thread.@@ -28,6 +29,27 @@ export type ContextUsage = {costUsd: number;};+/** Map the authoritative Redux token bucket onto the compact meter shape. */+export function contextUsageFromTokenUsage(+ usage: SessionTokenUsage,+ selectedModelContextWindow?: number | null+): ContextUsage {+ const cachedInput = Math.max(0, usage.cachedTokens || 0);+ return {+ used: Math.max(0, usage.lastTurnContextUsed || 0),+ limit:+ selectedModelContextWindow === undefined+ ? Math.max(0, usage.contextWindow || 0)+ : Math.max(0, selectedModelContextWindow ?? 0),+ // `inputTokens` includes provider-reported cache reads. Keep fresh input+ // and cached input in distinct rows instead of counting cache hits twice.+ input: Math.max(0, (usage.inputTokens || 0) - cachedInput),+ cachedInput,+ output: Math.max(0, usage.outputTokens || 0),+ costUsd: Math.max(0, usage.costUsd || 0),+ };+}+const compact = (n: number): string =>n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n);@@ -49,7 +71,8 @@ const Row = ({ label, value }: { label: string; value: string }) => (*/export function ContextWindowPill({ usage }: { usage: ContextUsage }) {const { t } = useT();- const ratio = usage.limit > 0 ? Math.min(1, usage.used / usage.limit) : 0;+ const limitKnown = usage.limit > 0;+ const ratio = limitKnown ? Math.min(1, usage.used / usage.limit) : 0;// Amber past three quarters, red past nine tenths: the points where the next// long turn starts being at risk of truncation.const tone = ratio > 0.9 ? 'bg-coral-500' : ratio > 0.75 ? 'bg-amber-500' : 'bg-primary-500';@@ -65,12 +88,12 @@ export function ContextWindowPill({ usage }: { usage: ContextUsage }) {className="text-muted-foreground hover:text-foreground hover:bg-muted flex h-7 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-xs transition-colors"><GaugeIcon className="size-3.5" /><span className="tabular-nums">- {compact(usage.used)}/{compact(usage.limit)}+ {compact(usage.used)}/{limitKnown ? compact(usage.limit) : '—'}</span><span className="bg-muted h-1 w-8 overflow-hidden rounded-full"><spanclassName={`block h-full rounded-full ${tone}`}- style={{ width: `${Math.max(2, ratio * 100)}%` }}+ style={{ width: limitKnown ? `${Math.max(2, ratio * 100)}%` : '0%' }}/></span></button>diff --git a/app/src/features/conversations/components/composer/GoalSelector.tsx b/app/src/features/conversations/components/composer/GoalSelector.tsxdeleted file mode 100644index 29d0916606..0000000000--- a/app/src/features/conversations/components/composer/GoalSelector.tsx+++ /dev/null@@ -1,96 +0,0 @@-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/assistant-ui/ui/dialog';-import { TargetIcon } from 'lucide-react';-import { useEffect, useState } from 'react';--import { Button } from '../../../../components/ui';-import { useT } from '../../../../lib/i18n/I18nContext';--export type GoalSelectorProps = {- goal: string | null;- onGoalChange: (goal: string | null) => void;- /** Controlled so a slash command can open the same dialog the pill opens. */- open: boolean;- onOpenChange: (open: boolean) => void;-};--/**- * The thread's goal: a pill showing the current one, and a dialog to set, edit- * or remove it.- *- * Open state is controlled by the caller rather than owned here because there- * are two ways in — clicking the pill and typing `/goal` — and a component that- * owned its own state could only serve the first.- */-export function GoalSelector({ goal, onGoalChange, open, onOpenChange }: GoalSelectorProps) {- const { t } = useT();- const [draft, setDraft] = useState(goal ?? '');-- // Reopening after a cancel should show the saved goal, not the abandoned- // edit, so the draft resyncs on each open rather than only on mount.- useEffect(() => {- if (open) setDraft(goal ?? '');- }, [open, goal]);-- const save = () => {- const trimmed = draft.trim();- onGoalChange(trimmed.length > 0 ? trimmed : null);- onOpenChange(false);- };-- return (- <>- <button- type="button"- onClick={() => onOpenChange(true)}- aria-label={t('conversations.composer.goal.title')}- className="text-muted-foreground hover:text-foreground hover:bg-muted flex h-7 min-w-0 shrink items-center gap-1.5 rounded-full px-2.5 text-xs transition-colors">- <TargetIcon className="size-3.5 shrink-0" />- <span className="max-w-40 truncate">{goal ?? t('conversations.composer.goal.set')}</span>- </button>-- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="sm:max-w-md">- <DialogHeader>- <DialogTitle>{t('conversations.composer.goal.title')}</DialogTitle>- <DialogDescription>{t('conversations.composer.goal.description')}</DialogDescription>- </DialogHeader>-- <textarea- value={draft}- onChange={event => setDraft(event.target.value)}- rows={3}- autoFocus- placeholder={t('conversations.composer.goal.placeholder')}- className="w-full resize-none rounded-lg border border-line bg-surface px-3 py-2 text-sm text-content placeholder:text-content-faint focus:outline-hidden focus:ring-2 focus:ring-primary-500/20"- />-- <DialogFooter>- {goal !== null && (- <Button- variant="tertiary"- onClick={() => {- onGoalChange(null);- onOpenChange(false);- }}>- {t('common.remove')}- </Button>- )}- <Button variant="secondary" onClick={() => onOpenChange(false)}>- {t('common.cancel')}- </Button>- <Button onClick={save}>{t('common.save')}</Button>- </DialogFooter>- </DialogContent>- </Dialog>- </>- );-}--export default GoalSelector;diff --git a/app/src/features/conversations/hooks/useChatSurfaceRegistration.test.tsx b/app/src/features/conversations/hooks/useChatSurfaceRegistration.test.tsxindex 6643304060..a9c7f2a8a7 100644--- a/app/src/features/conversations/hooks/useChatSurfaceRegistration.test.tsx+++ b/app/src/features/conversations/hooks/useChatSurfaceRegistration.test.tsx@@ -26,14 +26,15 @@ afterEach(() => __resetChatSurfaces());function useHarness(threadId: string | null,send: (text?: string) => Promise<void>,- stop: () => void+ stop: () => void,+ registerWithoutThread = false) {const sendRef = useRef<((text?: string) => Promise<void>) | null>(null);const stopRef = useRef<(() => void) | null>(null);// Assigned during render, exactly as `Conversations.tsx` does it.sendRef.current = send;stopRef.current = stop;- useChatSurfaceRegistration(threadId, sendRef, stopRef);+ useChatSurfaceRegistration(threadId, sendRef, stopRef, registerWithoutThread);}describe('useChatSurfaceRegistration', () => {@@ -89,6 +90,15 @@ describe('useChatSurfaceRegistration', () => {expect(getChatSurface(null)).toBeNull();});+ it('can register the home composer before its first thread exists', async () => {+ const send = vi.fn(async () => {});+ renderHook(() => useHarness(null, send, () => {}, true));++ await getChatSurface(null)?.send('/new');++ expect(send).toHaveBeenCalledWith('/new');+ });+it('keeps the registered identity stable across re-renders with fresh closures', () => {const { rerender } = renderHook(({ send }: { send: () => Promise<void> }) => useHarness('t-1', send, () => {}),diff --git a/app/src/features/conversations/hooks/useChatSurfaceRegistration.ts b/app/src/features/conversations/hooks/useChatSurfaceRegistration.tsindex f033ec920e..0f9dee84ca 100644--- a/app/src/features/conversations/hooks/useChatSurfaceRegistration.ts+++ b/app/src/features/conversations/hooks/useChatSurfaceRegistration.ts@@ -30,10 +30,11 @@ const debug = debugFactory('openhuman:chat-surface');export function useChatSurfaceRegistration(threadId: string | null,sendRef: RefObject<((text?: string) => Promise<void>) | null>,- stopRef: RefObject<(() => void) | null>+ stopRef: RefObject<(() => void) | null>,+ registerWithoutThread = false): void {useEffect(() => {- if (!threadId) return;+ if (!threadId && !registerWithoutThread) return;debug('[chat] registering assistant-ui chat surface thread=%s', threadId);const dispose = registerChatSurface(threadId, {send: async (text: string) => {@@ -51,5 +52,5 @@ export function useChatSurfaceRegistration(debug('[chat] unregistering assistant-ui chat surface thread=%s', threadId);dispose();};- }, [threadId, sendRef, stopRef]);+ }, [registerWithoutThread, threadId, sendRef, stopRef]);}diff --git a/app/src/lib/assistantUiMock/index.ts b/app/src/lib/assistantUiMock/index.tsdeleted file mode 100644index 0783cdb79d..0000000000--- a/app/src/lib/assistantUiMock/index.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * A scripted, offline assistant-ui turn.- *- * Two surfaces render assistant-ui against a stand-in model while the real- * OpenHuman seams are reconnected one at a time: the main chat pane- * (`features/conversations/components/AssistantUiChat`) and the vendored- * upstream demo (`pages/dev/assistant-ui-demo`). Both need the same thing —- * a turn that exercises every part the transcript can draw — so the script,- * the adapter that streams it, and the subagent renderer live here rather- * than inside either consumer.- *- * Nothing in here reaches the core, the backend, or any provider.- */-export { mockChatModelAdapter } from './mockChatModel';-export { buildSeedMessages, MOCK_SCRIPT, SEED_PROMPT } from './mockScript';-export type { MockStep, MockSubagentResult, MockSubagentStep } from './mockScript';-export { MockToolFallback, MockToolGroup, SubagentCall } from './SubagentCall';diff --git a/app/src/lib/commands/globalActions.ts b/app/src/lib/commands/globalActions.tsindex 3663f77133..f8d106575b 100644--- a/app/src/lib/commands/globalActions.ts+++ b/app/src/lib/commands/globalActions.ts@@ -80,6 +80,7 @@ interface GlobalActionDef {register?: boolean;handler: () => void;keywords?: string[];+ slashCommand?: { id: string; descriptionKey?: string };}/**@@ -186,6 +187,7 @@ function buildGlobalActions(h: GlobalActionHandlers): GlobalActionDef[] {allowInInput: true,handler: h.newChat,keywords: ['new', 'thread', 'compose', 'conversation', 'session'],+ slashCommand: { id: 'clear', descriptionKey: 'conversations.composer.command.clear' },},// ── View ────────────────────────────────────────────────────────────@@ -254,6 +256,7 @@ export function registerGlobalActions(shortcut: a.shortcut,handler: a.handler,keywords: a.keywords,+ slashCommand: a.slashCommand,allowInInput: a.allowInInput,enabled: a.enabled,},diff --git a/app/src/lib/commands/types.ts b/app/src/lib/commands/types.tsindex a0d19f9387..45a641a766 100644--- a/app/src/lib/commands/types.ts+++ b/app/src/lib/commands/types.ts@@ -28,6 +28,13 @@ export interface Action {repeat?: boolean;preventDefault?: boolean;keywords?: string[];+ /** Expose this registered action in assistant-ui's composer `/` menu. */+ slashCommand?: {+ /** Composer command text without the leading slash. */+ id: string;+ /** Optional i18n description key; falls back to `labelKey` / `label`. */+ descriptionKey?: string;+ };}export interface RegisteredAction extends Action {diff --git a/app/src/lib/commands/useSlashCommands.test.ts b/app/src/lib/commands/useSlashCommands.test.tsnew file mode 100644index 0000000000..addefadba1--- /dev/null+++ b/app/src/lib/commands/useSlashCommands.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it, vi } from 'vitest';++import { registry } from './registry';+import type { RegisteredAction } from './types';+import { slashCommandsFromActions } from './useSlashCommands';++describe('slashCommandsFromActions', () => {+ it('exposes only composer-enabled registry actions and executes the registry action', () => {+ const frame = Symbol('chat');+ const clear = vi.fn();+ registry.reset();+ registry.setActiveStack([frame]);+ registry.registerAction(+ {+ id: 'chat.new',+ label: 'New chat',+ handler: clear,+ slashCommand: { id: 'clear', descriptionKey: 'command.clear' },+ },+ frame+ );+ const actions = registry.getActiveActions([frame]) as RegisteredAction[];+ const commands = slashCommandsFromActions(actions, (key, fallback) => `${key}:${fallback}`);++ expect(commands).toHaveLength(1);+ expect(commands[0]).toMatchObject({ id: 'clear', description: 'command.clear:New chat' });+ commands[0]?.execute?.();+ expect(clear).toHaveBeenCalledOnce();+ });+});diff --git a/app/src/lib/commands/useSlashCommands.ts b/app/src/lib/commands/useSlashCommands.tsnew file mode 100644index 0000000000..d697832a61--- /dev/null+++ b/app/src/lib/commands/useSlashCommands.ts@@ -0,0 +1,47 @@+import type { Unstable_SlashCommand } from '@assistant-ui/react';+import { useMemo, useSyncExternalStore } from 'react';++import { useT } from '../i18n/I18nContext';+import { hotkeyManager } from './hotkeyManager';+import { registry } from './registry';+import type { RegisteredAction } from './types';++function subscribe(listener: () => void): () => void {+ const unregisterRegistry = registry.subscribe(listener);+ const unregisterHotkeys = hotkeyManager.subscribe(listener);+ return () => {+ unregisterRegistry();+ unregisterHotkeys();+ };+}++function getSnapshot(): RegisteredAction[] {+ return registry.getActiveActions(hotkeyManager.getStackSymbols());+}++export function slashCommandsFromActions(+ actions: readonly RegisteredAction[],+ translate: (key: string, fallback?: string) => string+): readonly Unstable_SlashCommand[] {+ return actions.flatMap(action => {+ const slash = action.slashCommand;+ if (!slash) return [];+ const descriptionKey = slash.descriptionKey ?? action.labelKey;+ return [+ {+ id: slash.id,+ description: descriptionKey ? translate(descriptionKey, action.label) : action.label,+ execute: () => {+ registry.runAction(action.id);+ },+ },+ ];+ });+}++/** Composer `/` commands projected from the same active registry as the palette. */+export function useSlashCommands(): readonly Unstable_SlashCommand[] {+ const { t } = useT();+ const actions = useSyncExternalStore(subscribe, getSnapshot);+ return useMemo(() => slashCommandsFromActions(actions, t), [actions, t]);+}diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.tsindex abeb219978..0ab75ecc4a 100644--- a/app/src/lib/i18n/ar.ts+++ b/app/src/lib/i18n/ar.ts@@ -3370,10 +3370,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': 'مدخلات مخزّنة','conversations.composer.context.output': 'المخرجات','conversations.composer.context.cost': 'التكلفة',- 'conversations.composer.goal.title': 'هدف المحادثة',- 'conversations.composer.goal.set': 'تحديد هدف',- 'conversations.composer.goal.description': 'امنح هذه المحادثة شيئًا تعمل من أجله. يبقى الهدف مرتبطًا بها.',- 'conversations.composer.goal.placeholder': 'ما الذي يجب أن تحققه هذه المحادثة؟','conversations.composer.command.clear': 'مسح المحادثة','conversations.composer.command.goal': 'تحديد هدف المحادثة أو تعديله','conversations.planReview.title': 'مراجعة الخطة',diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.tsindex 5be0b6c64d..3a3271ca6a 100644--- a/app/src/lib/i18n/bn.ts+++ b/app/src/lib/i18n/bn.ts@@ -3450,10 +3450,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': 'ক্যাশ করা ইনপুট','conversations.composer.context.output': 'আউটপুট','conversations.composer.context.cost': 'খরচ',- 'conversations.composer.goal.title': 'থ্রেডের লক্ষ্য',- 'conversations.composer.goal.set': 'লক্ষ্য নির্ধারণ',- 'conversations.composer.goal.description': 'এই থ্রেডকে কাজ করার মতো একটি লক্ষ্য দিন। এটি থ্রেডের সঙ্গেই থাকে।',- 'conversations.composer.goal.placeholder': 'এই থ্রেড কী অর্জন করবে?','conversations.composer.command.clear': 'কথোপকথন মুছে ফেলুন','conversations.composer.command.goal': 'থ্রেডের লক্ষ্য নির্ধারণ বা সম্পাদনা করুন','conversations.planReview.title': 'পরিকল্পনা পর্যালোচনা করুন',diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.tsindex 067737d58f..76cd7b827e 100644--- a/app/src/lib/i18n/de.ts+++ b/app/src/lib/i18n/de.ts@@ -3543,10 +3543,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': 'Zwischengespeicherte Eingabe','conversations.composer.context.output': 'Ausgabe','conversations.composer.context.cost': 'Kosten',- 'conversations.composer.goal.title': 'Ziel des Threads',- 'conversations.composer.goal.set': 'Ziel festlegen',- 'conversations.composer.goal.description': 'Geben Sie diesem Thread ein Ziel. Es bleibt beim Thread.',- 'conversations.composer.goal.placeholder': 'Was soll dieser Thread erreichen?','conversations.composer.command.clear': 'Unterhaltung leeren','conversations.composer.command.goal': 'Ziel des Threads festlegen oder bearbeiten','conversations.planReview.title': 'Plan prüfen',diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.tsindex e469ba8ed1..cb8ea45106 100644--- a/app/src/lib/i18n/en.ts+++ b/app/src/lib/i18n/en.ts@@ -3715,10 +3715,6 @@ const en: TranslationMap = {'conversations.composer.context.cached': 'Cached input','conversations.composer.context.output': 'Output','conversations.composer.context.cost': 'Cost',- 'conversations.composer.goal.title': 'Thread goal',- 'conversations.composer.goal.set': 'Set goal',- 'conversations.composer.goal.description': 'Give this thread something to work towards. It stays with the thread.',- 'conversations.composer.goal.placeholder': 'What should this thread accomplish?','conversations.composer.command.clear': 'Clear the conversation','conversations.composer.command.goal': 'Set or edit the thread goal','conversations.planReview.title': 'Review plan',diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.tsindex 07f2f8fd7b..b2a6f6dd5a 100644--- a/app/src/lib/i18n/es.ts+++ b/app/src/lib/i18n/es.ts@@ -3508,10 +3508,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': 'Entrada en caché','conversations.composer.context.output': 'Salida','conversations.composer.context.cost': 'Coste',- 'conversations.composer.goal.title': 'Objetivo del hilo',- 'conversations.composer.goal.set': 'Definir objetivo',- 'conversations.composer.goal.description': 'Dale a este hilo algo que lograr. El objetivo se queda con el hilo.',- 'conversations.composer.goal.placeholder': '¿Qué debería lograr este hilo?','conversations.composer.command.clear': 'Vaciar la conversación','conversations.composer.command.goal': 'Definir o editar el objetivo del hilo','conversations.planReview.title': 'Revisar plan',diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.tsindex 1b9e73b859..49e81d7a53 100644--- a/app/src/lib/i18n/fr.ts+++ b/app/src/lib/i18n/fr.ts@@ -3533,10 +3533,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': 'Entrée en cache','conversations.composer.context.output': 'Sortie','conversations.composer.context.cost': 'Coût',- 'conversations.composer.goal.title': 'Objectif du fil',- 'conversations.composer.goal.set': 'Définir un objectif',- 'conversations.composer.goal.description': 'Donnez un objectif à ce fil. Il reste associé au fil.',- 'conversations.composer.goal.placeholder': 'Que doit accomplir ce fil ?','conversations.composer.command.clear': 'Effacer la conversation','conversations.composer.command.goal': 'Définir ou modifier l’objectif du fil','conversations.planReview.title': 'Examiner le plan',diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.tsindex 1ca395e385..e6a4b8ef65 100644--- a/app/src/lib/i18n/hi.ts+++ b/app/src/lib/i18n/hi.ts@@ -3449,10 +3449,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': 'कैश किया गया इनपुट','conversations.composer.context.output': 'आउटपुट','conversations.composer.context.cost': 'लागत',- 'conversations.composer.goal.title': 'थ्रेड का लक्ष्य',- 'conversations.composer.goal.set': 'लक्ष्य तय करें',- 'conversations.composer.goal.description': 'इस थ्रेड को कोई लक्ष्य दें। यह थ्रेड के साथ ही रहता है।',- 'conversations.composer.goal.placeholder': 'यह थ्रेड क्या हासिल करे?','conversations.composer.command.clear': 'बातचीत साफ़ करें','conversations.composer.command.goal': 'थ्रेड का लक्ष्य तय करें या बदलें','conversations.planReview.title': 'योजना की समीक्षा करें',diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.tsindex 62716079b8..8159a6de6e 100644--- a/app/src/lib/i18n/id.ts+++ b/app/src/lib/i18n/id.ts@@ -3462,10 +3462,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': 'Masukan tersimpan','conversations.composer.context.output': 'Keluaran','conversations.composer.context.cost': 'Biaya',- 'conversations.composer.goal.title': 'Tujuan utas',- 'conversations.composer.goal.set': 'Tetapkan tujuan',- 'conversations.composer.goal.description': 'Beri utas ini sesuatu untuk dicapai. Tujuannya melekat pada utas.',- 'conversations.composer.goal.placeholder': 'Apa yang harus dicapai utas ini?','conversations.composer.command.clear': 'Bersihkan percakapan','conversations.composer.command.goal': 'Tetapkan atau ubah tujuan utas','conversations.planReview.title': 'Tinjau rencana',diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.tsindex 4e20e154c7..8dacacbb2a 100644--- a/app/src/lib/i18n/it.ts+++ b/app/src/lib/i18n/it.ts@@ -3507,10 +3507,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': 'Input in cache','conversations.composer.context.output': 'Output','conversations.composer.context.cost': 'Costo',- 'conversations.composer.goal.title': 'Obiettivo della conversazione',- 'conversations.composer.goal.set': 'Imposta un obiettivo',- 'conversations.composer.goal.description': 'Dai a questa conversazione un obiettivo da raggiungere. Resta legato alla conversazione.',- 'conversations.composer.goal.placeholder': 'Che cosa deve raggiungere questa conversazione?','conversations.composer.command.clear': 'Svuota la conversazione','conversations.composer.command.goal': 'Imposta o modifica l’obiettivo della conversazione','conversations.planReview.title': 'Rivedi il piano',diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.tsindex bd4755fc09..36cb326fb4 100644--- a/app/src/lib/i18n/ko.ts+++ b/app/src/lib/i18n/ko.ts@@ -3412,10 +3412,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': '캐시된 입력','conversations.composer.context.output': '출력','conversations.composer.context.cost': '비용',- 'conversations.composer.goal.title': '스레드 목표',- 'conversations.composer.goal.set': '목표 설정',- 'conversations.composer.goal.description': '이 스레드가 이룰 목표를 정하세요. 목표는 스레드에 남습니다.',- 'conversations.composer.goal.placeholder': '이 스레드로 무엇을 이루고 싶나요?','conversations.composer.command.clear': '대화 비우기','conversations.composer.command.goal': '스레드 목표 설정 또는 수정','conversations.planReview.title': '계획 검토',diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.tsindex 1bf9c8a424..dc24b59a7e 100644--- a/app/src/lib/i18n/pl.ts+++ b/app/src/lib/i18n/pl.ts@@ -3488,10 +3488,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': 'Wejście z pamięci podręcznej','conversations.composer.context.output': 'Wyjście','conversations.composer.context.cost': 'Koszt',- 'conversations.composer.goal.title': 'Cel wątku',- 'conversations.composer.goal.set': 'Ustaw cel',- 'conversations.composer.goal.description': 'Nadaj temu wątkowi cel do osiągnięcia. Zostaje przypisany do wątku.',- 'conversations.composer.goal.placeholder': 'Co ten wątek ma osiągnąć?','conversations.composer.command.clear': 'Wyczyść rozmowę','conversations.composer.command.goal': 'Ustaw lub zmień cel wątku','conversations.planReview.title': 'Przejrzyj plan',diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.tsindex 2244200f03..7090c35c4f 100644--- a/app/src/lib/i18n/pt.ts+++ b/app/src/lib/i18n/pt.ts@@ -3502,10 +3502,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': 'Entrada em cache','conversations.composer.context.output': 'Saída','conversations.composer.context.cost': 'Custo',- 'conversations.composer.goal.title': 'Objetivo da conversa',- 'conversations.composer.goal.set': 'Definir objetivo',- 'conversations.composer.goal.description': 'Dê a esta conversa algo a alcançar. O objetivo fica com a conversa.',- 'conversations.composer.goal.placeholder': 'O que esta conversa deve alcançar?','conversations.composer.command.clear': 'Limpar a conversa','conversations.composer.command.goal': 'Definir ou editar o objetivo da conversa','conversations.planReview.title': 'Revisar plano',diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex 04ad724ffc..46e0eb703c 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -3474,10 +3474,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': 'Ввод из кэша','conversations.composer.context.output': 'Вывод','conversations.composer.context.cost': 'Стоимость',- 'conversations.composer.goal.title': 'Цель обсуждения',- 'conversations.composer.goal.set': 'Задать цель',- 'conversations.composer.goal.description': 'Задайте этому обсуждению цель. Она сохраняется вместе с ним.',- 'conversations.composer.goal.placeholder': 'Чего должно достичь это обсуждение?','conversations.composer.command.clear': 'Очистить переписку','conversations.composer.command.goal': 'Задать или изменить цель обсуждения','conversations.planReview.title': 'Проверить план',diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.tsindex eca63c72b3..471a6f3f16 100644--- a/app/src/lib/i18n/zh-CN.ts+++ b/app/src/lib/i18n/zh-CN.ts@@ -3263,10 +3263,6 @@ const messages: TranslationMap = {'conversations.composer.context.cached': '缓存输入','conversations.composer.context.output': '输出','conversations.composer.context.cost': '费用',- 'conversations.composer.goal.title': '会话目标',- 'conversations.composer.goal.set': '设置目标',- 'conversations.composer.goal.description': '给这个会话一个要达成的目标,它会一直跟随该会话。',- 'conversations.composer.goal.placeholder': '这个会话要达成什么?','conversations.composer.command.clear': '清空对话','conversations.composer.command.goal': '设置或修改会话目标','conversations.planReview.title': '审阅计划',diff --git a/app/src/pages/__tests__/Conversations.render.test.tsx b/app/src/pages/__tests__/Conversations.render.test.tsxindex 50e83d7b8b..6ad3b85430 100644--- a/app/src/pages/__tests__/Conversations.render.test.tsx+++ b/app/src/pages/__tests__/Conversations.render.test.tsx@@ -19,23 +19,18 @@ import { chatCancel, chatClearQueue, chatSend } from '../../services/chatServiceimport { CoreRpcError } from '../../services/coreRpcClient';import agentProfileReducer from '../../store/agentProfileSlice';import chatRuntimeReducer, {- appendProcessingProse,beginInferenceTurn,bumpInferenceHeartbeatForThread,- clearFollowupsForThread,- enqueueFollowup,markInferenceTurnStreaming,setInferenceStatusForThread,- setPendingPlanReviewForThread,setStreamingAssistantForThread,- setTaskBoardForThread,setToolTimelineForThread,setTurnTimelinesForThread,} from '../../store/chatRuntimeSlice';import layoutReducer from '../../store/layoutSlice';import socketReducer from '../../store/socketSlice';import themeReducer from '../../store/themeSlice';-import threadReducer, { setSelectedThread } from '../../store/threadSlice';+import threadReducer from '../../store/threadSlice';import type { Thread, ThreadMessage } from '../../types/thread';// ── Hoisted mock state ─────────────────────────────────────────────────────@@ -90,7 +85,7 @@ vi.mock('../../services/api/threadApi', () => ({decidePlan: vi.fn().mockResolvedValue({ threadId: 't-1', cards: [], updatedAt: '2026-05-04T10:00:00Z' }),- appendMessage: vi.fn().mockResolvedValue({}),+ appendMessage: vi.fn(async (_threadId: string, message: ThreadMessage) => message),deleteThread: vi.fn().mockResolvedValue({ deleted: true }),generateTitleIfNeeded: vi.fn().mockResolvedValue({}),updateMessage: vi.fn().mockResolvedValue({}),@@ -364,16 +359,15 @@ async function renderSelectedConversation(});});- const textarea = await screen.findByPlaceholderText('Send a message...');+ const textarea = await screen.findByRole('textbox', { name: 'Message input' });return { store: renderedStore, textarea, thread };}async function submitComposerText(textarea: HTMLElement, text: string) {await act(async () => {- fireEvent.change(textarea, { target: { value: text } });+ setComposerText(textarea, text);});await waitFor(() => {- expect(textarea).toHaveValue(text);expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();});await act(async () => {@@ -381,6 +375,11 @@ async function submitComposerText(textarea: HTMLElement, text: string) {});}+function setComposerText(textarea: HTMLElement, text: string) {+ textarea.textContent = text;+ fireEvent.input(textarea, { data: text, inputType: 'insertText' });+}+// ── Tests ──────────────────────────────────────────────────────────────────describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {@@ -595,7 +594,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {});});- expect(screen.getByTestId('agent-message-text')).toHaveTextContent(+ 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();@@ -654,8 +653,8 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {});});- // No past-turn trail before hydration.- expect(screen.queryByTestId('past-turn-insights')).not.toBeInTheDocument();+ // No past-turn tool call before hydration.+ expect(screen.queryByText(/read_file/)).not.toBeInTheDocument();// Hydrate the older turn's timeline (as fetchAndHydrateTurnHistory would).await act(async () => {@@ -669,12 +668,12 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {);});- // The past turn's block now renders exactly once, above its answer.- const blocks = await screen.findAllByTestId('past-turn-insights');- expect(blocks).toHaveLength(1);+ // The past turn's tool call is projected into assistant-ui exactly once.+ fireEvent.click(await screen.findByRole('button', { name: /1 tool call/ }));+ expect(await screen.findByText('read_file')).toBeInTheDocument();});- it('keeps bubble mode interactions for assistant citations, copy, and reactions', async () => {+ 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' });@@ -726,42 +725,14 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {});});- expect(screen.queryByTestId('agent-message-text')).not.toBeInTheDocument();expect(screen.getByText('First assistant paragraph with enough text to render.')).toBeInTheDocument();- expect(screen.getByText('personal 91%')).toBeInTheDocument();- expect(screen.getByTitle(/Remembered preference/)).toBeInTheDocument();await act(async () => {- fireEvent.click(screen.getByTitle('Copy response'));+ fireEvent.click(screen.getByRole('button', { name: 'Copy' }));});expect(writeText).toHaveBeenCalledWith(agentContent);-- await act(async () => {- fireEvent.click(screen.getByTitle('Remove 👍'));- });- await waitFor(() => {- expect(threadApi.updateMessage).toHaveBeenCalledWith(- thread.id,- 'm-agent-bubble',- expect.objectContaining({ myReactions: [] })- );- });-- await act(async () => {- fireEvent.click(screen.getByTitle('Add reaction'));- });- await act(async () => {- fireEvent.click(screen.getByTitle('🎯'));- });- await waitFor(() => {- expect(threadApi.updateMessage).toHaveBeenCalledWith(- thread.id,- 'm-agent-bubble',- expect.objectContaining({ myReactions: expect.arrayContaining(['🎯']) })- );- });});// Covers budget banner: budget-exhausted banner + OpenRouter CTA@@ -1024,7 +995,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {await act(async () => {await renderConversations({ thread: emptyThreadState, socket: socketState('connected') });});- const textarea = await screen.findByPlaceholderText('Send a message...');+ const textarea = await screen.findByRole('textbox', { name: 'Message input' });vi.mocked(threadApi.createNewThread).mockClear();vi.mocked(chatSend).mockClear();@@ -1034,7 +1005,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {expect(threadApi.createNewThread).toHaveBeenCalled();});expect(chatSend).not.toHaveBeenCalled();- expect(textarea).toHaveValue('');+ expect(textarea).toHaveTextContent('');});it('blocks the send when the account is over budget (no rate-limit modal anymore)', async () => {@@ -1117,10 +1088,10 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea, thread } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'slow backend' } });+ setComposerText(textarea, 'slow backend');});await waitFor(() => {- expect(textarea).toHaveValue('slow backend');+ expect(textarea).toHaveTextContent('slow backend');expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();});@@ -1145,7 +1116,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {// 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.- expect(screen.getByTestId('stop-generation-button')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Stop generating' })).toBeInTheDocument();expect(screen.queryByRole('button', { name: 'Send message' })).not.toBeInTheDocument();resolveSend?.();});@@ -1161,7 +1132,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea, thread } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'cancel me' } });+ setComposerText(textarea, 'cancel me');});const sendButton = screen.getByRole('button', { name: 'Send message' });await act(async () => {@@ -1169,7 +1140,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {});// Empty composer + in-flight turn -> the Send button became the Stop button.- const stopButton = await screen.findByTestId('stop-generation-button');+ const stopButton = await screen.findByRole('button', { name: 'Stop generating' });await act(async () => {fireEvent.click(stopButton);});@@ -1277,7 +1248,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {it('preserves the partial reply marked stopped when Stop is clicked mid-stream (#4862)', async () => {const { thread } = await renderStreamingConversation({ streamingContent: 'half a thought' });- const stopButton = await screen.findByTestId('stop-generation-button');+ const stopButton = await screen.findByRole('button', { name: 'Stop generating' });await act(async () => {fireEvent.click(stopButton);});@@ -1300,7 +1271,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {it('does not persist a stopped message when nothing has streamed yet (#4862)', async () => {const { thread } = await renderStreamingConversation({ streamingContent: ' ' });- const stopButton = await screen.findByTestId('stop-generation-button');+ const stopButton = await screen.findByRole('button', { name: 'Stop generating' });await act(async () => {fireEvent.click(stopButton);});@@ -1317,7 +1288,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {vi.mocked(chatCancel).mockResolvedValueOnce(false);const { thread } = await renderStreamingConversation({ streamingContent: 'half a thought' });- const stopButton = await screen.findByTestId('stop-generation-button');+ const stopButton = await screen.findByRole('button', { name: 'Stop generating' });await act(async () => {fireEvent.click(stopButton);});@@ -1333,7 +1304,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {it('persists the stopped reply only once across repeated Stop clicks (#4862)', async () => {const { thread } = await renderStreamingConversation({ streamingContent: 'half a thought' });- const stopButton = await screen.findByTestId('stop-generation-button');+ 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);@@ -1357,8 +1328,8 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {streamingContent: 'streaming so far',});- const textarea = await screen.findByPlaceholderText(/Queue a follow-up/);- expect(textarea).toHaveValue('');+ const textarea = await screen.findByRole('textbox', { name: 'Message input' });+ expect(textarea).toHaveTextContent('');await act(async () => {fireEvent.keyDown(textarea, { key: 'Escape' });@@ -1367,7 +1338,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {// The turn is cancelled and the user's prompt is re-hydrated for editing.expect(chatCancel).toHaveBeenCalledWith(thread.id);await waitFor(() => {- expect(textarea).toHaveValue('my original question');+ expect(textarea).toHaveTextContent('my original question');});});@@ -1377,9 +1348,9 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {streamingContent: 'streaming so far',});- const textarea = await screen.findByPlaceholderText(/Queue a follow-up/);+ const textarea = await screen.findByRole('textbox', { name: 'Message input' });await act(async () => {- fireEvent.change(textarea, { target: { value: 'a fresh follow-up' } });+ setComposerText(textarea, 'a fresh follow-up');});await act(async () => {@@ -1388,7 +1359,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {// Interrupt still fires, but the in-progress follow-up text is left intact.expect(chatCancel).toHaveBeenCalledWith(thread.id);- expect(textarea).toHaveValue('a fresh follow-up');+ expect(textarea).toHaveTextContent('a fresh follow-up');});it('renders a Stopped marker on a stopped partial reply (#4862)', async () => {@@ -1431,7 +1402,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {it('shows Send and no Stop button while the thread is idle (#4862)', async () => {await renderSelectedConversation();- expect(screen.queryByTestId('stop-generation-button')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Stop generating' })).not.toBeInTheDocument();expect(screen.getByRole('button', { name: 'Send message' })).toBeInTheDocument();});@@ -1440,7 +1411,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'will fail locally' } });+ setComposerText(textarea, 'will fail locally');});const sendButton = screen.getByRole('button', { name: 'Send message' });await act(async () => {@@ -1456,7 +1427,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {// Pending guard released: the user can re-enter text and the send button// enables again.await act(async () => {- fireEvent.change(textarea, { target: { value: 'retry' } });+ setComposerText(textarea, 'retry');});await waitFor(() => {expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();@@ -1470,7 +1441,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'stale thread send' } });+ setComposerText(textarea, 'stale thread send');});const sendButton = screen.getByRole('button', { name: 'Send message' });await act(async () => {@@ -1484,7 +1455,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {// Stale-thread branch silently clears the guard; typing must re-enable Send.await act(async () => {- fireEvent.change(textarea, { target: { value: 'retry' } });+ setComposerText(textarea, 'retry');});await waitFor(() => {expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();@@ -1497,7 +1468,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'hang the backend' } });+ setComposerText(textarea, 'hang the backend');});const sendButton = screen.getByRole('button', { name: 'Send message' });await act(async () => {@@ -1515,7 +1486,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {// After the safety timeout, typing should re-enable Send — proves the// pending guard was reset inside the timeout callback.await act(async () => {- fireEvent.change(textarea, { target: { value: 'retry after timeout' } });+ setComposerText(textarea, 'retry after timeout');});await waitFor(() => {expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();@@ -1538,7 +1509,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea, store, thread } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'kick off a sub-agent loop' } });+ setComposerText(textarea, 'kick off a sub-agent loop');});await act(async () => {fireEvent.click(screen.getByRole('button', { name: 'Send message' }));@@ -1597,9 +1568,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea, store, thread } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, {- target: { value: 'summarize a big codebase in reasoning mode' },- });+ setComposerText(textarea, 'summarize a big codebase in reasoning mode');});await act(async () => {fireEvent.click(screen.getByRole('button', { name: 'Send message' }));@@ -1636,7 +1605,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea, store, thread } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'task whose connection dies' } });+ setComposerText(textarea, 'task whose connection dies');});await act(async () => {fireEvent.click(screen.getByRole('button', { name: 'Send message' }));@@ -1674,7 +1643,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea, store } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'send on the foreground thread' } });+ setComposerText(textarea, 'send on the foreground thread');});await act(async () => {fireEvent.click(screen.getByRole('button', { name: 'Send message' }));@@ -1711,7 +1680,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {await vi.advanceTimersByTimeAsync(50_000);});await act(async () => {- fireEvent.change(textarea, { target: { value: 'retry after timeout' } });+ setComposerText(textarea, 'retry after timeout');});await waitFor(() => {expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();@@ -1726,10 +1695,10 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'doomed send' } });+ setComposerText(textarea, 'doomed send');});await waitFor(() => {- expect(textarea).toHaveValue('doomed send');+ expect(textarea).toHaveTextContent('doomed send');});const sendButton = screen.getByRole('button', { name: 'Send message' });@@ -1744,7 +1713,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {// 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 () => {- fireEvent.change(textarea, { target: { value: 'retry send' } });+ setComposerText(textarea, 'retry send');});await waitFor(() => {expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();@@ -1755,10 +1724,10 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea, thread } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'enter send' } });+ setComposerText(textarea, 'enter send');});await waitFor(() => {- expect(textarea).toHaveValue('enter send');+ expect(textarea).toHaveTextContent('enter send');expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();});@@ -1781,10 +1750,10 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {const { textarea } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: '你好' } });+ setComposerText(textarea, '你好');});await waitFor(() => {- expect(textarea).toHaveValue('你好');+ expect(textarea).toHaveTextContent('你好');expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();});@@ -1795,17 +1764,17 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {});expect(chatSend).not.toHaveBeenCalled();- expect(textarea).toHaveValue('你好');+ expect(textarea).toHaveTextContent('你好');});it('does not send for legacy IME keyCode 229 events', async () => {const { textarea } = await renderSelectedConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'かな' } });+ setComposerText(textarea, 'かな');});await waitFor(() => {- expect(textarea).toHaveValue('かな');+ expect(textarea).toHaveTextContent('かな');expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();});@@ -1814,17 +1783,17 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {});expect(chatSend).not.toHaveBeenCalled();- expect(textarea).toHaveValue('かな');+ 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 () => {- fireEvent.change(textarea, { target: { value: '안녕' } });+ setComposerText(textarea, '안녕');});await waitFor(() => {- expect(textarea).toHaveValue('안녕');+ expect(textarea).toHaveTextContent('안녕');expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();});@@ -1834,7 +1803,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {});expect(chatSend).not.toHaveBeenCalled();- expect(textarea).toHaveValue('안녕');+ expect(textarea).toHaveTextContent('안녕');await act(async () => {fireEvent.compositionEnd(textarea);@@ -1873,930 +1842,190 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {// 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 — worker thread back-to-parent navigation (#1624)', () => {+describe('Conversations — active-thread restore across in-app navigation', () => {beforeEach(() => {vi.clearAllMocks();- mockGetThreads.mockResolvedValue({ threads: [], count: 0 });mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });});- it('renders a back-to-parent button when the active thread has a parent', async () => {- const parent = makeThread({ id: 't-parent', title: 'Parent Conversation' });- const child = makeThread({ id: 't-child', title: 'Worker Task', parentThreadId: 't-parent' });- mockGetThreads.mockResolvedValue({ threads: [parent, child], count: 2 });+ 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: [parent, child],- selectedThreadId: child.id,- messagesByThreadId: { [child.id]: [] },+ threads: [taskThread],+ selectedThreadId: 'task-active-1',+ messagesByThreadId: { 'task-active-1': [] },},});});- // The mount effect now restores the persisted worker session directly;- // re-select it explicitly so the assertion is independent of mount timing.- await act(async () => {- store!.dispatch(setSelectedThread('t-child'));+ await waitFor(() => {+ expect(store!.getState().thread.selectedThreadId).toBe('task-active-1');});-- const backBtn = await screen.findByTestId('worker-thread-back-to-parent');- expect(backBtn.textContent).toContain('Parent Conversation');+ expect(threadApi.createNewThread).not.toHaveBeenCalled();+ expect(mockGetThreadMessages).toHaveBeenCalledWith('task-active-1');});- it('falls back to a generic title when the parent thread is missing from the list', async () => {- const parent = makeThread({ id: 't-parent', title: 'Other Parent' });- const child = makeThread({- id: 't-child',- title: 'Worker Task',- parentThreadId: 't-missing-parent',+ 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'],});- // The parent referenced by `parentThreadId` is intentionally absent from- // the thread list so the `selectedThreadParent` resolver hits its fallback- // branch. A separate parent is kept around so mount-time resume has a- // visible thread to land on.- mockGetThreads.mockResolvedValue({ threads: [parent, child], count: 2 });+ mockGetThreads.mockResolvedValue({ threads: [taskThread], count: 1 });- let store: ReturnType<typeof buildStore> | undefined;await act(async () => {- store = await renderConversations({+ await renderConversations({thread: {...emptyThreadState,- threads: [parent, child],- selectedThreadId: child.id,- messagesByThreadId: { [child.id]: [] },+ threads: [taskThread],+ selectedThreadId: 'task-active-2',+ messagesByThreadId: { 'task-active-2': [] },},});});- await act(async () => {- store!.dispatch(setSelectedThread('t-child'));- });- const backBtn = await screen.findByTestId('worker-thread-back-to-parent');- expect(backBtn.textContent).toContain('parent thread');+ await waitFor(() => {+ expect(threadApi.createNewThread).not.toHaveBeenCalled();+ });+ // Main removed the visible General/Subconscious/Tasks chips; restoring a+ // task session should not reintroduce that tab UI.+ await openSidebar();+ expect(screen.queryByRole('tab', { name: 'Tasks' })).not.toBeInTheDocument();});- it('dispatches selection + load when the back-to-parent button is clicked', async () => {- const parent = makeThread({ id: 't-parent', title: 'Parent Conversation' });- const child = makeThread({ id: 't-child', title: 'Worker Task', parentThreadId: 't-parent' });- mockGetThreads.mockResolvedValue({ threads: [parent, child], count: 2 });+ 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,- threads: [parent, child],- selectedThreadId: child.id,- messagesByThreadId: { [child.id]: [] },- },- });- });- await act(async () => {- store!.dispatch(setSelectedThread('t-child'));- });-- const backBtn = await screen.findByTestId('worker-thread-back-to-parent');- await act(async () => {- fireEvent.click(backBtn);+ store = await renderConversations({ thread: emptyThreadState });});- // After click, the redux store should reflect the parent thread as the- // newly selected conversation.await waitFor(() => {- const state = store!.getState() as { thread: { selectedThreadId: string | null } };- expect(state.thread.selectedThreadId).toBe('t-parent');+ expect(store!.getState().thread.selectedThreadId).toBe('g-1');});- // The loadThreadMessages thunk goes through the threadApi.getThreadMessages- // helper — verify it was kicked off for the parent thread.- expect(mockGetThreadMessages).toHaveBeenCalledWith('t-parent');+ expect(threadApi.createNewThread).not.toHaveBeenCalled();});- // Covers line 1871: t('chat.budgetComplete') — cycleBudgetUsd=0 exhausted branch- it('renders budgetComplete copy when cycleBudgetUsd=0 and budget is exhausted', async () => {- const teamUsage = { cycleBudgetUsd: 0, remainingUsd: 0, cycleSpentUsd: 0, cycleEndsAt: null };-- mockUseUsageState.mockReturnValue({- teamUsage,- currentPlan: null,- currentTier: 'PRO' as const,- isFreeTier: false,- usagePct: 1.0,- isNearLimit: true,- isAtLimit: true,- isBudgetExhausted: true,- shouldShowBudgetCompletedMessage: true,- isLoading: false,- refresh: vi.fn(),- });+ 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 });});- // cycleBudgetUsd=0 → false branch of cycleBudgetUsd > 0 ternary → budgetComplete key- expect(screen.getByText(/Your included budget is complete/i)).toBeInTheDocument();+ await waitFor(() => {+ expect(threadApi.createNewThread).toHaveBeenCalled();+ });});});-// #3717 (Bug 2) — A single logical assistant turn can be persisted as multiple-// agent ThreadMessages. The "Agentic task insights" panel used to be anchored-// immediately before the LAST agent message, which dropped it BETWEEN the-// earlier agent content and the final message — splitting one response into two-// disconnected chunks. The panel (and the "View full agent process" button) now-// render exactly once, anchored after the latest turn's USER message so they-// sit ABOVE the whole answer (processing before result) — never split between-// agent bubbles, regardless of how many agent messages the turn produced.-describe('Conversations — agent task insights panel anchoring (#3717 Bug 2)', () => {+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 });- mockUseUsageState.mockReturnValue({- 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(),- });+ vi.mocked(chatSend).mockResolvedValue(undefined);+ vi.mocked(chatClearQueue).mockResolvedValue(0);});- it('renders the insights panel exactly once, above the answer of a multi-message turn (not split between bubbles)', async () => {- const thread = makeThread({ id: 'multi-agent-thread', title: 'Multi-message turn' });- // One logical assistant turn persisted as TWO agent ThreadMessages.- const messages: ThreadMessage[] = [- {- id: 'm-user',- sender: 'user',- type: 'text',- content: 'Plan and then summarize.',- extraMetadata: {},- createdAt: '2026-01-01T00:00:00.000Z',- },- {- id: 'm-agent-1',- sender: 'agent',- type: 'text',- content: 'First part of the answer.',- extraMetadata: {},- createdAt: '2026-01-01T00:01:00.000Z',- },- {- id: 'm-agent-2',- sender: 'agent',- type: 'text',- content: 'Second part of the answer.',- extraMetadata: {},- createdAt: '2026-01-01T00:02:00.000Z',- },- ];+ // 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: messages.length });-+ mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });let store: ReturnType<typeof buildStore> | undefined;await act(async () => {store = await renderConversations({- thread: {- ...selectedThreadState(thread),- messagesByThreadId: { [thread.id]: messages },- messages,- },+ thread: { ...selectedThreadState(thread), activeThreadIds: { [thread.id]: true } },socket: socketState('connected'),});});+ const textarea = await screen.findByRole('textbox', { name: 'Message input' });+ return { store, textarea, thread };+ }++ it('queues a plain-Enter submission as a follow-up and lists it in the strip', async () => {+ const { textarea } = await renderStreamingConversation();- // Seed the tool timeline after mount settles (mount-time turn-state- // hydration would otherwise clobber a preloaded timeline). Include a- // running subagent row so the panel exposes its "view full processing"- // affordance (drives the onViewSubagent callback below).- await screen.findByText('Second part of the answer.');await act(async () => {- store!.dispatch(- setToolTimelineForThread({- threadId: thread.id,- entries: [- { id: 'tl-1', name: 'web_fetch', round: 1, seq: 0, status: 'success' },- {- id: 'sa-1',- name: 'subagent:researcher',- round: 1,- seq: 0,- status: 'running',- subagent: { taskId: 'task-1', agentId: 'researcher', toolCalls: [] },- },- ],- })- );+ setComposerText(textarea, 'and the pricing?');+ });+ await act(async () => {+ fireEvent.keyDown(textarea, { key: 'Enter' });});- // Panel renders once — not once per agent message.- const panels = await screen.findAllByTestId('agent-task-insights');- expect(panels).toHaveLength(1);- const panel = panels[0];-- // The "View full agent process" button is hoisted alongside it — also once.- expect(screen.getAllByTestId('view-process-source')).toHaveLength(1);+ await waitFor(() => {+ expect(chatSend).toHaveBeenCalledWith(expect.objectContaining({ queueMode: 'followup' }));+ });+ expect(await screen.findByText('and the pricing?')).toBeInTheDocument();+ });- // DOM order: processing happens before the result, so the panel sits ABOVE- // the answer — after the latest turn's user message and before BOTH agent- // bubbles (never split between them, preserving the #3717 invariant).- const userText = screen.getByText('Plan and then summarize.');- const firstAgentText = screen.getByText('First part of the answer.');- const lastAgentText = screen.getByText('Second part of the answer.');- // The panel precedes the first agent bubble (and therefore both).- expect(firstAgentText.compareDocumentPosition(panel) & Node.DOCUMENT_POSITION_PRECEDING).toBe(- Node.DOCUMENT_POSITION_PRECEDING- );- expect(lastAgentText.compareDocumentPosition(panel) & Node.DOCUMENT_POSITION_PRECEDING).toBe(- Node.DOCUMENT_POSITION_PRECEDING- );- // …and follows the user message.- expect(userText.compareDocumentPosition(panel) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(- Node.DOCUMENT_POSITION_FOLLOWING- );+ it('queues via the Send button while a turn streams', async () => {+ const { textarea } = await renderStreamingConversation();- // Inline rows are compact — each shows a "View details →" link instead of- // an inline expand. Clicking one opens the full-run Agent Process Source- // side panel (every row opens the same panel).- const viewDetails = screen.getAllByTestId('view-details');- expect(viewDetails.length).toBeGreaterThan(0);await act(async () => {- fireEvent.click(viewDetails[0]);+ 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(chatSend).toHaveBeenCalledWith(expect.objectContaining({ queueMode: 'followup' }));});- expect(await screen.findByTestId('agent-process-source-panel')).toBeInTheDocument();+ expect(await screen.findByText('one more thing')).toBeInTheDocument();});- it('hides the verbose timeline when "hide agent thinking" is on, but still opens the source panel', async () => {- const thread = makeThread({ id: 'hide-insights-thread', title: 'Hide insights' });- const messages: ThreadMessage[] = [- {- id: 'm-user',- sender: 'user',- type: 'text',- content: 'How many posts?',- extraMetadata: {},- createdAt: '2026-01-01T00:00:00.000Z',- },- {- id: 'm-agent',- sender: 'agent',- type: 'text',- content: 'Zero posts went up.',- extraMetadata: {},- createdAt: '2026-01-01T00:01:00.000Z',- },- ];- mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });- mockGetThreadMessages.mockResolvedValue({ messages, count: messages.length });+ it('clears the queued follow-ups and the backend queue on Clear', async () => {+ const { textarea } = await renderStreamingConversation();- let store: ReturnType<typeof buildStore> | undefined;await act(async () => {- store = await renderConversations({- thread: {- ...selectedThreadState(thread),- messagesByThreadId: { [thread.id]: messages },- messages,- },- socket: socketState('connected'),- theme: {- mode: 'system',- tabBarLabels: 'hover',- fontSize: 'medium',- hideAgentInsights: true,- },- });+ setComposerText(textarea, 'dismiss me');});-- await screen.findByText('Zero posts went up.');await act(async () => {- store!.dispatch(- setToolTimelineForThread({- threadId: thread.id,- entries: [{ id: 'tl-1', name: 'web_fetch', round: 1, seq: 0, status: 'success' }],- })- );+ fireEvent.keyDown(textarea, { key: 'Enter' });});- // Settled turn + preference ON: the verbose inline timeline is suppressed…- expect(screen.queryByTestId('agent-task-insights')).toBeNull();- // …but the "View full agent process Source" affordance still works and the- // full run is one click away in the side panel (which renders the timeline).+ const strip = await screen.findByTestId('queued-followups');+ expect(within(strip).getByText('dismiss me')).toBeInTheDocument();+await act(async () => {- fireEvent.click(screen.getByTestId('view-process-source'));+ fireEvent.click(within(strip).getByText('Clear'));});- expect(await screen.findByTestId('agent-task-insights')).toBeInTheDocument();++ await waitFor(() => expect(chatClearQueue).toHaveBeenCalledWith('fup-thread'));+ await waitFor(() => expect(screen.queryByTestId('queued-followups')).not.toBeInTheDocument());});- it('shows a blinking "Processing" link instead of the timeline while in flight', async () => {- const thread = makeThread({ id: 'processing-thread', title: 'Processing' });- const messages: ThreadMessage[] = [- {- id: 'm-user',- sender: 'user',- type: 'text',- content: 'Go.',- extraMetadata: {},- createdAt: '2026-01-01T00:00:00.000Z',- },- ];- mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });- mockGetThreadMessages.mockResolvedValue({ messages, count: messages.length });+ it('keeps the queued pills when the backend clear fails', async () => {+ vi.mocked(chatClearQueue).mockResolvedValueOnce(null);+ const { textarea } = await renderStreamingConversation();- let store: ReturnType<typeof buildStore> | undefined;await act(async () => {- store = await renderConversations({- thread: {- ...selectedThreadState(thread),- messagesByThreadId: { [thread.id]: messages },- messages,- },- socket: socketState('connected'),- theme: {- mode: 'system',- tabBarLabels: 'hover',- fontSize: 'medium',- hideAgentInsights: true,- },- });- });-- await screen.findByText('Go.');- // Drive the thread into an in-flight turn so `isSending` is true, then seed- // a running timeline that the preference should keep hidden behind the link.- await act(async () => {- store!.dispatch(beginInferenceTurn({ threadId: thread.id }));- store!.dispatch(- setToolTimelineForThread({- threadId: thread.id,- entries: [{ id: 'tl-1', name: 'web_fetch', round: 1, seq: 0, status: 'running' }],- })- );- });-- const link = await screen.findByTestId('agent-processing-link');- expect(link).toBeInTheDocument();- expect(screen.queryByTestId('agent-task-insights')).toBeNull();-- // Clicking the compact link opens the full run in the source panel.- await act(async () => {- fireEvent.click(link);- });- expect(await screen.findByTestId('agent-task-insights')).toBeInTheDocument();- });-- it('surfaces a process-source opener for a tool-less (transcript-only) turn', async () => {- // The agent only streamed reasoning/narration — no tool calls — so the- // inline step timeline is empty, but the persisted thoughts must stay- // reachable through a standalone opener into the full-run panel.- const thread = makeThread({ id: 'transcript-only-thread', title: 'Thinking only' });- const messages: ThreadMessage[] = [- {- id: 'm-user',- sender: 'user',- type: 'text',- content: 'Just think out loud.',- extraMetadata: {},- createdAt: '2026-01-01T00:00:00.000Z',- },- {- id: 'm-agent',- sender: 'agent',- type: 'text',- content: 'Here is my reasoning result.',- extraMetadata: {},- createdAt: '2026-01-01T00:01: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,- },- socket: socketState('connected'),- });- });-- await screen.findByText('Here is my reasoning result.');- // Seed a narration-only transcript (no tool timeline at all).- await act(async () => {- store!.dispatch(- appendProcessingProse({- threadId: thread.id,- kind: 'narration',- round: 1,- delta: 'Let me reason about this carefully.',- })- );- });-- // The verbose step timeline never renders (there are no tool steps)…- expect(screen.queryByTestId('agent-task-insights')).toBeNull();- // …but the standalone opener appears and opens the full-run panel, which- // shows the persisted thoughts.- const opener = screen.getByTestId('view-process-source');- await act(async () => {- fireEvent.click(opener);- });- expect(await screen.findByTestId('agent-process-source-panel')).toBeInTheDocument();- });-- it('keeps a settled source opener when hidden and no agent message exists (cancelled first turn)', async () => {- // A cancelled first turn records timeline steps but never persists an agent- // message, so the hoisted "View full agent process Source" button does not- // render. With the timeline hidden, the fallback opener must keep those- // steps reachable.- const thread = makeThread({ id: 'cancelled-first-turn', title: 'Cancelled' });- const messages: ThreadMessage[] = [- {- id: 'm-user',- sender: 'user',- type: 'text',- content: 'Start then stop.',- 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,- },- socket: socketState('connected'),- theme: {- mode: 'system',- tabBarLabels: 'hover',- fontSize: 'medium',- hideAgentInsights: true,- },- });- });-- await screen.findByText('Start then stop.');- // Settled (no in-flight turn) timeline with steps but no agent message.- await act(async () => {- store!.dispatch(- setToolTimelineForThread({- threadId: thread.id,- entries: [{ id: 'tl-1', name: 'web_fetch', round: 1, seq: 0, status: 'cancelled' }],- })- );- });-- // No verbose timeline, and the hoisted opener is absent (no agent message)…- expect(screen.queryByTestId('agent-task-insights')).toBeNull();- expect(screen.queryByTestId('view-process-source')).toBeNull();- // …so the fallback opener carries access to the recorded steps.- const fallback = await screen.findByTestId('agent-process-source-fallback');- await act(async () => {- fireEvent.click(fallback);- });- expect(await screen.findByTestId('agent-task-insights')).toBeInTheDocument();- });-- it('remounts the standalone insights fallback (resetting its sticky disclosure) when switching between two proactive-only threads (#4944)', async () => {- // Neither thread has a user message (e.g. a proactive-only run), so the- // panel renders through the standalone fallback slot at the bottom of the- // message list — not the per-message anchor keyed by `msg.id` — which is- // the exact slot that previously had no key of its own.- const threadA = makeThread({ id: 'proactive-a', title: 'Proactive A' });- const threadB = makeThread({ id: 'proactive-b', title: 'Proactive B' });- mockGetThreads.mockResolvedValue({ threads: [threadA, threadB], count: 2 });-- let store: ReturnType<typeof buildStore> | undefined;- await act(async () => {- store = await renderConversations({- thread: {- ...emptyThreadState,- threads: [threadA, threadB],- selectedThreadId: threadA.id,- messagesByThreadId: { [threadA.id]: [], [threadB.id]: [] },- },- socket: socketState('connected'),- });- });-- // Thread A: a settled (non-running) timeline, so the group defaults to- // collapsed.- await act(async () => {- store!.dispatch(- setToolTimelineForThread({- threadId: threadA.id,- entries: [{ id: 'a-1', name: 'web_fetch', round: 1, seq: 0, status: 'success' }],- })- );- });-- const panelA = await screen.findByTestId('agent-task-insights');- // The disclosure moved from a native `<details>`/`<summary>` pair to a- // Radix `Collapsible`, so the observable is `data-state` on the root and- // the control is an `aria-expanded` button rather than a `<summary>`.- // Same element, same observable, same semantics — a port, not a- // weakening. Asserting merely that the trigger renders would leave #4944- // uncovered under a green tick.- expect(panelA).toHaveAttribute('data-state', 'closed');-- // The user manually expands it — this is the sticky per-instance- // `userOverrideOpen` state from #4942 that must not leak across threads.- const triggerA = panelA.querySelector('[aria-expanded]');- expect(triggerA).not.toBeNull();- await act(async () => {- fireEvent.click(triggerA!);- });- expect(panelA).toHaveAttribute('data-state', 'open');-- // Switch straight to a second proactive-only thread with its own settled- // timeline.- await act(async () => {- store!.dispatch(setSelectedThread(threadB.id));- store!.dispatch(- setToolTimelineForThread({- threadId: threadB.id,- entries: [{ id: 'b-1', name: 'send_email', round: 1, seq: 0, status: 'success' }],- })- );- });-- const panelB = await screen.findByTestId('agent-task-insights');- // Keyed by `selectedThreadId ?? 'none'`: switching threads remounts the- // `ToolTimelineBlock` instead of reusing the same instance, so thread B's- // panel starts collapsed again rather than inheriting thread A's- // manually-opened disclosure state.- expect(panelB).toHaveAttribute('data-state', 'closed');- });-});--describe('Conversations — open-session resume (View work)', () => {- beforeEach(() => {- vi.clearAllMocks();- mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });- });-- it('honours /chat/:threadId to open a task session on mount', async () => {- // A task-labelled session thread, reachable only via an explicit- // open-intent because it's hidden behind the default General tab.- const taskThread = makeThread({- id: 'task-open-1',- title: 'Autonomous run',- labels: ['tasks'],- });- mockGetThreads.mockResolvedValue({ threads: [taskThread], count: 1 });-- const store = buildStore({ thread: emptyThreadState });- const { default: Conversations } = await import('../../features/conversations/Conversations');-- await act(async () => {- render(- <Provider store={store}>- <MemoryRouter initialEntries={['/chat/task-open-1']}>- <Routes>- <Route path="/chat/:threadId" element={<Conversations />} />- </Routes>- </MemoryRouter>- </Provider>- );- });-- // The open-intent selects the task session (bypassing the General-tab- // filter) and loads its messages.- await waitFor(() => expect(store.getState().thread.selectedThreadId).toBe('task-open-1'));- await waitFor(() => expect(mockGetThreadMessages).toHaveBeenCalled());- });-- it("View work on a selected task board opens that card's session thread", async () => {- const thread = makeThread({ id: 'board-thread', title: 'Board thread' });- mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });-- const store = buildStore({ thread: selectedThreadState(thread) });-- const { default: Conversations } = await import('../../features/conversations/Conversations');- await act(async () => {- render(- <Provider store={store}>- <MemoryRouter initialEntries={['/conversations']}>- <Conversations />- </MemoryRouter>- </Provider>- );- });- // Let the mount-resume effect settle, then seed the selected thread's task- // board with a card that has a live session (seeding before mount gets- // clobbered by turn-state hydration).- await screen.findByPlaceholderText('Send a message...');- const selectedId = store.getState().thread.selectedThreadId ?? 'board-thread';- await act(async () => {- store.dispatch(- setTaskBoardForThread({- threadId: selectedId,- board: {- threadId: selectedId,- updatedAt: '',- cards: [- {- id: 'tc1',- title: 'Worked card',- status: 'in_progress',- order: 0,- updatedAt: '',- sessionThreadId: 'sess-99',- },- ],- },- })- );- });-- const viewBtn = await screen.findByTitle('View work');- await act(async () => {- fireEvent.click(viewBtn);- });-- // onViewSession navigates the chat view to the card's session thread.- await waitFor(() => expect(store.getState().thread.selectedThreadId).toBe('sess-99'));- });-- it('does not push chat routes when embedded chat opens task session work', async () => {- const thread = makeThread({ id: 'board-thread', title: 'Board thread' });- mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });-- const store = await renderEmbeddedConversationsRoute('/human', {- thread: selectedThreadState(thread),- });-- const selectedId = store.getState().thread.selectedThreadId ?? 'board-thread';- await act(async () => {- store.dispatch(- setTaskBoardForThread({- threadId: selectedId,- board: {- threadId: selectedId,- updatedAt: '',- cards: [- {- id: 'tc1',- title: 'Worked card',- status: 'in_progress',- order: 0,- updatedAt: '',- sessionThreadId: 'sess-99',- },- ],- },- })- );- });-- const viewBtn = await screen.findByTitle('View work');- await act(async () => {- fireEvent.click(viewBtn);- });-- await waitFor(() => expect(store.getState().thread.selectedThreadId).toBe('sess-99'));- expect(screen.getByTestId('route-path')).toHaveTextContent('/human');- });-- it('approves a parked plan from the plan-review card', async () => {- mockCallCoreRpc.mockClear().mockResolvedValue({});- const thread = makeThread({ id: 'approve-thread', title: 'Approve thread' });- mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });-- const store = await renderConversations({ thread: selectedThreadState(thread) });- const selectedId = store.getState().thread.selectedThreadId ?? 'approve-thread';- await act(async () => {- store.dispatch(- setPendingPlanReviewForThread({- threadId: selectedId,- review: { requestId: 'pr-1', summary: 'Needs sign-off', steps: ['do the thing'] },- })- );- });-- // A parked plan surfaces the PlanReviewCard above the composer; "Approve &- // run" resolves the parked turn via the plan_review_decide RPC.- const approveBtn = await screen.findByText('Approve & run');- await act(async () => {- fireEvent.click(approveBtn);- });-- await waitFor(() =>- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.plan_review_decide',- params: { request_id: 'pr-1', decision: 'approve', feedback: undefined },- })- );- });-});--// Returning to the Chat tab must restore the thread the user last had open-// (persisted on the `thread` slice, kept in-memory across in-app navigation),-// even when it's hidden behind the default General tab — a task / worker /-// subconscious / meeting session. The previous General-only resume default-// dropped such a session and, when it was the only thread, spawned a fresh-// chat — losing the active conversation.-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/Subconscious/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(chatClearQueue).mockResolvedValue(0);- });-- // 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.findByPlaceholderText(/Queue a follow-up/i);- return { store, textarea, thread };- }-- it('queues a plain-Enter submission as a follow-up and lists it in the strip', async () => {- const { textarea } = await renderStreamingConversation();-- await act(async () => {- fireEvent.change(textarea, { target: { value: 'and the pricing?' } });- });- await act(async () => {- fireEvent.keyDown(textarea, { key: 'Enter' });- });-- await waitFor(() => {- expect(chatSend).toHaveBeenCalledWith(expect.objectContaining({ queueMode: 'followup' }));- });- expect(await screen.findByText('and the pricing?')).toBeInTheDocument();- });-- it('queues via the Send button while a turn streams', async () => {- const { textarea } = await renderStreamingConversation();-- await act(async () => {- fireEvent.change(textarea, { target: { value: '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(chatSend).toHaveBeenCalledWith(expect.objectContaining({ queueMode: 'followup' }));- });- expect(await screen.findByText('one more thing')).toBeInTheDocument();- });-- it('clears the queued follow-ups and the backend queue on Clear', async () => {- const { textarea } = await renderStreamingConversation();-- await act(async () => {- fireEvent.change(textarea, { target: { value: 'dismiss me' } });- });- await act(async () => {- fireEvent.keyDown(textarea, { key: 'Enter' });- });-- const strip = await screen.findByTestId('queued-followups');- expect(within(strip).getByText('dismiss me')).toBeInTheDocument();-- await act(async () => {- fireEvent.click(within(strip).getByText('Clear'));- });-- await waitFor(() => expect(chatClearQueue).toHaveBeenCalledWith('fup-thread'));- await waitFor(() => expect(screen.queryByTestId('queued-followups')).not.toBeInTheDocument());- });-- it('keeps the queued pills when the backend clear fails', async () => {- vi.mocked(chatClearQueue).mockResolvedValueOnce(null);- const { textarea } = await renderStreamingConversation();-- await act(async () => {- fireEvent.change(textarea, { target: { value: 'still queued' } });+ setComposerText(textarea, 'still queued');});await act(async () => {fireEvent.keyDown(textarea, { key: 'Enter' });@@ -2821,7 +2050,7 @@ describe('Conversations — queued follow-ups while a turn streams', () => {const { textarea } = await renderStreamingConversation();await act(async () => {- fireEvent.change(textarea, { target: { value: 'keep me on failure' } });+ setComposerText(textarea, 'keep me on failure');});await act(async () => {fireEvent.keyDown(textarea, { key: 'Enter' });@@ -2831,248 +2060,10 @@ describe('Conversations — queued follow-ups while a turn streams', () => {// they can retry instead of silently losing it.await waitFor(() => expect(chatSend).toHaveBeenCalled());expect(screen.queryByTestId('queued-followups')).not.toBeInTheDocument();- expect(textarea).toHaveValue('keep me on failure');- });-});--describe('Conversations — message list reserves room for the floating composer footer (#4268)', () => {- beforeEach(() => {- vi.clearAllMocks();- mockGetThreads.mockResolvedValue({ threads: [], count: 0 });- mockGetThreadMessages.mockResolvedValue({ messages: [], count: 0 });- });-- function followupMessage(id: string, content: string): ThreadMessage {- return {- id,- sender: 'user',- type: 'text',- content,- extraMetadata: {},- createdAt: '2026-01-01T00:00:00.000Z',- };- }-- // Page-variant conversation with a visible message and an active (streaming)- // turn, so the message list, the follow-up composer, and the queued-followups- // panel all render together — the exact state where the overlap bug appeared.- async function renderActiveConversationWithMessages() {- const thread = makeThread({ id: 'pad-thread', title: 'Pad Thread' });- const messages: ThreadMessage[] = [- {- id: 'm-agent',- sender: 'agent',- type: 'text',- content: 'Streaming agent reply tail that must stay visible.',- extraMetadata: {},- createdAt: '2026-01-01T00:01: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,- activeThreadIds: { [thread.id]: true },- },- socket: socketState('connected'),- });- });- return { store: store as ReturnType<typeof buildStore>, thread };- }-- function paddingBottomPx(): number {- return parseInt(screen.getByTestId('chat-message-list').style.paddingBottom || '0', 10);- }-- it('reserves bottom padding via an inline style, not the static pb-32 (0 follow-ups)', async () => {- await renderActiveConversationWithMessages();- const list = screen.getByTestId('chat-message-list');- // The old static `pb-32` is gone; spacing is reserved by a dynamic inline- // style so it can grow with the footer.- expect(list.className).not.toMatch(/\bpb-32\b/);- expect(list.style.paddingBottom).not.toBe('');- expect(paddingBottomPx()).toBeGreaterThan(0);- expect(screen.queryByTestId('queued-followups')).not.toBeInTheDocument();- });-- it('keeps content padded when a single follow-up is queued', async () => {- const { store, thread } = await renderActiveConversationWithMessages();- await act(async () => {- store.dispatch(- enqueueFollowup({- threadId: thread.id,- message: followupMessage('f1', 'and the pricing?'),- label: 'and the pricing?',- })- );- });- expect(await screen.findByTestId('queued-followups')).toBeInTheDocument();- expect(paddingBottomPx()).toBeGreaterThan(0);- });-- it('keeps content padded with multiple queued follow-ups', async () => {- const { store, thread } = await renderActiveConversationWithMessages();- await act(async () => {- store.dispatch(- enqueueFollowup({- threadId: thread.id,- message: followupMessage('f1', 'one'),- label: 'one',- })- );- store.dispatch(- enqueueFollowup({- threadId: thread.id,- message: followupMessage('f2', 'two'),- label: 'two',- })- );- store.dispatch(- enqueueFollowup({- threadId: thread.id,- message: followupMessage('f3', 'three'),- label: 'three',- })- );- });- const strip = await screen.findByTestId('queued-followups');- expect(within(strip).getByText('one')).toBeInTheDocument();- expect(within(strip).getByText('three')).toBeInTheDocument();- expect(paddingBottomPx()).toBeGreaterThan(0);- });-- it('restores normal layout after the queued follow-ups are dismissed', async () => {- const { store, thread } = await renderActiveConversationWithMessages();- await act(async () => {- store.dispatch(- enqueueFollowup({- threadId: thread.id,- message: followupMessage('f1', 'dismiss me'),- label: 'dismiss me',- })- );- });- expect(await screen.findByTestId('queued-followups')).toBeInTheDocument();- await act(async () => {- store.dispatch(clearFollowupsForThread({ threadId: thread.id }));- });- await waitFor(() => expect(screen.queryByTestId('queued-followups')).not.toBeInTheDocument());- // Baseline padding stays reserved so the layout is still correct.- expect(paddingBottomPx()).toBeGreaterThan(0);- });-- it('grows the reserved padding to the footer height reported by the ResizeObserver', async () => {- // jsdom performs no layout, so the polyfilled ResizeObserver never fires.- // Drive it manually: capture the observed element + callback, report a- // concrete footer height, and assert the list reserves that height + the- // 16px gap.- const original = globalThis.ResizeObserver;- const handle: { cb: ResizeObserverCallback | null } = { cb: null };- class MockResizeObserver {- constructor(cb: ResizeObserverCallback) {- handle.cb = cb;- }- observe() {}- unobserve() {}- disconnect() {}- }- globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;- try {- await renderActiveConversationWithMessages();- const footer = document.querySelector('[data-walkthrough="home-cta"]') as HTMLElement | null;- expect(footer).not.toBeNull();- (footer as HTMLElement).getBoundingClientRect = () => ({ height: 240 }) as DOMRect;- await act(async () => {- handle.cb?.([], {} as ResizeObserver);- });- // 240px measured footer + 16px gap.- expect(paddingBottomPx()).toBe(256);- } finally {- globalThis.ResizeObserver = original;- }- });-- // #5162: this observer watches the footer that *contains* the composer while- // its measurement drives the message list's bottom padding — a cycle that is- // one oscillating measurement away from "Maximum update depth exceeded". This- // pins the observer's idempotence: a settled layout re-reporting the same- // height converges instead of re-rendering on every notification.- //- // Note on scope: this does NOT discriminate the `prev === next ? prev : next`- // guard in `measure()`. React's own Object.is bail-out already absorbs an- // identical `setState`, so render counts are byte-identical with and without- // that guard (measured: 8 → 9, 9, 9 either way). The guard is defensive and- // self-documenting, not load-bearing; what is worth pinning — and what this- // test pins — is that repeat notifications converge and never walk the- // padding.- it('converges when the observer re-reports an unchanged footer height', async () => {- const original = globalThis.ResizeObserver;- const handle: { cb: ResizeObserverCallback | null } = { cb: null };- class MockResizeObserver {- constructor(cb: ResizeObserverCallback) {- handle.cb = cb;- }- observe() {}- unobserve() {}- disconnect() {}- }- globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;- try {- await renderActiveConversationWithMessages();- const footer = document.querySelector('[data-walkthrough="home-cta"]') as HTMLElement | null;- expect(footer).not.toBeNull();- (footer as HTMLElement).getBoundingClientRect = () => ({ height: 240 }) as DOMRect;-- // First measurement settles the height.- await act(async () => {- handle.cb?.([], {} as ResizeObserver);- });- expect(paddingBottomPx()).toBe(256);-- // `useUsageState` is called exactly once per `Conversations` render, so- // its call count is a render counter for the component under test.- const settled = mockUseUsageState.mock.calls.length;-- // A settled layout re-reporting itself, as a ResizeObserver does on any- // sibling layout change. Each notification must stop costing renders.- await act(async () => {- handle.cb?.([], {} as ResizeObserver);- });- const afterFirstRepeat = mockUseUsageState.mock.calls.length;-- await act(async () => {- handle.cb?.([], {} as ResizeObserver);- });- await act(async () => {- handle.cb?.([], {} as ResizeObserver);- });-- // Converged: further identical notifications cost nothing at all, so a- // stuck-oscillating observer cannot escalate into a nested-update loop.- expect(mockUseUsageState.mock.calls.length).toBe(afterFirstRepeat);- expect(afterFirstRepeat - settled).toBeLessThanOrEqual(1);- expect(paddingBottomPx()).toBe(256);-- // A genuine resize must still get through — convergence is not deafness.- (footer as HTMLElement).getBoundingClientRect = () => ({ height: 300 }) as DOMRect;- await act(async () => {- handle.cb?.([], {} as ResizeObserver);- });- expect(paddingBottomPx()).toBe(316);- } finally {- globalThis.ResizeObserver = original;- }+ expect(textarea).toHaveTextContent('keep me on failure');});});-// The in-chat "Leaving your device" external-transfer disclosure card was-// removed. This guards against it coming back: even with a live external-// transfer flagged on the active thread, no such card renders in the chat view.describe('Conversations — external-transfer disclosure card removed', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/app/src/pages/dev/assistant-ui-demo/BaseDemo.tsx b/app/src/pages/dev/assistant-ui-demo/BaseDemo.tsxindex 243af28171..4a39de1b27 100644--- a/app/src/pages/dev/assistant-ui-demo/BaseDemo.tsx+++ b/app/src/pages/dev/assistant-ui-demo/BaseDemo.tsx@@ -33,7 +33,6 @@ import {import { TooltipIconButton } from '@/components/assistant-ui/tooltip-icon-button';import { Button } from '@/components/assistant-ui/ui/button';import { Skeleton } from '@/components/assistant-ui/ui/skeleton';-import { SubagentCall } from '@/lib/assistantUiMock';import {ActionBarMorePrimitive,ActionBarPrimitive,@@ -82,6 +81,7 @@ import {} from 'lucide-react';import { type FC, type ReactNode, useState } from 'react';+import { SubagentCall } from './assistantUiMock';import { CloneThreadShell } from './CloneThreadShell';import { DEFAULT_MODEL_ID, demoModelOptions } from './demoModels';diff --git a/app/src/pages/dev/assistant-ui-demo/MockRuntimeProvider.tsx b/app/src/pages/dev/assistant-ui-demo/MockRuntimeProvider.tsxindex 8a225939e8..247ed92392 100644--- a/app/src/pages/dev/assistant-ui-demo/MockRuntimeProvider.tsx+++ b/app/src/pages/dev/assistant-ui-demo/MockRuntimeProvider.tsx@@ -8,7 +8,6 @@* attachment/feedback adapters that never leave the browser. Mounting it cannot* touch a thread, a message, or the core.*/-import { buildSeedMessages, mockChatModelAdapter } from '@/lib/assistantUiMock';import {AssistantRuntimeProvider,CompositeAttachmentAdapter,@@ -21,6 +20,8 @@ import {import debugFactory from 'debug';import { createContext, type ReactNode, useContext, useId, useMemo, useRef, useState } from 'react';+import { buildSeedMessages, mockChatModelAdapter } from './assistantUiMock';+const debug = debugFactory('openhuman:assistant-ui-demo');/**diff --git a/app/src/lib/assistantUiMock/SubagentCall.tsx b/app/src/pages/dev/assistant-ui-demo/assistantUiMock/SubagentCall.tsxsimilarity index 100%rename from app/src/lib/assistantUiMock/SubagentCall.tsxrename to app/src/pages/dev/assistant-ui-demo/assistantUiMock/SubagentCall.tsxdiff --git a/app/src/pages/dev/assistant-ui-demo/assistantUiMock/index.ts b/app/src/pages/dev/assistant-ui-demo/assistantUiMock/index.tsnew file mode 100644index 0000000000..dd0e4e7293--- /dev/null+++ b/app/src/pages/dev/assistant-ui-demo/assistantUiMock/index.ts@@ -0,0 +1,13 @@+/**+ * A scripted, offline assistant-ui turn.+ *+ * The dev-only upstream demo renders assistant-ui against a stand-in model so+ * it can exercise every transcript part without touching OpenHuman data. The+ * product chat uses the external Redux runtime and never imports this folder.+ *+ * Nothing in here reaches the core, the backend, or any provider.+ */+export { mockChatModelAdapter } from './mockChatModel';+export { buildSeedMessages, MOCK_SCRIPT, SEED_PROMPT } from './mockScript';+export type { MockStep, MockSubagentResult, MockSubagentStep } from './mockScript';+export { MockToolFallback, MockToolGroup, SubagentCall } from './SubagentCall';diff --git a/app/src/lib/assistantUiMock/mockChatModel.ts b/app/src/pages/dev/assistant-ui-demo/assistantUiMock/mockChatModel.tssimilarity index 100%rename from app/src/lib/assistantUiMock/mockChatModel.tsrename to app/src/pages/dev/assistant-ui-demo/assistantUiMock/mockChatModel.tsdiff --git a/app/src/lib/assistantUiMock/mockScript.ts b/app/src/pages/dev/assistant-ui-demo/assistantUiMock/mockScript.tssimilarity index 100%rename from app/src/lib/assistantUiMock/mockScript.tsrename to app/src/pages/dev/assistant-ui-demo/assistantUiMock/mockScript.tsdiff --git a/app/src/providers/__tests__/assistantUiMessages.test.ts b/app/src/providers/__tests__/assistantUiMessages.test.tsindex 9e0eec1e60..5121494233 100644--- a/app/src/providers/__tests__/assistantUiMessages.test.ts+++ b/app/src/providers/__tests__/assistantUiMessages.test.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi } from 'vitest';+import type { ToolTimelineEntry } from '../../store/chatRuntimeSlice';import type { ThreadMessage } from '../../types/thread';import {buildRuntimeMessages,@@ -20,6 +21,10 @@ function msg(over: Partial<ThreadMessage> = {}): ThreadMessage {};}+function tool(over: Partial<ToolTimelineEntry> = {}): ToolTimelineEntry {+ return { id: 'call-1', name: 'web_search', round: 1, seq: 0, status: 'running', ...over };+}+describe('toThreadMessageLike', () => {it('maps sender to role', () => {expect(toThreadMessageLike(msg({ id: 'u' })).role).toBe('user');@@ -74,6 +79,42 @@ describe('streamingTailMessage', () => {content: [{ type: 'text', text: 'partial' }],});});++ it('projects streamed thinking as a reasoning part before visible text', () => {+ const tail = streamingTailMessage({ requestId: 'r', content: 'answer', thinking: 'reasoning' });+ expect(tail?.content).toEqual([+ { type: 'reasoning', text: 'reasoning' },+ { type: 'text', text: 'answer' },+ ]);+ });++ it('keeps a running delegation on args and adds result only when complete', () => {+ const subagent = {+ taskId: 'sub-1',+ agentId: 'researcher',+ toolCalls: [],+ transcript: [{ kind: 'thinking' as const, text: 'checking sources' }],+ };+ const running = streamingTailMessage(null, [+ tool({ id: 'sub-1', name: 'subagent:researcher', subagent }),+ ]);+ const runningPart = running?.content[0];+ expect(runningPart).toMatchObject({+ type: 'tool-call',+ toolName: 'task',+ args: { progress: subagent },+ });+ expect(runningPart).not.toHaveProperty('result');++ const complete = streamingTailMessage(null, [+ tool({ id: 'sub-1', name: 'subagent:researcher', status: 'success', subagent }),+ ]);+ expect(complete?.content[0]).toMatchObject({+ type: 'tool-call',+ toolName: 'task',+ result: subagent,+ });+ });});describe('buildRuntimeMessages', () => {@@ -92,6 +133,36 @@ describe('buildRuntimeMessages', () => {expect(ids).toEqual(['a', STREAMING_TAIL_ID]);});+ it('replays a settled turn reasoning and tool calls from its request id', () => {+ const answer = msg({+ id: 'answer',+ sender: 'agent',+ content: 'finished',+ extraMetadata: { requestId: 'req-1' },+ });+ const timeline = [tool({ id: 'call-1', status: 'success', result: 'found it' })];+ const transcript = [+ { kind: 'thinking' as const, round: 1, seq: 0, text: 'need to search' },+ { kind: 'toolCall' as const, round: 1, seq: 1, callId: 'call-1' },+ ];++ expect(+ buildRuntimeMessages([answer], null, {+ turnTimelines: { 'req-1': timeline },+ turnTranscripts: { 'req-1': transcript },+ })[0]?.content+ ).toEqual([+ { type: 'reasoning', text: 'need to search' },+ expect.objectContaining({+ type: 'tool-call',+ toolCallId: 'call-1',+ toolName: 'web_search',+ result: 'found it',+ }),+ { type: 'text', text: 'finished' },+ ]);+ });+it('re-converts only the tail as tokens land, never the settled transcript', () => {// The projection-level statement of the property `ChatThreadView.renderPerf`// pins for the render tree: streaming must not sweep the transcript.diff --git a/app/src/providers/__tests__/chatSurfaceHandlers.test.ts b/app/src/providers/__tests__/chatSurfaceHandlers.test.tsindex 1d2dfc00b4..f21c69e4f2 100644--- a/app/src/providers/__tests__/chatSurfaceHandlers.test.ts+++ b/app/src/providers/__tests__/chatSurfaceHandlers.test.ts@@ -16,6 +16,12 @@ describe('chatSurfaceHandlers', () => {expect(getChatSurface('t1')).toBe(handlers);});+ it('keeps an explicitly registered unscoped surface for a new chat', () => {+ const handlers = { send: vi.fn(async () => {}) };+ registerChatSurface(null, handlers);+ expect(getChatSurface(null)).toBe(handlers);+ });+it('keeps threads isolated from one another', () => {const a = { send: vi.fn(async () => {}) };const b = { send: vi.fn(async () => {}) };diff --git a/app/src/providers/assistantUiMessages.ts b/app/src/providers/assistantUiMessages.tsindex b5dd8c644f..6518602700 100644--- a/app/src/providers/assistantUiMessages.ts+++ b/app/src/providers/assistantUiMessages.ts@@ -1,7 +1,11 @@-import type { ThreadMessageLike } from '@assistant-ui/react';+import type { ThreadAssistantMessagePart, ThreadMessageLike } from '@assistant-ui/react';import { unwrapToolCallEnvelope } from '../lib/chat/toolCallEnvelope';-import type { StreamingAssistantState } from '../store/chatRuntimeSlice';+import type {+ ProcessingTranscriptItem,+ StreamingAssistantState,+ ToolTimelineEntry,+} from '../store/chatRuntimeSlice';import type { ThreadMessage } from '../types/thread';/**@@ -20,8 +24,21 @@ import type { ThreadMessage } from '../types/thread';* pins it for this projection.*/-/** Cache keyed on the source object, so a settled message converts exactly once. */-const conversionCache = new WeakMap<ThreadMessage, ThreadMessageLike>();+type ConversionCacheEntry = {+ timeline: readonly ToolTimelineEntry[];+ transcript: readonly ProcessingTranscriptItem[];+ converted: ThreadMessageLike;+};++/**+ * Cache keyed on the source message and its persisted process arrays. Socket+ * tokens only replace the live tail, so a settled message converts exactly+ * once while its transcript/timeline identities remain stable.+ */+const conversionCache = new WeakMap<ThreadMessage, ConversionCacheEntry>();++const EMPTY_TIMELINE: readonly ToolTimelineEntry[] = [];+const EMPTY_TRANSCRIPT: readonly ProcessingTranscriptItem[] = [];/** Synthetic id for the live streaming tail. Stable so React reconciles it. */export const STREAMING_TAIL_ID = '__openhuman_streaming_tail__';@@ -36,9 +53,91 @@ export const STREAMING_TAIL_ID = '__openhuman_streaming_tail__';* `toolTimelineByThread` projection that `ToolTimelineBlock` renders, and* duplicating it here would paint every tool twice.*/-export function toThreadMessageLike(msg: ThreadMessage): ThreadMessageLike {+function jsonObject(value: unknown): Record<string, never> {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {};+ try {+ return JSON.parse(JSON.stringify(value)) as Record<string, never>;+ } catch {+ return {};+ }+}++function toolArgs(entry: ToolTimelineEntry): Record<string, never> {+ if (!entry.argsBuffer) return {};+ try {+ return jsonObject(JSON.parse(entry.argsBuffer));+ } catch {+ return { raw: entry.argsBuffer } as never;+ }+}++function toolPart(entry: ToolTimelineEntry): ThreadAssistantMessagePart {+ const running = entry.status === 'running' || entry.status === 'awaiting_user';+ const isSubagent = entry.name.startsWith('subagent:') || entry.subagent !== undefined;+ const args = isSubagent+ ? jsonObject({+ subagent_type: entry.subagent?.agentId ?? entry.name.replace(/^subagent:/, ''),+ description: entry.detail,+ ...(running ? { progress: entry.subagent } : {}),+ })+ : toolArgs(entry);++ return {+ type: 'tool-call',+ toolCallId: entry.id,+ toolName: isSubagent ? 'task' : entry.name,+ args,+ argsText: JSON.stringify(args, null, 2),+ ...(!running+ ? {+ result: isSubagent+ ? (entry.subagent ?? { status: entry.status })+ : (entry.result ?? { status: entry.status, failure: entry.failure }),+ }+ : {}),+ };+}++function assistantParts(+ text: string,+ timeline: readonly ToolTimelineEntry[],+ transcript: readonly ProcessingTranscriptItem[]+): ThreadAssistantMessagePart[] {+ const parts: ThreadAssistantMessagePart[] = [];+ const timelineById = new Map(timeline.map(entry => [entry.id, entry]));+ const emittedToolIds = new Set<string>();++ for (const item of transcript) {+ if (item.kind === 'thinking') {+ if (item.text.trim().length > 0) parts.push({ type: 'reasoning', text: item.text });+ continue;+ }+ if (item.kind === 'toolCall') {+ const entry = timelineById.get(item.callId);+ if (entry) {+ parts.push(toolPart(entry));+ emittedToolIds.add(entry.id);+ }+ }+ // Narration is process commentary, not the final assistant answer. The+ // legacy pane keeps it in the processing view; projecting it as ordinary+ // text here would duplicate prose around the persisted final response.+ }++ for (const entry of [...timeline].sort((a, b) => a.seq - b.seq)) {+ if (!emittedToolIds.has(entry.id)) parts.push(toolPart(entry));+ }+ if (text.length > 0) parts.push({ type: 'text', text });+ return parts;+}++export function toThreadMessageLike(+ msg: ThreadMessage,+ timeline: readonly ToolTimelineEntry[] = EMPTY_TIMELINE,+ transcript: readonly ProcessingTranscriptItem[] = EMPTY_TRANSCRIPT+): ThreadMessageLike {const cached = conversionCache.get(msg);- if (cached !== undefined) return cached;+ if (cached?.timeline === timeline && cached.transcript === transcript) return cached.converted;const text =msg.sender === 'agent' ? unwrapToolCallEnvelope(msg.content ?? '').text : (msg.content ?? '');@@ -46,12 +145,20 @@ export function toThreadMessageLike(msg: ThreadMessage): ThreadMessageLike {const converted: ThreadMessageLike = {id: msg.id,role: msg.sender === 'agent' ? 'assistant' : 'user',- content: text.length > 0 ? [{ type: 'text', text }] : [],+ content:+ msg.sender === 'agent'+ ? assistantParts(text, timeline, transcript)+ : text.length > 0+ ? [{ type: 'text', text }]+ : [],createdAt: new Date(msg.createdAt),+ ...(msg.sender === 'agent' && msg.extraMetadata?.stopped === true+ ? { status: { type: 'incomplete' as const, reason: 'cancelled' as const } }+ : {}),metadata: { custom: { extraMetadata: msg.extraMetadata ?? {}, sourceType: msg.type } },};- conversionCache.set(msg, converted);+ conversionCache.set(msg, { timeline, transcript, converted });return converted;}@@ -65,20 +172,34 @@ export function toThreadMessageLike(msg: ThreadMessage): ThreadMessageLike {* token, and only that one object is ever re-converted.*/export function streamingTailMessage(- streaming: StreamingAssistantState | null+ streaming: StreamingAssistantState | null,+ timeline: readonly ToolTimelineEntry[] = EMPTY_TIMELINE,+ transcript: readonly ProcessingTranscriptItem[] = EMPTY_TRANSCRIPT): ThreadMessageLike | null {- if (!streaming) return null;- const text = streaming.content ?? '';- if (text.length === 0) return null;+ if (!streaming && timeline.length === 0 && transcript.length === 0) return null;+ const text = streaming?.content ?? '';+ const parts = assistantParts(text, timeline, transcript);+ if (streaming?.thinking.trim()) {+ const hasTranscriptThinking = transcript.some(item => item.kind === 'thinking');+ if (!hasTranscriptThinking) parts.unshift({ type: 'reasoning', text: streaming.thinking });+ }+ if (parts.length === 0) return null;return {id: STREAMING_TAIL_ID,role: 'assistant',- content: [{ type: 'text', text }],+ content: parts,status: { type: 'running' },- metadata: { custom: { requestId: streaming.requestId, streaming: true } },+ metadata: { custom: { requestId: streaming?.requestId, streaming: true } },};}+export type AssistantUiProjection = {+ liveTimeline?: readonly ToolTimelineEntry[];+ liveTranscript?: readonly ProcessingTranscriptItem[];+ turnTimelines?: Readonly<Record<string, readonly ToolTimelineEntry[]>>;+ turnTranscripts?: Readonly<Record<string, readonly ProcessingTranscriptItem[]>>;+};+/*** The full thread as assistant-ui sees it: settled transcript, then the live* tail when one is in flight.@@ -89,14 +210,29 @@ export function streamingTailMessage(*/export function buildRuntimeMessages(messages: readonly ThreadMessage[],- streaming: StreamingAssistantState | null+ streaming: StreamingAssistantState | null,+ projection: AssistantUiProjection = {}): ThreadMessageLike[] {const out: ThreadMessageLike[] = [];for (const msg of messages) {if (msg.extraMetadata?.hidden) continue;- out.push(toThreadMessageLike(msg));+ const requestId =+ msg.sender === 'agent' && typeof msg.extraMetadata?.requestId === 'string'+ ? msg.extraMetadata.requestId+ : undefined;+ out.push(+ toThreadMessageLike(+ msg,+ requestId ? (projection.turnTimelines?.[requestId] ?? EMPTY_TIMELINE) : EMPTY_TIMELINE,+ requestId ? (projection.turnTranscripts?.[requestId] ?? EMPTY_TRANSCRIPT) : EMPTY_TRANSCRIPT+ )+ );}- const tail = streamingTailMessage(streaming);+ const tail = streamingTailMessage(+ streaming,+ projection.liveTimeline ?? EMPTY_TIMELINE,+ projection.liveTranscript ?? EMPTY_TRANSCRIPT+ );if (tail) out.push(tail);return out;}diff --git a/app/src/providers/chatSurfaceHandlers.ts b/app/src/providers/chatSurfaceHandlers.tsindex 1339db599e..4e1102d43f 100644--- a/app/src/providers/chatSurfaceHandlers.ts+++ b/app/src/providers/chatSurfaceHandlers.ts@@ -27,21 +27,25 @@ export interface ChatSurfaceHandlers {}const registry = new Map<string, ChatSurfaceHandlers>();+const UNSCOPED_SURFACE = '__openhuman_unscoped_chat_surface__';/** Register the handlers for `threadId`; returns the unregister function. */-export function registerChatSurface(threadId: string, handlers: ChatSurfaceHandlers): () => void {- registry.set(threadId, handlers);+export function registerChatSurface(+ threadId: string | null,+ handlers: ChatSurfaceHandlers+): () => void {+ const key = threadId ?? UNSCOPED_SURFACE;+ registry.set(key, handlers);return () => {// Only clear if we still own the slot — a remount that re-registered first// must not be torn down by the outgoing instance's cleanup.- if (registry.get(threadId) === handlers) registry.delete(threadId);+ if (registry.get(key) === handlers) registry.delete(key);};}/** The handlers registered for `threadId`, or `null` when no surface owns it. */export function getChatSurface(threadId: string | null): ChatSurfaceHandlers | null {- if (!threadId) return null;- return registry.get(threadId) ?? null;+ return registry.get(threadId ?? UNSCOPED_SURFACE) ?? null;}/** Test seam — drops every registration. */diff --git a/app/src/providers/useOpenHumanExternalStore.ts b/app/src/providers/useOpenHumanExternalStore.tsindex dc87143e8c..60390f2fe1 100644--- a/app/src/providers/useOpenHumanExternalStore.ts+++ b/app/src/providers/useOpenHumanExternalStore.ts@@ -7,6 +7,9 @@ import { buildRuntimeMessages } from './assistantUiMessages';import { getChatSurface } from './chatSurfaceHandlers';const EMPTY_MESSAGES: ThreadMessage[] = [];+const EMPTY_TIMELINE: never[] = [];+const EMPTY_TRANSCRIPT: never[] = [];+const EMPTY_TURN_MAP = {};/** Flatten an assistant-ui append payload down to the plain text our core takes. */function appendMessageText(message: AppendMessage): string {@@ -29,18 +32,45 @@ export function useOpenHumanExternalStore(threadId: string | null) {threadId ? (state.thread.messagesByThreadId[threadId] ?? EMPTY_MESSAGES) : EMPTY_MESSAGES);const streaming = useAppSelector(state =>- threadId ? (state.chatRuntime.streamingAssistantByThread[threadId] ?? null) : null+ threadId ? (state.chatRuntime.streamingAssistantByThread?.[threadId] ?? null) : null);const lifecycle = useAppSelector(state =>- threadId ? (state.chatRuntime.inferenceTurnLifecycleByThread[threadId] ?? null) : null+ threadId ? (state.chatRuntime.inferenceTurnLifecycleByThread?.[threadId] ?? null) : null+ );+ const isLoading = useAppSelector(state => Boolean(threadId && state.thread.isLoadingMessages));+ const liveTimeline = useAppSelector(state =>+ threadId+ ? (state.chatRuntime.toolTimelineByThread?.[threadId] ?? EMPTY_TIMELINE)+ : EMPTY_TIMELINE+ );+ const liveTranscript = useAppSelector(state =>+ threadId+ ? (state.chatRuntime.processingByThread?.[threadId] ?? EMPTY_TRANSCRIPT)+ : EMPTY_TRANSCRIPT+ );+ const turnTimelines = useAppSelector(state =>+ threadId+ ? (state.chatRuntime.turnTimelinesByThread?.[threadId] ?? EMPTY_TURN_MAP)+ : EMPTY_TURN_MAP+ );+ const turnTranscripts = useAppSelector(state =>+ threadId+ ? (state.chatRuntime.turnTranscriptsByThread?.[threadId] ?? EMPTY_TURN_MAP)+ : EMPTY_TURN_MAP);// Recomputed only when the settled transcript or the live tail changes.// Settled messages are converted through an identity-keyed cache, so a token// landing on the tail re-converts exactly one message, never the transcript.const runtimeMessages = useMemo(- () => buildRuntimeMessages(messages, streaming),- [messages, streaming]+ () =>+ buildRuntimeMessages(messages, streaming, {+ liveTimeline,+ liveTranscript,+ turnTimelines,+ turnTranscripts,+ }),+ [messages, streaming, liveTimeline, liveTranscript, turnTimelines, turnTranscripts]);// `started` and `streaming` are both in-flight; the row is deleted on@@ -66,20 +96,16 @@ export function useOpenHumanExternalStore(threadId: string | null) {await getChatSurface(threadId)?.cancel?.();}, [threadId]);- const onReload = useCallback(async () => {- await getChatSurface(threadId)?.reload?.();- }, [threadId]);-return useMemo(() => ({messages: runtimeMessages,isRunning,+ isLoading,// Already `ThreadMessageLike`; the runtime's converter is the identity.convertMessage: (m: (typeof runtimeMessages)[number]) => m,onNew,onCancel,- onReload,}),- [runtimeMessages, isRunning, onNew, onCancel, onReload]+ [runtimeMessages, isRunning, isLoading, onNew, onCancel]);}diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.tsindex 96d849dd26..369fd26ce3 100644--- a/app/src/store/chatRuntimeSlice.ts+++ b/app/src/store/chatRuntimeSlice.ts@@ -364,7 +364,7 @@ export interface SubAgentUsage {}/** Running per-session totals accumulated from `chat:done` events (#703). */-interface SessionTokenUsage {+export interface SessionTokenUsage {inputTokens: number;outputTokens: number;turns: number;diff --git a/app/src/test/setup.ts b/app/src/test/setup.tsindex d5a0855d90..9f35c1b4bc 100644--- a/app/src/test/setup.ts+++ b/app/src/test/setup.ts@@ -128,6 +128,21 @@ if (typeof Element !== 'undefined' && !Element.prototype.scrollIntoView) {Element.prototype.scrollIntoView = function () {};}+// assistant-ui's thread viewport scrolls after a send. jsdom exposes scroll+// metrics but not the imperative `scrollTo` method used by that primitive.+if (typeof HTMLElement !== 'undefined' && !HTMLElement.prototype.scrollTo) {+ HTMLElement.prototype.scrollTo = function () {};+}++// Lexical measures the DOM selection after controlled composer updates. jsdom+// implements Range but omits its layout methods.+if (typeof Range !== 'undefined' && !Range.prototype.getBoundingClientRect) {+ Range.prototype.getBoundingClientRect = () => new DOMRect();+}+if (typeof Range !== 'undefined' && !Range.prototype.getClientRects) {+ Range.prototype.getClientRects = () => [] as unknown as DOMRectList;+}+// Polyfill the Pointer Capture API for Radix primitives in jsdom.// Radix's Select, Slider, Toggle and DropdownMenu call these unconditionally// on pointerdown; jsdom implements none of them, so without this the verydiff --git a/app/test/vitest.config.ts b/app/test/vitest.config.tsindex 52ed1b354c..10dfef40a3 100644--- a/app/test/vitest.config.ts+++ b/app/test/vitest.config.ts@@ -20,6 +20,7 @@ export default defineConfig({],resolve: {alias: {+ "@": path.resolve(projectRoot, "src"),buffer: "buffer",process: "process/browser",util: "util",diff --git a/docs/plans/2026-08-22-assistant-ui-real-data.md b/docs/plans/2026-08-22-assistant-ui-real-data.mdindex e4f603ecb0..953ca6440b 100644--- a/docs/plans/2026-08-22-assistant-ui-real-data.md+++ b/docs/plans/2026-08-22-assistant-ui-real-data.md@@ -1,15 +1,35 @@# Wiring the assistant-ui chat surface to real OpenHuman data-**Status:** plan. Nothing below is implemented.+**Status:** implementation in progress on `assistant-ui-real-data`.**Prerequisite:** the mock surface landed on `fix/ui-shdcdn` (see "What exists today").+Current checkpoint:++- The product chat uses `AssistantUiRuntimeProvider`; the scripted runtime is now+ isolated to the dev-only assistant-ui demo.+- Real reasoning, tool timelines and subagent activity are projected into+ assistant-ui parts, including the running-args/final-result invariant.+- Context usage reads the selected thread's Redux token bucket, and cached input+ remains separate from fresh input. A provider catalog selection now carries+ its real context window into both the meter and the model override used by+ `chatSend`; unknown windows render as unknown.+- The composer reuses the persisted thread-goal controller, and `/` commands are+ projected from the shared command registry. `/clear` executes `chat.new`.+- Focused tests, typecheck, lint and both i18n gates pass. The full `pnpm test`+ run reaches the previously-unexercised assistant-ui pane, but the legacy+ `Conversations.render.test.tsx` suite still asserts the hidden legacy pane and+ must be migrated before this plan is complete.+- `renderAssistantUiOnly` is removed. The voice-only `mic-cloud` embed still+ uses the legacy pane while the remaining non-plan affordances are ported;+ follow-up: [#5685](https://github.com/tinyhumansai/openhuman/issues/5685).+## What this is`Conversations` renders the assistant-ui `Thread` instead of the legacy pane(`renderAssistantUiOnly = true` in[`app/src/features/conversations/Conversations.tsx`](../../app/src/features/conversations/Conversations.tsx)),and everything under it is currently fed by a scripted offline adapter. That was-deliberate: it let the *shape* of the surface be built and reviewed — streamed+deliberate: it let the _shape_ of the surface be built and reviewed — streamedreasoning, tool calls, dispatched subagents, slash commands, a context meter, athread goal — before any of it was load-bearing.@@ -19,21 +39,21 @@ and the RPC method rather than describing them.**The through-line: none of these are new features.** OpenHuman already has agoal domain, a cost domain, a token-usage RPC, a command palette and a-Redux-backed transcript projection. Four of the five tasks are *deletions* —+Redux-backed transcript projection. Four of the five tasks are _deletions_ —removing a mock and pointing the component at machinery that already exists. Donot build a second implementation of any of them.-## What exists today+## Starting point-| Piece | File | Backed by |-| --- | --- | --- |-| Scripted turn | `app/src/lib/assistantUiMock/mockScript.ts` | fiction |-| Streaming adapter | `app/src/lib/assistantUiMock/mockChatModel.ts` | fiction |-| Subagent renderer | `app/src/lib/assistantUiMock/SubagentCall.tsx` | reads the mock's payload |-| Chat surface | `app/src/features/conversations/components/AssistantUiChat.tsx` | `useLocalRuntime` + the mock |-| Context meter | `app/src/features/conversations/components/composer/ContextWindowPill.tsx` | `MOCK_USAGE` constant |-| Goal control | `app/src/features/conversations/components/composer/GoalSelector.tsx` | React `useState` |-| Slash commands | `slashCommands` prop on `Thread` | two local closures |+| Piece | File | Backed by |+| ----------------- | -------------------------------------------------------------------------- | ---------------------------- |+| Scripted turn | `app/src/lib/assistantUiMock/mockScript.ts` | fiction |+| Streaming adapter | `app/src/lib/assistantUiMock/mockChatModel.ts` | fiction |+| Subagent renderer | `app/src/lib/assistantUiMock/SubagentCall.tsx` | reads the mock's payload |+| Chat surface | `app/src/features/conversations/components/AssistantUiChat.tsx` | `useLocalRuntime` + the mock |+| Context meter | `app/src/features/conversations/components/composer/ContextWindowPill.tsx` | `MOCK_USAGE` constant |+| Goal control | `app/src/features/conversations/components/composer/GoalSelector.tsx` | React `useState` |+| Slash commands | `slashCommands` prop on `Thread` | two local closures |Two seams were added to the vendored `Thread`([`app/src/components/assistant-ui/thread.tsx`](../../app/src/components/assistant-ui/thread.tsx))@@ -75,8 +95,11 @@ and is tested:Getting this wrong is a real bug with a real precedent — see the provider'sheader comment about the Workflow Copilot painting the home chat's messages.3. Sending: the composer must reach the same path the legacy composer used.- `useOpenHumanExternalStore`'s `onNew`/`onEdit` are the seam; verify they are- wired before removing the legacy pane, not after.+ `useOpenHumanExternalStore.onNew` is the seam; verify it is wired before+ removing the legacy pane, not after. The adapter deliberately exposes no+ `onEdit`: `openhuman.threads_message_update` updates metadata only, not+ message content, so advertising assistant-ui's edit capability would create+ a button the core cannot honour.### Watch for@@ -113,7 +136,7 @@ Relevant wire types already defined there: `ChatSegmentEvent`,3. Rework `SubagentCall` to read `SubagentProgressDetail` instead of the mock'spayload. **Preserve the running/complete split exactly as it is**, and readthe note in `mockChatModel.ts` before changing it: assistant-ui derives a tool- call's status from *whether a result is present*, so live progress must ride+ call's status from _whether a result is present_, so live progress must rideon the streaming `args` and `result` must be set once, at the end. Writingprogress into `result` marks the call complete the instant it starts, the toolgroup collapses, and a running delegation renders as finished. This was found@@ -140,10 +163,10 @@ does not change; only its source does.Two candidate sources, both real:-| Source | File | Shape |-| --- | --- | --- |-| Live, per-session | `chatRuntimeSlice` — `emptySessionTokenUsage`, `SubAgentUsage` | already consumed by `app/src/components/chat/ComposerTokenStats.tsx` |-| Persisted, per-thread | `openhuman.threads_token_usage` via `app/src/services/api/threadUsageApi.ts` (`fetchThreadTokenUsage`) | `ThreadTokenUsage` |+| Source | File | Shape |+| --------------------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- |+| Live, per-session | `chatRuntimeSlice` — `emptySessionTokenUsage`, `SubAgentUsage` | already consumed by `app/src/components/chat/ComposerTokenStats.tsx` |+| Persisted, per-thread | `openhuman.threads_token_usage` via `app/src/services/api/threadUsageApi.ts` (`fetchThreadTokenUsage`) | `ThreadTokenUsage` |### Steps@@ -160,7 +183,7 @@ Two candidate sources, both real:follow the model picker; `context_window` on `TurnUsageWire` is `0` in somecases (see the comment there) — decide what the meter shows then, rather thandividing by zero.-4. Cost for a *thread* may want `openhuman.cost_get_summary` from+4. Cost for a _thread_ may want `openhuman.cost_get_summary` from`src/openhuman/platform/cost/` instead of a per-turn sum. Check `README.md` inthat directory before choosing.@@ -217,7 +240,7 @@ OpenHuman already has a command surface:2. Reimplement `/clear` against the real transcript. It must go through whatever`threadSlice` / core RPC owns clearing a thread — **not** a runtime reset,which after Task 1 would desynchronise the projection from Redux.-3. Decide what `/clear` means before implementing: clear the *view*, archive the+3. Decide what `/clear` means before implementing: clear the _view_, archive thethread, or start a new one. The mock's behaviour (empty the transcript inplace) is the least likely to be right for real data, because the messages arepersisted.@@ -283,4 +306,5 @@ a PR. Diff coverage on changed lines must be ≥ 80%.- `AssistantUiChat` mounts no `useLocalRuntime` and imports nothing from a mock.- The context meter, the goal control and every slash command read live data.- `renderAssistantUiOnly` can be removed along with the legacy pane, or a- follow-up issue explains what still blocks it.+ follow-up issue explains what still blocks it. The constant is gone; [#5685](https://github.com/tinyhumansai/openhuman/issues/5685)+ tracks the remaining voice-only fallback and legacy affordances.