Skip to content

The agent that grows with you

fix(desktop): composer text answers a waiting clarify card

alt-glitchdf930df60c08
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
index 7d9a84c86eb..31557705e27 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
@@ -543,11 +543,15 @@ describe('useComposerSubmit with a clarify parked on the session', () => {
})
}
+ // SAFETY: the clarify lock path reads only `request` from the gateway.
+ const setGateway = (request: ReturnType<typeof vi.fn>) => $gateway.set({ request } as never)
+
afterEach(() => {
cleanup()
respond.mockClear()
resetServerRequestsForTests()
$clarifyRequests.set({})
+ $gateway.set(null)
vi.restoreAllMocks()
})
@@ -585,32 +589,55 @@ describe('useComposerSubmit with a clarify parked on the session', () => {
expect(hasOpenServerRequest('req-runtime-session')).toBe(false)
})
- it('skips the question and still sends the typed message on an idle session', async () => {
+ it('answers the question with the typed text and does not send it on an idle session', async () => {
parkClarify('runtime-session')
- const { hook, onSubmit } = renderSubmitHook({ text: 'actually do this instead' })
+ const request = vi.fn(async () => ({ status: 'ok', remaining: [] }))
+ setGateway(request)
+ const { hook, onSubmit, onSteer } = renderSubmitHook({ text: 'actually do this instead' })
act(() => {
hook.result.current.submitDraft()
})
- await waitFor(() => expect(respond).toHaveBeenCalledWith({}))
await waitFor(() =>
- expect(onSubmit).toHaveBeenCalledWith('actually do this instead', expect.objectContaining({ attachments: [] }))
+ expect(request).toHaveBeenCalledWith('clarify.lock', {
+ answer: 'actually do this instead',
+ question_id: 'q0',
+ request_id: 'req-runtime-session'
+ })
)
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(onSteer).not.toHaveBeenCalled()
+ expect(respond).not.toHaveBeenCalled()
expect($clarifyRequests.get()['runtime-session']).toBeUndefined()
- expect(hasOpenServerRequest('req-runtime-session')).toBe(false)
})
- it('skips the question before steering a busy turn', async () => {
- parkClarify('runtime-session')
- const { hook, onSteer } = renderSubmitHook({ busy: true, text: 'change course' })
+ it('answers one question per submit while a busy turn waits, matching a choice label', async () => {
+ const request = vi.fn(async () => ({ status: 'ok', remaining: ['q1'] }))
+ setGateway(request)
+ rememberServerRequest({ fail: vi.fn(), id: 'req-two', method: 'clarify', params: {}, respond })
+ $clarifyRequests.set({
+ 'runtime-session': {
+ requestId: 'req-two',
+ questions: [
+ { choices: ['Staging', 'Prod'], multiSelect: false, qid: 'q0', question: 'where?' },
+ { choices: null, multiSelect: false, qid: 'q1', question: 'why?' }
+ ],
+ sessionId: 'runtime-session'
+ }
+ })
+ const { hook, onSteer } = renderSubmitHook({ busy: true, text: 'prod' })
act(() => {
hook.result.current.submitDraft()
})
- await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course'))
- expect(respond).toHaveBeenCalledWith({})
+ await waitFor(() =>
+ expect(request).toHaveBeenCalledWith('clarify.lock', { answer: 'Prod', question_id: 'q0', request_id: 'req-two' })
+ )
+ expect(onSteer).not.toHaveBeenCalled()
+ expect($clarifyRequests.get()['runtime-session']?.lockedAnswers).toEqual({ q0: 'Prod' })
+ expect(hasOpenServerRequest('req-two')).toBe(true)
})
it('leaves the question alone for an empty Enter (Stop, not an answer)', () => {
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index ad1714f5853..16a8d9fba33 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@ -6,7 +6,7 @@ import { translateNow, useI18n } from '@/i18n'
import { isSlashCommandText } from '@/lib/chat-runtime'
import { isSideTaskSlashCommand } from '@/lib/desktop-slash-commands'
import { triggerHaptic } from '@/lib/haptics'
-import { answerSetupCard, hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'
+import { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'
import {
clearSessionDraft,
type ComposerAttachment,
@@ -17,6 +17,7 @@ import { resetBrowseState } from '@/store/composer-input-history'
import { enqueueQueuedPrompt, type QueuedPromptEntry } from '@/store/composer-queue'
import { hasConnectionRequest, skipConnectionRequest } from '@/store/connection-request'
import { notify } from '@/store/notifications'
+import { answerParkedCard } from '@/store/parked-card-answers'
import { hasBlockingPromptRequest } from '@/store/prompts'
import { cloneAttachments, type QueueEditState } from '../composer-utils'
@@ -270,34 +271,31 @@ export function useComposerSubmit({
return true
}
- // True when the draft was consumed as a parked setup card's answer.
- const answerParkedCard = (text: string, payloadPresent: boolean) => {
- // A clarify card parked on this session owns the turn: the agent is blocked
- // inside its tool batch waiting on `clarify.respond`, so a follow-up routed
- // through steer/queue sits undelivered until the clarify's own timeout
- // (default 5 min) — the message looks sent and nothing happens. Typing a
- // real message instead of picking an option IS the answer "none of these":
- // skip the question so the tool returns, then route the words normally.
- // A setup card is the exception: the setup turn reads typed words as its
- // answer, so they go back as the card's answer and the turn carries on.
+ // True when the draft was consumed as a parked card's answer.
+ const answerParkedCardWithDraft = (text: string, payloadPresent: boolean) => {
+ // A card parked on this session owns the turn: the agent is blocked inside
+ // its tool batch, so a steer or queued follow-up would sit undelivered until
+ // the card's own timeout. Plain text answers the card instead (a clarify
+ // takes it as its next question's answer) and is not sent again.
//
- // A slash command or attachments cannot be a setup answer either. The skip
- // is fire-and-forget, not awaited: it clears the card synchronously and
- // both RPCs ride the same socket in call order, so the gateway resolves the
- // clarify before it sees the follow-up. Awaiting first would leave the draft
- // live for a tick — long enough for a second Enter to send it twice.
+ // A slash command or attachments cannot be an answer: the card is skipped
+ // and the draft routes normally. The skip is fire-and-forget, not awaited:
+ // it clears the card synchronously and both RPCs ride the same socket in
+ // call order, so the gateway resolves the clarify before it sees the
+ // follow-up. Awaiting first would leave the draft live for a tick, long
+ // enough for a second Enter to send it twice.
//
- // /btw and /bg run beside the turn (snapshot / separate session) and answer
- // neither parked card. With attachments the draft isn't routed as a slash
+ // /btw and /bg run beside the turn (snapshot / separate session) and touch
+ // no parked card. With attachments the draft isn't routed as a slash
// command, so it falls back to the ordinary-message behavior.
const isSideQuestion = !attachments.length && isSideTaskSlashCommand(text)
- const cardParked = payloadPresent && !queueEdit && !isSideQuestion && hasClarifyRequest(sessionId)
+ const routable = payloadPresent && !queueEdit && !isSideQuestion
if (
- cardParked &&
+ routable &&
!attachments.length &&
!SLASH_COMMAND_RE.test(text.trim()) &&
- answerSetupCard(sessionId, text.trim())
+ answerParkedCard(sessionId ?? '', text.trim())
) {
triggerHaptic('submit')
resetBrowseState(sessionId)
@@ -307,12 +305,12 @@ export function useComposerSubmit({
return true
}
- if (cardParked) {
+ if (routable && hasClarifyRequest(sessionId)) {
void skipClarifyRequest(sessionId)
}
// Same for a pending connection card: ordinary typing continues the operation.
- if (payloadPresent && !queueEdit && !isSideQuestion && hasConnectionRequest(sessionId)) {
+ if (routable && hasConnectionRequest(sessionId)) {
void skipConnectionRequest(sessionId)
}
@@ -349,7 +347,7 @@ export function useComposerSubmit({
const text = pathifyRefs(draftRef.current)
const payloadPresent = text.trim().length > 0 || attachments.length > 0
- if (answerParkedCard(text, payloadPresent)) {
+ if (answerParkedCardWithDraft(text, payloadPresent)) {
return
}
diff --git a/apps/desktop/src/store/clarify.ts b/apps/desktop/src/store/clarify.ts
index 621bcdbbcea..7b6512bc091 100644
--- a/apps/desktop/src/store/clarify.ts
+++ b/apps/desktop/src/store/clarify.ts
@@ -1,8 +1,14 @@
import type { SetupChooseKind, SetupChooseOption } from '@hermes/shared'
import { atom, computed } from 'nanostores'
-import { hasOpenServerRequest, respondToServerRequest } from './server-requests'
+import { translateNow } from '@/i18n'
+
+import { $gateway } from './gateway'
+import { notifyError } from './notifications'
+import { registerParkedCardAnswer } from './parked-card-answers'
+import { forgetServerRequest, hasOpenServerRequest, respondToServerRequest } from './server-requests'
import { $activeSessionId } from './session'
+import { requestForOwnedSession } from './session-states'
export interface ClarifyQuestion {
qid: string
@@ -398,6 +404,89 @@ export function answerSetupCard(sessionId: string | null | undefined, text: stri
return request?.setup ? answerSetupChoose(request, request.setup, text) : false
}
+/**
+ * Answer the card parked on `sessionId` with composer text. A setup card reads the words as its
+ * pick; a clarify card takes them as the answer to its first question not yet locked.
+ */
+function answerClarifyText(sessionId: string, text: string): boolean {
+ const request = $clarifyRequests.get()[keyFor(sessionId)]
+
+ if (!request) {
+ return false
+ }
+
+ return request.setup ? answerSetupCard(sessionId, text) : lockTypedAnswer(request, text)
+}
+
+registerParkedCardAnswer('clarify', answerClarifyText)
+
+/** The choice typed text names (any case, as the messaging path matches labels), else the words themselves. */
+function typedAnswer(question: ClarifyQuestion, text: string): string {
+ const typed = text.toLowerCase()
+ const answer = question.choices?.map(bareChoice).find(choice => choice.toLowerCase() === typed) ?? text
+
+ return question.multiSelect ? JSON.stringify([answer]) : answer
+}
+
+function lockTypedAnswer(request: ClarifyRequest, text: string): boolean {
+ const gateway = $gateway.get()
+ const question = request.questions.find(entry => request.lockedAnswers?.[entry.qid] === undefined)
+
+ if (!gateway || !question) {
+ return false
+ }
+
+ const answer = typedAnswer(question, text)
+ const lockedAnswers = { ...request.lockedAnswers, [question.qid]: answer }
+ const last = request.questions.every(entry => lockedAnswers[entry.qid] !== undefined)
+
+ // The store changes before the RPC returns, so a second Enter locks the next question, not this one again.
+ if (last) {
+ clearClarifyRequest(request.requestId, request.sessionId)
+ settleClarify(request, {
+ outcome: 'submitted',
+ responses: request.questions.map(entry => {
+ const locked = lockedAnswers[entry.qid]
+
+ return locked
+ ? { question: entry.question, status: 'answered', user_response: lockedAnswer(entry, locked) }
+ : { question: entry.question, status: 'skipped', user_response: null }
+ })
+ })
+ } else {
+ setClarifyRequest({ ...request, lockedAnswers })
+ }
+
+ void requestForOwnedSession<{ status?: string }>(
+ request.sessionId,
+ <R>(...args: Parameters<typeof gateway.request>) => gateway.request<R>(...args),
+ 'clarify.lock',
+ { answer, question_id: question.qid, request_id: request.requestId }
+ )
+ .then(reply => {
+ if (reply.status === 'expired') {
+ // The wait already ended; the tool's own result says how.
+ forgetSettledClarify(request.requestId)
+ } else if (last) {
+ // The last lock resolved the batch server-side, so no response frame is owed.
+ forgetServerRequest(request.requestId)
+ }
+ })
+ .catch(error => {
+ forgetSettledClarify(request.requestId)
+
+ const current = $clarifyRequests.get()[keyFor(request.sessionId)]
+
+ if (hasOpenServerRequest(request.requestId) && (!current || current.requestId === request.requestId)) {
+ setClarifyRequest(request)
+ }
+
+ notifyError(error, translateNow('assistant.clarify.sendFailed'))
+ })
+
+ return true
+}
+
/** The row typed text names, by id or label (any case). */
function matchSetupRow(labels: Record<string, string>, text: string): string | undefined {
const typed = text.trim().toLowerCase()
diff --git a/apps/desktop/src/store/parked-card-answers.test.ts b/apps/desktop/src/store/parked-card-answers.test.ts
new file mode 100644
index 00000000000..9e86a658d33
--- /dev/null
+++ b/apps/desktop/src/store/parked-card-answers.test.ts
@@ -0,0 +1,31 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { answerParkedCard, registerParkedCardAnswer } from './parked-card-answers'
+
+describe('parked card answers', () => {
+ const unregister: Array<() => void> = []
+
+ afterEach(() => {
+ unregister.splice(0).forEach(off => off())
+ })
+
+ it('stops at the first card that takes the text, and forgets a card once it unregisters', () => {
+ const declines = vi.fn(() => false)
+ const takes = vi.fn((sessionId: string) => sessionId === 'session-a')
+ const later = vi.fn(() => true)
+
+ unregister.push(registerParkedCardAnswer('test-declines', declines))
+ const offTakes = registerParkedCardAnswer('test-takes', takes)
+ unregister.push(registerParkedCardAnswer('test-later', later))
+
+ expect(answerParkedCard('session-a', 'hello')).toBe(true)
+ expect(declines).toHaveBeenCalledWith('session-a', 'hello')
+ expect(later).not.toHaveBeenCalled()
+
+ offTakes()
+ later.mockReturnValue(false)
+
+ expect(answerParkedCard('session-a', 'hello')).toBe(false)
+ expect(takes).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/apps/desktop/src/store/parked-card-answers.ts b/apps/desktop/src/store/parked-card-answers.ts
new file mode 100644
index 00000000000..e9bb3410da0
--- /dev/null
+++ b/apps/desktop/src/store/parked-card-answers.ts
@@ -0,0 +1,29 @@
+/** Answers a card parked on `sessionId` with composer text; true when the text answered it. */
+export type ParkedCardAnswer = (sessionId: string, text: string) => boolean
+
+const answers = new Map<string, ParkedCardAnswer>()
+
+/** Register a card kind's typed-answer handler under `id`. Returns the unregister function. */
+export function registerParkedCardAnswer(id: string, answer: ParkedCardAnswer): () => void {
+ answers.set(id, answer)
+
+ return () => {
+ if (answers.get(id) === answer) {
+ answers.delete(id)
+ }
+ }
+}
+
+/**
+ * Offer composer text to every card waiting on `sessionId`, in registration order. True when one
+ * took it as its answer: the composer then neither sends nor steers the text.
+ */
+export function answerParkedCard(sessionId: string, text: string): boolean {
+ for (const answer of answers.values()) {
+ if (answer(sessionId, text)) {
+ return true
+ }
+ }
+
+ return false
+}
diff --git a/apps/desktop/src/store/prompts.ts b/apps/desktop/src/store/prompts.ts
index 6fc0636c34d..7d4dd6fa4d3 100644
--- a/apps/desktop/src/store/prompts.ts
+++ b/apps/desktop/src/store/prompts.ts
@@ -472,10 +472,10 @@ export const $activeSessionAwaitingInput = computed(
)
/** True when `sessionId` is parked on a blocking prompt that typing cannot
- * answer (approval / sudo / secret). Clarify is deliberately excluded: typing
- * a real message IS an answer to a clarify ("none of these" — the composer
- * skips it and routes the words), but no message text can approve a command
- * or supply a password. Imperative read — the composer checks this on Enter,
+ * answer (approval / sudo / secret). Clarify is deliberately excluded: typed
+ * text answers a clarify's next question (the composer locks it through
+ * `answerParkedCard`), but no message text can approve a command or supply a
+ * password. Imperative read — the composer checks this on Enter,
* not on every render. */
export const hasBlockingPromptRequest = (sessionId: string | null | undefined): boolean => {
const key = keyFor(sessionId)