Skip to content

The agent that grows with you

fix(desktop): re-arm pending clarify cards in place

Brooklyn Nicholsondc998a2d59f6
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx
index 8f2fe2defcd..2e1e1b31807 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx
@@ -1,6 +1,8 @@
import { act, cleanup } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ChatMessage } from '@/lib/chat-messages'
+import { createClientSessionState } from '@/lib/chat-runtime'
import { $clarifyRequests, clearClarifyRequest } from '@/store/clarify'
import { onScrollToBottomRequest } from '@/store/thread-scroll'
@@ -28,12 +30,25 @@ const clarifyRequest = (payload: Record<string, unknown>) =>
const toolStart = (payload: Record<string, unknown>) =>
act(() => stream.handleEvent({ payload, session_id: SID, type: 'tool.start' }))
+const toolComplete = (payload: Record<string, unknown>) =>
+ act(() => stream.handleEvent({ payload, session_id: SID, type: 'tool.complete' }))
+
+const clarifyExpire = (requestId: string) =>
+ act(() => stream.handleEvent({ payload: { request_id: requestId }, session_id: SID, type: 'clarify.expire' }))
+
function clarifyParts() {
const messages = stream.state().messages ?? []
return messages.flatMap(m => m.parts).filter(p => p.type === 'tool-call' && p.toolName === 'clarify')
}
+function seedHydratedMessages(messages: ChatMessage[]) {
+ const state = createClientSessionState()
+ state.messages = messages
+ state.streamId = null
+ stream.states.set(SID, state)
+}
+
describe('clarify.request stream hydration', () => {
beforeEach(() => {
clearClarifyRequest()
@@ -132,6 +147,131 @@ describe('clarify.request stream hydration', () => {
expect(clarifyParts()).toHaveLength(1)
})
+ it('re-arms a hydrated Codex tool-only clarify in place instead of appending a second card', () => {
+ mountStream()
+
+ seedHydratedMessages([
+ { id: 'user-1', role: 'user', parts: [{ type: 'text', text: 'help me choose' }] },
+ {
+ id: 'assistant-codex',
+ role: 'assistant',
+ parts: [
+ {
+ type: 'tool-call',
+ toolCallId: 'call-codex',
+ toolName: 'clarify',
+ args: { choices: ['a', 'b'], question: 'Pick' },
+ argsText: '{"question":"Pick","choices":["a","b"]}'
+ }
+ ]
+ }
+ ])
+
+ clarifyRequest({ choices: ['a', 'b'], question: 'Pick', request_id: 'req-codex' })
+
+ const messages = stream.state().messages
+ expect(messages).toHaveLength(2)
+ expect(clarifyParts()).toHaveLength(1)
+ expect(messages[1]).toMatchObject({ id: 'assistant-codex', pending: true })
+ expect(stream.state().streamId).toBe('assistant-codex')
+ })
+
+ it('keeps a hydrated DeepSeek text-plus-clarify row in its original position', () => {
+ mountStream()
+
+ seedHydratedMessages([
+ { id: 'user-1', role: 'user', parts: [{ type: 'text', text: 'inspect this' }] },
+ {
+ id: 'assistant-deepseek',
+ role: 'assistant',
+ parts: [
+ { type: 'text', text: 'I found two paths; choose one.' },
+ {
+ type: 'tool-call',
+ toolCallId: 'call-deepseek',
+ toolName: 'clarify',
+ args: { choices: ['safe', 'fast'], question: 'Which path?' },
+ argsText: '{"question":"Which path?","choices":["safe","fast"]}'
+ }
+ ]
+ }
+ ])
+
+ clarifyRequest({ choices: ['safe', 'fast'], question: 'Which path?', request_id: 'req-deepseek' })
+
+ const messages = stream.state().messages
+ expect(messages).toHaveLength(2)
+ expect(messages[1].id).toBe('assistant-deepseek')
+ expect(messages[1].parts.map(part => part.type)).toEqual(['text', 'tool-call'])
+ expect(messages[1].pending).toBe(true)
+ expect(stream.state().streamId).toBe('assistant-deepseek')
+ })
+
+ it('settles the re-armed provider tool id in place when tool.complete arrives', () => {
+ mountStream()
+
+ seedHydratedMessages([
+ { id: 'user-1', role: 'user', parts: [{ type: 'text', text: 'inspect this' }] },
+ {
+ id: 'assistant-deepseek',
+ role: 'assistant',
+ parts: [
+ { type: 'text', text: 'I found two paths; choose one.' },
+ {
+ type: 'tool-call',
+ toolCallId: 'call-provider',
+ toolName: 'clarify',
+ args: { choices: ['safe', 'fast'], question: 'Which path?' },
+ argsText: '{"question":"Which path?","choices":["safe","fast"]}'
+ }
+ ]
+ }
+ ])
+
+ clarifyRequest({ choices: ['safe', 'fast'], question: 'Which path?', request_id: 'req-ui' })
+ toolComplete({
+ args: { choices: ['safe', 'fast'], question: 'Which path?' },
+ name: 'clarify',
+ result: { question: 'Which path?', user_response: 'safe' },
+ tool_id: 'call-provider'
+ })
+
+ const parts = clarifyParts()
+ expect(parts).toHaveLength(1)
+ expect(parts[0]).toMatchObject({ toolCallId: 'call-provider', result: { user_response: 'safe' } })
+ })
+
+ it('ignores a late clarify.request after the turn was interrupted', () => {
+ mountStream()
+ seedHydratedMessages([{ id: 'user-1', role: 'user', parts: [{ type: 'text', text: 'stop this' }] }])
+
+ const state = stream.states.get(SID)!
+ state.interrupted = true
+
+ clarifyRequest({ choices: ['a', 'b'], question: 'Pick', request_id: 'req-late' })
+
+ expect($clarifyRequests.get()[SID]).toBeUndefined()
+ expect(stream.state().messages).toHaveLength(1)
+ })
+
+ it('expires only the matching clarify request and deactivates its card', () => {
+ mountStream()
+
+ toolStart({ args: { choices: ['a'], question: 'Pick' }, name: 'clarify', tool_id: 'call-provider' })
+ clarifyRequest({ choices: ['a'], question: 'Pick', request_id: 'req-expire' })
+ clarifyExpire('req-other')
+
+ expect($clarifyRequests.get()[SID]?.requestId).toBe('req-expire')
+ expect(clarifyParts()[0]).not.toHaveProperty('result')
+
+ clarifyExpire('req-expire')
+
+ expect($clarifyRequests.get()[SID]).toBeUndefined()
+ expect(clarifyParts()).toHaveLength(1)
+ expect(clarifyParts()[0]).toHaveProperty('result')
+ expect(stream.state().needsInput).toBe(false)
+ })
+
it('merges a BATCH tool.start row with its clarify.request (no top-level question)', () => {
mountStream()
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
index a227d11f25a..368de696607 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
@@ -1,5 +1,14 @@
+import { pendingClarifyToolPayload } from '@/app/session/hooks/use-session-actions/restore-pending-clarify'
import { translateNow } from '@/i18n'
-import { normalizeChoices, normalizeQuestions, setClarifyRequest, warnDroppedChoices } from '@/store/clarify'
+import { restorePendingClarifyToolCall, settlePendingClarifyToolCall } from '@/lib/chat-messages'
+import {
+ $clarifyRequests,
+ clearClarifyRequest,
+ normalizeChoices,
+ normalizeQuestions,
+ setClarifyRequest,
+ warnDroppedChoices
+} from '@/store/clarify'
import { $gateway } from '@/store/gateway'
import { setMcpSetupRequest } from '@/store/mcp-setup'
import { dispatchNativeNotification } from '@/store/native-notifications'
@@ -13,7 +22,7 @@ import type { GatewayEventContext } from './types'
* each of these must be parked per-session and surfaced. */
export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
const { deps, event, payload, sessionId, occurredAt } = ctx
- const { activeSessionIdRef, updateSessionState, upsertToolCall } = deps
+ const { activeSessionIdRef, sessionInterrupted, updateSessionState, upsertToolCall } = deps
if (event.type === 'clarify.request') {
// Surface the clarify tool's overlay. The Python side is blocked on
@@ -26,6 +35,10 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
// indefinitely and re-focusing it could never recover (the event is
// gone). Parking it per-session lets the user answer once they switch
// over; the inline ClarifyTool reads the active session's entry.
+ if (sessionId && sessionInterrupted(sessionId)) {
+ return true
+ }
+
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
const question = typeof payload?.question === 'string' ? payload.question : ''
const rawChoices = payload?.choices
@@ -46,38 +59,39 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
: undefined
if (requestId && questions.length > 0) {
- setClarifyRequest({
+ const request = {
choices: null,
lockedAnswers,
multiSelect: false,
question: '',
questions,
+ receivedAt: Date.now() / 1000,
requestId,
sessionId: sessionId ?? null
- })
+ }
+
+ setClarifyRequest(request)
if (sessionId) {
- // Same hydration-race guard as the single-question path below: the
- // form mounts from the tool row, so upsert a stable one keyed by
- // the request id in case tool.start was missed.
- upsertToolCall(
- sessionId,
- {
- args: {
- questions: questions.map(q => ({
- choices: q.choices ?? undefined,
- multi_select: q.multiSelect || undefined,
- question: q.question
- }))
- },
- name: 'clarify',
- tool_id: requestId
- },
- 'running',
- event.type,
- occurredAt
- )
- updateSessionState(sessionId, state => ({ ...state, needsInput: true }))
+ // A resumed/hydrated transcript may already contain this provider's
+ // clarify call while carrying no live streamId. Re-arm that exact row
+ // instead of letting the generic stream mutator append a second card.
+ updateSessionState(sessionId, state => {
+ const projection = restorePendingClarifyToolCall(
+ state.messages,
+ pendingClarifyToolPayload(request),
+ occurredAt
+ )
+
+ return {
+ ...state,
+ messages: projection.messages,
+ streamId: projection.streamId,
+ sawAssistantPayload: true,
+ awaitingResponse: false,
+ needsInput: true
+ }
+ })
if (sessionId === activeSessionIdRef.current) {
requestScrollToBottom()
@@ -95,40 +109,37 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
warnDroppedChoices('gateway', question, rawChoices)
}
- setClarifyRequest({
+ const request = {
requestId,
question,
choices: choices.length > 0 ? choices : null,
multiSelect,
+ receivedAt: Date.now() / 1000,
sessionId: sessionId ?? null
- })
+ }
+
+ setClarifyRequest(request)
if (sessionId) {
- // `clarify.request` is the blocking event the Python side waits on,
- // while the inline UI normally mounts from the earlier `tool.start`
- // row. If that row was missed (stream reconnect / hydration race) the
- // sidebar still says "needs input" but there is nowhere to render the
- // choices. Upsert a stable pending clarify tool row from the request
- // itself so the prompt stays answerable; a real tool.start/complete
- // with the same request id merges rather than duplicates.
- upsertToolCall(
- sessionId,
- {
- args: { choices, ...(multiSelect ? { multi_select: true } : {}), question },
- name: 'clarify',
- tool_id: requestId
- },
- 'running',
- event.type,
- occurredAt
- )
+ // Same provider-shape-aware repair as the batch path above. This keeps
+ // the original hydrated row and provider tool id, while still seeding
+ // a row when tool.start was genuinely missed.
+ updateSessionState(sessionId, state => {
+ const projection = restorePendingClarifyToolCall(
+ state.messages,
+ pendingClarifyToolPayload(request),
+ occurredAt
+ )
- // The transcript only renders the active session, so a background
- // clarify is otherwise invisible (the row just keeps spinning like
- // it's working). Flag the session so the sidebar shows a persistent
- // "needs input" indicator on its row — works for the active session
- // too, and survives alt-tab / window blur (unlike a toast).
- updateSessionState(sessionId, state => ({ ...state, needsInput: true }))
+ return {
+ ...state,
+ messages: projection.messages,
+ streamId: projection.streamId,
+ sawAssistantPayload: true,
+ awaitingResponse: false,
+ needsInput: true
+ }
+ })
if (sessionId === activeSessionIdRef.current) {
requestScrollToBottom()
@@ -146,6 +157,40 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
return true
}
+ if (event.type === 'clarify.expire') {
+ if (!sessionId) {
+ return true
+ }
+
+ const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
+ const request = $clarifyRequests.get()[sessionId]
+
+ // Expiry is request-correlated: a delayed event from an older prompt must
+ // not erase a newer clarify raised by the same session.
+ if (!requestId || !request || request.requestId !== requestId) {
+ return true
+ }
+
+ clearClarifyRequest(requestId, sessionId)
+ updateSessionState(sessionId, state => {
+ const projection = settlePendingClarifyToolCall(
+ state.messages,
+ pendingClarifyToolPayload(request),
+ state.busy,
+ occurredAt
+ )
+
+ return {
+ ...state,
+ messages: projection.messages,
+ needsInput: false,
+ streamId: state.busy ? (projection.streamId ?? state.streamId) : null
+ }
+ })
+
+ return true
+ }
+
if (event.type === 'mcp.setup.request') {
// setup_mcp tool (desktop GUI): the agent proposed an MCP server and
// the Python side is blocked on mcp.setup.respond. Park the request
diff --git a/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx b/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx
index 638a7b7913e..9b5d763822c 100644
--- a/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx
@@ -543,7 +543,7 @@ function liveBatchProps(): ToolCallMessagePartProps {
}
}
-function renderLiveBatch(lockedAnswers?: Record<string, string>) {
+function renderLiveBatch(lockedAnswers?: Record<string, string>, multiSelect = false) {
const request = vi.fn().mockResolvedValue({ ok: true, remaining: [] })
$activeSessionId.set('session-1')
@@ -554,7 +554,7 @@ function renderLiveBatch(lockedAnswers?: Record<string, string>) {
multiSelect: false,
question: '',
questions: [
- { choices: ['red', 'blue'], multiSelect: false, qid: 'q0', question: 'Color?' },
+ { choices: ['red', 'blue'], multiSelect, qid: 'q0', question: 'Color?' },
{ choices: null, multiSelect: false, qid: 'q1', question: 'Name?' }
],
requestId: 'request-batch',
@@ -664,6 +664,14 @@ describe('ClarifyTool batch card', () => {
expect(screen.getByText('1 of 2 answered')).toBeTruthy()
})
+ it('reselects every choice from a replayed multi-select JSON answer', () => {
+ renderLiveBatch({ q0: '["red","blue"]' }, true)
+
+ expect(screen.getByRole('button', { name: /red/ }).getAttribute('aria-pressed')).toBe('true')
+ expect(screen.getByRole('button', { name: /blue/ }).getAttribute('aria-pressed')).toBe('true')
+ expect(screen.getByText('1 of 2 answered')).toBeTruthy()
+ })
+
it('Skip cancels the whole batch without a question_id', async () => {
const request = renderLiveBatch()
diff --git a/apps/desktop/src/components/assistant-ui/clarify-tool.tsx b/apps/desktop/src/components/assistant-ui/clarify-tool.tsx
index 295abce16b8..cb362333049 100644
--- a/apps/desktop/src/components/assistant-ui/clarify-tool.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify-tool.tsx
@@ -958,8 +958,24 @@ function ClarifyToolBatchPending({
continue
}
- const asChoice = (question.choices ?? []).find(choice => bareChoice(choice) === answer)
- next[question.qid] = asChoice ? { choices: [asChoice], draft: '' } : { choices: [], draft: answer }
+ const options = question.choices ?? []
+ let replayedAnswers = [answer]
+
+ if (question.multiSelect) {
+ try {
+ const parsed = JSON.parse(answer)
+
+ if (Array.isArray(parsed) && parsed.every(value => typeof value === 'string')) {
+ replayedAnswers = parsed
+ }
+ } catch {
+ // Older/non-JSON replies remain a one-value replay below.
+ }
+ }
+
+ const matchedChoices = options.filter(choice => replayedAnswers.includes(bareChoice(choice)))
+ next[question.qid] =
+ matchedChoices.length > 0 ? { choices: matchedChoices, draft: '' } : { choices: [], draft: answer }
}
return next
diff --git a/apps/desktop/src/lib/chat-messages.test.ts b/apps/desktop/src/lib/chat-messages.test.ts
index 69ad6604ceb..65d8182ee13 100644
--- a/apps/desktop/src/lib/chat-messages.test.ts
+++ b/apps/desktop/src/lib/chat-messages.test.ts
@@ -14,6 +14,7 @@ import {
reasoningPart,
renderMediaTags,
sealOpenToolParts,
+ stripPendingClarifyProjectionForCache,
toChatMessages,
upsertToolPart,
withUniqueToolCallIdsWithinMessage
@@ -1333,6 +1334,40 @@ describe('collectUnspokenTurnSpeech', () => {
})
})
+describe('stripPendingClarifyProjectionForCache', () => {
+ const clarifyPart = (toolCallId: string): ChatMessagePart => ({
+ type: 'tool-call',
+ toolCallId,
+ toolName: 'clarify',
+ args: { choices: ['a'], question: 'Pick' },
+ argsText: '{"question":"Pick","choices":["a"]}'
+ })
+
+ it('drops a synthetic request-id-only clarify row from the durable cache', () => {
+ const messages: ChatMessage[] = [
+ { id: 'user', role: 'user', parts: [{ type: 'text', text: 'choose' }] },
+ { id: 'synthetic', role: 'assistant', parts: [clarifyPart('req-1')], pending: true }
+ ]
+
+ expect(stripPendingClarifyProjectionForCache(messages, 'req-1')).toEqual([messages[0]])
+ })
+
+ it('keeps a provider-authored clarify in position but strips its local running bit', () => {
+ const messages: ChatMessage[] = [
+ {
+ id: 'provider',
+ role: 'assistant',
+ parts: [{ type: 'text', text: 'Choose.' }, clarifyPart('call-provider')],
+ pending: true
+ }
+ ]
+
+ const [cached] = stripPendingClarifyProjectionForCache(messages, 'req-1')
+ expect(cached.pending).toBe(false)
+ expect(cached.parts.map(part => part.type)).toEqual(['text', 'tool-call'])
+ })
+})
+
describe('sealOpenToolParts', () => {
const toolPart = (over: Partial<ChatMessagePart> = {}): ChatMessagePart =>
({
diff --git a/apps/desktop/src/lib/chat-messages/index.ts b/apps/desktop/src/lib/chat-messages/index.ts
index d69c676a7d5..0166e5769ee 100644
--- a/apps/desktop/src/lib/chat-messages/index.ts
+++ b/apps/desktop/src/lib/chat-messages/index.ts
@@ -14,5 +14,13 @@ export {
} from './parts'
export type { UnspokenTurnSpeech } from './parts'
export { branchGroupForUser, preserveLocalAssistantErrors } from './reconciliation'
-export { sealOpenToolParts, upsertToolPart, withUniqueToolCallIdsWithinMessage } from './tool-parts'
+export {
+ restorePendingClarifyToolCall,
+ sealOpenToolParts,
+ settlePendingClarifyToolCall,
+ stripPendingClarifyProjectionForCache,
+ upsertToolPart,
+ withUniqueToolCallIdsWithinMessage
+} from './tool-parts'
+export type { PendingClarifyProjection, SettledClarifyProjection } from './tool-parts'
export type { ChatMessage, ChatMessagePart, GatewayEventPayload, TimelinePartMetadata } from './types'
diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.ts
index 835a0eda7e9..de523aaa0ae 100644
--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts
+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts
@@ -333,6 +333,221 @@ export function upsertToolPart(
return next
}
+export interface PendingClarifyProjection {
+ messages: ChatMessage[]
+ streamId: string
+}
+
+export interface SettledClarifyProjection {
+ messages: ChatMessage[]
+ streamId: string | null
+}
+
+interface PendingClarifyLocation {
+ messageIndex: number
+ partIndex: number
+}
+
+function findPendingClarifyLocation(
+ messages: ChatMessage[],
+ payload: GatewayEventPayload
+): PendingClarifyLocation | null {
+ const stableId = toolId(payload)
+ const matchValues = toolPayloadMatchValues(payload)
+ let solePending: PendingClarifyLocation | null = null
+ let pendingCount = 0
+
+ for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
+ const message = messages[messageIndex]
+
+ for (let partIndex = message.parts.length - 1; partIndex >= 0; partIndex -= 1) {
+ const part = message.parts[partIndex]
+
+ if (part.type !== 'tool-call' || part.toolName !== 'clarify' || part.result !== undefined) {
+ continue
+ }
+
+ pendingCount += 1
+ solePending = { messageIndex, partIndex }
+
+ const exactId = Boolean(stableId && part.toolCallId === stableId)
+ const contextual = hasToolMatchOverlap(matchValues, toolPartMatchValues(part))
+
+ if (exactId || contextual) {
+ return { messageIndex, partIndex }
+ }
+ }
+ }
+
+ // Older/sparse projections can lose the identifying args. One session can
+ // only block on one clarify at a time, so a sole open clarify is still the
+ // authoritative row even without a usable correlation value.
+ return pendingCount === 1 ? solePending : null
+}
+
+function skippedClarifyResult(part: Extract<ChatMessagePart, { type: 'tool-call' }>): Record<string, unknown> {
+ const args = recordFromUnknown(part.args) ?? {}
+ const questions = Array.isArray(args.questions) ? args.questions : []
+
+ if (questions.length > 0) {
+ return {
+ responses: questions.map(entry => ({
+ question: firstStringField(recordFromUnknown(entry) ?? {}, ['question']),
+ user_response: ''
+ })),
+ timed_out: true
+ }
+ }
+
+ return {
+ question: firstStringField(args, ['question']),
+ user_response: ''
+ }
+}
+
+/** Mark one pending clarify as timed out/settled without ending a later phase
+ * of the same assistant turn. `keepMessageRunning` keeps the containing message
+ * open for subsequent deltas while the clarify part itself becomes settled. */
+export function settlePendingClarifyToolCall(
+ messages: ChatMessage[],
+ payload: GatewayEventPayload,
+ keepMessageRunning: boolean,
+ occurredAt = Date.now() / 1000
+): SettledClarifyProjection {
+ const clarifyPayload = { ...payload, name: 'clarify' }
+ const location = findPendingClarifyLocation(messages, clarifyPayload)
+
+ if (!location) {
+ return { messages, streamId: null }
+ }
+
+ const message = messages[location.messageIndex]
+ const part = message.parts[location.partIndex]
+
+ if (part.type !== 'tool-call') {
+ return { messages, streamId: null }
+ }
+
+ const parts = [...message.parts]
+ parts[location.partIndex] = {
+ ...part,
+ completedAt: occurredAt,
+ result: skippedClarifyResult(part)
+ }
+
+ const next = [...messages]
+ next[location.messageIndex] = { ...message, parts, pending: keepMessageRunning }
+
+ return { messages: next, streamId: message.id }
+}
+
+/** Remove ephemeral clarify liveness before writing the durable transcript-tail
+ * cache. A synthetic request-id part is dropped; a provider-authored call stays
+ * visible but loses its local `pending` bit until an authoritative resume
+ * snapshot re-arms it. */
+export function stripPendingClarifyProjectionForCache(messages: ChatMessage[], requestId?: string): ChatMessage[] {
+ let changed = false
+ const next: ChatMessage[] = []
+
+ for (const message of messages) {
+ const hasOpenClarify = message.parts.some(
+ part => part.type === 'tool-call' && part.toolName === 'clarify' && part.result === undefined
+ )
+
+ if (!hasOpenClarify) {
+ next.push(message)
+
+ continue
+ }
+
+ const parts = message.parts.filter(
+ part =>
+ !(
+ requestId &&
+ part.type === 'tool-call' &&
+ part.toolName === 'clarify' &&
+ part.result === undefined &&
+ part.toolCallId === requestId
+ )
+ )
+
+ changed = true
+
+ if (parts.length > 0) {
+ next.push({ ...message, parts, pending: false })
+ }
+ }
+
+ return changed ? next : messages
+}
+
+/**
+ * Re-arm a clarify request against a transcript that may already have been
+ * hydrated from REST/session.resume.
+ *
+ * Provider transcript shapes differ: Codex commonly persists a tool-only
+ * assistant row, while DeepSeek can persist visible assistant text and the
+ * clarify call on the same row. The clarify request id is distinct from the
+ * provider's tool-call id and can arrive when `state.streamId` is null, so the
+ * generic live-stream mutator would append a second assistant row at the tail.
+ * Match the existing open clarify by its question(s), keep that row's provider
+ * tool id/position, and mark it running. If the backend projection omitted the
+ * tool call, attach it to trailing assistant commentary or seed one tail row as
+ * a last resort.
+ */
+export function restorePendingClarifyToolCall(
+ messages: ChatMessage[],
+ payload: GatewayEventPayload,
+ occurredAt = Date.now() / 1000
+): PendingClarifyProjection {
+ const clarifyPayload = { ...payload, name: 'clarify' }
+ const location = findPendingClarifyLocation(messages, clarifyPayload)
+
+ if (location) {
+ const message = messages[location.messageIndex]
+
+ if (message.pending) {
+ return { messages, streamId: message.id }
+ }
+
+ const next = [...messages]
+ next[location.messageIndex] = { ...message, pending: true }
+
+ return { messages: next, streamId: message.id }
+ }
+
+ const parts = upsertToolPart([], clarifyPayload, 'running', occurredAt)
+ const tailIndex = messages.findLastIndex(message => !message.hidden)
+ const tail = messages[tailIndex]
+
+ if (tail?.role === 'assistant') {
+ const next = [...messages]
+ next[tailIndex] = {
+ ...tail,
+ parts: [...completeOpenStreamParts(tail.parts, occurredAt), ...parts],
+ pending: true
+ }
+
+ return { messages: next, streamId: tail.id }
+ }
+
+ const streamId = nextLiveToolId('clarify-message')
+
+ return {
+ messages: [
+ ...messages,
+ {
+ id: streamId,
+ role: 'assistant',
+ parts,
+ pending: true,
+ timestamp: occurredAt
+ }
+ ],
+ streamId
+ }
+}
+
/**
* Turn-settle reconciliation: close every tool-call part that never received
* its completion event. A `tool.complete` lost to a degraded websocket
diff --git a/apps/desktop/src/store/clarify.ts b/apps/desktop/src/store/clarify.ts
index e318dc2a915..485691eb896 100644
--- a/apps/desktop/src/store/clarify.ts
+++ b/apps/desktop/src/store/clarify.ts
@@ -16,6 +16,8 @@ export interface ClarifyRequest {
question: string
choices: string[] | null
multiSelect: boolean
+ /** Local receipt time (Unix seconds), used to reject stale resume cleanup. */
+ receivedAt?: number
sessionId: string | null
/** Batch (multi-question) clarify: present instead of question/choices. */
questions?: ClarifyQuestion[]
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index 0c8b6bbb4a5..f00bdd09cc8 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -666,9 +666,11 @@ export interface SessionResumeResponse {
// class as pending_approval: emitted-while-detached prompts are restored
// from the resume snapshot instead of being lost until server-side timeout.
pending_clarify?: {
+ answers?: Record<string, unknown>
choices?: null | string[]
multi_select?: boolean
question?: string
+ questions?: unknown
request_id?: string
}
info?: SessionRuntimeInfo