Skip to content

The agent that grows with you

fix(desktop): stop one clarify call from rendering as N identical live cards

liuhao1024988d26b569b0
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts
index eff319eb6a4..d9c07241184 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts
@@ -2106,6 +2106,44 @@ describe('overlayConcurrentMessageChanges', () => {
])
})
+ // A re-delivered open_requests marks the cached activation row "changed";
+ // the raw concat used to carry the same clarify call twice, interleaved
+ // with reasoning that ran between the copies.
+ it('does not duplicate a tool call the re-fetched row already carries when merging the prefix', () => {
+ const authoritative = [
+ {
+ id: 'assistant-stream-activation',
+ role: 'assistant',
+ parts: [
+ { type: 'text', text: 'partial A' },
+ { type: 'tool-call', toolCallId: 'call-clarify', toolName: 'clarify' }
+ ],
+ pending: true
+ }
+ ] as ChatMessage[]
+
+ const current = [
+ {
+ id: 'assistant-stream-runtime',
+ role: 'assistant',
+ parts: [
+ { type: 'tool-call', toolCallId: 'call-clarify', toolName: 'clarify' },
+ { type: 'reasoning', text: 'mid reasoning' },
+ { type: 'text', text: ' + delta B' }
+ ],
+ pending: true
+ }
+ ] as ChatMessage[]
+
+ const overlaid = overlayConcurrentMessageChanges(authoritative, [], current)
+
+ expect(overlaid.map(message => message.id)).toEqual(['assistant-stream-runtime'])
+ const toolCallIds = overlaid[0].parts.flatMap(part => (part.type === 'tool-call' ? [part.toolCallId] : []))
+ expect(toolCallIds).toEqual(['call-clarify'])
+ // The activation side still contributes what the fresh row lacks.
+ expect(overlaid[0].parts[0]).toEqual({ type: 'text', text: 'partial A' })
+ })
+
// Switch back to a chat mid-reply: session.activate snapshots the first
// chunk, message.complete settles the live row, THEN the gated REST page
// resolves with the committed reply. Warm-activation composition order.
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
index e0a4bb426fd..d3d49317c9a 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
@@ -1595,6 +1595,25 @@ export function removeRepresentedLocalLiveProjection(
)
}
+/**
+ * Concatenate an activation row's parts with the re-fetched row's parts, but
+ * let the fresher side win per tool call: a re-delivered `open_requests` marks
+ * the cached row changed, and a raw concat would render the same call twice —
+ * interleaved with reasoning from between the copies. Non-tool parts concat
+ * unchanged.
+ */
+function mergeActivationStreamParts(activationParts: ChatMessage['parts'], currentParts: ChatMessage['parts']) {
+ const deliveredIds = new Set(
+ currentParts.flatMap(part => (part.type === 'tool-call' ? [part.toolCallId] : []))
+ )
+
+ const activationTail = activationParts.filter(
+ part => !(part.type === 'tool-call' && deliveredIds.has(part.toolCallId))
+ )
+
+ return [...activationTail, ...currentParts]
+}
+
/**
* Overlay messages that changed while activation waited on REST. Existing ids
* replace the older activation row; only rows added or changed since the warm
@@ -1728,7 +1747,7 @@ export function overlayConcurrentMessageChanges(
const replacement =
activationText && !currentText.startsWith(activationText)
- ? { ...current, parts: [...activationStream.parts, ...current.parts] }
+ ? { ...current, parts: mergeActivationStreamParts(activationStream.parts, current.parts) }
: current
nextIndexById.delete(activationStream.id)
diff --git a/apps/desktop/src/components/assistant-ui/clarify/clarify-tool.test.tsx b/apps/desktop/src/components/assistant-ui/clarify/clarify-tool.test.tsx
index 8a96e68fe9a..b1770037ef4 100644
--- a/apps/desktop/src/components/assistant-ui/clarify/clarify-tool.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify/clarify-tool.test.tsx
@@ -2,7 +2,7 @@ import type { ToolCallMessagePartProps } from '@assistant-ui/react'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { atom } from 'nanostores'
import type { ReactNode } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { type SessionView, SessionViewProvider } from '@/app/chat/session-view'
import { hiddenPaneProps } from '@/components/pane-shell/pane-visibility'
@@ -56,6 +56,7 @@ beforeEach(() => {
afterEach(() => {
cleanup()
clearClarifyRequest()
+ $settledClarifyResults.set({})
resetServerRequestsForTests()
$activeSessionId.set(null)
$gateway.set(null)
@@ -229,12 +230,14 @@ describe('ClarifyTool live card stays mounted across settle', () => {
requestId: 'request-1',
sessionId: 'session-1'
})
+
const args = {
questions: [
{ question: 'Which deployment target?', choices: ['staging', 'production'] },
{ question: 'Which region?', choices: ['us', 'eu'] }
]
}
+
const props = { ...liveClarifyProps(), args, argsText: JSON.stringify(args) }
renderClarify(<ClarifyTool {...props} />)
@@ -296,6 +299,84 @@ describe('ClarifyTool live card stays mounted across settle', () => {
})
})
+describe('ClarifyTool stale rows vs the session current question', () => {
+ // jsdom has no Web Animations API; the demoted row's enter animation would
+ // throw on mount.
+ beforeAll(() => {
+ Element.prototype.animate ??= (() => ({ cancel: () => {}, finished: Promise.resolve() })) as never
+ })
+
+ it('a row that does not carry the live question renders as history, not a second card', () => {
+ // A re-delivered activate left a duplicate result-less row behind; the
+ // session's live request asks a different question than this row's args.
+ messageRunning = true
+ $activeSessionId.set('session-1')
+ $gateway.set({ request: vi.fn() } as never)
+ setClarifyRequest({
+ questions: [{ choices: ['us', 'eu'], multiSelect: false, qid: 'q0', question: 'Which region?' }],
+ requestId: 'request-2',
+ sessionId: 'session-1'
+ })
+
+ renderClarify(<ClarifyTool {...liveClarifyProps()} toolCallId="clarify-dup" />)
+
+ expect(document.querySelector('[data-clarify-choices]')).toBeNull()
+ expect(screen.queryByText('Which region?')).toBeNull()
+ })
+
+ it('a batch row keeps following the live request while its args cover the questions', () => {
+ messageRunning = true
+ $activeSessionId.set('session-1')
+ $gateway.set({ request: vi.fn() } as never)
+ setClarifyRequest({
+ questions: [{ choices: ['us', 'eu'], multiSelect: false, qid: 'q0', question: 'Which region?' }],
+ requestId: 'request-2',
+ sessionId: 'session-1'
+ })
+
+ const args = {
+ questions: [
+ { question: 'Which deployment target?', choices: ['staging', 'production'] },
+ { question: 'Which region?', choices: ['us', 'eu'] }
+ ]
+ }
+
+ renderClarify(<ClarifyTool {...liveClarifyProps()} args={args} argsText={JSON.stringify(args)} toolCallId="clarify-batch" />)
+
+ expect(document.querySelector('[data-clarify-choices]')).toBeTruthy()
+ expect(screen.getByText('Which region?')).toBeTruthy()
+ })
+
+ it('a row bound to its answered request settles instead of following a newer question', () => {
+ messageRunning = true
+ $activeSessionId.set('session-1')
+ $gateway.set({ request: vi.fn() } as never)
+ setClarifyRequest({
+ questions: [{ choices: ['staging', 'production'], multiSelect: false, qid: 'q0', question: 'Which deployment target?' }],
+ requestId: 'request-1',
+ sessionId: 'session-1'
+ })
+ const { rerender } = renderClarify(<ClarifyTool {...liveClarifyProps()} toolCallId="clarify-history" />)
+
+ expect(document.querySelector('[data-clarify-choices]')).toBeTruthy()
+
+ act(() => {
+ $settledClarifyResults.set({
+ 'request-1': { outcome: 'submitted', responses: [{ question: 'Which deployment target?', status: 'answered', user_response: 'staging' }] }
+ })
+ setClarifyRequest({
+ questions: [{ choices: ['us', 'eu'], multiSelect: false, qid: 'q0', question: 'Which region?' }],
+ requestId: 'request-2',
+ sessionId: 'session-1'
+ })
+ })
+ rerender(clarifyTree(<ClarifyTool {...liveClarifyProps()} toolCallId="clarify-history" />))
+
+ expect(document.querySelector('[data-clarify-settled]')).toBeTruthy()
+ expect(document.querySelector('[data-clarify-choices]')).toBeNull()
+ })
+})
+
describe('ClarifyTool choice selection', () => {
it('labels single-select vs multi-select before the user clicks', () => {
const { rerender } = renderLiveClarify()
diff --git a/apps/desktop/src/components/assistant-ui/clarify/index.tsx b/apps/desktop/src/components/assistant-ui/clarify/index.tsx
index 1bb815a7392..525ce825b20 100644
--- a/apps/desktop/src/components/assistant-ui/clarify/index.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify/index.tsx
@@ -6,11 +6,11 @@ import { useMemo, useState } from 'react'
import { useSessionView } from '@/app/chat/session-view'
import { ToolFallback } from '@/components/assistant-ui/tool/fallback'
-import { $settledClarifyResults, sessionClarifyRequest } from '@/store/clarify'
+import { $settledClarifyResults, type ClarifyRequest, sessionClarifyRequest } from '@/store/clarify'
import { selectMessageRunning } from '../tool/fallback-model'
-import { readClarifyArgs } from './parse'
+import { type ClarifyArgs, readClarifyArgs } from './parse'
import { ClarifyToolPending } from './pending'
import { ClarifyToolSettled } from './settled'
import { useUndeliveredClarify } from './use-undelivered'
@@ -31,6 +31,21 @@ export const ClarifyTool = (props: ToolCallMessagePartProps) => {
// would show a later card the answer of an earlier one.
const requestIdByToolCall = new Map<string, string>()
+// Whether this row may follow the session's live request: only when its own
+// args cover every question the request asks. A one-at-a-time batch re-arms
+// the same row for its next question, so the row must keep up — but a
+// duplicate row left behind by a re-delivered activate must not paint the
+// current question as a second live card. No request means nothing to follow.
+function rowCoversRequest(request: ClarifyRequest | null, args: ClarifyArgs): boolean {
+ if (!request) {
+ return true
+ }
+
+ const asked = new Set((args.questions ?? []).map(entry => entry.question.trim()))
+
+ return asked.size > 0 && request.questions.every(question => asked.has(question.question.trim()))
+}
+
function ClarifyToolLive(props: ToolCallMessagePartProps) {
// The tool row is in whichever session's transcript rendered it — read THAT
// session's clarify (primary or tile), not the globally-active one.
@@ -47,11 +62,13 @@ function ClarifyToolLive(props: ToolCallMessagePartProps) {
const [answered, setAnswered] = useState(false)
const settledResults = useStore($settledClarifyResults)
const requestId = requestIdByToolCall.get(rowKey)
+ const covers = rowCoversRequest(request, fromArgs)
// The chat bar settles a one-question card as soon as it is answered. The
// gateway then sends the next question as a new request on this same row.
// That live request replaces the settlement, or the next question never
- // appears and the next chat-bar line is taken as its answer.
- const nextRequest = Boolean(request && request.requestId !== requestId)
+ // appears and the next chat-bar line is taken as its answer. Only a row
+ // whose args cover the request follows it.
+ const nextRequest = Boolean(request && covers && request.requestId !== requestId)
if (request && nextRequest) {
requestIdByToolCall.set(rowKey, request.requestId)
@@ -65,6 +82,13 @@ function ClarifyToolLive(props: ToolCallMessagePartProps) {
return <ClarifyToolSettled {...props} result={settledResult} />
}
+ // A row that does not carry the live question (a re-delivered duplicate, an
+ // earlier call) is history: it renders its own args as a plain tool row,
+ // never as the session's one interactive card.
+ if (request && !covers && !answered) {
+ return <ToolFallback {...props} />
+ }
+
// Stopped mid-prompt with no result — don't leave a dead interactive panel.
// `session.info` reports running=false while clarify is blocking, so the
// running flag alone would remount the question as a tool row. Keep the