Skip to content

The agent that grows with you

fix(desktop): render a clarify request only on the row the re-arm bound

Austin Pickette76e8ca41fac
diff --git a/apps/desktop/src/components/assistant-ui/clarify/clarify-one-card-per-question.test.tsx b/apps/desktop/src/components/assistant-ui/clarify/clarify-one-card-per-question.test.tsx
index 005adb5c0d7..b630076dc32 100644
--- a/apps/desktop/src/components/assistant-ui/clarify/clarify-one-card-per-question.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify/clarify-one-card-per-question.test.tsx
@@ -1,5 +1,5 @@
import type { ToolCallMessagePartProps } from '@assistant-ui/react'
-import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
@@ -62,23 +62,20 @@ const tree = (ui: ReactNode) => (
</I18nProvider>
)
-function rowProps(messages: ChatMessage[], toolCallId: string): ToolCallMessagePartProps {
- const part = messages[0].parts.find(entry => entry.type === 'tool-call' && entry.toolCallId === toolCallId)
-
- if (part?.type !== 'tool-call') {
- throw new Error(`no tool row ${toolCallId}`)
- }
+type ClarifyPart = Extract<ChatMessage['parts'][number], { type: 'tool-call' }>
+function rowProps(part: ClarifyPart): ToolCallMessagePartProps & { clarifyRequestId?: string } {
return {
addResult: vi.fn(),
args: part.args,
argsText: JSON.stringify(part.args),
+ clarifyRequestId: part.clarifyRequestId,
isError: false,
respondToApproval: vi.fn(),
result: undefined,
resume: vi.fn(),
status: { type: 'running' },
- toolCallId,
+ toolCallId: part.toolCallId,
toolName: 'clarify',
type: 'tool-call'
} as ToolCallMessagePartProps
@@ -88,37 +85,61 @@ function clarifyCall(toolCallId: string, questions: (typeof TARGET)[]) {
return { args: { questions }, toolCallId, toolName: 'clarify', type: 'tool-call' } as never
}
-/** One assistant message whose clarify rows re-arm the way `parkClarify` does. */
-function transcript(...calls: ReturnType<typeof clarifyCall>[]) {
+const clarifyParts = (messages: ChatMessage[]) =>
+ messages.flatMap(message => message.parts.filter((part): part is ClarifyPart => part.type === 'tool-call'))
+
+/** Cards whose choices can be answered right now. */
+const liveCards = (container: HTMLElement) =>
+ [...container.querySelectorAll('[data-clarify-choices]')].filter(choices =>
+ choices.querySelector('button:not([disabled])')
+ ).length
+
+/** Assistant messages (one per argument) whose clarify rows re-arm the way `parkClarify` does. */
+function transcript(...rows: ReturnType<typeof clarifyCall>[][]) {
const request = vi.fn().mockResolvedValue({ ok: true })
- let messages: ChatMessage[] = [{ id: 'm1', parts: calls, pending: true, role: 'assistant' }]
+
+ let messages: ChatMessage[] = rows.map((parts, index) => ({
+ id: `m${index + 1}`,
+ parts,
+ pending: true,
+ role: 'assistant'
+ }))
$activeSessionId.set('session-1')
$gateway.set({ request } as never)
return {
add(call: ReturnType<typeof clarifyCall>) {
- messages = [{ ...messages[0], parts: [...messages[0].parts, call] }]
+ const tail = messages.at(-1)!
+ messages = [...messages.slice(0, -1), { ...tail, parts: [...tail.parts, call] }]
},
locks: () =>
[...request.mock.calls, ...gatewayMocks.requestGatewayForAgent.mock.calls].filter(call =>
(call as unknown[]).includes('clarify.lock')
),
- park(next: ClarifyRequest) {
+ /** Park the next card. `appends`: the re-arm cannot pick between open rows and adds its own. */
+ park(next: ClarifyRequest, { appends = false } = {}) {
rememberServerRequest({ fail: vi.fn(), id: next.requestId, method: 'clarify', params: {}, respond: vi.fn() })
setClarifyRequest(next)
- const projection = restorePendingClarifyToolCall(messages, pendingClarifyToolPayload(next))
- // Re-armed in place: a card never grows a second row.
- expect(projection.messages[0].parts).toHaveLength(messages[0].parts.length)
- messages = projection.messages
+ const before = clarifyParts(messages).length
+ messages = restorePendingClarifyToolCall(messages, pendingClarifyToolPayload(next)).messages
+ expect(clarifyParts(messages)).toHaveLength(before + (appends ? 1 : 0))
},
- props: (toolCallId: string) => rowProps(messages, toolCallId)
+ props: (toolCallId: string) => rowProps(clarifyParts(messages).find(part => part.toolCallId === toolCallId)!),
+ /** Every clarify row, in transcript order. */
+ rows: () => (
+ <>
+ {clarifyParts(messages).map((part, index) => (
+ <ClarifyTool key={index} {...rowProps(part)} />
+ ))}
+ </>
+ )
}
}
describe('a clarify asked one card per question', () => {
it('shows the next card after the chat bar answered the first, and the chat bar answers that card', async () => {
- const chat = transcript(clarifyCall('call-1', [TARGET, REGION]))
+ const chat = transcript([clarifyCall('call-1', [TARGET, REGION])])
chat.park(card('prompt-1', TARGET))
const view = render(tree(<ClarifyTool {...chat.props('call-1')} />))
@@ -148,7 +169,7 @@ describe('a clarify asked one card per question', () => {
})
it('shows the next card after Skip on the first', () => {
- const chat = transcript(clarifyCall('call-1', [TARGET, REGION]))
+ const chat = transcript([clarifyCall('call-1', [TARGET, REGION])])
chat.park(card('prompt-1', TARGET))
const view = render(tree(<ClarifyTool {...chat.props('call-1')} />))
@@ -165,9 +186,9 @@ describe('a clarify asked one card per question', () => {
it("keeps an earlier call's answered row settled when a later call asks", () => {
// The earlier row never got its tool.complete (a lost frame, or a duplicate row a re-delivered
// activate left behind), so it is still a live clarify row when the later call's question lands.
- const chat = transcript(clarifyCall('call-1', [TARGET]))
+ const chat = transcript([clarifyCall('call-1', [TARGET])])
chat.park(card('prompt-1', TARGET))
- const view = render(tree(<ClarifyTool {...chat.props('call-1')} />))
+ const view = render(tree(chat.rows()))
act(() => {
expect(answerParkedCard('session-1', 'staging')).toBe(true)
@@ -175,17 +196,72 @@ describe('a clarify asked one card per question', () => {
chat.add(clarifyCall('call-2', [REGION]))
act(() => chat.park(card('prompt-2', REGION)))
- view.rerender(
- tree(
- <>
- <ClarifyTool {...chat.props('call-1')} />
- <ClarifyTool {...chat.props('call-2')} />
- </>
- )
- )
+ view.rerender(tree(chat.rows()))
+
+ expect(view.container.querySelectorAll('[data-clarify-settled]')).toHaveLength(1)
+ expect(screen.getAllByText('Which region?')).toHaveLength(1)
+ expect(screen.getByRole('button', { name: /^.*eu/ }).hasAttribute('disabled')).toBe(false)
+ })
+
+ it('keeps an earlier answered call settled when a later call asks the same question', () => {
+ const chat = transcript([clarifyCall('call-1', [TARGET])])
+ chat.park(card('prompt-1', TARGET))
+ const view = render(tree(chat.rows()))
+
+ act(() => {
+ expect(answerParkedCard('session-1', 'staging')).toBe(true)
+ })
+
+ chat.add(clarifyCall('call-2', [TARGET]))
+ act(() => chat.park(card('prompt-2', TARGET)))
+ view.rerender(tree(chat.rows()))
expect(view.container.querySelectorAll('[data-clarify-settled]')).toHaveLength(1)
+ expect(liveCards(view.container)).toBe(1)
+ })
+
+ it("does not show a later call's question on a card answered with its own Confirm", async () => {
+ // Confirm latches the card until tool.complete; here that completion has not landed yet.
+ const chat = transcript([clarifyCall('call-1', [TARGET])])
+ chat.park(card('prompt-1', TARGET))
+ const view = render(tree(chat.rows()))
+
+ fireEvent.click(screen.getByRole('button', { name: /staging/ }))
+ fireEvent.click(screen.getByRole('button', { name: /Confirm and continue/ }))
+ await waitFor(() => expect(chat.locks()).toHaveLength(1))
+
+ chat.add(clarifyCall('call-2', [REGION]))
+ act(() => chat.park(card('prompt-2', REGION)))
+ view.rerender(tree(chat.rows()))
+
+ expect(liveCards(view.container)).toBe(1)
expect(screen.getAllByText('Which region?')).toHaveLength(1)
+ })
+
+ it('shows each card once when the call is duplicated in a second message', () => {
+ // A re-delivered activate can leave a copy of the call; neither copy's args single out a card,
+ // so the re-arm adds its own row for each one.
+ const chat = transcript([clarifyCall('call-1', [TARGET, REGION])], [clarifyCall('call-1', [TARGET, REGION])])
+ chat.park(card('prompt-1', TARGET), { appends: true })
+ const view = render(tree(chat.rows()))
+ expect(liveCards(view.container)).toBe(1)
+
+ act(() => {
+ expect(answerParkedCard('session-1', 'staging')).toBe(true)
+ })
+
+ act(() => chat.park(card('prompt-2', REGION), { appends: true }))
+ view.rerender(tree(chat.rows()))
+
+ expect(liveCards(view.container)).toBe(1)
expect(screen.getByRole('button', { name: /^.*eu/ }).hasAttribute('disabled')).toBe(false)
})
+
+ it('shows one card when a one-question call is duplicated', () => {
+ const chat = transcript([clarifyCall('call-1', [TARGET])], [clarifyCall('call-1', [TARGET])])
+ chat.park(card('prompt-1', TARGET))
+ const view = render(tree(chat.rows()))
+
+ expect(liveCards(view.container)).toBe(1)
+ })
})
diff --git a/apps/desktop/src/components/assistant-ui/clarify/index.tsx b/apps/desktop/src/components/assistant-ui/clarify/index.tsx
index 525ce825b20..9195167d9aa 100644
--- a/apps/desktop/src/components/assistant-ui/clarify/index.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify/index.tsx
@@ -6,6 +6,7 @@ import { useMemo, useState } from 'react'
import { useSessionView } from '@/app/chat/session-view'
import { ToolFallback } from '@/components/assistant-ui/tool/fallback'
+import type { TimelinePartMetadata } from '@/lib/chat-messages'
import { $settledClarifyResults, type ClarifyRequest, sessionClarifyRequest } from '@/store/clarify'
import { selectMessageRunning } from '../tool/fallback-model'
@@ -15,7 +16,9 @@ import { ClarifyToolPending } from './pending'
import { ClarifyToolSettled } from './settled'
import { useUndeliveredClarify } from './use-undelivered'
-export const ClarifyTool = (props: ToolCallMessagePartProps) => {
+type ClarifyToolProps = ToolCallMessagePartProps & Pick<TimelinePartMetadata, 'clarifyRequestId'>
+
+export const ClarifyTool = (props: ClarifyToolProps) => {
// Answered → settled Q&A (ToolFallback collapsed the answer away).
if (props.result !== undefined) {
return <ClarifyToolSettled {...props} />
@@ -31,14 +34,19 @@ 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 {
+// Whether this row renders the session's live request. The transcript re-arm
+// ties each request to one row (`clarifyRequestId`): that row follows it, even
+// when the gateway asks a batch one card per question on the same row. Every
+// other row it saw is history, including an earlier call or a duplicated copy
+// that asks the same question. A row no re-arm has seen follows a request its
+// own args cover.
+function ownsRequest(request: ClarifyRequest | null, row: ClarifyToolProps, args: ClarifyArgs): boolean {
if (!request) {
- return true
+ return false
+ }
+
+ if (row.clarifyRequestId !== undefined) {
+ return row.clarifyRequestId === request.requestId
}
const asked = new Set((args.questions ?? []).map(entry => entry.question.trim()))
@@ -46,7 +54,7 @@ function rowCoversRequest(request: ClarifyRequest | null, args: ClarifyArgs): bo
return asked.size > 0 && request.questions.every(question => asked.has(question.question.trim()))
}
-function ClarifyToolLive(props: ToolCallMessagePartProps) {
+function ClarifyToolLive(props: ClarifyToolProps) {
// The tool row is in whichever session's transcript rendered it — read THAT
// session's clarify (primary or tile), not the globally-active one.
const sessionId = useStore(useSessionView().$runtimeId)
@@ -61,20 +69,18 @@ function ClarifyToolLive(props: ToolCallMessagePartProps) {
// the request and must still collapse an unanswered card.
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. Only a row
- // whose args cover the request follows it.
- const nextRequest = Boolean(request && covers && request.requestId !== requestId)
-
- if (request && nextRequest) {
+ const owner = ownsRequest(request, props, fromArgs)
+
+ if (request && owner) {
requestIdByToolCall.set(rowKey, request.requestId)
}
- const settledResult = !nextRequest && requestId ? settledResults[requestId] : undefined
+ // The chat bar and Skip store an answer before `tool.complete`. It shows
+ // until this row's next live request: the gateway asks a batch one card per
+ // question, and a stored answer that outlived its card would hide the next
+ // question while the chat bar answered it.
+ const requestId = requestIdByToolCall.get(rowKey)
+ const settledResult = !owner && requestId ? settledResults[requestId] : undefined
const undelivered = useUndeliveredClarify(sessionId, messageRunning && !request && !answered && !settledResult)
@@ -82,10 +88,10 @@ 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) {
+ // A row that does not own the live question (an earlier call, a duplicated
+ // copy) is history: it renders its own args as a plain tool row, never as
+ // the session's one interactive card.
+ if (request && !owner && !answered) {
return <ToolFallback {...props} />
}
@@ -97,11 +103,13 @@ function ClarifyToolLive(props: ToolCallMessagePartProps) {
return <ToolFallback {...props} />
}
+ // A row answered from its own card waits for `tool.complete` with its own
+ // args. A live request it does not own belongs to another row.
return (
<ClarifyToolPending
fromArgs={fromArgs}
onAnswered={() => setAnswered(true)}
- request={request}
+ request={owner ? request : null}
undelivered={undelivered}
/>
)
diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.ts
index 4c7cfcf562b..45f812249e6 100644
--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts
+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts
@@ -623,7 +623,46 @@ export function restorePendingClarifyToolCall(
payload: GatewayEventPayload,
occurredAt = Date.now() / 1000
): PendingClarifyProjection {
- return restorePendingBlockingToolCall(messages, { name: 'clarify', ...payload }, occurredAt)
+ const { at, ...projection } = rearmBlockingToolCall(messages, { name: 'clarify', ...payload }, occurredAt)
+ const requestId = toolId(payload)
+
+ return at && requestId ? { ...projection, messages: bindClarifyRow(projection.messages, at, requestId) } : projection
+}
+
+/**
+ * Tie the live clarify request to the one row the re-arm picked: that row carries the request id, every
+ * other open clarify row `''`, so `ClarifyToolLive` renders the request on that row only. Question text
+ * cannot decide this: an earlier call left without its completion, or a duplicated copy of this one, can
+ * ask the same question. A row already tied to another request keeps that id.
+ */
+function bindClarifyRow(messages: ChatMessage[], at: PendingClarifyLocation, requestId: string): ChatMessage[] {
+ return messages.map((message, messageIndex) => {
+ let changed = false
+
+ const parts = message.parts.map((part, partIndex) => {
+ if (part.type !== 'tool-call' || !QUESTION_CARD_TOOLS.has(part.toolName) || part.result !== undefined) {
+ return part
+ }
+
+ const owner = messageIndex === at.messageIndex && partIndex === at.partIndex
+
+ const clarifyRequestId = owner
+ ? requestId
+ : part.clarifyRequestId === undefined || part.clarifyRequestId === requestId
+ ? ''
+ : part.clarifyRequestId
+
+ if (part.clarifyRequestId === clarifyRequestId) {
+ return part
+ }
+
+ changed = true
+
+ return { ...part, clarifyRequestId }
+ })
+
+ return changed ? { ...message, parts } : message
+ })
}
/** Restore a blocking tool row (clarify, connection card) from a resume snapshot: mark the
@@ -633,6 +672,17 @@ export function restorePendingBlockingToolCall(
clarifyPayload: GatewayEventPayload & { name: string },
occurredAt = Date.now() / 1000
): PendingClarifyProjection {
+ const { at: _at, ...projection } = rearmBlockingToolCall(messages, clarifyPayload, occurredAt)
+
+ return projection
+}
+
+/** `restorePendingBlockingToolCall`, plus where the re-armed or appended part sits. */
+function rearmBlockingToolCall(
+ messages: ChatMessage[],
+ clarifyPayload: GatewayEventPayload & { name: string },
+ occurredAt: number
+): PendingClarifyProjection & { at: null | PendingClarifyLocation } {
const location = findPendingClarifyLocation(messages, clarifyPayload, new Set([clarifyPayload.name]))
if (location) {
@@ -640,7 +690,7 @@ export function restorePendingBlockingToolCall(
const part = message.parts[location.partIndex]
if (part.type !== 'tool-call') {
- return { messages, streamId: message.id }
+ return { at: null, messages, streamId: message.id }
}
// A correlated row that settle sealed (stop, lost completion) is live
@@ -661,7 +711,7 @@ export function restorePendingBlockingToolCall(
const next = [...messages]
next[location.messageIndex] = { ...message, parts, pending: true }
- return { messages: next, streamId: message.id }
+ return { at: location, messages: next, streamId: message.id }
}
const parts = upsertToolPart([], clarifyPayload, 'running', occurredAt)
@@ -670,18 +720,16 @@ export function restorePendingBlockingToolCall(
if (tail?.role === 'assistant') {
const next = [...messages]
- next[tailIndex] = {
- ...tail,
- parts: [...completeOpenStreamParts(tail.parts, occurredAt), ...parts],
- pending: true
- }
+ const tailParts = [...completeOpenStreamParts(tail.parts, occurredAt), ...parts]
+ next[tailIndex] = { ...tail, parts: tailParts, pending: true }
- return { messages: next, streamId: tail.id }
+ return { at: { messageIndex: tailIndex, partIndex: tailParts.length - 1 }, messages: next, streamId: tail.id }
}
const streamId = nextLiveToolId(`${clarifyPayload.name}-message`)
return {
+ at: { messageIndex: messages.length, partIndex: 0 },
messages: [
...messages,
{
diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.ts
index 59153fdabaa..9eef26d1bcc 100644
--- a/apps/desktop/src/lib/chat-messages/types.ts
+++ b/apps/desktop/src/lib/chat-messages/types.ts
@@ -24,6 +24,10 @@ export interface TimelinePartMetadata {
storedResultToolName?: string
/** Durable source occurrence, even when several backend rows share a bubble. */
sourceRowId?: number
+ /** A clarify row's tie to the session's live request, set by the transcript re-arm
+ * (`restorePendingClarifyToolCall`): the id of the request it bound to this row, or `''` on every
+ * other open clarify row it saw. Only the row carrying the live request's id renders it. */
+ clarifyRequestId?: string
}
export type ChatMessagePart = Exclude<ThreadMessageLike['content'], string>[number] & TimelinePartMetadata