Skip to content

The agent that grows with you

fix(desktop): restore pending_clarify snapshots on activate and resume

Brooklyn Nicholson53c469300443
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
index aafafcad026..34c6c694af9 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
@@ -16,6 +16,7 @@ import {
type SessionResumeResponse
} from '@/hermes'
import { createClientSessionState } from '@/lib/chat-runtime'
+import { $clarifyRequests, clearClarifyRequest, setClarifyRequest } from '@/store/clarify'
import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'
import { requestGatewayForAgent } from '@/store/gateway'
import { $activeGatewayProfile, $newChatProfile, $newChatRoute, ensureGatewayProfile } from '@/store/profile'
@@ -811,6 +812,7 @@ describe('resumeSession failure recovery', () => {
setResumeFailedSessionId(null)
setMessages([])
setSessions([])
+ clearClarifyRequest()
vi.restoreAllMocks()
})
@@ -827,6 +829,130 @@ describe('resumeSession failure recovery', () => {
await resume!('stored-1', true)
}
+ it.each([
+ ['Codex tool-only', ''],
+ ['DeepSeek text-plus-tool', 'I found two paths; choose one.']
+ ])('restores a pending clarify as a running inline card for a %s transcript', async (_shape, content) => {
+ const stateMapRef: MutableRefObject<Map<string, ClientSessionState>> = { current: new Map() }
+
+ const toolCall = {
+ function: { arguments: '{"question":"Which path?","choices":["safe","fast"]}', name: 'clarify' },
+ id: 'call-provider'
+ }
+
+ setSessions([storedSession({ id: 'stored-1', message_count: 2 })])
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({
+ messages: [
+ { content: 'help me choose', role: 'user', timestamp: 1 },
+ { content, role: 'assistant', timestamp: 2, tool_calls: [toolCall] }
+ ],
+ session_id: 'stored-1'
+ } as never)
+
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'session.resume') {
+ return {
+ info: {},
+ message_count: 2,
+ messages: [],
+ messages_omitted: true,
+ pending_clarify: {
+ choices: ['safe', 'fast'],
+ question: 'Which path?',
+ request_id: 'req-resumed'
+ },
+ resumed: 'stored-1',
+ running: true,
+ session_id: 'runtime-1',
+ session_key: 'stored-1'
+ } as never
+ }
+
+ return {} as never
+ })
+
+ await runResume(requestGateway, { sessionStateByRuntimeIdRef: stateMapRef })
+
+ const state = stateMapRef.current.get('runtime-1')
+
+ const clarifyMessages =
+ state?.messages.filter(message =>
+ message.parts.some(part => part.type === 'tool-call' && part.toolName === 'clarify')
+ ) ?? []
+
+ expect(clarifyMessages).toHaveLength(1)
+ expect(clarifyMessages[0].pending).toBe(true)
+ expect(state?.streamId).toBe(clarifyMessages[0].id)
+ expect($clarifyRequests.get()['runtime-1']).toMatchObject({ requestId: 'req-resumed', question: 'Which path?' })
+ })
+
+ it('restores a pending batch clarify whose resume snapshot has no top-level question', async () => {
+ const stateMapRef: MutableRefObject<Map<string, ClientSessionState>> = { current: new Map() }
+
+ setSessions([storedSession({ id: 'stored-1', message_count: 2 })])
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({
+ messages: [
+ { content: 'help me choose', role: 'user', timestamp: 1 },
+ {
+ content: '',
+ role: 'assistant',
+ timestamp: 2,
+ tool_calls: [
+ {
+ function: {
+ arguments: '{"questions":[{"question":"Color?"},{"question":"Size?"}]}',
+ name: 'clarify'
+ },
+ id: 'call-batch-provider'
+ }
+ ]
+ }
+ ],
+ session_id: 'stored-1'
+ } as never)
+
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'session.resume') {
+ return {
+ info: {},
+ message_count: 2,
+ messages: [],
+ messages_omitted: true,
+ pending_clarify: {
+ answers: { q0: 'Blue' },
+ questions: [
+ { choices: ['Blue', 'Red'], qid: 'q0', question: 'Color?' },
+ { choices: ['Small', 'Large'], qid: 'q1', question: 'Size?' }
+ ],
+ request_id: 'req-batch-resumed'
+ },
+ resumed: 'stored-1',
+ running: true,
+ session_id: 'runtime-1',
+ session_key: 'stored-1'
+ } as never
+ }
+
+ return {} as never
+ })
+
+ await runResume(requestGateway, { sessionStateByRuntimeIdRef: stateMapRef })
+
+ const state = stateMapRef.current.get('runtime-1')
+ const request = $clarifyRequests.get()['runtime-1']
+ expect(request).toMatchObject({
+ lockedAnswers: { q0: 'Blue' },
+ question: '',
+ requestId: 'req-batch-resumed'
+ })
+ expect(request.questions).toHaveLength(2)
+ expect(
+ state?.messages.flatMap(message => message.parts).filter(part => part.type === 'tool-call' && part.toolName === 'clarify')
+ ).toHaveLength(1)
+ expect(state?.messages.filter(message => message.pending)).toHaveLength(1)
+ expect(state?.streamId).toBe(state?.messages.find(message => message.pending)?.id)
+ })
+
it('arms $resumeFailedSessionId when resume RPC and REST fallback both fail', async () => {
// session.resume rejects (e.g. timeout against a wedged backend)...
const requestGateway = vi.fn(async (method: string) => {
@@ -1863,6 +1989,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
.mockReset()
.mockResolvedValue({ messages: [] } as never)
vi.mocked(requestGatewayForAgent).mockReset()
+ clearClarifyRequest()
vi.restoreAllMocks()
})
@@ -2126,6 +2253,265 @@ describe('resumeSession warm-cache mapping integrity', () => {
expect(runtimeIdByStoredSessionIdRef.current.get('stored-A')).toBe('rt-A')
})
+ it('re-arms a pending clarify in place on the warm session.activate path', async () => {
+ const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {
+ current: new Map([['stored-A', 'rt-A']])
+ }
+
+ const state = clientState('stored-A')
+ state.messages = [
+ { id: 'cached-user', role: 'user', parts: [{ type: 'text', text: 'help me choose' }] },
+ {
+ id: 'cached-assistant',
+ role: 'assistant',
+ parts: [
+ { type: 'text', text: 'I found two paths.' },
+ {
+ type: 'tool-call',
+ toolCallId: 'call-provider',
+ toolName: 'clarify',
+ args: { choices: ['safe', 'fast'], question: 'Which path?' },
+ argsText: '{"question":"Which path?","choices":["safe","fast"]}'
+ }
+ ]
+ }
+ ]
+
+ const sessionStateByRuntimeIdRef: MutableRefObject<Map<string, ClientSessionState>> = {
+ current: new Map([['rt-A', state]])
+ }
+
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({
+ messages: [
+ { content: 'help me choose', role: 'user', timestamp: 1 },
+ {
+ content: 'I found two paths.',
+ role: 'assistant',
+ timestamp: 2,
+ tool_calls: [
+ {
+ function: {
+ arguments: '{"question":"Which path?","choices":["safe","fast"]}',
+ name: 'clarify'
+ },
+ id: 'call-provider'
+ }
+ ]
+ }
+ ],
+ session_id: 'stored-A'
+ } as never)
+
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'session.activate') {
+ return {
+ info: {},
+ message_count: 2,
+ messages: [],
+ messages_omitted: true,
+ pending_clarify: {
+ choices: ['safe', 'fast'],
+ question: 'Which path?',
+ request_id: 'req-warm'
+ },
+ resumed: 'stored-A',
+ running: true,
+ session_id: 'rt-A',
+ session_key: 'stored-A'
+ } as never
+ }
+
+ return {} as never
+ })
+
+ let resume: ((storedSessionId: string, replaceRoute?: boolean) => Promise<unknown>) | null = null
+ render(
+ <ResumeHarness
+ onReady={ready => (resume = ready)}
+ requestGateway={requestGateway}
+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}
+ sessionStateByRuntimeIdRef={sessionStateByRuntimeIdRef}
+ />
+ )
+ await waitFor(() => expect(resume).not.toBeNull())
+ await resume!('stored-A', true)
+
+ const resumedState = sessionStateByRuntimeIdRef.current.get('rt-A')
+
+ const clarifyMessages =
+ resumedState?.messages.filter(message =>
+ message.parts.some(part => part.type === 'tool-call' && part.toolName === 'clarify')
+ ) ?? []
+
+ expect(requestGateway.mock.calls.map(([method]) => method)).toContain('session.activate')
+ expect(clarifyMessages).toHaveLength(1)
+ expect(clarifyMessages[0].pending).toBe(true)
+ expect(
+ clarifyMessages[0].parts.find(part => part.type === 'tool-call' && part.toolName === 'clarify')
+ ).toMatchObject({ toolCallId: 'call-provider' })
+ expect(resumedState?.streamId).toBe(clarifyMessages[0].id)
+ expect($clarifyRequests.get()['rt-A']).toMatchObject({ requestId: 'req-warm' })
+ })
+
+ it.each([
+ ['with a stale request-store entry', true],
+ ['after the request store was already cleared', false]
+ ])('de-arms stale clarify state %s when session.activate reports no pending request', async (_case, keepStore) => {
+ const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {
+ current: new Map([['stored-A', 'rt-A']])
+ }
+
+ const state = clientState('stored-A')
+ state.busy = true
+ state.needsInput = true
+ state.streamId = 'cached-assistant'
+ state.messages = [
+ { id: 'cached-user', role: 'user', parts: [{ type: 'text', text: 'help me choose' }] },
+ {
+ id: 'cached-assistant',
+ role: 'assistant',
+ pending: true,
+ parts: [
+ {
+ type: 'tool-call',
+ toolCallId: 'call-provider',
+ toolName: 'clarify',
+ args: { choices: ['safe', 'fast'], question: 'Which path?' },
+ argsText: '{"question":"Which path?","choices":["safe","fast"]}'
+ }
+ ]
+ }
+ ]
+
+ const sessionStateByRuntimeIdRef: MutableRefObject<Map<string, ClientSessionState>> = {
+ current: new Map([['rt-A', state]])
+ }
+
+ if (keepStore) {
+ setClarifyRequest({
+ choices: ['safe', 'fast'],
+ multiSelect: false,
+ question: 'Which path?',
+ requestId: 'req-stale',
+ sessionId: 'rt-A'
+ })
+ }
+
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({
+ messages: [
+ { content: 'help me choose', role: 'user', timestamp: 1 },
+ {
+ content: '',
+ role: 'assistant',
+ timestamp: 2,
+ tool_calls: [
+ {
+ function: {
+ arguments: '{"question":"Which path?","choices":["safe","fast"]}',
+ name: 'clarify'
+ },
+ id: 'call-provider'
+ }
+ ]
+ }
+ ],
+ session_id: 'stored-A'
+ } as never)
+
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'session.activate') {
+ return {
+ info: {},
+ message_count: 2,
+ messages: [],
+ messages_omitted: true,
+ resumed: 'stored-A',
+ running: false,
+ session_id: 'rt-A',
+ session_key: 'stored-A'
+ } as never
+ }
+
+ return {} as never
+ })
+
+ let resume: ((storedSessionId: string, replaceRoute?: boolean) => Promise<unknown>) | null = null
+ render(
+ <ResumeHarness
+ onReady={ready => (resume = ready)}
+ requestGateway={requestGateway}
+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}
+ sessionStateByRuntimeIdRef={sessionStateByRuntimeIdRef}
+ />
+ )
+ await waitFor(() => expect(resume).not.toBeNull())
+ await resume!('stored-A', true)
+
+ const resumedState = sessionStateByRuntimeIdRef.current.get('rt-A')
+
+ const clarifyPart = resumedState?.messages
+ .flatMap(message => message.parts)
+ .find(part => part.type === 'tool-call' && part.toolName === 'clarify')
+
+ expect($clarifyRequests.get()['rt-A']).toBeUndefined()
+ expect(resumedState).toMatchObject({ needsInput: false, streamId: null })
+ expect(resumedState?.messages.find(message => message.id === resumedState.streamId)).toBeUndefined()
+ expect(clarifyPart).toHaveProperty('result')
+ })
+
+ it('does not let an older activate response clear a newer clarify request', async () => {
+ const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {
+ current: new Map([['stored-A', 'rt-A']])
+ }
+
+ const sessionStateByRuntimeIdRef: MutableRefObject<Map<string, ClientSessionState>> = {
+ current: new Map([['rt-A', clientState('stored-A')]])
+ }
+
+ const activated = deferred<SessionResumeResponse>()
+
+ const requestGateway = vi.fn((method: string) =>
+ method === 'session.activate' ? activated.promise : Promise.resolve({})
+ )
+
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({ messages: [], session_id: 'stored-A' } as never)
+
+ let resume: ((storedSessionId: string, replaceRoute?: boolean) => Promise<unknown>) | null = null
+ render(
+ <ResumeHarness
+ onReady={ready => (resume = ready)}
+ requestGateway={requestGateway as never}
+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}
+ sessionStateByRuntimeIdRef={sessionStateByRuntimeIdRef}
+ />
+ )
+ await waitFor(() => expect(resume).not.toBeNull())
+ const resumePromise = resume!('stored-A', true)
+ await waitFor(() => expect(requestGateway).toHaveBeenCalledWith('session.activate', expect.anything()))
+
+ setClarifyRequest({
+ choices: ['new'],
+ multiSelect: false,
+ question: 'New question?',
+ receivedAt: Date.now() / 1000 + 60,
+ requestId: 'req-newer',
+ sessionId: 'rt-A'
+ })
+ activated.resolve({
+ info: {},
+ message_count: 0,
+ messages: [],
+ messages_omitted: true,
+ resumed: 'stored-A',
+ running: false,
+ session_id: 'rt-A',
+ session_key: 'stored-A'
+ })
+ await resumePromise
+
+ expect($clarifyRequests.get()['rt-A']).toMatchObject({ requestId: 'req-newer' })
+ })
+
it('preserves cached image attachments through an idle persisted transcript refresh', async () => {
const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {
current: new Map([['stored-A', 'rt-A']])
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index 95708f282a7..d210ef1f165 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -8,11 +8,18 @@ import { revealTreePane } from '@/components/pane-shell/tree/store'
import { setWorkspaceScope } from '@/components/pane-shell/workspace-scope'
import { deleteSession, getAllSessionMessages, getLatestSessionMessages, setSessionArchived } from '@/hermes'
import { useI18n } from '@/i18n'
-import { type ChatMessage, preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'
+import {
+ type ChatMessage,
+ preserveLocalAssistantErrors,
+ restorePendingClarifyToolCall,
+ settlePendingClarifyToolCall,
+ stripPendingClarifyProjectionForCache,
+ toChatMessages
+} from '@/lib/chat-messages'
import { isMissingRpcMethod } from '@/lib/gateway-rpc'
import { recoverInFlightTurnJournal } from '@/lib/inflight-turn-journal'
import { setSessionYolo } from '@/lib/yolo-session'
-import { normalizeChoices, setClarifyRequest } from '@/store/clarify'
+import { $clarifyRequests } from '@/store/clarify'
import { migrateSessionDraft } from '@/store/composer'
import { clearQueuedPrompts, migrateQueuedPrompts } from '@/store/composer-queue'
import { openGatewayForAgent, openGatewayForProfile, requestGatewayForAgent } from '@/store/gateway'
@@ -102,7 +109,7 @@ import { navigateToWorkspacePage, NEW_CHAT_ROUTE, sessionRoute, SETTINGS_ROUTE }
import type { ClientSessionState, SidebarNavItem } from '../../../types'
import { sessionContextDrift } from '../session-context-drift'
import { singleFlightSessionResume } from '../use-prompt-actions/single-flight-resume'
-
+import { pendingClarifyToolPayload, restorePendingClarifyFromSnapshot } from './restore-pending-clarify'
import {
appendLiveSessionProjection,
applyRuntimeInfo,
@@ -265,29 +272,6 @@ function restorePendingApproval(response: SessionResumeResponse, sessionId: stri
return true
}
-function restorePendingClarify(response: SessionResumeResponse, sessionId: string): boolean {
- // Same replay class as pending_approval: the clarify.request event was
- // emitted while this client's transport was detached, so without the resume
- // snapshot the question stays invisible until it times out server-side.
- const pending = response.pending_clarify
-
- if (!pending || typeof pending.request_id !== 'string' || typeof pending.question !== 'string') {
- return false
- }
-
- const choices = normalizeChoices(pending.choices)
-
- setClarifyRequest({
- choices: choices.length > 0 ? choices : null,
- multiSelect: pending.multi_select === true,
- question: pending.question,
- requestId: pending.request_id,
- sessionId
- })
-
- return true
-}
-
function normalizeNewChatWorkspaceTarget(target: NewChatWorkspaceTarget): NewChatWorkspaceTarget {
return typeof target === 'string' ? target.trim() || null : target
}
@@ -932,6 +916,9 @@ export function useSessionActions({
try {
let activated: SessionResumeResponse | null = null
+ const activateStartedAt = Date.now() / 1000
+ const activateBaselineState = sessionStateByRuntimeIdRef.current.get(cachedRuntimeId) ?? cachedViewState
+ const clarifyRequestIdAtActivateStart = $clarifyRequests.get()[cachedRuntimeId]?.requestId
try {
activated = await requestForSession<SessionResumeResponse>('session.activate', {
@@ -970,7 +957,23 @@ export function useSessionActions({
dropSessionState(cachedRuntimeId)
} else {
const pendingApproval = restorePendingApproval(activated, cachedRuntimeId)
- const pendingClarify = restorePendingClarify(activated, cachedRuntimeId)
+
+ const pendingClarifyState = restorePendingClarifyFromSnapshot(
+ activated,
+ cachedRuntimeId,
+ activateStartedAt,
+ clarifyRequestIdAtActivateStart
+ )
+
+ const pendingClarify = pendingClarifyState.request
+
+ const clarifyAuthoritativelyAbsent =
+ pendingClarifyState.authoritativeAbsent && !$clarifyRequests.get()[cachedRuntimeId]
+
+ const staleClarifyAtActivateStart = clarifyAuthoritativelyAbsent
+ ? Boolean(settlePendingClarifyToolCall(cachedViewState.messages, {}, false).streamId)
+ : false
+
const runtimeInfo = applyRuntimeInfo(activated.info)
// `omit_messages` means the response carries NO transcript, not
@@ -990,11 +993,21 @@ export function useSessionActions({
// #70449: never let the activate snapshot's stale running:false
// rewind a turn that started while the RPC was in flight — read
// the freshest cache entry, not the pre-await cachedViewState.
- const running = resolveResumedBusy(
- activated.running ?? cachedViewState.busy,
- Boolean(sessionStateByRuntimeIdRef.current.get(cachedRuntimeId)?.busy)
+ const latestCachedState = sessionStateByRuntimeIdRef.current.get(cachedRuntimeId)
+
+ const busyChangedWhileActivating = Boolean(
+ latestCachedState?.busy &&
+ (latestCachedState.turnStartedAt !== activateBaselineState.turnStartedAt ||
+ (latestCachedState.turnLive && !activateBaselineState.turnLive))
)
+ const running =
+ (pendingClarifyState.cleared || staleClarifyAtActivateStart) &&
+ activated.running === false &&
+ !busyChangedWhileActivating
+ ? false
+ : resolveResumedBusy(activated.running ?? cachedViewState.busy, Boolean(latestCachedState?.busy))
+
const activatedTurnStartedAt =
typeof activated.turn_started_at === 'number' && activated.turn_started_at > 0
? activated.turn_started_at * 1000
@@ -1065,34 +1078,73 @@ export function useSessionActions({
)
}
+ const pendingClarifyProjection = pendingClarify
+ ? restorePendingClarifyToolCall(activatedMessages, pendingClarifyToolPayload(pendingClarify))
+ : null
+
+ const clearedClarifyProjection = clarifyAuthoritativelyAbsent
+ ? settlePendingClarifyToolCall(
+ activatedMessages,
+ pendingClarifyState.cleared ? pendingClarifyToolPayload(pendingClarifyState.cleared) : {},
+ running
+ )
+ : null
+
+ const visibleActivatedMessages =
+ pendingClarifyProjection?.messages ?? clearedClarifyProjection?.messages ?? activatedMessages
+
const activatedState = updateSessionState(
cachedRuntimeId,
state => ({
...state,
...(runtimeInfo ?? {}),
- messages: activatedMessages,
+ messages: visibleActivatedMessages,
busy: running,
awaitingResponse: running,
// Resumed onto an already-running turn — that IS backend
// proof the turn is live (no message.start will replay).
turnLive: state.turnLive || running,
- needsInput: pendingApproval || pendingClarify || state.needsInput,
+ needsInput:
+ pendingApproval ||
+ Boolean(pendingClarify) ||
+ (clarifyAuthoritativelyAbsent ? false : state.needsInput),
// Adopting someone else's turn: we'll stream its reply
// without ever having received its prompt, so the settle
// path must not take the "I saw it all" shortcut.
adoptedRunningTurn: state.adoptedRunningTurn || running,
- turnStartedAt: running ? (activatedTurnStartedAt ?? state.turnStartedAt ?? Date.now()) : null
+ turnStartedAt: running ? (activatedTurnStartedAt ?? state.turnStartedAt ?? Date.now()) : null,
+ ...(pendingClarifyProjection
+ ? {
+ awaitingResponse: false,
+ sawAssistantPayload: true,
+ streamId: pendingClarifyProjection.streamId
+ }
+ : {}),
+ ...(clearedClarifyProjection
+ ? {
+ streamId: running ? (clearedClarifyProjection.streamId ?? state.streamId) : null
+ }
+ : {})
}),
storedSessionId
)
busyRef.current = running
setBusy(running)
- setAwaitingResponse(running)
+ setAwaitingResponse(running && !pendingClarify)
syncSessionStateToView(cachedRuntimeId, activatedState)
- // Durable tail refresh — same post-reconcile contract as the
- // cold path's save below.
- saveTranscriptTail(storedSessionId, activatedState.messages)
+ // Cache backend transcript truth only. The pending/running bit and
+ // any synthetic clarify row are a live resume projection and must
+ // not survive after the server-side request expires.
+ saveTranscriptTail(
+ storedSessionId,
+ stripPendingClarifyProjectionForCache(
+ activatedMessages,
+ pendingClarify?.requestId ??
+ pendingClarifyState.cleared?.requestId ??
+ $clarifyRequests.get()[cachedRuntimeId]?.requestId
+ )
+ )
return
}
@@ -1207,6 +1259,7 @@ export function useSessionActions({
const prefetchPromise = watchWindow ? null : getLatestSessionMessages(storedSessionId, sessionRestScope)
let resumeRuntimeBaselineMessages: ChatMessage[] = []
+ const resumeStartedAt = Date.now() / 1000
const resumePromise = singleFlightSessionResume(storedSessionId, () =>
requestForSession<SessionResumeResponse>('session.resume', {
@@ -1396,7 +1449,12 @@ export function useSessionActions({
setActiveSessionId(resumed.session_id)
activeSessionIdRef.current = resumed.session_id
const pendingApproval = restorePendingApproval(resumed, resumed.session_id)
- const pendingClarify = restorePendingClarify(resumed, resumed.session_id)
+ const pendingClarifyState = restorePendingClarifyFromSnapshot(resumed, resumed.session_id, resumeStartedAt)
+ const pendingClarify = pendingClarifyState.request
+
+ const clarifyAuthoritativelyAbsent =
+ pendingClarifyState.authoritativeAbsent && !$clarifyRequests.get()[resumed.session_id]
+
const runtimeInfo = applyRuntimeInfo(resumed.info)
patchSessionWorkspace(storedSessionId, runtimeInfo?.cwd)
@@ -1409,17 +1467,33 @@ export function useSessionActions({
? resumed.turn_started_at * 1000
: null
+ const pendingClarifyProjection = pendingClarify
+ ? restorePendingClarifyToolCall(messagesForView, pendingClarifyToolPayload(pendingClarify))
+ : null
+
+ const clearedClarifyProjection = clarifyAuthoritativelyAbsent
+ ? settlePendingClarifyToolCall(
+ messagesForView,
+ pendingClarifyState.cleared ? pendingClarifyToolPayload(pendingClarifyState.cleared) : {},
+ resumedRunning
+ )
+ : null
+
+ const visibleMessagesForView =
+ pendingClarifyProjection?.messages ?? clearedClarifyProjection?.messages ?? messagesForView
+
updateSessionState(
resumed.session_id,
state => ({
...state,
...(runtimeInfo ?? {}),
- messages: messagesForView,
+ messages: visibleMessagesForView,
busy: resumedRunning,
awaitingResponse: resumedRunning && !recoveredInFlightTail,
// Backend reported this turn running at resume time — live proof.
turnLive: state.turnLive || resumedRunning,
- needsInput: pendingApproval || pendingClarify || state.needsInput,
+ needsInput:
+ pendingApproval || Boolean(pendingClarify) || (clarifyAuthoritativelyAbsent ? false : state.needsInput),
adoptedRunningTurn: state.adoptedRunningTurn || resumedRunning,
...(inFlightRecovery.applied
? {
@@ -1431,7 +1505,19 @@ export function useSessionActions({
}
: {
turnStartedAt: resumedRunning && resumedTurnStartedAt !== null ? resumedTurnStartedAt : null
- })
+ }),
+ ...(pendingClarifyProjection
+ ? {
+ awaitingResponse: false,
+ sawAssistantPayload: true,
+ streamId: pendingClarifyProjection.streamId
+ }
+ : {}),
+ ...(clearedClarifyProjection
+ ? {
+ streamId: resumedRunning ? (clearedClarifyProjection.streamId ?? state.streamId) : null
+ }
+ : {})
}),
storedSessionId
)
@@ -1440,15 +1526,21 @@ export function useSessionActions({
// Commit the final, already-reconciled transcript now so resume has one
// additive DOM build instead of an eager prefetch build plus a later
// runtime projection build.
- if (!chatMessageArraysEquivalent($messages.get(), messagesForView)) {
- setMessages(messagesForView)
+ if (!chatMessageArraysEquivalent($messages.get(), visibleMessagesForView)) {
+ setMessages(visibleMessagesForView)
}
- // Refresh the durable tail cache with the authoritative transcript so
- // the NEXT wake of this session paints instantly (fresh launch,
- // reaped backend). Post-reconcile only — never persist an optimistic
- // or in-flight-recovered projection ahead of backend truth.
- saveTranscriptTail(storedSessionId, messagesForView)
+ // Refresh the durable tail cache with backend transcript truth only;
+ // the live pending clarify projection expires with the server request.
+ saveTranscriptTail(
+ storedSessionId,
+ stripPendingClarifyProjectionForCache(
+ messagesForView,
+ pendingClarify?.requestId ??
+ pendingClarifyState.cleared?.requestId ??
+ $clarifyRequests.get()[resumed.session_id]?.requestId
+ )
+ )
} catch (err) {
if (!isCurrentResume()) {
return
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.test.ts
new file mode 100644
index 00000000000..9bafef9d767
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.test.ts
@@ -0,0 +1,184 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type * as clarifyStore from '@/store/clarify'
+
+const { setClarifyRequestMock, clearClarifyRequestMock } = vi.hoisted(() => ({
+ clearClarifyRequestMock: vi.fn(),
+ setClarifyRequestMock: vi.fn()
+}))
+
+vi.mock('@/store/clarify', async importOriginal => {
+ const actual = await importOriginal<typeof clarifyStore>()
+
+ return {
+ ...actual,
+ clearClarifyRequest: clearClarifyRequestMock,
+ setClarifyRequest: setClarifyRequestMock
+ }
+})
+
+import { $clarifyRequests } from '@/store/clarify'
+
+import { pendingClarifyToolPayload, restorePendingClarifyFromSnapshot } from './restore-pending-clarify'
+
+const resumeStartedAt = 1_700_000_000
+
+describe('restorePendingClarifyFromSnapshot', () => {
+ beforeEach(() => {
+ clearClarifyRequestMock.mockClear()
+ setClarifyRequestMock.mockClear()
+ $clarifyRequests.set({})
+ })
+
+ it('restores a batch clarify snapshot (questions, no top-level question)', () => {
+ const state = restorePendingClarifyFromSnapshot(
+ {
+ pending_clarify: {
+ request_id: 'rid1',
+ questions: [
+ { choices: ['Yes', 'No'], multi_select: false, qid: 'q0', question: 'Proceed?' },
+ { qid: 'q1', question: 'Which region?' }
+ ]
+ }
+ },
+ 'sess-1',
+ resumeStartedAt
+ )
+
+ expect(state.request).not.toBeNull()
+ expect(setClarifyRequestMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ multiSelect: false,
+ question: '',
+ requestId: 'rid1',
+ sessionId: 'sess-1',
+ questions: [
+ { choices: ['Yes', 'No'], multiSelect: false, qid: 'q0', question: 'Proceed?' },
+ { multiSelect: false, qid: 'q1', question: 'Which region?', choices: null }
+ ]
+ })
+ )
+ })
+
+ it('carries server-locked answers into the replayed batch card', () => {
+ restorePendingClarifyFromSnapshot(
+ {
+ pending_clarify: {
+ answers: { q0: 'Yes', junk: 42 },
+ request_id: 'rid2',
+ questions: [{ qid: 'q0', question: 'Proceed?' }]
+ }
+ },
+ 'sess-2',
+ resumeStartedAt
+ )
+
+ expect(setClarifyRequestMock).toHaveBeenCalledWith(
+ expect.objectContaining({ lockedAnswers: { q0: 'Yes' }, requestId: 'rid2' })
+ )
+ })
+
+ it('still restores the single-question form', () => {
+ const state = restorePendingClarifyFromSnapshot(
+ {
+ pending_clarify: {
+ choices: ['A', 'B'],
+ multi_select: true,
+ question: 'Pick one',
+ request_id: 'rid3'
+ }
+ },
+ 'sess-3',
+ resumeStartedAt
+ )
+
+ expect(state.request).not.toBeNull()
+ expect(setClarifyRequestMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ choices: ['A', 'B'],
+ multiSelect: true,
+ question: 'Pick one',
+ requestId: 'rid3'
+ })
+ )
+ })
+
+ it('rejects a payload with neither form (no request restored)', () => {
+ const state = restorePendingClarifyFromSnapshot(
+ { pending_clarify: { request_id: 'rid4' } },
+ 'sess-4',
+ resumeStartedAt
+ )
+
+ expect(state.request).toBeNull()
+ expect(setClarifyRequestMock).not.toHaveBeenCalled()
+ })
+
+ it('rejects a payload with no request id', () => {
+ const state = restorePendingClarifyFromSnapshot(
+ { pending_clarify: { question: 'Orphaned prompt' } },
+ 'sess-5',
+ resumeStartedAt
+ )
+
+ expect(state.request).toBeNull()
+ expect(state.authoritativeAbsent).toBe(true)
+ expect(setClarifyRequestMock).not.toHaveBeenCalled()
+ })
+
+ it('clears a stale local request when the snapshot has none, and leaves a newer in-flight one', () => {
+ $clarifyRequests.set({
+ 'sess-6': {
+ choices: null,
+ multiSelect: false,
+ question: 'Old',
+ receivedAt: resumeStartedAt - 10,
+ requestId: 'old-rid',
+ sessionId: 'sess-6'
+ }
+ })
+
+ const cleared = restorePendingClarifyFromSnapshot({}, 'sess-6', resumeStartedAt, 'old-rid')
+
+ expect(cleared.authoritativeAbsent).toBe(true)
+ expect(cleared.cleared?.requestId).toBe('old-rid')
+ expect(clearClarifyRequestMock).toHaveBeenCalledWith('old-rid', 'sess-6')
+
+ $clarifyRequests.set({
+ 'sess-6': {
+ choices: null,
+ multiSelect: false,
+ question: 'Newer',
+ receivedAt: resumeStartedAt + 1,
+ requestId: 'new-rid',
+ sessionId: 'sess-6'
+ }
+ })
+
+ const kept = restorePendingClarifyFromSnapshot({}, 'sess-6', resumeStartedAt, 'old-rid')
+
+ expect(kept.cleared).toBeNull()
+ expect(kept.request).toBeNull()
+ expect(clearClarifyRequestMock).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('pendingClarifyToolPayload', () => {
+ it('mirrors the batch wire shape for in-place re-arm', () => {
+ expect(
+ pendingClarifyToolPayload({
+ choices: null,
+ multiSelect: false,
+ question: '',
+ questions: [{ choices: ['Yes', 'No'], multiSelect: false, qid: 'q0', question: 'Proceed?' }],
+ requestId: 'rid',
+ sessionId: 'sess'
+ })
+ ).toEqual({
+ args: {
+ questions: [{ choices: ['Yes', 'No'], question: 'Proceed?' }]
+ },
+ tool_id: 'rid'
+ })
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.ts b/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.ts
new file mode 100644
index 00000000000..ce5570d2631
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.ts
@@ -0,0 +1,105 @@
+import type { GatewayEventPayload } from '@/lib/chat-messages'
+import {
+ $clarifyRequests,
+ type ClarifyRequest,
+ clearClarifyRequest,
+ normalizeChoices,
+ normalizeQuestions,
+ setClarifyRequest
+} from '@/store/clarify'
+import type { SessionResumeResponse } from '@/types/hermes'
+
+export interface PendingClarifyResumeState {
+ authoritativeAbsent: boolean
+ cleared: ClarifyRequest | null
+ request: ClarifyRequest | null
+}
+
+/**
+ * Restore a pending clarify from a resume/activate snapshot onto `sessionId`.
+ *
+ * The snapshot mirrors the live clarify.request wire shape: single-question
+ * payloads carry `question`/`choices`/`multi_select`; batch (multi-question)
+ * ones carry `questions` (+ any answers already locked server-side) and no
+ * top-level `question`. Multi-select locks arrive as JSON-encoded arrays
+ * inside a string — never a bare array — so `lockedAnswers` keeps string
+ * values only.
+ *
+ * A missing snapshot is authoritative only for requests that already existed
+ * when the RPC began. A newer clarify.request that arrives while the response
+ * is in flight is left alone.
+ */
+export function restorePendingClarifyFromSnapshot(
+ response: Pick<SessionResumeResponse, 'pending_clarify'>,
+ sessionId: string,
+ resumeStartedAt: number,
+ requestIdAtStart?: string
+): PendingClarifyResumeState {
+ const pending = response.pending_clarify
+
+ if (!pending || typeof pending.request_id !== 'string') {
+ const current = $clarifyRequests.get()[sessionId]
+
+ const existedAtStart = Boolean(current && requestIdAtStart && current.requestId === requestIdAtStart)
+ const definitelyOlder = Boolean(current?.receivedAt !== undefined && current.receivedAt < resumeStartedAt)
+ const legacyWithoutTime = Boolean(current && current.receivedAt === undefined && !requestIdAtStart)
+
+ if (current && (existedAtStart || definitelyOlder || legacyWithoutTime)) {
+ clearClarifyRequest(current.requestId, sessionId)
+
+ return { authoritativeAbsent: true, cleared: current, request: null }
+ }
+
+ return { authoritativeAbsent: true, cleared: null, request: null }
+ }
+
+ const questions = normalizeQuestions(pending.questions)
+ const question = typeof pending.question === 'string' ? pending.question : ''
+
+ if (!question && questions.length === 0) {
+ return { authoritativeAbsent: false, cleared: null, request: null }
+ }
+
+ const choices = normalizeChoices(pending.choices)
+
+ const lockedAnswers =
+ typeof pending.answers === 'object' && pending.answers !== null
+ ? Object.fromEntries(
+ Object.entries(pending.answers).filter((entry): entry is [string, string] => typeof entry[1] === 'string')
+ )
+ : undefined
+
+ const request: ClarifyRequest = {
+ choices: choices.length > 0 ? choices : null,
+ lockedAnswers,
+ multiSelect: pending.multi_select === true,
+ question,
+ receivedAt: Date.now() / 1000,
+ requestId: pending.request_id,
+ sessionId,
+ ...(questions.length > 0 ? { questions } : {})
+ }
+
+ setClarifyRequest(request)
+
+ return { authoritativeAbsent: false, cleared: null, request }
+}
+
+export function pendingClarifyToolPayload(request: ClarifyRequest): GatewayEventPayload {
+ return {
+ args: request.questions?.length
+ ? {
+ questions: request.questions.map(question => ({
+ choices: question.choices ?? undefined,
+ multi_select: question.multiSelect || undefined,
+ question: question.question
+ }))
+ }
+ : {
+ choices: request.choices ?? [],
+ ...(request.multiSelect ? { multi_select: true } : {}),
+ question: request.question
+ },
+ tool_id: request.requestId
+ }
+}