Skip to content

The agent that grows with you

feat(desktop): a multi-question clarify is one form on Desktop and the Webapp

Teknium981e1325e8bd
diff --git a/apps/desktop/src/api/canonical-clarify-batch.test.ts b/apps/desktop/src/api/canonical-clarify-batch.test.ts
new file mode 100644
index 00000000000..e7ca4da4e1b
--- /dev/null
+++ b/apps/desktop/src/api/canonical-clarify-batch.test.ts
@@ -0,0 +1,72 @@
+// @vitest-environment node
+import { expect, test } from 'vitest'
+
+import { HermesGateway } from './client'
+
+// The owner asks a multi-question clarify as ONE request (the card's single form) only for a turn
+// whose submit declared `clarify_batch`; an older owner's closed submit params refuse the key, so the
+// Desktop declares it only where `client.capabilities` advertised `canonical_clarify_batch`.
+async function submitThrough(capabilities: Record<string, unknown> | null, dial = 'native_dial=fixture&ticket=t') {
+ const wsPackage = 'ws'
+ const { WebSocketServer } = await import(wsPackage)
+ const server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
+ await new Promise<void>(resolve => server.once('listening', resolve))
+ const submits: Record<string, unknown>[] = []
+ let advertised = 0
+
+ server.on('connection', (socket: any) => {
+ socket.send(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'gateway.ready', payload: {} } }))
+ socket.on('message', (bytes: Buffer) => {
+ const frame = JSON.parse(bytes.toString())
+ const reply = (result: unknown) => socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result }))
+
+ if (frame.method === 'client.capabilities') {
+ if (frame.params.server_requests) { advertised++ }
+
+ return capabilities
+ ? reply({ server_requests: ['clarify'], ...capabilities })
+ : socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, error: { code: -32601, message: 'unknown method' } }))
+ }
+
+ if (frame.method === 'session.resume') {
+ return reply({ session_id: 's', revision: 1, execution_generation: 1, replay_epoch: 'e', last_sequence: 0, prompts: [] })
+ }
+
+ if (frame.method === 'prompt.submit') { submits.push(frame.params) }
+
+ reply({ admission_id: `a${submits.length}`, ref: { session_id: 's' }, sequence: 1, status: 'queued', outcome: null,
+ authority_epoch: 1, execution_generation: 1 })
+ })
+ })
+ const client = new HermesGateway()
+
+ try {
+ await client.connect(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/ws?${dial}`)
+ await expect.poll(() => advertised).toBe(1)
+ // Let the capability answer land before the turn, as the app's boot does.
+ await new Promise(resolve => setTimeout(resolve, 20))
+ await client.request('prompt.submit', { session_id: 's', text: 'one' })
+ await client.request('prompt.submit', { session_id: 's', text: 'two' })
+
+ return submits
+ } finally {
+ client.close()
+
+ for (const socket of server.clients) { socket.terminate() }
+
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ }
+}
+
+test('every turn declares clarify_batch to an owner advertising canonical_clarify_batch', async () => {
+ const submits = await submitThrough({ declines_not_shown: true, canonical_clarify_batch: true })
+ expect(submits.map(params => params.clarify_batch)).toEqual([true, true])
+})
+
+test('an older owner (no field, or no client.capabilities at all) never sees the key', async () => {
+ for (const capabilities of [{ declines_not_shown: true }, null]) {
+ const submits = await submitThrough(capabilities)
+ expect(submits).toHaveLength(2)
+ expect(submits.some(params => 'clarify_batch' in params)).toBe(false)
+ }
+})
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index 35361e5f2a4..4541bd87973 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -424,6 +424,11 @@ export class HermesGateway extends JsonRpcGatewayClient {
if (local) { return local as T }
+ // The clarify card answers a whole question set as one form: declared, the owner asks the
+ // turn's multi-question clarify as ONE request; undeclared, one card per question. An older
+ // owner refuses the unknown key, so it rides only where `client.capabilities` advertised it.
+ if (method === 'prompt.submit' && this.backendClarifyBatch) { params = { ...params, clarify_batch: true } }
+
let prepared = this.protocol.prepare(method, params)
const wireMethod = this.protocol.wire(method, prepared)
diff --git a/apps/desktop/src/components/assistant-ui/clarify/clarify-set-form.test.tsx b/apps/desktop/src/components/assistant-ui/clarify/clarify-set-form.test.tsx
new file mode 100644
index 00000000000..e798a4fcc76
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/clarify-set-form.test.tsx
@@ -0,0 +1,89 @@
+import type { ToolCallMessagePartProps } from '@assistant-ui/react'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { I18nProvider } from '@/i18n'
+import { clearClarifyRequest, setClarifyRequest } from '@/store/clarify'
+import { $gateway } from '@/store/gateway'
+import { rememberServerRequest, resetServerRequestsForTests } from '@/store/server-requests'
+import { $activeSessionId } from '@/store/session'
+
+import { ClarifyTool } from './index'
+
+vi.mock('@/store/gateway', async importActual => ({
+ ...(await importActual<Record<string, unknown>>()),
+ requestGatewayForAgent: vi.fn(async () => ({ ok: true }))
+}))
+
+vi.mock('@assistant-ui/react', () => ({ useAuiState: () => true }))
+
+afterEach(() => {
+ cleanup()
+ clearClarifyRequest()
+ resetServerRequestsForTests()
+ $activeSessionId.set(null)
+ $gateway.set(null)
+ vi.clearAllMocks()
+})
+
+const QUESTIONS = [
+ { choices: ['staging', 'production'], multiSelect: false, qid: 'q0', question: 'Which target?' },
+ { choices: ['us', 'eu'], multiSelect: false, qid: 'q1', question: 'Which region?' },
+ { choices: null, multiSelect: false, qid: 'q2', question: 'Anything else?' }
+]
+
+function renderSet() {
+ const request = vi.fn().mockResolvedValue({ ok: true, remaining: [] })
+ rememberServerRequest({ fail: vi.fn(), id: 'request-set', method: 'clarify', params: {}, respond: vi.fn() })
+ $activeSessionId.set('session-1')
+ $gateway.set({ request } as never)
+ setClarifyRequest({ questions: QUESTIONS, requestId: 'request-set', sessionId: 'session-1' })
+ const args = { questions: QUESTIONS.map(({ choices, question }) => ({ choices, question })) }
+
+ const props: ToolCallMessagePartProps = {
+ addResult: vi.fn(), args, argsText: JSON.stringify(args), isError: false, respondToApproval: vi.fn(),
+ result: undefined, resume: vi.fn(), status: { type: 'running' }, toolCallId: 'clarify-set', toolName: 'clarify',
+ type: 'tool-call'
+ }
+
+ render(
+ <I18nProvider configClient={null} initialLocale="en">
+ <ClarifyTool {...props} />
+ </I18nProvider>
+ )
+
+ return request
+}
+
+const locks = (request: ReturnType<typeof vi.fn>) =>
+ request.mock.calls.filter(call => call[0] === 'clarify.lock').map(call => [call[1].question_id, call[1].answer])
+
+describe('a multi-question clarify set is one form', () => {
+ it('shows every question at once with one submit', () => {
+ renderSet()
+
+ for (const { question } of QUESTIONS) { expect(screen.getByText(question)).toBeTruthy() }
+
+ expect(screen.getAllByRole('button', { name: /Confirm and continue/ })).toHaveLength(1)
+ })
+
+ it('plain Enter on an answered earlier question moves on instead of sending the set half answered', async () => {
+ const request = renderSet()
+
+ // Picking moves the cursor to the next open question; the user goes back to the answered one.
+ fireEvent.click(screen.getByRole('button', { name: /staging/ }))
+ fireEvent.pointerDown(screen.getByText('Which target?'))
+ // Enter on that answered row must not submit while two questions are still open: it moves on.
+ fireEvent.keyDown(window, { key: 'Enter' })
+ await new Promise(resolve => setTimeout(resolve, 20))
+ expect(locks(request)).toEqual([])
+ // The cursor is on the next question now: Enter picks its highlighted row.
+ fireEvent.keyDown(window, { key: 'Enter' })
+
+ // Answering the rest and pressing Enter on the last question sends the whole set once.
+ fireEvent.change(screen.getByPlaceholderText(/Type your answer/), { target: { value: 'after 5pm' } })
+ fireEvent.keyDown(screen.getByPlaceholderText(/Type your answer/), { key: 'Enter', ctrlKey: true })
+ await waitFor(() => expect(locks(request)).toHaveLength(3))
+ expect(locks(request)).toEqual([['q0', 'staging'], ['q1', 'us'], ['q2', 'after 5pm']])
+ })
+})
diff --git a/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys.ts b/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys.ts
index 6c3a906bec7..f1d41de498e 100644
--- a/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys.ts
+++ b/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys.ts
@@ -137,7 +137,18 @@ export function useClarifyKeys({
}
if (isStaged(active, row)) {
- onConfirm()
+ // Plain Enter submits the set only from the last question or once nothing is left open:
+ // an earlier question moves on to the next unanswered one, so a set is never sent half
+ // answered by accident (Cmd/Ctrl+Enter still submits from anywhere).
+ const next = questionIndex < questions.length - 1 ? nextUnstaged(questionIndex) : null
+
+ if (next === null) {
+ onConfirm()
+ } else if (questions[next]?.choices?.length) {
+ setCursor({ question: next, row: 0 })
+ } else {
+ focusOther(next)
+ }
return
}
@@ -149,7 +160,7 @@ export function useClarifyKeys({
}
focusOther(questionIndex)
- }, [active, focusOther, isStaged, onConfirm, pick, questionIndex, row])
+ }, [active, focusOther, isStaged, nextUnstaged, onConfirm, pick, questionIndex, questions, row])
useEffect(() => {
if (!enabled || !active) {
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index b4be1f6440e..ab3df77f3a8 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -1937,6 +1937,7 @@ export interface ClientCapabilitiesParams {
export interface ClientCapabilitiesResult {
server_requests: string[]
declines_not_shown?: boolean
+ canonical_clarify_batch?: boolean
}
/** Client→server method params / server→client request params. Unknown keys are rejected. */
export type Params = Record<string, never>
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 3a8fa20fac6..237cd0ed52b 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -11775,6 +11775,11 @@
"default": false,
"title": "Declines Not Shown",
"type": "boolean"
+ },
+ "canonical_clarify_batch": {
+ "default": false,
+ "title": "Canonical Clarify Batch",
+ "type": "boolean"
}
},
"required": [
diff --git a/apps/shared/src/json-rpc-channel.ts b/apps/shared/src/json-rpc-channel.ts
index 4fc0a78094b..7b6c526eb10 100644
--- a/apps/shared/src/json-rpc-channel.ts
+++ b/apps/shared/src/json-rpc-channel.ts
@@ -215,6 +215,8 @@ export class JsonRpcRequestChannel {
private lastLivenessAt = 0
/** The bound generation's backend counts `decline` as one client abstaining (see `ServerRequest.decline`). */
private backendCountsDeclines = false
+ /** The bound generation's canonical owner admits `clarify_batch` on `prompt.submit` (`client.capabilities`). */
+ private backendClarifyBatch = false
private readonly requestHandlers: ServerRequestHandler[] = []
private readonly options: Required<
Omit<JsonRpcRequestChannelOptions, 'onEvent' | 'onHeartbeatFailure' | 'onRequestHandlerError' | 'onUnhandledRequest'>
@@ -242,6 +244,11 @@ export class JsonRpcRequestChannel {
return this.options.requestTimeoutMs
}
+ /** Whether the bound generation's canonical owner admits `clarify_batch` on `prompt.submit`. */
+ get clarifyBatch(): boolean {
+ return this.backendClarifyBatch
+ }
+
get connected(): boolean {
return this.transport !== null
}
@@ -252,6 +259,7 @@ export class JsonRpcRequestChannel {
this.transport = transport
this.lastLivenessAt = Date.now()
this.backendCountsDeclines = false
+ this.backendClarifyBatch = false
// First on the socket, before the owner's own requests: the backend reads frames in order, and its
// answer to the boot's first onboarding.state already depends on this. A call of its own, so a
@@ -540,6 +548,7 @@ export class JsonRpcRequestChannel {
.then(result => {
if (this.transport === transport) {
this.backendCountsDeclines = result?.declines_not_shown === true
+ this.backendClarifyBatch = result?.canonical_clarify_batch === true
}
})
.catch(() => undefined)
diff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.ts
index fa97c67a591..20875628a59 100644
--- a/apps/shared/src/json-rpc-gateway.ts
+++ b/apps/shared/src/json-rpc-gateway.ts
@@ -214,6 +214,11 @@ export class JsonRpcGatewayClient {
return this.state
}
+ /** The connected canonical owner admits `clarify_batch` on `prompt.submit` (`client.capabilities`). */
+ protected get backendClarifyBatch(): boolean {
+ return this.channel.clarifyBatch
+ }
+
async connect(wsUrl: string): Promise<void> {
// Refuse garbage; WebSocket coerces non-strings into
// `ws://<origin>/[object%20Object]` (#68250 stale-emit boot loop).
diff --git a/tui_gateway/contracts/liveness.py b/tui_gateway/contracts/liveness.py
index 9367d76e630..abd2da4884e 100644
--- a/tui_gateway/contracts/liveness.py
+++ b/tui_gateway/contracts/liveness.py
@@ -46,6 +46,11 @@ class ClientCapabilitiesResult(Result):
#: answer: the request settles only once every attached client declined (server_requests.py).
#: An older backend settles on the first error, so a client sends the decline only when this is true.
declines_not_shown: bool = False
+ #: A canonical owner on this backend admits ``clarify_batch`` on ``prompt.submit``: the turn's
+ #: multi-question clarify arrives as ONE ``clarify`` request answered with ``clarify.lock``, not
+ #: one card per question. An older owner refuses the unknown key, so a client declares it only when
+ #: this is true. (The legacy sidecar always asks the batch at once and is never sent the key.)
+ canonical_clarify_batch: bool = False
method("client.capabilities", params=ClientCapabilitiesParams, result=ClientCapabilitiesResult,
diff --git a/tui_gateway/methods_voice.py b/tui_gateway/methods_voice.py
index 697c58838f0..13a9a84aaa2 100644
--- a/tui_gateway/methods_voice.py
+++ b/tui_gateway/methods_voice.py
@@ -537,7 +537,8 @@ def _(rid, params: dict) -> dict:
if transport.desktop_local:
from tui_gateway import server
server.begin_local_desktop_boot()
- return _ok(rid, {"server_requests": sorted(contracts.SERVER_REQUESTS), "declines_not_shown": True})
+ return _ok(rid, {"server_requests": sorted(contracts.SERVER_REQUESTS), "declines_not_shown": True,
+ "canonical_clarify_batch": True})
@method("ping")