Skip to content

The agent that grows with you

fix(desktop): restore pending clarify cards on session re-entry

Eddo Jansen5d8cd4d56fb8
diff --git a/apps/desktop/e2e/core/interactive-prompts.spec.ts b/apps/desktop/e2e/core/interactive-prompts.spec.ts
index daa95f4b363..25b9e1824fe 100644
--- a/apps/desktop/e2e/core/interactive-prompts.spec.ts
+++ b/apps/desktop/e2e/core/interactive-prompts.spec.ts
@@ -61,7 +61,11 @@ test('clarify and approval prompts round-trip exactly once', async () => {
const provider = await startScriptedProvider()
const sandbox = createCoreSandbox('prompts')
writeProviderHome(sandbox.hermesHome, provider.url, '', 'manual')
- const { app, page } = await launchCoreApp(coreAppEnv(sandbox))
+ // Keep this explicit gateway home distinct from the sandbox account default:
+ // launchd belongs to the real UID, not HOME, and must never select its bare service.
+ const accountHome = path.join(sandbox.root, 'account-home')
+ fs.mkdirSync(accountHome)
+ const { app, page } = await launchCoreApp(coreAppEnv(sandbox, { HOME: accountHome }))
const ws = recordWebSockets(page)
const session: OracleTarget = { sessionId: '', expectUserMarkers: [] }
@@ -95,6 +99,16 @@ test('clarify and approval prompts round-trip exactly once', async () => {
const openForms = page.locator('form[data-clarify-choices], form[data-clarify-batch]').filter({ visible: true })
await expect(openForms).toHaveCount(1, { timeout: 120_000 })
await expect(viewport(page).getByText(question)).toHaveCount(1)
+
+ // Switching away must not settle a question whose tool is still waiting.
+ const waitingSession = await currentSessionId(page)
+ await page.evaluate(() => { window.location.hash = '#/' })
+ await expect.poll(() => currentSessionId(page)).toBe('')
+ await page.evaluate(id => { window.location.hash = `#/${id}` }, waitingSession)
+ await expect.poll(() => currentSessionId(page)).toBe(waitingSession)
+ await expect(openForms).toHaveCount(1)
+ await expect(viewport(page).getByText(question)).toHaveCount(1)
+
await openForms.getByRole('button', { name: new RegExp(pick) }).click()
const submit = openForms.locator('button[type="submit"]')
await expect(submit).toBeEnabled()
diff --git a/apps/desktop/src/api/canonical-clarify-lifecycle.test.ts b/apps/desktop/src/api/canonical-clarify-lifecycle.test.ts
new file mode 100644
index 00000000000..b236fe9c7d6
--- /dev/null
+++ b/apps/desktop/src/api/canonical-clarify-lifecycle.test.ts
@@ -0,0 +1,117 @@
+import { JsonRpcGatewayClient, type ServerRequest } from '@hermes/shared'
+import { afterEach, beforeEach, expect, test, vi } from 'vitest'
+
+import { handleServerRequest } from '@/app/session/hooks/use-message-stream/gateway-event/server-requests'
+import { restorePendingClarifyFromSnapshot } from '@/app/session/hooks/use-session-actions/restore-pending-clarify'
+import { $clarifyRequests } from '@/store/clarify'
+import { $gateway } from '@/store/gateway'
+import { answerParkedCard } from '@/store/parked-card-answers'
+import { resetServerRequestsForTests } from '@/store/server-requests'
+import type { SessionResumeResult } from '@/types/hermes'
+
+import { CanonicalDesktopProtocol } from './canonical-protocol'
+import { HermesGateway } from './client'
+
+beforeEach(() => {
+ $clarifyRequests.set({})
+ resetServerRequestsForTests()
+})
+
+afterEach(() => vi.restoreAllMocks())
+
+test.each([
+ { method: 'session.resume', warm: true },
+ { method: 'session.activate', warm: true },
+ { method: 'session.resume', warm: false }
+])('a question remains answerable through $method (warm=$warm)', async ({ method, warm }) => {
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'connect').mockResolvedValue()
+ const wire = vi.spyOn(JsonRpcGatewayClient.prototype, 'request').mockImplementation(async name => {
+ if (name === 'session.resume') {
+ return { session_id: 'waiting', stored_session_id: 'waiting', revision: 1, execution_generation: 3,
+ running: true, messages: [], prompts: [{ kind: 'clarify', prompt_id: 'question-1',
+ execution_generation: 3, question: 'Which target?', choices: ['staging', 'production'] }] } as never
+ }
+
+ return { status: 'resolved' } as never
+ })
+ const client = new HermesGateway()
+ const previousGateway = $gateway.get()
+ $gateway.set(client)
+ const shown = vi.fn((request: ServerRequest) => handleServerRequest({ ...request, profile: 'default' }, {
+ activeSessionIdRef: { current: 'waiting' },
+ sessionInterrupted: () => false,
+ sessionStateByRuntimeIdRef: { current: new Map() },
+ updateSessionState: vi.fn(),
+ upsertToolCall: vi.fn()
+ }, 'waiting'))
+ client.onRequest(shown)
+
+ try {
+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=fixture')
+ await client.request('session.resume', { session_id: 'waiting' })
+ expect($clarifyRequests.get().waiting?.requestId).toBe('question-1')
+
+ // The first delivery is retained while another chat is foregrounded. A warm
+ // activation must not interpret a differently-shaped snapshot as no question.
+ const startedAt = Date.now() / 1000 + 1
+ const snapshot = await client.request<SessionResumeResult>(method, { session_id: 'waiting' })
+ const restored = restorePendingClarifyFromSnapshot(snapshot, 'waiting', startedAt, warm ? 'question-1' : undefined)
+
+ expect(restored.authoritativeAbsent).toBe(false)
+ expect(restored.request?.requestId).toBe('question-1')
+ expect($clarifyRequests.get().waiting?.requestId).toBe('question-1')
+ expect(shown).toHaveBeenCalledTimes(1)
+
+ // An answer and a switch-back snapshot may overlap. Even if that snapshot
+ // still contains the question, it must not reopen the locally answered card.
+ const racingSnapshot = client.request<SessionResumeResult>('session.activate', { session_id: 'waiting' })
+ expect(answerParkedCard('waiting', 'staging')).toBe(true)
+ const afterAnswer = restorePendingClarifyFromSnapshot(await racingSnapshot, 'waiting', startedAt, 'question-1')
+ expect(afterAnswer.request).toBeNull()
+ expect($clarifyRequests.get().waiting).toBeUndefined()
+ expect(shown).toHaveBeenCalledTimes(1)
+ await vi.waitFor(() => expect(wire.mock.calls.filter(([name]) => name === 'clarify.respond')).toHaveLength(1))
+ expect(wire.mock.calls.some(([name]) => name === 'prompt.submit')).toBe(false)
+ expect(wire.mock.calls.find(([name]) => name === 'clarify.respond')).toEqual(['clarify.respond', {
+ session_id: 'waiting', profile: 'default', execution_generation: 3, prompt_id: 'question-1', answer: 'staging'
+ }, expect.any(Number), undefined])
+ } finally {
+ $gateway.set(previousGateway)
+ client.close()
+ }
+})
+
+test.each([false, true])('an empty snapshot clears only questions predating it (newer=$newer)', newer => {
+ const startedAt = Date.now() / 1000
+ const snapshot = new CanonicalDesktopProtocol().result('session.resume', { session_id: 'waiting' }, {
+ session_id: 'waiting', revision: 1, execution_generation: 3, running: false, prompts: []
+ })
+ const request = {
+ sessionId: 'waiting', requestId: 'question-1', receivedAt: startedAt + (newer ? 1 : -1),
+ questions: [{ qid: 'question-1', question: 'Which target?', choices: ['staging'], multiSelect: false }]
+ }
+ $clarifyRequests.set({ waiting: request })
+
+ const restored = restorePendingClarifyFromSnapshot(snapshot, 'waiting', startedAt)
+
+ expect(restored.authoritativeAbsent).toBe(true)
+ expect(restored.cleared).toEqual(newer ? null : request)
+ expect($clarifyRequests.get().waiting).toEqual(newer ? request : undefined)
+})
+
+test('snapshots expose batch question params without losing already locked answers', () => {
+ const questions = [
+ { qid: 'q1', question: 'Which target?', choices: ['staging'], multi_select: false },
+ { qid: 'q2', question: 'Which mode?', choices: ['read only'], multi_select: false }
+ ]
+ const answers = { q1: 'staging' }
+ const snapshot = new CanonicalDesktopProtocol().result('session.resume', { session_id: 'waiting' }, {
+ session_id: 'waiting', revision: 1, execution_generation: 3, prompts: [
+ { kind: 'clarify', prompt_id: 'question-1', questions, answers, execution_generation: 3 }
+ ]
+ })
+
+ expect(snapshot.open_requests).toEqual([{
+ id: 'question-1', method: 'clarify', params: { session_id: 'waiting', questions, answers }
+ }])
+})
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index 5167ab82108..f661c1d49d7 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -9,6 +9,17 @@ export const canonicalProfile = (profile: unknown): string =>
export const canonicalSessionKey = (sessionId: unknown, profile?: unknown): string =>
JSON.stringify([canonicalProfile(profile), sessionId])
+/** Live events and retained snapshots must describe the same answerable card. */
+export function canonicalPromptParams(kind: unknown, sessionId: string, prompt: Record<string, unknown>): Record<string, unknown> {
+ const choices = Array.isArray(prompt.choices) ? prompt.choices : []
+
+ return kind === 'clarify'
+ ? { session_id: sessionId, answers: prompt.answers,
+ questions: Array.isArray(prompt.questions) ? prompt.questions : [{ qid: prompt.prompt_id, question: prompt.question, choices, multi_select: prompt.multi_select }] }
+ : { session_id: sessionId, request_id: prompt.prompt_id, command: prompt.command, description: prompt.description, choices,
+ allow_permanent: choices.includes('always'), edit: prompt.edit }
+}
+
// Only the authenticated adapter can establish this renderer-side provenance;
// a JSON-RPC payload's ordinary `profile` property cannot impersonate it.
const canonicalOwners = new WeakMap<object, string>()
@@ -651,7 +662,11 @@ export class CanonicalDesktopProtocol {
return projected
})
- return { ...value, pending_approval: prompts.find((p: any) => p.kind === 'approval'), pending_clarify: prompts.find((p: any) => p.kind === 'clarify'), info: { ...value.info, stored_session_id: value.stored_session_id, pending_submissions: value.pending_submissions, replay_epoch: value.replay_epoch, last_sequence: value.last_sequence, execution_generation: value.execution_generation, running: value.running } }
+ const open_requests = prompts.map((prompt: Record<string, unknown>) => ({
+ id: prompt.prompt_id, method: prompt.kind, params: canonicalPromptParams(prompt.kind, sid, prompt)
+ }))
+
+ return { ...value, open_requests, pending_approval: prompts.find((p: any) => p.kind === 'approval'), pending_clarify: prompts.find((p: any) => p.kind === 'clarify'), info: { ...value.info, stored_session_id: value.stored_session_id, pending_submissions: value.pending_submissions, replay_epoch: value.replay_epoch, last_sequence: value.last_sequence, execution_generation: value.execution_generation, running: value.running } }
}
// The canonical compress receipt carries counts, not the retained transcript;
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index 488b2c69760..0a47553f444 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -9,7 +9,7 @@ import { map, type MapStore } from 'nanostores'
import type { HermesApiRequest } from '@/global'
-import { CANONICAL_GATEWAY_PROTOCOL, CanonicalDesktopProtocol, canonicalProfile, canonicalSessionKey, recordCanonicalOwner, splitRewindSubmit } from './canonical-protocol'
+import { CANONICAL_GATEWAY_PROTOCOL, CanonicalDesktopProtocol, canonicalProfile, canonicalPromptParams, canonicalSessionKey, recordCanonicalOwner, splitRewindSubmit } from './canonical-protocol'
// Desktop startup fires a burst of read-only data calls (config, profiles,
// model info/options, cron) the moment the backend passes readiness. On a
@@ -115,16 +115,7 @@ export class HermesGateway extends JsonRpcGatewayClient {
if (this.deliveredPrompts.has(id)) { return }
this.deliveredPrompts.set(id, { sessionId: sid, profile })
- const choices = Array.isArray(p.choices) ? p.choices : []
-
- // The question card reads one `questions[]` shape. A canonical clarify prompt is one
- // question (the shared gateway asks a batch one card at a time), so its prompt id doubles
- // as the qid that `clarify.lock` answers with (see `request` below).
- const params: Record<string, unknown> = kind === 'clarify'
- ? { session_id: sid, answers: p.answers,
- questions: Array.isArray(p.questions) ? p.questions : [{ qid: id, question: p.question, choices, multi_select: p.multi_select }] }
- : { session_id: sid, request_id: id, command: p.command, description: p.description, choices,
- allow_permanent: choices.includes('always'), edit: p.edit }
+ const params = canonicalPromptParams(kind, sid, p)
let settled = false