The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stop transcript jumps when a turn settles
Brooklyn Nicholsonead9d8e3d4f0
diff --git a/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx b/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsxindex 5660ace8664..b315f4d6165 100644--- a/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx+++ b/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx@@ -1,5 +1,5 @@import type { ToolCallMessagePartProps } from '@assistant-ui/react'-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import type { ReactNode } from 'react'import { afterEach, describe, expect, it, vi } from 'vitest'@@ -11,10 +11,12 @@ import { $activeSessionId } from '@/store/session'import { ClarifyTool, readClarifyBatchResult, readClarifyResult } from './clarify-tool'-// The live pending card only renders while its message is running. Force that so-// keyboard-navigation tests can exercise ClarifyToolPending directly.+// The live pending card used to require message-running. Tests that exercise+// the pending form force that on; the settle-shift case flips it off.+let messageRunning = true+vi.mock('@assistant-ui/react', () => ({- useAuiState: () => true+ useAuiState: () => messageRunning}))afterEach(() => {@@ -22,6 +24,7 @@ afterEach(() => {clearClarifyRequest()$activeSessionId.set(null)$gateway.set(null)+ messageRunning = truevi.clearAllMocks()})@@ -88,6 +91,50 @@ function renderLiveClarify({ multiSelect = false }: { multiSelect?: boolean } =return request}+describe('ClarifyTool live card stays mounted across settle', () => {+ it('keeps the question card while the gateway request is open and the turn reports not-running', () => {+ messageRunning = false+ renderLiveClarify()++ expect(screen.getByText('Which deployment target?')).toBeTruthy()+ expect(document.querySelector('[data-clarify-choices]')).toBeTruthy()+ expect(document.querySelector('[data-clarify-settled]')).toBeNull()+ })++ it('demotes to a tool row when the turn stopped and no request is left to answer', () => {+ messageRunning = false+ $activeSessionId.set('session-1')+ $gateway.set({ request: vi.fn() } as never)+ renderClarify(<ClarifyTool {...liveClarifyProps()} />)++ expect(document.querySelector('[data-clarify-choices]')).toBeNull()+ expect(screen.queryByRole('button', { name: /Continue/ })).toBeNull()+ })++ it('holds the card through the gap between answering and the settled result', () => {+ renderLiveClarify()++ expect(document.querySelector('[data-clarify-choices]')).toBeTruthy()++ // Answering clears the request; the settled card only arrives with+ // tool.complete, and the turn can already read as not-running by then.+ messageRunning = false+ act(() => clearClarifyRequest('request-1', 'session-1'))++ expect(document.querySelector('[data-clarify-choices]')).toBeTruthy()+ })++ it('paints the question from tool args instead of a spinner while request_id is still racing', () => {+ $activeSessionId.set('session-1')+ $gateway.set({ request: vi.fn() } as never)+ renderClarify(<ClarifyTool {...liveClarifyProps()} />)++ expect(screen.getByText('Which deployment target?')).toBeTruthy()+ expect(screen.queryByRole('status', { name: /loading question/i })).toBeNull()+ expect(screen.getByRole('button', { name: /Continue/ }).hasAttribute('disabled')).toBe(true)+ })+})+describe('ClarifyTool choice selection', () => {it('selects independently, deselects and submits multi-select choices as a JSON array', async () => {const request = renderLiveClarify({ multiSelect: true })diff --git a/apps/desktop/src/components/assistant-ui/clarify-tool.tsx b/apps/desktop/src/components/assistant-ui/clarify-tool.tsxindex 67624f0979b..2cd8f6c402e 100644--- a/apps/desktop/src/components/assistant-ui/clarify-tool.tsx+++ b/apps/desktop/src/components/assistant-ui/clarify-tool.tsx@@ -286,17 +286,6 @@ export const ClarifyTool = (props: ToolCallMessagePartProps) => {return <ClarifyToolSettled {...props} />}- return <ClarifyToolLive {...props} />-}--function ClarifyToolLive(props: ToolCallMessagePartProps) {- const messageRunning = useAuiState(selectMessageRunning)-- // Stopped mid-prompt with no result — don't leave a dead interactive panel.- if (!messageRunning) {- return <ToolFallback {...props} />- }-return <ClarifyToolPending {...props} />}@@ -384,6 +373,25 @@ function ClarifyToolPending(props: ToolCallMessagePartProps) {const $request = useMemo(() => sessionClarifyRequest(sessionId), [sessionId])const request = useStore($request)const fromArgs = useMemo(() => readClarifyArgs(props.args), [props.args])+ const messageRunning = useAuiState(selectMessageRunning)+ // Answering clears the request a beat before `tool.complete` swaps in the+ // settled card. Latch that this card was live so that gap doesn't demote it.+ const [wasLive, setWasLive] = useState(false)++ if (request && !wasLive) {+ setWasLive(true)+ }++ // Stopped mid-prompt with no result — don't leave a dead interactive panel.+ // The turn's running flag alone can't decide that: `session.info` reports+ // running=false while clarify is blocking on the user, and demoting there+ // remounts the question as a tool row and jumps the transcript. The live+ // request is the real signal — every path that ends a turn (complete, stop,+ // error) clears it for the session, so a request that never arrived on a+ // settled turn means there is nothing left to answer.+ if (!messageRunning && !request && !wasLive) {+ return <ToolFallback {...props} />+ }// Batch: the gateway request carries qid-keyed questions. Args alone can't// drive the form (no qids to respond with), so batch waits for the request.@@ -435,11 +443,12 @@ function ClarifyToolSinglePending({ fromArgs, request }: { fromArgs: ClarifyArgsconst textareaRef = useRef<HTMLTextAreaElement | null>(null)// Race: tool.start fires a tick before clarify.request, so request_id- // arrives slightly after the tool block mounts. Hold the whole panel on a- // spinner until the gateway request is wired — showing disabled choices or- // a "loading question" stub is worse than a brief wait.+ // arrives slightly after the tool block mounts. If the question text is+ // already in the tool args, paint the card immediately (disabled until+ // the request is wired) — a spinner→question swap is a layout jump for+ // no reason. Only spin when we have nothing to show yet.const ready = Boolean(matchingRequest?.requestId)- const loading = !ready && !submitting+ const loading = !ready && !submitting && !questionconst respond = useCallback(async (answer: string) => {@@ -708,7 +717,7 @@ function ClarifyToolSinglePending({ fromArgs, request }: { fromArgs: ClarifyArgsactive={activeIndex === index}char={letterFor(index)}choice={choice}- disabled={submitting}+ disabled={submitting || !ready}key={`${index}-${choice}`}keyShortcuts={`${letterFor(index)} ${index + 1}`}onClick={() => selectChoice(choice, index)}@@ -732,7 +741,7 @@ function ClarifyToolSinglePending({ fromArgs, request }: { fromArgs: ClarifyArgsaria-current={activeIndex === choices.length || undefined}aria-keyshortcuts={`${letterFor(choices.length)} ${choices.length + 1}`}className={CLARIFY_TEXTAREA_CLASS}- disabled={submitting}+ disabled={submitting || !ready}onBlur={() => setOtherFocused(false)}onChange={event => onDraftChange(event.target.value)}onFocus={() => {@@ -752,7 +761,7 @@ function ClarifyToolSinglePending({ fromArgs, request }: { fromArgs: ClarifyArgs) : (<TextareaclassName={CLARIFY_TEXTAREA_CLASS}- disabled={submitting}+ disabled={submitting || !ready}onChange={event => onDraftChange(event.target.value)}onKeyDown={handleTextareaKey}placeholder={copy.placeholder}@@ -765,10 +774,10 @@ function ClarifyToolSinglePending({ fromArgs, request }: { fromArgs: ClarifyArgs</ClarifyShell><div className="flex items-center justify-end gap-1">- <Button disabled={submitting} onClick={() => void respond('')} size="xs" type="button" variant="text">+ <Button disabled={submitting || !ready} onClick={() => void respond('')} size="xs" type="button" variant="text">{copy.skip}</Button>- <Button disabled={submitting || !pendingAnswer} size="xs" type="submit">+ <Button disabled={submitting || !ready || !pendingAnswer} size="xs" type="submit">{submitting ? (<Loader2 className="size-3 animate-spin" />) : (diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsxindex 31e3b5790fe..1ac4b7a7658 100644--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx@@ -578,7 +578,12 @@ const ErrorRecoveryActions: FC = () => {)}-const AssistantActionBar: FC<MessageActionProps> = ({ messageId, getMessageText, onBranchInNewChat }) => {+const AssistantActionBar: FC<MessageActionProps & { durationS?: number }> = ({+ durationS,+ messageId,+ getMessageText,+ onBranchInNewChat+}) => {const { t } = useI18n()const copy = t.assistant.thread@@ -595,6 +600,15 @@ const AssistantActionBar: FC<MessageActionProps> = ({ messageId, getMessageText,return (<div className="relative flex w-full shrink-0 items-center justify-end gap-1.5">+ {durationS !== undefined && (+ <span+ className="mr-auto select-none px-0.5 text-[0.6875rem] leading-5 tabular-nums text-muted-foreground"+ data-slot="aui_turn-duration"+ title={t.assistant.thread.turnDuration(formatElapsed(durationS))}+ >+ ⏱ {formatElapsed(durationS)}+ </span>+ )}<ActionBarPrimitive.RootclassName={// NOTE: intentionally NOT `hideWhenRunning`. That prop unmounts the@@ -713,19 +727,8 @@ const ReadAloudButton: FC<{ getText: () => string; messageId: string }> = ({ get}const AssistantFooter: FC<MessageActionProps & { durationS?: number }> = ({ durationS, ...props }) => {- const { t } = useI18n()-return (<div className="flex min-h-6 flex-col items-end gap-1 pr-(--message-text-indent) pl-(--message-text-indent)">- {durationS !== undefined && (- <span- className="select-none px-0.5 text-[0.6875rem] leading-5 tabular-nums text-muted-foreground"- data-slot="aui_turn-duration"- title={t.assistant.thread.turnDuration(formatElapsed(durationS))}- >- ⏱ {formatElapsed(durationS)}- </span>- )}<BranchPickerPrimitive.RootclassName="inline-flex h-6 items-center gap-1 text-xs text-muted-foreground"hideWhenSingleBranch@@ -740,7 +743,7 @@ const AssistantFooter: FC<MessageActionProps & { durationS?: number }> = ({ dura<Codicon name="chevron-right" size="0.875rem" /></BranchPickerPrimitive.Next></BranchPickerPrimitive.Root>- <AssistantActionBar {...props} />+ <AssistantActionBar durationS={durationS} {...props} /></div>)}diff --git a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsxindex 96e46879c05..e50718b189b 100644--- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx@@ -140,9 +140,21 @@ const ThinkingDisclosure: FC<{const scrollRef = useRef<HTMLDivElement | null>(null)const contentRef = useRef<HTMLDivElement | null>(null)const enterRef = useEnterAnimation(messageRunning, timerKey)+ // A live preview that later settles must not unmount its body — that is the+ // "turn settled and everything jumped" shift. Latch that we showed one so+ // the clip stays. Groups that mount already complete (earlier thoughts in+ // a still-running turn) never latch, so they stay collapsed.+ const [sawLivePreview, setSawLivePreview] = useState(false)++ if (pending && !sawLivePreview) {+ setSawLivePreview(true)+ }- const open = userOpen ?? (pending && !reasoningCollapsedByDefault)- const isPreview = pending && userOpen === null && !reasoningCollapsedByDefault+ // The collapsed-by-default preference outranks the latch: it opts out of+ // live previews entirely, so there is nothing to hold open.+ const showPreview = !reasoningCollapsedByDefault && (pending || sawLivePreview)+ const open = userOpen ?? showPreview+ const isPreview = userOpen === null && showPreview// Three ways a finished block can report itself. With a measured duration it// says so, unless the timer's whole seconds round it to "0s" — accurate anddiff --git a/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx b/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsxindex de9bb5cb8ac..8d2d386ec4d 100644--- a/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx@@ -396,6 +396,34 @@ function RunningReasoningHarness() {)}+// A turn that streams reasoning and then settles — the transition the+// preview latch exists for. `settle()` flips the thread to not-running.+function renderSettlingReasoning() {+ let setRunning: ((running: boolean) => void) | undefined++ function SettlingReasoningHarness() {+ const [running, setRunningState] = useState(true)++ setRunning = setRunningState++ const runtime = useExternalStoreRuntime<ThreadMessage>({+ messages: [assistantReasoningMessage('The user asked a question.', running)],+ isRunning: running,+ onNew: async () => {}+ })++ return (+ <AssistantRuntimeProvider runtime={runtime}>+ <Thread />+ </AssistantRuntimeProvider>+ )+ }++ const { container } = render(<SettlingReasoningHarness />)++ return { container, settle: () => act(() => setRunning?.(false)) }+}+function GroupedReasoningHarness() {const runtime = useExternalStoreRuntime<ThreadMessage>({messages: [assistantMultiReasoningMessage([' First thought.', ' Second thought.'])],@@ -510,6 +538,30 @@ describe('assistant-ui streaming renderer', () => {expect(finalRoot?.querySelector('[data-slot="aui_msg-actions"]')).toBeTruthy()})+ it('puts the turn duration on the action bar row instead of a line of its own', () => {+ const settled = {+ ...assistantMessage('All done.', false),+ metadata: {+ unstable_state: null,+ unstable_annotations: [],+ unstable_data: [],+ steps: [],+ custom: { durationS: 12 }+ }+ } as ThreadMessage++ const { container } = render(<TranscriptHarness messages={[userMessage(), settled]} />)++ const duration = container.querySelector('[data-slot="aui_turn-duration"]')+ const actions = container.querySelector('[data-slot="aui_msg-actions"]')++ // Same row as the (always-mounted) action bar: the footer's height is+ // already reserved while the turn streams, so landing the duration there+ // adds no height when the turn settles.+ expect(duration).toBeTruthy()+ expect(duration?.parentElement).toBe(actions?.parentElement)+ })+it('renders assistant provider errors inline', () => {render(<MessageHarness message={assistantErrorMessage('OpenRouter rejected the request (403).')} />)@@ -569,6 +621,48 @@ describe('assistant-ui streaming renderer', () => {expect(container.textContent).not.toContain('```ts')})+ it('does not collapse a live thinking preview when the turn settles', async () => {+ const { container, settle } = renderSettlingReasoning()+ const toggle = within(container).getByRole('button', { name: /thinking/i })++ expect(toggle.getAttribute('aria-expanded')).toBe('true')+ expect(container.querySelector('[data-slot="aui_reasoning-text"]')).toBeTruthy()++ settle()++ await waitFor(() => {+ expect(+ within(container)+ .getByRole('button', { name: /thought/i })+ .getAttribute('aria-expanded')+ ).toBe('true')+ })+ expect(container.querySelector('[data-slot="aui_reasoning-text"]')).toBeTruthy()+ })++ it('leaves a settling turn collapsed when the collapsed-by-default preference is enabled', async () => {+ $reasoningCollapsedByDefault.set(true)++ const { container, settle } = renderSettlingReasoning()++ expect(+ within(container)+ .getByRole('button', { name: /thinking/i })+ .getAttribute('aria-expanded')+ ).toBe('false')++ settle()++ await waitFor(() => {+ expect(+ within(container)+ .getByRole('button', { name: /thought/i })+ .getAttribute('aria-expanded')+ ).toBe('false')+ })+ expect(container.querySelector('[data-slot="aui_reasoning-text"]')).toBeNull()+ })+it('keeps streaming reasoning collapsed by default when the preference is enabled', () => {$reasoningCollapsedByDefault.set(true)