Skip to content

The agent that grows with you

fix(desktop): replay pending clarify prompts after reconnect

Teknium73bcfddb3de2
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
index 0ba4b2a0db6..6cee7a24693 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
@@ -324,6 +324,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
const isActiveEvent = !!sessionId && sessionId === activeSessionIdRef.current
const replaySessionId = approvalReplaySessionId(event.type, activeSessionIdRef.current, sessionId)
+
if (replaySessionId) {
void replayPendingApproval($gateway.get(), replaySessionId).catch(() => undefined)
}
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 8edd118c871..5b4aeb3ce5b 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
@@ -9,12 +9,12 @@ import { type ChatMessage, preserveLocalAssistantErrors, toChatMessages } from '
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 { migrateSessionDraft } from '@/store/composer'
import { clearQueuedPrompts, migrateQueuedPrompts } from '@/store/composer-queue'
import { $pinnedSessionIds } from '@/store/layout'
import { clearNotifications, notify, notifyError } from '@/store/notifications'
import { $activeGatewayProfile, $newChatProfile, ensureGatewayProfile, normalizeProfileKey } from '@/store/profile'
-import { setApprovalRequest } from '@/store/prompts'
import {
beginSessionMutation,
endSessionMutation,
@@ -22,6 +22,7 @@ import {
tombstoneSessions,
untombstoneSessions
} from '@/store/projects'
+import { setApprovalRequest } from '@/store/prompts'
import {
$activeSessionStoredIdRotation,
$currentCwd,
@@ -205,9 +206,34 @@ function restorePendingApproval(response: SessionResumeResponse, sessionId: stri
choices: pending.choices,
command: pending.command ?? '',
description: pending.description ?? 'dangerous command',
+ requestId: typeof pending.request_id === 'string' ? pending.request_id : undefined,
sessionId,
smartDenied: pending.smart_denied === true
})
+
+ 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
}
@@ -787,6 +813,7 @@ export function useSessionActions({
dropSessionState(cachedRuntimeId)
} else {
const pendingApproval = restorePendingApproval(activated, cachedRuntimeId)
+ const pendingClarify = restorePendingClarify(activated, cachedRuntimeId)
const runtimeInfo = applyRuntimeInfo(activated.info)
// `omit_messages` means the response carries NO transcript, not
@@ -843,7 +870,7 @@ export function useSessionActions({
messages: activatedMessages,
busy: running,
awaitingResponse: running,
- needsInput: pendingApproval || state.needsInput,
+ needsInput: pendingApproval || pendingClarify || 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.
@@ -1061,6 +1088,7 @@ 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 runtimeInfo = applyRuntimeInfo(resumed.info)
patchSessionWorkspace(storedSessionId, runtimeInfo?.cwd)
@@ -1073,7 +1101,7 @@ export function useSessionActions({
messages: messagesForView,
busy: resumedRunning,
awaitingResponse: resumedRunning && !recoveredInFlightTail,
- needsInput: pendingApproval || state.needsInput,
+ needsInput: pendingApproval || pendingClarify || state.needsInput,
adoptedRunningTurn: state.adoptedRunningTurn || resumedRunning,
...(inFlightRecovery.applied
? {
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 5213b8b4a4f..a0d616633cd 100644
--- a/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx
@@ -377,6 +377,7 @@ describe('ClarifyTool recommended option', () => {
$gateway.set({ request } as never)
setClarifyRequest({
choices: ['staging (Recommended)', 'production'],
+ multiSelect: false,
question: 'Which deployment target?',
requestId: 'request-1',
sessionId: 'session-1'
diff --git a/apps/desktop/src/lib/gateway-events.ts b/apps/desktop/src/lib/gateway-events.ts
index 0dd2a6cc27d..c937acf50c2 100644
--- a/apps/desktop/src/lib/gateway-events.ts
+++ b/apps/desktop/src/lib/gateway-events.ts
@@ -78,9 +78,11 @@ export function approvalReplaySessionId(
if (eventType === 'gateway.ready') {
return activeSessionId
}
+
if (eventType === 'session.info') {
return routedSessionId
}
+
return null
}
diff --git a/apps/desktop/src/store/prompts.test.ts b/apps/desktop/src/store/prompts.test.ts
index 284f1ed4e5b..bbe2d2f2ca3 100644
--- a/apps/desktop/src/store/prompts.test.ts
+++ b/apps/desktop/src/store/prompts.test.ts
@@ -81,9 +81,11 @@ describe('approval prompt store', () => {
it('acknowledges an approval only after parking it', async () => {
const calls: Array<[string, Record<string, unknown>]> = []
+
const gateway = {
request: async (method: string, params: Record<string, unknown>) => {
calls.push([method, params])
+
return { acknowledged: true }
}
}
@@ -101,9 +103,11 @@ describe('approval prompt store', () => {
it('replays and acknowledges the oldest unresolved approval after reconnect', async () => {
const calls: Array<[string, Record<string, unknown>]> = []
+
const gateway = {
request: async (method: string, params: Record<string, unknown>) => {
calls.push([method, params])
+
if (method === 'approval.pending') {
return {
approvals: [
@@ -112,6 +116,7 @@ describe('approval prompt store', () => {
]
}
}
+
return { acknowledged: true }
}
}
diff --git a/apps/desktop/src/store/prompts.ts b/apps/desktop/src/store/prompts.ts
index 6e7d7bc6c92..35f95455bcb 100644
--- a/apps/desktop/src/store/prompts.ts
+++ b/apps/desktop/src/store/prompts.ts
@@ -117,6 +117,7 @@ export const clearApprovalRequest = approval.clear
export async function receiveApprovalRequest(gateway: ApprovalGateway | null, request: ApprovalRequest): Promise<void> {
setApprovalRequest(request)
+
if (gateway && request.requestId && request.sessionId) {
await gateway.request('approval.received', {
request_id: request.requestId,
@@ -129,14 +130,18 @@ export async function replayPendingApproval(gateway: ApprovalGateway | null, ses
if (!gateway || !sessionId) {
return
}
+
const rawResult = await gateway.request('approval.pending', {
session_id: sessionId
})
+
const result = rawResult && typeof rawResult === 'object' ? (rawResult as { approvals?: PendingApprovalPayload[] }) : {}
const pending = Array.isArray(result?.approvals) ? result.approvals[0] : undefined
+
if (!pending || typeof pending.request_id !== 'string') {
return
}
+
await receiveApprovalRequest(gateway, {
allowPermanent: pending.allow_permanent !== false,
choices: Array.isArray(pending.choices) ? pending.choices.filter(choice => typeof choice === 'string') : undefined,
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index 3d92f358b4b..8fc2e23ef90 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -624,8 +624,18 @@ export interface SessionResumeResponse {
choices?: string[]
command?: string
description?: string
+ request_id?: string
smart_denied?: boolean
}
+ // The clarify question still blocking this session, if any. Same replay
+ // class as pending_approval: emitted-while-detached prompts are restored
+ // from the resume snapshot instead of being lost until server-side timeout.
+ pending_clarify?: {
+ choices?: null | string[]
+ multi_select?: boolean
+ question?: string
+ request_id?: string
+ }
info?: SessionRuntimeInfo
message_count: number
messages: SessionMessage[]
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py
index a6dfafd659a..b6b265c777e 100644
--- a/tests/tui_gateway/test_protocol.py
+++ b/tests/tui_gateway/test_protocol.py
@@ -207,8 +207,50 @@ def test_live_session_payload_replays_pending_approval(server, monkeypatch):
if saved_queue is not None:
approval._gateway_queues["stored-session"] = saved_queue
- assert payload["pending_approval"] == first
assert payload["pending_approval"] is not first
+ replayed = payload["pending_approval"]
+ # request_id is injected by _ApprovalEntry so reconnecting clients can
+ # correlate their approval.respond with the exact queued request.
+ assert replayed.pop("request_id")
+ assert replayed == first
+
+
+def test_live_session_payload_replays_pending_clarify(server):
+ """A reattached client also receives a clarify question emitted while detached."""
+ session = {
+ "agent": types.SimpleNamespace(),
+ "cols": 80,
+ "created_at": 1.0,
+ "history": [],
+ "history_lock": threading.Lock(),
+ "running": True,
+ "session_key": "stored-session",
+ }
+ clarify_payload = {
+ "choices": ["staging", "production"],
+ "question": "Which deployment target?",
+ "request_id": "rid-clarify",
+ }
+ with server._prompt_lock:
+ server._pending["rid-clarify"] = ("runtime-session", threading.Event())
+ server._pending_prompt_payloads["rid-clarify"] = (
+ "clarify.request",
+ dict(clarify_payload),
+ )
+
+ try:
+ payload = server._live_session_payload("runtime-session", session)
+ other = server._live_session_payload("other-session", session)
+ finally:
+ with server._prompt_lock:
+ server._pending.pop("rid-clarify", None)
+ server._pending_prompt_payloads.pop("rid-clarify", None)
+
+ assert payload["pending_clarify"] == clarify_payload
+ # Snapshot, not a live reference into the registry.
+ assert payload["pending_clarify"] is not clarify_payload
+ # Scoped to the owning runtime session only.
+ assert "pending_clarify" not in other
def test_disable_flush_env_var_actually_wires_to_module_constant(monkeypatch):
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index f391f7c4ef0..62f5725a62b 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1908,6 +1908,26 @@ def _approval_request_payload(data: dict | None) -> dict:
return payload
+def _pending_clarify_request_payload(sid: str) -> dict | None:
+ """Read the clarify prompt still blocking a session, if there is one.
+
+ Clarify prompts share `_block()`'s pending registry, so a reconnecting
+ client whose transport was detached when `clarify.request` was emitted
+ would otherwise never see the question — the agent thread stays parked on
+ the Event until timeout. Same replay contract as `pending_approval`: a
+ read-only snapshot, the registry stays authoritative and `clarify.respond`
+ with the embedded request_id resolves it.
+ """
+ with _prompt_lock:
+ for rid, (owner_sid, _ev) in _pending.items():
+ if owner_sid != sid:
+ continue
+ event, prompt_payload = _pending_prompt_payloads.get(rid, ("", {}))
+ if event == "clarify.request":
+ return dict(prompt_payload)
+ return None
+
+
def _pending_approval_request_payload(session_key: str) -> dict | None:
"""Read the oldest unresolved approval in a session, if there is one."""
try:
@@ -8493,6 +8513,8 @@ def _live_session_payload(
payload["queued"] = queued
if approval := _pending_approval_request_payload(str(session.get("session_key") or "")):
payload["pending_approval"] = approval
+ if clarify := _pending_clarify_request_payload(sid):
+ payload["pending_clarify"] = clarify
return payload