Skip to content

The agent that grows with you

Clarify: one question shape and one result shape on every surface (skip, cancel, timeout and undelivered are told apart) (#127760)

Siddharth Balyan5eea87882aeb
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index cb66f2bbd67..3c9eb165550 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -864,23 +864,6 @@ def _is_summary_stub(content: str) -> bool:
# user answer is never re-summarized away on a later prune pass.
_PRUNE_MIN_CHARS = 200
-# Sentinel ``user_response`` values from timeout / no-user clarify callbacks;
-# must never be quoted as a user answer.
-_CLARIFY_NON_RESPONSE_PREFIXES = (
- "The user did not provide a response", "[user did not respond",
- "[clarify prompt could not be delivered", "[oneshot mode:",
-)
-
-
-def _is_clarify_non_response_sentinel(response: Any) -> bool:
- """Return True when a clarify ``user_response`` is runtime sentinel prose, not an answer.
- For lists, ANY sentinel item poisons the whole response: real producers only emit scalar sentinels,
- so a mixed list is forged/corrupt content — fall back to the generic path (may lose info, never
- misattributes a user answer)."""
- items = [response] if isinstance(response, str) else response if isinstance(response, list) else ()
- return any(isinstance(s, str) and s.lstrip().startswith(_CLARIFY_NON_RESPONSE_PREFIXES) for s in items)
-
-
# Ghost-skill defense: the ONE canonical prune marker; emit sites and presence
# checks must use the same string so they cannot drift.
# Ghost-skill defense (#32106): when compaction reduces an old ``skill_view`` result to a 1-line metadata
@@ -1741,36 +1724,19 @@ def _sum_clarify(name, args, content, content_len, line_count):
# Strictly below _PRUNE_MIN_CHARS so the summary survives later prune passes via the
# min_prune_chars guard and skips the >=200-char dedup.
max_summary_chars = _PRUNE_MIN_CHARS - 1
- parsed = _json_dict(content)
- response = parsed.get("user_response")
- # Batch clarify (``questions=[...]``) nests each answer inside ``responses[].user_response``
- # rather than the top level; without this every batch answer was lost and the summarizer only
- # saw "asked user a question" (#106077).
- if response is None:
- batch_responses = parsed.get("responses")
- if isinstance(batch_responses, list) and batch_responses:
- collected = []
- for entry in batch_responses:
- if not isinstance(entry, dict):
- continue
- single = entry.get("user_response")
- # multi_select emits a list of strings; flatten it so the summary keeps every choice.
- if isinstance(single, str) and single:
- collected.append(single)
- elif isinstance(single, list) and all(isinstance(s, str) and s for s in single):
- collected.extend(single)
- response = collected if collected else None
- is_answer_shaped = (isinstance(response, str) and bool(response)) or (
- isinstance(response, list) and bool(response) and all(isinstance(s, str) and s for s in response)
- )
- # Timeout / no-user sentinel prose must not be quoted as a user answer.
- if is_answer_shaped and not _is_clarify_non_response_sentinel(response):
- # Escape lone UTF-16 surrogates so the message stays UTF-8/SQLite safe.
- serialized = json.dumps(response, ensure_ascii=False).encode("utf-8", errors="backslashreplace")
- summary = response_prefix + serialized.decode("utf-8")
- summary = elide(summary, max_summary_chars)
- return summary
- return "[clarify] asked user a question"
+ responses = _json_dict(content).get("responses")
+ answers: list = []
+ for entry in responses if isinstance(responses, list) else ():
+ if isinstance(entry, dict) and entry.get("status") == "answered":
+ value = entry.get("user_response")
+ answers.extend(value if isinstance(value, list) else [value])
+ answers = [answer for answer in answers if isinstance(answer, str) and answer]
+ if not answers:
+ return "[clarify] asked user a question"
+ # Escape lone UTF-16 surrogates so the message stays UTF-8/SQLite safe.
+ serialized = json.dumps(answers[0] if len(answers) == 1 else answers,
+ ensure_ascii=False).encode("utf-8", errors="backslashreplace")
+ return elide(response_prefix + serialized.decode("utf-8"), max_summary_chars)
def _sum_skill_manage(name, args, content, content_len, line_count):
diff --git a/agent/display.py b/agent/display.py
index 3995197499d..2a4574ec2b6 100644
--- a/agent/display.py
+++ b/agent/display.py
@@ -358,7 +358,7 @@ _PRIMARY_ARGS = {
"write_file": "path", "patch": "path", "search_files": "pattern", "browser_navigate": "url",
"browser_click": "ref", "browser_type": "text", "image_generate": "prompt", "text_to_speech": "text",
"vision_analyze": "question", "skill_view": "name", "skills_list": "category", "cronjob_manage": "action",
- "execute_code": "code", "browser_exec": "code", "delegate_task": "goal", "clarify": "question",
+ "execute_code": "code", "browser_exec": "code", "delegate_task": "goal",
"skill_manage": "name",
}
_FALLBACK_PREVIEW_KEYS = ("query", "text", "command", "path", "name", "prompt", "code", "goal")
@@ -441,6 +441,14 @@ def _preview_skill_view(args: dict, max_len: int) -> str | None:
return _tail_trunc(label, max_len) or None
+def _preview_clarify(args: dict, max_len: int) -> str | None:
+ questions = args.get("questions")
+ first = questions[0] if isinstance(questions, list) and questions else None
+ if not isinstance(first, dict):
+ return None
+ return _tail_trunc(_oneline(str(first.get("question") or "")), max_len) or None
+
+
def _preview_bridge_call(tool_name: str):
def _build(args: dict, max_len: int) -> str | None:
labels = bridge_tool_labels(tool_name, args)
@@ -458,7 +466,7 @@ _PREVIEW_BUILDERS = {
"process_manage": _preview_process_manage, "todo_list": _preview_todo_list,
"terminal": _preview_shell("command"), "execute_code": _preview_shell("code"),
"read_file": _preview_read_file, "memory": _preview_memory, "send_message": _preview_send_message,
- "skill_view": _preview_skill_view,
+ "skill_view": _preview_skill_view, "clarify": _preview_clarify,
"session_search": lambda args, _m: t("display.preview.session_search_recall", query=_clip(_oneline(args.get("query", "")), 25)),
"tool_call": _preview_bridge_call("tool_call"),
"tool_search": _preview_bridge_call("tool_search"),
diff --git a/agent/inline_tool_executors.py b/agent/inline_tool_executors.py
index 43d855635e8..cdc4c4c1b54 100644
--- a/agent/inline_tool_executors.py
+++ b/agent/inline_tool_executors.py
@@ -246,9 +246,7 @@ INLINE_TOOL_EXECUTORS: Dict[str, InlineToolExecutor] = {
"session_search": _session_search,
"memory": _memory,
"clarify": _tool(
- "tools.clarify_tool", "clarify_tool",
- ("question", "question", ""), ("choices", "choices"), ("multi_select", "multi_select", False),
- ("questions", "questions"),
+ "tools.clarify_tool", "clarify_tool", ("questions", "questions"),
callback=lambda agent, ctx: agent.clarify_callback,
),
"read_terminal": _callback_tool(
diff --git a/apps/desktop/e2e/batch-clarify.spec.ts b/apps/desktop/e2e/batch-clarify.spec.ts
index 062a022b59e..3442bbcf808 100644
--- a/apps/desktop/e2e/batch-clarify.spec.ts
+++ b/apps/desktop/e2e/batch-clarify.spec.ts
@@ -12,9 +12,6 @@
* clarify.request event → renderer, against the mock inference server.
*/
-import { expect, test } from './test'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
import {
BATCH_CLARIFY_QUESTIONS,
BATCH_CLARIFY_TRIGGER,
@@ -22,6 +19,9 @@ import {
SINGLE_BATCH_CLARIFY_TRIGGER
} from '../../../tests-js/scripts/mock-server'
+import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
+import { expect, test } from './test'
+
let fixture: MockBackendFixture | null = null
test.beforeAll(async () => {
@@ -68,7 +68,7 @@ test.describe('batch clarify card', () => {
await expect(confirmButton).toBeDisabled()
await batchCard.getByRole('button', { name: /Coffee/ }).click()
- await expect(confirmButton).toBeDisabled()
+ await expect(confirmButton).toBeEnabled()
await batchCard.getByRole('button', { name: /Morning/ }).click()
await expect(confirmButton).toBeEnabled()
diff --git a/apps/desktop/e2e/core/interactive-prompts.spec.ts b/apps/desktop/e2e/core/interactive-prompts.spec.ts
index 18fb9b6e40e..f963260570e 100644
--- a/apps/desktop/e2e/core/interactive-prompts.spec.ts
+++ b/apps/desktop/e2e/core/interactive-prompts.spec.ts
@@ -91,7 +91,6 @@ test('clarify and approval prompts round-trip exactly once', async () => {
{ text: [`${A(1)} `, 'noted ', 'your ', 'choice'] }
])
await send(page, `${U(1)} ask me`, 'Enter', ws)
- // The open (unanswered) clarify form: single-question or batch shape.
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)
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 28cd5cd0eb5..14bb3c9cb36 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
@@ -475,7 +475,7 @@ describe('useComposerSubmit busy-turn routing', () => {
describe('useComposerSubmit with a clarify parked on the session', () => {
// The clarify is a live server→client request: skipping it answers that
- // request frame (`{ answer: '' }`), not a `clarify.respond` RPC.
+ // request frame (`{}`), not a `clarify.respond` RPC.
const respond = vi.fn()
const parkClarify = (sessionId: string) => {
@@ -485,9 +485,7 @@ describe('useComposerSubmit with a clarify parked on the session', () => {
$clarifyRequests.set({
[sessionId]: {
requestId,
- question: 'which one?',
- choices: ['a', 'b'],
- multiSelect: false,
+ questions: [{ choices: ['a', 'b'], multiSelect: false, qid: 'q0', question: 'which one?' }],
sessionId
}
})
@@ -531,7 +529,7 @@ describe('useComposerSubmit with a clarify parked on the session', () => {
})
await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('/status', expect.anything()))
- expect(respond).toHaveBeenCalledWith({ answer: '' })
+ expect(respond).toHaveBeenCalledWith({})
expect(hasOpenServerRequest('req-runtime-session')).toBe(false)
})
@@ -543,7 +541,7 @@ describe('useComposerSubmit with a clarify parked on the session', () => {
hook.result.current.submitDraft()
})
- await waitFor(() => expect(respond).toHaveBeenCalledWith({ answer: '' }))
+ await waitFor(() => expect(respond).toHaveBeenCalledWith({}))
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith('actually do this instead', expect.objectContaining({ attachments: [] }))
)
@@ -560,7 +558,7 @@ describe('useComposerSubmit with a clarify parked on the session', () => {
})
await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course'))
- expect(respond).toHaveBeenCalledWith({ answer: '' })
+ expect(respond).toHaveBeenCalledWith({})
})
it('leaves the question alone for an empty Enter (Stop, not an answer)', () => {
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx
index c503e983f23..b4679627655 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx
@@ -73,21 +73,23 @@ describe('clarify request stream hydration', () => {
it('mounts an answerable clarify row when the tool.start row was missed', () => {
mountStream()
- clarifyRequest({ choices: ['yes', 'no'], question: 'Ship it?', request_id: 'req-1' })
+ clarifyRequest({ questions: [{ choices: ['yes', 'no'], qid: 'q0', question: 'Ship it?' }], request_id: 'req-1' })
const parts = clarifyParts()
expect(parts).toHaveLength(1)
expect(parts[0].type === 'tool-call' && parts[0].toolCallId).toBe('req-1')
expect(parts[0].type === 'tool-call' && parts[0].args).toMatchObject({
- choices: ['yes', 'no'],
- question: 'Ship it?'
+ questions: [{ choices: ['yes', 'no'], question: 'Ship it?' }]
})
})
it('reveals a clarify prompt raised by the active session', () => {
mountStream()
- clarifyRequest({ choices: ['yes', 'no'], question: 'Ship it?', request_id: 'req-reveal' })
+ clarifyRequest({
+ questions: [{ choices: ['yes', 'no'], qid: 'q0', question: 'Ship it?' }],
+ request_id: 'req-reveal'
+ })
expect(scrollToBottom).toHaveBeenCalledOnce()
})
@@ -99,7 +101,10 @@ describe('clarify request stream hydration', () => {
() =>
void stream.handleRequest(
'clarify',
- { choices: ['yes', 'no'], question: 'Ship it?', session_id: 'session-background' },
+ {
+ questions: [{ choices: ['yes', 'no'], qid: 'q0', question: 'Ship it?' }],
+ session_id: 'session-background'
+ },
'req-background'
)
)
@@ -111,13 +116,11 @@ describe('clarify request stream hydration', () => {
mountStream()
clarifyRequest({
- choices: ['read', 'write'],
- multi_select: true,
- question: 'Which permissions?',
+ questions: [{ choices: ['read', 'write'], multi_select: true, qid: 'q0', question: 'Which permissions?' }],
request_id: 'req-multi'
})
- expect($clarifyRequests.get()[SID]?.multiSelect).toBe(true)
+ expect($clarifyRequests.get()[SID]?.questions[0]?.multiSelect).toBe(true)
const part = clarifyParts()[0]
expect(part?.type).toBe('tool-call')
@@ -127,33 +130,10 @@ describe('clarify request stream hydration', () => {
}
expect(part.args).toMatchObject({
- choices: ['read', 'write'],
- multi_select: true,
- question: 'Which permissions?'
+ questions: [{ choices: ['read', 'write'], multi_select: true, question: 'Which permissions?' }]
})
})
- it('merges with the real tool.start row even though its id differs from the request id', () => {
- mountStream()
-
- // Reality: tool.start carries the model's tool_call_id, the clarify request a
- // separately-generated request_id. They must still collapse to ONE card
- // (correlated by question), not two.
- toolStart({ args: { choices: ['a'], question: 'Pick' }, name: 'clarify', tool_id: 'call-abc' })
- clarifyRequest({ choices: ['a'], question: 'Pick', request_id: 'req-2' })
-
- expect(clarifyParts()).toHaveLength(1)
- })
-
- it('does not duplicate when clarify.request arrives before the tool.start row', () => {
- mountStream()
-
- clarifyRequest({ choices: ['a'], question: 'Pick', request_id: 'req-3' })
- toolStart({ args: { choices: ['a'], question: 'Pick' }, name: 'clarify', tool_id: 'call-xyz' })
-
- expect(clarifyParts()).toHaveLength(1)
- })
-
it('re-arms a hydrated Codex tool-only clarify in place instead of appending a second card', () => {
mountStream()
@@ -167,14 +147,14 @@ describe('clarify request stream hydration', () => {
type: 'tool-call',
toolCallId: 'call-codex',
toolName: 'clarify',
- args: { choices: ['a', 'b'], question: 'Pick' },
- argsText: '{"question":"Pick","choices":["a","b"]}'
+ args: { questions: [{ choices: ['a', 'b'], question: 'Pick' }] },
+ argsText: '{"questions":[{"question":"Pick","choices":["a","b"]}]}'
}
]
}
])
- clarifyRequest({ choices: ['a', 'b'], question: 'Pick', request_id: 'req-codex' })
+ clarifyRequest({ questions: [{ choices: ['a', 'b'], qid: 'q0', question: 'Pick' }], request_id: 'req-codex' })
const messages = stream.state().messages
expect(messages).toHaveLength(2)
@@ -197,14 +177,17 @@ describe('clarify request stream hydration', () => {
type: 'tool-call',
toolCallId: 'call-deepseek',
toolName: 'clarify',
- args: { choices: ['safe', 'fast'], question: 'Which path?' },
- argsText: '{"question":"Which path?","choices":["safe","fast"]}'
+ args: { questions: [{ choices: ['safe', 'fast'], question: 'Which path?' }] },
+ argsText: '{"questions":[{"question":"Which path?","choices":["safe","fast"]}]}'
}
]
}
])
- clarifyRequest({ choices: ['safe', 'fast'], question: 'Which path?', request_id: 'req-deepseek' })
+ clarifyRequest({
+ questions: [{ choices: ['safe', 'fast'], qid: 'q0', question: 'Which path?' }],
+ request_id: 'req-deepseek'
+ })
const messages = stream.state().messages
expect(messages).toHaveLength(2)
@@ -228,24 +211,32 @@ describe('clarify request stream hydration', () => {
type: 'tool-call',
toolCallId: 'call-provider',
toolName: 'clarify',
- args: { choices: ['safe', 'fast'], question: 'Which path?' },
- argsText: '{"question":"Which path?","choices":["safe","fast"]}'
+ args: { questions: [{ choices: ['safe', 'fast'], question: 'Which path?' }] },
+ argsText: '{"questions":[{"question":"Which path?","choices":["safe","fast"]}]}'
}
]
}
])
- clarifyRequest({ choices: ['safe', 'fast'], question: 'Which path?', request_id: 'req-ui' })
+ clarifyRequest({
+ questions: [{ choices: ['safe', 'fast'], qid: 'q0', question: 'Which path?' }],
+ request_id: 'req-ui'
+ })
toolComplete({
- args: { choices: ['safe', 'fast'], question: 'Which path?' },
+ args: { questions: [{ choices: ['safe', 'fast'], question: 'Which path?' }] },
name: 'clarify',
- result: { question: 'Which path?', user_response: 'safe' },
+ result: {
+ outcome: 'submitted',
+ responses: [
+ { choices_offered: ['safe', 'fast'], question: 'Which path?', status: 'answered', user_response: 'safe' }
+ ]
+ },
tool_id: 'call-provider'
})
const parts = clarifyParts()
expect(parts).toHaveLength(1)
- expect(parts[0]).toMatchObject({ toolCallId: 'call-provider', result: { user_response: 'safe' } })
+ expect(parts[0]).toMatchObject({ toolCallId: 'call-provider', result: { outcome: 'submitted' } })
})
it('ignores a late clarify.request after the turn was interrupted', () => {
@@ -255,7 +246,7 @@ describe('clarify request stream hydration', () => {
const state = stream.states.get(SID)!
state.interrupted = true
- clarifyRequest({ choices: ['a', 'b'], question: 'Pick', request_id: 'req-late' })
+ clarifyRequest({ questions: [{ choices: ['a', 'b'], qid: 'q0', question: 'Pick' }], request_id: 'req-late' })
expect($clarifyRequests.get()[SID]).toBeUndefined()
expect(stream.state().messages).toHaveLength(1)
@@ -264,8 +255,12 @@ describe('clarify request stream hydration', () => {
it('expires only the matching clarify request and deactivates its card', () => {
mountStream()
- toolStart({ args: { choices: ['a'], question: 'Pick' }, name: 'clarify', tool_id: 'call-provider' })
- clarifyRequest({ choices: ['a'], question: 'Pick', request_id: 'req-expire' })
+ toolStart({
+ args: { questions: [{ choices: ['a'], question: 'Pick' }] },
+ name: 'clarify',
+ tool_id: 'call-provider'
+ })
+ clarifyRequest({ questions: [{ choices: ['a'], qid: 'q0', question: 'Pick' }], request_id: 'req-expire' })
clarifyExpire('req-other')
expect($clarifyRequests.get()[SID]?.requestId).toBe('req-expire')
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
index acb41278a1f..f741bb054c7 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
@@ -12,7 +12,7 @@ import { translateNow } from '@/i18n'
import { restorePendingClarifyToolCall } from '@/lib/chat-messages'
import type { PreviewActAction } from '@/lib/preview-act/act-in-page'
import type { TourAction, TourStep } from '@/lib/tour'
-import { normalizeChoices, normalizeQuestions, setClarifyRequest, warnDroppedChoices } from '@/store/clarify'
+import { normalizeQuestions, setClarifyRequest } from '@/store/clarify'
import type { ScopedServerRequest } from '@/store/gateway'
import { dispatchNativeNotification } from '@/store/native-notifications'
import {
@@ -216,60 +216,38 @@ const clarify: Handler = ctx => {
const p = request.params
if (sessionId && deps.sessionInterrupted(sessionId)) {
- request.respond({ answer: '' })
+ request.respond({})
return
}
- const question = str(p.question)
- const rawChoices = p.choices
- const choices = normalizeChoices(rawChoices)
- const multiSelect = p.multi_select === true
- // Batch (multi-question) clarify: `questions` replaces question/choices on the
- // wire. `answers` rides along only on a reconnect replay (locks the server
- // already accepted).
const questions = normalizeQuestions(p.questions)
+ // `answers` rides along only on a reconnect replay (locks the server
+ // already accepted).
const lockedAnswers =
typeof p.answers === 'object' && p.answers !== null
? Object.fromEntries(
Object.entries(p.answers as Record<string, unknown>).filter(
- (entry): entry is [string, string] => typeof entry[1] === 'string'
+ (entry): entry is [string, null | string] => entry[1] === null || typeof entry[1] === 'string'
)
)
: undefined
- if (questions.length === 0 && !question) {
- request.respond({ answer: '' })
+ if (questions.length === 0) {
+ request.respond({})
return
}
- if (questions.length === 0 && rawChoices != null && choices.length === 0) {
- warnDroppedChoices('gateway', question, rawChoices)
+ const clarifyRequest = {
+ lockedAnswers,
+ questions,
+ receivedAt: Date.now() / 1000,
+ requestId: request.id,
+ sessionId: sessionId || null
}
- const clarifyRequest =
- questions.length > 0
- ? {
- choices: null,
- lockedAnswers,
- multiSelect: false,
- question: '',
- questions,
- receivedAt: Date.now() / 1000,
- requestId: request.id,
- sessionId: sessionId || null
- }
- : {
- choices: choices.length > 0 ? choices : null,
- multiSelect,
- question,
- receivedAt: Date.now() / 1000,
- requestId: request.id,
- sessionId: sessionId || null
- }
-
rememberServerRequest(request)
setClarifyRequest(clarifyRequest)
@@ -301,7 +279,7 @@ const clarify: Handler = ctx => {
}
}
- notifyInput(ctx, questions.length > 0 ? questions.map(q => q.question).join(' · ') : question)
+ notifyInput(ctx, questions.map(q => q.question).join(' · '))
}
const approval: Handler = ctx => {
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 1f619446c4d..5ec44e62886 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
@@ -1298,7 +1298,7 @@ describe('resumeSession failure recovery', () => {
const stateMapRef: MutableRefObject<Map<string, ClientSessionState>> = { current: new Map() }
const toolCall = {
- function: { arguments: '{"question":"Which path?","choices":["safe","fast"]}', name: 'clarify' },
+ function: { arguments: '{"questions":[{"question":"Which path?","choices":["safe","fast"]}]}', name: 'clarify' },
id: 'call-provider'
}
@@ -1317,9 +1317,7 @@ describe('resumeSession failure recovery', () => {
// the caller sees the result; that handler parks the card. Mirror that
// ordering here (no channel in this harness).
setClarifyRequest({
- choices: ['safe', 'fast'],
- multiSelect: false,
- question: 'Which path?',
+ questions: [{ choices: ['safe', 'fast'], multiSelect: false, qid: 'q0', question: 'Which path?' }],
receivedAt: Date.now(),
requestId: 'req-resumed',
sessionId: 'runtime-1'
@@ -1331,7 +1329,11 @@ describe('resumeSession failure recovery', () => {
messages: [],
messages_omitted: true,
open_requests: [
- { id: 'req-resumed', method: 'clarify', params: { choices: ['safe', 'fast'], question: 'Which path?' } }
+ {
+ id: 'req-resumed',
+ method: 'clarify',
+ params: { questions: [{ choices: ['safe', 'fast'], qid: 'q0', question: 'Which path?' }] }
+ }
],
resumed: 'stored-1',
running: true,
@@ -1355,7 +1357,10 @@ describe('resumeSession failure recovery', () => {
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?' })
+ expect($clarifyRequests.get()['runtime-1']).toMatchObject({
+ requestId: 'req-resumed',
+ questions: [{ question: 'Which path?' }]
+ })
})
it('restores a pending batch clarify whose resume snapshot has no top-level question', async () => {
@@ -1393,10 +1398,7 @@ describe('resumeSession failure recovery', () => {
// Request handler parks the batch card (with the server-locked answer)
// from the re-delivered open request before the result lands.
setClarifyRequest({
- choices: null,
lockedAnswers: { q0: 'Blue' },
- multiSelect: false,
- question: '',
questions: questions.map(q => ({ ...q, multiSelect: false })),
receivedAt: Date.now(),
requestId: 'req-batch-resumed',
@@ -1427,7 +1429,6 @@ describe('resumeSession failure recovery', () => {
const request = $clarifyRequests.get()['runtime-1']
expect(request).toMatchObject({
lockedAnswers: { q0: 'Blue' },
- question: '',
requestId: 'req-batch-resumed'
})
expect(request.questions).toHaveLength(2)
@@ -3540,8 +3541,8 @@ describe('resumeSession warm-cache mapping integrity', () => {
type: 'tool-call',
toolCallId: 'call-provider',
toolName: 'clarify',
- args: { choices: ['safe', 'fast'], question: 'Which path?' },
- argsText: '{"question":"Which path?","choices":["safe","fast"]}'
+ args: { questions: [{ choices: ['safe', 'fast'], question: 'Which path?' }] },
+ argsText: '{"questions":[{"question":"Which path?","choices":["safe","fast"]}]}'
}
]
}
@@ -3561,7 +3562,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
tool_calls: [
{
function: {
- arguments: '{"question":"Which path?","choices":["safe","fast"]}',
+ arguments: '{"questions":[{"question":"Which path?","choices":["safe","fast"]}]}',
name: 'clarify'
},
id: 'call-provider'
@@ -3575,9 +3576,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
const requestGateway = vi.fn(async (method: string) => {
if (method === 'session.activate') {
setClarifyRequest({
- choices: ['safe', 'fast'],
- multiSelect: false,
- question: 'Which path?',
+ questions: [{ choices: ['safe', 'fast'], multiSelect: false, qid: 'q0', question: 'Which path?' }],
receivedAt: Date.now(),
requestId: 'req-warm',
sessionId: 'rt-A'
@@ -3589,7 +3588,11 @@ describe('resumeSession warm-cache mapping integrity', () => {
messages: [],
messages_omitted: true,
open_requests: [
- { id: 'req-warm', method: 'clarify', params: { choices: ['safe', 'fast'], question: 'Which path?' } }
+ {
+ id: 'req-warm',
+ method: 'clarify',
+ params: { questions: [{ choices: ['safe', 'fast'], qid: 'q0', question: 'Which path?' }] }
+ }
],
resumed: 'stored-A',
running: true,
@@ -3674,9 +3677,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
const requestGateway = vi.fn(async (method: string) => {
if (method === 'session.activate') {
setClarifyRequest({
- choices: ['safe', 'fast'],
- multiSelect: false,
- question: 'Which path?',
+ questions: [{ choices: ['safe', 'fast'], multiSelect: false, qid: 'q0', question: 'Which path?' }],
receivedAt: Date.now(),
requestId: 'req-navigation',
sessionId: 'rt-A'
@@ -3688,7 +3689,11 @@ describe('resumeSession warm-cache mapping integrity', () => {
messages: [],
messages_omitted: true,
open_requests: [
- { id: 'req-navigation', method: 'clarify', params: { choices: ['safe', 'fast'], question: 'Which path?' } }
+ {
+ id: 'req-navigation',
+ method: 'clarify',
+ params: { questions: [{ choices: ['safe', 'fast'], qid: 'q0', question: 'Which path?' }] }
+ }
],
resumed: 'stored-A',
running: true,
@@ -3739,7 +3744,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
expect(answerable[0].parts).toEqual(
expect.arrayContaining([
expect.objectContaining({
- args: expect.objectContaining({ choices: ['safe', 'fast'], question: 'Which path?' }),
+ args: expect.objectContaining({ questions: [{ choices: ['safe', 'fast'], question: 'Which path?' }] }),
toolCallId: 'req-navigation',
toolName: 'clarify',
type: 'tool-call'
@@ -3818,8 +3823,8 @@ describe('resumeSession warm-cache mapping integrity', () => {
type: 'tool-call',
toolCallId: 'call-provider',
toolName: 'clarify',
- args: { choices: ['safe', 'fast'], question: 'Which path?' },
- argsText: '{"question":"Which path?","choices":["safe","fast"]}'
+ args: { questions: [{ choices: ['safe', 'fast'], question: 'Which path?' }] },
+ argsText: '{"questions":[{"question":"Which path?","choices":["safe","fast"]}]}'
}
]
}
@@ -3831,9 +3836,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
if (keepStore) {
setClarifyRequest({
- choices: ['safe', 'fast'],
- multiSelect: false,
- question: 'Which path?',
+ questions: [{ choices: ['safe', 'fast'], multiSelect: false, qid: 'q0', question: 'Which path?' }],
requestId: 'req-stale',
sessionId: 'rt-A'
})
@@ -3849,7 +3852,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
tool_calls: [
{
function: {
- arguments: '{"question":"Which path?","choices":["safe","fast"]}',
+ arguments: '{"questions":[{"question":"Which path?","choices":["safe","fast"]}]}',
name: 'clarify'
},
id: 'call-provider'
@@ -3932,9 +3935,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
await waitFor(() => expect(requestGateway).toHaveBeenCalledWith('session.activate', expect.anything()))
setClarifyRequest({
- choices: ['new'],
- multiSelect: false,
- question: 'New question?',
+ questions: [{ choices: ['new'], multiSelect: false, qid: 'q0', question: 'New question?' }],
receivedAt: Date.now() / 1000 + 60,
requestId: 'req-newer',
sessionId: 'rt-A'
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
index 3a1a70cd5d8..4888ac31489 100644
--- 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
@@ -33,9 +33,7 @@ describe('restorePendingClarifyFromSnapshot', () => {
it('hands back the card the request handler already parked for a replayed open clarify request', () => {
$clarifyRequests.set({
'sess-1': {
- choices: null,
- multiSelect: false,
- question: 'Proceed?',
+ questions: [{ choices: null, multiSelect: false, qid: 'q0', question: 'Proceed?' }],
receivedAt: resumeStartedAt + 5,
requestId: 'rid1',
sessionId: 'sess-1'
@@ -43,7 +41,9 @@ describe('restorePendingClarifyFromSnapshot', () => {
})
const state = restorePendingClarifyFromSnapshot(
- { open_requests: [{ id: 'rid1', method: 'clarify', params: { question: 'Proceed?' } }] },
+ {
+ open_requests: [{ id: 'rid1', method: 'clarify', params: { questions: [{ qid: 'q0', question: 'Proceed?' }] } }]
+ },
'sess-1',
resumeStartedAt
)
@@ -68,9 +68,7 @@ describe('restorePendingClarifyFromSnapshot', () => {
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',
+ questions: [{ choices: null, multiSelect: false, qid: 'q0', question: 'Old' }],
receivedAt: resumeStartedAt - 10,
requestId: 'old-rid',
sessionId: 'sess-6'
@@ -85,9 +83,7 @@ describe('restorePendingClarifyFromSnapshot', () => {
$clarifyRequests.set({
'sess-6': {
- choices: null,
- multiSelect: false,
- question: 'Newer',
+ questions: [{ choices: null, multiSelect: false, qid: 'q0', question: 'Newer' }],
receivedAt: resumeStartedAt + 1,
requestId: 'new-rid',
sessionId: 'sess-6'
@@ -106,9 +102,6 @@ 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'
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
index f375ac056a8..fb49bc33665 100644
--- 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
@@ -54,19 +54,13 @@ export function restorePendingClarifyFromSnapshot(
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
- },
+ args: {
+ questions: request.questions.map(question => ({
+ choices: question.choices ?? undefined,
+ multi_select: question.multiSelect || undefined,
+ question: question.question
+ }))
+ },
tool_id: request.requestId
}
}
diff --git a/apps/desktop/src/components/assistant-ui/clarify-tool.tsx b/apps/desktop/src/components/assistant-ui/clarify-tool.tsx
deleted file mode 100644
index 44e22adac67..00000000000
--- a/apps/desktop/src/components/assistant-ui/clarify-tool.tsx
+++ /dev/null
@@ -1,1351 +0,0 @@
-'use client'
-
-import { type ToolCallMessagePartProps, useAuiState } from '@assistant-ui/react'
-import { useStore } from '@nanostores/react'
-import {
- type ComponentProps,
- type FormEvent,
- type KeyboardEvent,
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState
-} from 'react'
-
-import { requestComposerFocus, requestComposerInsert } from '@/app/chat/composer/focus'
-import { useSessionView } from '@/app/chat/session-view'
-import { ToolFallback } from '@/components/assistant-ui/tool/fallback'
-import { WIDGET_SHELL_CLASS } from '@/components/chat/widget-shell'
-import { Alert, AlertDescription } from '@/components/ui/alert'
-import { Button } from '@/components/ui/button'
-import { Kbd } from '@/components/ui/kbd'
-import { Loader } from '@/components/ui/loader'
-import { Textarea } from '@/components/ui/textarea'
-import { Tip } from '@/components/ui/tooltip'
-import { useI18n } from '@/i18n'
-import { triggerHaptic } from '@/lib/haptics'
-import { AlertTriangle, CircleLetterA, Loader2, MessageQuestion } from '@/lib/icons'
-import { isSubmitEnter } from '@/lib/ime'
-import { visibleClarifyCard } from '@/lib/keybinds/composer-focus-keys'
-import { cn } from '@/lib/utils'
-import {
- bareChoice,
- type ClarifyQuestion,
- type ClarifyRequest,
- clearClarifyRequest,
- normalizeChoices,
- RECOMMENDED_LABEL,
- sessionClarifyRequest,
- warnDroppedChoices
-} from '@/store/clarify'
-import { $gateway } from '@/store/gateway'
-import { reconnectAction } from '@/store/gateway-reconnect'
-import { notifyError } from '@/store/notifications'
-import { forgetServerRequest, respondToServerRequest } from '@/store/server-requests'
-import { requestForOwnedSession } from '@/store/session-states'
-
-import { handleClarifySubmitShortcut } from './clarify-submit-shortcut'
-import { selectMessageRunning } from './tool/fallback-model'
-import { parseMaybeObject } from './tool/fallback-model/format'
-
-interface ClarifyArgs {
- question?: string
- choices?: string[] | null
- multiSelect?: boolean
- questions?: { question: string; choices?: string[] | null; multiSelect?: boolean }[]
-}
-
-interface ClarifyResult {
- question?: string
- answer?: string
- error?: string
-}
-
-function stringField(row: Record<string, unknown>, ...keys: string[]): string | undefined {
- for (const key of keys) {
- const value = row[key]
-
- if (typeof value === 'string') {
- return value
- }
- }
-}
-
-function readClarifyArgs(args: unknown): ClarifyArgs {
- const row = parseMaybeObject(args)
- const rawChoices = row.choices
- const choices = normalizeChoices(rawChoices)
-
- const question = stringField(row, 'question')
-
- if (rawChoices != null && choices.length === 0 && question) {
- warnDroppedChoices('tool_args', question, rawChoices)
- }
-
- // Batch form: tool args carry the model's questions array. Entries are
- // normalized leniently here (qid comes from the gateway request, not args).
- let questions: ClarifyArgs['questions']
-
- if (Array.isArray(row.questions)) {
- const parsed = row.questions
- .map(entry => {
- const item = parseMaybeObject(entry)
- const text = stringField(item, 'question')
-
- if (!text) {
- return null
- }
-
- const itemChoices = normalizeChoices(item.choices)
-
- return {
- choices: itemChoices.length > 0 ? itemChoices : null,
- multiSelect: item.multi_select === true && itemChoices.length > 0,
- question: text
- }
- })
- .filter((entry): entry is NonNullable<typeof entry> => entry !== null)
-
- if (parsed.length > 0) {
- questions = parsed
- }
- }
-
- return {
- question,
- choices: choices.length > 0 ? choices : null,
- multiSelect: row.multi_select === true,
- questions
- }
-}
-
-interface ClarifyBatchResponse {
- id?: string
- question?: string
- answer?: string | string[]
-}
-
-/** Parse batch clarify tool JSON (`responses` array + optional timed_out). */
-export function readClarifyBatchResult(result: unknown): {
- responses: ClarifyBatchResponse[]
- timedOut: boolean
-} {
- const row = parseMaybeObject(result)
-
- if (!Array.isArray(row.responses)) {
- return { responses: [], timedOut: false }
- }
-
- const responses = row.responses.map((entry): ClarifyBatchResponse => {
- const item = parseMaybeObject(entry)
- const answer = item.user_response
-
- return {
- answer: Array.isArray(answer) ? answer.map(String) : typeof answer === 'string' ? answer : undefined,
- id: stringField(item, 'id'),
- question: stringField(item, 'question')
- }
- })
-
- return { responses, timedOut: row.timed_out === true }
-}
-
-/** Parse clarify tool JSON (`question` + `user_response`). */
-export function readClarifyResult(result: unknown): ClarifyResult {
- const row = parseMaybeObject(result)
-
- if (Object.keys(row).length === 0) {
- return typeof result === 'string' && result.trim() ? { answer: result.trim() } : {}
- }
-
- return {
- question: stringField(row, 'question'),
- answer: stringField(row, 'user_response', 'answer'),
- error: stringField(row, 'error')
- }
-}
-
-const letterFor = (index: number): string => String.fromCharCode(65 + index)
-
-// The backend tags the agent's preferred option (`mark_recommended`); the card
-// renders the label in tertiary text so the option itself still reads first.
-function ChoiceLabel({ choice }: { choice: string }) {
- const bare = bareChoice(choice)
-
- if (bare === choice) {
- return <>{choice}</>
- }
-
- return (
- <>
- {bare} <span className="text-(--ui-text-tertiary)">{RECOMMENDED_LABEL}</span>
- </>
- )
-}
-
-const OPTION_ROW_CLASS =
- 'flex w-full items-start gap-2 rounded-[0.25rem] px-1.5 py-1 text-left disabled:cursor-not-allowed disabled:opacity-50'
-
-// field-sizing on top of Textarea's shared chrome; kill min-h-16 for one-liners.
-const CLARIFY_TEXTAREA_CLASS = 'field-sizing-content max-h-40 min-h-0 resize-none'
-
-const CLARIFY_SHELL_CLASS = `${WIDGET_SHELL_CLASS} text-[length:var(--conversation-text-font-size)] text-(--ui-text-primary)`
-
-const CLARIFY_ICON_CLASS = 'mt-px size-4 shrink-0 text-(--ui-text-tertiary)'
-
-function ClarifyShell({ children, className, ...props }: ComponentProps<'div'>) {
- return (
- <div className={cn(CLARIFY_SHELL_CLASS, className)} data-slot="clarify-inline" {...props}>
- {children}
- </div>
- )
-}
-
-function ClarifyLine({
- children,
- className,
- icon: Icon,
- ...props
-}: ComponentProps<'div'> & { icon: typeof MessageQuestion }) {
- return (
- <div className={cn('flex items-start gap-2', className)} {...props}>
- <div className="min-w-0 flex-1">{children}</div>
- <Icon aria-hidden className={CLARIFY_ICON_CLASS} />
- </div>
- )
-}
-
-function KeyBadge({
- char,
- disabled,
- preview,
- selected
-}: {
- char: string
- disabled?: boolean
- preview?: boolean
- selected: boolean
-}) {
- // The "Other" row is a <label>, which has no :disabled state of its own —
- // dim its badge alongside the disabled textarea so it matches the options.
- return (
- <Kbd
- className={cn(
- 'mt-px',
- disabled && 'opacity-50',
- selected && 'border-primary bg-primary text-white shadow-none',
- !selected && preview && 'border-primary text-primary shadow-none'
- )}
- size="sm"
- >
- {char}
- </Kbd>
- )
-}
-
-/** A letter-badged option row. Shared by the live pending card (where a click
- * selects an answer) and the settled skip card (where a click drafts a
- * follow-up), so both stay visually identical. */
-function ChoiceButton({
- active = false,
- char,
- choice,
- disabled,
- keyShortcuts,
- onClick,
- selected,
- title
-}: {
- active?: boolean
- char: string
- choice: string
- disabled?: boolean
- keyShortcuts?: string
- onClick: () => void
- selected?: boolean
- title?: string
-}) {
- // `Tip` is the repo's themed replacement for native `title=` (a native
- // tooltip on a <button> is banned by the no-native-title guard). It renders
- // the child untouched when `label` is falsy, so the live card (no tip) is
- // unaffected and only the settled skip card gets the hover hint.
- //
- // `active` is the keyboard cursor on the live card (arrow-key navigation);
- // it highlights the row and previews its key badge. The settled skip card
- // never passes it, so its rows stay plain.
- return (
- <Tip label={title}>
- <button
- aria-current={active || undefined}
- aria-keyshortcuts={keyShortcuts}
- aria-pressed={selected}
- className={cn(
- OPTION_ROW_CLASS,
- 'text-(--ui-text-secondary) hover:bg-(--chrome-action-hover) hover:text-(--ui-text-primary)',
- active && 'bg-(--chrome-action-hover) text-(--ui-text-primary)',
- selected && 'text-(--ui-text-primary)'
- )}
- data-choice
- data-highlighted={active || undefined}
- disabled={disabled}
- onClick={onClick}
- type="button"
- >
- <KeyBadge char={char} preview={active} selected={Boolean(selected)} />
- <span className="flex-1 wrap-anywhere">
- <ChoiceLabel choice={choice} />
- </span>
- </button>
- </Tip>
- )
-}
-
-export const ClarifyTool = (props: ToolCallMessagePartProps) => {
- // Answered → settled Q&A (ToolFallback collapsed the answer away).
- if (props.result !== undefined) {
- return <ClarifyToolSettled {...props} />
- }
-
- return <ClarifyToolPending {...props} />
-}
-
-function ClarifyToolSettled(props: ToolCallMessagePartProps) {
- const batch = readClarifyBatchResult(props.result)
-
- if (batch.responses.length > 0) {
- return <ClarifyToolBatchSettled responses={batch.responses} />
- }
-
- return <ClarifyToolSingleSettled {...props} />
-}
-
-function ClarifyToolSingleSettled({ args, result }: ToolCallMessagePartProps) {
- const { t } = useI18n()
- const copy = t.assistant.clarify
- const fromArgs = useMemo(() => readClarifyArgs(args), [args])
- const fromResult = useMemo(() => readClarifyResult(result), [result])
-
- const question = fromResult.question || fromArgs.question || ''
- const answer = fromResult.answer
- const error = fromResult.error
- const skipped = !error && answer !== undefined && !answer.trim()
- const answerText = error || (skipped ? copy.skipped : (answer ?? '').trim())
- const choices = fromArgs.choices ?? []
-
- // A skipped (timed-out) clarify keeps its choices on screen and actionable.
- // The blocking request is long gone — the tool already returned empty — so a
- // pick can't resolve it retroactively. Instead it drafts a quoted follow-up
- // into the composer (Enter sends; if the agent is mid-turn it queues like
- // any other prompt). Without this the card collapsed to just "Skipped" and
- // the options were unrecoverable.
- const followUp = useCallback(
- (choice: string) => {
- requestComposerInsert(copy.lateAnswer(question, choice), { mode: 'block' })
- requestComposerFocus()
- triggerHaptic('selection')
- },
- [copy, question]
- )
-
- return (
- <ClarifyShell className="my-1.5 grid gap-1.5" data-clarify-settled="">
- {question ? (
- <ClarifyLine icon={MessageQuestion}>
- <span className="whitespace-pre-wrap font-medium leading-(--conversation-line-height)">{question}</span>
- </ClarifyLine>
- ) : null}
- {answerText ? (
- <ClarifyLine icon={CircleLetterA}>
- <p
- className={cn(
- 'whitespace-pre-wrap leading-(--conversation-line-height)',
- error ? 'text-destructive' : 'text-(--ui-text-secondary)',
- skipped && 'italic text-(--ui-text-tertiary)'
- )}
- data-clarify-answer=""
- >
- {answerText}
- </p>
- </ClarifyLine>
- ) : null}
- {skipped && choices.length > 0 ? (
- <div className="grid gap-px" data-clarify-late-choices="" role="group">
- {choices.map((choice, index) => (
- <ChoiceButton
- char={letterFor(index)}
- choice={choice}
- key={`${index}-${choice}`}
- onClick={() => followUp(choice)}
- title={copy.lateAnswerTip}
- />
- ))}
- <p className="px-1.5 pt-0.5 text-[0.6875rem] leading-4 text-(--ui-text-tertiary)">{copy.lateAnswerHint}</p>
- </div>
- ) : null}
- </ClarifyShell>
- )
-}
-
-/** How long a painted card may wait for its gateway request before asking the
- * backend to re-deliver it. `clarify.request` normally trails `tool.start` by
- * a tick; seconds of silence mean the frame was lost on the way. */
-const CLARIFY_DELIVERY_GRACE_MS = 4_000
-
-/**
- * True once the card has waited past the grace period for a request that
- * never arrived, and a re-delivery attempt found nothing (#98645).
- *
- * The attempt asks the owner socket for `session.events.since` from the end
- * of the ring: no events come back, but the channel re-delivers the
- * session's `open_requests` to the request handlers before the call
- * resolves, so a request the backend still holds parks and the card goes
- * live on its own.
- */
-function useUndeliveredClarify(sessionId: null | string, waiting: boolean): boolean {
- const [undelivered, setUndelivered] = useState(false)
-
- useEffect(() => {
- if (!waiting || !sessionId) {
- return
- }
-
- let cancelled = false
-
- const timer = window.setTimeout(async () => {
- const gateway = $gateway.get()
-
- if (gateway) {
- try {
- await requestForOwnedSession(
- sessionId,
- gateway.request.bind(gateway) as typeof gateway.request,
- 'session.events.since',
- {
- last_seen: Number.MAX_SAFE_INTEGER,
- session_id: sessionId
- }
- )
- } catch {
- // An older backend or a dropped socket: the notice is still right.
- }
- }
-
- if (!cancelled && !sessionClarifyRequest(sessionId).get()) {
- setUndelivered(true)
- }
- }, CLARIFY_DELIVERY_GRACE_MS)
-
- return () => {
- cancelled = true
- window.clearTimeout(timer)
- setUndelivered(false)
- }
- }, [sessionId, waiting])
-
- return waiting && undelivered
-}
-
-function ClarifyToolPending(props: ToolCallMessagePartProps) {
- // The tool row is in whichever session's transcript rendered it — read THAT
- // session's clarify (primary or tile), not the globally-active one.
- const sessionId = useStore(useSessionView().$runtimeId)
- const $request = useMemo(() => sessionClarifyRequest(sessionId), [sessionId])
- const request = useStore($request)
- const fromArgs = useMemo(() => readClarifyArgs(props.args), [props.args])
- const messageRunning = useAuiState(selectMessageRunning)
- // Answering clears the request a beat before `tool.complete` swaps in the
- // settled card. Latch submit so that gap doesn't demote; Stop also clears
- // the request and must still collapse an unanswered card.
- const [answered, setAnswered] = useState(false)
- const undelivered = useUndeliveredClarify(sessionId, messageRunning && !request && !answered)
-
- // Stopped mid-prompt with no result — don't leave a dead interactive panel.
- // `session.info` reports running=false while clarify is blocking, so the
- // running flag alone would remount the question as a tool row. Keep the
- // card while a request is open or this instance already submitted.
- if (!messageRunning && !request && !answered) {
- return <ToolFallback {...props} />
- }
-
- // Batch: the gateway request carries qid-keyed questions. Args alone can't
- // drive the form (no qids to respond with), so the live form waits for the
- // request — but the question TEXT is already in the tool args, so paint a
- // disabled preview immediately instead of a spinner (the single-question
- // card does the same while request_id races the tool block).
- if (request?.questions?.length || fromArgs.questions) {
- return (
- <ClarifyToolBatchPending
- fromArgs={fromArgs}
- onAnswered={() => setAnswered(true)}
- request={request}
- undelivered={undelivered}
- />
- )
- }
-
- return (
- <ClarifyToolSinglePending
- fromArgs={fromArgs}
- onAnswered={() => setAnswered(true)}
- request={request}
- undelivered={undelivered}
- />
- )
-}
-
-/** Heads a card whose request never reached this window: nothing on it can
- * answer, so say so and point at the way out instead of a silent wait. */
-function UndeliveredNotice() {
- const { t } = useI18n()
-
- return (
- <Alert className="gap-x-2 px-3 py-2 text-xs" role="status" variant="warning">
- <AlertTriangle />
- <AlertDescription>{t.assistant.clarify.notDelivered}</AlertDescription>
- </Alert>
- )
-}
-
-function ClarifyToolSinglePending({
- fromArgs,
- onAnswered,
- request,
- undelivered
-}: {
- fromArgs: ClarifyArgs
- onAnswered: () => void
- request: ClarifyRequest | null
- undelivered: boolean
-}) {
- const { t } = useI18n()
- const copy = t.assistant.clarify
- const gateway = useStore($gateway)
-
- const matchingRequest = useMemo(() => {
- if (!request || request.questions?.length) {
- return null
- }
-
- if (fromArgs.question && request.question && fromArgs.question !== request.question) {
- return null
- }
-
- return request
- }, [fromArgs.question, request])
-
- const question = fromArgs.question || matchingRequest?.question || ''
-
- const choices = useMemo(
- // Prefer the gateway request's choices over the raw tool args: the backend
- // labels the recommended option there (`mark_recommended`), and the card
- // only renders once `matchingRequest` exists, so the args are a fallback
- // for a hydration race, not the normal path.
- () => matchingRequest?.choices ?? fromArgs.choices ?? [],
- [fromArgs.choices, matchingRequest?.choices]
- )
-
- const hasChoices = choices.length > 0
- const multiSelect = hasChoices && Boolean(matchingRequest?.multiSelect ?? fromArgs.multiSelect)
-
- const [draft, setDraft] = useState('')
- const [submitting, setSubmitting] = useState(false)
- const [selectedChoices, setSelectedChoices] = useState<string[]>([])
- // The keyboard cursor. Indices 0..choices.length-1 are the options; the
- // trailing index (=== choices.length) is the "Other" free-text row.
- const [activeIndex, setActiveIndex] = useState(0)
- const [otherFocused, setOtherFocused] = useState(false)
- const textareaRef = useRef<HTMLTextAreaElement | null>(null)
- // Identity for the visible-card check below — this is the element carrying
- // `data-clarify-choices`, i.e. the one `visibleClarifyCard()` resolves.
- const formRef = useRef<HTMLFormElement | null>(null)
-
- // Race: tool.start fires a tick before clarify.request, so request_id
- // arrives slightly after the tool block mounts. If the question text is
- // already in the tool args, paint the card immediately (disabled until
- // the request is wired) — a spinner→question swap is a layout jump for
- // no reason. Only spin when we have nothing to show yet.
- const ready = Boolean(matchingRequest?.requestId)
- const loading = !ready && !submitting && !question
-
- const respond = useCallback(
- async (answer: string) => {
- if (!ready || !matchingRequest) {
- notifyError(new Error(copy.notReady), copy.sendFailed)
-
- return
- }
-
- if (!gateway) {
- notifyError(new Error(copy.gatewayDisconnected), copy.sendFailed, { action: reconnectAction() })
-
- return
- }
-
- setSubmitting(true)
-
- try {
- // The response frame goes back over the socket the request arrived on —
- // the owner backend by construction (#91684's class cannot recur).
- respondToServerRequest(matchingRequest.requestId, { answer })
- triggerHaptic('submit')
- onAnswered()
- clearClarifyRequest(matchingRequest.requestId, matchingRequest.sessionId)
- // tool.complete lands next → ClarifyToolSettled.
- } catch (error) {
- notifyError(error, copy.sendFailed)
- setSubmitting(false)
- }
- },
- [copy.gatewayDisconnected, copy.notReady, copy.sendFailed, gateway, matchingRequest, onAnswered, ready]
- )
-
- const trimmedDraft = draft.trim()
- // The answer is whichever input is active: a picked choice, or typed text.
- // Picking a choice no longer fires immediately — it selects, then the user
- // confirms with Continue (or Enter from the field). Multi-select treats the
- // typed text as one more answer alongside whatever is already picked.
- const multiSelectAnswers = multiSelect && trimmedDraft ? [...selectedChoices, trimmedDraft] : selectedChoices
-
- const selectedAnswer = multiSelect
- ? multiSelectAnswers.length > 0
- ? JSON.stringify(multiSelectAnswers)
- : null
- : (selectedChoices[0] ?? null)
-
- const pendingAnswer = selectedAnswer ?? (trimmedDraft || null)
-
- const selectChoice = useCallback(
- (choice: string, index: number) => {
- // Picking a choice and typing are mutually exclusive answers in
- // single-select; multi-select keeps the typed text as one more answer.
- if (!multiSelect) {
- setDraft('')
- }
-
- setSelectedChoices(selected => {
- if (!multiSelect) {
- return [choice]
- }
-
- return selected.includes(choice) ? selected.filter(value => value !== choice) : [...selected, choice]
- })
- setActiveIndex(index)
- },
- [multiSelect]
- )
-
- // Keep the cursor in range when the choice set changes (never past "Other").
- useEffect(() => {
- setActiveIndex(index => Math.min(index, choices.length))
- }, [choices.length])
-
- const moveActive = useCallback(
- (delta: number) => {
- const itemCount = choices.length + 1
-
- // Arrow navigation is a move, not a pick. Multi-select keeps staged
- // choices and the typed text while the cursor moves so the user can
- // build a set; the single-select path retains its existing
- // clear-on-navigation behaviour.
- if (!multiSelect) {
- setDraft('')
- setSelectedChoices([])
- }
-
- setActiveIndex(index => (index + delta + itemCount) % itemCount)
- },
- [choices.length, multiSelect]
- )
-
- const submitAnswer = useCallback(() => {
- if (pendingAnswer) {
- void respond(pendingAnswer)
- }
- }, [pendingAnswer, respond])
-
- const activateActive = useCallback(() => {
- const choice = choices[activeIndex]
-
- // Multi-select Enter toggles the highlighted choice. The user confirms the
- // staged set explicitly with Continue so this path never submits a scalar.
- if (multiSelect && choice) {
- selectChoice(choice, activeIndex)
-
- return
- }
-
- // A staged answer (picked choice or typed text) wins — confirm it.
- if (pendingAnswer) {
- submitAnswer()
-
- return
- }
-
- // Otherwise act on the highlighted row: a choice responds immediately, and
- // the trailing "Other" row focuses the free-text field.
- if (choice) {
- void respond(choice)
-
- return
- }
-
- textareaRef.current?.focus()
- }, [activeIndex, choices, multiSelect, pendingAnswer, respond, selectChoice, submitAnswer])
-
- const handleTextareaKey = useCallback(
- (event: KeyboardEvent<HTMLTextAreaElement>) => {
- if (isSubmitEnter(event) && !event.shiftKey) {
- event.preventDefault()
- submitAnswer()
- }
- },
- [submitAnswer]
- )
-
- const handleSubmit = useCallback(
- (event: FormEvent<HTMLFormElement>) => {
- event.preventDefault()
- submitAnswer()
- },
- [submitAnswer]
- )
-
- // Arrow keys move a visual cursor, 1-9 and A/B/C… pick directly, and Enter
- // confirms the current answer (or acts on the highlighted row). A focused
- // choice row stays in this handler so Enter reaches activateActive: that
- // submits a staged single-select answer and toggles a multi-select row.
- // Every other focused control (the Other box, Skip, Continue, the composer)
- // keeps its own keys. Inactive cards stand down too — the binding is
- // window-wide but the answer is session-specific.
- useEffect(() => {
- if (!ready || !hasChoices || submitting) {
- return
- }
-
- const onKeyDown = (event: globalThis.KeyboardEvent) => {
- if (event.metaKey || event.ctrlKey || event.altKey || event.defaultPrevented) {
- return
- }
-
- // Not the visible card ⇒ not our keystroke. Inactive tabs stay MOUNTED,
- // so every parked clarify keeps a live `window` listener; without this the
- // card that acts is whichever mounted first, and answering the question in
- // front of you silently answers a background session's question instead —
- // resuming an agent turn the user never saw. Same resolver the composer's
- // `clarifyCardOwnsKey` yields to, so the two cannot disagree about which
- // card is live.
- if (visibleClarifyCard() !== formRef.current) {
- return
- }
-
- const active = document.activeElement as HTMLElement | null
-
- if (
- active &&
- (active.isContentEditable ||
- (active.matches('a[href], button, input, select, textarea, [role="button"]') &&
- // Choice rows stay in this handler so Enter reaches activateActive.
- // That submits a staged single-select answer and toggles a
- // multi-select row. Skip, Continue, and the Other field stay
- // hands-off.
- !active.matches('button[data-choice]')))
- ) {
- return
- }
-
- if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
- event.preventDefault()
- moveActive(event.key === 'ArrowDown' ? 1 : -1)
-
- return
- }
-
- if (/^[1-9]$/.test(event.key)) {
- const index = Number(event.key) - 1
-
- if (index < choices.length) {
- event.preventDefault()
- selectChoice(choices[index], index)
- } else if (index === choices.length) {
- event.preventDefault()
- setActiveIndex(index)
- textareaRef.current?.focus()
- }
-
- return
- }
-
- const key = event.key.toLowerCase()
-
- // Only the letters this card actually renders a row for. Anything past
- // the last row belongs to the composer — the user is typing a message
- // instead of picking an option, and swallowing the keystroke here would
- // make the first letter of it vanish.
- if (key.length === 1 && key >= 'a' && key <= 'z') {
- const index = key.charCodeAt(0) - 97
-
- if (index < choices.length) {
- event.preventDefault()
- selectChoice(choices[index], index)
- } else if (index === choices.length) {
- event.preventDefault()
- setActiveIndex(index)
- textareaRef.current?.focus()
- }
-
- return
- }
-
- if (event.key === 'Enter') {
- event.preventDefault()
- activateActive()
- }
- }
-
- window.addEventListener('keydown', onKeyDown)
-
- return () => window.removeEventListener('keydown', onKeyDown)
- }, [activateActive, choices, hasChoices, moveActive, ready, selectChoice, submitting])
-
- if (loading) {
- return (
- <ClarifyShell aria-label={copy.loadingQuestion} className="my-1.5 grid min-h-12 place-items-center" role="status">
- <Loader aria-hidden="true" className="size-6 text-(--ui-text-tertiary)" role="presentation" type="rose-curve" />
- </ClarifyShell>
- )
- }
-
- const onDraftChange = (value: string) => {
- setDraft(value)
-
- // Typing is its own answer — drop any picked choice so the two inputs can't
- // both look selected. Multi-select allows both: the typed text becomes an
- // additional answer instead of replacing the picked choices.
- if (value.trim() && !multiSelect) {
- setSelectedChoices([])
- }
- }
-
- return (
- // `data-clarify-choices` marks the panel as owning its OWN shortcut keys
- // (Enter, and 1..N+1 / A.. for the N choices plus "Other") while they're
- // live, so the global type-to-focus listener (`clarifyCardOwnsKey`) yields
- // exactly those and lets every other printable through to the composer —
- // typing a real message instead of picking an option stays possible. The
- // value is the choice count so the check needs no store access.
- //
- // The form is the outer element so the actions can sit OUTSIDE the card and
- // still submit it — the panel holds the question, the buttons ride below it.
- <form
- className="my-1.5 grid gap-4"
- data-clarify-choices={hasChoices ? choices.length : undefined}
- onKeyDownCapture={handleClarifySubmitShortcut}
- onSubmit={handleSubmit}
- ref={formRef}
- >
- <ClarifyShell className="grid gap-2">
- <div className="flex items-start gap-2">
- <span className="flex-1 whitespace-pre-wrap font-medium leading-(--conversation-line-height)">
- {question}
- </span>
- <MessageQuestion aria-hidden className="mt-px size-4 shrink-0 text-(--ui-text-tertiary)" />
- </div>
- {undelivered ? <UndeliveredNotice /> : null}
-
- {hasChoices ? (
- <div className="grid gap-px" role="group">
- {choices.map((choice, index) => (
- <ChoiceButton
- active={!undelivered && activeIndex === index}
- char={letterFor(index)}
- choice={choice}
- disabled={submitting || !ready}
- key={`${index}-${choice}`}
- keyShortcuts={`${letterFor(index)} ${index + 1}`}
- onClick={() => selectChoice(choice, index)}
- selected={selectedChoices.includes(choice)}
- />
- ))}
- <label
- className={cn(
- OPTION_ROW_CLASS,
- 'items-center',
- !undelivered && activeIndex === choices.length && 'bg-(--chrome-action-hover)'
- )}
- data-highlighted={(!undelivered && activeIndex === choices.length) || undefined}
- >
- <KeyBadge
- char={letterFor(choices.length)}
- disabled={submitting || !ready}
- preview={!undelivered && (otherFocused || activeIndex === choices.length)}
- selected={Boolean(trimmedDraft)}
- />
- <Textarea
- aria-current={activeIndex === choices.length || undefined}
- aria-keyshortcuts={`${letterFor(choices.length)} ${choices.length + 1}`}
- className={CLARIFY_TEXTAREA_CLASS}
- disabled={submitting || !ready}
- onBlur={() => setOtherFocused(false)}
- onChange={event => onDraftChange(event.target.value)}
- onFocus={() => {
- if (!multiSelect) {
- setSelectedChoices([])
- }
-
- setActiveIndex(choices.length)
- setOtherFocused(true)
- }}
- onKeyDown={handleTextareaKey}
- placeholder={copy.other}
- ref={textareaRef}
- rows={1}
- size="sm"
- value={draft}
- />
- </label>
- </div>
- ) : (
- <Textarea
- className={CLARIFY_TEXTAREA_CLASS}
- disabled={submitting || !ready}
- onChange={event => onDraftChange(event.target.value)}
- onKeyDown={handleTextareaKey}
- placeholder={copy.placeholder}
- ref={textareaRef}
- rows={1}
- size="sm"
- value={draft}
- />
- )}
- </ClarifyShell>
-
- {/* Nothing here can answer an undelivered request — drop the actions
- like the settled card does rather than leave a dead primary button. */}
- {undelivered ? null : (
- <div className="flex items-center justify-end gap-1">
- <Button
- disabled={submitting || !ready}
- onClick={() => void respond('')}
- size="xs"
- type="button"
- variant="text"
- >
- {copy.skip}
- </Button>
- <Button disabled={submitting || !ready || !pendingAnswer} size="xs" type="submit">
- {submitting ? (
- <Loader2 className="animate-spin" />
- ) : (
- <>
- {copy.continueLabel}
- <span aria-hidden className="ml-0.5 text-[0.625rem] opacity-70">
- ⏎
- </span>
- </>
- )}
- </Button>
- </div>
- )}
- </form>
- )
-}
-
-// ─── Batch (multi-question) clarify ─────────────────────────────────────────
-
-/** Settled batch card: every question with its locked (or absent) answer. */
-function ClarifyToolBatchSettled({ responses }: { responses: { question?: string; answer?: string | string[] }[] }) {
- const { t } = useI18n()
- const copy = t.assistant.clarify
-
- return (
- <ClarifyShell className="my-1.5 grid gap-2.5" data-clarify-settled="">
- {responses.map((row, index) => {
- const answer = Array.isArray(row.answer) ? row.answer.join(', ') : (row.answer ?? '')
- const blank = !answer.trim()
-
- return (
- <div className="grid gap-1" key={`${index}-${row.question ?? ''}`}>
- {row.question ? (
- <ClarifyLine icon={MessageQuestion}>
- <span className="whitespace-pre-wrap font-medium leading-(--conversation-line-height)">
- {row.question}
- </span>
- </ClarifyLine>
- ) : null}
- <ClarifyLine icon={CircleLetterA}>
- <p
- className={cn(
- 'whitespace-pre-wrap leading-(--conversation-line-height)',
- blank ? 'italic text-(--ui-text-tertiary)' : 'text-(--ui-text-secondary)'
- )}
- data-clarify-answer=""
- >
- {blank ? copy.skipped : answer}
- </p>
- </ClarifyLine>
- </div>
- )
- })}
- </ClarifyShell>
- )
-}
-
-/** One question's interactive block inside the live batch card. */
-function BatchQuestionBlock({
- disabled,
- locked,
- onDraft,
- onToggle,
- question,
- staged
-}: {
- disabled: boolean
- locked: boolean
- onDraft: (value: string) => void
- onToggle: (choice: string) => void
- question: ClarifyQuestion
- staged: { choices: string[]; draft: string }
-}) {
- const { t } = useI18n()
- const copy = t.assistant.clarify
- const choices = question.choices ?? []
-
- return (
- <div className="grid gap-1" data-clarify-batch-question={question.qid} data-locked={locked || undefined}>
- <div className="flex items-start gap-2">
- <span className="flex-1 whitespace-pre-wrap font-medium leading-(--conversation-line-height)">
- {question.question}
- </span>
- {locked ? (
- <span className="shrink-0 rounded-sm bg-(--chrome-action-hover) px-1 py-px text-[0.625rem] text-(--ui-text-tertiary)">
- ✓ {copy.answeredBadge}
- </span>
- ) : null}
- </div>
-
- {choices.length > 0 ? (
- <div className="grid gap-px" role="group">
- {choices.map((choice, index) => (
- <ChoiceButton
- char={letterFor(index)}
- choice={choice}
- disabled={disabled}
- key={`${index}-${choice}`}
- onClick={() => onToggle(choice)}
- selected={staged.choices.includes(choice)}
- />
- ))}
- <label className={cn(OPTION_ROW_CLASS, 'items-center')}>
- <KeyBadge char={letterFor(choices.length)} disabled={disabled} selected={Boolean(staged.draft.trim())} />
- <Textarea
- className={CLARIFY_TEXTAREA_CLASS}
- disabled={disabled}
- onChange={event => onDraft(event.target.value)}
- placeholder={copy.other}
- rows={1}
- size="sm"
- value={staged.draft}
- />
- </label>
- </div>
- ) : (
- <Textarea
- className={CLARIFY_TEXTAREA_CLASS}
- disabled={disabled}
- onChange={event => onDraft(event.target.value)}
- placeholder={copy.placeholder}
- rows={1}
- size="sm"
- value={staged.draft}
- />
- )}
- </div>
- )
-}
-
-const emptyStage = { choices: [] as string[], draft: '' }
-
-/** Live batch card: all questions at once, staged locally, ONE confirm.
- * Picks and drafts stay in component state — nothing reaches the server
- * until every question has a staged answer and the user presses the single
- * "Confirm and continue" button, which sends the per-question locks
- * back-to-back and completes the batch. Staged answers stay editable up to
- * that moment. The per-question wire protocol is unchanged (the TUI/CLI
- * still lock incrementally); this card just batches its locks at the end. */
-function ClarifyToolBatchPending({
- fromArgs,
- onAnswered,
- request,
- undelivered
-}: {
- fromArgs?: ClarifyArgs
- onAnswered: () => void
- request: ClarifyRequest | null
- undelivered: boolean
-}) {
- const { t } = useI18n()
- const copy = t.assistant.clarify
- const gateway = useStore($gateway)
-
- // qids only exist on the gateway request — args are a hydration-race
- // fallback for display, never answerable (no ids to respond with).
- const liveQuestions = request?.questions ?? []
- const ready = Boolean(request?.requestId) && liveQuestions.length > 0
-
- // Preview items from the tool args: same question text/choices, synthetic
- // qids, shown disabled until the live request lands (or indefinitely when
- // the caller has no gateway request at all — e.g. an external tool call —
- // so the user sees the question instead of an endless spinner). ONE form
- // renders both states: every control is disabled while !ready, so nothing
- // is ever staged under a synthetic qid and the swap to live qids is clean.
- const previewQuestions: ClarifyQuestion[] = useMemo(
- () =>
- (fromArgs?.questions ?? []).map((entry, index) => ({
- choices: entry.choices ?? null,
- multiSelect: entry.multiSelect ?? false,
- qid: `args-${index}`,
- question: entry.question
- })),
- [fromArgs]
- )
-
- const questions = ready ? liveQuestions : previewQuestions
-
- const [staged, setStaged] = useState<Record<string, { choices: string[]; draft: string }>>({})
- const [submitting, setSubmitting] = useState(false)
-
- // Reconnect replay: answers the server already locked (an earlier window's
- // partial progress) pre-stage their questions so the restored card shows
- // them selected instead of blank.
- useEffect(() => {
- const lockedAnswers = request?.lockedAnswers
-
- if (!lockedAnswers) {
- return
- }
-
- setStaged(current => {
- const next = { ...current }
-
- for (const question of questions) {
- const answer = lockedAnswers[question.qid]
-
- if (answer === undefined || next[question.qid]) {
- continue
- }
-
- const options = question.choices ?? []
- let replayedAnswers = [answer]
-
- if (question.multiSelect) {
- try {
- const parsed = JSON.parse(answer)
-
- if (Array.isArray(parsed) && parsed.every(value => typeof value === 'string')) {
- replayedAnswers = parsed
- }
- } catch {
- // Older/non-JSON replies remain a one-value replay below.
- }
- }
-
- const matchedChoices = options.filter(choice => replayedAnswers.includes(bareChoice(choice)))
- next[question.qid] =
- matchedChoices.length > 0 ? { choices: matchedChoices, draft: '' } : { choices: [], draft: answer }
- }
-
- return next
- })
- // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed by the replay map only
- }, [request?.lockedAnswers])
-
- const stageFor = (qid: string) => staged[qid] ?? emptyStage
-
- const stagedAnswer = useCallback(
- (question: ClarifyQuestion): string | null => {
- const stage = staged[question.qid] ?? emptyStage
- const draft = stage.draft.trim()
-
- if (question.multiSelect) {
- // The typed text is an additional answer, not a replacement for the
- // staged choices.
- const combined = [...stage.choices.map(bareChoice), ...(draft ? [draft] : [])]
-
- return combined.length > 0 ? JSON.stringify(combined) : null
- }
-
- if (stage.choices.length > 0) {
- return bareChoice(stage.choices[0])
- }
-
- return draft ? draft : null
- },
- [staged]
- )
-
- const answeredCount = questions.filter(q => stagedAnswer(q) !== null).length
- const allStaged = answeredCount === questions.length
-
- const confirmAll = useCallback(async () => {
- if (!request || !gateway) {
- notifyError(
- new Error(request ? copy.gatewayDisconnected : copy.notReady),
- copy.sendFailed,
- request ? { action: reconnectAction() } : {}
- )
-
- return
- }
-
- setSubmitting(true)
-
- try {
- // Sequential, not Promise.all: the LAST lock resolves the blocked
- // server request, so every earlier lock must already be accepted when
- // it lands — a reordered burst could complete the batch with a missing
- // answer. `clarify.lock` is a normal RPC; it rides the session's OWNER
- // socket (a profile / Bot Chat switch re-points ambient elsewhere).
- for (const question of questions) {
- const answer = stagedAnswer(question)
-
- await requestForOwnedSession<{ remaining?: string[]; status?: string }>(
- request.sessionId,
- gateway.request.bind(gateway) as typeof gateway.request,
- 'clarify.lock',
- {
- answer: answer ?? '',
- question_id: question.qid,
- request_id: request.requestId
- }
- )
- }
-
- forgetServerRequest(request.requestId)
-
- triggerHaptic('submit')
- onAnswered()
- // tool.complete lands next → ClarifyToolBatchSettled.
- clearClarifyRequest(request.requestId, request.sessionId)
- } catch (error) {
- notifyError(error, copy.sendFailed)
- setSubmitting(false)
- }
- }, [copy, gateway, onAnswered, questions, request, stagedAnswer])
-
- const toggleChoice = useCallback((question: ClarifyQuestion, choice: string) => {
- setStaged(current => {
- const stage = current[question.qid] ?? emptyStage
-
- const next = question.multiSelect
- ? stage.choices.includes(choice)
- ? stage.choices.filter(value => value !== choice)
- : [...stage.choices, choice]
- : [choice]
-
- // Multi-select keeps the typed text alongside the toggled choices;
- // single-select stays mutually exclusive.
- return { ...current, [question.qid]: { choices: next, draft: question.multiSelect ? stage.draft : '' } }
- })
- }, [])
-
- const draftFor = useCallback((question: ClarifyQuestion, value: string) => {
- setStaged(current => {
- const stage = current[question.qid] ?? emptyStage
-
- // Multi-select keeps the staged choices while the free-text field is
- // edited; single-select stays mutually exclusive.
- return { ...current, [question.qid]: { choices: question.multiSelect ? stage.choices : [], draft: value } }
- })
- }, [])
-
- const cancelAll = useCallback(async () => {
- if (!request) {
- return
- }
-
- onAnswered()
- clearClarifyRequest(request.requestId, request.sessionId)
-
- // A response with no `answers` is the cancel-all (the plain Esc path).
- respondToServerRequest(request.requestId, {})
- }, [gateway, onAnswered, request])
-
- const handleSubmit = useCallback(
- (event: FormEvent<HTMLFormElement>) => {
- event.preventDefault()
-
- if (ready && allStaged) {
- void confirmAll()
- }
- },
- [allStaged, confirmAll, ready]
- )
-
- const disabled = submitting || !ready
-
- if (questions.length === 0) {
- return (
- <ClarifyShell aria-label={copy.loadingQuestion} className="my-1.5 grid min-h-12 place-items-center" role="status">
- <Loader aria-hidden="true" className="size-6 text-(--ui-text-tertiary)" role="presentation" type="rose-curve" />
- </ClarifyShell>
- )
- }
-
- return (
- <form
- aria-busy={ready || undelivered ? undefined : 'true'}
- className="my-1.5 grid gap-4"
- data-clarify-batch={questions.length}
- data-clarify-batch-preview={ready ? undefined : ''}
- onKeyDownCapture={handleClarifySubmitShortcut}
- onSubmit={handleSubmit}
- >
- {ready || undelivered ? null : (
- <span className="sr-only" role="status">
- {copy.loadingQuestion}
- </span>
- )}
- <ClarifyShell className="grid gap-3">
- <div className="flex items-start gap-2">
- <span className="flex-1 text-[0.6875rem] leading-4 text-(--ui-text-tertiary)">
- {copy.questionProgress(answeredCount, questions.length)}
- </span>
- <MessageQuestion aria-hidden className={CLARIFY_ICON_CLASS} />
- </div>
- {undelivered ? <UndeliveredNotice /> : null}
- {questions.map(question => (
- <BatchQuestionBlock
- disabled={disabled}
- key={question.qid}
- locked={false}
- onDraft={value => draftFor(question, value)}
- onToggle={choice => toggleChoice(question, choice)}
- question={question}
- staged={stageFor(question.qid)}
- />
- ))}
- </ClarifyShell>
-
- {undelivered ? null : (
- <div className="flex items-center justify-end gap-1">
- <Button disabled={disabled} onClick={() => void cancelAll()} size="xs" type="button" variant="text">
- {copy.skip}
- </Button>
- <Button disabled={disabled || !allStaged} size="xs" type="submit">
- {submitting ? (
- <Loader2 className="animate-spin" />
- ) : (
- <>
- {copy.confirmAndContinueLabel}
- <span aria-hidden className="ml-0.5 text-[0.625rem] opacity-70">
- ⏎
- </span>
- </>
- )}
- </Button>
- </div>
- )}
- </form>
- )
-}
diff --git a/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx b/apps/desktop/src/components/assistant-ui/clarify/clarify-tool.test.tsx
similarity index 72%
rename from apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx
rename to apps/desktop/src/components/assistant-ui/clarify/clarify-tool.test.tsx
index bc22256d76b..4eb4db1170d 100644
--- a/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify/clarify-tool.test.tsx
@@ -4,7 +4,6 @@ import { atom } from 'nanostores'
import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { onComposerInsertRequest } from '@/app/chat/composer/focus'
import { type SessionView, SessionViewProvider } from '@/app/chat/session-view'
import { hiddenPaneProps } from '@/components/pane-shell/pane-visibility'
import { $activeTreeGroup, $hoveredTreeGroup } from '@/components/pane-shell/tree/store'
@@ -15,7 +14,9 @@ import { $profiles } from '@/store/profile'
import { hasOpenServerRequest, rememberServerRequest, resetServerRequestsForTests } from '@/store/server-requests'
import { $activeSessionId, _resetSessionOwnerHintsForTests, setSessionOwnerHint } from '@/store/session'
-import { ClarifyTool, readClarifyBatchResult, readClarifyResult } from './clarify-tool'
+import { readClarifyResult } from './parse'
+
+import { ClarifyTool } from './index'
// The OWNER-socket seam (`requestForOwnedSession` → `requestForSessionProfile`
// → here). Mocked so the real owner ladder still runs against real fixtures and
@@ -95,7 +96,7 @@ function settledClarifyProps(
}
function liveClarifyProps(choices = ['staging', 'production']): ToolCallMessagePartProps {
- const args = { choices, question: 'Which deployment target?' }
+ const args = { questions: [{ choices, question: 'Which deployment target?' }] }
return {
addResult: vi.fn(),
@@ -112,16 +113,18 @@ function liveClarifyProps(choices = ['staging', 'production']): ToolCallMessageP
}
}
+function lock(answer: string, requestId = 'request-1') {
+ return ['clarify.lock', { answer, question_id: 'q0', request_id: requestId }]
+}
+
function renderLiveClarify({ multiSelect = false }: { multiSelect?: boolean } = {}) {
- const request = vi.fn().mockResolvedValue({ ok: true })
+ const request = vi.fn().mockResolvedValue({ ok: true, remaining: [] })
const respond = liveServerRequest('request-1')
$activeSessionId.set('session-1')
$gateway.set({ request } as never)
setClarifyRequest({
- choices: ['staging', 'production'],
- multiSelect,
- question: 'Which deployment target?',
+ questions: [{ choices: ['staging', 'production'], multiSelect, qid: 'q0', question: 'Which deployment target?' }],
requestId: 'request-1',
sessionId: 'session-1'
})
@@ -147,17 +150,17 @@ describe('ClarifyTool live card stays mounted across settle', () => {
renderClarify(<ClarifyTool {...liveClarifyProps()} />)
expect(document.querySelector('[data-clarify-choices]')).toBeNull()
- expect(screen.queryByRole('button', { name: /Continue/ })).toBeNull()
+ expect(screen.queryByRole('button', { name: /Confirm and continue/ })).toBeNull()
})
it('holds the card through the gap between answering and the settled result', async () => {
- const { rerender, respond } = renderLiveClarify()
+ const { request, rerender } = renderLiveClarify()
fireEvent.click(screen.getByRole('button', { name: /staging/ }))
- fireEvent.click(screen.getByRole('button', { name: /Continue/ }))
+ fireEvent.click(screen.getByRole('button', { name: /Confirm and continue/ }))
await waitFor(() => {
- expect(respond).toHaveBeenCalled()
+ expect(request).toHaveBeenCalled()
})
// tool.complete is what swaps in the settled card; the turn can already
@@ -165,7 +168,7 @@ describe('ClarifyTool live card stays mounted across settle', () => {
messageRunning = false
rerender(clarifyTree(<ClarifyTool {...liveClarifyProps()} />))
- expect(document.querySelector('[data-clarify-choices]')).toBeTruthy()
+ expect(document.querySelector('form[data-clarify-batch]')).toBeTruthy()
})
it('demotes when the turn is stopped after the card was live but never answered', () => {
@@ -177,7 +180,7 @@ describe('ClarifyTool live card stays mounted across settle', () => {
act(() => clearClarifyRequest('request-1', 'session-1'))
expect(document.querySelector('[data-clarify-choices]')).toBeNull()
- expect(screen.queryByRole('button', { name: /Continue/ })).toBeNull()
+ expect(screen.queryByRole('button', { name: /Confirm and continue/ })).toBeNull()
})
it('paints the question from tool args instead of a spinner while request_id is still racing', () => {
@@ -187,13 +190,13 @@ describe('ClarifyTool live card stays mounted across settle', () => {
expect(screen.getByText('Which deployment target?')).toBeTruthy()
expect(screen.queryByRole('status', { name: /loading question/i })).toBeNull()
- expect(screen.getByRole('button', { name: /Continue/ }).hasAttribute('disabled')).toBe(true)
+ expect(screen.getByRole('button', { name: /Confirm and continue/ }).hasAttribute('disabled')).toBe(true)
})
})
describe('ClarifyTool choice selection', () => {
it('selects independently, deselects and submits multi-select choices as a JSON array', async () => {
- const { respond } = renderLiveClarify({ multiSelect: true })
+ const { request } = renderLiveClarify({ multiSelect: true })
const staging = screen.getByRole('button', { name: /staging/ })
const production = screen.getByRole('button', { name: /production/ })
@@ -210,200 +213,11 @@ describe('ClarifyTool choice selection', () => {
expect(staging.getAttribute('aria-pressed')).toBe('false')
fireEvent.click(staging)
- fireEvent.click(screen.getByRole('button', { name: /Continue/ }))
-
- await waitFor(() => {
- expect(respond).toHaveBeenCalledWith({ answer: JSON.stringify(['production', 'staging']) })
- })
- })
-
- it('keeps picked multi-select choices when typing a custom answer alongside them', async () => {
- const { respond } = renderLiveClarify({ multiSelect: true })
- const staging = screen.getByRole('button', { name: /staging/ })
- const production = screen.getByRole('button', { name: /production/ })
- const other = screen.getByPlaceholderText(/Other/)
-
- fireEvent.click(staging)
- fireEvent.click(production)
- fireEvent.focus(other)
- fireEvent.change(other, { target: { value: 'something else' } })
-
- // Typing in "Other" must not silently drop the picks already made.
- expect(staging.getAttribute('aria-pressed')).toBe('true')
- expect(production.getAttribute('aria-pressed')).toBe('true')
-
- fireEvent.click(screen.getByRole('button', { name: /Continue/ }))
-
- await waitFor(() => {
- expect(respond).toHaveBeenCalledWith({ answer: JSON.stringify(['staging', 'production', 'something else']) })
- })
- })
-
- it('keeps a typed multi-select custom answer when picking a choice after typing it', async () => {
- const { respond } = renderLiveClarify({ multiSelect: true })
- const staging = screen.getByRole('button', { name: /staging/ })
- const other = screen.getByPlaceholderText(/Other/)
-
- fireEvent.focus(other)
- fireEvent.change(other, { target: { value: 'something else' } })
- fireEvent.click(staging)
-
- // Picking a choice must not silently discard the text already typed.
- expect((other as HTMLInputElement).value).toBe('something else')
- expect(staging.getAttribute('aria-pressed')).toBe('true')
-
- fireEvent.click(screen.getByRole('button', { name: /Continue/ }))
-
- await waitFor(() => {
- expect(respond).toHaveBeenCalledWith({ answer: JSON.stringify(['staging', 'something else']) })
- })
- })
-
- it('keeps single-select replacement and plain-string submission', async () => {
- const { respond } = renderLiveClarify()
- const staging = screen.getByRole('button', { name: /staging/ })
- const production = screen.getByRole('button', { name: /production/ })
-
- fireEvent.click(staging)
- fireEvent.click(production)
-
- expect(staging.getAttribute('aria-pressed')).toBe('false')
- expect(production.getAttribute('aria-pressed')).toBe('true')
-
- fireEvent.click(screen.getByRole('button', { name: /Continue/ }))
+ fireEvent.click(screen.getByRole('button', { name: /Confirm and continue/ }))
await waitFor(() => {
- expect(respond).toHaveBeenCalledWith({ answer: 'production' })
+ expect(request).toHaveBeenCalledWith(...lock(JSON.stringify(['production', 'staging'])))
})
- expect(hasOpenServerRequest('request-1')).toBe(false)
- })
-})
-
-describe('readClarifyResult', () => {
- it('reads question + user_response from the tool JSON payload', () => {
- expect(
- readClarifyResult({
- question: 'Which target?',
- choices_offered: ['staging', 'prod'],
- user_response: 'staging'
- })
- ).toEqual({
- question: 'Which target?',
- answer: 'staging',
- error: undefined
- })
- })
-
- it('parses a JSON string result the same way as an object', () => {
- expect(
- readClarifyResult(
- JSON.stringify({
- question: 'Ship it?',
- user_response: 'yes'
- })
- )
- ).toEqual({
- question: 'Ship it?',
- answer: 'yes',
- error: undefined
- })
- })
-
- it('keeps an empty user_response so Skip can render as skipped', () => {
- expect(readClarifyResult({ question: 'Ok?', user_response: '' })).toEqual({
- question: 'Ok?',
- answer: '',
- error: undefined
- })
- })
-})
-
-describe('ClarifyTool settled view', () => {
- it('keeps the question and answer visible after the tool completes', () => {
- renderClarify(
- <ClarifyTool
- {...settledClarifyProps(
- { question: 'Which deployment target?', choices: ['staging', 'prod'] },
- {
- question: 'Which deployment target?',
- choices_offered: ['staging', 'prod'],
- user_response: 'staging'
- },
- 'clarify-1'
- )}
- />
- )
-
- expect(screen.getByText('Which deployment target?')).toBeTruthy()
- expect(screen.getByText('staging')).toBeTruthy()
- expect(document.querySelector('[data-clarify-settled]')).toBeTruthy()
- expect(document.querySelector('[data-clarify-answer]')?.textContent).toBe('staging')
- })
-
- it('keeps the original choices visible and clickable after a skip', async () => {
- const inserts: string[] = []
-
- const stop = onComposerInsertRequest(detail => {
- inserts.push(detail.text)
- })
-
- try {
- renderClarify(
- <ClarifyTool
- {...settledClarifyProps(
- { question: 'Which deployment target?', choices: ['staging', 'prod'] },
- { question: 'Which deployment target?', user_response: '' },
- 'clarify-3'
- )}
- />
- )
-
- // The skip label renders AND the original options are still on screen.
- expect(screen.getByText('Skipped')).toBeTruthy()
- const group = document.querySelector('[data-clarify-late-choices]')
- expect(group).toBeTruthy()
- expect(screen.getByText('staging')).toBeTruthy()
- expect(screen.getByText('prod')).toBeTruthy()
-
- // Picking one drafts a quoted follow-up into the composer. The insert
- // bus defers dispatch by a macrotask, so flush one tick.
- fireEvent.click(screen.getByText('prod'))
- await new Promise(resolve => window.setTimeout(resolve, 0))
-
- expect(inserts).toHaveLength(1)
- expect(inserts[0]).toContain('Which deployment target?')
- expect(inserts[0]).toContain('prod')
- } finally {
- stop()
- }
- })
-
- it('does not render late choices on an answered clarify', () => {
- renderClarify(
- <ClarifyTool
- {...settledClarifyProps(
- { question: 'Which deployment target?', choices: ['staging', 'prod'] },
- { question: 'Which deployment target?', user_response: 'staging' },
- 'clarify-4'
- )}
- />
- )
-
- expect(document.querySelector('[data-clarify-late-choices]')).toBeNull()
- })
-
- it('does not render late choices for a free-text (no-choice) skip', () => {
- renderClarify(
- <ClarifyTool
- {...settledClarifyProps(
- { question: 'Anything else?' },
- { question: 'Anything else?', user_response: '' },
- 'clarify-5'
- )}
- />
- )
-
- expect(document.querySelector('[data-clarify-late-choices]')).toBeNull()
})
})
@@ -435,30 +249,30 @@ describe('ClarifyTool keyboard navigation', () => {
})
it('selects by number and confirms the answer with Enter', async () => {
- const { respond } = renderLiveClarify()
+ const { request } = renderLiveClarify()
fireEvent.keyDown(window, { key: '2' })
fireEvent.keyDown(window, { key: 'Enter' })
await waitFor(() => {
- expect(respond).toHaveBeenCalledWith({ answer: 'production' })
+ expect(request).toHaveBeenCalledWith(...lock('production'))
})
})
- it('stages a highlighted multi-select choice with Enter and submits it with Continue', async () => {
- const { respond } = renderLiveClarify({ multiSelect: true })
+ it('stages a highlighted multi-select choice with Enter and submits it with Confirm', async () => {
+ const { request } = renderLiveClarify({ multiSelect: true })
const production = screen.getByRole('button', { name: /production/ })
fireEvent.keyDown(window, { key: 'ArrowDown' })
fireEvent.keyDown(window, { key: 'Enter' })
expect(production.getAttribute('aria-pressed')).toBe('true')
- expect(respond).not.toHaveBeenCalled()
+ expect(request).not.toHaveBeenCalled()
- fireEvent.click(screen.getByRole('button', { name: /Continue/ }))
+ fireEvent.click(screen.getByRole('button', { name: /Confirm and continue/ }))
await waitFor(() => {
- expect(respond).toHaveBeenCalledWith({ answer: JSON.stringify(['production']) })
+ expect(request).toHaveBeenCalledWith(...lock(JSON.stringify(['production'])))
})
})
@@ -477,7 +291,7 @@ describe('ClarifyTool keyboard navigation', () => {
})
it('does not intercept keyboard events while an action button has focus', () => {
- const { respond } = renderLiveClarify()
+ const { request, respond } = renderLiveClarify()
const skip = screen.getByRole('button', { name: 'Skip' })
skip.focus()
@@ -485,10 +299,11 @@ describe('ClarifyTool keyboard navigation', () => {
expect(fireEvent.keyDown(window, { key: 'Enter' })).toBe(true)
expect(fireEvent.keyDown(window, { key: 'ArrowDown' })).toBe(true)
expect(respond).not.toHaveBeenCalled()
+ expect(request).not.toHaveBeenCalled()
})
it('confirms a clicked choice with Enter while the choice button keeps focus', async () => {
- const { respond } = renderLiveClarify()
+ const { request } = renderLiveClarify()
const production = screen.getByRole('button', { name: /production/ })
// Click selects the choice; in a real browser the option button keeps
@@ -502,30 +317,29 @@ describe('ClarifyTool keyboard navigation', () => {
fireEvent.keyDown(window, { key: 'Enter' })
await waitFor(() => {
- expect(respond).toHaveBeenCalledWith({ answer: 'production' })
+ expect(request).toHaveBeenCalledWith(...lock('production'))
})
})
- it('confirms the highlighted choice with Enter when a choice button is focused but not clicked', async () => {
- const { respond } = renderLiveClarify()
+ it('picks the highlighted choice with Enter when a choice button is focused but not clicked, then confirms', async () => {
+ const { request } = renderLiveClarify()
const production = screen.getByRole('button', { name: /production/ })
- // Tabbing onto a choice does not stage it. Enter still belongs to
- // activateActive, which confirms the highlighted row (staging by default)
- // rather than falling through as a hands-off keypress.
production.focus()
expect(production.getAttribute('aria-pressed')).toBe('false')
expect(document.activeElement).toBe(production)
+ fireEvent.keyDown(window, { key: 'Enter' })
+ expect(screen.getByRole('button', { name: /staging/ }).getAttribute('aria-pressed')).toBe('true')
fireEvent.keyDown(window, { key: 'Enter' })
await waitFor(() => {
- expect(respond).toHaveBeenCalledWith({ answer: 'staging' })
+ expect(request).toHaveBeenCalledWith(...lock('staging'))
})
})
- it('toggles a focused multi-select row with Enter and confirms the set with Continue', async () => {
- const { respond } = renderLiveClarify({ multiSelect: true })
+ it('toggles a focused multi-select row with Enter and confirms the set with Confirm', async () => {
+ const { request } = renderLiveClarify({ multiSelect: true })
const staging = screen.getByRole('button', { name: /staging/ })
const production = screen.getByRole('button', { name: /production/ })
@@ -540,26 +354,32 @@ describe('ClarifyTool keyboard navigation', () => {
expect(production.getAttribute('aria-pressed')).toBe('false')
expect(staging.getAttribute('aria-pressed')).toBe('true')
- expect(respond).not.toHaveBeenCalled()
+ expect(request).not.toHaveBeenCalled()
- fireEvent.click(screen.getByRole('button', { name: /Continue/ }))
+ fireEvent.click(screen.getByRole('button', { name: /Confirm and continue/ }))
await waitFor(() => {
- expect(respond).toHaveBeenCalledWith({ answer: JSON.stringify(['staging']) })
+ expect(request).toHaveBeenCalledWith(...lock(JSON.stringify(['staging'])))
})
})
})
describe('ClarifyTool recommended option', () => {
- it('dims the (Recommended) label and answers with the choice the backend sent', async () => {
- const respond = liveServerRequest('request-1')
+ it('dims the (Recommended) label and answers with the bare choice', async () => {
+ const request = vi.fn().mockResolvedValue({ ok: true, remaining: [] })
+ liveServerRequest('request-1')
$activeSessionId.set('session-1')
- $gateway.set({ request: vi.fn() } as never)
+ $gateway.set({ request } as never)
setClarifyRequest({
- choices: ['staging (Recommended)', 'production'],
- multiSelect: false,
- question: 'Which deployment target?',
+ questions: [
+ {
+ choices: ['staging (Recommended)', 'production'],
+ multiSelect: false,
+ qid: 'q0',
+ question: 'Which deployment target?'
+ }
+ ],
requestId: 'request-1',
sessionId: 'session-1'
})
@@ -570,10 +390,8 @@ describe('ClarifyTool recommended option', () => {
fireEvent.click(recommended)
fireEvent.keyDown(window, { key: 'Enter' })
- // The decorated string goes back verbatim; the tool strips the label before
- // the agent ever sees the answer.
await waitFor(() => {
- expect(respond).toHaveBeenCalledWith({ answer: 'staging (Recommended)' })
+ expect(request).toHaveBeenCalledWith(...lock('staging'))
})
})
})
@@ -590,38 +408,6 @@ describe('ClarifyTool pending marker', () => {
expect(card).toBeTruthy()
expect(Number(card?.getAttribute('data-clarify-choices'))).toBeGreaterThan(0)
})
-
- it('does not mark a free-text (no-choice) pending card', () => {
- $activeSessionId.set('session-1')
- $gateway.set({ request: vi.fn().mockResolvedValue({ ok: true }) } as never)
- setClarifyRequest({
- choices: null,
- multiSelect: false,
- question: 'Anything else?',
- requestId: 'request-1',
- sessionId: 'session-1'
- })
-
- const args = { question: 'Anything else?' }
- renderClarify(
- <ClarifyTool
- addResult={vi.fn()}
- args={args}
- argsText={JSON.stringify(args)}
- isError={false}
- respondToApproval={vi.fn()}
- result={undefined}
- resume={vi.fn()}
- status={{ type: 'running' }}
- toolCallId="clarify-free"
- toolName="clarify"
- type="tool-call"
- />
- )
-
- // No shortcuts → nothing to protect → composer type-to-focus stays live.
- expect(document.querySelector('[data-clarify-choices]')).toBeNull()
- })
})
// ─── Batch (multi-question) clarify ─────────────────────────────────────────
@@ -657,10 +443,7 @@ function renderLiveBatch(lockedAnswers?: Record<string, string>, multiSelect = f
$activeSessionId.set('session-1')
$gateway.set({ request } as never)
setClarifyRequest({
- choices: null,
lockedAnswers,
- multiSelect: false,
- question: '',
questions: [
{ choices: ['red', 'blue'], multiSelect, qid: 'q0', question: 'Color?' },
{ choices: null, multiSelect: false, qid: 'q1', question: 'Name?' }
@@ -673,58 +456,58 @@ function renderLiveBatch(lockedAnswers?: Record<string, string>, multiSelect = f
return { request, respond }
}
-describe('readClarifyBatchResult', () => {
- it('parses responses with string and list answers plus timed_out', () => {
- const parsed = readClarifyBatchResult(
+describe('readClarifyResult', () => {
+ it('parses responses with string and list answers', () => {
+ const parsed = readClarifyResult(
JSON.stringify({
responses: [
{ question: 'Color?', user_response: 'red' },
{ question: 'Tools?', user_response: ['a', 'b'] },
{ question: 'Name?', user_response: '' }
- ],
- timed_out: true
+ ]
})
)
- expect(parsed.timedOut).toBe(true)
expect(parsed.responses).toHaveLength(3)
expect(parsed.responses[1]?.answer).toEqual(['a', 'b'])
expect(parsed.responses[2]?.answer).toBe('')
})
it('returns empty responses for single-question payloads', () => {
- expect(readClarifyBatchResult({ question: 'Q?', user_response: 'a' }).responses).toEqual([])
+ expect(readClarifyResult({ question: 'Q?', user_response: 'a' }).responses).toEqual([])
})
})
describe('ClarifyTool submit shortcut', () => {
it('submits selected choices with Cmd/Ctrl+Enter without toggling the focused option', async () => {
for (const modifier of [{ metaKey: true }, { ctrlKey: true }]) {
- const { respond } = renderLiveClarify({ multiSelect: true })
+ const { request } = renderLiveClarify({ multiSelect: true })
const choice = screen.getByRole('button', { name: /staging/ })
fireEvent.click(choice)
choice.focus()
fireEvent.keyDown(choice, { key: 'Enter', ...modifier })
- await waitFor(() => expect(respond).toHaveBeenCalledTimes(1))
- expect(respond).toHaveBeenCalledWith({ answer: '["staging"]' })
+ await waitFor(() => expect(request).toHaveBeenCalledTimes(1))
+ expect(request).toHaveBeenCalledWith(...lock('["staging"]'))
cleanup()
}
})
- it('submits a complete batch from its text field while preserving incomplete and multiline input', async () => {
+ it('submits the batch from its text field while preserving multiline input', async () => {
for (const modifier of [{ metaKey: true }, { ctrlKey: true }]) {
const { request } = renderLiveBatch()
const field = screen.getByPlaceholderText('Type your answer…')
fireEvent.change(field, { target: { value: 'packet' } })
field.focus()
- fireEvent.keyDown(field, { key: 'Enter', ...modifier })
- expect(request).not.toHaveBeenCalled()
- fireEvent.click(screen.getByRole('button', { name: /red/ }))
fireEvent.keyDown(field, { key: 'Enter', shiftKey: true })
fireEvent.keyDown(field, { key: 'Enter', isComposing: true, ...modifier })
expect(request).not.toHaveBeenCalled()
fireEvent.keyDown(field, { key: 'Enter', ...modifier })
await waitFor(() => expect(request).toHaveBeenCalledTimes(2))
+ expect(request).toHaveBeenNthCalledWith(1, 'clarify.lock', {
+ answer: null,
+ question_id: 'q0',
+ request_id: 'request-batch'
+ })
expect(request).toHaveBeenNthCalledWith(2, 'clarify.lock', {
answer: 'packet',
question_id: 'q1',
@@ -797,9 +580,6 @@ describe('ClarifyTool batch card', () => {
const request = vi.fn(async (method: string) => {
if (method === 'session.events.since') {
setClarifyRequest({
- choices: null,
- multiSelect: false,
- question: '',
questions: [
{ choices: ['red', 'blue'], multiSelect: false, qid: 'q0', question: 'Color?' },
{ choices: null, multiSelect: false, qid: 'q1', question: 'Name?' }
@@ -828,26 +608,6 @@ describe('ClarifyTool batch card', () => {
}
})
- it('shows the same notice on a single-question card whose request never arrived', async () => {
- vi.useFakeTimers()
-
- try {
- $activeSessionId.set('session-1')
- $gateway.set({ request: vi.fn(async () => ({ events: [], open_requests: [] })) } as never)
- renderClarify(<ClarifyTool {...liveClarifyProps()} />)
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(4_000)
- })
-
- expect(screen.getByRole('status').textContent).toMatch(/didn't reach the app/)
- expect(screen.queryByRole('button', { name: /Continue/ })).toBeNull()
- expect(screen.queryByRole('button', { name: /Skip/ })).toBeNull()
- } finally {
- vi.useRealTimers()
- }
- })
-
it('swaps the preview for the live form and answers with the request qids', async () => {
const request = vi.fn().mockResolvedValue({ ok: true, remaining: [] })
$activeSessionId.set('session-1')
@@ -859,9 +619,6 @@ describe('ClarifyTool batch card', () => {
act(() => {
liveServerRequest('request-batch')
setClarifyRequest({
- choices: null,
- multiSelect: false,
- question: '',
questions: [
{ choices: ['red', 'blue'], multiSelect: false, qid: 'q0', question: 'Color?' },
{ choices: null, multiSelect: false, qid: 'q1', question: 'Name?' }
@@ -893,7 +650,7 @@ describe('ClarifyTool batch card', () => {
})
})
- it('stages locally and keeps the single confirm disabled until all answered', async () => {
+ it('stages locally and enables the single confirm once one question is answered', async () => {
const { request } = renderLiveBatch()
const confirm = screen.getByRole('button', { name: /Confirm and continue/ })
@@ -903,7 +660,7 @@ describe('ClarifyTool batch card', () => {
fireEvent.click(screen.getByRole('button', { name: /red/ }))
expect(screen.getByText('1 of 2 answered')).toBeTruthy()
expect(request).not.toHaveBeenCalled()
- expect((confirm as HTMLButtonElement).disabled).toBe(true)
+ expect((confirm as HTMLButtonElement).disabled).toBe(false)
fireEvent.change(screen.getByPlaceholderText('Type your answer…'), { target: { value: 'packet' } })
expect(screen.getByText('2 of 2 answered')).toBeTruthy()
@@ -1064,9 +821,6 @@ describe('ClarifyTool batch card', () => {
function singleBatchRequest() {
return {
- choices: null,
- multiSelect: false,
- question: '',
questions: [
{
choices: ['Local Markdown under .scratch/', 'GitHub Issues', 'Linear', 'GitLab Issues'],
@@ -1133,9 +887,10 @@ describe('ClarifyTool batch card', () => {
{...settledClarifyProps(
batchArgs(),
JSON.stringify({
+ outcome: 'submitted',
responses: [
- { choices_offered: ['red', 'blue'], question: 'Color?', user_response: 'red' },
- { choices_offered: null, question: 'Name?', user_response: '' }
+ { choices_offered: ['red', 'blue'], question: 'Color?', status: 'answered', user_response: 'red' },
+ { choices_offered: null, question: 'Name?', status: 'skipped', user_response: null }
]
}),
'clarify-batch-settled'
@@ -1196,37 +951,11 @@ describe('ClarifyTool owner routing', () => {
gatewayMocks.requestGatewayForAgent.mockClear()
})
- it('answers a single clarify through its server request, never profile B ambient', async () => {
- const ambient = armCrossProfileOwner()
- const respond = liveServerRequest('request-1')
-
- setClarifyRequest({
- choices: ['staging', 'production'],
- multiSelect: false,
- question: 'Which deployment target?',
- requestId: 'request-1',
- sessionId: 'session-a'
- })
- renderClarify(<ClarifyTool {...liveClarifyProps()} />)
-
- fireEvent.click(screen.getByRole('button', { name: /staging/ }))
- fireEvent.click(screen.getByRole('button', { name: /Continue/ }))
-
- await waitFor(() => {
- expect(respond).toHaveBeenCalledWith({ answer: 'staging' })
- })
- expect(gatewayMocks.requestGatewayForAgent).not.toHaveBeenCalled()
- expect(ambient).not.toHaveBeenCalled()
- })
-
it('sends both sequential batch locks on the owner socket, in order', async () => {
const ambient = armCrossProfileOwner()
liveServerRequest('request-batch')
setClarifyRequest({
- choices: null,
- multiSelect: false,
- question: '',
questions: [
{ choices: ['red', 'blue'], multiSelect: false, qid: 'q0', question: 'Color?' },
{ choices: null, multiSelect: false, qid: 'q1', question: 'Name?' }
@@ -1254,9 +983,6 @@ describe('ClarifyTool owner routing', () => {
const respond = liveServerRequest('request-batch')
setClarifyRequest({
- choices: null,
- multiSelect: false,
- question: '',
questions: [
{ choices: ['red', 'blue'], multiSelect: false, qid: 'q0', question: 'Color?' },
{ choices: null, multiSelect: false, qid: 'q1', question: 'Name?' }
@@ -1298,25 +1024,23 @@ describe('ClarifyTool visible-card scoping', () => {
}
function pendingCardProps(toolCallId: string): ToolCallMessagePartProps {
- const args = { choices: ['staging', 'production'], question: QUESTION }
-
- return { ...liveClarifyProps(), args, argsText: JSON.stringify(args), toolCallId }
+ return { ...liveClarifyProps(), toolCallId }
}
- /** Park a clarify on `sessionId` with its own live server request; the
- * returned spy sees that request's (and only that request's) answer. */
function parkClarify(requestId: string, sessionId: string) {
- const respond = liveServerRequest(requestId)
+ liveServerRequest(requestId)
setClarifyRequest({
- choices: ['staging', 'production'],
- multiSelect: false,
- question: QUESTION,
+ questions: [{ choices: ['staging', 'production'], multiSelect: false, qid: 'q0', question: QUESTION }],
requestId,
sessionId
})
+ }
- return respond
+ function lockedRequestIds(request: ReturnType<typeof vi.fn>) {
+ return request.mock.calls
+ .filter(call => call[0] === 'clarify.lock')
+ .map(call => (call[1] as { request_id: string }).request_id)
}
/** A card inside an inactive tab layer — mounted and live, just not on screen. */
@@ -1331,9 +1055,10 @@ describe('ClarifyTool visible-card scoping', () => {
}
it('answers the visible card, not a background one that mounted first', async () => {
- $gateway.set({ request: vi.fn() } as never)
- const background = parkClarify(BACKGROUND_REQUEST, BACKGROUND_SESSION)
- const foreground = parkClarify(FOREGROUND_REQUEST, FOREGROUND_SESSION)
+ const request = vi.fn().mockResolvedValue({ ok: true, remaining: [] })
+ $gateway.set({ request } as never)
+ parkClarify(BACKGROUND_REQUEST, BACKGROUND_SESSION)
+ parkClarify(FOREGROUND_REQUEST, FOREGROUND_SESSION)
// The background card is rendered FIRST, so its window listener registers
// first. Registration order used to decide the winner, which meant the card
@@ -1348,27 +1073,26 @@ describe('ClarifyTool visible-card scoping', () => {
)
fireEvent.keyDown(window, { key: 'Enter' })
-
- await waitFor(() => {
- expect(foreground).toHaveBeenCalledTimes(1)
- })
+ fireEvent.keyDown(window, { key: 'Enter' })
// Exactly one answer, on the FOREGROUND request — the background session's
// turn must not be resumed by a keystroke aimed at this one.
- expect(foreground).toHaveBeenCalledWith({ answer: 'staging' })
- expect(background).not.toHaveBeenCalled()
+ await waitFor(() => {
+ expect(lockedRequestIds(request)).toEqual([FOREGROUND_REQUEST])
+ })
})
it('leaves the key alone when the only pending card is hidden', () => {
- $gateway.set({ request: vi.fn() } as never)
- const background = parkClarify(BACKGROUND_REQUEST, BACKGROUND_SESSION)
+ const request = vi.fn()
+ $gateway.set({ request } as never)
+ parkClarify(BACKGROUND_REQUEST, BACKGROUND_SESSION)
renderClarify(backgroundCard())
// Untouched (no preventDefault) ⇒ the keystroke stays available to the
// composer, matching what `clarifyCardOwnsKey` reports with no visible card.
expect(fireEvent.keyDown(window, { key: 'Enter' })).toBe(true)
- expect(background).not.toHaveBeenCalled()
+ expect(request).not.toHaveBeenCalled()
})
/** A card in its own split zone — unlike `backgroundCard` this one IS on
@@ -1386,9 +1110,10 @@ describe('ClarifyTool visible-card scoping', () => {
/** Both zones visible, zone-a first in document order. */
function renderSplit() {
- $gateway.set({ request: vi.fn() } as never)
- const zoneA = parkClarify(ZONE_A_REQUEST, ZONE_A_SESSION)
- const zoneB = parkClarify(ZONE_B_REQUEST, ZONE_B_SESSION)
+ const request = vi.fn().mockResolvedValue({ ok: true, remaining: [] })
+ $gateway.set({ request } as never)
+ parkClarify(ZONE_A_REQUEST, ZONE_A_SESSION)
+ parkClarify(ZONE_B_REQUEST, ZONE_B_SESSION)
renderClarify(
<>
@@ -1397,38 +1122,34 @@ describe('ClarifyTool visible-card scoping', () => {
</>
)
- return { zoneA, zoneB }
+ return request
}
it('answers the later-in-document card when its zone is the focused one', async () => {
- const { zoneA, zoneB } = renderSplit()
+ const request = renderSplit()
$activeTreeGroup.set('zone-b')
fireEvent.keyDown(window, { key: 'Enter' })
-
- await waitFor(() => {
- expect(zoneB).toHaveBeenCalledTimes(1)
- })
+ fireEvent.keyDown(window, { key: 'Enter' })
// Both cards are visible and both hold a live window listener, so this is
// the case document order gets wrong: it would answer zone-a's question.
- expect(zoneB).toHaveBeenCalledWith({ answer: 'staging' })
- expect(zoneA).not.toHaveBeenCalled()
+ await waitFor(() => {
+ expect(lockedRequestIds(request)).toEqual([ZONE_B_REQUEST])
+ })
})
it('answers the other visible card once the focus moves to its zone', async () => {
- const { zoneA, zoneB } = renderSplit()
+ const request = renderSplit()
$activeTreeGroup.set('zone-a')
fireEvent.keyDown(window, { key: 'Enter' })
-
- await waitFor(() => {
- expect(zoneA).toHaveBeenCalledTimes(1)
- })
+ fireEvent.keyDown(window, { key: 'Enter' })
// The direct pin for "the other visible card then cannot receive its
// shortcut": neither zone may be permanently starved of its own keys.
- expect(zoneA).toHaveBeenCalledWith({ answer: 'staging' })
- expect(zoneB).not.toHaveBeenCalled()
+ await waitFor(() => {
+ expect(lockedRequestIds(request)).toEqual([ZONE_A_REQUEST])
+ })
})
})
diff --git a/apps/desktop/src/components/assistant-ui/clarify/core/choice-row.tsx b/apps/desktop/src/components/assistant-ui/clarify/core/choice-row.tsx
new file mode 100644
index 00000000000..5ee8b79d722
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/core/choice-row.tsx
@@ -0,0 +1,99 @@
+'use client'
+
+import { Kbd } from '@/components/ui/kbd'
+import { cn } from '@/lib/utils'
+import { bareChoice, RECOMMENDED_LABEL } from '@/store/clarify'
+
+export const letterFor = (index: number): string => String.fromCharCode(65 + index)
+
+// The backend tags the agent's preferred option (`mark_recommended`); the card
+// renders the label in tertiary text so the option itself still reads first.
+export function ChoiceLabel({ choice }: { choice: string }) {
+ const bare = bareChoice(choice)
+
+ if (bare === choice) {
+ return <>{choice}</>
+ }
+
+ return (
+ <>
+ {bare} <span className="text-(--ui-text-tertiary)">{RECOMMENDED_LABEL}</span>
+ </>
+ )
+}
+
+export const OPTION_ROW_CLASS =
+ 'flex w-full items-start gap-2 rounded-[0.25rem] px-1.5 py-1 text-left disabled:cursor-not-allowed disabled:opacity-50'
+
+export function KeyBadge({
+ char,
+ disabled,
+ preview,
+ selected
+}: {
+ char: string
+ disabled?: boolean
+ preview?: boolean
+ selected: boolean
+}) {
+ // The "Other" row is a <label>, which has no :disabled state of its own —
+ // dim its badge alongside the disabled textarea so it matches the options.
+ return (
+ <Kbd
+ className={cn(
+ 'mt-px',
+ disabled && 'opacity-50',
+ selected && 'border-primary bg-primary text-white shadow-none',
+ !selected && preview && 'border-primary text-primary shadow-none'
+ )}
+ size="sm"
+ >
+ {char}
+ </Kbd>
+ )
+}
+
+/** A letter-badged option row. */
+export function ChoiceButton({
+ active = false,
+ char,
+ choice,
+ disabled,
+ keyShortcuts,
+ onClick,
+ selected
+}: {
+ active?: boolean
+ char: string
+ choice: string
+ disabled?: boolean
+ keyShortcuts?: string
+ onClick: () => void
+ selected?: boolean
+}) {
+ // `active` is the keyboard cursor on the live card (arrow-key navigation);
+ // it highlights the row and previews its key badge.
+ return (
+ <button
+ aria-current={active || undefined}
+ aria-keyshortcuts={keyShortcuts}
+ aria-pressed={selected}
+ className={cn(
+ OPTION_ROW_CLASS,
+ 'text-(--ui-text-secondary) hover:bg-(--chrome-action-hover) hover:text-(--ui-text-primary)',
+ active && 'bg-(--chrome-action-hover) text-(--ui-text-primary)',
+ selected && 'text-(--ui-text-primary)'
+ )}
+ data-choice
+ data-highlighted={active || undefined}
+ disabled={disabled}
+ onClick={onClick}
+ type="button"
+ >
+ <KeyBadge char={char} preview={active} selected={Boolean(selected)} />
+ <span className="flex-1 wrap-anywhere">
+ <ChoiceLabel choice={choice} />
+ </span>
+ </button>
+ )
+}
diff --git a/apps/desktop/src/components/assistant-ui/clarify/core/question-block.tsx b/apps/desktop/src/components/assistant-ui/clarify/core/question-block.tsx
new file mode 100644
index 00000000000..27b9bbc05b1
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/core/question-block.tsx
@@ -0,0 +1,105 @@
+'use client'
+
+import { Textarea } from '@/components/ui/textarea'
+import { useI18n } from '@/i18n'
+import { cn } from '@/lib/utils'
+import type { ClarifyQuestion } from '@/store/clarify'
+
+import { ChoiceButton, KeyBadge, letterFor, OPTION_ROW_CLASS } from './choice-row'
+import { CLARIFY_TEXTAREA_CLASS } from './shell'
+
+interface QuestionBlockProps {
+ cursor: null | number
+ disabled: boolean
+ onActivate: () => void
+ onDraft: (value: string) => void
+ onOtherFocus: () => void
+ onPick: (index: number) => void
+ question: ClarifyQuestion
+ staged: { choices: string[]; draft: string }
+}
+
+/** One question's interactive block inside the live batch card. */
+export function QuestionBlock({
+ cursor,
+ disabled,
+ onActivate,
+ onDraft,
+ onOtherFocus,
+ onPick,
+ question,
+ staged
+}: QuestionBlockProps) {
+ const { t } = useI18n()
+ const copy = t.assistant.clarify
+ const choices = question.choices ?? []
+ const otherActive = cursor === choices.length
+
+ return (
+ <div
+ className="grid gap-1"
+ data-clarify-batch-question={question.qid}
+ onFocus={onActivate}
+ onPointerDown={onActivate}
+ >
+ <div className="flex items-start gap-2">
+ <span className="flex-1 whitespace-pre-wrap font-medium leading-(--conversation-line-height)">
+ {question.question}
+ </span>
+ </div>
+
+ {choices.length > 0 ? (
+ <div className="grid gap-px" role="group">
+ {choices.map((choice, index) => (
+ <ChoiceButton
+ active={cursor === index}
+ char={letterFor(index)}
+ choice={choice}
+ disabled={disabled}
+ key={`${index}-${choice}`}
+ keyShortcuts={cursor === null ? undefined : `${letterFor(index)} ${index + 1}`}
+ onClick={() => onPick(index)}
+ selected={staged.choices.includes(choice)}
+ />
+ ))}
+ <label
+ className={cn(OPTION_ROW_CLASS, 'items-center', otherActive && 'bg-(--chrome-action-hover)')}
+ data-highlighted={otherActive || undefined}
+ >
+ <KeyBadge
+ char={letterFor(choices.length)}
+ disabled={disabled}
+ preview={otherActive}
+ selected={Boolean(staged.draft.trim())}
+ />
+ <Textarea
+ aria-current={otherActive || undefined}
+ aria-keyshortcuts={cursor === null ? undefined : `${letterFor(choices.length)} ${choices.length + 1}`}
+ className={CLARIFY_TEXTAREA_CLASS}
+ disabled={disabled}
+ onChange={event => onDraft(event.target.value)}
+ onFocus={onOtherFocus}
+ placeholder={copy.other}
+ rows={1}
+ size="sm"
+ value={staged.draft}
+ />
+ </label>
+ </div>
+ ) : (
+ <Textarea
+ className={CLARIFY_TEXTAREA_CLASS}
+ disabled={disabled}
+ onChange={event => onDraft(event.target.value)}
+ onFocus={onOtherFocus}
+ placeholder={copy.placeholder}
+ rows={1}
+ size="sm"
+ value={staged.draft}
+ />
+ )}
+ </div>
+ )
+}
+
+export const emptyStage = { choices: [] as string[], draft: '' }
diff --git a/apps/desktop/src/components/assistant-ui/clarify/core/shell.tsx b/apps/desktop/src/components/assistant-ui/clarify/core/shell.tsx
new file mode 100644
index 00000000000..8e611042145
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/core/shell.tsx
@@ -0,0 +1,36 @@
+'use client'
+
+import type { ComponentProps } from 'react'
+
+import { WIDGET_SHELL_CLASS } from '@/components/chat/widget-shell'
+import type { MessageQuestion } from '@/lib/icons'
+import { cn } from '@/lib/utils'
+
+// field-sizing on top of Textarea's shared chrome; kill min-h-16 for one-liners.
+export const CLARIFY_TEXTAREA_CLASS = 'field-sizing-content max-h-40 min-h-0 resize-none'
+
+export const CLARIFY_SHELL_CLASS = `${WIDGET_SHELL_CLASS} text-[length:var(--conversation-text-font-size)] text-(--ui-text-primary)`
+
+export const CLARIFY_ICON_CLASS = 'mt-px size-4 shrink-0 text-(--ui-text-tertiary)'
+
+export function ClarifyShell({ children, className, ...props }: ComponentProps<'div'>) {
+ return (
+ <div className={cn(CLARIFY_SHELL_CLASS, className)} data-slot="clarify-inline" {...props}>
+ {children}
+ </div>
+ )
+}
+
+export function ClarifyLine({
+ children,
+ className,
+ icon: Icon,
+ ...props
+}: ComponentProps<'div'> & { icon: typeof MessageQuestion }) {
+ return (
+ <div className={cn('flex items-start gap-2', className)} {...props}>
+ <div className="min-w-0 flex-1">{children}</div>
+ <Icon aria-hidden className={CLARIFY_ICON_CLASS} />
+ </div>
+ )
+}
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
new file mode 100644
index 00000000000..97d34bec549
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys.ts
@@ -0,0 +1,217 @@
+import { type RefObject, useCallback, useEffect, useState } from 'react'
+
+import { visibleClarifyCard } from '@/lib/keybinds/composer-focus-keys'
+import type { ClarifyQuestion } from '@/store/clarify'
+
+interface ClarifyKeysOptions {
+ enabled: boolean
+ formRef: RefObject<HTMLFormElement | null>
+ isStaged: (question: ClarifyQuestion) => boolean
+ onClear: (question: ClarifyQuestion) => void
+ onConfirm: () => void
+ onToggle: (question: ClarifyQuestion, choice: string) => void
+ questions: ClarifyQuestion[]
+}
+
+export function useClarifyKeys({
+ enabled,
+ formRef,
+ isStaged,
+ onClear,
+ onConfirm,
+ onToggle,
+ questions
+}: ClarifyKeysOptions) {
+ const [cursor, setCursor] = useState({ question: 0, row: 0 })
+ const questionIndex = Math.min(cursor.question, Math.max(questions.length - 1, 0))
+ const active = questions[questionIndex]
+ const choices = active?.choices ?? []
+ const row = Math.min(cursor.row, choices.length)
+
+ const focusQuestion = useCallback(
+ (index: number) => setCursor(current => (current.question === index ? current : { question: index, row: 0 })),
+ []
+ )
+
+ const onOtherFocus = useCallback(
+ (index: number) => setCursor({ question: index, row: questions[index]?.choices?.length ?? 0 }),
+ [questions]
+ )
+
+ const focusOther = useCallback(
+ (index: number) => {
+ onOtherFocus(index)
+
+ const block = formRef.current?.querySelectorAll<HTMLElement>('[data-clarify-batch-question]')[index]
+
+ block?.querySelector<HTMLTextAreaElement>('textarea')?.focus()
+ },
+ [formRef, onOtherFocus]
+ )
+
+ const nextUnstaged = useCallback(
+ (index: number): null | number => {
+ for (let offset = 1; offset < questions.length; offset += 1) {
+ const candidate = (index + offset) % questions.length
+
+ if (!isStaged(questions[candidate])) {
+ return candidate
+ }
+ }
+
+ return null
+ },
+ [isStaged, questions]
+ )
+
+ const pick = useCallback(
+ (index: number, choiceIndex: number) => {
+ const question = questions[index]
+ const choice = question?.choices?.[choiceIndex]
+
+ if (!question || choice === undefined) {
+ return
+ }
+
+ onToggle(question, choice)
+
+ const next = question.multiSelect ? null : nextUnstaged(index)
+
+ if (next !== null && !questions[next]?.choices?.length) {
+ focusOther(next)
+
+ return
+ }
+
+ setCursor(next === null ? { question: index, row: choiceIndex } : { question: next, row: 0 })
+ },
+ [focusOther, nextUnstaged, onToggle, questions]
+ )
+
+ const move = useCallback(
+ (delta: number) => {
+ if (!active) {
+ return
+ }
+
+ if (!active.multiSelect) {
+ onClear(active)
+ }
+
+ const itemCount = choices.length + 1
+
+ setCursor({ question: questionIndex, row: (row + delta + itemCount) % itemCount })
+ },
+ [active, choices.length, onClear, questionIndex, row]
+ )
+
+ const activate = useCallback(() => {
+ if (!active) {
+ return
+ }
+
+ const choice = active.choices?.[row]
+
+ if (active.multiSelect && choice !== undefined) {
+ pick(questionIndex, row)
+
+ return
+ }
+
+ if (isStaged(active)) {
+ onConfirm()
+
+ return
+ }
+
+ if (choice !== undefined) {
+ pick(questionIndex, row)
+
+ return
+ }
+
+ focusOther(questionIndex)
+ }, [active, focusOther, isStaged, onConfirm, pick, questionIndex, row])
+
+ useEffect(() => {
+ if (!enabled || !active) {
+ return
+ }
+
+ const pickByIndex = (event: globalThis.KeyboardEvent, index: number) => {
+ if (index < choices.length) {
+ event.preventDefault()
+ pick(questionIndex, index)
+ } else if (index === choices.length) {
+ event.preventDefault()
+ focusOther(questionIndex)
+ }
+ }
+
+ const onKeyDown = (event: globalThis.KeyboardEvent) => {
+ if (event.metaKey || event.ctrlKey || event.altKey || event.defaultPrevented) {
+ return
+ }
+
+ // Not the visible card ⇒ not our keystroke. Inactive tabs stay MOUNTED,
+ // so every parked clarify keeps a live `window` listener; without this the
+ // card that acts is whichever mounted first, and answering the question in
+ // front of you silently answers a background session's question instead —
+ // resuming an agent turn the user never saw. Same resolver the composer's
+ // `clarifyCardOwnsKey` yields to, so the two cannot disagree about which
+ // card is live.
+ if (visibleClarifyCard() !== formRef.current) {
+ return
+ }
+
+ const focused = document.activeElement as HTMLElement | null
+
+ if (
+ focused &&
+ (focused.isContentEditable ||
+ (focused.matches('a[href], button, input, select, textarea, [role="button"]') &&
+ !focused.matches('button[data-choice]')))
+ ) {
+ return
+ }
+
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ if (choices.length > 0) {
+ event.preventDefault()
+ move(event.key === 'ArrowDown' ? 1 : -1)
+ }
+
+ return
+ }
+
+ if (/^[1-9]$/.test(event.key)) {
+ pickByIndex(event, Number(event.key) - 1)
+
+ return
+ }
+
+ const key = event.key.toLowerCase()
+
+ // Only the letters this card actually renders a row for. Anything past
+ // the last row belongs to the composer — the user is typing a message
+ // instead of picking an option, and swallowing the keystroke here would
+ // make the first letter of it vanish.
+ if (key.length === 1 && key >= 'a' && key <= 'z') {
+ pickByIndex(event, key.charCodeAt(0) - 97)
+
+ return
+ }
+
+ if (event.key === 'Enter') {
+ event.preventDefault()
+ activate()
+ }
+ }
+
+ window.addEventListener('keydown', onKeyDown)
+
+ return () => window.removeEventListener('keydown', onKeyDown)
+ }, [activate, active, choices.length, enabled, focusOther, formRef, move, pick, questionIndex])
+
+ return { activeQuestion: questionIndex, cursorRow: row, focusQuestion, onOtherFocus, pick }
+}
diff --git a/apps/desktop/src/components/assistant-ui/clarify/index.tsx b/apps/desktop/src/components/assistant-ui/clarify/index.tsx
new file mode 100644
index 00000000000..cca33b58437
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/index.tsx
@@ -0,0 +1,57 @@
+'use client'
+
+import { type ToolCallMessagePartProps, useAuiState } from '@assistant-ui/react'
+import { useStore } from '@nanostores/react'
+import { useMemo, useState } from 'react'
+
+import { useSessionView } from '@/app/chat/session-view'
+import { ToolFallback } from '@/components/assistant-ui/tool/fallback'
+import { sessionClarifyRequest } from '@/store/clarify'
+
+import { selectMessageRunning } from '../tool/fallback-model'
+
+import { readClarifyArgs } from './parse'
+import { ClarifyToolPending } from './pending'
+import { ClarifyToolSettled } from './settled'
+import { useUndeliveredClarify } from './use-undelivered'
+
+export const ClarifyTool = (props: ToolCallMessagePartProps) => {
+ // Answered → settled Q&A (ToolFallback collapsed the answer away).
+ if (props.result !== undefined) {
+ return <ClarifyToolSettled {...props} />
+ }
+
+ return <ClarifyToolLive {...props} />
+}
+
+function ClarifyToolLive(props: ToolCallMessagePartProps) {
+ // The tool row is in whichever session's transcript rendered it — read THAT
+ // session's clarify (primary or tile), not the globally-active one.
+ const sessionId = useStore(useSessionView().$runtimeId)
+ const $request = useMemo(() => sessionClarifyRequest(sessionId), [sessionId])
+ const request = useStore($request)
+ const fromArgs = useMemo(() => readClarifyArgs(props.args), [props.args])
+ const messageRunning = useAuiState(selectMessageRunning)
+ // Answering clears the request a beat before `tool.complete` swaps in the
+ // settled card. Latch submit so that gap doesn't demote; Stop also clears
+ // the request and must still collapse an unanswered card.
+ const [answered, setAnswered] = useState(false)
+ const undelivered = useUndeliveredClarify(sessionId, messageRunning && !request && !answered)
+
+ // Stopped mid-prompt with no result — don't leave a dead interactive panel.
+ // `session.info` reports running=false while clarify is blocking, so the
+ // running flag alone would remount the question as a tool row. Keep the
+ // card while a request is open or this instance already submitted.
+ if (!messageRunning && !request && !answered) {
+ return <ToolFallback {...props} />
+ }
+
+ return (
+ <ClarifyToolPending
+ fromArgs={fromArgs}
+ onAnswered={() => setAnswered(true)}
+ request={request}
+ undelivered={undelivered}
+ />
+ )
+}
diff --git a/apps/desktop/src/components/assistant-ui/clarify/parse.ts b/apps/desktop/src/components/assistant-ui/clarify/parse.ts
new file mode 100644
index 00000000000..2197bd1f52e
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/parse.ts
@@ -0,0 +1,71 @@
+import { normalizeChoices } from '@/store/clarify'
+
+import { parseMaybeObject } from '../tool/fallback-model/format'
+
+export interface ClarifyArgs {
+ questions?: { question: string; choices?: string[] | null; multiSelect?: boolean }[]
+}
+
+function stringField(row: Record<string, unknown>, key: string): string | undefined {
+ const value = row[key]
+
+ return typeof value === 'string' ? value : undefined
+}
+
+export function readClarifyArgs(args: unknown): ClarifyArgs {
+ const row = parseMaybeObject(args)
+
+ if (!Array.isArray(row.questions)) {
+ return {}
+ }
+
+ // Entries are normalized leniently here (qid comes from the gateway request, not args).
+ const questions = row.questions
+ .map(entry => {
+ const item = parseMaybeObject(entry)
+ const text = stringField(item, 'question')
+
+ if (!text) {
+ return null
+ }
+
+ const itemChoices = normalizeChoices(item.choices)
+
+ return {
+ choices: itemChoices.length > 0 ? itemChoices : null,
+ multiSelect: item.multi_select === true && itemChoices.length > 0,
+ question: text
+ }
+ })
+ .filter((entry): entry is NonNullable<typeof entry> => entry !== null)
+
+ return questions.length > 0 ? { questions } : {}
+}
+
+export interface ClarifyResponse {
+ question?: string
+ answer?: string | string[]
+ unanswered: boolean
+}
+
+/** Parse clarify tool JSON (`responses` array). */
+export function readClarifyResult(result: unknown): { responses: ClarifyResponse[] } {
+ const row = parseMaybeObject(result)
+
+ if (!Array.isArray(row.responses)) {
+ return { responses: [] }
+ }
+
+ const responses = row.responses.map((entry): ClarifyResponse => {
+ const item = parseMaybeObject(entry)
+ const answer = item.user_response
+
+ return {
+ answer: Array.isArray(answer) ? answer.map(String) : typeof answer === 'string' ? answer : undefined,
+ question: stringField(item, 'question'),
+ unanswered: item.status === 'unanswered'
+ }
+ })
+
+ return { responses }
+}
diff --git a/apps/desktop/src/components/assistant-ui/clarify/pending.tsx b/apps/desktop/src/components/assistant-ui/clarify/pending.tsx
new file mode 100644
index 00000000000..5f6d61e1874
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/pending.tsx
@@ -0,0 +1,329 @@
+'use client'
+
+import { useStore } from '@nanostores/react'
+import { type FormEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react'
+
+import { Button } from '@/components/ui/button'
+import { Loader } from '@/components/ui/loader'
+import { useI18n } from '@/i18n'
+import { triggerHaptic } from '@/lib/haptics'
+import { Loader2, MessageQuestion } from '@/lib/icons'
+import { bareChoice, type ClarifyQuestion, type ClarifyRequest, clearClarifyRequest } from '@/store/clarify'
+import { $gateway } from '@/store/gateway'
+import { reconnectAction } from '@/store/gateway-reconnect'
+import { notifyError } from '@/store/notifications'
+import { forgetServerRequest, respondToServerRequest } from '@/store/server-requests'
+import { requestForOwnedSession } from '@/store/session-states'
+
+import { emptyStage, QuestionBlock } from './core/question-block'
+import { CLARIFY_ICON_CLASS, ClarifyShell } from './core/shell'
+import { useClarifyKeys } from './core/use-clarify-keys'
+import type { ClarifyArgs } from './parse'
+import { handleClarifySubmitShortcut } from './submit-shortcut'
+import { UndeliveredNotice } from './undelivered-notice'
+
+/** Live batch card: all questions at once, staged locally, ONE confirm.
+ * Picks and drafts stay in component state — nothing reaches the server
+ * until the user presses the single
+ * "Confirm and continue" button, which sends the per-question locks
+ * back-to-back and completes the batch. Staged answers stay editable up to
+ * that moment. The per-question wire protocol is unchanged (the TUI/CLI
+ * still lock incrementally); this card just batches its locks at the end. */
+export function ClarifyToolPending({
+ fromArgs,
+ onAnswered,
+ request,
+ undelivered
+}: {
+ fromArgs?: ClarifyArgs
+ onAnswered: () => void
+ request: ClarifyRequest | null
+ undelivered: boolean
+}) {
+ const { t } = useI18n()
+ const copy = t.assistant.clarify
+ const gateway = useStore($gateway)
+
+ // qids only exist on the gateway request — args are a hydration-race
+ // fallback for display, never answerable (no ids to respond with).
+ const liveQuestions = request?.questions ?? []
+ const ready = Boolean(request?.requestId) && liveQuestions.length > 0
+
+ // Preview items from the tool args: same question text/choices, synthetic
+ // qids, shown disabled until the live request lands (or indefinitely when
+ // the caller has no gateway request at all — e.g. an external tool call —
+ // so the user sees the question instead of an endless spinner). ONE form
+ // renders both states: every control is disabled while !ready, so nothing
+ // is ever staged under a synthetic qid and the swap to live qids is clean.
+ const previewQuestions: ClarifyQuestion[] = useMemo(
+ () =>
+ (fromArgs?.questions ?? []).map((entry, index) => ({
+ choices: entry.choices ?? null,
+ multiSelect: entry.multiSelect ?? false,
+ qid: `args-${index}`,
+ question: entry.question
+ })),
+ [fromArgs]
+ )
+
+ const questions = ready ? liveQuestions : previewQuestions
+
+ const [staged, setStaged] = useState<Record<string, { choices: string[]; draft: string }>>({})
+ const [submitting, setSubmitting] = useState(false)
+
+ // Reconnect replay: answers the server already locked (an earlier window's
+ // partial progress) pre-stage their questions so the restored card shows
+ // them selected instead of blank.
+ useEffect(() => {
+ const lockedAnswers = request?.lockedAnswers
+
+ if (!lockedAnswers) {
+ return
+ }
+
+ setStaged(current => {
+ const next = { ...current }
+
+ for (const question of questions) {
+ const answer = lockedAnswers[question.qid]
+
+ if (answer === undefined || answer === null || next[question.qid]) {
+ continue
+ }
+
+ const options = question.choices ?? []
+ let replayedAnswers = [answer]
+
+ if (question.multiSelect) {
+ try {
+ const parsed = JSON.parse(answer)
+
+ if (Array.isArray(parsed) && parsed.every(value => typeof value === 'string')) {
+ replayedAnswers = parsed
+ }
+ } catch {
+ // Older/non-JSON replies remain a one-value replay below.
+ }
+ }
+
+ const matchedChoices = options.filter(choice => replayedAnswers.includes(bareChoice(choice)))
+ next[question.qid] =
+ matchedChoices.length > 0 ? { choices: matchedChoices, draft: '' } : { choices: [], draft: answer }
+ }
+
+ return next
+ })
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed by the replay map only
+ }, [request?.lockedAnswers])
+
+ const stageFor = (qid: string) => staged[qid] ?? emptyStage
+
+ const stagedAnswer = useCallback(
+ (question: ClarifyQuestion): string | null => {
+ const stage = staged[question.qid] ?? emptyStage
+ const draft = stage.draft.trim()
+
+ if (question.multiSelect) {
+ // The typed text is an additional answer, not a replacement for the
+ // staged choices.
+ const combined = [...stage.choices.map(bareChoice), ...(draft ? [draft] : [])]
+
+ return combined.length > 0 ? JSON.stringify(combined) : null
+ }
+
+ if (stage.choices.length > 0) {
+ return bareChoice(stage.choices[0])
+ }
+
+ return draft ? draft : null
+ },
+ [staged]
+ )
+
+ const answeredCount = questions.filter(q => stagedAnswer(q) !== null).length
+ const canConfirm = answeredCount > 0
+
+ const confirmAll = useCallback(async () => {
+ if (!request || !gateway) {
+ notifyError(
+ new Error(request ? copy.gatewayDisconnected : copy.notReady),
+ copy.sendFailed,
+ request ? { action: reconnectAction() } : {}
+ )
+
+ return
+ }
+
+ setSubmitting(true)
+
+ try {
+ // Sequential, not Promise.all: the LAST lock resolves the blocked
+ // server request, so every earlier lock must already be accepted when
+ // it lands — a reordered burst could complete the batch with a missing
+ // answer. `clarify.lock` is a normal RPC; it rides the session's OWNER
+ // socket (a profile / Bot Chat switch re-points ambient elsewhere).
+ for (const question of questions) {
+ const answer = stagedAnswer(question)
+
+ await requestForOwnedSession<{ remaining?: string[]; status?: string }>(
+ request.sessionId,
+ gateway.request.bind(gateway) as typeof gateway.request,
+ 'clarify.lock',
+ {
+ answer,
+ question_id: question.qid,
+ request_id: request.requestId
+ }
+ )
+ }
+
+ forgetServerRequest(request.requestId)
+
+ triggerHaptic('submit')
+ onAnswered()
+ // tool.complete lands next → ClarifyToolSettled.
+ clearClarifyRequest(request.requestId, request.sessionId)
+ } catch (error) {
+ notifyError(error, copy.sendFailed)
+ setSubmitting(false)
+ }
+ }, [copy, gateway, onAnswered, questions, request, stagedAnswer])
+
+ const toggleChoice = useCallback((question: ClarifyQuestion, choice: string) => {
+ setStaged(current => {
+ const stage = current[question.qid] ?? emptyStage
+
+ const next = question.multiSelect
+ ? stage.choices.includes(choice)
+ ? stage.choices.filter(value => value !== choice)
+ : [...stage.choices, choice]
+ : [choice]
+
+ // Multi-select keeps the typed text alongside the toggled choices;
+ // single-select stays mutually exclusive.
+ return { ...current, [question.qid]: { choices: next, draft: question.multiSelect ? stage.draft : '' } }
+ })
+ }, [])
+
+ const draftFor = useCallback((question: ClarifyQuestion, value: string) => {
+ setStaged(current => {
+ const stage = current[question.qid] ?? emptyStage
+
+ // Multi-select keeps the staged choices while the free-text field is
+ // edited; single-select stays mutually exclusive.
+ return { ...current, [question.qid]: { choices: question.multiSelect ? stage.choices : [], draft: value } }
+ })
+ }, [])
+
+ const cancelAll = useCallback(async () => {
+ if (!request) {
+ return
+ }
+
+ onAnswered()
+ clearClarifyRequest(request.requestId, request.sessionId)
+
+ // A response with no `answers` is the cancel-all (the plain Esc path).
+ respondToServerRequest(request.requestId, {})
+ }, [onAnswered, request])
+
+ const handleSubmit = useCallback(
+ (event: FormEvent<HTMLFormElement>) => {
+ event.preventDefault()
+
+ if (ready && canConfirm) {
+ void confirmAll()
+ }
+ },
+ [canConfirm, confirmAll, ready]
+ )
+
+ const clearStage = useCallback((question: ClarifyQuestion) => {
+ setStaged(current => ({ ...current, [question.qid]: emptyStage }))
+ }, [])
+
+ const isStaged = useCallback((question: ClarifyQuestion) => stagedAnswer(question) !== null, [stagedAnswer])
+
+ const formRef = useRef<HTMLFormElement | null>(null)
+
+ const keys = useClarifyKeys({
+ enabled: ready && !submitting,
+ formRef,
+ isStaged,
+ onClear: clearStage,
+ onConfirm: () => void confirmAll(),
+ onToggle: toggleChoice,
+ questions
+ })
+
+ const disabled = submitting || !ready
+
+ if (questions.length === 0) {
+ return (
+ <ClarifyShell aria-label={copy.loadingQuestion} className="my-1.5 grid min-h-12 place-items-center" role="status">
+ <Loader aria-hidden="true" className="size-6 text-(--ui-text-tertiary)" role="presentation" type="rose-curve" />
+ </ClarifyShell>
+ )
+ }
+
+ return (
+ <form
+ aria-busy={ready || undelivered ? undefined : 'true'}
+ className="my-1.5 grid gap-4"
+ data-clarify-batch={questions.length}
+ data-clarify-batch-preview={ready ? undefined : ''}
+ data-clarify-choices={ready ? questions[keys.activeQuestion]?.choices?.length || undefined : undefined}
+ onKeyDownCapture={handleClarifySubmitShortcut}
+ onSubmit={handleSubmit}
+ ref={formRef}
+ >
+ {ready || undelivered ? null : (
+ <span className="sr-only" role="status">
+ {copy.loadingQuestion}
+ </span>
+ )}
+ <ClarifyShell className="grid gap-3">
+ <div className="flex items-start gap-2">
+ <span className="flex-1 text-[0.6875rem] leading-4 text-(--ui-text-tertiary)">
+ {copy.questionProgress(answeredCount, questions.length)}
+ </span>
+ <MessageQuestion aria-hidden className={CLARIFY_ICON_CLASS} />
+ </div>
+ {undelivered ? <UndeliveredNotice /> : null}
+ {questions.map((question, index) => (
+ <QuestionBlock
+ cursor={ready && keys.activeQuestion === index ? keys.cursorRow : null}
+ disabled={disabled}
+ key={question.qid}
+ onActivate={() => keys.focusQuestion(index)}
+ onDraft={value => draftFor(question, value)}
+ onOtherFocus={() => keys.onOtherFocus(index)}
+ onPick={choiceIndex => keys.pick(index, choiceIndex)}
+ question={question}
+ staged={stageFor(question.qid)}
+ />
+ ))}
+ </ClarifyShell>
+
+ {undelivered ? null : (
+ <div className="flex items-center justify-end gap-1">
+ <Button disabled={disabled} onClick={() => void cancelAll()} size="xs" type="button" variant="text">
+ {copy.skip}
+ </Button>
+ <Button disabled={disabled || !canConfirm} size="xs" type="submit">
+ {submitting ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ <>
+ {copy.confirmAndContinueLabel}
+ <span aria-hidden className="ml-0.5 text-[0.625rem] opacity-70">
+ ⏎
+ </span>
+ </>
+ )}
+ </Button>
+ </div>
+ )}
+ </form>
+ )
+}
diff --git a/apps/desktop/src/components/assistant-ui/clarify/settled.tsx b/apps/desktop/src/components/assistant-ui/clarify/settled.tsx
new file mode 100644
index 00000000000..e076570d226
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/settled.tsx
@@ -0,0 +1,54 @@
+'use client'
+
+import type { ToolCallMessagePartProps } from '@assistant-ui/react'
+
+import { ToolFallback } from '@/components/assistant-ui/tool/fallback'
+import { useI18n } from '@/i18n'
+import { CircleLetterA, MessageQuestion } from '@/lib/icons'
+import { cn } from '@/lib/utils'
+
+import { ClarifyLine, ClarifyShell } from './core/shell'
+import { readClarifyResult } from './parse'
+
+/** Settled batch card: every question with its locked (or absent) answer. */
+export function ClarifyToolSettled(props: ToolCallMessagePartProps) {
+ const { t } = useI18n()
+ const copy = t.assistant.clarify
+ const { responses } = readClarifyResult(props.result)
+
+ if (responses.length === 0) {
+ return <ToolFallback {...props} />
+ }
+
+ return (
+ <ClarifyShell className="my-1.5 grid gap-2.5" data-clarify-settled="">
+ {responses.map((row, index) => {
+ const answer = Array.isArray(row.answer) ? row.answer.join(', ') : (row.answer ?? '')
+ const blank = !answer.trim()
+
+ return (
+ <div className="grid gap-1" key={`${index}-${row.question ?? ''}`}>
+ {row.question ? (
+ <ClarifyLine icon={MessageQuestion}>
+ <span className="whitespace-pre-wrap font-medium leading-(--conversation-line-height)">
+ {row.question}
+ </span>
+ </ClarifyLine>
+ ) : null}
+ <ClarifyLine icon={CircleLetterA}>
+ <p
+ className={cn(
+ 'whitespace-pre-wrap leading-(--conversation-line-height)',
+ blank ? 'italic text-(--ui-text-tertiary)' : 'text-(--ui-text-secondary)'
+ )}
+ data-clarify-answer=""
+ >
+ {blank ? (row.unanswered ? copy.noAnswer : copy.skipped) : answer}
+ </p>
+ </ClarifyLine>
+ </div>
+ )
+ })}
+ </ClarifyShell>
+ )
+}
diff --git a/apps/desktop/src/components/assistant-ui/clarify-submit-shortcut.ts b/apps/desktop/src/components/assistant-ui/clarify/submit-shortcut.ts
similarity index 100%
rename from apps/desktop/src/components/assistant-ui/clarify-submit-shortcut.ts
rename to apps/desktop/src/components/assistant-ui/clarify/submit-shortcut.ts
diff --git a/apps/desktop/src/components/assistant-ui/clarify/undelivered-notice.tsx b/apps/desktop/src/components/assistant-ui/clarify/undelivered-notice.tsx
new file mode 100644
index 00000000000..27e8b4ee096
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/undelivered-notice.tsx
@@ -0,0 +1,18 @@
+'use client'
+
+import { Alert, AlertDescription } from '@/components/ui/alert'
+import { useI18n } from '@/i18n'
+import { AlertTriangle } from '@/lib/icons'
+
+/** Heads a card whose request never reached this window: nothing on it can
+ * answer, so say so and point at the way out instead of a silent wait. */
+export function UndeliveredNotice() {
+ const { t } = useI18n()
+
+ return (
+ <Alert className="gap-x-2 px-3 py-2 text-xs" role="status" variant="warning">
+ <AlertTriangle />
+ <AlertDescription>{t.assistant.clarify.notDelivered}</AlertDescription>
+ </Alert>
+ )
+}
diff --git a/apps/desktop/src/components/assistant-ui/clarify/use-undelivered.ts b/apps/desktop/src/components/assistant-ui/clarify/use-undelivered.ts
new file mode 100644
index 00000000000..4666423bbcc
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/use-undelivered.ts
@@ -0,0 +1,64 @@
+import { useEffect, useState } from 'react'
+
+import { sessionClarifyRequest } from '@/store/clarify'
+import { $gateway } from '@/store/gateway'
+import { requestForOwnedSession } from '@/store/session-states'
+
+/** How long a painted card may wait for its gateway request before asking the
+ * backend to re-deliver it. `clarify.request` normally trails `tool.start` by
+ * a tick; seconds of silence mean the frame was lost on the way. */
+const CLARIFY_DELIVERY_GRACE_MS = 4_000
+
+/**
+ * True once the card has waited past the grace period for a request that
+ * never arrived, and a re-delivery attempt found nothing (#98645).
+ *
+ * The attempt asks the owner socket for `session.events.since` from the end
+ * of the ring: no events come back, but the channel re-delivers the
+ * session's `open_requests` to the request handlers before the call
+ * resolves, so a request the backend still holds parks and the card goes
+ * live on its own.
+ */
+export function useUndeliveredClarify(sessionId: null | string, waiting: boolean): boolean {
+ const [undelivered, setUndelivered] = useState(false)
+
+ useEffect(() => {
+ if (!waiting || !sessionId) {
+ return
+ }
+
+ let cancelled = false
+
+ const timer = window.setTimeout(async () => {
+ const gateway = $gateway.get()
+
+ if (gateway) {
+ try {
+ await requestForOwnedSession(
+ sessionId,
+ gateway.request.bind(gateway) as typeof gateway.request,
+ 'session.events.since',
+ {
+ last_seen: Number.MAX_SAFE_INTEGER,
+ session_id: sessionId
+ }
+ )
+ } catch {
+ // An older backend or a dropped socket: the notice is still right.
+ }
+ }
+
+ if (!cancelled && !sessionClarifyRequest(sessionId).get()) {
+ setUndelivered(true)
+ }
+ }, CLARIFY_DELIVERY_GRACE_MS)
+
+ return () => {
+ cancelled = true
+ window.clearTimeout(timer)
+ setUndelivered(false)
+ }
+ }, [sessionId, waiting])
+
+ return waiting && undelivered
+}
diff --git a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
index 4627243d3b0..79abac997d7 100644
--- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
@@ -10,7 +10,7 @@ import { useStore } from '@nanostores/react'
import { type ComponentProps, type FC, type ReactNode, useEffect, useRef, useState } from 'react'
import { CatalogInstallTool } from '@/components/assistant-ui/catalog-install-tool'
-import { ClarifyTool } from '@/components/assistant-ui/clarify-tool'
+import { ClarifyTool } from '@/components/assistant-ui/clarify'
import { ConnectorExecution, ConnectorTool } from '@/components/assistant-ui/connector-tool'
import { MarkdownText, MarkdownTextContent } from '@/components/assistant-ui/markdown-text'
import { McpSetupTool } from '@/components/assistant-ui/mcp-setup-tool'
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index 35e94cd03c5..9c1b65c40f3 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -3359,9 +3359,7 @@ export const ar = defineLocale({
other: 'غير ذلك',
placeholder: 'اكتب إجابتك...',
skip: 'تخطي',
- continueLabel: 'متابعة',
confirmAndContinueLabel: 'تأكيد ومتابعة',
- answeredBadge: 'تمت الإجابة',
questionProgress: (answered, total) => `تمت الإجابة على ${answered} من ${total}`
},
tool: {
diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.ts
index e7c3a0f1231..d5e7266fbbd 100644
--- a/apps/desktop/src/i18n/de.ts
+++ b/apps/desktop/src/i18n/de.ts
@@ -5709,14 +5709,9 @@ export const deOverrides = {
placeholder: 'Geben Sie Ihre Antwort ein…',
skip: 'Überspringen',
skipped: 'Übersprungen',
- continueLabel: 'Weiter',
+ noAnswer: 'Keine Antwort',
confirmAndContinueLabel: 'Bestätigen und fortfahren',
- answeredBadge: 'Beantwortet',
questionProgress: (answered, total) => `${answered} von ${total} beantwortet`,
- lateAnswer: (question, choice) => `Re: „${question}“ — meine Antwort: ${choice}`,
- lateAnswerTip: 'Diese Antwort als Folgenachricht entwerfen',
- lateAnswerHint:
- 'Dieser Prompt wartet nicht mehr. Wählen Sie eine Option, um sie als Folgenachricht zu entwerfen.',
notDelivered:
'Diese Frage hat die App nicht erreicht und kann hier nicht beantwortet werden. Klicken Sie auf Stopp, um den Durchgang zu beenden, und antworten Sie dann im Chat.'
},
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index b82435bd4ff..ee5a33acb71 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -5309,13 +5309,9 @@ export const en: Translations = {
placeholder: 'Type your answer…',
skip: 'Skip',
skipped: 'Skipped',
- continueLabel: 'Continue',
+ noAnswer: 'No answer',
confirmAndContinueLabel: 'Confirm and continue',
- answeredBadge: 'Answered',
questionProgress: (answered, total) => `${answered} of ${total} answered`,
- lateAnswer: (question, choice) => `Re: "${question}" — my answer: ${choice}`,
- lateAnswerTip: 'Draft this answer as a follow-up message',
- lateAnswerHint: 'This prompt is no longer waiting. Pick an option to draft it as a follow-up message.',
notDelivered:
"This question didn't reach the app, so it can't be answered here. Press Stop to end the turn, then reply in chat."
},
diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.ts
index 673e6343bf5..08ea1bafad5 100644
--- a/apps/desktop/src/i18n/es.ts
+++ b/apps/desktop/src/i18n/es.ts
@@ -5702,14 +5702,9 @@ export const esOverrides = {
placeholder: 'Escribe tu respuesta…',
skip: 'Omitir',
skipped: 'Omitido',
- continueLabel: 'Continuar',
+ noAnswer: 'Sin respuesta',
confirmAndContinueLabel: 'Confirmar y continuar',
- answeredBadge: 'Respondido',
questionProgress: (answered, total) => `${answered} de ${total} respondidas`,
- lateAnswer: (question, choice) => `Con respecto a “${question}”: mi respuesta es ${choice}`,
- lateAnswerTip: 'Redactar esta respuesta como mensaje de seguimiento',
- lateAnswerHint:
- 'Este prompt ya no espera una respuesta. Elige una opción para redactarla como mensaje de seguimiento.',
notDelivered:
'Esta pregunta no llegó a la app, así que no se puede responder aquí. Pulsa Detener para terminar el turno y luego responde en el chat.'
},
diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.ts
index 0f4413fc9cb..7dd7ea632ae 100644
--- a/apps/desktop/src/i18n/fr.ts
+++ b/apps/desktop/src/i18n/fr.ts
@@ -5723,14 +5723,9 @@ export const frOverrides = {
placeholder: 'Saisissez votre réponse…',
skip: 'Passer',
skipped: 'Ignoré',
- continueLabel: 'Continuer',
+ noAnswer: 'Pas de réponse',
confirmAndContinueLabel: 'Confirmer et continuer',
- answeredBadge: 'Répondu',
questionProgress: (answered, total) => `${answered} réponse${answered === 1 ? '' : 's'} sur ${total}`,
- lateAnswer: (question, choice) => `Re : « ${question} » — ma réponse : ${choice}`,
- lateAnswerTip: 'Rédiger cette réponse comme message de suivi',
- lateAnswerHint:
- "Cette invite n'attend plus de réponse. Choisissez une option pour la rédiger comme message de suivi.",
notDelivered:
"Cette question n'a pas atteint l'app, elle ne peut donc pas être répondue ici. Appuyez sur Arrêter pour terminer le tour, puis répondez dans le chat."
},
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 62c0f9d06dc..fffb761b772 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -3929,14 +3929,9 @@ export const ja = defineLocale({
placeholder: '回答を入力…',
skip: 'スキップ',
skipped: 'スキップ済み',
- continueLabel: '続行',
+ noAnswer: '回答なし',
confirmAndContinueLabel: '確定して続行',
- answeredBadge: '回答済み',
questionProgress: (answered, total) => `${total}問中${answered}問回答済み`,
- lateAnswer: (question, choice) => `「${question}」について — 私の回答: ${choice}`,
- lateAnswerTip: 'この回答をフォローアップメッセージとして下書きします',
- lateAnswerHint:
- 'この質問はもう回答を待っていません。選択肢を選ぶとフォローアップメッセージとして下書きされます。',
notDelivered:
'この質問はアプリに届かなかったため、ここでは回答できません。停止を押してターンを終了し、チャットで返信してください。'
},
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index 3de6c352377..a51fb67fb18 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -4051,13 +4051,9 @@ export const ru = defineLocale({
placeholder: 'Введите ваш ответ…',
skip: 'Пропустить',
skipped: 'Пропущено',
- continueLabel: 'Продолжить',
+ noAnswer: 'Нет ответа',
confirmAndContinueLabel: 'Подтвердить и продолжить',
- answeredBadge: 'Ответ дан',
questionProgress: (answered, total) => `Ответ дан на ${answered} из ${total}`,
- lateAnswer: (question, choice) => `Re: «${question}» — мой ответ: ${choice}`,
- lateAnswerTip: 'Составить этот ответ как продолжение',
- lateAnswerHint: 'Этот промпт больше не ждёт. Выберите вариант, чтобы составить его как сообщение-продолжение.',
notDelivered:
'Этот вопрос не дошёл до приложения, поэтому ответить здесь нельзя. Нажмите «Стоп», чтобы завершить ход, и ответьте в чате.'
},
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index ef9bb820e8c..d15be99951f 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -4421,13 +4421,9 @@ export interface Translations {
placeholder: string
skip: string
skipped: string
- continueLabel: string
+ noAnswer: string
confirmAndContinueLabel: string
- answeredBadge: string
questionProgress: (answered: number, total: number) => string
- lateAnswer: (question: string, choice: string) => string
- lateAnswerTip: string
- lateAnswerHint: string
notDelivered: string
}
catalogInstall: {
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index 20769f6d9b7..a4d6d9c7781 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -4093,13 +4093,9 @@ export const zhHant = defineLocale({
placeholder: '輸入您的答案…',
skip: '略過',
skipped: '已略過',
- continueLabel: '繼續',
+ noAnswer: '未回答',
confirmAndContinueLabel: '確認並繼續',
- answeredBadge: '已回答',
questionProgress: (answered, total) => `已回答 ${answered}/${total}`,
- lateAnswer: (question, choice) => `關於「${question}」 — 我的回答: ${choice}`,
- lateAnswerTip: '將此回答起草為後續訊息',
- lateAnswerHint: '此問題已不再等待回答。選擇一個選項會將其起草為後續訊息。',
notDelivered: '此問題未送達應用程式,無法在此回答。請按停止結束本輪,然後在聊天中回覆。'
},
tool: {
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index e5b2cce8352..0150c2786fc 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -4883,13 +4883,9 @@ export const zh = defineLocale({
placeholder: '输入你的答案…',
skip: '跳过',
skipped: '已跳过',
- continueLabel: '继续',
+ noAnswer: '未回答',
confirmAndContinueLabel: '确认并继续',
- answeredBadge: '已回答',
questionProgress: (answered, total) => `已回答 ${answered}/${total}`,
- lateAnswer: (question, choice) => `关于"${question}" — 我的回答: ${choice}`,
- lateAnswerTip: '将此回答起草为后续消息',
- lateAnswerHint: '此问题已不再等待回答。选择一个选项会将其起草为后续消息。',
notDelivered: '此问题未送达应用,无法在此回答。请按停止结束本轮,然后在聊天中回复。'
},
catalogInstall: {
diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.ts
index 33d29107778..466d88e2380 100644
--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts
+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts
@@ -93,10 +93,10 @@ function liveToolArgs(payload: GatewayEventPayload | undefined): Record<string,
function toolPayloadMatchValues(payload: GatewayEventPayload | undefined): string[] {
const payloadArgs = liveToolArgs(payload)
- // `question` is clarify's identifying arg: a synthetic row hydrated from
- // `clarify.request` (a fresh request id) must correlate with the `tool.start`
- // row (the model's tool_call_id) so the two ids don't produce a duplicate
- // clarify card — same correlation ClarifyToolPending uses for request↔args.
+ // A synthetic row hydrated from `clarify.request` (a fresh request id) must
+ // correlate with the `tool.start` row (the model's tool_call_id) so the two
+ // ids don't produce a duplicate clarify card — same correlation
+ // ClarifyToolPending uses for request↔args.
// A connection request carries the model's tool_call_id itself, so it needs no arg match.
const query =
firstStringField(payloadArgs, ['search_term', 'query', 'question', 'command', 'code', 'path']) ||
@@ -109,13 +109,9 @@ function toolPayloadMatchValues(payload: GatewayEventPayload | undefined): strin
}
/**
- * The batch-clarify counterpart of the `question` correlation key: a batch
- * payload has no top-level `question`, only `questions[]`, so without this
- * the request row and the tool.start row never match and the card mounts
- * twice. The joined per-question texts identify the batch the same way one
- * question text identifies a single prompt. The `\u0000` separator cannot
- * appear in real question text, so a batch key can never collide with a
- * single-question key.
+ * A batch payload has no top-level `question`, only `questions[]`, so without
+ * this the request row and the tool.start row never match and the card mounts
+ * twice. The joined per-question texts identify the batch.
*/
function batchClarifyMatchValue(questions: unknown): string {
if (!Array.isArray(questions)) {
@@ -495,19 +491,13 @@ function skippedClarifyResult(part: Extract<ChatMessagePart, { type: 'tool-call'
const args = recordFromUnknown(part.args) ?? {}
const questions = Array.isArray(args.questions) ? args.questions : []
- if (questions.length > 0) {
- return {
- responses: questions.map(entry => ({
- question: firstStringField(recordFromUnknown(entry) ?? {}, ['question']),
- user_response: ''
- })),
- timed_out: true
- }
- }
-
return {
- question: firstStringField(args, ['question']),
- user_response: ''
+ outcome: 'cancelled',
+ responses: questions.map(entry => ({
+ question: firstStringField(recordFromUnknown(entry) ?? {}, ['question']),
+ status: 'unanswered',
+ user_response: null
+ }))
}
}
diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.ts
index e09b9075795..d6a23486aa0 100644
--- a/apps/desktop/src/lib/chat-messages/types.ts
+++ b/apps/desktop/src/lib/chat-messages/types.ts
@@ -134,10 +134,6 @@ export type GatewayEventPayload = {
question?: string
// btw.complete / background.complete — id of the side/background task
task_id?: string
- choices?: string[] | null
- multi_select?: boolean
- // clarify.request batch form: questions replaces question/choices, and
- // answers (qid → locked answer) rides along on reconnect replay only.
questions?: unknown
answers?: Record<string, unknown>
// connection request (manage_connections MCP targets — inline approval card)
diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-parts.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-parts.tsx
index bead6b31a28..733529b5eb7 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-chat-parts.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-parts.tsx
@@ -350,7 +350,7 @@ export function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...
}
/** A pending prompt as the room renders it. */
-export interface GroupRoomPrompt extends GroupPrompt {
+export type GroupRoomPrompt = GroupPrompt & {
/** TODO(bot-mode-types): nothing ever sets this — syncGroupClarify builds
* every entry without a thread — so the answer GroupClarifyCard echoes back
* into the room always lands in the 'legacy' thread instead of the thread
@@ -387,22 +387,21 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
const [picked, setPicked] = useState<Record<string, string[]>>({})
const [sending, setSending] = useState(false)
- const questions: GroupClarifyQuestion[] =
- entry.questions && entry.questions.length
- ? entry.questions.map((q, i) => ({
- qid: q?.qid ?? q?.id ?? `q${i}`,
- question: typeof q?.question === 'string' ? q.question : '',
- choices: Array.isArray(q?.choices) ? q.choices.filter(c => typeof c === 'string' && c) : [],
- multiSelect: Boolean(q?.multi_select ?? q?.multiSelect)
- }))
- : [
- {
- qid: '__single__',
- question: entry.question,
- choices: entry.choices,
- multiSelect: entry.multiSelect
- }
- ]
+ const questions: GroupClarifyQuestion[] = isApproval
+ ? [
+ {
+ qid: 'approval',
+ question: entry.question,
+ choices: entry.choices,
+ multiSelect: false
+ }
+ ]
+ : entry.questions.map(q => ({
+ qid: q.qid,
+ question: typeof q.question === 'string' ? q.question : '',
+ choices: Array.isArray(q.choices) ? q.choices.filter(c => typeof c === 'string' && c) : [],
+ multiSelect: Boolean(q.multi_select)
+ }))
const answerFor = (q: GroupClarifyQuestion) => {
const chosen = picked[q.qid] || []
@@ -414,7 +413,7 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
return isApproval ? '' : (drafts[q.qid] || '').trim()
}
- const allAnswered = questions.every(q => answerFor(q))
+ const anyAnswered = questions.some(q => answerFor(q))
/** `chosen` short-circuits the staged answer: approval choices submit on
* click (#91706), so the value travels with the click instead of waiting
@@ -422,20 +421,20 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
const submit = async (chosen?: string) => {
const resolve = (q: GroupClarifyQuestion) => chosen ?? answerFor(q)
- if (!member || sending || !questions.every(q => resolve(q))) {
+ if (!member || sending || !questions.some(q => resolve(q))) {
return
}
setSending(true)
try {
- if (isApproval || !(entry.questions && entry.questions.length)) {
+ if (isApproval) {
await answerGroupClarify(entry, member, resolve(questions[0]))
} else {
- const answers: Record<string, string> = {}
+ const answers: Record<string, null | string> = {}
for (const q of questions) {
- answers[q.qid] = resolve(q)
+ answers[q.qid] = resolve(q) || null
}
await answerGroupClarify(entry, member, answers)
@@ -444,7 +443,10 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
// Echo the exchange into the room log so the thread reads complete.
const summary = isApproval
? `${resolve(questions[0])} — ${entry.command || entry.question || b.group.commandApproval}`
- : questions.map(q => (questions.length > 1 ? `${q.question}: ${resolve(q)}` : resolve(q))).join('\n')
+ : questions
+ .filter(q => resolve(q))
+ .map(q => (questions.length > 1 ? `${q.question}: ${resolve(q)}` : resolve(q)))
+ .join('\n')
appendGroupChatEntry(
group,
@@ -575,7 +577,7 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
{/* Approval choices submit on click; only clarify answers need a footer. */}
{isApproval ? null : (
<div className="flex justify-end">
- <Button disabled={sending || !allAnswered || !member} onClick={() => void submit()} size="sm">
+ <Button disabled={sending || !anyAnswered || !member} onClick={() => void submit()} size="sm">
{sending ? 'Sending…' : 'Answer'}
</Button>
</div>
diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts
index 1335369d9c2..e363efc1f0d 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts
@@ -614,7 +614,11 @@ describe('clarify and approvals (#90694)', () => {
const CLARIFY = {
id: 'req-clarify-1',
method: 'clarify',
- params: { choices: ['staging', 'prod'], multi_select: false, question: 'Which env should I target?' }
+ params: {
+ questions: [
+ { choices: ['staging', 'prod'], multi_select: false, qid: 'q0', question: 'Which env should I target?' }
+ ]
+ }
}
const APPROVAL = {
@@ -673,8 +677,7 @@ describe('clarify and approvals (#90694)', () => {
expect(mirrored).toHaveLength(1)
expect(mirrored[0].requestId).toBe('req-clarify-1')
- expect(mirrored[0].question).toBe('Which env should I target?')
- expect(mirrored[0].choices).toEqual(['staging', 'prod'])
+ expect(mirrored[0]).toMatchObject({ kind: 'clarify', questions: CLARIFY.params.questions })
// Badge is derived from $groupClarify, not a copy — nothing writes
// $groupNeedsYou here, so there is nothing to keep in sync.
expect(turns.groupHasPendingClarify(chat.$groupClarify.get(), 'Core')).toBe(true)
@@ -698,19 +701,6 @@ describe('clarify and approvals (#90694)', () => {
expect(Object.keys(chat.$groupClarify.get())).toHaveLength(0)
})
- it('answers the open request by id through request.answer and clears the mirror', async () => {
- const room = await loadRoom()
- const member: GroupMember = { name: 'research', title: '' }
-
- room.turns.syncGroupClarify('Core', member, 't1', { open_requests: [CLARIFY] })
- await room.turns.answerGroupClarify(Object.values(room.chat.$groupClarify.get())[0], member, 'staging')
-
- expect(room.gateway.rpcFor('request.answer').map(call => call.params)).toEqual([
- { id: 'req-clarify-1', result: { answer: 'staging' } }
- ])
- expect(Object.keys(room.chat.$groupClarify.get())).toHaveLength(0)
- })
-
it('locks one batch question per clarify.lock call, in order', async () => {
const room = await loadRoom()
const member: GroupMember = { name: 'research', title: '' }
@@ -811,7 +801,7 @@ describe('clarify and approvals (#90694)', () => {
submitted = true
}
- if (method === 'request.answer') {
+ if (method === 'clarify.lock') {
answered = true
}
@@ -855,7 +845,7 @@ describe('clarify and approvals (#90694)', () => {
await mirrored
const [prompt] = Object.values(room.chat.$groupClarify.get())
const correctRoom = prompt.group
- await room.turns.answerGroupClarify(prompt, member, 'staging')
+ await room.turns.answerGroupClarify(prompt, member, { q0: 'staging' })
await drive
expect(correctRoom).toBe('Renamed')
expect(Object.keys(room.chat.$groupChats.get())).toEqual(['Renamed'])
@@ -1131,11 +1121,13 @@ describe('clarify and approvals (#90694)', () => {
const entry = Object.values(chat.$groupClarify.get())[0]
- expect(entry.kind).toBe('approval')
- expect(entry.command).toBe('rm -rf ./build')
- expect(entry.question).toBe('Clean the build directory')
- expect(entry.choices).toEqual(['once', 'session', 'deny'])
- expect(entry.sessionId).toBe('rt-research-1')
+ expect(entry).toMatchObject({
+ choices: ['once', 'session', 'deny'],
+ command: 'rm -rf ./build',
+ kind: 'approval',
+ question: 'Clean the build directory',
+ sessionId: 'rt-research-1'
+ })
})
it('falls back to once/deny when the server sends no choice set', async () => {
@@ -1145,7 +1137,7 @@ describe('clarify and approvals (#90694)', () => {
pending_approval: { command: 'ls', request_id: 'req-a2' }
})
- expect(Object.values(chat.$groupClarify.get())[0].choices).toEqual(['once', 'deny'])
+ expect(Object.values(chat.$groupClarify.get())[0]).toMatchObject({ choices: ['once', 'deny'] })
})
it('routes approvals through approval.respond with the session and choice', async () => {
diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.ts
index d15b4dbe64e..9a6e5b21cf8 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-turns.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.ts
@@ -155,9 +155,6 @@ function pickStrandedGroupTurnReply(messages: GroupTurnTranscriptMessage[], befo
/** A clarify question blocking inside a member's session, as `session.resume`
* reports it. Older backends omit the field entirely. */
interface GroupPendingClarify {
- choices?: string[]
- multi_select?: unknown
- question?: unknown
questions?: GroupPromptQuestion[]
request_id?: string
}
@@ -700,12 +697,9 @@ export function syncGroupClarify(
? {
...base,
kind: 'clarify',
- question: typeof clarify.question === 'string' ? clarify.question : '',
- choices: Array.isArray(clarify.choices) ? clarify.choices.filter(c => typeof c === 'string' && c) : [],
- multiSelect: Boolean(clarify.multi_select),
// Batch clarifies carry `questions`; the room card answers them
// one wire call per question, mirroring the 1:1 batch contract.
- questions: Array.isArray(clarify.questions) ? clarify.questions : null
+ questions: Array.isArray(clarify.questions) ? clarify.questions : []
}
: {
...base,
@@ -717,9 +711,7 @@ export function syncGroupClarify(
choices:
Array.isArray(approval.choices) && approval.choices.length
? approval.choices.filter(c => typeof c === 'string' && c)
- : ['once', 'deny'],
- multiSelect: false,
- questions: null
+ : ['once', 'deny']
}
})
@@ -799,14 +791,13 @@ export function renameGroupClarify(oldName: string, newName: string) {
* to the member's OWN source (requestForBot), so cross-connection members work.
* - clarify: `clarify.lock` per question, sequentially — the LAST lock
* resolves the blocked server request (same contract as the 1:1 batch
- * card). A single question answers the open request by id through
- * `request.answer` (the cross-socket proxy for a response frame).
+ * card).
* - approval: `approval.respond` with the choice (once/session/always/deny),
* keyed by session + request_id — the queue-level wire every surface shares. */
export async function answerGroupClarify(
entry: GroupPrompt,
member: GroupMember,
- answers: Record<string, string> | string | undefined
+ answers: Record<string, null | string> | string | undefined
) {
let group = entry.group
@@ -828,22 +819,14 @@ export async function answerGroupClarify(
},
{ timeoutMs: APPROVAL_RESPOND_TIMEOUT_MS }
)
- } else if (entry.questions && entry.questions.length) {
+ } else {
for (const question of entry.questions) {
- // Question ids are opaque on the wire (`GroupPrompt.questions` types
- // them `unknown`); the batch card keys its answer bag by exactly them.
- const qid = (question?.qid ?? question?.id) as string
await requestForBot(member, 'clarify.lock', {
request_id: entry.requestId,
- question_id: qid,
- answer: (answers as Record<string, string>)?.[qid] ?? ''
+ question_id: question.qid,
+ answer: (answers as Record<string, null | string>)?.[question.qid] ?? null
})
}
- } else {
- await requestForBot(member, 'request.answer', {
- id: entry.requestId,
- result: { answer: typeof answers === 'string' ? answers : '' }
- })
}
if (!binding.isLive()) {
diff --git a/apps/desktop/src/plugins/hermes-bots/types.ts b/apps/desktop/src/plugins/hermes-bots/types.ts
index 42c4bfb733a..2e0021c8e76 100644
--- a/apps/desktop/src/plugins/hermes-bots/types.ts
+++ b/apps/desktop/src/plugins/hermes-bots/types.ts
@@ -237,33 +237,22 @@ export interface GroupChat {
watermarks: Record<string, number>
}
-export type GroupPromptKind = 'approval' | 'clarify'
-
/**
* One sub-question of a batch clarify, straight off the wire. `choices` and
- * `question` stay unknown because the card re-validates them; the two id
- * spellings are the keys it maps drafts and answers by.
+ * `question` stay unknown because the card re-validates them.
*/
export interface GroupPromptQuestion {
choices?: unknown
- id?: string
multi_select?: boolean
- multiSelect?: boolean
- qid?: string
+ qid: string
question?: unknown
}
-export interface GroupPrompt {
+interface GroupPromptBase {
at: number
- choices: string[]
- command?: string
group: string
- kind: GroupPromptKind
member: string
memberKey: string
- multiSelect: boolean
- question: string
- questions?: GroupPromptQuestion[] | null
requestId: string
sessionId?: null | string
/** The thread the blocking question belongs to — part of the mirror key,
@@ -271,6 +260,20 @@ export interface GroupPrompt {
thread?: string
}
+interface GroupApprovalPrompt extends GroupPromptBase {
+ choices: string[]
+ command?: string
+ kind: 'approval'
+ question: string
+}
+
+interface GroupClarifyPrompt extends GroupPromptBase {
+ kind: 'clarify'
+ questions: GroupPromptQuestion[]
+}
+
+export type GroupPrompt = GroupApprovalPrompt | GroupClarifyPrompt
+
export type GroupActivityKind =
| 'cancelled'
| 'capped'
diff --git a/apps/desktop/src/store/clarify.test.ts b/apps/desktop/src/store/clarify.test.ts
index f1973af7e93..27e2ef74295 100644
--- a/apps/desktop/src/store/clarify.test.ts
+++ b/apps/desktop/src/store/clarify.test.ts
@@ -17,10 +17,8 @@ import { $activeSessionId } from './session'
function clarify(sessionId: string | null, requestId: string): ClarifyRequest {
return {
+ questions: [{ choices: null, multiSelect: false, qid: 'q0', question: `question-${requestId}` }],
requestId,
- question: `question-${requestId}`,
- choices: null,
- multiSelect: false,
sessionId
}
}
@@ -102,7 +100,7 @@ describe('skipClarifyRequest', () => {
$gateway.set(null)
})
- it('answers the session\u2019s clarify with an empty answer and drops it', async () => {
+ it('cancels the session\u2019s clarify with an empty response and drops it', async () => {
const respond = vi.fn()
rememberServerRequest({ fail: vi.fn(), id: 'req-a', method: 'clarify', params: {}, respond })
@@ -111,7 +109,7 @@ describe('skipClarifyRequest', () => {
await expect(skipClarifyRequest('session-a')).resolves.toBe(true)
- expect(respond).toHaveBeenCalledWith({ answer: '' })
+ expect(respond).toHaveBeenCalledWith({})
expect(hasClarifyRequest('session-a')).toBe(false)
// A background session's question is untouched — only the one being typed
// over is skipped.
diff --git a/apps/desktop/src/store/clarify.ts b/apps/desktop/src/store/clarify.ts
index aaef93106cb..22e74717c2d 100644
--- a/apps/desktop/src/store/clarify.ts
+++ b/apps/desktop/src/store/clarify.ts
@@ -4,7 +4,6 @@ import { respondToServerRequest } from './server-requests'
import { $activeSessionId } from './session'
export interface ClarifyQuestion {
- /** Server-generated wire id (q0..qN) — clarify.respond keys answers by it. */
qid: string
question: string
choices: string[] | null
@@ -13,16 +12,12 @@ export interface ClarifyQuestion {
export interface ClarifyRequest {
requestId: string
- question: string
- choices: string[] | null
- multiSelect: boolean
/** Local receipt time (Unix seconds), used to reject stale resume cleanup. */
receivedAt?: number
sessionId: string | null
- /** Batch (multi-question) clarify: present instead of question/choices. */
- questions?: ClarifyQuestion[]
- /** Answers already locked server-side (reconnect replay): qid → answer. */
- lockedAnswers?: Record<string, string>
+ questions: ClarifyQuestion[]
+ /** Answers already locked server-side (reconnect replay): qid → answer, null = skipped. */
+ lockedAnswers?: Record<string, null | string>
}
/**
@@ -53,19 +48,6 @@ export function normalizeChoices(choices: unknown): string[] {
)
}
-/**
- * Structured warning for a clarify payload that arrived with choices but had
- * them all normalized away — keeps the remaining #69122 "no selectable choices"
- * triggers diagnosable in the field without dead constant fields.
- */
-export function warnDroppedChoices(source: 'gateway' | 'tool_args', question: string, rawChoices: unknown): void {
- console.warn('[clarify] choices dropped after normalization', {
- choices_count: Array.isArray(rawChoices) ? rawChoices.length : 0,
- question_length: question.length,
- source
- })
-}
-
/**
* Validate and normalize a batch clarify payload's `questions` array.
*
@@ -178,17 +160,11 @@ export const hasClarifyRequest = (sessionId: string | null | undefined): boolean
Boolean($clarifyRequests.get()[keyFor(sessionId)])
/**
- * Answer `sessionId`'s pending clarify with an empty answer (a skip) and drop it
- * locally, resolving to whether there was one to skip.
- *
* The composer uses this when the user types a real message instead of picking
* an option: a clarify blocks the agent inside its tool batch, so leaving it
* unanswered would park the follow-up until the server-side clarify timeout
- * (default 5 min) — the message looks sent and nothing happens. Skipping lets
+ * — the message looks sent and nothing happens. Skipping lets
* the tool return and the turn carry on with the user's actual words.
- *
- * An empty answer is the same thing the card's own Skip button sends; answering
- * a request that already expired is a no-op, so racing the timeout is harmless.
*/
export async function skipClarifyRequest(sessionId: string | null | undefined): Promise<boolean> {
const request = $clarifyRequests.get()[keyFor(sessionId)]
@@ -201,7 +177,7 @@ export async function skipClarifyRequest(sessionId: string | null | undefined):
// leave a live card the user can answer a second time.
clearClarifyRequest(request.requestId, request.sessionId)
- respondToServerRequest(request.requestId, { answer: '' })
+ respondToServerRequest(request.requestId, {})
return true
}
diff --git a/apps/desktop/src/store/prompts.test.ts b/apps/desktop/src/store/prompts.test.ts
index 00a3a21009c..b564bd4b171 100644
--- a/apps/desktop/src/store/prompts.test.ts
+++ b/apps/desktop/src/store/prompts.test.ts
@@ -429,7 +429,11 @@ describe('$activeSessionAwaitingInput', () => {
clearApprovalRequest('s1')
expect($activeSessionAwaitingInput.get()).toBe(false)
- setClarifyRequest({ choices: null, multiSelect: false, question: 'q', requestId: 'c1', sessionId: 's1' })
+ setClarifyRequest({
+ questions: [{ choices: null, multiSelect: false, qid: 'q0', question: 'q' }],
+ requestId: 'c1',
+ sessionId: 's1'
+ })
expect($activeSessionAwaitingInput.get()).toBe(true)
})
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index d6f7d4534f5..8b657edcac1 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4320,14 +4320,11 @@ export interface OnboardingCatalogPlugin {
app_state: CatalogAppState
sentence: string
}
-/** Single question: ``question`` / ``choices`` (/ ``multi_select``); batch: ``questions``. ``answers`` rides only on a reconnect replay (locks the server already accepted). */
+/** ``answers`` rides only on a reconnect replay (locks the server already accepted; null = skipped). */
export interface ClarifyRequestParams {
session_id: string
- question?: string | null
- choices?: string[] | null
- multi_select?: boolean | null
- questions?: ClarifyQuestion[] | null
- answers?: Record<string, string> | null
+ questions: ClarifyQuestion[]
+ answers?: Record<string, string | null> | null
}
export interface ClarifyQuestion {
qid: string
@@ -4335,10 +4332,9 @@ export interface ClarifyQuestion {
choices?: string[] | null
multi_select?: boolean
}
-/** Single: ``{answer}`` ('' = skip). Batch: ``{answers}`` for the whole set (early locks go through the ``clarify.lock`` RPC); a response with neither is cancel-all. */
+/** ``{answers}`` for the whole set (early locks go through the ``clarify.lock`` RPC); a response without ``answers`` is cancel-all. */
export interface ClarifyResult {
- answer?: string | null
- answers?: Record<string, string> | null
+ answers?: Record<string, string | null> | null
}
/** ``tui_gateway/server.py::_approval_request_payload`` — the command is redacted server-side. */
export interface ApprovalRequestParams {
@@ -5625,7 +5621,7 @@ export const RPC_METHODS = [
export interface ServerRequestMap {
/** A dangerous command awaits the user's decision. */
approval: { params: ApprovalRequestParams; result: ApprovalResult }
- /** The clarify tool: ask the user one question or a batch. */
+ /** The clarify tool: ask the user 1-5 questions. */
clarify: { params: ClarifyRequestParams; result: ClarifyResult }
/** Masked sudo password for the Bot Screen package install; app-level (empty session). */
'display.install.sudo': { params: DisplayInstallSudoParams; result: ValueResult }
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 7a63156f324..2cec2bb8dd4 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -7634,71 +7634,31 @@
},
"ClarifyRequestParams": {
"additionalProperties": false,
- "description": "Single question: ``question`` / ``choices`` (/ ``multi_select``); batch: ``questions``.\n``answers`` rides only on a reconnect replay (locks the server already accepted).",
+ "description": "``answers`` rides only on a reconnect replay (locks the server already accepted; null = skipped).",
"properties": {
"session_id": {
"title": "Session Id",
"type": "string"
},
- "question": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Question"
- },
- "choices": {
- "anyOf": [
- {
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Choices"
- },
- "multi_select": {
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Multi Select"
- },
"questions": {
- "anyOf": [
- {
- "items": {
- "$ref": "#/components/schemas/ClarifyQuestion"
- },
- "type": "array"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Questions"
+ "items": {
+ "$ref": "#/components/schemas/ClarifyQuestion"
+ },
+ "title": "Questions",
+ "type": "array"
},
"answers": {
"anyOf": [
{
"additionalProperties": {
- "type": "string"
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
},
"type": "object"
},
@@ -7711,32 +7671,28 @@
}
},
"required": [
- "session_id"
+ "session_id",
+ "questions"
],
"title": "ClarifyRequestParams",
"type": "object"
},
"ClarifyResult": {
"additionalProperties": false,
- "description": "Single: ``{answer}`` ('' = skip). Batch: ``{answers}`` for the whole set (early locks go through\nthe ``clarify.lock`` RPC); a response with neither is cancel-all.",
+ "description": "``{answers}`` for the whole set (early locks go through the ``clarify.lock`` RPC); a response\nwithout ``answers`` is cancel-all.",
"properties": {
- "answer": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Answer"
- },
"answers": {
"anyOf": [
{
"additionalProperties": {
- "type": "string"
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
},
"type": "object"
},
@@ -39003,7 +38959,7 @@
},
{
"name": "clarify",
- "summary": "The clarify tool: ask the user one question or a batch.",
+ "summary": "The clarify tool: ask the user 1-5 questions.",
"params": [
{
"name": "params",
diff --git a/evals/core_tool_deferral/worker.py b/evals/core_tool_deferral/worker.py
index b94d23d0e35..c37a851a488 100644
--- a/evals/core_tool_deferral/worker.py
+++ b/evals/core_tool_deferral/worker.py
@@ -104,17 +104,14 @@ IMG_URL = taskmod.IMG_URL
_clarify_answers = list(TASK.get("clarify_answers") or [])
-def clarify_cb(question, choices, multi_select=False):
- CALLBACK_LOG.append({"name": "clarify", "question": question, "choices": choices})
- if _clarify_answers:
- ans = _clarify_answers.pop(0)
- else:
- ans = "Use your best judgement."
- if choices:
- for c in choices:
- if ans.lower() in str(c).lower():
- return str(c)
- return ans
+def clarify_cb(questions):
+ answers = {}
+ for entry in questions:
+ CALLBACK_LOG.append({"name": "clarify", "question": entry["question"], "choices": entry["choices"]})
+ ans = _clarify_answers.pop(0) if _clarify_answers else "Use your best judgement."
+ match = next((str(c) for c in entry["choices"] or [] if ans.lower() in str(c).lower()), None)
+ answers[entry["qid"]] = match or ans
+ return {"answers": answers, "outcome": "submitted"}
def tour_cb(payload):
CALLBACK_LOG.append({"name": "tour", "payload": payload})
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index f6e990badfb..626d7806ad1 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -454,7 +454,9 @@ class GatewayInboundMixin:
try:
await _clarify_adapter.retire_clarify_card(
_pending_clarify.clarify_id,
- t("gateway.clarify.answered", response=_pending_clarify.response or _raw_clarify_reply))
+ t("gateway.clarify.answered",
+ response=_raw_clarify_reply if _pending_clarify.response == _clarify_mod.SKIPPED
+ else _pending_clarify.response or _raw_clarify_reply))
except Exception:
logger.debug("Failed to retire clarify card after typed answer", exc_info=True)
return ""
@@ -466,7 +468,7 @@ class GatewayInboundMixin:
# Native-choice prompts reject unmatched prose so it continues through normal busy
# routing. Release this clarify first: redirect() degrades to steer() while tools
# execute, and that steer cannot drain until the clarify tool returns.
- if _clarify_mod.resolve_gateway_clarify(_pending_clarify.clarify_id, ""):
+ if _clarify_mod.resolve_gateway_clarify(_pending_clarify.clarify_id, _clarify_mod.CANCELLED):
# Adapters with a persistent native card (Slack Block Kit) retire it now, before the
# prose is routed, so its buttons stop advertising a dead answer path. The pop inside
# retire_clarify_card runs before its first await, so the agent thread's own expiry
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index f4d1ef3899d..79a23ec83a7 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -164,7 +164,7 @@ class TurnRunner:
or event_type != "tool.started"
# The adapter's send_clarify IS the user-facing rendering (interactive buttons or the
# numbered-text fallback), so a progress bubble is pure duplication — and in verbose mode it
- # dumps the raw tool-call args JSON ({"question": ..., "choices": [...]}) into the chat. Because
+ # dumps the raw tool-call args JSON into the chat. Because
# the progress queue drains on a background task, that raw JSON typically lands right underneath
# the rendered prompt (#52374).
or tool_name == "clarify"
@@ -1345,46 +1345,35 @@ class TurnRunner:
logger.warning("%s boundary timed out or failed: %s", reason, err)
return False
- def _clarify_callback_sync(self, question: str, choices, multi_select: bool = False,
- questions=None) -> str:
- """Present a clarify prompt and block on a response (clarify_tool's synchronous contract):
- schedule send_clarify on the gateway loop, block on the primitive's threading.Event with a
- timeout. Returns the response string, or a sentinel when none arrived.
-
- ``questions`` (clarify_tool's batch form) is answered here, one card per question, because
- this surface knows whether an answer arrived: the loop that would otherwise call this
- callback once per question can only recognize "no answer" from the returned sentinel text,
- and treated that text as the question's answer.
- """
- if questions:
- return self._clarify_batch_sync(questions)
- response, _answered = self._ask_clarify_question(question, choices, multi_select)
- return response
-
- def _clarify_batch_sync(self, questions) -> str:
- """Answer a batch: one card per question, stop at the first the user never answers.
- Returns the JSON shape clarify_tool's batch path reads. The stream/typing re-arm waits for
- the last question — between two cards it only opens a bubble the next boundary closes."""
+ def _clarify_callback_sync(self, questions) -> dict:
+ """Answer the clarify tool's questions (clarify_tool's synchronous contract): one card per
+ question, stop at the first the user never answers. The stream/typing re-arm waits for the
+ last question — between two cards it only opens a bubble the next boundary closes."""
+ from gateway.run_turn_runner_clarify_delivery import UNDELIVERED, UNDELIVERED_DECLINED, UNDELIVERED_NO_SURFACE
+ from tools.clarify_gateway import CANCELLED, SKIPPED
answers: Dict[str, Any] = {}
- payload: Dict[str, Any] = {"answers": answers, "timed_out": False}
+ reply: Dict[str, Any] = {"answers": answers, "outcome": "submitted"}
last = len(questions) - 1
for index, entry in enumerate(questions):
+ question = f"{entry['question']}\n{t('gateway.clarify.skip_hint')}"
raw, answered = self._ask_clarify_question(
- entry.get("question", ""), entry.get("choices"), bool(entry.get("multi_select")),
- rearm=index == last)
+ question, entry["choices"], bool(entry["multi_select"]), rearm=index == last)
+ if raw == CANCELLED:
+ reply["outcome"] = "cancelled"
+ break
if not answered:
# The surface's own no-answer text ("could not be delivered", "did not respond
# within Nm") rides along as ``notice``: blank answers alone read as user
# inactivity, which is the misreport #112684 describes for an undelivered card.
- payload.update(timed_out=True, notice=raw)
+ undelivered = raw in (UNDELIVERED, UNDELIVERED_DECLINED, UNDELIVERED_NO_SURFACE)
+ reply.update(outcome="undelivered" if undelivered else "timed_out", notice=raw)
break
- answers[entry.get("qid") or f"q{index}"] = raw
- return json.dumps(payload, ensure_ascii=False)
+ answers[entry["qid"]] = None if raw == SKIPPED else raw
+ return reply
def _ask_clarify_question(self, question, choices, multi_select, rearm: bool = True) -> tuple[str, bool]:
"""One card: register, send, wait, then retire it (no answer) or re-arm (answer).
- Returns ``(response, answered)``; the caller decides what "no answer" means — a sentinel
- for a single question, the batch's ``timed_out`` flag."""
+ Returns ``(response, answered)``; the caller decides what "no answer" means."""
from gateway.run_turn_runner_clarify_delivery import (
UNDELIVERED_NO_SURFACE, _clarify_send_then_wait, text_fallback_coro)
from tools import clarify_gateway as clarify_mod
diff --git a/gateway/run_turn_runner_clarify_delivery.py b/gateway/run_turn_runner_clarify_delivery.py
index 1370d1b397b..3b707442da9 100644
--- a/gateway/run_turn_runner_clarify_delivery.py
+++ b/gateway/run_turn_runner_clarify_delivery.py
@@ -18,9 +18,7 @@ logger = logging.getLogger(__name__)
UNDELIVERED = "[clarify prompt could not be delivered]"
UNDELIVERED_DECLINED = "[clarify prompt could not be delivered: destination refused]"
-# No status adapter (a run whose chat surface is gone): shares the ``[clarify prompt could not be
-# delivered`` prefix every consumer already treats as a non-answer
-# (agent/context_compressor.py::_CLARIFY_NON_RESPONSE_PREFIXES).
+# No status adapter (a run whose chat surface is gone).
UNDELIVERED_NO_SURFACE = "[clarify prompt could not be delivered: no chat surface]"
# Seconds a scheduled card send may take before it is classified ``ambiguous`` (possibly posted).
@@ -110,6 +108,8 @@ def _clarify_send_then_wait(fut, *, clarify_id: str, session_key: str, clarify_m
late.disarm()
if late.undeliverable:
return late.undeliverable, False
+ if response == clarify_mod.CANCELLED:
+ return response, False
if response is None or response == "":
return f"[user did not respond within {int(timeout / 60)}m]", False
return response, True
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py
index e12cfeaff94..0bdeb01cd45 100644
--- a/hermes_cli/cli_agent_setup_mixin.py
+++ b/hermes_cli/cli_agent_setup_mixin.py
@@ -12,7 +12,7 @@ from agent.i18n import t
from utils import base_url_host_matches
-def _single_query_clarify_callback(question: str, choices=None, multi_select=False) -> str:
+def _single_query_clarify_callback(questions: list) -> dict:
"""Headless clarify answer for ``hermes chat -q``.
A -q turn never builds the prompt_toolkit app, so the interactive clarify modal
@@ -23,11 +23,9 @@ def _single_query_clarify_callback(question: str, choices=None, multi_select=Fal
The oneshot path answers immediately via ``_oneshot_clarify_callback``; single-query turns need the same
headless behavior (#94943).
"""
- prefix = f"[single-query mode: no user available to answer {question!r}. "
- if choices:
- what = "subset" if multi_select else "option"
- return f"{prefix}Pick the best {what} from {choices} using your own judgment and continue.]"
- return f"{prefix}Make the most reasonable assumption you can and continue.]"
+ return {"answers": {}, "outcome": "undelivered", "notice": (
+ "single-query mode: no user available to answer. Pick the best choices using your own "
+ "judgment, or make the most reasonable assumption you can, and continue.")}
def _current_runtime(cli) -> dict:
diff --git a/hermes_cli/cli_modal_mixin.py b/hermes_cli/cli_modal_mixin.py
index 34908e53655..139dd4566b6 100644
--- a/hermes_cli/cli_modal_mixin.py
+++ b/hermes_cli/cli_modal_mixin.py
@@ -40,11 +40,6 @@ def _approval_outcome_label(result) -> str:
return t(key) if key else str(result)
-_CLARIFY_TIMEOUT_REPLY = (
- "The user did not provide a response within the time limit. "
- "Use your best judgement to make the choice and proceed.")
-
-
def _approval_gate_on(key: str) -> bool:
"""Read ``approvals.<key>`` (default on); any load failure keeps the prompt enabled."""
from cli import load_cli_config
@@ -598,48 +593,6 @@ class CLIModalMixin:
self._clarify_multi_base = None
self._paint_now()
- def _clarify_callback(self, question, choices, multi_select=False, questions=None):
- """Clarify-tool platform callback (agent thread): show the selection UI (or freetext for
- open-ended questions) and block until the key bindings answer or the timeout dismisses it
- (the agent is then told to decide). ``multi_select`` shows checkboxes (Space toggles).
- A non-empty ``questions`` list switches to the batch panel and returns
- ``{"answers": {qid: raw}}`` (plus ``"timed_out": True`` on a partial deadline expiry).
-
- The single-question path below is unchanged. See #18450.
- """
- from cli import CLI_CONFIG, _DIM, _RST, _cprint
- from tools.clarify_gateway import resolve_clarify_timeout
-
- if questions:
- return self._clarify_callback_batch(questions)
-
- # Canonical clarify timeout, shared with the gateway/TUI path; `<= 0` = unlimited.
- timeout = resolve_clarify_timeout(CLI_CONFIG)
- response_queue = queue.Queue()
- is_open_ended = not choices
- effective_multi = multi_select and not is_open_ended
- self._clarify_state = {
- "question": question,
- "choices": choices if not is_open_ended else [],
- "selected": 0,
- "multi_select": effective_multi,
- "selected_indices": set() if effective_multi else None,
- "response_queue": response_queue}
- self._clarify_deadline = None if timeout <= 0 else _time.monotonic() + timeout
- self._clarify_freetext = is_open_ended # open-ended → straight to freetext
- self._clarify_multi_base = None
- self._ring_bell(prompt=True, context=t("cli.clarify.bell_context"))
- self._paint_now()
-
- result = self._poll_modal_queue(response_queue, "_clarify_deadline")
- if result is not _TIMED_OUT:
- self._clarify_deadline = None
- self._persist_prompt_summary("?", t("cli.clarify.label"), question, str(result))
- return result
- self._clarify_teardown()
- _cprint(f"\n{_DIM}{t('cli.clarify.timed_out_agent_decides', timeout=timeout)}{_RST}")
- return _CLARIFY_TIMEOUT_REPLY
-
# --- Connection setup --------------------------------------------------
def _connection_operation(self, payload):
from tools.connectors import live
@@ -963,7 +916,7 @@ class CLIModalMixin:
# --- Batch clarify (multi-question, issue #18450) -----------------------
def _clarify_batch_set_active(self, state, index) -> None:
"""Point the batch clarify panel at question ``index``: mirror it into the flat keys the
- single-question keybindings/renderer read so ↑/↓/Space/number keys work unchanged;
+ keybindings/renderer read so ↑/↓/Space/number keys work unchanged;
open-ended drops into freetext; re-visiting restores the earlier cursor/checkboxes."""
questions_list = state["questions"]
index = max(0, min(index, len(questions_list) - 1))
@@ -1000,7 +953,7 @@ class CLIModalMixin:
entry = state["questions"][state["active"]]
state["answers"][entry["qid"]] = answer
state.setdefault("answer_meta", {})[entry["qid"]] = meta or {"kind": "choice"}
- self._persist_prompt_summary("?", t("cli.clarify.label"), entry["question"], str(answer))
+ self._persist_prompt_summary("?", t("cli.clarify.label"), entry["question"], "" if answer is None else str(answer))
total = len(state["questions"])
for offset in range(1, total + 1):
candidate = (state["active"] + offset) % total
@@ -1043,11 +996,11 @@ class CLIModalMixin:
self._clarify_freetext = True
self._clarify_prefill = meta.get("other_text") or "" if meta.get("kind") == "other" else ""
- def _clarify_callback_batch(self, questions):
- """Batch clarify panel (A-compact): all questions, one active. Returns
- ``{"answers": {qid: raw}}`` when every question is locked, plus ``"timed_out": True`` when
- the deadline expires with partial answers; a cancel string passes through unchanged so the
- tool core resolves the batch empty."""
+ def _clarify_callback(self, questions):
+ """Clarify-tool platform callback (agent thread, #18450): the batch panel (A-compact) shows
+ all questions, one active, and blocks until the key bindings lock every answer. Returns
+ ``{"answers": {qid: raw | None}, "outcome"}`` (None = skipped): ``submitted`` when every
+ question is locked, ``timed_out`` when the deadline expires, ``cancelled`` on an interrupt."""
from cli import CLI_CONFIG, _DIM, _RST, _cprint
from tools.clarify_gateway import resolve_clarify_timeout
@@ -1074,11 +1027,12 @@ class CLIModalMixin:
result = self._poll_modal_queue(response_queue, "_clarify_deadline")
if result is not _TIMED_OUT:
self._clarify_deadline = None
- return {"answers": result} if isinstance(result, dict) else result
+ outcome = "cancelled" if result is None else "submitted"
+ return {"answers": dict(state["answers"]), "outcome": outcome}
partial = dict(state["answers"])
self._clarify_teardown()
_cprint(f"\n{_DIM}{t('cli.clarify.timed_out_locked_answers', timeout=timeout)}{_RST}")
- return {"answers": partial, "timed_out": True}
+ return {"answers": partial, "outcome": "timed_out"}
def _sudo_password_callback(self) -> str:
"""Prompt for a sudo password through the prompt_toolkit UI (agent thread); clarify-style
@@ -1307,7 +1261,7 @@ class CLIModalMixin:
if self._connection_state:
self._connection_interrupt()
if self._clarify_state:
- _put(self._clarify_state, "The user cancelled. Use your best judgement to proceed.")
+ _put(self._clarify_state, None)
self._clarify_state = None
self._clarify_freetext = False
self._clarify_multi_base = None
diff --git a/hermes_cli/cli_tui_mixin.py b/hermes_cli/cli_tui_mixin.py
index 7b6835f2ae9..ee1b737ad63 100644
--- a/hermes_cli/cli_tui_mixin.py
+++ b/hermes_cli/cli_tui_mixin.py
@@ -457,11 +457,14 @@ class CLITuiMixin:
# visually move the input area. Input/agent events invalidate explicitly.
time.sleep(0.2)
- def _get_clarify_batch_display_fragments(self, state):
+ def _get_clarify_display_fragments(self):
"""Batch (multi-question) clarify panel: "N questions" header, one status line per question
(✓ answered → answer / ▸ active / · pending), and the active question's numbered choices
(+ Other) expanded beneath its status line."""
from cli import _panel_box_width, _wrap_panel_text
+ state = self._clarify_state
+ if not state:
+ return []
questions_list = state.get("questions") or []
answers = state.get("answers") or {}
answer_meta = state.get("answer_meta") or {}
@@ -484,7 +487,8 @@ class CLITuiMixin:
rows.append((row_style, wrapped))
if answered:
# Locked answer on its own line/color so it stays readable while Tab-walking.
- answer = f" {answers[entry['qid']]}"
+ locked = answers[entry['qid']]
+ answer = f" {'—' if locked is None else locked}"
for wrapped in _wrap_panel_text(answer, width, subsequent_indent=" "):
rows.append(('class:clarify-answer', wrapped))
if idx != active:
@@ -532,102 +536,6 @@ class CLITuiMixin:
panel.row(style, text)
return panel.close()
- def _get_clarify_display_fragments(self):
- """Clarify question/choices panel.
-
- Layout priority: choices + the Other option must always render even for a very long
- question; the question is budgeted to the rows left over and truncated with a marker.
- """
- from cli import _panel_box_width, _wrap_panel_text
- state = self._clarify_state
- if not state:
- return []
- if state.get("questions"):
- return self._get_clarify_batch_display_fragments(state)
- wrap = _wrap_panel_text
- question = state["question"]
- choices = state.get("choices") or []
- selected = state.get("selected", 0)
- multi_select = state.get("multi_select", False)
- selected_indices = state.get("selected_indices", set()) if multi_select else set()
- freetext = self._clarify_freetext
- title = t("cli.tui.clarify_title", agent_name=_agent_name())
- other_idx = len(choices)
-
- def _label(i, text):
- cursor = "❯" if (i == selected and not freetext) or (freetext and i == other_idx) else " "
- cb = ("[x] " if i in selected_indices else "[ ] ") if multi_select else ""
- return f"{cursor} {cb}{_num_prefix(i)}. {text}"
-
- choice_labels = [_label(i, c) for i, c in enumerate(choices)]
- other_label = _label(
- other_idx, t("cli.tui.clarify_other_type_below") if freetext else t("cli.tui.clarify_other_type_answer"))
-
- preview_lines = wrap(question, 60)
- preview_lines.extend(w for _i, w in _wrap_rows(wrap, choice_labels + [other_label], 60, " "))
- box_width = _panel_box_width(title, preview_lines)
- inner_text_width = max(8, box_width - 2)
-
- # Mandatory rows: choices + Other (or the freetext guidance line when there are no choices).
- choice_wrapped = _wrap_rows(wrap, choice_labels, inner_text_width, " ")
- if choices:
- other_wrapped = wrap(other_label, inner_text_width, subsequent_indent=" ")
- elif freetext:
- other_wrapped = wrap(t("cli.tui.clarify_guidance"), inner_text_width)
- else:
- other_wrapped = []
-
- # Row budget so the mandatory rows always render. Full chrome = top border + blank after
- # title + blank after question + blank before bottom + bottom border (5); tight = the two
- # borders (2). The compact decision reserves 1 question row on top of the choices —
- # otherwise full chrome is kept when there is no room for it, the panel overflows and
- # HSplit silently clips the choices.
- available = max(0, _term_rows() - _PANEL_RESERVED_BELOW)
- mandatory = len(choice_wrapped) + len(other_wrapped)
- use_compact_chrome = 5 + 1 + mandatory > available
- chrome_rows = 2 if use_compact_chrome else 5
- max_question_rows = min(12, max(1, available - chrome_rows - mandatory)) # soft cap on huge terminals
- # When the choices alone (plus compact chrome) fill the viewport, drop the question
- # entirely — the choices are all the user needs to select; the 1-row floor above would
- # push the tail of the choices off-screen.
- if chrome_rows + mandatory >= available:
- max_question_rows = 0
- question_wrapped = wrap(question, inner_text_width)
- if max_question_rows <= 0:
- question_wrapped = []
- elif len(question_wrapped) > max_question_rows:
- # The marker is itself a row: with a 1-row budget show the marker alone so the
- # rendered question never exceeds max_question_rows.
- question_wrapped = question_wrapped[:max(0, max_question_rows - 1)] + [t("cli.tui.clarify_question_truncated")]
-
- panel = _Panel('class:clarify-border', box_width, title, 'class:clarify-title')
- if not use_compact_chrome:
- panel.blank()
- for wrapped in question_wrapped:
- panel.row('class:clarify-question', wrapped)
- if not use_compact_chrome:
- panel.blank()
- if freetext and not choices:
- for wrapped in other_wrapped:
- panel.row('class:clarify-choice', wrapped)
- if not use_compact_chrome:
- panel.blank()
- if choices:
- for i, wrapped in choice_wrapped:
- style = 'class:clarify-selected' if i == selected and not freetext else 'class:clarify-choice'
- panel.row(style, wrapped)
- if selected == other_idx and not freetext:
- other_style = 'class:clarify-selected'
- elif freetext:
- other_style = 'class:clarify-active-other'
- else:
- other_style = 'class:clarify-choice'
- for wrapped in other_wrapped:
- panel.row(other_style, wrapped)
- if not use_compact_chrome:
- panel.blank()
- return panel.close()
-
def _render_scroll_list_panel(self, state, title, hint, labels, *, min_width, max_width, indent):
"""Titled panel with a hint row and a scrolling selectable list (model picker, palette).
@@ -856,10 +764,8 @@ class CLITuiMixin:
countdown = f' ({max(0, int(self._clarify_deadline - time.monotonic()))}s)'
if self._clarify_freetext:
hint = " " + t("cli.tui.hint_clarify_freetext")
- elif self._clarify_state.get("questions"):
- hint = " " + t("cli.tui.hint_clarify_batch")
else:
- hint = " " + t("cli.tui.hint_clarify_choice")
+ hint = " " + t("cli.tui.hint_clarify_batch")
return [('class:hint', hint), ('class:clarify-countdown', countdown)]
if self._command_running:
frame = self._command_spinner_frame()
@@ -1086,13 +992,9 @@ class CLITuiMixin:
if idx == len(choices):
# "Other" → freetext
self._clarify_freetext = True
- elif state.get("questions"):
- # Batch mode: lock the numbered choice for the active question only.
- self._clarify_batch_lock(state, choices[idx])
else:
- state["response_queue"].put(choices[idx])
- self._clarify_state = None
- self._clarify_freetext = False
+ # Lock the numbered choice for the active question only.
+ self._clarify_batch_lock(state, choices[idx])
event.app.invalidate()
return handler
@@ -1413,7 +1315,7 @@ class CLITuiMixin:
def _tui_clarify_batch_step(self, event, delta: int):
state = self._clarify_state
- if state and state.get("questions"):
+ if state:
self._clarify_batch_set_active(state, (state["active"] + delta) % len(state["questions"]))
event.app.invalidate()
@@ -1712,76 +1614,46 @@ class CLITuiMixin:
return False
def _tui_enter_clarify_freetext(self, event) -> None:
- """Clarify "Other": submit the typed answer (empty input is ignored)."""
+ """Clarify "Other": lock the typed answer; empty input skips the question."""
buf = event.app.current_buffer
text = buf.text.strip()
- if not text:
- return
state = self._clarify_state
base = getattr(self, '_clarify_multi_base', None)
- if state.get("questions"):
- # Batch mode: lock the typed answer for the active question. Multi-select "Other"
- # appends the typed answer to the checked labels as a JSON array string.
- if base is not None:
- answer = json.dumps(base + [text], ensure_ascii=False)
- meta = {"kind": "multi", "choices": list(base), "other_text": text}
- self._clarify_multi_base = None
- else:
- answer = text
- meta = {"kind": "other", "other_text": text}
+ if not text:
self._clarify_freetext = False
self._clarify_prefill = ""
- self._clarify_batch_lock(state, answer, meta=meta)
- else:
- # Multi-select: prepend the previously checked real choices.
+ self._clarify_multi_base = None
if base:
- text = ", ".join(base) + ", " + text
- self._clarify_multi_base = None
- state["response_queue"].put(text)
- self._clarify_state = None
- self._clarify_freetext = False
+ self._clarify_batch_lock(state, json.dumps(base, ensure_ascii=False),
+ meta={"kind": "multi", "choices": list(base), "other_text": ""})
+ else:
+ self._clarify_batch_lock(state, None, meta={"kind": "skipped"})
+ buf.reset()
+ event.app.invalidate()
+ return
+ # Multi-select "Other" appends the typed answer to the checked labels as a JSON array string.
+ if base is not None:
+ answer = json.dumps(base + [text], ensure_ascii=False)
+ meta = {"kind": "multi", "choices": list(base), "other_text": text}
+ self._clarify_multi_base = None
+ else:
+ answer = text
+ meta = {"kind": "other", "other_text": text}
+ self._clarify_freetext = False
+ self._clarify_prefill = ""
+ self._clarify_batch_lock(state, answer, meta=meta)
buf.reset()
event.app.invalidate()
def _tui_enter_clarify_choice(self, event) -> None:
- """Clarify choice mode: confirm the highlighted selection."""
- state = self._clarify_state
- if state.get("questions"):
- # Batch mode: lock the active question's answer and advance to the next unanswered.
- self._clarify_batch_enter(state)
- # Editing an earlier "Other" answer: prefill the composer with the previous text.
- if self._clarify_freetext and self._clarify_prefill:
- event.app.current_buffer.text = self._clarify_prefill
- event.app.current_buffer.cursor_position = len(self._clarify_prefill)
- self._clarify_prefill = ""
- event.app.invalidate()
- return
- selected = state["selected"]
- choices = state.get("choices") or []
- if state.get("multi_select"):
- indices = state.get("selected_indices")
- if not indices:
- # Nothing checked → submit empty string (parses to []).
- state["response_queue"].put("")
- self._clarify_state = None
- else:
- sorted_idx = sorted(indices)
- selected_choices = [choices[i] for i in sorted_idx if i < len(choices)]
- if len(choices) in sorted_idx and selected_choices:
- # "Other" + real choices: remember the base, switch to freetext so the typed
- # custom answer gets appended.
- self._clarify_multi_base = selected_choices
- self._clarify_freetext = True
- elif selected_choices:
- state["response_queue"].put(", ".join(selected_choices))
- self._clarify_state = None
- else:
- self._clarify_freetext = True # only "Other" checked
- elif selected < len(choices):
- state["response_queue"].put(choices[selected])
- self._clarify_state = None
- else:
- self._clarify_freetext = True # "Other" selected
+ """Clarify choice mode: lock the active question's answer and advance to the next
+ unanswered."""
+ self._clarify_batch_enter(self._clarify_state)
+ # Editing an earlier "Other" answer: prefill the composer with the previous text.
+ if self._clarify_freetext and self._clarify_prefill:
+ event.app.current_buffer.text = self._clarify_prefill
+ event.app.current_buffer.cursor_position = len(self._clarify_prefill)
+ self._clarify_prefill = ""
event.app.invalidate()
def _tui_collapse_paste(self, text: str, line_count: int, *, fallback: bool) -> str:
@@ -2117,9 +1989,6 @@ class CLITuiMixin:
def _tui_bind_overlay_navigation(self, kb) -> None:
"""Clarify / approval / slash-confirm / model picker / command palette navigation keys."""
_clarify_nav = Condition(lambda: bool(self._clarify_state) and not self._clarify_freetext)
- _clarify_batch = Condition(
- lambda: bool(self._clarify_state) and bool(self._clarify_state.get("questions"))
- and not self._clarify_freetext)
kb.add('up', filter=_clarify_nav)(self._tui_clarify_up)
kb.add('down', filter=_clarify_nav)(self._tui_clarify_down)
_connection_nav = Condition(lambda: bool(self._connection_state))
@@ -2135,8 +2004,8 @@ class CLITuiMixin:
# Batch clarify: Tab / Shift-Tab cycle the active question (any-order answering; moving
# onto an answered question lets the user re-answer it). Registered after the generic
# tab handler so this filtered binding wins while the batch panel is open.
- kb.add('tab', filter=_clarify_batch, eager=True)(self._tui_clarify_batch_tab)
- kb.add('s-tab', filter=_clarify_batch, eager=True)(self._tui_clarify_batch_backtab)
+ kb.add('tab', filter=_clarify_nav, eager=True)(self._tui_clarify_batch_tab)
+ kb.add('s-tab', filter=_clarify_nav, eager=True)(self._tui_clarify_batch_backtab)
# Number keys: 1-9 select items 0-8, 0 selects item 9 (10th).
for _num in range(10):
_idx = 9 if _num == 0 else _num - 1
diff --git a/hermes_cli/oneshot.py b/hermes_cli/oneshot.py
index 54f62223288..6a0d7ada683 100644
--- a/hermes_cli/oneshot.py
+++ b/hermes_cli/oneshot.py
@@ -644,12 +644,8 @@ def _close_agent(agent, session_db) -> None:
_quietly("session store cleanup", lambda: session_db.close())
-def _oneshot_clarify_callback(question: str, choices=None, multi_select=False) -> str:
+def _oneshot_clarify_callback(questions: list) -> dict:
"""Clarify is disabled in oneshot mode — tell the agent to pick a default and proceed."""
- if choices:
- what = "subset" if multi_select else "option"
- return (
- f"[oneshot mode: no user available. Pick the best {what} from "
- f"{choices} using your own judgment and continue.]"
- )
- return "[oneshot mode: no user available. Make the most reasonable assumption you can and continue.]"
+ return {"answers": {}, "outcome": "undelivered", "notice": (
+ "oneshot mode: no user available. Pick the best choices using your own judgment, "
+ "or make the most reasonable assumption you can, and continue.")}
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index 37f1d145db7..53066131b68 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -129,14 +129,10 @@
"assistant.catalogInstall.targetProfile",
"assistant.catalogInstall.tier.community",
"assistant.catalogInstall.tier.official",
- "assistant.clarify.answeredBadge",
"assistant.clarify.confirmAndContinueLabel",
- "assistant.clarify.continueLabel",
"assistant.clarify.gatewayDisconnected",
- "assistant.clarify.lateAnswer",
- "assistant.clarify.lateAnswerHint",
- "assistant.clarify.lateAnswerTip",
"assistant.clarify.loadingQuestion",
+ "assistant.clarify.noAnswer",
"assistant.clarify.notDelivered",
"assistant.clarify.notReady",
"assistant.clarify.other",
diff --git a/locales/_keys.tui.json b/locales/_keys.tui.json
index 520efb76387..0b0b61ff99d 100644
--- a/locales/_keys.tui.json
+++ b/locales/_keys.tui.json
@@ -515,10 +515,8 @@
"libText.terminalSetup.summaryIn",
"libText.text.argsLabel",
"libText.text.clarifyAnswered",
- "libText.text.clarifyBatchHead",
- "libText.text.clarifyBatchReason",
"libText.text.clarifyHead",
- "libText.text.clarifyNoSelection",
+ "libText.text.clarifyReason",
"libText.text.clarifyUnanswered",
"libText.text.errorLabel",
"libText.text.omittedChars",
@@ -637,16 +635,12 @@
"prompt.approval.once",
"prompt.approval.session",
"prompt.approval.title",
- "prompt.clarify.back",
- "prompt.clarify.batchHint",
- "prompt.clarify.batchTypingHint",
- "prompt.clarify.cancel",
"prompt.clarify.confirmAndContinue",
- "prompt.clarify.ctrlCCancel",
+ "prompt.clarify.hint",
"prompt.clarify.lockAnswer",
- "prompt.clarify.macClipboardHint",
"prompt.clarify.other",
"prompt.clarify.skipped",
+ "prompt.clarify.toggle",
"prompt.clarify.typingHint",
"prompt.confirm.cancel",
"prompt.confirm.confirm",
diff --git a/locales/af.tui.yaml b/locales/af.tui.yaml
index 6d0f4e358fc..34457e07cfe 100644
--- a/locales/af.tui.yaml
+++ b/locales/af.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "Kon nie die {0}-instellingspad op hi
libText.terminalSetup.summaryIn: "{0} in {1}"
libText.text.argsLabel: "Argumente"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "vra ({0} vrae)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "vra {0}"
-libText.text.clarifyNoSelection: "({0} — geen keuse)"
+libText.text.clarifyHead: "vra ({0} vrae)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (geen antwoord)"
libText.text.errorLabel: "Fout"
libText.text.omittedChars: "[{0}; {1} karakters weggelaat]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… +{0} reël(s) meer (volledige teks hierbo)"
prompt.approval.once: "Laat eenmalig toe"
prompt.approval.session: "Laat vir hierdie sessie toe"
prompt.approval.title: "⚠ goedkeuring vereis"
-prompt.clarify.back: "terug"
-prompt.clarify.batchHint: "↑/↓ kies · Enter {0} · Tab/Shift+Tab wissel vraag · Esc/Ctrl+C kanselleer"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc terug"
-prompt.clarify.cancel: "kanselleer"
+prompt.clarify.hint: "↑/↓ kies · Enter {0} · Tab/Shift+Tab wissel vraag · Esc/Ctrl+C kanselleer"
+prompt.clarify.typingHint: "Enter {0} · Esc terug"
prompt.clarify.confirmAndContinue: "bevestig en gaan voort"
-prompt.clarify.ctrlCCancel: "Ctrl+C kanselleer"
prompt.clarify.lockAnswer: "sluit antwoord vas"
-prompt.clarify.macClipboardHint: "Cmd+C kopieer · Cmd+V plak · Ctrl+C kanselleer"
prompt.clarify.other: "Ander (tik jou antwoord)"
prompt.clarify.skipped: "(oorgeslaan)"
-prompt.clarify.typingHint: "Enter stuur · Esc {0} ·"
+prompt.clarify.toggle: "Spasie wissel"
prompt.confirm.cancel: "Nee"
prompt.confirm.confirm: "Ja"
prompt.confirm.hint: "↑/↓ kies · Enter bevestig · Y/N vinnig · Esc kanselleer"
diff --git a/locales/af.yaml b/locales/af.yaml
index 7971bcfacfa..72e3decff6b 100644
--- a/locales/af.yaml
+++ b/locales/af.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ Verduideliking gekanselleer — jou boodskap sal as 'n opvolg hanteer word."
expired: "⏳ Hierdie prompt het verval — stuur asseblief 'n nuwe versoek."
native_stream_placeholder: "💬 Wag vir jou keuse..."
+ skip_hint: 'Antwoord "skip" om hierdie vraag oor te slaan.'
errors:
rate_limited: "⏱️ Die KI-modeldiens beperk tans die tempo van versoeke. Wag 'n oomblik en gebruik dan /retry."
auth_failed: "⚠️ Aanmelding by die KI-modeldiens het misluk. Gebruik /login om weer aan te meld, of vra die persoon wat hierdie bot bedryf om `hermes doctor` op die gasheer uit te voer."
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "Ander (tik hieronder)"
clarify_other_type_answer: "Ander (tik jou antwoord)"
clarify_guidance: "Tik jou antwoord in die prompt hieronder en druk dan Enter."
- clarify_question_truncated: "… (vraag afgekap)"
picker_title_provider: "⚙ Modelkieser — Kies Verskaffer"
picker_provider_row_one: "{name} ({count} model)"
picker_provider_row_other: "{name} ({count} modelle)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "word gewys terwyl jy tik · Enter om voort te gaan"
hint_clarify_freetext: "tik jou antwoord en druk Enter"
hint_clarify_batch: "↑/↓ om te kies, Enter om vas te maak, Tab volgende vraag"
- hint_clarify_choice: "↑/↓ om te kies, Enter om te bevestig"
hint_input_disabled: "invoer tydelik gedeaktiveer"
hint_input_queues: "invoer bly aktief; Enter plaas in tou"
hint_command_running: "{frame} opdrag aan die gang · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "verduideliking"
label: "Verduidelik"
- timed_out_agent_decides: "(verduideliking se tyd het na {timeout}s verstryk — agent sal besluit)"
timed_out_locked_answers: "(verduideliking se tyd het na {timeout}s verstryk — vasgestelde antwoorde teruggestuur)"
connect:
bell_context: "verbindingsopstelling"
diff --git a/locales/ar.tui.yaml b/locales/ar.tui.yaml
index a8fffe269ef..f78be696223 100644
--- a/locales/ar.tui.yaml
+++ b/locales/ar.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "تعذّر تحديد مسار إع
libText.terminalSetup.summaryIn: "{0} في {1}"
libText.text.argsLabel: "الوسائط"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "سؤال ({0} أسئلة)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "سؤال {0}"
-libText.text.clarifyNoSelection: "({0} — بلا اختيار)"
+libText.text.clarifyHead: "سؤال ({0} أسئلة)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (بلا إجابة)"
libText.text.errorLabel: "خطأ"
libText.text.omittedChars: "[{0}؛ حُذف {1} حرف]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… +{0} أسطر إضافية (النص الكام
prompt.approval.once: "السماح مرة واحدة"
prompt.approval.session: "السماح لهذه الجلسة"
prompt.approval.title: "⚠ الموافقة مطلوبة"
-prompt.clarify.back: "رجوع"
-prompt.clarify.batchHint: "↑/↓ اختيار · Enter {0} · Tab/Shift+Tab تبديل السؤال · Esc/Ctrl+C إلغاء"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc رجوع"
-prompt.clarify.cancel: "إلغاء"
+prompt.clarify.hint: "↑/↓ اختيار · Enter {0} · Tab/Shift+Tab تبديل السؤال · Esc/Ctrl+C إلغاء"
+prompt.clarify.typingHint: "Enter {0} · Esc رجوع"
prompt.clarify.confirmAndContinue: "تأكيد ومتابعة"
-prompt.clarify.ctrlCCancel: "Ctrl+C إلغاء"
prompt.clarify.lockAnswer: "تثبيت الإجابة"
-prompt.clarify.macClipboardHint: "Cmd+C نسخ · Cmd+V لصق · Ctrl+C إلغاء"
prompt.clarify.other: "أخرى (اكتب إجابتك)"
prompt.clarify.skipped: "(تم التخطي)"
-prompt.clarify.typingHint: "Enter إرسال · Esc {0} ·"
+prompt.clarify.toggle: "مسافة للتبديل"
prompt.confirm.cancel: "لا"
prompt.confirm.confirm: "نعم"
prompt.confirm.hint: "↑/↓ اختيار · Enter تأكيد · Y/N سريع · Esc إلغاء"
diff --git a/locales/ar.yaml b/locales/ar.yaml
index d85a8cb96b5..1503c9aa211 100644
--- a/locales/ar.yaml
+++ b/locales/ar.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ أُلغي الاستيضاح — ستُعالج رسالتك كمتابعة."
expired: "⏳ انتهت صلاحية هذه المطالبة — يُرجى إرسال طلب جديد."
native_stream_placeholder: "💬 في انتظار اختيارك..."
+ skip_hint: 'رُدّ بـ "skip" لتخطي هذا السؤال.'
errors:
rate_limited: "⏱️ خدمة نموذج الذكاء الاصطناعي تحدّ من معدّل الطلبات. انتظر قليلًا، ثم استخدم /retry."
auth_failed: "⚠️ فشل تسجيل الدخول إلى خدمة نموذج الذكاء الاصطناعي. استخدم /login لتسجيل الدخول مجددًا، أو اطلب ممّن يدير هذا البوت تشغيل `hermes doctor` على المضيف."
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "أخرى (اكتب أدناه)"
clarify_other_type_answer: "أخرى (اكتب إجابتك)"
clarify_guidance: "اكتب إجابتك في المطالبة أدناه، ثم اضغط Enter."
- clarify_question_truncated: "… (السؤال مقتطع)"
picker_title_provider: "⚙ منتقي النماذج — اختر المزوّد"
picker_provider_row_one: "{name} ({count} نموذج)"
picker_provider_row_other: "{name} ({count} نماذج)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "يظهر أثناء الكتابة · Enter للمتابعة"
hint_clarify_freetext: "اكتب إجابتك واضغط Enter"
hint_clarify_batch: "↑/↓ للاختيار، Enter للتثبيت، Tab للسؤال التالي"
- hint_clarify_choice: "↑/↓ للاختيار، Enter للتأكيد"
hint_input_disabled: "الإدخال معطّل مؤقتًا"
hint_input_queues: "الإدخال يبقى نشطًا؛ Enter يضيف إلى قائمة الانتظار"
hint_command_running: "{frame} الأمر قيد التنفيذ · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "استيضاح"
label: "استيضاح"
- timed_out_agent_decides: "(انتهت مهلة الاستيضاح بعد {timeout} ث — سيقرر الوكيل)"
timed_out_locked_answers: "(انتهت مهلة الاستيضاح بعد {timeout} ث — أُعيدت الإجابات المثبّتة)"
connect:
bell_context: "إعداد الاتصال"
diff --git a/locales/de.tui.yaml b/locales/de.tui.yaml
index 5aa69872cf7..55220b22755 100644
--- a/locales/de.tui.yaml
+++ b/locales/de.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "Der {0}-Einstellungspfad konnte auf
libText.terminalSetup.summaryIn: "{0} in {1}"
libText.text.argsLabel: "Argumente"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "Frage ({0} Fragen)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "Frage {0}"
-libText.text.clarifyNoSelection: "({0} — keine Auswahl)"
+libText.text.clarifyHead: "Frage ({0} Fragen)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (keine Antwort)"
libText.text.errorLabel: "Fehler"
libText.text.omittedChars: "[{0}; {1} Zeichen ausgelassen]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… +{0} weitere Zeile(n) (vollständiger Text oben)
prompt.approval.once: "Einmalig erlauben"
prompt.approval.session: "Für diese Sitzung erlauben"
prompt.approval.title: "⚠ Genehmigung erforderlich"
-prompt.clarify.back: "zurück"
-prompt.clarify.batchHint: "↑/↓ auswählen · Enter {0} · Tab/Shift+Tab Frage wechseln · Esc/Ctrl+C abbrechen"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc zurück"
-prompt.clarify.cancel: "abbrechen"
+prompt.clarify.hint: "↑/↓ auswählen · Enter {0} · Tab/Shift+Tab Frage wechseln · Esc/Ctrl+C abbrechen"
+prompt.clarify.typingHint: "Enter {0} · Esc zurück"
prompt.clarify.confirmAndContinue: "bestätigen und fortfahren"
-prompt.clarify.ctrlCCancel: "Ctrl+C abbrechen"
prompt.clarify.lockAnswer: "Antwort festlegen"
-prompt.clarify.macClipboardHint: "Cmd+C kopieren · Cmd+V einfügen · Ctrl+C abbrechen"
prompt.clarify.other: "Andere (Antwort eingeben)"
prompt.clarify.skipped: "(übersprungen)"
-prompt.clarify.typingHint: "Enter senden · Esc {0} ·"
+prompt.clarify.toggle: "Leertaste umschalten"
prompt.confirm.cancel: "Nein"
prompt.confirm.confirm: "Ja"
prompt.confirm.hint: "↑/↓ auswählen · Enter bestätigen · Y/N direkt · Esc abbrechen"
diff --git a/locales/de.yaml b/locales/de.yaml
index 3f89801e1e0..b5e6dd90b89 100644
--- a/locales/de.yaml
+++ b/locales/de.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ Rückfrage abgebrochen — Ihre Nachricht wird als Folgenachricht behandelt."
expired: "⏳ Diese Abfrage ist abgelaufen — bitte senden Sie eine neue Anfrage."
native_stream_placeholder: "💬 Warte auf Ihre Auswahl..."
+ skip_hint: 'Antworte mit „skip“, um diese Frage zu überspringen.'
errors:
rate_limited: "⏱️ Der KI-Modelldienst begrenzt derzeit die Anfragerate. Warten Sie einen Moment und verwenden Sie dann /retry."
auth_failed: "⚠️ Die Anmeldung beim KI-Modelldienst ist fehlgeschlagen. Verwenden Sie /login, um sich erneut anzumelden, oder bitten Sie den Betreiber dieses Bots, `hermes doctor` auf dem Host auszuführen."
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "Sonstiges (unten eingeben)"
clarify_other_type_answer: "Sonstiges (eigene Antwort eingeben)"
clarify_guidance: "Geben Sie Ihre Antwort unten ein und drücken Sie Enter."
- clarify_question_truncated: "… (Frage gekürzt)"
picker_title_provider: "⚙ Modellauswahl — Anbieter wählen"
picker_provider_row_one: "{name} ({count} Modell)"
picker_provider_row_other: "{name} ({count} Modelle)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "sichtbar beim Tippen · Enter zum Fortfahren"
hint_clarify_freetext: "Antwort eingeben und Enter drücken"
hint_clarify_batch: "↑/↓ zum Auswählen, Enter zum Festlegen, Tab nächste Frage"
- hint_clarify_choice: "↑/↓ zum Auswählen, Enter zum Bestätigen"
hint_input_disabled: "Eingabe vorübergehend deaktiviert"
hint_input_queues: "Eingabe bleibt aktiv; Enter reiht ein"
hint_command_running: "{frame} Befehl wird ausgeführt · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "Rückfrage"
label: "Rückfrage"
- timed_out_agent_decides: "(Rückfrage nach {timeout}s abgelaufen — der Agent entscheidet)"
timed_out_locked_answers: "(Rückfrage nach {timeout}s abgelaufen — festgelegte Antworten zurückgegeben)"
connect:
bell_context: "Verbindungseinrichtung"
diff --git a/locales/en.yaml b/locales/en.yaml
index d55b948e264..b1cf1ad84a3 100644
--- a/locales/en.yaml
+++ b/locales/en.yaml
@@ -660,6 +660,7 @@ gateway:
cancelled: "↩️ Clarification cancelled — your message will be handled as a follow-up."
expired: "⏳ This prompt expired — please send a new request."
native_stream_placeholder: "💬 Waiting for your choice..."
+ skip_hint: 'Reply "skip" to skip this question.'
errors:
rate_limited: "⏱️ The AI model service is rate-limiting requests. Wait a moment, then use /retry."
@@ -2128,7 +2129,6 @@ cli:
clarify_other_type_below: "Other (type below)"
clarify_other_type_answer: "Other (type your answer)"
clarify_guidance: "Type your answer in the prompt below, then press Enter."
- clarify_question_truncated: "… (question truncated)"
picker_title_provider: "⚙ Model Picker — Select Provider"
picker_provider_row_one: "{name} ({count} model)"
picker_provider_row_other: "{name} ({count} models)"
@@ -2173,7 +2173,6 @@ cli:
hint_vault_username: "shown as you type · Enter to continue"
hint_clarify_freetext: "type your answer and press Enter"
hint_clarify_batch: "↑/↓ to select, Enter to lock, Tab next question"
- hint_clarify_choice: "↑/↓ to select, Enter to confirm"
hint_input_disabled: "input temporarily disabled"
hint_input_queues: "input stays active; Enter queues"
hint_command_running: "{frame} command in progress · {detail}"
@@ -2360,7 +2359,6 @@ cli:
clarify:
bell_context: "clarify"
label: "Clarify"
- timed_out_agent_decides: "(clarify timed out after {timeout}s — agent will decide)"
timed_out_locked_answers: "(clarify timed out after {timeout}s — locked answers returned)"
connect:
bell_context: "connection setup"
diff --git a/locales/es.tui.yaml b/locales/es.tui.yaml
index 43f8d33bf92..62c1cdae1c4 100644
--- a/locales/es.tui.yaml
+++ b/locales/es.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "No se pudo determinar la ruta de aju
libText.terminalSetup.summaryIn: "{0} en {1}"
libText.text.argsLabel: "Args"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "consulta ({0} preguntas)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "consulta {0}"
-libText.text.clarifyNoSelection: "({0} — sin selección)"
+libText.text.clarifyHead: "consulta ({0} preguntas)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (sin respuesta)"
libText.text.errorLabel: "Error"
libText.text.omittedChars: "[{0}; omitidos {1} caracteres]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… +{0} línea(s) más (texto completo arriba)"
prompt.approval.once: "Permitir una vez"
prompt.approval.session: "Permitir en esta sesión"
prompt.approval.title: "⚠ se requiere aprobación"
-prompt.clarify.back: "volver"
-prompt.clarify.batchHint: "↑/↓ seleccionar · Enter {0} · Tab/Shift+Tab cambiar de pregunta · Esc/Ctrl+C cancelar"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc volver"
-prompt.clarify.cancel: "cancelar"
+prompt.clarify.hint: "↑/↓ seleccionar · Enter {0} · Tab/Shift+Tab cambiar de pregunta · Esc/Ctrl+C cancelar"
+prompt.clarify.typingHint: "Enter {0} · Esc volver"
prompt.clarify.confirmAndContinue: "confirmar y continuar"
-prompt.clarify.ctrlCCancel: "Ctrl+C cancelar"
prompt.clarify.lockAnswer: "fijar respuesta"
-prompt.clarify.macClipboardHint: "Cmd+C copiar · Cmd+V pegar · Ctrl+C cancelar"
prompt.clarify.other: "Otra (escribe tu respuesta)"
prompt.clarify.skipped: "(omitida)"
-prompt.clarify.typingHint: "Enter enviar · Esc {0} ·"
+prompt.clarify.toggle: "Espacio alternar"
prompt.confirm.cancel: "No"
prompt.confirm.confirm: "Sí"
prompt.confirm.hint: "↑/↓ seleccionar · Enter confirmar · Y/N rápido · Esc cancelar"
diff --git a/locales/es.yaml b/locales/es.yaml
index f4191175ba6..eaec6f4f221 100644
--- a/locales/es.yaml
+++ b/locales/es.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ Aclaración cancelada — tu mensaje se tratará como un mensaje de seguimiento."
expired: "⏳ Esta pregunta expiró — envía una nueva solicitud."
native_stream_placeholder: "💬 Esperando tu elección..."
+ skip_hint: 'Responde "skip" para omitir esta pregunta.'
errors:
rate_limited: "⏱️ El servicio del modelo de IA está limitando la tasa de solicitudes. Espera un momento y luego usa /retry."
auth_failed: "⚠️ Falló el inicio de sesión en el servicio del modelo de IA. Usa /login para iniciar sesión de nuevo, o pide a quien administra este bot que ejecute `hermes doctor` en el host."
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "Otra (escríbela abajo)"
clarify_other_type_answer: "Otra (escribe tu respuesta)"
clarify_guidance: "Escribe tu respuesta en el prompt de abajo y luego presiona Enter."
- clarify_question_truncated: "… (pregunta truncada)"
picker_title_provider: "⚙ Selector de modelos — Elige un proveedor"
picker_provider_row_one: "{name} ({count} modelo)"
picker_provider_row_other: "{name} ({count} modelos)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "visible mientras escribes · Enter para continuar"
hint_clarify_freetext: "escribe tu respuesta y presiona Enter"
hint_clarify_batch: "↑/↓ para seleccionar, Enter para fijar, Tab siguiente pregunta"
- hint_clarify_choice: "↑/↓ para seleccionar, Enter para confirmar"
hint_input_disabled: "entrada desactivada temporalmente"
hint_input_queues: "la entrada sigue activa; Enter pone en cola"
hint_command_running: "{frame} comando en curso · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "aclaración"
label: "Aclarar"
- timed_out_agent_decides: "(la aclaración expiró tras {timeout}s — el agente decidirá)"
timed_out_locked_answers: "(la aclaración expiró tras {timeout}s — se devolvieron las respuestas fijadas)"
connect:
bell_context: "configuración de conexión"
diff --git a/locales/fr.tui.yaml b/locales/fr.tui.yaml
index 0a32f542e7f..d9d7cb9e64f 100644
--- a/locales/fr.tui.yaml
+++ b/locales/fr.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "Impossible de déterminer le chemin
libText.terminalSetup.summaryIn: "{0} dans {1}"
libText.text.argsLabel: "Arguments"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "questions ({0})"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "question {0}"
-libText.text.clarifyNoSelection: "({0} — aucune sélection)"
+libText.text.clarifyHead: "questions ({0})"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (sans réponse)"
libText.text.errorLabel: "Erreur"
libText.text.omittedChars: "[{0} ; {1} caractères omis]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… +{0} ligne(s) de plus (texte complet ci-dessus)"
prompt.approval.once: "Autoriser une fois"
prompt.approval.session: "Autoriser pour cette session"
prompt.approval.title: "⚠ approbation requise"
-prompt.clarify.back: "retour"
-prompt.clarify.batchHint: "↑/↓ choisir · Entrée {0} · Tab/Shift+Tab changer de question · Échap/Ctrl+C annuler"
-prompt.clarify.batchTypingHint: "Entrée {0} · Échap retour"
-prompt.clarify.cancel: "annuler"
+prompt.clarify.hint: "↑/↓ choisir · Entrée {0} · Tab/Shift+Tab changer de question · Échap/Ctrl+C annuler"
+prompt.clarify.typingHint: "Entrée {0} · Échap retour"
prompt.clarify.confirmAndContinue: "confirmer et continuer"
-prompt.clarify.ctrlCCancel: "Ctrl+C annuler"
prompt.clarify.lockAnswer: "valider la réponse"
-prompt.clarify.macClipboardHint: "Cmd+C copier · Cmd+V coller · Ctrl+C annuler"
prompt.clarify.other: "Autre (saisissez votre réponse)"
prompt.clarify.skipped: "(ignorée)"
-prompt.clarify.typingHint: "Entrée envoyer · Échap {0} ·"
+prompt.clarify.toggle: "Espace basculer"
prompt.confirm.cancel: "Non"
prompt.confirm.confirm: "Oui"
prompt.confirm.hint: "↑/↓ choisir · Entrée confirmer · Y/N raccourci · Échap annuler"
diff --git a/locales/fr.yaml b/locales/fr.yaml
index 767c062b8ba..656e3ac811c 100644
--- a/locales/fr.yaml
+++ b/locales/fr.yaml
@@ -762,6 +762,7 @@ gateway:
cancelled: "↩️ Clarification annulée — votre message sera traité comme une suite de la conversation."
expired: "⏳ Cette demande a expiré — veuillez envoyer une nouvelle requête."
native_stream_placeholder: "💬 En attente de votre choix..."
+ skip_hint: 'Répondez « skip » pour passer cette question.'
errors:
rate_limited: "⏱️ Le service de modèle IA limite le débit des requêtes. Patientez un instant, puis utilisez /retry."
auth_failed: "⚠️ La connexion au service de modèle IA a échoué. Utilisez /login pour vous reconnecter, ou demandez à la personne qui gère ce bot de lancer `hermes doctor` sur l'hôte."
@@ -2284,7 +2285,6 @@ cli:
clarify_other_type_below: "Autre (saisir ci-dessous)"
clarify_other_type_answer: "Autre (saisissez votre réponse)"
clarify_guidance: "Tapez votre réponse dans le prompt ci-dessous, puis appuyez sur Entrée."
- clarify_question_truncated: "… (question tronquée)"
picker_title_provider: "⚙ Sélecteur de modèle — Choisir un fournisseur"
picker_provider_row_one: "{name} ({count} modèle)"
picker_provider_row_other: "{name} ({count} modèles)"
@@ -2341,7 +2341,6 @@ cli:
hint_vault_username: "affiché pendant la saisie · Entrée pour continuer"
hint_clarify_freetext: "tapez votre réponse et appuyez sur Entrée"
hint_clarify_batch: "↑/↓ pour sélectionner, Entrée pour valider, Tab question suivante"
- hint_clarify_choice: "↑/↓ pour sélectionner, Entrée pour confirmer"
hint_input_disabled: "saisie temporairement désactivée"
hint_input_queues: "la saisie reste active ; Entrée met en file"
hint_command_running: "{frame} commande en cours · {detail}"
@@ -2533,7 +2532,6 @@ cli:
clarify:
bell_context: "clarification"
label: "Clarification"
- timed_out_agent_decides: "(clarification expirée après {timeout} s — l'agent décidera)"
timed_out_locked_answers: "(clarification expirée après {timeout} s — réponses verrouillées renvoyées)"
connect:
bell_context: "configuration de connexion"
diff --git a/locales/ga.tui.yaml b/locales/ga.tui.yaml
index 3898b313a57..659c4f7387e 100644
--- a/locales/ga.tui.yaml
+++ b/locales/ga.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "Níorbh fhéidir conair socruithe {0
libText.terminalSetup.summaryIn: "{0} i {1}"
libText.text.argsLabel: "Argóintí"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "ceisteanna ({0} ceist)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "ceist {0}"
-libText.text.clarifyNoSelection: "({0} — gan roghnú)"
+libText.text.clarifyHead: "ceisteanna ({0} ceist)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (gan freagra)"
libText.text.errorLabel: "Earráid"
libText.text.omittedChars: "[{0}; {1} carachtar fágtha ar lár]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… +{0} líne eile (téacs iomlán thuas)"
prompt.approval.once: "Ceadaigh uair amháin"
prompt.approval.session: "Ceadaigh don seisiún seo"
prompt.approval.title: "⚠ cead de dhíth"
-prompt.clarify.back: "siar"
-prompt.clarify.batchHint: "↑/↓ roghnaigh · Enter {0} · Tab/Shift+Tab athraigh ceist · Esc/Ctrl+C cealaigh"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc siar"
-prompt.clarify.cancel: "cealaigh"
+prompt.clarify.hint: "↑/↓ roghnaigh · Enter {0} · Tab/Shift+Tab athraigh ceist · Esc/Ctrl+C cealaigh"
+prompt.clarify.typingHint: "Enter {0} · Esc siar"
prompt.clarify.confirmAndContinue: "dearbhaigh agus lean ar aghaidh"
-prompt.clarify.ctrlCCancel: "Ctrl+C cealaigh"
prompt.clarify.lockAnswer: "glasáil an freagra"
-prompt.clarify.macClipboardHint: "Cmd+C cóipeáil · Cmd+V greamaigh · Ctrl+C cealaigh"
prompt.clarify.other: "Eile (clóscríobh do fhreagra)"
prompt.clarify.skipped: "(scipeáilte)"
-prompt.clarify.typingHint: "Enter seol · Esc {0} ·"
+prompt.clarify.toggle: "Spás le scoránú"
prompt.confirm.cancel: "Níl"
prompt.confirm.confirm: "Tá"
prompt.confirm.hint: "↑/↓ roghnaigh · Enter dearbhaigh · Y/N go tapa · Esc cealaigh"
diff --git a/locales/ga.yaml b/locales/ga.yaml
index 6f502ae79ab..602d0c86fb7 100644
--- a/locales/ga.yaml
+++ b/locales/ga.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ Soiléiriú cealaithe — láimhseálfar do theachtaireacht mar theachtaireacht leantach."
expired: "⏳ Tá an leid seo imithe in éag — seol iarratas nua le do thoil."
native_stream_placeholder: "💬 Ag fanacht le do rogha..."
+ skip_hint: 'Freagair "skip" chun an cheist seo a scipeáil.'
errors:
rate_limited: "⏱️ Tá seirbhís na samhla AI ag teorannú ráta na n-iarratas. Fan nóiméad, ansin úsáid /retry."
auth_failed: "⚠️ Theip ar shíniú isteach i seirbhís na samhla AI. Úsáid /login chun síniú isteach arís, nó iarr ar an duine a ritheann an bot seo `hermes doctor` a rith ar an óstach."
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "Eile (clóscríobh thíos)"
clarify_other_type_answer: "Eile (clóscríobh do fhreagra)"
clarify_guidance: "Clóscríobh do fhreagra sa leid thíos, ansin brúigh Enter."
- clarify_question_truncated: "… (ceist giorraithe)"
picker_title_provider: "⚙ Roghnóir Samhlacha — Roghnaigh Soláthraí"
picker_provider_row_one: "{name} ({count} samhail)"
picker_provider_row_other: "{name} ({count} samhail)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "le feiceáil agus tú ag clóscríobh · Enter le leanúint"
hint_clarify_freetext: "clóscríobh do fhreagra agus brúigh Enter"
hint_clarify_batch: "↑/↓ le roghnú, Enter le glasáil, Tab don chéad cheist eile"
- hint_clarify_choice: "↑/↓ le roghnú, Enter le dearbhú"
hint_input_disabled: "ionchur díchumasaithe go sealadach"
hint_input_queues: "fanann an t-ionchur gníomhach; cuireann Enter i scuaine"
hint_command_running: "{frame} ordú ar siúl · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "soiléiriú"
label: "Soiléirigh"
- timed_out_agent_decides: "(chuaigh an soiléiriú thar am tar éis {timeout}s — déanfaidh an gníomhaire cinneadh)"
timed_out_locked_answers: "(chuaigh an soiléiriú thar am tar éis {timeout}s — seoladh na freagraí glasáilte ar ais)"
connect:
bell_context: "socrú ceangail"
diff --git a/locales/hu.tui.yaml b/locales/hu.tui.yaml
index 2eca6985cc0..83b7005d2f1 100644
--- a/locales/hu.tui.yaml
+++ b/locales/hu.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "Nem sikerült megállapítani a {0}
libText.terminalSetup.summaryIn: "{0} itt: {1}"
libText.text.argsLabel: "Argumentumok"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "kérdések ({0})"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "kérdés {0}"
-libText.text.clarifyNoSelection: "({0} — nincs kijelölés)"
+libText.text.clarifyHead: "kérdések ({0})"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (nincs válasz)"
libText.text.errorLabel: "Hiba"
libText.text.omittedChars: "[{0}; kihagyva {1} karakter]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… +{0} további sor (a teljes szöveg fent)"
prompt.approval.once: "Egyszer engedélyez"
prompt.approval.session: "Engedélyez erre a munkamenetre"
prompt.approval.title: "⚠ jóváhagyás szükséges"
-prompt.clarify.back: "vissza"
-prompt.clarify.batchHint: "↑/↓ választás · Enter {0} · Tab/Shift+Tab kérdésváltás · Esc/Ctrl+C mégse"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc vissza"
-prompt.clarify.cancel: "mégse"
+prompt.clarify.hint: "↑/↓ választás · Enter {0} · Tab/Shift+Tab kérdésváltás · Esc/Ctrl+C mégse"
+prompt.clarify.typingHint: "Enter {0} · Esc vissza"
prompt.clarify.confirmAndContinue: "megerősítés és folytatás"
-prompt.clarify.ctrlCCancel: "Ctrl+C mégse"
prompt.clarify.lockAnswer: "válasz rögzítése"
-prompt.clarify.macClipboardHint: "Cmd+C másolás · Cmd+V beillesztés · Ctrl+C mégse"
prompt.clarify.other: "Egyéb (írd be a válaszod)"
prompt.clarify.skipped: "(kihagyva)"
-prompt.clarify.typingHint: "Enter küldés · Esc {0} ·"
+prompt.clarify.toggle: "Szóköz váltás"
prompt.confirm.cancel: "Nem"
prompt.confirm.confirm: "Igen"
prompt.confirm.hint: "↑/↓ választás · Enter megerősítés · Y/N gyors · Esc mégse"
diff --git a/locales/hu.yaml b/locales/hu.yaml
index 200f6e5dd12..76395504fc4 100644
--- a/locales/hu.yaml
+++ b/locales/hu.yaml
@@ -663,6 +663,7 @@ gateway:
cancelled: "↩️ Pontosítás megszakítva — az üzenetedet folytatásként kezelem."
expired: "⏳ Ez a kérdés lejárt — küldj új kérést."
native_stream_placeholder: "💬 Várom a választásodat..."
+ skip_hint: 'Válaszolj „skip” szóval a kérdés kihagyásához.'
errors:
rate_limited: "⏱️ Az AI-modellszolgáltatás korlátozza a kérések számát. Várj egy kicsit, majd használd a /retry parancsot."
auth_failed: "⚠️ Nem sikerült bejelentkezni az AI-modellszolgáltatásba. Jelentkezz be újra a /login paranccsal, vagy kérd meg a bot üzemeltetőjét, hogy futtassa a `hermes doctor` parancsot a gépen."
@@ -2049,7 +2050,6 @@ cli:
clarify_other_type_below: "Egyéb (írd be lent)"
clarify_other_type_answer: "Egyéb (írd be a válaszodat)"
clarify_guidance: "Írd be a válaszodat az alábbi mezőbe, majd nyomj Entert."
- clarify_question_truncated: "… (a kérdés csonkolva)"
picker_title_provider: "⚙ Modellválasztó — Válassz szolgáltatót"
picker_provider_row_one: "{name} ({count} modell)"
picker_provider_row_other: "{name} ({count} modell)"
@@ -2094,7 +2094,6 @@ cli:
hint_vault_username: "gépelés közben látható · Enter a folytatáshoz"
hint_clarify_freetext: "írd be a válaszodat, és nyomj Entert"
hint_clarify_batch: "↑/↓ a választáshoz, Enter rögzít, Tab a következő kérdés"
- hint_clarify_choice: "↑/↓ a választáshoz, Enter a megerősítéshez"
hint_input_disabled: "a bevitel átmenetileg le van tiltva"
hint_input_queues: "a bevitel aktív marad; az Enter sorba állít"
hint_command_running: "{frame} parancs folyamatban · {detail}"
@@ -2277,7 +2276,6 @@ cli:
clarify:
bell_context: "pontosítás"
label: "Pontosítás"
- timed_out_agent_decides: "(a pontosítás {timeout} mp után lejárt — az ügynök dönt)"
timed_out_locked_answers: "(a pontosítás {timeout} mp után lejárt — a rögzített válaszok visszaküldve)"
connect:
bell_context: "kapcsolat beállítása"
diff --git a/locales/it.tui.yaml b/locales/it.tui.yaml
index 11b8e501f05..abf1da7cf4c 100644
--- a/locales/it.tui.yaml
+++ b/locales/it.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "Impossibile determinare il percorso
libText.terminalSetup.summaryIn: "{0} in {1}"
libText.text.argsLabel: "Argomenti"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "domanda ({0} quesiti)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "domanda {0}"
-libText.text.clarifyNoSelection: "({0} — nessuna selezione)"
+libText.text.clarifyHead: "domanda ({0} quesiti)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (nessuna risposta)"
libText.text.errorLabel: "Errore"
libText.text.omittedChars: "[{0}; omessi {1} caratteri]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… +{0} riga/righe (testo completo sopra)"
prompt.approval.once: "Consenti una volta"
prompt.approval.session: "Consenti per questa sessione"
prompt.approval.title: "⚠ approvazione richiesta"
-prompt.clarify.back: "indietro"
-prompt.clarify.batchHint: "↑/↓ seleziona · Invio {0} · Tab/Shift+Tab cambia domanda · Esc/Ctrl+C annulla"
-prompt.clarify.batchTypingHint: "Invio {0} · Esc indietro"
-prompt.clarify.cancel: "annulla"
+prompt.clarify.hint: "↑/↓ seleziona · Invio {0} · Tab/Shift+Tab cambia domanda · Esc/Ctrl+C annulla"
+prompt.clarify.typingHint: "Invio {0} · Esc indietro"
prompt.clarify.confirmAndContinue: "conferma e continua"
-prompt.clarify.ctrlCCancel: "Ctrl+C annulla"
prompt.clarify.lockAnswer: "blocca la risposta"
-prompt.clarify.macClipboardHint: "Cmd+C copia · Cmd+V incolla · Ctrl+C annulla"
prompt.clarify.other: "Altro (scrivi la tua risposta)"
prompt.clarify.skipped: "(saltata)"
-prompt.clarify.typingHint: "Invio invia · Esc {0} ·"
+prompt.clarify.toggle: "Spazio seleziona"
prompt.confirm.cancel: "No"
prompt.confirm.confirm: "Sì"
prompt.confirm.hint: "↑/↓ seleziona · Invio conferma · Y/N rapido · Esc annulla"
diff --git a/locales/it.yaml b/locales/it.yaml
index 9e740d12a44..274b986a5c9 100644
--- a/locales/it.yaml
+++ b/locales/it.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ Chiarimento annullato — il tuo messaggio verrà gestito come follow-up."
expired: "⏳ Questa richiesta è scaduta — invia una nuova richiesta."
native_stream_placeholder: "💬 In attesa della tua scelta..."
+ skip_hint: 'Rispondi "skip" per saltare questa domanda.'
errors:
rate_limited: "⏱️ Il servizio del modello AI sta limitando le richieste. Attendi un momento, poi usa /retry."
auth_failed: "⚠️ Accesso al servizio del modello AI non riuscito. Usa /login per accedere di nuovo, oppure chiedi a chi gestisce questo bot di eseguire `hermes doctor` sull'host."
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "Altro (digita sotto)"
clarify_other_type_answer: "Altro (digita la tua risposta)"
clarify_guidance: "Digita la tua risposta nel prompt qui sotto, poi premi Invio."
- clarify_question_truncated: "… (domanda troncata)"
picker_title_provider: "⚙ Selettore modelli — Scegli il provider"
picker_provider_row_one: "{name} ({count} modello)"
picker_provider_row_other: "{name} ({count} modelli)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "visibile mentre digiti · Invio per continuare"
hint_clarify_freetext: "digita la tua risposta e premi Invio"
hint_clarify_batch: "↑/↓ per selezionare, Invio per bloccare, Tab domanda successiva"
- hint_clarify_choice: "↑/↓ per selezionare, Invio per confermare"
hint_input_disabled: "input temporaneamente disattivato"
hint_input_queues: "l'input resta attivo; Invio mette in coda"
hint_command_running: "{frame} comando in corso · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "chiarimento"
label: "Chiarimento"
- timed_out_agent_decides: "(chiarimento scaduto dopo {timeout}s — deciderà l'agente)"
timed_out_locked_answers: "(chiarimento scaduto dopo {timeout}s — restituite le risposte bloccate)"
connect:
bell_context: "configurazione connessione"
diff --git a/locales/ja.tui.yaml b/locales/ja.tui.yaml
index 215a7ac47c0..cfea9feffa9 100644
--- a/locales/ja.tui.yaml
+++ b/locales/ja.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "このプラットフォームでは
libText.terminalSetup.summaryIn: "{1} 内: {0}"
libText.text.argsLabel: "引数"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "質問 ({0} 件)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "質問 {0}"
-libText.text.clarifyNoSelection: "({0} — 未選択)"
+libText.text.clarifyHead: "質問 ({0} 件)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (未回答)"
libText.text.errorLabel: "エラー"
libText.text.omittedChars: "[{0}; {1} 文字を省略]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… 他 {0} 行(全文は上記)"
prompt.approval.once: "今回のみ許可"
prompt.approval.session: "このセッション中は許可"
prompt.approval.title: "⚠ 承認が必要です"
-prompt.clarify.back: "戻る"
-prompt.clarify.batchHint: "↑/↓ 選択 · Enter {0} · Tab/Shift+Tab 質問を切り替え · Esc/Ctrl+C キャンセル"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc 戻る"
-prompt.clarify.cancel: "キャンセル"
+prompt.clarify.hint: "↑/↓ 選択 · Enter {0} · Tab/Shift+Tab 質問を切り替え · Esc/Ctrl+C キャンセル"
+prompt.clarify.typingHint: "Enter {0} · Esc 戻る"
prompt.clarify.confirmAndContinue: "確定して続行"
-prompt.clarify.ctrlCCancel: "Ctrl+C キャンセル"
prompt.clarify.lockAnswer: "回答を確定"
-prompt.clarify.macClipboardHint: "Cmd+C コピー · Cmd+V 貼り付け · Ctrl+C キャンセル"
prompt.clarify.other: "その他(回答を入力)"
prompt.clarify.skipped: "(スキップ)"
-prompt.clarify.typingHint: "Enter 送信 · Esc {0} ·"
+prompt.clarify.toggle: "Space で切り替え"
prompt.confirm.cancel: "いいえ"
prompt.confirm.confirm: "はい"
prompt.confirm.hint: "↑/↓ 選択 · Enter 確定 · Y/N で即決 · Esc キャンセル"
diff --git a/locales/ja.yaml b/locales/ja.yaml
index a2f18b3d2b4..700df7a9fe4 100644
--- a/locales/ja.yaml
+++ b/locales/ja.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ 確認をキャンセルしました — あなたのメッセージは続きの指示として処理されます。"
expired: "⏳ このプロンプトは期限切れです — 新しいリクエストを送信してください。"
native_stream_placeholder: "💬 選択をお待ちしています..."
+ skip_hint: 'この質問をスキップするには「skip」と返信してください。'
errors:
rate_limited: "⏱️ AI モデルサービスがリクエストをレート制限しています。少し待ってから /retry を使ってください。"
auth_failed: "⚠️ AI モデルサービスへのサインインに失敗しました。/login で再度サインインするか、このボットの運用者にホストで `hermes doctor` を実行するよう依頼してください。"
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "その他 (下に入力)"
clarify_other_type_answer: "その他 (回答を入力)"
clarify_guidance: "下のプロンプトに回答を入力し、Enter を押してください。"
- clarify_question_truncated: "… (質問を切り詰めました)"
picker_title_provider: "⚙ モデルピッカー — プロバイダーを選択"
picker_provider_row_one: "{name} ({count} モデル)"
picker_provider_row_other: "{name} ({count} モデル)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "入力内容は表示されます · Enter で続行"
hint_clarify_freetext: "回答を入力して Enter を押してください"
hint_clarify_batch: "↑/↓ で選択、Enter で確定、Tab で次の質問"
- hint_clarify_choice: "↑/↓ で選択、Enter で確定"
hint_input_disabled: "入力は一時的に無効です"
hint_input_queues: "入力は引き続き有効です。Enter でキューに追加"
hint_command_running: "{frame} コマンド実行中 · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "確認"
label: "確認"
- timed_out_agent_decides: "(確認は {timeout} 秒でタイムアウトしました — エージェントが判断します)"
timed_out_locked_answers: "(確認は {timeout} 秒でタイムアウトしました — 確定済みの回答を返しました)"
connect:
bell_context: "接続のセットアップ"
diff --git a/locales/ko.tui.yaml b/locales/ko.tui.yaml
index f297de9ebb1..54cf39d3160 100644
--- a/locales/ko.tui.yaml
+++ b/locales/ko.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "이 플랫폼에서 {0} 설정 경
libText.terminalSetup.summaryIn: "{1}에 {0}"
libText.text.argsLabel: "인자"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "질문 ({0}개)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "질문 {0}"
-libText.text.clarifyNoSelection: "({0} — 선택 없음)"
+libText.text.clarifyHead: "질문 ({0}개)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (답변 없음)"
libText.text.errorLabel: "오류"
libText.text.omittedChars: "[{0}; {1}자 생략]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… 외 {0}줄 더 있음 (전체 내용은 위 참
prompt.approval.once: "한 번 허용"
prompt.approval.session: "이 세션에서 허용"
prompt.approval.title: "⚠ 승인 필요"
-prompt.clarify.back: "뒤로"
-prompt.clarify.batchHint: "↑/↓ 선택 · Enter {0} · Tab/Shift+Tab 질문 전환 · Esc/Ctrl+C 취소"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc 뒤로"
-prompt.clarify.cancel: "취소"
+prompt.clarify.hint: "↑/↓ 선택 · Enter {0} · Tab/Shift+Tab 질문 전환 · Esc/Ctrl+C 취소"
+prompt.clarify.typingHint: "Enter {0} · Esc 뒤로"
prompt.clarify.confirmAndContinue: "확인 후 계속"
-prompt.clarify.ctrlCCancel: "Ctrl+C 취소"
prompt.clarify.lockAnswer: "답변 확정"
-prompt.clarify.macClipboardHint: "Cmd+C 복사 · Cmd+V 붙여넣기 · Ctrl+C 취소"
prompt.clarify.other: "기타 (직접 입력)"
prompt.clarify.skipped: "(건너뜀)"
-prompt.clarify.typingHint: "Enter 보내기 · Esc {0} ·"
+prompt.clarify.toggle: "Space 전환"
prompt.confirm.cancel: "아니요"
prompt.confirm.confirm: "예"
prompt.confirm.hint: "↑/↓ 선택 · Enter 확인 · Y/N 바로 선택 · Esc 취소"
diff --git a/locales/ko.yaml b/locales/ko.yaml
index 5e91aee82e0..3997a4d98eb 100644
--- a/locales/ko.yaml
+++ b/locales/ko.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ 확인 질문이 취소되었어요 — 메시지는 후속 메시지로 처리돼요."
expired: "⏳ 이 질문은 만료되었어요 — 새 요청을 보내 주세요."
native_stream_placeholder: "💬 선택을 기다리고 있어요..."
+ skip_hint: '이 질문을 건너뛰려면 "skip"이라고 답장하세요.'
errors:
rate_limited: "⏱️ AI 모델 서비스가 요청을 제한하고 있어요. 잠시 기다린 뒤 /retry를 사용하세요."
auth_failed: "⚠️ AI 모델 서비스 로그인에 실패했어요. /login으로 다시 로그인하거나, 이 봇 운영자에게 호스트에서 `hermes doctor`를 실행해 달라고 요청하세요."
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "기타 (아래에 입력)"
clarify_other_type_answer: "기타 (직접 입력)"
clarify_guidance: "아래 프롬프트에 답을 입력한 뒤 Enter를 누르세요."
- clarify_question_truncated: "… (질문이 잘렸어요)"
picker_title_provider: "⚙ 모델 선택기 — 제공자 선택"
picker_provider_row_one: "{name} (모델 {count}개)"
picker_provider_row_other: "{name} (모델 {count}개)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "입력 내용 표시됨 · Enter로 계속"
hint_clarify_freetext: "답을 입력하고 Enter를 누르세요"
hint_clarify_batch: "↑/↓로 선택, Enter로 확정, Tab으로 다음 질문"
- hint_clarify_choice: "↑/↓로 선택, Enter로 확인"
hint_input_disabled: "입력이 일시적으로 비활성화됨"
hint_input_queues: "입력 가능 · Enter로 대기열에 추가"
hint_command_running: "{frame} 명령 실행 중 · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "명확화"
label: "명확화"
- timed_out_agent_decides: "(명확화 요청이 {timeout}초 후 시간 초과 — 에이전트가 결정해요)"
timed_out_locked_answers: "(명확화 요청이 {timeout}초 후 시간 초과 — 확정된 답변을 반환했어요)"
connect:
bell_context: "연결 설정"
diff --git a/locales/pt.tui.yaml b/locales/pt.tui.yaml
index 5bc850c4774..a92431e5525 100644
--- a/locales/pt.tui.yaml
+++ b/locales/pt.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "Não foi possível determinar o cami
libText.terminalSetup.summaryIn: "{0} em {1}"
libText.text.argsLabel: "Argumentos"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "pergunta ({0} perguntas)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "pergunta {0}"
-libText.text.clarifyNoSelection: "({0} — nada selecionado)"
+libText.text.clarifyHead: "pergunta ({0} perguntas)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (sem resposta)"
libText.text.errorLabel: "Erro"
libText.text.omittedChars: "[{0}; {1} caracteres omitidos]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… +{0} linha(s) a mais (texto completo acima)"
prompt.approval.once: "Permitir uma vez"
prompt.approval.session: "Permitir nesta sessão"
prompt.approval.title: "⚠ aprovação necessária"
-prompt.clarify.back: "voltar"
-prompt.clarify.batchHint: "↑/↓ selecionar · Enter {0} · Tab/Shift+Tab trocar pergunta · Esc/Ctrl+C cancelar"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc voltar"
-prompt.clarify.cancel: "cancelar"
+prompt.clarify.hint: "↑/↓ selecionar · Enter {0} · Tab/Shift+Tab trocar pergunta · Esc/Ctrl+C cancelar"
+prompt.clarify.typingHint: "Enter {0} · Esc voltar"
prompt.clarify.confirmAndContinue: "confirmar e continuar"
-prompt.clarify.ctrlCCancel: "Ctrl+C cancelar"
prompt.clarify.lockAnswer: "fixar resposta"
-prompt.clarify.macClipboardHint: "Cmd+C copiar · Cmd+V colar · Ctrl+C cancelar"
prompt.clarify.other: "Outra (digite sua resposta)"
prompt.clarify.skipped: "(ignorada)"
-prompt.clarify.typingHint: "Enter enviar · Esc {0} ·"
+prompt.clarify.toggle: "Espaço alternar"
prompt.confirm.cancel: "Não"
prompt.confirm.confirm: "Sim"
prompt.confirm.hint: "↑/↓ selecionar · Enter confirmar · Y/N rápido · Esc cancelar"
diff --git a/locales/pt.yaml b/locales/pt.yaml
index 913747dab17..91c18cc5542 100644
--- a/locales/pt.yaml
+++ b/locales/pt.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ Esclarecimento cancelado — sua mensagem será tratada como continuação."
expired: "⏳ Este prompt expirou — envie uma nova solicitação."
native_stream_placeholder: "💬 Aguardando sua escolha..."
+ skip_hint: 'Responda "skip" para pular esta pergunta.'
errors:
rate_limited: "⏱️ O serviço do modelo de IA está limitando a taxa de requisições. Aguarde um momento e use /retry."
auth_failed: "⚠️ Falha ao entrar no serviço do modelo de IA. Use /login para entrar novamente ou peça a quem administra este bot para executar `hermes doctor` no host."
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "Outro (digite abaixo)"
clarify_other_type_answer: "Outro (digite sua resposta)"
clarify_guidance: "Digite sua resposta no prompt abaixo e pressione Enter."
- clarify_question_truncated: "… (pergunta truncada)"
picker_title_provider: "⚙ Seletor de modelos — Selecione o fornecedor"
picker_provider_row_one: "{name} ({count} modelo)"
picker_provider_row_other: "{name} ({count} modelos)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "visível ao digitar · Enter para continuar"
hint_clarify_freetext: "digite sua resposta e pressione Enter"
hint_clarify_batch: "↑/↓ para selecionar, Enter para fixar, Tab próxima pergunta"
- hint_clarify_choice: "↑/↓ para selecionar, Enter para confirmar"
hint_input_disabled: "entrada temporariamente desativada"
hint_input_queues: "entrada continua ativa; Enter enfileira"
hint_command_running: "{frame} comando em andamento · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "esclarecimento"
label: "Esclarecer"
- timed_out_agent_decides: "(esclarecimento expirou após {timeout}s — o agente decidirá)"
timed_out_locked_answers: "(esclarecimento expirou após {timeout}s — respostas travadas retornadas)"
connect:
bell_context: "configuração de conexão"
diff --git a/locales/ru.tui.yaml b/locales/ru.tui.yaml
index f29d6731cb0..a1212fb59ef 100644
--- a/locales/ru.tui.yaml
+++ b/locales/ru.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "Не удалось определи
libText.terminalSetup.summaryIn: "{0} в {1}"
libText.text.argsLabel: "Аргументы"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "вопрос ({0} вопросов)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "вопрос {0}"
-libText.text.clarifyNoSelection: "({0} — ничего не выбрано)"
+libText.text.clarifyHead: "вопрос ({0} вопросов)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (без ответа)"
libText.text.errorLabel: "Ошибка"
libText.text.omittedChars: "[{0}; пропущено {1} символов]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… ещё строк: {0} (полный текст
prompt.approval.once: "Разрешить один раз"
prompt.approval.session: "Разрешить на этот сеанс"
prompt.approval.title: "⚠ требуется одобрение"
-prompt.clarify.back: "назад"
-prompt.clarify.batchHint: "↑/↓ выбор · Enter {0} · Tab/Shift+Tab другой вопрос · Esc/Ctrl+C отмена"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc назад"
-prompt.clarify.cancel: "отмена"
+prompt.clarify.hint: "↑/↓ выбор · Enter {0} · Tab/Shift+Tab другой вопрос · Esc/Ctrl+C отмена"
+prompt.clarify.typingHint: "Enter {0} · Esc назад"
prompt.clarify.confirmAndContinue: "подтвердить и продолжить"
-prompt.clarify.ctrlCCancel: "Ctrl+C отмена"
prompt.clarify.lockAnswer: "зафиксировать ответ"
-prompt.clarify.macClipboardHint: "Cmd+C копировать · Cmd+V вставить · Ctrl+C отмена"
prompt.clarify.other: "Другое (введите свой ответ)"
prompt.clarify.skipped: "(пропущено)"
-prompt.clarify.typingHint: "Enter отправить · Esc {0} ·"
+prompt.clarify.toggle: "Пробел переключить"
prompt.confirm.cancel: "Нет"
prompt.confirm.confirm: "Да"
prompt.confirm.hint: "↑/↓ выбор · Enter подтвердить · Y/N быстрый выбор · Esc отмена"
diff --git a/locales/ru.yaml b/locales/ru.yaml
index 14d3485bd2d..3bfea963cba 100644
--- a/locales/ru.yaml
+++ b/locales/ru.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ Уточняющий вопрос отменён — ваше сообщение будет обработано как обычное продолжение."
expired: "⏳ Срок этого запроса истёк — отправьте новый запрос."
native_stream_placeholder: "💬 Жду вашего выбора..."
+ skip_hint: 'Ответьте «skip», чтобы пропустить этот вопрос.'
errors:
rate_limited: "⏱️ Сервис ИИ-модели ограничивает частоту запросов. Подождите немного, затем используйте /retry."
auth_failed: "⚠️ Не удалось войти в сервис ИИ-модели. Используйте /login, чтобы войти заново, или попросите того, кто запускает этого бота, выполнить `hermes doctor` на хосте."
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "Другое (введите ниже)"
clarify_other_type_answer: "Другое (введите свой ответ)"
clarify_guidance: "Введите ответ в поле ниже и нажмите Enter."
- clarify_question_truncated: "… (вопрос обрезан)"
picker_title_provider: "⚙ Выбор модели — выберите провайдера"
picker_provider_row_one: "{name} ({count} модель)"
picker_provider_row_other: "{name} (моделей: {count})"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "отображается при вводе · Enter — продолжить"
hint_clarify_freetext: "введите ответ и нажмите Enter"
hint_clarify_batch: "↑/↓ — выбрать, Enter — зафиксировать, Tab — следующий вопрос"
- hint_clarify_choice: "↑/↓ — выбрать, Enter — подтвердить"
hint_input_disabled: "ввод временно отключён"
hint_input_queues: "ввод доступен; Enter ставит в очередь"
hint_command_running: "{frame} команда выполняется · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "уточняющий вопрос"
label: "Уточнение"
- timed_out_agent_decides: "(уточняющий вопрос: тайм-аут через {timeout} с — агент решит сам)"
timed_out_locked_answers: "(уточняющий вопрос: тайм-аут через {timeout} с — возвращены зафиксированные ответы)"
connect:
bell_context: "настройка подключения"
diff --git a/locales/tr.tui.yaml b/locales/tr.tui.yaml
index c437d4006e0..efe2e8c1c38 100644
--- a/locales/tr.tui.yaml
+++ b/locales/tr.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "Bu platformda {0} ayar dosyasının
libText.terminalSetup.summaryIn: "{0} ({1})"
libText.text.argsLabel: "Argümanlar"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "sorular ({0} soru)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "soru {0}"
-libText.text.clarifyNoSelection: "({0} — seçim yok)"
+libText.text.clarifyHead: "sorular ({0} soru)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (yanıt yok)"
libText.text.errorLabel: "Hata"
libText.text.omittedChars: "[{0}; {1} karakter atlandı]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… +{0} satır daha (tam metin yukarıda)"
prompt.approval.once: "Bir kez izin ver"
prompt.approval.session: "Bu oturum için izin ver"
prompt.approval.title: "⚠ onay gerekiyor"
-prompt.clarify.back: "geri"
-prompt.clarify.batchHint: "↑/↓ seç · Enter {0} · Tab/Shift+Tab soru değiştir · Esc/Ctrl+C iptal"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc geri"
-prompt.clarify.cancel: "iptal"
+prompt.clarify.hint: "↑/↓ seç · Enter {0} · Tab/Shift+Tab soru değiştir · Esc/Ctrl+C iptal"
+prompt.clarify.typingHint: "Enter {0} · Esc geri"
prompt.clarify.confirmAndContinue: "onayla ve devam et"
-prompt.clarify.ctrlCCancel: "Ctrl+C iptal"
prompt.clarify.lockAnswer: "yanıtı kilitle"
-prompt.clarify.macClipboardHint: "Cmd+C kopyala · Cmd+V yapıştır · Ctrl+C iptal"
prompt.clarify.other: "Diğer (yanıtınızı yazın)"
prompt.clarify.skipped: "(atlandı)"
-prompt.clarify.typingHint: "Enter gönder · Esc {0} ·"
+prompt.clarify.toggle: "Boşluk seç/kaldır"
prompt.confirm.cancel: "Hayır"
prompt.confirm.confirm: "Evet"
prompt.confirm.hint: "↑/↓ seç · Enter onayla · Y/N hızlı · Esc iptal"
diff --git a/locales/tr.yaml b/locales/tr.yaml
index 0dcc6c2b6da..9520061392c 100644
--- a/locales/tr.yaml
+++ b/locales/tr.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ Netleştirme iptal edildi — mesajınız devam mesajı olarak işlenecek."
expired: "⏳ Bu sorunun süresi doldu — lütfen yeni bir istek gönderin."
native_stream_placeholder: "💬 Seçiminiz bekleniyor..."
+ skip_hint: 'Bu soruyu atlamak için "skip" yazın.'
errors:
rate_limited: "⏱️ Yapay zekâ model servisi istekleri hız sınırlamasına tabi tutuyor. Biraz bekleyin, ardından /retry kullanın."
auth_failed: "⚠️ Yapay zekâ model servisine giriş başarısız oldu. Yeniden giriş yapmak için /login kullanın veya bu botu işleten kişiden ana makinede `hermes doctor` çalıştırmasını isteyin."
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "Diğer (aşağıya yazın)"
clarify_other_type_answer: "Diğer (yanıtınızı yazın)"
clarify_guidance: "Yanıtınızı aşağıdaki istem satırına yazın, ardından Enter'a basın."
- clarify_question_truncated: "… (soru kısaltıldı)"
picker_title_provider: "⚙ Model Seçici — Sağlayıcı Seçin"
picker_provider_row_one: "{name} ({count} model)"
picker_provider_row_other: "{name} ({count} model)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "yazarken görünür · devam için Enter"
hint_clarify_freetext: "yanıtınızı yazıp Enter'a basın"
hint_clarify_batch: "↑/↓ seç, Enter kilitle, Tab sonraki soru"
- hint_clarify_choice: "↑/↓ seç, Enter onayla"
hint_input_disabled: "giriş geçici olarak devre dışı"
hint_input_queues: "giriş aktif kalır; Enter sıraya alır"
hint_command_running: "{frame} komut çalışıyor · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "netleştirme"
label: "Netleştirme"
- timed_out_agent_decides: "(netleştirme {timeout} sn sonra zaman aşımına uğradı — ajan karar verecek)"
timed_out_locked_answers: "(netleştirme {timeout} sn sonra zaman aşımına uğradı — kilitlenen yanıtlar döndürüldü)"
connect:
bell_context: "bağlantı kurulumu"
diff --git a/locales/uk.tui.yaml b/locales/uk.tui.yaml
index feb8089bf54..8462bb64648 100644
--- a/locales/uk.tui.yaml
+++ b/locales/uk.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "Не вдалося визначит
libText.terminalSetup.summaryIn: "{0} у {1}"
libText.text.argsLabel: "Аргументи"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "запит (питань: {0})"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "запит {0}"
-libText.text.clarifyNoSelection: "({0} — нічого не вибрано)"
+libText.text.clarifyHead: "запит (питань: {0})"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0} (без відповіді)"
libText.text.errorLabel: "Помилка"
libText.text.omittedChars: "[{0}; пропущено {1} симв.]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… ще {0} рядк. (повний текст ви
prompt.approval.once: "Дозволити один раз"
prompt.approval.session: "Дозволити на цей сеанс"
prompt.approval.title: "⚠ потрібне схвалення"
-prompt.clarify.back: "назад"
-prompt.clarify.batchHint: "↑/↓ вибрати · Enter {0} · Tab/Shift+Tab перейти до іншого питання · Esc/Ctrl+C скасувати"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc назад"
-prompt.clarify.cancel: "скасувати"
+prompt.clarify.hint: "↑/↓ вибрати · Enter {0} · Tab/Shift+Tab перейти до іншого питання · Esc/Ctrl+C скасувати"
+prompt.clarify.typingHint: "Enter {0} · Esc назад"
prompt.clarify.confirmAndContinue: "підтвердити й продовжити"
-prompt.clarify.ctrlCCancel: "Ctrl+C скасувати"
prompt.clarify.lockAnswer: "зафіксувати відповідь"
-prompt.clarify.macClipboardHint: "Cmd+C копіювати · Cmd+V вставити · Ctrl+C скасувати"
prompt.clarify.other: "Інше (введіть свою відповідь)"
prompt.clarify.skipped: "(пропущено)"
-prompt.clarify.typingHint: "Enter надіслати · Esc {0} ·"
+prompt.clarify.toggle: "Пробіл перемкнути"
prompt.confirm.cancel: "Ні"
prompt.confirm.confirm: "Так"
prompt.confirm.hint: "↑/↓ вибрати · Enter підтвердити · Y/N швидко · Esc скасувати"
diff --git a/locales/uk.yaml b/locales/uk.yaml
index aadc921d86b..fd4f481e7a7 100644
--- a/locales/uk.yaml
+++ b/locales/uk.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ Уточнення скасовано — ваше повідомлення буде оброблено як продовження."
expired: "⏳ Термін цього запиту минув — надішліть новий запит."
native_stream_placeholder: "💬 Очікую на ваш вибір..."
+ skip_hint: 'Відповідайте «skip», щоб пропустити це питання.'
errors:
rate_limited: "⏱️ Сервіс AI-моделі обмежує частоту запитів. Зачекайте трохи, а потім скористайтеся /retry."
auth_failed: "⚠️ Не вдалося ввійти в сервіс AI-моделі. Скористайтеся /login, щоб увійти знову, або попросіть того, хто адмініструє цього бота, виконати `hermes doctor` на хості."
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "Інше (введіть нижче)"
clarify_other_type_answer: "Інше (введіть свою відповідь)"
clarify_guidance: "Введіть відповідь у полі нижче та натисніть Enter."
- clarify_question_truncated: "… (питання скорочено)"
picker_title_provider: "⚙ Вибір моделі — виберіть провайдера"
picker_provider_row_one: "{name} ({count} модель)"
picker_provider_row_other: "{name} ({count} моделей)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "видно під час введення · Enter — продовжити"
hint_clarify_freetext: "введіть відповідь і натисніть Enter"
hint_clarify_batch: "↑/↓ — вибрати, Enter — зафіксувати, Tab — наступне питання"
- hint_clarify_choice: "↑/↓ — вибрати, Enter — підтвердити"
hint_input_disabled: "введення тимчасово вимкнено"
hint_input_queues: "введення активне; Enter додає в чергу"
hint_command_running: "{frame} команда виконується · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "уточнення"
label: "Уточнення"
- timed_out_agent_decides: "(час на уточнення вийшов через {timeout} с — агент вирішить сам)"
timed_out_locked_answers: "(час на уточнення вийшов через {timeout} с — повернено зафіксовані відповіді)"
connect:
bell_context: "налаштування підключення"
diff --git a/locales/zh-hant.tui.yaml b/locales/zh-hant.tui.yaml
index 0c4f689b1c0..24aa3d64ab8 100644
--- a/locales/zh-hant.tui.yaml
+++ b/locales/zh-hant.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "無法在此平台上判斷 {0} 的
libText.terminalSetup.summaryIn: "{0}(位於 {1})"
libText.text.argsLabel: "參數"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "詢問({0} 個問題)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "詢問 {0}"
-libText.text.clarifyNoSelection: "({0} — 未選擇)"
+libText.text.clarifyHead: "詢問({0} 個問題)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0}(未回答)"
libText.text.errorLabel: "錯誤"
libText.text.omittedChars: "[{0};已省略 {1} 字元]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… 還有 {0} 行(完整內容見上方)"
prompt.approval.once: "允許一次"
prompt.approval.session: "本工作階段允許"
prompt.approval.title: "⚠ 需要批准"
-prompt.clarify.back: "返回"
-prompt.clarify.batchHint: "↑/↓ 選擇 · Enter {0} · Tab/Shift+Tab 切換問題 · Esc/Ctrl+C 取消"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc 返回"
-prompt.clarify.cancel: "取消"
+prompt.clarify.hint: "↑/↓ 選擇 · Enter {0} · Tab/Shift+Tab 切換問題 · Esc/Ctrl+C 取消"
+prompt.clarify.typingHint: "Enter {0} · Esc 返回"
prompt.clarify.confirmAndContinue: "確認並繼續"
-prompt.clarify.ctrlCCancel: "Ctrl+C 取消"
prompt.clarify.lockAnswer: "鎖定答案"
-prompt.clarify.macClipboardHint: "Cmd+C 複製 · Cmd+V 貼上 · Ctrl+C 取消"
prompt.clarify.other: "其他(自行輸入答案)"
prompt.clarify.skipped: "(已略過)"
-prompt.clarify.typingHint: "Enter 送出 · Esc {0} ·"
+prompt.clarify.toggle: "空白鍵切換"
prompt.confirm.cancel: "否"
prompt.confirm.confirm: "是"
prompt.confirm.hint: "↑/↓ 選擇 · Enter 確認 · Y/N 快速選擇 · Esc 取消"
diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yaml
index 1c8042b5dad..71fab641747 100644
--- a/locales/zh-hant.yaml
+++ b/locales/zh-hant.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ 已取消釐清 — 你的訊息將作為後續訊息處理。"
expired: "⏳ 此提問已逾期 — 請重新送出請求。"
native_stream_placeholder: "💬 等待你的選擇..."
+ skip_hint: '回覆「skip」即可略過此問題。'
errors:
rate_limited: "⏱️ AI 模型服務正在限制請求速率。請稍候,再使用 /retry。"
auth_failed: "⚠️ 登入 AI 模型服務失敗。請使用 /login 重新登入,或請這個 bot 的管理者在主機上執行 `hermes doctor`。"
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "其他(在下方輸入)"
clarify_other_type_answer: "其他(輸入你的答案)"
clarify_guidance: "在下方的輸入欄輸入答案,然後按 Enter。"
- clarify_question_truncated: "…(問題已截斷)"
picker_title_provider: "⚙ 模型選擇器 — 選擇提供方"
picker_provider_row_one: "{name}({count} 個模型)"
picker_provider_row_other: "{name}({count} 個模型)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "輸入內容會顯示 · Enter 繼續"
hint_clarify_freetext: "輸入答案並按 Enter"
hint_clarify_batch: "↑/↓ 選擇,Enter 鎖定,Tab 下一題"
- hint_clarify_choice: "↑/↓ 選擇,Enter 確認"
hint_input_disabled: "輸入暫時停用"
hint_input_queues: "仍可輸入;Enter 排入佇列"
hint_command_running: "{frame} 指令執行中 · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "澄清"
label: "澄清"
- timed_out_agent_decides: "(澄清已在 {timeout} 秒後逾時 — 由代理決定)"
timed_out_locked_answers: "(澄清已在 {timeout} 秒後逾時 — 已回傳鎖定的答案)"
connect:
bell_context: "連線設定"
diff --git a/locales/zh.tui.yaml b/locales/zh.tui.yaml
index 15f2de9200c..9588ba3d0c4 100644
--- a/locales/zh.tui.yaml
+++ b/locales/zh.tui.yaml
@@ -529,10 +529,8 @@ libText.terminalSetup.settingsPathUnknown: "无法在此平台上确定 {0} 的
libText.terminalSetup.summaryIn: "{0}(位于 {1})"
libText.text.argsLabel: "参数"
libText.text.clarifyAnswered: "✓ {0} → {1}"
-libText.text.clarifyBatchHead: "提问({0} 个问题)"
-libText.text.clarifyBatchReason: "({0})"
-libText.text.clarifyHead: "提问 {0}"
-libText.text.clarifyNoSelection: "({0} — 未选择)"
+libText.text.clarifyHead: "提问({0} 个问题)"
+libText.text.clarifyReason: "({0})"
libText.text.clarifyUnanswered: "· {0}(未回答)"
libText.text.errorLabel: "错误"
libText.text.omittedChars: "[{0};已省略 {1} 字符]"
@@ -653,17 +651,13 @@ prompt.approval.moreLines: "… 还有 {0} 行(完整内容见上方)"
prompt.approval.once: "仅允许一次"
prompt.approval.session: "本次会话允许"
prompt.approval.title: "⚠ 需要批准"
-prompt.clarify.back: "返回"
-prompt.clarify.batchHint: "↑/↓ 选择 · Enter {0} · Tab/Shift+Tab 切换问题 · Esc/Ctrl+C 取消"
-prompt.clarify.batchTypingHint: "Enter {0} · Esc 返回"
-prompt.clarify.cancel: "取消"
+prompt.clarify.hint: "↑/↓ 选择 · Enter {0} · Tab/Shift+Tab 切换问题 · Esc/Ctrl+C 取消"
+prompt.clarify.typingHint: "Enter {0} · Esc 返回"
prompt.clarify.confirmAndContinue: "确认并继续"
-prompt.clarify.ctrlCCancel: "Ctrl+C 取消"
prompt.clarify.lockAnswer: "锁定答案"
-prompt.clarify.macClipboardHint: "Cmd+C 复制 · Cmd+V 粘贴 · Ctrl+C 取消"
prompt.clarify.other: "其他(输入你的回答)"
prompt.clarify.skipped: "(已跳过)"
-prompt.clarify.typingHint: "Enter 发送 · Esc {0} ·"
+prompt.clarify.toggle: "空格切换"
prompt.confirm.cancel: "否"
prompt.confirm.confirm: "是"
prompt.confirm.hint: "↑/↓ 选择 · Enter 确认 · Y/N 快捷 · Esc 取消"
diff --git a/locales/zh.yaml b/locales/zh.yaml
index 914fe20cfad..311a8d790bb 100644
--- a/locales/zh.yaml
+++ b/locales/zh.yaml
@@ -653,6 +653,7 @@ gateway:
cancelled: "↩️ 澄清已取消——你的消息将作为后续消息处理。"
expired: "⏳ 此提示已过期——请发送新的请求。"
native_stream_placeholder: "💬 等待你的选择..."
+ skip_hint: '回复“skip”即可跳过此问题。'
errors:
rate_limited: "⏱️ AI 模型服务正在限流。请稍等片刻,然后使用 /retry。"
auth_failed: "⚠️ 登录 AI 模型服务失败。请使用 /login 重新登录,或请运行此机器人的人在主机上执行 `hermes doctor`。"
@@ -2032,7 +2033,6 @@ cli:
clarify_other_type_below: "其他(在下方输入)"
clarify_other_type_answer: "其他(输入你的回答)"
clarify_guidance: "在下方提示中输入你的回答,然后按 Enter。"
- clarify_question_truncated: "…(问题已截断)"
picker_title_provider: "⚙ 模型选择器 — 选择提供方"
picker_provider_row_one: "{name}({count} 个模型)"
picker_provider_row_other: "{name}({count} 个模型)"
@@ -2077,7 +2077,6 @@ cli:
hint_vault_username: "输入时可见 · Enter 继续"
hint_clarify_freetext: "输入你的回答并按 Enter"
hint_clarify_batch: "↑/↓ 选择,Enter 锁定,Tab 下一个问题"
- hint_clarify_choice: "↑/↓ 选择,Enter 确认"
hint_input_disabled: "输入已暂时禁用"
hint_input_queues: "输入仍可用;Enter 加入队列"
hint_command_running: "{frame} 命令执行中 · {detail}"
@@ -2260,7 +2259,6 @@ cli:
clarify:
bell_context: "澄清"
label: "澄清"
- timed_out_agent_decides: "(澄清在 {timeout} 秒后超时——由代理自行决定)"
timed_out_locked_answers: "(澄清在 {timeout} 秒后超时——已返回锁定的答案)"
connect:
bell_context: "连接设置"
diff --git a/optional-skills/creative/baoyu-article-illustrator/PORT_NOTES.md b/optional-skills/creative/baoyu-article-illustrator/PORT_NOTES.md
index d81dbc9ed83..4dd7013314f 100644
--- a/optional-skills/creative/baoyu-article-illustrator/PORT_NOTES.md
+++ b/optional-skills/creative/baoyu-article-illustrator/PORT_NOTES.md
@@ -13,7 +13,7 @@ Ported from [JimLiu/baoyu-skills](https://github.com/JimLiu/baoyu-skills) v1.57.
| Metadata namespace | `openclaw` | `hermes` |
| Trigger | `/baoyu-article-illustrator` slash command + CLI flags | Natural language skill matching |
| User config | EXTEND.md (project/user/XDG paths) + first-time-setup | Removed — not part of Hermes infra |
-| User prompts | `AskUserQuestion` (batched, multi-question) | `clarify` tool (one question at a time) |
+| User prompts | `AskUserQuestion` (batched, multi-question) | `clarify` tool (batched, up to 5 questions) |
| Image generation | `baoyu-imagine` (Bun/TypeScript, multi-provider, accepts `--ref`, writes to local path) | `image_generate` (returns URL only; agent downloads via `terminal`/`curl`) |
| Backend selection | User picks provider via CLI flags | Not agent-selectable — `image_generate` uses the user-configured FAL model. Removed hardcoded "nano banana pro" line from `prompts/system.md`. |
| Reference images | Passed to backend via `--ref`, copied via shell | `vision_analyze` extracts a textual description (binary never touched by `write_file`/`read_file`); description is embedded in prompts. Optional `terminal cp` for a local record. |
diff --git a/optional-skills/creative/baoyu-article-illustrator/SKILL.md b/optional-skills/creative/baoyu-article-illustrator/SKILL.md
index 6adbebf0e98..2baafc3d385 100644
--- a/optional-skills/creative/baoyu-article-illustrator/SKILL.md
+++ b/optional-skills/creative/baoyu-article-illustrator/SKILL.md
@@ -83,7 +83,7 @@ If the user asks for a different layout (e.g., images alongside the article, or
```
- [ ] Step 1: Detect reference images (if provided)
- [ ] Step 2: Analyze content
-- [ ] Step 3: Confirm settings (clarify tool, one question at a time)
+- [ ] Step 3: Confirm settings (clarify tool)
- [ ] Step 4: Generate outline
- [ ] Step 5: Generate prompts
- [ ] Step 6: Generate images (image_generate)
@@ -115,7 +115,7 @@ Full procedures: [references/workflow.md](references/workflow.md#step-2-analyze)
### Step 3: Confirm Settings
-Use the `clarify` tool. Since `clarify` handles one question at a time, ask the most important question first. Skip any question whose answer is already present in the user's request.
+Use the `clarify` tool. Put the independent questions in one `questions` array (up to 5). Skip any question whose answer is already present in the user's request.
| Order | Question | Options |
|-------|----------|---------|
diff --git a/optional-skills/creative/baoyu-article-illustrator/references/workflow.md b/optional-skills/creative/baoyu-article-illustrator/references/workflow.md
index b859b7f3a60..b8c594fec30 100644
--- a/optional-skills/creative/baoyu-article-illustrator/references/workflow.md
+++ b/optional-skills/creative/baoyu-article-illustrator/references/workflow.md
@@ -109,7 +109,7 @@ Note: `image_generate` does not accept reference-image inputs under any usage ty
## Step 3: Confirm Settings
-Use the `clarify` tool. Since `clarify` handles one question at a time, ask the most important question first. Skip any question the user already answered in their request.
+Use the `clarify` tool. Put the independent questions in one `questions` array (up to 5). Skip any question the user already answered in their request.
### Q1: Preset or Type (highest priority)
diff --git a/optional-skills/creative/baoyu-comic/PORT_NOTES.md b/optional-skills/creative/baoyu-comic/PORT_NOTES.md
index 637b7befb54..f0e622e74ea 100644
--- a/optional-skills/creative/baoyu-comic/PORT_NOTES.md
+++ b/optional-skills/creative/baoyu-comic/PORT_NOTES.md
@@ -11,7 +11,7 @@ Ported from [JimLiu/baoyu-skills](https://github.com/JimLiu/baoyu-skills) v1.56.
| Metadata namespace | `openclaw` | `hermes` (with `tags` + `homepage`) |
| Trigger | Slash commands / CLI flags | Natural language skill matching |
| User config | EXTEND.md file (project/user/XDG paths) | Removed — not part of Hermes infra |
-| User prompts | `AskUserQuestion` (batched) | `clarify` tool (one question at a time) |
+| User prompts | `AskUserQuestion` (batched) | `clarify` tool (batched, up to 5 questions) |
| Image generation | baoyu-imagine (Bun/TypeScript, supports `--ref`) | `image_generate` — **prompt-only**, returns a URL; no reference image input; agent must download the URL to the output directory |
| PDF assembly | `scripts/merge-to-pdf.ts` (Bun + `pdf-lib`) | Removed — the PDF merge step is out of scope for this port; pages are delivered as PNGs only |
| Platform support | Linux/macOS/Windows/WSL/PowerShell | Linux/macOS only |
diff --git a/optional-skills/creative/baoyu-comic/SKILL.md b/optional-skills/creative/baoyu-comic/SKILL.md
index 6745b55e04e..8ca881e981f 100644
--- a/optional-skills/creative/baoyu-comic/SKILL.md
+++ b/optional-skills/creative/baoyu-comic/SKILL.md
@@ -168,11 +168,11 @@ Input → Analyze → [Check Existing?] → [Confirm: Style + Reviews] → Story
### User Questions
-Use the `clarify` tool to confirm options. Since `clarify` handles one question at a time, ask the most important question first and proceed sequentially. See [references/workflow.md](references/workflow.md) for the full Step 2 question set.
+Use the `clarify` tool to confirm options. Put independent questions in one `questions` array (up to 5); ask separately any question whose options depend on an earlier answer. See [references/workflow.md](references/workflow.md) for the full Step 2 question set.
-**Timeout handling (CRITICAL)**: `clarify` can return `"The user did not provide a response within the time limit. Use your best judgement to make the choice and proceed."` — this is NOT user consent to default everything.
+**Timeout handling (CRITICAL)**: `clarify` can return `"outcome": "timed_out"` with responses marked `"status": "unanswered"` — this is NOT user consent to default everything.
-- Treat it as a default **for that one question only**. Continue asking the remaining Step 2 questions in sequence; each question is an independent consent point.
+- Treat it as a default **for the unanswered questions only**. Each question is an independent consent point.
- **Surface the default to the user visibly** in your next message so they have a chance to correct it: e.g. `"Style: defaulted to ohmsha preset (clarify timed out). Say the word to switch."` — an unreported default is indistinguishable from never having asked.
- Do NOT collapse Step 2 into a single "use all defaults" pass after one timeout. If the user is genuinely absent, they will be equally absent for all five questions — but they can correct visible defaults when they return, and cannot correct invisible ones.
diff --git a/optional-skills/creative/baoyu-comic/references/workflow.md b/optional-skills/creative/baoyu-comic/references/workflow.md
index f98109374a8..2d288167225 100644
--- a/optional-skills/creative/baoyu-comic/references/workflow.md
+++ b/optional-skills/creative/baoyu-comic/references/workflow.md
@@ -97,9 +97,9 @@ Save result and handle accordingly:
- Language (detected or user-specified)
- **Recommended style**: [art] + [tone] (based on content signals)
-**Use `clarify` one question at a time**, in priority order:
+**Use `clarify` with the independent questions in one `questions` array**, in priority order:
-> **Timeout handling (CRITICAL)**: if `clarify` returns `"The user did not provide a response within the time limit. Use your best judgement..."`, that is a per-question default, NOT blanket consent. Continue to the next question in the sequence — do not bail out of Step 2. Then, in your next user-visible message, explicitly surface every default that was taken (e.g. `"Defaulted style → ohmsha, narrative focus → concept explanation, audience → developers (clarify timed out on all three). Say the word to redirect."`). An unreported default is indistinguishable to the user from "the agent never asked."
+> **Timeout handling (CRITICAL)**: if `clarify` returns `"outcome": "timed_out"`, every response marked `"status": "unanswered"` is a per-question default, NOT blanket consent — do not bail out of Step 2. Then, in your next user-visible message, explicitly surface every default that was taken (e.g. `"Defaulted style → ohmsha, narrative focus → concept explanation, audience → developers (clarify timed out on all three). Say the word to redirect."`). An unreported default is indistinguishable to the user from "the agent never asked."
### Question 1: Visual Style
diff --git a/optional-skills/migration/openclaw-migration/SKILL.md b/optional-skills/migration/openclaw-migration/SKILL.md
index d9e69ac3396..0913366c91c 100644
--- a/optional-skills/migration/openclaw-migration/SKILL.md
+++ b/optional-skills/migration/openclaw-migration/SKILL.md
@@ -102,7 +102,7 @@ For every `clarify` call:
- never include fake form fields in the question such as `enter directory here`, blank lines to fill in, or underscores like `_____`
- for open-ended path questions, ask only the plain sentence; the user types in the normal CLI prompt below the panel
-If a `clarify` call returns an error, inspect the error text, correct the payload, and retry once with a valid `question` and clean choices.
+If a `clarify` call returns an error, inspect the error text, correct the payload, and retry once with a valid `questions` array and clean choices.
When `clarify` is available and the dry run reveals any required user decision, your **next action must be a `clarify` tool call**.
Do not end the turn with a normal assistant message such as:
diff --git a/skills/creative/baoyu-infographic/PORT_NOTES.md b/skills/creative/baoyu-infographic/PORT_NOTES.md
index 0a2d86d89ca..2a5dd091c7d 100644
--- a/skills/creative/baoyu-infographic/PORT_NOTES.md
+++ b/skills/creative/baoyu-infographic/PORT_NOTES.md
@@ -13,7 +13,7 @@ Only `SKILL.md` was modified. All 45 reference files are verbatim copies.
| Metadata namespace | `openclaw` | `hermes` |
| Trigger | `/baoyu-infographic` slash command | Natural language skill matching |
| User config | EXTEND.md file (project/user/XDG paths) | Removed — not part of Hermes infra |
-| User prompts | `AskUserQuestion` (batched) | `clarify` tool (one at a time) |
+| User prompts | `AskUserQuestion` (batched) | `clarify` tool (batched, up to 5 questions) |
| Image generation | baoyu-imagine (Bun/TypeScript) | `image_generate` tool |
| Platform support | Linux/macOS/Windows/WSL/PowerShell | Linux/macOS only |
| File operations | Bash commands | Hermes file tools (write_file, read_file) |
diff --git a/skills/creative/baoyu-infographic/SKILL.md b/skills/creative/baoyu-infographic/SKILL.md
index 6206a5b220a..bab7607aadf 100644
--- a/skills/creative/baoyu-infographic/SKILL.md
+++ b/skills/creative/baoyu-infographic/SKILL.md
@@ -180,7 +180,7 @@ See `references/structured-content-template.md` for detailed format.
### Step 4: Confirm Options
-Use the `clarify` tool to confirm options with the user. Since `clarify` handles one question at a time, ask the most important question first:
+Use the `clarify` tool to confirm options with the user. Put the independent questions below in one `questions` array (up to 5); ask separately any question whose options depend on an earlier answer:
**Q1 — Combination**: Present 3+ layout×style combos with rationale. Ask user to pick one.
diff --git a/tests-js/scripts/mock-server.ts b/tests-js/scripts/mock-server.ts
index efe9106e8cd..43735b36ed3 100644
--- a/tests-js/scripts/mock-server.ts
+++ b/tests-js/scripts/mock-server.ts
@@ -269,7 +269,7 @@ const SIDEBAR_CROSS_SCRIPT: ScriptedTurn[] = sidebarCrossScript()
const QUEUE_STOP_SCRIPT: ScriptedTurn[] = [
{
text: 'Starting a task that will keep this turn active.',
- toolCalls: [{ name: 'clarify', args: { question: 'Keep working?', choices: ['Yes', 'No'] } }],
+ toolCalls: [{ name: 'clarify', args: { questions: [{ question: 'Keep working?', choices: ['Yes', 'No'] }] } }],
},
{ text: 'The paused task completed.' },
]
@@ -379,7 +379,7 @@ const TOOL_THEN_FAILURE_TURN: ScriptedTurn = {
const BLOCKING_CLARIFY_TURN: ScriptedTurn = {
text: '',
- toolCalls: [{ name: 'clarify', args: { question: BLOCKING_CLARIFY_QUESTION, choices: ['Yes', 'No'] } }],
+ toolCalls: [{ name: 'clarify', args: { questions: [{ question: BLOCKING_CLARIFY_QUESTION, choices: ['Yes', 'No'] }] } }],
}
/**
diff --git a/tests/agent/test_compression_marker.py b/tests/agent/test_compression_marker.py
index 84e67ec3c58..f2917056efe 100644
--- a/tests/agent/test_compression_marker.py
+++ b/tests/agent/test_compression_marker.py
@@ -39,7 +39,7 @@ def test_real_renderers_emit_a_guard_visible_marker_never_the_imitable_idiom():
the marker's own apostrophe out of the guard's reach.
"""
quoted = "a'b\"c " * 400
- clarify = json.dumps({"user_response": "A" * 5000})
+ clarify = json.dumps({"responses": [{"status": "answered", "user_response": "A" * 5000}]})
outputs = {
"clarify": _summarize_tool_result("clarify", "{}", clarify),
"fallback_turn": _compact_fallback_turn("z " * 5000),
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index 029af6e5c54..aa724120384 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -105,33 +105,36 @@ class TestSummarizeToolResultSkillTools:
class TestSummarizeToolResultClarify:
def test_preserves_resolved_user_response_without_metadata(self):
- content = json.dumps({
+ content = json.dumps({"responses": [{
"question": "When should I deploy?",
"choices_offered": ["Friday", "Monday"],
+ "status": "answered",
"user_response": "Friday",
- })
+ }], "outcome": "submitted"})
summary = _summarize_tool_result("clarify", "{}", content)
assert summary == '[clarify] user responded: "Friday"'
def test_preserves_multi_select_user_response(self):
- content = json.dumps({
+ content = json.dumps({"responses": [{
"question": "Which checks should I run?",
"choices_offered": ["lint", "tests", "types"],
+ "status": "answered",
"user_response": ["lint", "tests"],
- })
+ }], "outcome": "submitted"})
summary = _summarize_tool_result("clarify", "{}", content)
assert summary == '[clarify] user responded: ["lint", "tests"]'
def test_long_response_is_bounded_and_prefixed_text_is_not_trusted(self):
- content = json.dumps({
+ content = json.dumps({"responses": [{
"question": "Describe the deployment constraints",
"choices_offered": None,
+ "status": "answered",
"user_response": "A" * 1_000,
- })
+ }], "outcome": "submitted"})
summary = _summarize_tool_result("clarify", "{}", content)
@@ -168,7 +171,9 @@ class TestSummarizeToolResultClarify:
assert connection.execute("SELECT content FROM messages").fetchone()[0] == summary
def test_unpaired_surrogates_are_safe_through_pruning_and_sqlite(self, compressor):
- content = json.dumps({"user_response": "Привет 😀" + "\ud83d" * 1_000})
+ content = json.dumps({"responses": [{
+ "status": "answered", "user_response": "Привет 😀" + "\ud83d" * 1_000,
+ }], "outcome": "submitted"})
messages = [
{
"role": "assistant",
@@ -209,8 +214,8 @@ class TestSummarizeToolResultClarify:
"content",
[
json.dumps({"error": "Failed to get user input: internal details"}),
- json.dumps({"question": "Q?", "user_response": ""}),
- json.dumps({"question": "Q?", "user_response": {"internal": "value"}}),
+ json.dumps({"responses": [{"question": "Q?", "status": "skipped", "user_response": None}]}),
+ json.dumps({"responses": [{"question": "Q?", "status": "answered", "user_response": {"internal": "value"}}]}),
"not json",
],
)
@@ -219,69 +224,15 @@ class TestSummarizeToolResultClarify:
assert summary == "[clarify] asked user a question"
- @pytest.mark.parametrize(
- "sentinel",
- [
- # cli.py clarify timeout callback
- "The user did not provide a response within the time limit. "
- "Use your best judgement to make the choice and proceed.",
- # gateway/run.py timeout + delivery-failure paths
- "[user did not respond within 15m]",
- "[clarify prompt could not be delivered]",
- # hermes_cli/oneshot.py no-user callback
- "[oneshot mode: no user available. Pick the best option from "
- "['a', 'b'] using your own judgment and continue.]",
- ],
- )
- def test_non_response_sentinels_are_not_attributed_to_user(self, sentinel):
- """Timeout/no-user sentinel prose must not be quoted as a user answer."""
- content = json.dumps({
- "question": "Deploy when?",
- "choices_offered": ["Friday", "Monday"],
- "user_response": sentinel,
- })
-
- summary = _summarize_tool_result("clarify", "{}", content)
-
- assert summary == "[clarify] asked user a question"
-
- def test_multi_select_containing_sentinel_stays_generic(self):
- content = json.dumps({
- "user_response": ["lint", "[user did not respond within 15m]"],
- })
-
- summary = _summarize_tool_result("clarify", "{}", content)
-
- assert summary == "[clarify] asked user a question"
-
- def test_live_oneshot_producer_is_recognized_as_sentinel(self):
- """Producer→recognizer drift guard: run the REAL oneshot no-user
- callback and assert its output is filtered. If the producer's wording
- drifts away from _CLARIFY_NON_RESPONSE_PREFIXES, this fails."""
- from hermes_cli.oneshot import _oneshot_clarify_callback
-
- sentinels = (
- _oneshot_clarify_callback("Deploy when?", choices=["a", "b"]),
- _oneshot_clarify_callback(
- "Deploy when?", choices=["a", "b"], multi_select=True
- ),
- _oneshot_clarify_callback("Deploy when?"),
- )
- for sentinel in sentinels:
- content = json.dumps({"user_response": sentinel})
-
- summary = _summarize_tool_result("clarify", "{}", content)
-
- assert summary == "[clarify] asked user a question", sentinel
-
def test_preserves_batch_user_response_from_responses_list(self):
- """Batch clarify (``questions=[...]``) nests answers inside ``responses[].user_response``;
- the summarizer must surface them, not just 'asked user a question' (#106077)."""
+ """Answers live inside ``responses[].user_response``; the summarizer must surface them,
+ not just 'asked user a question' (#106077)."""
content = json.dumps({
"responses": [
{
"question": "May the fields be removed?",
"choices_offered": None,
+ "status": "answered",
"user_response": "Keep the fields until ratification.",
}
]
@@ -289,15 +240,15 @@ class TestSummarizeToolResultClarify:
summary = _summarize_tool_result("clarify", "{}", content)
- assert summary == '[clarify] user responded: ["Keep the fields until ratification."]'
+ assert summary == '[clarify] user responded: "Keep the fields until ratification."'
def test_preserves_batch_multi_select_and_skips_empties(self):
"""A partially-answered batch (multi_select + a skipped question) still surfaces every real decision."""
content = json.dumps({
"responses": [
- {"question": "Q1?", "user_response": "Answer one"},
- {"question": "Q2?", "user_response": ["Choice A", "Choice B"]},
- {"question": "Q3?", "user_response": ""},
+ {"question": "Q1?", "status": "answered", "user_response": "Answer one"},
+ {"question": "Q2?", "status": "answered", "user_response": ["Choice A", "Choice B"]},
+ {"question": "Q3?", "status": "skipped", "user_response": None},
]
})
diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.py
index 547a6793d0c..76c2e4b305b 100644
--- a/tests/agent/test_run_agent.py
+++ b/tests/agent/test_run_agent.py
@@ -2246,7 +2246,7 @@ class TestAgentRuntimePostHookOwnershipSync:
("todo_list", {"todos": []}),
("session_search", {"query": "needle"}),
("memory", {"action": "view", "target": "memory"}),
- ("clarify", {"question": "Continue?"}),
+ ("clarify", {"questions": [{"question": "Continue?"}]}),
("read_terminal", {}),
("desktop_preview", {"action": "read"}),
("drive_preview", {"action": "elements"}),
diff --git a/tests/agent/test_sequential_tool_timeout.py b/tests/agent/test_sequential_tool_timeout.py
index 3f0f6066111..1250f584ae3 100644
--- a/tests/agent/test_sequential_tool_timeout.py
+++ b/tests/agent/test_sequential_tool_timeout.py
@@ -112,7 +112,7 @@ def _clarify_call(call_id: str = "clarify-1"):
type="function",
function=SimpleNamespace(
name="clarify",
- arguments='{"question": "Pick one?", "choices": ["A", "B"]}',
+ arguments='{"questions": [{"question": "Pick one?", "choices": ["A", "B"]}]}',
),
)
@@ -309,11 +309,11 @@ def test_sequential_timeout_does_not_cut_clarify_human_wait(
lambda: clarify_timeout,
)
- def _callback(question, choices, multi_select=False):
+ def _callback(questions):
# Must OUTLAST the 1.0s sequential deadline — the test proves the
# generic timeout never cuts a human clarify wait.
time.sleep(1.3)
- return "A"
+ return {"answers": {"q0": "A"}, "outcome": "submitted"}
agent.clarify_callback = _callback
terminal_events: list[dict] = []
@@ -343,7 +343,7 @@ def test_sequential_timeout_does_not_cut_clarify_human_wait(
assert time.monotonic() - started < 10.0
assert [message["tool_call_id"] for message in messages] == ["clarify-1", "next"]
payload = json.loads(messages[0]["content"])
- assert payload["user_response"] == "A"
+ assert payload["responses"][0]["user_response"] == "A"
assert "timed out" not in messages[0]["content"]
assert messages[1]["content"] == "second result"
assert not any(event.get("error_type") == "tool_timeout" for event in terminal_events)
diff --git a/tests/e2e/core/terminal/test_interactive_roundtrip.py b/tests/e2e/core/terminal/test_interactive_roundtrip.py
index 830bb3f45bb..6306b0db4d6 100644
--- a/tests/e2e/core/terminal/test_interactive_roundtrip.py
+++ b/tests/e2e/core/terminal/test_interactive_roundtrip.py
@@ -66,7 +66,7 @@ class Script:
self.tool_results.setdefault(tag, []).append(str(last.get("content") or ""))
return Text(f"DONE {tag}")
if kind == "CLARIFY":
- return ToolCall("clarify", {"question": f"Which colour for {tag}?", "choices": ["red", "blue"]})
+ return ToolCall("clarify", {"questions": [{"question": f"Which colour for {tag}?", "choices": ["red", "blue"]}]})
return ToolCall("terminal", {"command": f"rm -rf {self.victims[tag]}"})
@@ -118,7 +118,7 @@ def _drive(backend: Backend, script: Script, kind: str, how: str, tag: str) -> N
req_idx = next(i for i, f in enumerate(a.snapshot()) if f is request or f.get("id") == rid)
assert isinstance(rid, str) and rid.startswith("srq-"), request
if kind == "clarify":
- assert request["params"].get("question") == f"Which colour for {tag}?", request["params"]
+ assert request["params"]["questions"][0]["question"] == f"Which colour for {tag}?", request["params"]
else:
assert str(victim) in str(request["params"].get("command")), request["params"]
assert request["params"].get("request_id"), request["params"]
@@ -149,7 +149,7 @@ def _drive(backend: Backend, script: Script, kind: str, how: str, tag: str) -> N
answer = f"blue-{tag}"
if kind == "clarify":
- responder.respond(rid, {"answer": answer})
+ responder.respond(rid, {"answers": {"q0": answer}})
elif how == "rpc":
choice = "deny" if kind == "approval_deny" else "once"
resolved = responder.call("approval.respond", session_id=sid, choice=choice,
diff --git a/tests/e2e/core/tui_pty/test_modals_resize.py b/tests/e2e/core/tui_pty/test_modals_resize.py
index eb9276402de..b83767e84af 100644
--- a/tests/e2e/core/tui_pty/test_modals_resize.py
+++ b/tests/e2e/core/tui_pty/test_modals_resize.py
@@ -78,7 +78,7 @@ def _visible_once(tui: TmuxTui, needles: list[str]) -> str:
def _scenario(root, victim) -> object:
command = f"for i in $(seq -w 1 {len(TOOL_LINES)}); do echo tout$i; sleep 0.3; done"
script = [
- ToolCall("clarify", {"question": QUESTION, "choices": ["red", "blue"]}), Text(REPLIES["c1"]),
+ ToolCall("clarify", {"questions": [{"question": QUESTION, "choices": ["red", "blue"]}]}), Text(REPLIES["c1"]),
ToolCall("terminal", {"command": f"rm -rf {victim}"}), Text(REPLIES["a1"]),
ToolCall("terminal", {"command": command}), Text(REPLIES["t1"]),
]
@@ -98,18 +98,18 @@ def _scenario(root, victim) -> object:
cells.phase = "clarify"
# 1. clarify card open across a shrink and a grow, answered afterwards.
tui.submit("pick a colour mq1")
- tui.wait_for("quick pick")
+ tui.wait_for("1. red")
for cols in (90, 130):
tui.resize(cols)
tui.wait_quiet(1.0)
cells.add("clarify_card_survives_resize",
- _visible_once(tui, [f"ask {QUESTION}", "1. red", "2. blue"]), tui.dump())
+ _visible_once(tui, ["ask 1 question", f"▸ {QUESTION}", "1. red", "2. blue"]), tui.dump())
tui.key("Down")
tui.wait_for(lambda t: "▸ 2. blue" in t, history=False)
tui.key("Enter")
tui.wait_replies(1)
results = _tool_results(llm)
- answer = json.loads(results[0]).get("user_response") if results else None
+ answer = json.loads(results[0])["responses"][0]["user_response"] if results else None
cells.add("clarify_answer_reaches_tool", "" if answer == "blue" else f"tool result {results[:1]}")
tui.wait_quiet(1.0)
n = tui.text().count(f'Clarify("{QUESTION}")')
diff --git a/tests/gateway/test_clarify_card_retire_on_timeout.py b/tests/gateway/test_clarify_card_retire_on_timeout.py
index 622806983e9..e5985b0e9c6 100644
--- a/tests/gateway/test_clarify_card_retire_on_timeout.py
+++ b/tests/gateway/test_clarify_card_retire_on_timeout.py
@@ -39,13 +39,19 @@ class _TextAdapter(_CardAdapter):
retire_clarify_card = None # type: ignore[assignment]
-def _run_clarify(adapter, answer=None, questions=None, answers=(), via_tool=False):
+_ONE_QUESTION = [{"qid": "q0", "question": "Pick one", "choices": ["a", "b"], "multi_select": False}]
+
+
+def _asked(adapter):
+ return [text.split("\n")[0] for text in adapter.asked]
+
+
+def _run_clarify(adapter, questions=_ONE_QUESTION, answers=(), via_tool=False):
"""Returns (clarify result, labels of every coroutine the runner scheduled).
- ``answer`` resolves a single question with that text instead of letting it time out.
- ``questions`` drives clarify_tool's batch form instead: question i resolves from
- ``answers[i]``, and ``None`` leaves it unanswered so it expires. ``via_tool`` routes the
- batch through ``clarify_tool`` itself rather than calling the runner's callback directly."""
+ Question i resolves from ``answers[i]``, and ``None`` leaves it unanswered so it expires.
+ ``via_tool`` routes the questions through ``clarify_tool`` itself rather than calling the
+ runner's callback directly."""
from gateway.run_turn_runner import TurnRunner
from tools import clarify_gateway as cm
@@ -72,26 +78,24 @@ def _run_clarify(adapter, answer=None, questions=None, answers=(), via_tool=Fals
entry = real_register(**kwargs)
index = seen["n"]
seen["n"] += 1
- target = answer if questions is None else (answers[index] if index < len(answers) else None)
+ target = answers[index] if index < len(answers) else None
if target is not None:
cm.resolve_gateway_clarify(kwargs["clarify_id"], target)
return entry
with patch.object(cm, "register", _register), \
patch("tools.clarify_gateway.get_clarify_timeout", return_value=0.05):
- if questions is None:
- return runner._clarify_callback_sync("Pick one", ["a", "b"]), labels
if via_tool:
from tools.clarify_tool import clarify_tool
- return clarify_tool("", questions=questions,
- callback=runner._clarify_callback_sync), labels
- return runner._clarify_callback_sync("", None, questions=questions), labels
+ return clarify_tool(questions, callback=runner._clarify_callback_sync), labels
+ return runner._clarify_callback_sync(questions), labels
def test_timeout_retires_the_native_card_with_the_expired_notice():
adapter = _CardAdapter()
- response, _labels = _run_clarify(adapter)
- assert response.startswith("[user did not respond")
+ reply, _labels = _run_clarify(adapter)
+ assert reply["outcome"] == "timed_out"
+ assert reply["notice"].startswith("[user did not respond")
assert len(adapter.retired) == 1
assert "expired" in adapter.retired[0][1].lower()
@@ -104,8 +108,8 @@ def test_timeout_schedules_nothing_for_adapters_without_a_card():
def test_real_answer_starting_with_a_bracket_is_not_mistaken_for_a_sentinel():
"""'[A] staging' is a user answer, not a timeout: no card retirement, typing re-armed."""
adapter = _CardAdapter()
- response, labels = _run_clarify(adapter, answer="[A] staging")
- assert response == "[A] staging"
+ reply, labels = _run_clarify(adapter, answers=("[A] staging",))
+ assert reply == {"answers": {"q0": "[A] staging"}, "outcome": "submitted"}
assert adapter.retired == []
assert labels == ["Clarify send failed to schedule"]
assert adapter.resumed == 1 # a lone card re-arms typing the moment it is answered
@@ -114,29 +118,29 @@ def test_real_answer_starting_with_a_bracket_is_not_mistaken_for_a_sentinel():
# --- Batches: one card per question, stop at the first unanswered one -----
-_THREE_QUESTIONS = [{"qid": f"q{i}", "question": q, "choices": ["a", "b"]}
+_THREE_QUESTIONS = [{"qid": f"q{i}", "question": q, "choices": ["a", "b"], "multi_select": False}
for i, q in enumerate(("One?", "Two?", "Three?"))]
@pytest.mark.parametrize("answers,asked,payload,resumed", [
# Nobody answers question 1: the batch ends there instead of re-asking — every further
# question used to cost another full clarify_timeout — and reports the walk-away.
- ((), ["One?"], {"answers": {}, "timed_out": True, "notice": "[user did not respond within 0m]"}, 0),
+ ((), ["One?"], {"answers": {}, "outcome": "timed_out", "notice": "[user did not respond within 0m]"}, 0),
# Answers already given survive; the unanswered question is not invented.
(("use postgres",), ["One?", "Two?"],
- {"answers": {"q0": "use postgres"}, "timed_out": True, "notice": "[user did not respond within 0m]"}, 0),
+ {"answers": {"q0": "use postgres"}, "outcome": "timed_out", "notice": "[user did not respond within 0m]"}, 0),
# A fully answered batch re-arms typing once, at the end: between two cards the re-arm
# would only open a bubble the next question's boundary finalizes.
(("one", "two", "three"), ["One?", "Two?", "Three?"],
- {"answers": {"q0": "one", "q1": "two", "q2": "three"}, "timed_out": False}, 1),
+ {"answers": {"q0": "one", "q1": "two", "q2": "three"}, "outcome": "submitted"}, 1),
])
def test_batch_routing(answers, asked, payload, resumed):
adapter = _CardAdapter()
- raw, _labels = _run_clarify(adapter, questions=_THREE_QUESTIONS, answers=answers)
- assert adapter.asked == asked
- assert json.loads(raw) == payload
+ reply, _labels = _run_clarify(adapter, questions=_THREE_QUESTIONS, answers=answers)
+ assert _asked(adapter) == asked
+ assert reply == payload
assert adapter.resumed == resumed
- if payload["timed_out"]:
+ if payload["outcome"] == "timed_out":
assert len(adapter.retired) == 1 # the card that expired is retired
@@ -148,20 +152,20 @@ class _UndeliverableAdapter(_CardAdapter):
return SendResult(success=False, error="Bad Request: chat not found")
[email protected]("adapter_cls,notice", [
- (_CardAdapter, "[user did not respond within 0m]"),
- # #112684: an undelivered card must not read as user inactivity — the delivery
- # sentinel rides along instead of being stored as the question's "answer".
- (_UndeliverableAdapter, "[clarify prompt could not be delivered]"),
[email protected]("adapter_cls,outcome,notice", [
+ (_CardAdapter, "timed_out", "[user did not respond within 0m]"),
+ # #112684: an undelivered card must not read as user inactivity — the outcome says
+ # undelivered and the delivery notice rides along.
+ (_UndeliverableAdapter, "undelivered", "[clarify prompt could not be delivered]"),
])
-def test_clarify_tool_batch_route_answers_and_stops_together(adapter_cls, notice):
- """End to end: the tool sees blank answers + ``timed_out`` + the surface's notice, where the
- legacy loop stored the sentinel as each question's answer and never set the flag."""
+def test_clarify_tool_batch_route_answers_and_stops_together(adapter_cls, outcome, notice):
+ """End to end: the tool sees unanswered questions + the outcome + the surface's notice."""
adapter = adapter_cls()
raw, _labels = _run_clarify(
adapter, questions=_THREE_QUESTIONS[:2], via_tool=True)
- assert adapter.asked == ["One?"]
+ assert _asked(adapter) == ["One?"]
result = json.loads(raw)
- assert result["timed_out"] is True
+ assert result["outcome"] == outcome
assert result["notice"] == notice
- assert [r["user_response"] for r in result["responses"]] == ["", ""]
+ assert [r["status"] for r in result["responses"]] == ["unanswered", "unanswered"]
+ assert [r["user_response"] for r in result["responses"]] == [None, None]
diff --git a/tests/gateway/test_clarify_delivery_fallback.py b/tests/gateway/test_clarify_delivery_fallback.py
index 62d5400225c..0e1816260a0 100644
--- a/tests/gateway/test_clarify_delivery_fallback.py
+++ b/tests/gateway/test_clarify_delivery_fallback.py
@@ -18,6 +18,7 @@ from gateway.platforms.base import BasePlatformAdapter, SendResult
from tools import clarify_gateway as cm
UNDELIVERED = "[clarify prompt could not be delivered" # prefix shared by every delivery notice
+PICK = [{"qid": "q0", "question": "Pick?", "choices": ["alpha", "beta"], "multi_select": False}]
class _CardAdapter(BasePlatformAdapter):
@@ -95,8 +96,8 @@ def test_rejected_card_is_reasked_as_plain_text_and_the_typed_answer_counts(loop
adapter = _CardAdapter(rejected)
_answer_once_text_prompt_is_seen(adapter, "2")
- response = _runner(adapter, loop, monkeypatch)._clarify_callback_sync("Pick?", ["alpha", "beta"])
- assert response == "beta" # the numbered text prompt maps "2" back to the choice
+ reply = _runner(adapter, loop, monkeypatch)._clarify_callback_sync(PICK)
+ assert reply == {"answers": {"q0": "beta"}, "outcome": "submitted"} # the numbered text prompt maps "2" back to the choice
assert adapter.cards == 1
assert len(adapter.sent_text) == 1 and "1. alpha" in adapter.sent_text[0]
@@ -108,8 +109,9 @@ def test_declined_card_is_never_reasked_as_text(loop, monkeypatch):
return SendResult(success=False, error="egress declined: destination not allowed")
adapter = _CardAdapter(declined)
- response = _runner(adapter, loop, monkeypatch)._clarify_callback_sync("Pick?", ["alpha", "beta"])
- assert response.startswith(UNDELIVERED)
+ reply = _runner(adapter, loop, monkeypatch)._clarify_callback_sync(PICK)
+ assert reply["outcome"] == "undelivered"
+ assert reply["notice"].startswith(UNDELIVERED)
assert adapter.sent_text == []
@@ -128,9 +130,9 @@ def test_card_failing_after_the_ack_window_falls_back_to_text_instead_of_waiting
adapter = _CardAdapter(late_failure)
_answer_once_text_prompt_is_seen(adapter, "beta")
started = time.monotonic()
- response = _runner(adapter, loop, monkeypatch, timeout=30)._clarify_callback_sync("Pick?", ["alpha", "beta"])
+ reply = _runner(adapter, loop, monkeypatch, timeout=30)._clarify_callback_sync(PICK)
elapsed = time.monotonic() - started
- assert response == "beta"
+ assert reply["answers"] == {"q0": "beta"}
assert len(adapter.sent_text) == 1 # the plain-text prompt was actually sent, once
assert elapsed < 0.2 + 2 # released right after the ack window + late failure, never clarify_timeout
@@ -218,8 +220,7 @@ def test_card_declined_after_the_ack_window_releases_with_the_declined_notice(lo
def test_no_status_adapter_reports_the_missing_surface_not_inactivity(loop, monkeypatch):
runner = _runner(None, loop, monkeypatch)
- payload = json.loads(runner._clarify_callback_sync(
- "", None, questions=[{"qid": "q0", "question": "One?", "choices": ["a"]}]))
- assert payload["timed_out"] is True
- assert payload["notice"].startswith(UNDELIVERED)
- assert runner._clarify_callback_sync("One?", ["a"]).startswith(UNDELIVERED)
+ reply = runner._clarify_callback_sync(
+ [{"qid": "q0", "question": "One?", "choices": ["a"], "multi_select": False}])
+ assert reply["outcome"] == "undelivered"
+ assert reply["notice"].startswith(UNDELIVERED)
diff --git a/tests/gateway/test_clarify_thread_followup_not_swallowed.py b/tests/gateway/test_clarify_thread_followup_not_swallowed.py
index 1ca05e90e13..b319b415136 100644
--- a/tests/gateway/test_clarify_thread_followup_not_swallowed.py
+++ b/tests/gateway/test_clarify_thread_followup_not_swallowed.py
@@ -139,7 +139,7 @@ async def test_thread_prose_not_swallowed_by_native_multi_choice_clarify():
entry = cm._entries.get("cl-native")
assert entry is not None
assert entry.event.is_set()
- assert entry.response == ""
+ assert entry.response == cm.CANCELLED
_clear_clarify_state()
@@ -284,7 +284,7 @@ async def test_native_multi_select_prose_releases_clarify_before_routing():
entry = cm._entries.get("cl-ms-prose")
assert entry is not None
assert entry.event.is_set()
- assert entry.response == ""
+ assert entry.response == cm.CANCELLED
_clear_clarify_state()
diff --git a/tests/hermes_cli/test_cli_approval_ui.py b/tests/hermes_cli/test_cli_approval_ui.py
index 92ae1deb7ef..feec4091d65 100644
--- a/tests/hermes_cli/test_cli_approval_ui.py
+++ b/tests/hermes_cli/test_cli_approval_ui.py
@@ -457,7 +457,9 @@ class TestPersistPromptSummary:
result = {}
def _run():
- result["value"] = cli._clarify_callback("Pick a path?", ["A", "B"])
+ result["value"] = cli._clarify_callback([{
+ "qid": "q0", "question": "Pick a path?", "choices": ["A", "B"],
+ "choices_offered": ["A", "B"], "multi_select": False}])
with patch.object(cli_module, "_cprint", printed.append):
t = threading.Thread(target=_run, daemon=True)
@@ -465,10 +467,10 @@ class TestPersistPromptSummary:
deadline = time.time() + 2
while cli._clarify_state is None and time.time() < deadline:
time.sleep(0.01)
- cli._clarify_state["response_queue"].put("B")
+ cli._clarify_batch_lock(cli._clarify_state, "B")
t.join(timeout=2)
- assert result["value"] == "B"
+ assert result["value"] == {"answers": {"q0": "B"}, "outcome": "submitted"}
summary = "\n".join(printed)
assert "Clarify" in summary
assert "Pick a path?" in summary
@@ -515,7 +517,7 @@ class TestClearOverlaysForInterrupt:
# Each blocked thread would have received a terminal value.
assert approval_q.get_nowait() == "deny"
- assert clarify_q.get_nowait() # cancellation sentinel string
+ assert clarify_q.get_nowait() is None
assert sudo_q.get_nowait() == ""
assert secret_q.get_nowait() == ""
@@ -537,7 +539,7 @@ class TestClearOverlaysForInterrupt:
assert cli._approval_state is None # cleared despite dead queue
assert cli._clarify_state is None
- assert clarify_q.get_nowait()
+ assert clarify_q.get_nowait() is None
def test_interrupt_unblocks_thread_blocked_on_approval(self):
"""End-to-end: a worker blocked on the approval queue unblocks when the
diff --git a/tests/hermes_cli/test_cli_clarify_batch.py b/tests/hermes_cli/test_cli_clarify_batch.py
index b3c465db8e9..8a7d35764a0 100644
--- a/tests/hermes_cli/test_cli_clarify_batch.py
+++ b/tests/hermes_cli/test_cli_clarify_batch.py
@@ -33,7 +33,6 @@ def _q(index, question, choices=None, multi_select=False):
"""One normalized batch entry, shaped like _normalize_questions output."""
return {
"qid": f"q{index}",
- "id": None,
"question": question,
"choices": list(choices) if choices else None,
"choices_offered": list(choices) if choices else None,
@@ -46,7 +45,7 @@ def _start_batch(cli, questions):
result = {}
def _run():
- result["value"] = cli._clarify_callback("", None, questions=questions)
+ result["value"] = cli._clarify_callback(questions)
thread = threading.Thread(target=_run, daemon=True)
thread.start()
@@ -81,7 +80,7 @@ class TestClarifyBatchPanel:
cli._clarify_batch_enter(state)
thread.join(timeout=2)
- assert result["value"] == {"answers": {"q0": "red", "q1": "large"}}
+ assert result["value"] == {"answers": {"q0": "red", "q1": "large"}, "outcome": "submitted"}
assert cli._clarify_state is None
def test_any_order_answering_via_tab_cycle(self):
@@ -111,7 +110,7 @@ class TestClarifyBatchPanel:
thread.join(timeout=2)
assert result["value"] == {
- "answers": {"q0": "b", "q1": "c", "q2": "e"}
+ "answers": {"q0": "b", "q1": "c", "q2": "e"}, "outcome": "submitted"
}
def test_reanswer_overwrites_before_completion(self):
@@ -139,10 +138,10 @@ class TestClarifyBatchPanel:
thread.join(timeout=2)
assert result["value"] == {
- "answers": {"q0": "thorough", "q1": "narrow"}
+ "answers": {"q0": "thorough", "q1": "narrow"}, "outcome": "submitted"
}
- def test_timeout_returns_partials_with_timed_out_flag(self):
+ def test_timeout_returns_partials_with_timed_out_outcome(self):
cli = _make_cli_stub()
questions = [
_q(0, "Answered?", ["yes", "no"]),
@@ -157,7 +156,7 @@ class TestClarifyBatchPanel:
thread.join(timeout=5)
assert not thread.is_alive()
- assert result["value"] == {"answers": {"q0": "yes"}, "timed_out": True}
+ assert result["value"] == {"answers": {"q0": "yes"}, "outcome": "timed_out"}
assert cli._clarify_state is None
def test_multi_select_lock_produces_json_array_string(self):
@@ -197,7 +196,7 @@ class TestClarifyBatchPanel:
thread.join(timeout=2)
assert result["value"] == {
- "answers": {"q0": "custom words", "q1": "a"}
+ "answers": {"q0": "custom words", "q1": "a"}, "outcome": "submitted"
}
def test_locked_question_persists_scrollback_summary(self):
@@ -218,26 +217,8 @@ class TestClarifyBatchPanel:
assert calls[0].args == ("?", "Clarify", "Color?", "red")
assert calls[1].args == ("?", "Clarify", "Size?", "small")
- def test_single_question_path_returns_plain_string(self):
+ def test_connection_callback_masks_secret_and_submits_env(self):
cli = _make_cli_stub()
- result = {}
-
- def _run():
- result["value"] = cli._clarify_callback("Pick?", ["a", "b"])
-
- thread = threading.Thread(target=_run, daemon=True)
- thread.start()
-
- deadline = time.time() + 2
- while cli._clarify_state is None and time.time() < deadline:
- time.sleep(0.01)
- assert cli._clarify_state is not None
- assert "questions" not in cli._clarify_state
-
- cli._clarify_state["response_queue"].put("a")
- thread.join(timeout=2)
- assert result["value"] == "a"
-
cli._connection_state = None
cli._capture_modal_input_snapshot = MagicMock()
cli._restore_modal_input_snapshot = MagicMock()
@@ -301,7 +282,7 @@ class TestClarifyBatchNavigation:
cli._clarify_batch_set_active(state, (state["active"] - 1) % 3)
assert state["active"] == 1
- state["response_queue"].put("cancel")
+ state["response_queue"].put(None)
thread.join(timeout=2)
def test_revisit_choice_answer_restores_cursor(self):
@@ -322,7 +303,7 @@ class TestClarifyBatchNavigation:
cli._clarify_batch_set_active(state, 0)
assert state["selected"] == 1
- state["response_queue"].put("cancel")
+ state["response_queue"].put(None)
thread.join(timeout=2)
def test_revisit_other_answer_highlights_other_and_prefills_edit(self):
@@ -355,7 +336,7 @@ class TestClarifyBatchNavigation:
assert cli._clarify_freetext is True
assert cli._clarify_prefill == "chartreuse"
- state["response_queue"].put("cancel")
+ state["response_queue"].put(None)
thread.join(timeout=2)
def test_reanswer_overwrites_and_updates_meta(self):
@@ -383,7 +364,7 @@ class TestClarifyBatchNavigation:
cli._clarify_batch_set_active(state, 1)
cli._clarify_batch_enter(state)
thread.join(timeout=2)
- assert result["value"] == {"answers": {"q0": "red", "q1": "small"}}
+ assert result["value"] == {"answers": {"q0": "red", "q1": "small"}, "outcome": "submitted"}
@@ -401,14 +382,14 @@ class TestClarifyBellOnPrompt:
"tools.clarify_gateway.resolve_clarify_timeout", return_value=60
):
thread = threading.Thread(
- target=cli._clarify_callback, args=("Color?", ["red", "blue"]), daemon=True
+ target=cli._clarify_callback, args=([_q(0, "Color?", ["red", "blue"])],), daemon=True
)
thread.start()
deadline = time.time() + 2
while cli._clarify_state is None and time.time() < deadline:
time.sleep(0.01)
assert cli._clarify_state is not None
- cli._clarify_state["response_queue"].put("red")
+ cli._clarify_state["response_queue"].put(None)
thread.join(timeout=2)
return out.getvalue()
diff --git a/tests/hermes_cli/test_single_query_clarify.py b/tests/hermes_cli/test_single_query_clarify.py
index 3dddcd44283..ff71bc8cbe7 100644
--- a/tests/hermes_cli/test_single_query_clarify.py
+++ b/tests/hermes_cli/test_single_query_clarify.py
@@ -14,9 +14,12 @@ construction site that already knows it is in single-query mode.
from __future__ import annotations
-def test_no_choices_returns_immediate_headless_answer():
+def test_returns_immediate_undelivered_reply():
from hermes_cli.cli_agent_setup_mixin import _single_query_clarify_callback
- result = _single_query_clarify_callback("Which timezone should I use?")
- assert result.startswith("[single-query mode: no user available")
- assert "most reasonable assumption" in result
+ result = _single_query_clarify_callback([{
+ "qid": "q0", "question": "Which timezone should I use?", "choices": None,
+ "choices_offered": None, "multi_select": False}])
+ assert result["answers"] == {}
+ assert result["outcome"] == "undelivered"
+ assert "no user available" in result["notice"]
diff --git a/tests/tools/test_clarify_gateway.py b/tests/tools/test_clarify_gateway.py
index 5a92a1a53aa..a73e4e2017f 100644
--- a/tests/tools/test_clarify_gateway.py
+++ b/tests/tools/test_clarify_gateway.py
@@ -77,7 +77,7 @@ class TestClarifyPrimitive:
def test_clear_session_cancels_pending_entries(self):
- """clear_session unblocks blocked threads with empty response."""
+ """clear_session unblocks blocked threads."""
from tools import clarify_gateway as cm
cm.register("id7", "sk7", "Q?", ["A"])
@@ -91,8 +91,7 @@ class TestClarifyPrimitive:
cancelled = cm.clear_session("sk7")
assert cancelled == 1
result = fut.result(timeout=10.0)
- # clear_session sets response="" then the wait returns it
- assert result == ""
+ assert result == cm.CANCELLED
def test_clear_session_preserves_resolved_response(self):
diff --git a/tests/tools/test_clarify_tool.py b/tests/tools/test_clarify_tool.py
index bcd4d2208fe..850dc74d84e 100644
--- a/tests/tools/test_clarify_tool.py
+++ b/tests/tools/test_clarify_tool.py
@@ -1,39 +1,46 @@
"""Tests for tools/clarify_tool.py - Interactive clarifying questions."""
import json
-from typing import List, Optional
-
from tools.clarify_tool import (
clarify_tool,
MAX_CHOICES,
MAX_QUESTIONS,
CLARIFY_SCHEMA,
- _flatten_choice,
)
+def _ask(callback, questions):
+ return json.loads(clarify_tool(questions, callback=callback))
+
+
+def _reply(answers, outcome="submitted", **extra):
+ return {"answers": answers, "outcome": outcome, **extra}
+
+
class TestClarifyToolBasics:
"""Basic functionality tests for clarify_tool."""
def test_simple_question_with_callback(self):
"""Should return user response for simple question."""
- def mock_callback(question: str, choices: Optional[List[str]]) -> str:
- assert question == "What color?"
- assert choices is None
- return "blue"
-
- result = json.loads(clarify_tool("What color?", callback=mock_callback))
- assert result["question"] == "What color?"
- assert result["choices_offered"] is None
- assert result["user_response"] == "blue"
-
+ def mock_callback(questions):
+ assert questions[0]["question"] == "What color?"
+ assert questions[0]["choices"] is None
+ return _reply({"q0": "blue"})
+
+ result = _ask(mock_callback, [{"question": "What color?"}])
+ response = result["responses"][0]
+ assert response["question"] == "What color?"
+ assert response["choices_offered"] is None
+ assert response["status"] == "answered"
+ assert response["user_response"] == "blue"
+ assert result["outcome"] == "submitted"
def test_no_callback_returns_error(self):
"""Should return error when no callback is provided."""
- result = json.loads(clarify_tool("What do you want?"))
+ result = json.loads(clarify_tool([{"question": "What do you want?"}]))
assert "error" in result
- assert "user_response" not in result
+ assert "responses" not in result
class TestClarifyToolChoicesValidation:
@@ -43,148 +50,79 @@ class TestClarifyToolChoicesValidation:
"""Should trim choices to MAX_CHOICES."""
choices_passed = []
- def mock_callback(question: str, choices: Optional[List[str]]) -> str:
- choices_passed.extend(choices or [])
- return "picked"
+ def mock_callback(questions):
+ choices_passed.extend(questions[0]["choices"] or [])
+ return _reply({"q0": "picked"})
many_choices = ["a", "b", "c", "d", "e", "f", "g"]
- clarify_tool("Pick one", choices=many_choices, callback=mock_callback)
+ _ask(mock_callback, [{"question": "Pick one", "choices": many_choices}])
assert len(choices_passed) == MAX_CHOICES
- def test_choices_converted_to_strings(self):
- """Non-string choices should be converted to strings."""
- choices_received = []
-
- def mock_callback(question: str, choices: Optional[List[str]]) -> str:
- choices_received.extend(choices or [])
- return "answer"
-
- clarify_tool("Pick", choices=[1, 2, 3], callback=mock_callback) # type: ignore
- assert choices_received == ["1 (Recommended)", "2", "3"]
-
-
class TestClarifyToolCallbackHandling:
"""Tests for callback error handling."""
def test_callback_exception_returns_error(self):
"""Should return error if callback raises exception."""
- def failing_callback(question: str, choices: Optional[List[str]]) -> str:
+ def failing_callback(questions):
raise RuntimeError("User cancelled")
- result = json.loads(clarify_tool("Question?", callback=failing_callback))
+ result = _ask(failing_callback, [{"question": "Question?"}])
assert "error" in result
assert "User cancelled" in result["error"]
-
def test_user_response_stripped(self):
"""User response should be stripped of whitespace."""
- def mock_callback(question: str, choices: Optional[List[str]]) -> str:
- return " response with spaces \n"
-
- result = json.loads(clarify_tool("Q?", callback=mock_callback))
- assert result["user_response"] == "response with spaces"
-
-
-
-
-class TestClarifyDictChoices:
- """Dict-shaped choices must be unwrapped to user-facing text at the source.
-
- LLMs sometimes emit [{"description": "..."}] instead of bare strings. The
- naive str(c) coercion leaked the Python dict repr onto every surface (CLI
- panel, Discord buttons, Telegram list) AND returned it verbatim as the
- user's answer. _flatten_choice normalises at the one platform-agnostic
- entry point so the whole class is fixed in one place.
- """
-
- def test_flatten_unwraps_label_first(self):
- assert _flatten_choice({"label": "Short", "description": "Long"}) == "Short"
-
-
- def test_dict_choices_reach_callback_as_clean_text(self):
- """The whole point: the UI callback never sees a dict repr."""
- seen = []
+ def mock_callback(questions):
+ return _reply({"q0": " response with spaces \n"})
- def cb(question, choices):
- seen.extend(choices or [])
- return choices[0]
-
- result = json.loads(clarify_tool(
- "Pick a layout",
- choices=[
- {"choice": "Tight", "description": "Tight, covers all 3 points"},
- {"description": "Loose layout"},
- {"name": "modelid", "value": "abc"}, # dropped, not leaked
- "A plain string choice",
- ],
- callback=cb,
- )) # type: ignore
- assert seen == [
- "Tight, covers all 3 points (Recommended)",
- "Loose layout",
- "A plain string choice",
- ]
- # and the resolved answer is clean text, not a dict repr
- assert result["user_response"] == "Tight, covers all 3 points"
- assert "{" not in result["user_response"]
- assert all("{" not in c for c in result["choices_offered"])
+ result = _ask(mock_callback, [{"question": "Q?"}])
+ assert result["responses"][0]["user_response"] == "response with spaces"
class TestClarifySchema:
"""Tests for the OpenAI function-calling schema."""
-
-
-
-
-
-
-
-
def test_schema_questions_param_is_required_and_capped(self):
"""`questions` is the single documented way to call (a single question
is a one-entry array) and carries the batch cap so the model sees the
- limit. The legacy top-level `question` shape stays handler-accepted
- but unadvertised."""
+ limit."""
params = CLARIFY_SCHEMA["parameters"]
+ assert params["required"] == ["questions"]
assert params["properties"]["questions"]["maxItems"] == MAX_QUESTIONS
class TestClarifyToolMultiSelect:
"""Tests for multi_select (checkbox) support added to clarify_tool."""
-
def test_multi_select_true_returns_list(self):
"""When multi_select=True, user_response should be a list of strings."""
- def mock_callback(question, choices):
- return "red, blue"
-
- result = json.loads(clarify_tool(
- "Which colors?",
- choices=["red", "blue", "green"],
- multi_select=True,
- callback=mock_callback,
- ))
- assert result["user_response"] == ["red", "blue"]
- assert isinstance(result["user_response"], list)
+ def mock_callback(questions):
+ return _reply({"q0": ["red", "blue"]})
+
+ result = _ask(mock_callback, [{
+ "question": "Which colors?",
+ "choices": ["red", "blue", "green"],
+ "multi_select": True,
+ }])
+ response = result["responses"][0]
+ assert response["user_response"] == ["red", "blue"]
+ assert isinstance(response["user_response"], list)
def test_multi_select_single_choice_still_list(self):
"""Even a single selection should be a list when multi_select=True."""
- def mock_callback(question, choices):
- return "red"
-
- result = json.loads(clarify_tool(
- "Which color?",
- choices=["red", "blue"],
- multi_select=True,
- callback=mock_callback,
- ))
- assert result["user_response"] == ["red"]
- assert isinstance(result["user_response"], list)
-
+ def mock_callback(questions):
+ return _reply({"q0": '["red"]'})
+ result = _ask(mock_callback, [{
+ "question": "Which color?",
+ "choices": ["red", "blue"],
+ "multi_select": True,
+ }])
+ response = result["responses"][0]
+ assert response["user_response"] == ["red"]
+ assert isinstance(response["user_response"], list)
class TestClarifyRecommendedLabel:
@@ -199,96 +137,65 @@ class TestClarifyRecommendedLabel:
def test_first_choice_is_labelled(self):
seen = []
- def cb(question, choices):
- seen.extend(choices or [])
- return choices[1]
+ def cb(questions):
+ seen.extend(questions[0]["choices"] or [])
+ return _reply({"q0": seen[1]})
- clarify_tool("Pick", choices=["Rebase", "Merge"], callback=cb)
+ _ask(cb, [{"question": "Pick", "choices": ["Rebase", "Merge"]}])
assert seen == ["Rebase (Recommended)", "Merge"]
def test_answer_strips_the_label(self):
"""Picking the recommended option returns the bare option text."""
- def cb(question, choices):
- return choices[0]
+ def cb(questions):
+ return _reply({"q0": questions[0]["choices"][0]})
- result = json.loads(clarify_tool("Pick", choices=["Rebase", "Merge"], callback=cb))
- assert result["user_response"] == "Rebase"
- assert result["choices_offered"] == ["Rebase", "Merge"]
+ result = _ask(cb, [{"question": "Pick", "choices": ["Rebase", "Merge"]}])
+ response = result["responses"][0]
+ assert response["user_response"] == "Rebase"
+ assert response["choices_offered"] == ["Rebase", "Merge"]
def test_multi_select_answers_strip_the_label(self):
- def cb(question, choices, multi_select=False):
- return ", ".join(choices[:2])
+ def cb(questions):
+ return _reply({"q0": questions[0]["choices"][:2]})
- result = json.loads(clarify_tool(
- "Pick some",
- choices=["Rebase", "Merge", "Squash"],
- multi_select=True,
- callback=cb,
- ))
- assert result["user_response"] == ["Rebase", "Merge"]
+ result = _ask(cb, [{
+ "question": "Pick some",
+ "choices": ["Rebase", "Merge", "Squash"],
+ "multi_select": True,
+ }])
+ assert result["responses"][0]["user_response"] == ["Rebase", "Merge"]
def test_single_choice_is_not_labelled(self):
"""One option isn't a recommendation — there's nothing to prefer it over."""
seen = []
- def cb(question, choices):
- seen.extend(choices or [])
- return choices[0]
+ def cb(questions):
+ seen.extend(questions[0]["choices"] or [])
+ return _reply({"q0": seen[0]})
- clarify_tool("Confirm", choices=["Ship it"], callback=cb)
+ _ask(cb, [{"question": "Confirm", "choices": ["Ship it"]}])
assert seen == ["Ship it"]
def test_label_is_not_doubled(self):
"""A model that wrote its own label doesn't get a second one."""
seen = []
- def cb(question, choices):
- seen.extend(choices or [])
- return choices[0]
+ def cb(questions):
+ seen.extend(questions[0]["choices"] or [])
+ return _reply({"q0": seen[0]})
- clarify_tool("Pick", choices=["Rebase (recommended)", "Merge"], callback=cb)
+ _ask(cb, [{"question": "Pick", "choices": ["Rebase (recommended)", "Merge"]}])
assert seen == ["Rebase (recommended)", "Merge"]
def test_open_ended_unaffected(self):
- def cb(question, choices):
- assert choices is None
- return "whatever"
-
- result = json.loads(clarify_tool("Thoughts?", callback=cb))
- assert result["choices_offered"] is None
- assert result["user_response"] == "whatever"
-
-
-class TestInvokeCallbackDispatch:
- """_invoke_callback uses signature inspection, never a TypeError retry."""
-
- def test_internal_typeerror_not_swallowed_or_retried(self):
- """A compatible callback that raises TypeError internally must be
- invoked exactly once and its error surfaced — not retried with the
- legacy 2-arg form (which would prompt the user twice)."""
- from tools.clarify_tool import _invoke_callback
- calls = []
-
- def bad_callback(question, choices, multi_select=False):
- calls.append(1)
- raise TypeError("internal bug")
-
- import pytest
- with pytest.raises(TypeError, match="internal bug"):
- _invoke_callback(bad_callback, "Q?", ["a"], True)
- assert len(calls) == 1
-
+ def cb(questions):
+ assert questions[0]["choices"] is None
+ return _reply({"q0": "whatever"})
- def test_var_keyword_callback_receives_flag(self):
- from tools.clarify_tool import _invoke_callback
- seen = {}
-
- def kw_cb(question, choices, **kwargs):
- seen.update(kwargs)
- return "ok"
-
- _invoke_callback(kw_cb, "Q?", ["a"], True)
- assert seen.get("multi_select") is True
+ result = _ask(cb, [{"question": "Thoughts?"}])
+ response = result["responses"][0]
+ assert response["choices_offered"] is None
+ assert response["user_response"] == "whatever"
class TestRegistryMultiSelectPassThrough:
@@ -299,291 +206,136 @@ class TestRegistryMultiSelectPassThrough:
entry = registry.get_entry("clarify")
seen = {}
- def cb(question, choices, multi_select=False):
- seen["multi"] = multi_select
- return "a, b"
+ def cb(questions):
+ seen["multi"] = questions[0]["multi_select"]
+ return _reply({"q0": ["a", "b"]})
result = json.loads(entry.handler(
- {"question": "Pick", "choices": ["a", "b"], "multi_select": True},
+ {"questions": [{"question": "Pick", "choices": ["a", "b"], "multi_select": True}]},
callback=cb,
))
assert seen["multi"] is True
- assert result["user_response"] == ["a", "b"]
+ assert result["responses"][0]["user_response"] == ["a", "b"]
def test_handler_default_single_select(self):
from tools.registry import registry
entry = registry.get_entry("clarify")
seen = {}
- def cb(question, choices, multi_select=False):
- seen["multi"] = multi_select
- return "a"
+ def cb(questions):
+ seen["multi"] = questions[0]["multi_select"]
+ return _reply({"q0": "a"})
result = json.loads(entry.handler(
- {"question": "Pick", "choices": ["a", "b"]},
+ {"questions": [{"question": "Pick", "choices": ["a", "b"]}]},
callback=cb,
))
assert seen["multi"] is False
- assert result["user_response"] == "a"
+ assert result["responses"][0]["user_response"] == "a"
class TestClarifyBatchValidation:
"""Validation of the `questions` batch parameter (issue #18450)."""
- def test_batch_takes_precedence_over_question(self):
- """When both are present, `questions` wins and `question` is ignored."""
- seen = {}
-
- def cb(question, choices, multi_select=False, questions=None):
- seen["questions"] = questions
- return {"answers": {"q0": "blue"}}
-
- result = json.loads(clarify_tool(
- "ignored single question",
- questions=[{"question": "What color?"}],
- callback=cb,
- ))
- assert "responses" in result
- assert len(result["responses"]) == 1
- assert result["responses"][0]["question"] == "What color?"
- assert seen["questions"][0]["question"] == "What color?"
-
def test_batch_rejects_more_than_five(self):
- result = json.loads(clarify_tool(
- "",
- questions=[{"question": f"Q{i}?"} for i in range(6)],
- callback=lambda *a, **k: "",
- ))
+ result = _ask(lambda questions: _reply({}), [{"question": f"Q{i}?"} for i in range(6)])
assert "error" in result
def test_batch_rejects_blank_question_text(self):
- result = json.loads(clarify_tool(
- "",
- questions=[{"question": "Real?"}, {"question": " "}],
- callback=lambda *a, **k: "",
- ))
+ result = _ask(lambda questions: _reply({}), [{"question": "Real?"}, {"question": " "}])
assert "error" in result
def test_batch_rejects_non_list(self):
- result = json.loads(clarify_tool(
- "", questions={"question": "Q?"}, callback=lambda *a, **k: "",
- ))
+ result = _ask(lambda questions: _reply({}), {"question": "Q?"})
assert "error" in result
- def test_batch_empty_list_falls_back_to_single_question(self):
- """An empty questions array degrades to the single-question path."""
- def cb(question, choices):
- assert question == "Single?"
- return "yes"
-
- result = json.loads(clarify_tool("Single?", questions=[], callback=cb))
- assert result["user_response"] == "yes"
- assert "responses" not in result
-
- def test_batch_choices_flattened_capped_and_labelled_per_question(self):
- """Each question gets the full choice pipeline: flatten, cap, label."""
+ def test_batch_choices_capped_and_labelled_per_question(self):
+ """Each question gets the full choice pipeline: cap, label."""
seen = {}
- def cb(question, choices, multi_select=False, questions=None):
+ def cb(questions):
seen["questions"] = questions
- return {"answers": {"q0": "a", "q1": "Loose layout"}}
-
- clarify_tool(
- "",
- questions=[
- {"question": "Pick letter", "choices": ["a", "b", "c", "d", "e", "f"]},
- {"question": "Pick layout", "choices": [
- {"description": "Loose layout"}, "Tight",
- ]},
- ],
- callback=cb,
- )
+ return _reply({"q0": "a", "q1": "Loose layout"})
+
+ _ask(cb, [
+ {"question": "Pick letter", "choices": ["a", "b", "c", "d", "e", "f"]},
+ {"question": "Pick layout", "choices": ["Loose layout", "Tight"]},
+ ])
q0, q1 = seen["questions"]
assert len(q0["choices"]) == MAX_CHOICES
assert q0["choices"][0] == "a (Recommended)"
assert q1["choices"] == ["Loose layout (Recommended)", "Tight"]
- def test_batch_internal_ids_are_stable_and_model_id_echoed(self):
- """Wire ids are q0..qN. A model-supplied id only shows in results."""
+ def test_batch_internal_ids_are_stable(self):
+ """Wire ids are q0..qN."""
seen = {}
- def cb(question, choices, multi_select=False, questions=None):
+ def cb(questions):
seen["questions"] = questions
- return {"answers": {"q0": "A", "q1": "B"}}
-
- result = json.loads(clarify_tool(
- "",
- questions=[
- {"id": "approach", "question": "Which approach?"},
- {"question": "Timeline?"},
- ],
- callback=cb,
- ))
+ return _reply({"q0": "A", "q1": "B"})
+
+ _ask(cb, [{"question": "Which approach?"}, {"question": "Timeline?"}])
assert [q["qid"] for q in seen["questions"]] == ["q0", "q1"]
- assert result["responses"][0]["id"] == "approach"
- assert "id" not in result["responses"][1]
def test_batch_multi_select_needs_choices(self):
"""multi_select is only honored when the question has choices."""
seen = {}
- def cb(question, choices, multi_select=False, questions=None):
+ def cb(questions):
seen["questions"] = questions
- return {"answers": {"q0": "free text"}}
+ return _reply({"q0": "free text"})
- clarify_tool(
- "",
- questions=[{"question": "Thoughts?", "multi_select": True}],
- callback=cb,
- )
+ _ask(cb, [{"question": "Thoughts?", "multi_select": True}])
assert seen["questions"][0]["multi_select"] is False
class TestClarifyBatchDispatch:
- """Batch-capable callbacks get the list once. Legacy callbacks loop."""
+ """The callback gets the list once and answers by qid."""
def test_batch_callback_receives_list_once(self):
calls = []
- def cb(question, choices, multi_select=False, questions=None):
+ def cb(questions):
calls.append(questions)
- return {"answers": {"q0": "x", "q1": "y"}}
+ return _reply({"q0": "x", "q1": "y"})
- result = json.loads(clarify_tool(
- "",
- questions=[{"question": "One?"}, {"question": "Two?"}],
- callback=cb,
- ))
+ result = _ask(cb, [{"question": "One?"}, {"question": "Two?"}])
assert len(calls) == 1
assert [r["user_response"] for r in result["responses"]] == ["x", "y"]
- def test_batch_callback_json_string_response(self):
- """A _block-style bridge returns the answers as a JSON string."""
- def cb(question, choices, multi_select=False, questions=None):
- return json.dumps({"answers": {"q0": "picked"}})
-
- result = json.loads(clarify_tool(
- "", questions=[{"question": "One?"}], callback=cb,
- ))
- assert result["responses"][0]["user_response"] == "picked"
-
- def test_batch_recommended_label_stripped_per_question(self):
- def cb(question, choices, multi_select=False, questions=None):
- return {"answers": {"q0": questions[0]["choices"][0]}}
-
- result = json.loads(clarify_tool(
- "",
- questions=[{"question": "Pick", "choices": ["Rebase", "Merge"]}],
- callback=cb,
- ))
- assert result["responses"][0]["user_response"] == "Rebase"
- assert result["responses"][0]["choices_offered"] == ["Rebase", "Merge"]
-
def test_batch_multi_select_answer_parsed_to_list(self):
- def cb(question, choices, multi_select=False, questions=None):
- return {"answers": {"q0": '["red", "blue"]'}}
-
- result = json.loads(clarify_tool(
- "",
- questions=[{
- "question": "Colors?",
- "choices": ["red", "blue", "green"],
- "multi_select": True,
- }],
- callback=cb,
- ))
+ def cb(questions):
+ return _reply({"q0": '["red", "blue"]'})
+
+ result = _ask(cb, [{
+ "question": "Colors?",
+ "choices": ["red", "blue", "green"],
+ "multi_select": True,
+ }])
assert result["responses"][0]["user_response"] == ["red", "blue"]
- def test_batch_timed_out_flag_passthrough_with_partials(self):
- """Timeout keeps the locked answers and sets the top-level flag."""
- def cb(question, choices, multi_select=False, questions=None):
- return {"answers": {"q0": "kept"}, "timed_out": True}
+ def test_batch_timed_out_keeps_partials(self):
+ """Timeout keeps the locked answers and marks the rest unanswered."""
+ def cb(questions):
+ return _reply({"q0": "kept"}, outcome="timed_out", notice="no reply")
- result = json.loads(clarify_tool(
- "",
- questions=[{"question": "One?"}, {"question": "Two?"}],
- callback=cb,
- ))
- assert result["timed_out"] is True
+ result = _ask(cb, [{"question": "One?"}, {"question": "Two?"}])
+ assert result["outcome"] == "timed_out"
+ assert result["notice"] == "no reply"
+ assert result["responses"][0]["status"] == "answered"
assert result["responses"][0]["user_response"] == "kept"
- assert result["responses"][1]["user_response"] == ""
-
- def test_batch_empty_response_is_skip_not_timeout(self):
- """A cancel-all resolves every answer empty with no timed_out flag."""
- def cb(question, choices, multi_select=False, questions=None):
- return ""
+ assert result["responses"][1]["status"] == "unanswered"
+ assert result["responses"][1]["user_response"] is None
- result = json.loads(clarify_tool(
- "", questions=[{"question": "One?"}], callback=cb,
- ))
- assert result["responses"][0]["user_response"] == ""
- assert "timed_out" not in result
-
- def test_legacy_callback_gets_sequential_calls_in_order(self):
- """A callback without `questions` support is looped per question."""
- calls = []
-
- def legacy_cb(question, choices, multi_select=False):
- calls.append((question, tuple(choices or []) or None, multi_select))
- return f"answer to {question}"
-
- result = json.loads(clarify_tool(
- "",
- questions=[
- {"question": "One?", "choices": ["a", "b"]},
- {"question": "Two?"},
- ],
- callback=legacy_cb,
- ))
- assert [c[0] for c in calls] == ["One?", "Two?"]
- assert calls[0][1] == ("a (Recommended)", "b")
- assert calls[1][1] is None
- assert [r["user_response"] for r in result["responses"]] == [
- "answer to One?", "answer to Two?",
- ]
- assert "timed_out" not in result
-
- def test_legacy_loop_aborts_on_timeout_and_keeps_partials(self):
- """The loop stops on the first timeout. Collected answers survive."""
- from tools.clarify_tool import TIMEOUT_RESPONSE
- calls = []
-
- def legacy_cb(question, choices):
- calls.append(question)
- if len(calls) == 2:
- return TIMEOUT_RESPONSE
- return "answered"
-
- result = json.loads(clarify_tool(
- "",
- questions=[
- {"question": "One?"}, {"question": "Two?"}, {"question": "Three?"},
- ],
- callback=legacy_cb,
- ))
- assert calls == ["One?", "Two?"]
- assert result["timed_out"] is True
- assert [r["user_response"] for r in result["responses"]] == [
- "answered", "", "",
- ]
-
- def test_legacy_loop_skip_continues(self):
- """An explicit empty answer is a skip. The loop continues."""
- calls = []
-
- def legacy_cb(question, choices):
- calls.append(question)
- return "" if len(calls) == 1 else "second"
-
- result = json.loads(clarify_tool(
- "",
- questions=[{"question": "One?"}, {"question": "Two?"}],
- callback=legacy_cb,
- ))
- assert calls == ["One?", "Two?"]
- assert [r["user_response"] for r in result["responses"]] == ["", "second"]
- assert "timed_out" not in result
+ def test_batch_skipped_is_not_unanswered(self):
+ """A question locked empty is skipped; a missing one is unanswered."""
+ def cb(questions):
+ return _reply({"q0": None})
+ result = _ask(cb, [{"question": "One?"}, {"question": "Two?"}])
+ assert [r["status"] for r in result["responses"]] == ["skipped", "unanswered"]
+ assert result["outcome"] == "submitted"
+ assert "notice" not in result
class TestRegistryBatchPassThrough:
@@ -594,9 +346,9 @@ class TestRegistryBatchPassThrough:
entry = registry.get_entry("clarify")
seen = {}
- def cb(question, choices, multi_select=False, questions=None):
+ def cb(questions):
seen["questions"] = questions
- return {"answers": {"q0": "yes"}}
+ return _reply({"q0": "yes"})
result = json.loads(entry.handler(
{"questions": [{"question": "Go?"}]},
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py
index 8a968fd2a65..bd05c0faa6c 100644
--- a/tests/tui_gateway/test_protocol.py
+++ b/tests/tui_gateway/test_protocol.py
@@ -271,7 +271,7 @@ def test_server_request_round_trip_uses_response_frame(capture):
lambda sr, req: sr.resolve_response({"id": req.id, "result": {"value": "yes"}}) is True,
{"value": "yes"}),
# Batch clarify's lock-based resolution follows the same first-settlement rule.
- ("clarify", ["q1"], lambda sr, req: sr.lock_answer(req.id, "q1", "yes") == [], {"answers": {"q1": "yes"}}),
+ ("clarify", ["q1"], lambda sr, req: sr.lock_answer(req.id, "q1", "yes") == [], {"answers": {"q1": "yes"}, "outcome": "submitted"}),
])
def test_settlement_wins_over_a_later_cancel(capture, method, qids, settle, expected):
"""A response and cancellation may race; the first settlement owns the result."""
@@ -514,7 +514,7 @@ def _start_batch_clarify(server, buf, qids, timeout=None):
if timeout is not None:
server._clarify_timeout_seconds = lambda: timeout
thread = threading.Thread(
- target=lambda: box.__setitem__("answer", server._clarify_block("s1", "", None, questions=normalized)), daemon=True)
+ target=lambda: box.__setitem__("answer", server._clarify_block("s1", normalized)), daemon=True)
thread.start()
return thread, box, _wait_open(server_requests, buf)
@@ -541,9 +541,9 @@ def test_clarify_batch_locks_resolve_in_order_and_keep_partial_on_timeout(captur
"params": {"request_id": req.id, "question_id": "q1", "answer": ""}})
assert last["result"] == {"status": "ok", "remaining": []}
thread.join(timeout=5)
- assert json.loads(box["answer"]) == {"answers": {"q0": "y", "q1": ""}}
+ assert box["answer"] == {"answers": {"q0": "y", "q1": ""}, "outcome": "submitted"}
- # Deadline: locked answers survive, timed_out flagged, one request.cancel.
+ # Deadline: locked answers survive, outcome timed_out, one request.cancel.
original_timeout = server._clarify_timeout_seconds
try:
thread, box, req = _start_batch_clarify(server, buf, ["q0", "q1"], timeout=1.5)
@@ -553,7 +553,7 @@ def test_clarify_batch_locks_resolve_in_order_and_keep_partial_on_timeout(captur
thread.join(timeout=5)
finally:
server._clarify_timeout_seconds = original_timeout
- assert json.loads(box["answer"]) == {"answers": {"q0": "kept"}, "timed_out": True}
+ assert box["answer"] == {"answers": {"q0": "kept"}, "outcome": "timed_out"}
cancels = [f for f in _frames(buf) if f.get("method") == "event" and f["params"]["type"] == "request.cancel"]
assert [c["params"]["payload"]["id"] for c in cancels] == [req.id]
@@ -563,7 +563,7 @@ def test_clarify_batch_cancel_all_is_a_response_without_answers(capture):
thread, box, req = _start_batch_clarify(server, buf, ["q0", "q1"])
server.dispatch({"jsonrpc": "2.0", "id": req.id, "result": {}})
thread.join(timeout=5)
- assert box["answer"] == ""
+ assert box["answer"] == {"answers": {}, "outcome": "cancelled"}
def test_clear_pending_cancels_only_that_session(capture):
diff --git a/tests/tui_gateway/test_show_reasoning_display_gate.py b/tests/tui_gateway/test_show_reasoning_display_gate.py
index de0a706fe83..3ca92781ccb 100644
--- a/tests/tui_gateway/test_show_reasoning_display_gate.py
+++ b/tests/tui_gateway/test_show_reasoning_display_gate.py
@@ -90,10 +90,10 @@ def _emit_ordinary_and_essential_tools(sid):
server._on_tool_complete(sid, "tool-read", "read_file", {"path": "README.md"}, "contents")
server._agent_cbs(sid)["tool_gen_callback"]("terminal")
- clarify_args = {"question": "Pick one", "choices": ["A", "B"]}
+ clarify_args = {"questions": [{"question": "Pick one", "choices": ["A", "B"]}]}
server._on_tool_start(sid, "tool-clarify", "clarify", clarify_args)
server._on_tool_complete(
- sid, "tool-clarify", "clarify", clarify_args, json.dumps({"question": "Pick one", "user_response": "A"})
+ sid, "tool-clarify", "clarify", clarify_args, json.dumps({"responses": [{"question": "Pick one", "status": "answered", "user_response": "A"}], "outcome": "submitted"})
)
server._on_tool_complete(sid, "tool-fail", "terminal", {"command": "deploy"}, json.dumps({"error": "disk full"}))
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index 5ff31f14006..55bcedae8ce 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -1619,8 +1619,8 @@ def test_tui_clarify_lifecycle_events_emit_when_tool_progress_off(monkeypatch):
{"tool_progress_mode": "off", "tool_started_at": {}},
)
- args = {"question": "Pick one", "choices": ["A", "B"]}
- result = '{"question":"Pick one","choices_offered":["A","B"],"user_response":"A"}'
+ args = {"questions": [{"question": "Pick one", "choices": ["A", "B"]}]}
+ result = '{"responses":[{"question":"Pick one","choices_offered":["A","B"],"status":"answered","user_response":"A"}],"outcome":"submitted"}'
server._on_tool_start("clarify-off-test", "tool-clarify", "clarify", args)
server._on_tool_complete("clarify-off-test", "tool-clarify", "clarify", args, result)
@@ -1628,7 +1628,7 @@ def test_tui_clarify_lifecycle_events_emit_when_tool_progress_off(monkeypatch):
assert [event[0] for event in events] == ["tool.start", "tool.complete"]
assert events[0][2]["name"] == "clarify"
assert events[0][2]["tool_id"] == "tool-clarify"
- assert events[1][2]["result"]["user_response"] == "A"
+ assert events[1][2]["result"]["responses"][0]["user_response"] == "A"
def test_tui_non_interactive_tool_lifecycle_stays_hidden_when_tool_progress_off(monkeypatch):
@@ -21053,29 +21053,19 @@ def _capture_server_request(monkeypatch, result):
def test_clarify_callback_uses_configured_timeout(monkeypatch):
"""The TUI/desktop clarify bridge sends a ``clarify`` server request with the canonical clarify timeout
- (via _clarify_timeout_seconds), and returns the response's ``answer``."""
+ (via _clarify_timeout_seconds), and returns the response's ``answers`` and ``outcome``."""
monkeypatch.setattr(server, "_clarify_timeout_seconds", lambda: 42)
- captured = _capture_server_request(monkeypatch, {"answer": "answer"})
+ reply = {"answers": {"q0": "a"}, "outcome": "submitted"}
+ captured = _capture_server_request(monkeypatch, reply)
+ questions = [{"qid": "q0", "question": "Pick one", "choices": ["a", "b"], "multi_select": False}]
- result = server._agent_cbs("sid-1")["clarify_callback"]("Pick one", ["a", "b"])
+ result = server._agent_cbs("sid-1")["clarify_callback"](questions)
- assert result == "answer"
+ assert result == reply
assert captured["method"] == "clarify" and captured["sid"] == "sid-1"
assert captured["timeout"] == 42
- assert captured["params"] == {"question": "Pick one", "choices": ["a", "b"]}
-
-
-def test_clarify_callback_multi_select_hint(monkeypatch):
- """multi_select=True adds the hint to the params; the single-select shape stays byte-identical to the
- pre-multi-select protocol (older renderers must never see the extra field)."""
- captured = _capture_server_request(monkeypatch, {"answer": "answer"})
- cb = server._agent_cbs("sid-1")["clarify_callback"]
-
- cb("Pick many", ["a", "b"], multi_select=True)
- assert captured["params"] == {"question": "Pick many", "choices": ["a", "b"], "multi_select": True}
-
- cb("Pick one", ["a", "b"], multi_select=False)
- assert captured["params"] == {"question": "Pick one", "choices": ["a", "b"]}
+ assert captured["params"] == {"questions": questions}
+ assert captured["qids"] == ["q0"]
@pytest.mark.parametrize(
diff --git a/tests/tui_gateway/test_warning_callback_conservation.py b/tests/tui_gateway/test_warning_callback_conservation.py
index 1804e9f9a54..2c47919e4c2 100644
--- a/tests/tui_gateway/test_warning_callback_conservation.py
+++ b/tests/tui_gateway/test_warning_callback_conservation.py
@@ -10,6 +10,8 @@ from agent.status_output import StatusOutputMixin
from tui_gateway import server
from tests.tui_gateway.test_auto_continue import turn_env, marker_home, _session
+CLARIFY_QUESTIONS = [{"qid": "q0", "question": "Continue recovery?", "choices": ["yes", "no"], "multi_select": False}]
+
class Agent(StatusOutputMixin):
log_prefix = ""
@@ -63,7 +65,7 @@ def test_post_turn_drain_uses_owner_and_preserves_real_clarify(turn_env, marker_
def wire(frame):
frames.append(frame)
if frame.get("method") == "clarify":
- assert server_requests.resolve_response({"id": frame["id"], "result": {"answer": "yes"}})
+ assert server_requests.resolve_response({"id": frame["id"], "result": {"answers": {"q0": "yes"}}})
return True
monkeypatch.setattr(server, "write_json", wire)
monkeypatch.setattr(server_requests, "_write", wire)
@@ -73,7 +75,7 @@ def test_post_turn_drain_uses_owner_and_preserves_real_clarify(turn_env, marker_
agent.clarify_callback = server._agent_cbs("drain-owner")["clarify_callback"]
def run(message, **kwargs):
work.append(message)
- controls.append(agent.clarify_callback("Continue recovery?", ["yes", "no"]))
+ controls.append(agent.clarify_callback(CLARIFY_QUESTIONS))
logging.getLogger("operator").warning("watch diagnostic retained")
return {"final_response": "diagnostic final", "messages": []}
agent.run_conversation = run
@@ -84,7 +86,7 @@ def test_post_turn_drain_uses_owner_and_preserves_real_clarify(turn_env, marker_
with caplog.at_level(logging.WARNING, logger="operator"):
server._run_post_turn_followups("request", "drain-owner", session, {}, None)
assert len(work) == 1
- assert controls == ["yes"]
+ assert [c["answers"] for c in controls] == [{"q0": "yes"}]
assert process_registry.completion_queue.empty()
assert "watch diagnostic retained" in caplog.text
presentation = [f for f in frames if f.get("params", {}).get("type") in {"status.update", "message.complete", "message.start", "error"}]
@@ -102,7 +104,7 @@ def test_diagnostic_turn_callbacks_from_real_worker_keep_controls_and_logs(turn_
def wire(frame):
frames.append(frame)
if frame.get("method") == "clarify":
- assert server_requests.resolve_response({"id": frame["id"], "result": {"answer": "yes"}})
+ assert server_requests.resolve_response({"id": frame["id"], "result": {"answers": {"q0": "yes"}}})
return True
monkeypatch.setattr(server, "write_json", wire)
monkeypatch.setattr(server_requests, "_write", wire)
@@ -126,7 +128,7 @@ def test_diagnostic_turn_callbacks_from_real_worker_keep_controls_and_logs(turn_
agent._emit_wait_notice("plain wake thinking")
agent._emit_notice(SimpleNamespace(level="info", text="wake notice", kind="custom", ttl_ms=0, key="custom", id="n"))
kwargs["stream_callback"]("wake stream")
- controls.append(agent.clarify_callback("Continue recovery?", ["yes", "no"]))
+ controls.append(agent.clarify_callback(CLARIFY_QUESTIONS))
logging.getLogger("operator").warning("worker diagnostic retained")
except BaseException as exc:
failures.append(exc)
@@ -142,7 +144,7 @@ def test_diagnostic_turn_callbacks_from_real_worker_keep_controls_and_logs(turn_
session["_run_thread"].join(timeout=10)
assert not session["_run_thread"].is_alive()
assert not failures
- assert controls == ["yes"]
+ assert [c["answers"] for c in controls] == [{"q0": "yes"}]
assert "worker diagnostic retained" in caplog.text
presentation = [f for f in frames if f.get("params", {}).get("type") in
{"status.update", "thinking.delta", "notification.show", "message.delta", "message.complete"}]
diff --git a/tools/clarify_gateway.py b/tools/clarify_gateway.py
index dd03b6e185b..ec84a97dc7f 100644
--- a/tools/clarify_gateway.py
+++ b/tools/clarify_gateway.py
@@ -41,6 +41,9 @@ TEXT_RESOLVED = "resolved"
TEXT_REJECTED_PROSE = "rejected_prose"
TEXT_REJECTED_SELECTION = "rejected_selection"
TEXT_NO_PENDING = "no_pending"
+SKIP_WORD = "skip"
+SKIPPED = "\x00skipped"
+CANCELLED = "\x00cancelled"
def register(clarify_id: str, session_key: str, question: str, choices: Optional[List[str]],
@@ -167,8 +170,9 @@ def _coerce_text_response_detailed(entry: _ClarifyEntry, response: str) -> tuple
``awaiting_text`` accept any text; numeric picks and exact labels always resolve; multi-select
returns a JSON array string (decoded tool-side); one bad token rejects the whole reply."""
text = str(response).strip()
+ is_skip = text.casefold() == SKIP_WORD
if not entry.choices:
- return text, None
+ return (SKIPPED if is_skip else text), None
if entry.multi_select:
coerced = _coerce_multi_select_text(entry, text)
selection_shaped = _selection_attempt_tokens(text, entry.choices) is not None
@@ -179,6 +183,8 @@ def _coerce_text_response_detailed(entry: _ClarifyEntry, response: str) -> tuple
coerced = entry.choices[idx] if 0 <= idx < len(entry.choices) else _match_label(text, entry.choices)
if coerced is not None:
return coerced, None
+ if is_skip:
+ return SKIPPED, None
if entry.awaiting_text:
return text, None
return None, "invalid_selection" if selection_shaped else "prose"
@@ -239,9 +245,7 @@ def has_pending(session_key: str) -> bool:
def clear_session(session_key: str) -> int:
"""Drop every pending clarify for a session (``/new``, shutdown, cached-agent eviction) so
- blocked agent threads don't outlive it; returns how many were cancelled. Cancelled waiters
- see "" (callers tell it from a real reply only via their own timeout bookkeeping; most treat
- any falsy result as no response). First-writer-wins: an already-set entry was answered for
+ blocked agent threads don't outlive it; returns how many were cancelled. First-writer-wins: an already-set entry was answered for
real, so it is dropped but its response preserved. The loop stays inside the lock so a button
callback cannot slip between pop and check; entries go regardless of state so a cleared
session is never resurrected by late callbacks."""
@@ -250,7 +254,7 @@ def clear_session(session_key: str) -> int:
for entry in (_entries.pop(cid, None) for cid in list(_session_index.pop(session_key, []) or [])):
if entry is None or entry.event.is_set():
continue
- entry.response = ""
+ entry.response = CANCELLED
entry.event.set()
cancelled += 1
return cancelled
diff --git a/tools/clarify_tool.py b/tools/clarify_tool.py
index 70d3a99df62..e09ac84bd13 100644
--- a/tools/clarify_tool.py
+++ b/tools/clarify_tool.py
@@ -2,34 +2,15 @@
Schema, validation and a thin dispatcher; the UI lives in a platform-provided
callback (cli.py, gateway/run.py, tui_gateway)."""
-import inspect
import json
-from typing import Dict, List, Optional, Callable
+from typing import Callable, Dict, List, Optional
MAX_CHOICES = 4 # the UI always appends an "Other (type your answer)" row
-MAX_QUESTIONS = 5 # independent questions per batch call
-# Canonical timeout sentinel. The CLI returns this exact text; the batch loop
-# treats it (like ``None``) as "the user walked away" and aborts remaining questions.
-TIMEOUT_RESPONSE = ("The user did not provide a response within the time limit. "
- "Use your best judgement to make the choice and proceed.")
+MAX_QUESTIONS = 5 # independent questions per call
# Applied to the first choice here (not per-surface) so every adapter renders it identically.
RECOMMENDED_LABEL = "(Recommended)"
_UNAVAILABLE = "Clarify tool is not available in this execution context."
-
-
-def _flatten_choice(c) -> str:
- """Coerce one choice to display text. LLMs sometimes emit dict-shaped choices and ``str(c)``
- would leak the repr onto every surface and back as the answer; unwrap order ``label`` >
- ``description`` > ``text`` > ``title`` (``name``/``value`` excluded: raw component enums,
- not labels). No match -> "" and dropped: no choice beats a garbage label."""
- if isinstance(c, str):
- return c.strip()
- if isinstance(c, dict):
- return next((v.strip() for k in ("label", "description", "text", "title")
- if isinstance(v := c.get(k), str) and v.strip()), "")
- if isinstance(c, (list, tuple)):
- return " ".join(_flatten_choice(x) for x in c).strip()
- return "" if c is None else str(c).strip()
+_SHAPE = "Pass questions=[{question, choices?, multi_select?}]; a single question is a one-entry array."
def mark_recommended(choices: List[str]) -> List[str]:
@@ -49,191 +30,84 @@ def strip_recommended(text: str) -> str:
return stripped
-def _accepts_kwarg(callback, name: str) -> bool:
- """Signature-inspect (never a TypeError retry, which could re-prompt the user) whether
- ``callback`` takes ``name`` or ``**kwargs``; non-introspectable callables are legacy."""
- try:
- params = inspect.signature(callback).parameters
- except (TypeError, ValueError):
- return False
- return name in params or any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
-
-
-def _invoke_callback(callback, question, choices, multi_select):
- """Invoke the platform callback, passing multi_select if supported."""
- if _accepts_kwarg(callback, "multi_select"):
- return callback(question, choices, multi_select=multi_select)
- return callback(question, choices)
-
-
-def _json_as(raw: str, kind):
- """``json.loads(raw)`` when it decodes to an instance of ``kind``, else None."""
- try:
- parsed = json.loads(raw)
- except json.JSONDecodeError:
- return None
- return parsed if isinstance(parsed, kind) else None
-
-
-def _parse_multi_select_response(raw_response) -> List[str]:
- """Parse a list / JSON array / comma-separated reply into stripped non-empty strings."""
- items = raw_response
- if not isinstance(items, list):
- raw = str(items).strip()
- items = _json_as(raw, list) if raw.startswith("[") else None
- if items is None:
- items = raw.split(",")
- return [str(r).strip() for r in items if str(r).strip()]
-
-
def _clean_answer(raw, multi: bool):
- """Strip presentation (the label, multi-select JSON) from a locked answer."""
- return [strip_recommended(r) for r in _parse_multi_select_response(raw)] if multi else strip_recommended(raw)
-
-
-def _clean_choices(choices: list) -> Optional[List[str]]:
- """Flatten, drop empties, cap at MAX_CHOICES; None when nothing survives (open-ended)."""
- cleaned = [s for s in (_flatten_choice(c) for c in choices) if s]
- return cleaned[:MAX_CHOICES] or None
+ """Strip presentation (the label, multi-select JSON) from a locked answer: a multi-select
+ answer is a list, a JSON array string, or one typed ("Other") answer."""
+ if not multi:
+ return strip_recommended(raw)
+ if isinstance(raw, str):
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError:
+ parsed = None
+ raw = parsed if isinstance(parsed, list) else [raw]
+ return [strip_recommended(item) for item in raw if str(item).strip()]
-def _is_timeout(raw) -> bool:
- return raw is None or (isinstance(raw, str) and raw.strip() == TIMEOUT_RESPONSE)
-
-
-# ============================================================================= Batch (multi-question)
-# support — issue #18450 =============================================================================
def _normalize_questions(questions) -> tuple:
- """Validate the ``questions`` batch param -> ``(normalized, error)``; an empty list gives
- ``(None, None)`` (fall back to the single-question path). Entries carry ``qid`` (stable
- wire id ``q<index>`` surfaces key answers by; the model's ``id`` is unvalidated text, only
- echoed), ``question``, decorated ``choices``, bare ``choices_offered``, ``multi_select``."""
- if not isinstance(questions, list):
- return None, "questions must be an array of question objects."
- if not questions:
- return None, None
+ """Validate ``questions`` -> ``(normalized, error)``. Entries carry ``qid`` (stable wire id
+ ``q<index>`` surfaces key answers by), ``question``, decorated ``choices``, bare
+ ``choices_offered`` and ``multi_select``."""
+ if not isinstance(questions, list) or not questions:
+ return None, f"questions must be a non-empty array. {_SHAPE}"
if len(questions) > MAX_QUESTIONS:
return None, f"questions supports at most {MAX_QUESTIONS} items."
normalized = []
for index, item in enumerate(questions):
- if isinstance(item, str): # tolerate bare-string items: LLMs sometimes send ["Q1?", "Q2?"]
- item = {"question": item}
if not isinstance(item, dict):
- return None, f"questions[{index}] must be an object with a 'question'."
+ return None, f"questions[{index}] must be an object. {_SHAPE}"
text = str(item.get("question") or "").strip()
if not text:
return None, f"questions[{index}].question must be non-empty text."
choices = item.get("choices")
if choices is not None:
- if not isinstance(choices, list):
- return None, f"questions[{index}].choices must be a list."
- choices = _clean_choices(choices)
+ if not isinstance(choices, list) or not all(isinstance(c, str) for c in choices):
+ return None, f"questions[{index}].choices must be a list of strings."
+ choices = [c.strip() for c in choices if c.strip()][:MAX_CHOICES] or None
normalized.append({
- "qid": f"q{index}", "id": str(item.get("id") or "").strip() or None, "question": text,
+ "qid": f"q{index}", "question": text,
"choices": mark_recommended(list(choices)) if choices else None,
"choices_offered": list(choices) if choices else None,
"multi_select": bool(item.get("multi_select")) and bool(choices)})
return normalized, None
-def _batch_result(normalized: List[dict], answers: dict, timed_out: bool, notice: Optional[str] = None) -> str:
- """Batch result JSON; unanswered -> "". The top-level ``timed_out`` flag (present only when
- true) tells the agent whether blanks are deliberate skips or the user walking away; ``notice``
- (surface-supplied, only beside ``timed_out``) says WHY the wait ended, so an undeliverable
- prompt never reads as user inactivity."""
- responses = []
- for entry in normalized:
- raw = answers.get(entry["qid"])
- responses.append({
- **({"id": entry["id"]} if entry["id"] else {}),
- "question": entry["question"], "choices_offered": entry["choices_offered"],
- "user_response": _clean_answer(raw, entry["multi_select"]) if raw else ""})
- result: Dict[str, object] = {"responses": responses}
- if timed_out:
- result["timed_out"] = True
- if notice:
- result["notice"] = str(notice)
- return json.dumps(result, ensure_ascii=False)
+def _response_status(qid: str, answers: dict, multi: bool) -> tuple:
+ raw = answers.get(qid)
+ cleaned = _clean_answer(raw, multi) if raw not in (None, "") else None
+ if cleaned:
+ return "answered", cleaned
+ return ("skipped" if qid in answers else "unanswered"), None
-def _run_batch(normalized: List[dict], callback, question: str) -> str:
- """Dispatch a validated batch. Batch-capable callbacks (``questions`` kwarg) get the
- whole list once and reply ``{"answers": {qid: raw}, "timed_out"?}`` as a dict or JSON
- string (the tui_gateway bridge only carries strings); any other falsy/unparseable reply
- is a cancel-all (mirrors the single-question skip). Legacy callbacks are looped per
- question: an empty answer is a skip, a timeout (``None`` or the sentinel) means the user
- walked away so the loop aborts instead of pestering them; earlier answers are kept."""
- answers: dict = {}
- timed_out = False
- notice = None
- if _accepts_kwarg(callback, "questions"):
- raw = callback(question, None, questions=normalized)
- timed_out = _is_timeout(raw)
- if isinstance(raw, str):
- raw = _json_as(raw, dict) # the sentinel is not JSON -> None, timed_out stays True
- if isinstance(raw, dict):
- answers = dict(raw.get("answers") or {})
- timed_out = bool(raw.get("timed_out"))
- notice = raw.get("notice")
- return _batch_result(normalized, answers, timed_out, notice)
+def _result(normalized: List[dict], reply: dict) -> str:
+ """Result JSON from a callback reply ``{"answers": {qid: raw | None}, "outcome", "notice"?}``:
+ every response carries ``status`` and ``user_response`` (null unless answered); ``outcome``
+ says how the wait ended and ``notice`` (surface-supplied) says why."""
+ answers = reply.get("answers") or {}
+ responses = []
for entry in normalized:
- raw = _invoke_callback(callback, entry["question"], entry["choices"], entry["multi_select"])
- if _is_timeout(raw):
- timed_out = True
- break
- answers[entry["qid"]] = raw
- return _batch_result(normalized, answers, timed_out)
-
+ status, value = _response_status(entry["qid"], answers, entry["multi_select"])
+ responses.append({"question": entry["question"], "choices_offered": entry["choices_offered"],
+ "status": status, "user_response": value})
+ result: Dict[str, object] = {"responses": responses, "outcome": reply["outcome"]}
+ if reply.get("notice"):
+ result["notice"] = str(reply["notice"])
+ return json.dumps(result, ensure_ascii=False)
-def clarify_tool(question: str, choices: Optional[List[str]] = None, multi_select: bool = False,
- questions: Optional[List[dict]] = None, callback: Optional[Callable] = None) -> str:
- """Ask one question (``question``/``choices``/``multi_select``) or a batch (``questions``
- wins when non-empty). ``callback(question, choices, multi_select=False) -> str`` is
- platform injected (batch-capable ones also take ``questions=``). Returns result JSON.
- Args: question: The question text to present. choices: Up to 4 predefined answer choices. When
- omitted the question is purely open-ended. multi_select: When True, the user can select multiple choices
- (checkboxes). The ``user_response`` in the output JSON will be a list of strings instead of a single
- string. Has no effect when ``choices`` is omitted. questions: Up to 5 independent questions asked as
- one batch (issue #18450). When present (non-empty), the single ``question``/``choices``/``multi_select``
- parameters are ignored and the result JSON is ``{"responses": [...]}`` (plus ``"timed_out": true`` when
- the user stopped answering partway). callback: Platform-provided function that handles the actual UI
- interaction. Batch-capable platforms additionally accept a ``questions`` keyword and receive the
- normalized list in one call; platforms without it are looped one question at a time. Injected by the
- agent runner (cli.py / gateway).
- """
- if questions is not None:
- normalized, error = _normalize_questions(questions)
- if error:
- return tool_error(error)
- if normalized:
- if callback is None:
- return tool_error(_UNAVAILABLE)
- try:
- return _run_batch(normalized, callback, str(question or "").strip())
- except Exception as exc:
- return tool_error(f"Failed to get user input: {exc}")
- # Empty questions array → fall through to the single-question path.
- if not question or not question.strip():
- return tool_error("No question provided. Pass questions=[{question: '...', "
- "choices?: [...], multi_select?: bool}, ...] — a single question "
- "is a one-entry array.")
- question = question.strip()
- if choices is not None:
- if not isinstance(choices, list):
- return tool_error("choices must be a list of strings.")
- choices = _clean_choices(choices)
+def clarify_tool(questions, callback: Optional[Callable] = None) -> str:
+ """Ask 1-5 questions in one call. ``callback(questions) -> {"answers", "outcome", "notice"?}``
+ is platform injected (cli.py / gateway / tui_gateway) and receives the normalized list."""
+ normalized, error = _normalize_questions(questions)
+ if error:
+ return tool_error(error)
if callback is None:
return tool_error(_UNAVAILABLE)
- # The bare list goes back to the agent; the "(Recommended)" label is presentation only.
- shown = mark_recommended(choices) if choices is not None else None
try:
- raw_response = _invoke_callback(callback, question, shown, multi_select)
+ return _result(normalized, callback(normalized))
except Exception as exc:
return tool_error(f"Failed to get user input: {exc}")
- return json.dumps({"question": question, "choices_offered": choices,
- "user_response": _clean_answer(raw_response, multi_select and choices is not None)},
- ensure_ascii=False)
def check_clarify_requirements() -> bool:
@@ -256,9 +130,11 @@ CLARIFY_SCHEMA = {
"open-ended (omit choices). Options go ONLY in `choices`, never "
"enumerated inside the question text (choices render as pickable "
"rows; options written into the question are dead prose the user "
- "can't click). Result: {responses: [...]} in question order (plus "
- "timed_out=true, and a notice saying why, if the user stopped "
- "part-way or the prompt could not be delivered). Prefer deciding "
+ "can't click). Result: {responses: [...], outcome} in question order. "
+ "Each response has status answered, skipped or unanswered "
+ "(user_response is null unless answered); outcome is submitted, "
+ "cancelled, timed_out or undelivered, with a notice saying why "
+ "when the wait ended without a submit. Prefer deciding "
"low-stakes questions yourself; don't use this for dangerous-command "
"confirmation (the terminal tool handles that)."
),
@@ -289,12 +165,6 @@ CLARIFY_SCHEMA = {
"required": ["question"],
},
},
- # NOTE: the handler also accepts (unadvertised): a per-question
- # `id` (echoed in the matching response — redundant since rows
- # carry the question text and preserve order), and the legacy
- # single-question shape (`question` + `choices` + `multi_select`
- # at top level; a top-level `question` beside `questions` is the
- # batch form's title). One documented way to call.
},
"required": ["questions"],
},
@@ -307,12 +177,7 @@ registry.register(
name="clarify",
toolset="clarify",
schema=CLARIFY_SCHEMA,
- handler=lambda args, **kw: clarify_tool(
- question=args.get("question", ""),
- choices=args.get("choices"),
- multi_select=args.get("multi_select", False),
- questions=args.get("questions"),
- callback=kw.get("callback")),
+ handler=lambda args, **kw: clarify_tool(args.get("questions"), callback=kw.get("callback")),
check_fn=check_clarify_requirements,
emoji="❓",
)
diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.py
index 22bc45a1a2f..adc9c05e90b 100644
--- a/tui_gateway/agent_callbacks.py
+++ b/tui_gateway/agent_callbacks.py
@@ -162,8 +162,7 @@ def _agent_cbs(sid: str) -> dict:
# Credits/notice spine: AgentNotice → notification.show; recovery → notification.clear.
"notice_callback": lambda n: _agent_notice_update(sid, n),
"notice_clear_callback": lambda key: _emit("notification.clear", sid, {"key": key}),
- "clarify_callback": lambda q, c, multi_select=False, questions=None: (
- _clarify_block(sid, q, c, multi_select=multi_select, questions=questions)),
+ "clarify_callback": lambda questions: _clarify_block(sid, questions),
"read_terminal_callback": _read_block("terminal.read", 30),
"read_preview_callback": _read_block("preview.read", 45),
# drive_preview / annotate_preview (desktop GUI): same budget as the preview read it ends with.
diff --git a/tui_gateway/compute_host_bridge.py b/tui_gateway/compute_host_bridge.py
index 26060806b1e..5d08876b6e6 100644
--- a/tui_gateway/compute_host_bridge.py
+++ b/tui_gateway/compute_host_bridge.py
@@ -194,7 +194,7 @@ def _relay_compute_host_response(frame: dict) -> bool:
return True
-def _lock_compute_host_clarify(rid: str, request_id: str, question_id: str, answer: str) -> dict | None:
+def _lock_compute_host_clarify(rid: str, request_id: str, question_id: str, answer: str | None) -> dict | None:
"""Proxy a batch-clarify lock into the child that owns the request; keeps the parent mirror's locked
answers current for reconnect snapshots. None when the request is not host-owned."""
located = _compute_host_request_session(request_id)
diff --git a/tui_gateway/contracts/server_requests.py b/tui_gateway/contracts/server_requests.py
index 92cba6fcff6..e0ef4ef4043 100644
--- a/tui_gateway/contracts/server_requests.py
+++ b/tui_gateway/contracts/server_requests.py
@@ -37,26 +37,21 @@ class ClarifyQuestion(Params):
class ClarifyRequestParams(ServerRequestParams):
- """Single question: ``question`` / ``choices`` (/ ``multi_select``); batch: ``questions``.
- ``answers`` rides only on a reconnect replay (locks the server already accepted)."""
+ """``answers`` rides only on a reconnect replay (locks the server already accepted; null = skipped)."""
- question: str | None = None
- choices: list[str] | None = None
- multi_select: bool | None = None
- questions: list[ClarifyQuestion] | None = None
- answers: dict[str, str] | None = None
+ questions: list[ClarifyQuestion]
+ answers: dict[str, str | None] | None = None
class ClarifyResult(Result):
- """Single: ``{answer}`` ('' = skip). Batch: ``{answers}`` for the whole set (early locks go through
- the ``clarify.lock`` RPC); a response with neither is cancel-all."""
+ """``{answers}`` for the whole set (early locks go through the ``clarify.lock`` RPC); a response
+ without ``answers`` is cancel-all."""
- answer: str | None = None
- answers: dict[str, str] | None = None
+ answers: dict[str, str | None] | None = None
server_request("clarify", params=ClarifyRequestParams, result=ClarifyResult,
- doc="The clarify tool: ask the user one question or a batch.")
+ doc="The clarify tool: ask the user 1-5 questions.")
# ── approval ──────────────────────────────────────────────────────────────────────────────────
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index 0a6bf0b8853..d26c4d793e9 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -1020,7 +1020,8 @@ def _(rid, params: dict) -> dict:
if not request_id or not question_id:
return _err(rid, 4002, "request_id and question_id required")
answer = params.get("answer", "")
- answer = answer if isinstance(answer, str) else json.dumps(answer, ensure_ascii=False)
+ if answer is not None and not isinstance(answer, str):
+ answer = json.dumps(answer, ensure_ascii=False)
if (proxied := _lock_compute_host_clarify(rid, request_id, question_id, answer)) is not None:
return proxied
from tui_gateway import server_requests
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 6a743aed397..6743ab93e58 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1361,24 +1361,16 @@ def _clarify_timeout_seconds() -> float | None:
return 300
-def _clarify_block(sid: str, q, c, multi_select=False, questions=None) -> str:
- """Bridge the clarify tool callback onto a ``clarify`` server request. Single question: the response is
- ``{"answer"}`` ("" = skip). Batch: one request with only the wire fields (tool-side entries carry
- result-assembly keys too); answers lock one at a time through ``clarify.lock`` and the tool gets
- ``{"answers", "timed_out"?}`` as JSON — a response with no ``answers`` is a cancel-all."""
+def _clarify_block(sid: str, questions: list[dict]) -> dict:
+ """Bridge the clarify tool callback onto one ``clarify`` server request carrying only the wire fields
+ (tool-side entries carry result-assembly keys too). Answers lock one at a time through ``clarify.lock``
+ (``null`` = skipped); the tool gets ``{"answers", "outcome"}`` — ``undelivered`` when no client took it."""
from tui_gateway import server_requests
- if questions:
- wire = [{"qid": e["qid"], "question": e["question"], "choices": e["choices"], "multi_select": bool(e["multi_select"])}
- for e in questions]
- result = server_requests.send("clarify", sid, {"questions": wire}, timeout=_clarify_timeout_seconds(),
- qids=[e["qid"] for e in questions])
- if not result or "answers" not in result:
- return ""
- return json.dumps(result, ensure_ascii=False)
- params = {"question": q, "choices": c, "multi_select": True} if multi_select else {"question": q, "choices": c}
- result = server_requests.send("clarify", sid, params, timeout=_clarify_timeout_seconds())
- answer = (result or {}).get("answer", "")
- return answer if isinstance(answer, str) else ""
+ wire = [{"qid": e["qid"], "question": e["question"], "choices": e["choices"], "multi_select": bool(e["multi_select"])}
+ for e in questions]
+ result = server_requests.send("clarify", sid, {"questions": wire}, timeout=_clarify_timeout_seconds(),
+ qids=[e["qid"] for e in questions])
+ return result or {"answers": {}, "outcome": "undelivered"}
# A tour action is a DOM op the renderer answers in ms; the generous deadline exists only because a
diff --git a/tui_gateway/server_requests.py b/tui_gateway/server_requests.py
index 97a236d17d5..c38d7ed5fca 100644
--- a/tui_gateway/server_requests.py
+++ b/tui_gateway/server_requests.py
@@ -62,7 +62,7 @@ class ServerRequest:
self.created_at = time.time()
# Batch clarify: question ids still to lock, and the answers locked so far.
self.qids = list(qids) if qids else None
- self.locked: dict[str, str] = {}
+ self.locked: dict[str, str | None] = {}
self.on_result = on_result
# Client transports that answered NOT_SHOWN_CODE (no window there shows this session).
self.declined: set = set()
@@ -166,8 +166,8 @@ def send(method: str, sid: str, params: dict, *, timeout: float | None,
Returns ``None`` when the renderer never answered (timeout, cancel, or an error response — e.g.
a client without a handler for ``method``). ``timeout`` semantics: None → wait until answered or
- cancelled, 0 → return immediately, > 0 → bounded wait. A batch (``qids``) that times out
- returns ``{"answers": <locked so far>, "timed_out": True}`` instead of None.
+ cancelled, 0 → return immediately, > 0 → bounded wait. A batch (``qids``) that settled returns
+ ``{"answers": <locked so far>, "outcome"}`` (``submitted`` / ``cancelled`` / ``timed_out``).
"""
if _unanswerable(method, sid):
return None
@@ -195,7 +195,7 @@ def send(method: str, sid: str, params: dict, *, timeout: float | None,
if timed_out:
_emit_cancel(req, "timeout")
if req.qids is not None:
- return {"answers": locked, "timed_out": True}
+ return {"answers": locked, "outcome": "timed_out"}
return None
@@ -283,7 +283,9 @@ def resolve_response(frame: dict, transport: Any = None) -> bool:
merged = dict(req.locked)
if isinstance(answers, dict):
merged.update(answers)
- req.result = {**req.result, "answers": merged}
+ req.result = {**req.result, "answers": merged, "outcome": "submitted"}
+ elif req.qids:
+ req.result = {"answers": dict(req.locked), "outcome": "cancelled"}
req.answered = True
if req.on_result is not None:
req.on_result(req.result)
@@ -291,10 +293,10 @@ def resolve_response(frame: dict, transport: Any = None) -> bool:
return True
-def lock_answer(request_id: str, question_id: str, answer: str) -> list[str] | None:
- """Lock one batch-clarify answer (update-in-place). Returns the question ids still unanswered;
- the last lock resolves the request with the full ``{"answers"}`` set. ``None`` when no open
- batch has that id (expired or foreign); ``ValueError`` for an unknown question id."""
+def lock_answer(request_id: str, question_id: str, answer: str | None) -> list[str] | None:
+ """Lock one batch-clarify answer (update-in-place; ``None`` = skipped). Returns the question ids
+ still unanswered; the last lock resolves the request with the full ``{"answers"}`` set. ``None``
+ when no open batch has that id (expired or foreign); ``ValueError`` for an unknown question id."""
with _lock:
req = _open.get(request_id)
if req is None or req.qids is None:
@@ -304,7 +306,7 @@ def lock_answer(request_id: str, question_id: str, answer: str) -> list[str] | N
req.locked[question_id] = answer
remaining = [qid for qid in req.qids if qid not in req.locked]
if not remaining:
- req.result, req.answered = {"answers": dict(req.locked)}, True
+ req.result, req.answered = {"answers": dict(req.locked), "outcome": "submitted"}, True
_open.pop(request_id, None)
if not remaining:
req.event.set()
@@ -313,13 +315,17 @@ def lock_answer(request_id: str, question_id: str, answer: str) -> list[str] | N
def cancel(sid: str | None = None, reason: str = "interrupted") -> int:
"""Withdraw open requests — only *sid*'s (session.interrupt must not touch other sessions'), or
- every one when *sid* is None (shutdown). Blocked waits return None; queue-backed requests run
- ``on_result(None)`` so their owner can settle. Returns the number withdrawn."""
+ every one when *sid* is None (shutdown). Blocked waits return None (a batch returns its locked
+ answers with ``outcome: cancelled``); queue-backed requests run ``on_result(None)`` so their
+ owner can settle. Returns the number withdrawn."""
with _lock:
targets = [req for req in _open.values() if sid is None or req.sid == sid]
for req in targets:
_open.pop(req.id, None)
- req.result, req.answered = None, False
+ if req.qids is not None:
+ req.result, req.answered = {"answers": dict(req.locked), "outcome": "cancelled"}, True
+ else:
+ req.result, req.answered = None, False
for req in targets:
if req.on_result is not None:
req.on_result(None)
diff --git a/ui-tui/README.md b/ui-tui/README.md
index 04fea12f431..027fa895133 100644
--- a/ui-tui/README.md
+++ b/ui-tui/README.md
@@ -190,10 +190,12 @@ Notes:
| approval prompt | `Up/Down`, `Enter` | Move and confirm the selected approval choice |
| approval prompt | `o`, `s`, `a`, `d` | Quick-pick `once`, `session`, `always`, `deny` |
| approval prompt | `Esc`, `Ctrl+C` | Deny |
-| clarify prompt with choices | `Up/Down`, `Enter` | Move and confirm the selected choice |
+| clarify prompt with choices | `Up/Down`, `Enter` | Move and lock the selected choice |
| clarify prompt with choices | single-digit number | Quick-pick the matching numbered choice |
| clarify prompt with choices | `Enter` on "Other" | Switch into free-text entry |
-| clarify free-text mode | `Enter` | Submit typed answer |
+| clarify free-text mode | `Enter` | Lock typed answer (empty skips the question) |
+| clarify prompt | `Tab`, `Shift+Tab` | Switch question |
+| clarify prompt | `Esc`, `Ctrl+C` | Cancel the remaining questions |
| sudo / secret prompt | `Enter` | Submit typed value |
| sudo / secret prompt | `Ctrl+C` | Cancel by sending an empty response |
| resume picker | `Up/Down`, `Enter` | Move and resume the selected session |
@@ -204,7 +206,7 @@ Notes:
- Clarify free-text mode and masked prompts use `ink-text-input`, so text editing there follows the library's default bindings rather than `components/textInput.tsx`.
- When a blocking prompt is open, the main chat input hotkeys are suspended.
-- Clarify mode has no dedicated cancel shortcut in the current client. Sudo and secret prompts only expose `Ctrl+C` cancellation from the app-level blocked handler.
+- Sudo and secret prompts only expose `Ctrl+C` cancellation from the app-level blocked handler.
### Interaction rules
@@ -237,7 +239,7 @@ The Python gateway can pause the main loop and ask the client a question. These
`createServerRequestHandler.ts`), not events:
- `approval`: allow once, allow for session, allow always, or deny → `{ choice }`
-- `clarify`: pick from choices or type a custom answer → `{ answer }` (batch: `{ answers }`)
+- `clarify`: one or more questions; each answer is locked with the `clarify.lock` RPC, cancel → `{}`
- `sudo`: masked password entry → `{ value }`
- `secret`: masked value entry for a named env var → `{ value }`
- `session.list`: used by `SessionPicker` for `/resume`
diff --git a/ui-tui/src/__tests__/appChromeBlockedTimers.test.tsx b/ui-tui/src/__tests__/appChromeBlockedTimers.test.tsx
index 028a42f7ac5..eafc6d0cee1 100644
--- a/ui-tui/src/__tests__/appChromeBlockedTimers.test.tsx
+++ b/ui-tui/src/__tests__/appChromeBlockedTimers.test.tsx
@@ -132,9 +132,9 @@ const layoutProps: AppLayoutProps = {
actions: {
activateLiveSession: () => {},
answerApproval: () => {},
- answerClarify: () => {},
answerSecret: () => {},
answerSudo: () => {},
+ cancelClarify: () => {},
clearSelection: () => {},
closeLiveSession: () => Promise.resolve(null),
newLiveSession: () => {},
@@ -370,7 +370,7 @@ describe('status-chrome timers track the current overlay model', () => {
['agents', { agents: true }],
['approval', { approval: { command: 'ls', requestId: 'a-1' } as OverlayState['approval'] }],
['billing', { billing: { kind: 'credits' } as OverlayState['billing'] }],
- ['clarify', { clarify: { question: 'which?', requestId: 'c-1' } as OverlayState['clarify'] }],
+ ['clarify', { clarify: { questions: [{ choices: null, qid: 'q0', question: 'which?' }], requestId: 'c-1' } }],
['confirm', { confirm: { onConfirm: () => {}, prompt: 'sure?' } as OverlayState['confirm'] }],
['journey', { journey: true }],
['secret', { secret: { envVar: 'TOKEN', prompt: 'token?' } as OverlayState['secret'] }],
diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
index 3e374c90175..47475f6e579 100644
--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
@@ -1702,39 +1702,19 @@ describe('createGatewayEventHandler', () => {
).toBe(false)
})
- it('persists an abandoned (timed-out) clarify into the transcript when the clarify tool completes', () => {
- const appended: Msg[] = []
- const onEvent = createGatewayEventHandler(buildCtx(appended))
-
- // Backend clarify timed out: the overlay is still live (Python returned an
- // empty answer), and the clarify tool's own tool.complete then fires.
- patchOverlayState({
- clarify: { choices: ['Scope A', 'Scope B'], question: 'How do you want to scope?', requestId: 'req-1' }
- })
-
- onEvent({ payload: { duration_s: 300, name: 'clarify', tool_id: 'clar-1' }, type: 'tool.complete' } as any)
-
- const record = appended.find(msg => msg.role === 'system' && msg.text.startsWith('ask How do you want to scope?'))
- expect(record).toBeDefined()
- expect(record?.text).toContain('1. Scope A')
- expect(record?.text).toContain('2. Scope B')
- // The live overlay is cleared so it doesn't double-render with the record.
- expect(getOverlayState().clarify).toBeNull()
- })
-
it('only persists an abandoned clarify once even if tool.complete fires twice', () => {
const appended: Msg[] = []
const onEvent = createGatewayEventHandler(buildCtx(appended))
patchOverlayState({
- clarify: { choices: ['A'], question: 'Pick?', requestId: 'req-3' }
+ clarify: { questions: [{ choices: ['A'], qid: 'q0', question: 'Pick?' }], requestId: 'req-3' }
})
onEvent({ payload: { name: 'clarify', tool_id: 'clar-1' }, type: 'tool.complete' } as any)
// A duplicate clarify tool.complete must not re-persist the same prompt.
onEvent({ payload: { name: 'clarify', tool_id: 'clar-1' }, type: 'tool.complete' } as any)
- const records = appended.filter(msg => msg.role === 'system' && msg.text.startsWith('ask Pick?'))
+ const records = appended.filter(msg => msg.role === 'system' && msg.text.startsWith('ask ('))
expect(records).toHaveLength(1)
})
@@ -1745,7 +1725,7 @@ describe('createGatewayEventHandler', () => {
// A clarify is live, but it's a *different* tool that just completed — the
// clarify itself is still pending, so we must not persist or clear it.
patchOverlayState({
- clarify: { choices: ['A', 'B'], question: 'Pick?', requestId: 'req-4' }
+ clarify: { questions: [{ choices: ['A', 'B'], qid: 'q0', question: 'Pick?' }], requestId: 'req-4' }
})
onEvent({ payload: { name: 'search', tool_id: 'tool-1' }, type: 'tool.complete' } as any)
@@ -1758,7 +1738,7 @@ describe('createGatewayEventHandler', () => {
const appended: Msg[] = []
const onEvent = createGatewayEventHandler(buildCtx(appended))
- // Answered path (answerClarify) clears the overlay before the agent's
+ // Answered path (answerClarifyQuestion) clears the overlay before the agent's
// tool.complete arrives, so there's nothing live to persist.
onEvent({ payload: { duration_s: 4.2, name: 'clarify', tool_id: 'clar-1' }, type: 'tool.complete' } as any)
@@ -1923,26 +1903,6 @@ describe('createGatewayEventHandler', () => {
expect(getOverlayState().clarify?.answers).toEqual({ q0: 'a' })
})
- it('drops malformed batch entries and falls back to single-question shape when none survive', () => {
- serverRequest(
- 'clarify',
- {
- choices: ['x', 'y'],
- question: 'Fallback?',
- questions: [
- { qid: '', question: 'no qid' },
- { qid: 'q1', question: ' ' }
- ]
- },
- 'req-bad'
- )
-
- const clarify = getOverlayState().clarify
- expect(clarify?.questions).toBeUndefined()
- expect(clarify?.question).toBe('Fallback?')
- expect(clarify?.choices).toEqual(['x', 'y'])
- })
-
it('persists an abandoned batch clarify with its locked partials on tool.complete', () => {
const appended: Msg[] = []
const onEvent = createGatewayEventHandler(buildCtx(appended))
@@ -1950,8 +1910,6 @@ describe('createGatewayEventHandler', () => {
patchOverlayState({
clarify: {
answers: { q0: 'alpha' },
- choices: null,
- question: '',
questions: [
{ choices: ['alpha', 'beta'], qid: 'q0', question: 'One?' },
{ choices: null, qid: 'q1', question: 'Two?' }
diff --git a/ui-tui/src/__tests__/libTextI18n.test.ts b/ui-tui/src/__tests__/libTextI18n.test.ts
index 3d2c46c4fbc..f1977fa415f 100644
--- a/ui-tui/src/__tests__/libTextI18n.test.ts
+++ b/ui-tui/src/__tests__/libTextI18n.test.ts
@@ -79,14 +79,16 @@ describe('libText catalog swap', () => {
pack({
'libText.attachments.imageToken': '[[ XX-Bild {0} ]]',
'libText.text.showingLiveTail': 'XX-tail',
- 'libText.text.clarifyHead': 'XX-frage {0}',
+ 'libText.text.clarifyHead': 'XX-frage ({0})',
'libText.messages.longMessage': '{0} XX-lang'
})
)
expect(imageToken(2)).toBe('[[ XX-Bild 2 ]]')
expect(boundedLiveRenderText('abcdefghij', { maxChars: 4, maxLines: 10 })).toContain('[XX-tail; omitted')
- expect(formatAbandonedClarify('Why?', null, 'timed out').split('\n')[0]).toBe('XX-frage Why?')
+ expect(formatAbandonedClarify([{ qid: 'q0', question: 'Why?' }], {}, 'timed out').split('\n')[0]).toBe(
+ 'XX-frage (1)'
+ )
expect(userDisplay('word '.repeat(2000))).toContain('XX-lang')
expect(t('libText.text.argsLabel')).toBe('Args')
})
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index 59a1eea2a1e..e0a76c19568 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -23,7 +23,7 @@ import { openExternalUrl } from '../lib/openExternalUrl.js'
import { rpcErrorMessage } from '../lib/rpc.js'
import { topLevelSubagents } from '../lib/subagentTree.js'
import { isPaintableHex, setTerminalBackground, setTerminalForeground } from '../lib/terminalModes.js'
-import { formatAbandonedClarify, formatAbandonedClarifyBatch, formatToolCall } from '../lib/text.js'
+import { formatAbandonedClarify, formatToolCall } from '../lib/text.js'
import { bootSeededPin, invalidateBootBackground, writeBootTheme } from '../lib/themeBoot.js'
import { defaultThemeForCurrentBackground, fromSkin, skinIsLight, type Theme, themeToneHex } from '../theme.js'
import type { Msg, SessionInfo, SubagentProgress } from '../types.js'
@@ -471,8 +471,8 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
// and options vanish from the screen while the agent's follow-up still refers
// to them. The reliable signal is the clarify tool's own tool.complete (and,
// as a backstop, message.complete): at those points the overlay is provably
- // still set on a timeout, but already cleared by answerClarify() on a real
- // answer (so this no-ops there). Flush the question + options into the
+ // still set on a timeout, but already cleared by answerClarifyQuestion() on a
+ // real answer (so this no-ops there). Flush the question into the
// transcript as a persistent system line, then clear the overlay.
const flushAbandonedClarify = () => {
const { clarify } = getOverlayState()
@@ -484,9 +484,7 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
persistedAbandonedClarify.add(clarify.requestId)
appendMessage({
role: 'system',
- text: clarify.questions?.length
- ? formatAbandonedClarifyBatch(clarify.questions, clarify.answers ?? {}, t('gatewayMsg.clarify.timedOut'))
- : formatAbandonedClarify(clarify.question, clarify.choices, t('gatewayMsg.clarify.timedOut'))
+ text: formatAbandonedClarify(clarify.questions, clarify.answers ?? {}, t('gatewayMsg.clarify.timedOut'))
})
patchOverlayState({ clarify: null })
}
@@ -1292,8 +1290,8 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
case 'tool.complete': {
// The clarify tool finishing with its overlay still live means it was
// abandoned (backend _block timed out, empty answer). A real answer
- // clears the overlay in answerClarify() before this fires, so this
- // no-ops there. Persist the question + options so they don't vanish.
+ // clears the overlay in answerClarifyQuestion() before this fires, so
+ // this no-ops there.
if (!ev.payload) {
return
}
diff --git a/ui-tui/src/app/createServerRequestHandler.ts b/ui-tui/src/app/createServerRequestHandler.ts
index 8ab8a78f4cf..2e4e8b84da3 100644
--- a/ui-tui/src/app/createServerRequestHandler.ts
+++ b/ui-tui/src/app/createServerRequestHandler.ts
@@ -1,7 +1,7 @@
import type { ServerRequest } from '@hermes/shared/json-rpc-channel'
import { t } from '../i18n/runtime.js'
-import type { ClarifyBatchQuestion } from '../types.js'
+import type { ClarifyQuestion } from '../types.js'
import { patchOverlayState } from './overlayStore.js'
import { rememberServerRequest } from './serverRequestStore.js'
@@ -42,7 +42,7 @@ export function createServerRequestHandler(ctx: ServerRequestHandlerContext): (r
switch (request.method) {
case 'clarify': {
- const batch: ClarifyBatchQuestion[] = (Array.isArray(p.questions) ? (p.questions as unknown[]) : [])
+ const questions: ClarifyQuestion[] = (Array.isArray(p.questions) ? (p.questions as unknown[]) : [])
.map(raw => (raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}))
.filter(q => str(q.qid) && str(q.question).trim())
.map(q => ({
@@ -52,20 +52,22 @@ export function createServerRequestHandler(ctx: ServerRequestHandlerContext): (r
question: str(q.question).trim()
}))
+ if (!questions.length) {
+ request.respond({})
+
+ return true
+ }
+
const answers =
p.answers && typeof p.answers === 'object'
? Object.fromEntries(
- Object.entries(p.answers as Record<string, unknown>).filter(
- (entry): entry is [string, string] => typeof entry[1] === 'string'
- )
+ Object.entries(p.answers as Record<string, unknown>)
+ .map(([qid, answer]): [string, unknown] => [qid, answer === null ? '' : answer])
+ .filter((entry): entry is [string, string] => typeof entry[1] === 'string')
)
: {}
- patchOverlayState({
- clarify: batch.length
- ? { answers, choices: null, question: '', questions: batch, requestId: request.id }
- : { choices: strList(p.choices), question: str(p.question), requestId: request.id }
- })
+ patchOverlayState({ clarify: { answers, questions, requestId: request.id } })
open(request, t('session.status.waitingForInput'))
return true
diff --git a/ui-tui/src/app/interfaces.ts b/ui-tui/src/app/interfaces.ts
index f3bf26f7799..6bea7c363f8 100644
--- a/ui-tui/src/app/interfaces.ts
+++ b/ui-tui/src/app/interfaces.ts
@@ -443,8 +443,8 @@ export interface UseComposerStateResult {
}
export interface InputHandlerActions {
- answerClarify: (answer: string) => void
appendMessage: (msg: Msg) => void
+ cancelClarify: () => void
die: () => void
dispatchSubmission: (full: string) => void
guardBusySessionSwitch: (what?: string) => boolean
@@ -572,11 +572,11 @@ export interface SlashHandlerContext {
export interface AppLayoutActions {
answerApproval: (choice: string) => void
- answerClarify: (answer: string) => void
answerClarifyQuestion: (qid: string, answer: string) => void
answerSecret: (value: string) => void
answerSudo: (pw: string) => void
answerVaultUnlock: (password: string) => void
+ cancelClarify: () => void
clearSelection: () => void
activateLiveSession: (id: string) => void
closeLiveSession: (id: string) => Promise<null | SessionCloseResponse>
@@ -641,7 +641,7 @@ export interface AppOverlaysProps {
compIdx: number
completions: CompletionItem[]
onApprovalChoice: (choice: string) => void
- onClarifyAnswer: (value: string) => void
+ onClarifyCancel: () => void
onClarifyQuestionAnswer: (qid: string, value: string) => void
onActiveSessionSelect: (sessionId: string) => void
onActiveSessionClose: (sessionId: string) => Promise<null | SessionCloseResponse>
diff --git a/ui-tui/src/app/useInputHandlers.ts b/ui-tui/src/app/useInputHandlers.ts
index 8bd02fffaf2..76febe62ca7 100644
--- a/ui-tui/src/app/useInputHandlers.ts
+++ b/ui-tui/src/app/useInputHandlers.ts
@@ -251,7 +251,7 @@ export function useInputHandlers(ctx: InputHandlerContext): InputHandlerResult {
const cancelOverlayFromCtrlC = () => {
if (overlay.clarify) {
- return actions.answerClarify('')
+ return actions.cancelClarify()
}
if (overlay.approval) {
diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.ts
index e29062b7837..46230d3e167 100644
--- a/ui-tui/src/app/useMainApp.ts
+++ b/ui-tui/src/app/useMainApp.ts
@@ -42,8 +42,8 @@ import { asRpcResult, rpcErrorMessage } from '../lib/rpc.js'
import { terminalParityHints } from '../lib/terminalParity.js'
import {
buildToolTrailLine,
+ clarifyAnswerText,
formatAbandonedClarify,
- formatAbandonedClarifyBatch,
sameToolTrailGroup,
toolTrailLabel
} from '../lib/text.js'
@@ -745,54 +745,34 @@ export function useMainApp(gw: GatewayClient) {
}
}, [rpc, stdout, ui.sid])
- const answerClarify = useCallback(
- (answer: string) => {
- const clarify = overlay.clarify
-
- if (!clarify) {
- return
- }
+ const cancelClarify = useCallback(() => {
+ const clarify = overlay.clarify
- const label = toolTrailLabel('clarify')
+ if (!clarify) {
+ return
+ }
- turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))
- patchTurnState({ turnTrail: turnController.turnTools })
+ const label = toolTrailLabel('clarify')
- if (!respondToServerRequest(clarify.requestId, { answer })) {
- // The request already expired (request.cancel raced the keystroke): nothing to answer.
- patchOverlayState({ clarify: null })
+ turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))
+ patchTurnState({ turnTrail: turnController.turnTools })
- return
- }
+ if (!respondToServerRequest(clarify.requestId, {})) {
+ // The request already expired (request.cancel raced the keystroke): nothing to answer.
+ patchOverlayState({ clarify: null })
- {
- if (answer) {
- turnController.persistedToolLabels.add(label)
- appendMessage({
- kind: 'trail',
- role: 'system',
- text: '',
- tools: [buildToolTrailLine('clarify', clarify.question)]
- })
- appendMessage({ role: 'user', text: answer })
- patchUiState({ status: 'running…' })
- } else {
- // Esc / Ctrl+C cancel: persist the question + options as a system
- // line (not a transient "prompt cancelled" flash) so the prompt
- // survives on screen as standard output, matching the timeout path.
- appendMessage({
- role: 'system',
- text: clarify.questions?.length
- ? formatAbandonedClarifyBatch(clarify.questions, clarify.answers ?? {}, 'cancelled')
- : formatAbandonedClarify(clarify.question, clarify.choices, 'cancelled')
- })
- }
+ return
+ }
- patchOverlayState({ clarify: null })
- }
- },
- [appendMessage, overlay.clarify]
- )
+ // Esc / Ctrl+C cancel: persist the question as a system line (not a
+ // transient "prompt cancelled" flash) so the prompt survives on screen as
+ // standard output, matching the timeout path.
+ appendMessage({
+ role: 'system',
+ text: formatAbandonedClarify(clarify.questions, clarify.answers ?? {}, 'cancelled')
+ })
+ patchOverlayState({ clarify: null })
+ }, [appendMessage, overlay.clarify])
// Lock one answer of a batch clarify (`clarify.lock` RPC). The overlay stays
// up until the server reports no remaining questions — the final lock
@@ -801,12 +781,12 @@ export function useMainApp(gw: GatewayClient) {
(qid: string, answer: string) => {
const clarify = overlay.clarify
- if (!clarify?.questions?.length) {
+ if (!clarify) {
return
}
rpc<ClarifyLockResponse>('clarify.lock', {
- answer,
+ answer: answer.trim() ? answer : null,
question_id: qid,
request_id: clarify.requestId
}).then(r => {
@@ -828,8 +808,7 @@ export function useMainApp(gw: GatewayClient) {
return
}
- // Batch complete: persist the whole Q&A set as one user-visible
- // block (mirrors the single-question trail + answer lines).
+ // Batch complete: persist the whole Q&A set as one user-visible block.
const label = toolTrailLabel('clarify')
turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))
@@ -839,13 +818,14 @@ export function useMainApp(gw: GatewayClient) {
kind: 'trail',
role: 'system',
text: '',
- tools: [buildToolTrailLine('clarify', clarifyQuestionCountLabel(clarify.questions!.length))]
+ tools: [buildToolTrailLine('clarify', clarifyQuestionCountLabel(clarify.questions.length))]
})
appendMessage({
role: 'user',
- text: clarify
- .questions!.map(
- q => `${q.question} → ${answers[q.qid]?.trim() ? answers[q.qid] : t('session.main.skipped')}`
+ text: clarify.questions
+ .map(
+ q =>
+ `${q.question} → ${answers[q.qid]?.trim() ? clarifyAnswerText(answers[q.qid]!, q.multiSelect) : t('session.main.skipped')}`
)
.join('\n')
})
@@ -897,8 +877,8 @@ export function useMainApp(gw: GatewayClient) {
const { pagerPageSize } = useInputHandlers({
actions: {
- answerClarify,
appendMessage,
+ cancelClarify,
die,
dispatchSubmission,
guardBusySessionSwitch: session.guardBusySessionSwitch,
@@ -1318,11 +1298,11 @@ export function useMainApp(gw: GatewayClient) {
activateLiveSession: session.activateLiveSession,
closeLiveSession,
answerApproval,
- answerClarify,
answerClarifyQuestion,
answerSecret,
answerSudo,
answerVaultUnlock,
+ cancelClarify,
clearSelection,
newLiveSession: () => session.newLiveSession(),
newPromptSession,
@@ -1342,11 +1322,11 @@ export function useMainApp(gw: GatewayClient) {
}),
[
answerApproval,
- answerClarify,
answerClarifyQuestion,
answerSecret,
answerSudo,
answerVaultUnlock,
+ cancelClarify,
clearSelection,
closeLiveSession,
newPromptSession,
diff --git a/ui-tui/src/components/appLayout.tsx b/ui-tui/src/components/appLayout.tsx
index bc65d45faaa..ecba126148d 100644
--- a/ui-tui/src/components/appLayout.tsx
+++ b/ui-tui/src/components/appLayout.tsx
@@ -616,7 +616,7 @@ export const AppLayout = memo(function AppLayout({
<PromptZone
cols={composer.cols}
onApprovalChoice={actions.answerApproval}
- onClarifyAnswer={actions.answerClarify}
+ onClarifyCancel={actions.cancelClarify}
onClarifyQuestionAnswer={actions.answerClarifyQuestion}
onSecretSubmit={actions.answerSecret}
onSudoSubmit={actions.answerSudo}
diff --git a/ui-tui/src/components/appOverlays.tsx b/ui-tui/src/components/appOverlays.tsx
index 305d6451d88..d0ed5b7424b 100644
--- a/ui-tui/src/components/appOverlays.tsx
+++ b/ui-tui/src/components/appOverlays.tsx
@@ -59,7 +59,7 @@ function PromptCell({ children, cols, id }: { children: ReactNode; cols: number;
export function PromptZone({
cols,
onApprovalChoice,
- onClarifyAnswer,
+ onClarifyCancel,
onClarifyQuestionAnswer,
onSecretSubmit,
onSudoSubmit,
@@ -68,7 +68,7 @@ export function PromptZone({
AppOverlaysProps,
| 'cols'
| 'onApprovalChoice'
- | 'onClarifyAnswer'
+ | 'onClarifyCancel'
| 'onClarifyQuestionAnswer'
| 'onSecretSubmit'
| 'onSudoSubmit'
@@ -147,8 +147,7 @@ export function PromptZone({
<PromptCell cols={cols} id="clarify">
<ClarifyPrompt
cols={cols}
- onAnswer={onClarifyAnswer}
- onCancel={() => onClarifyAnswer('')}
+ onCancel={onClarifyCancel}
onQuestionAnswer={onClarifyQuestionAnswer}
req={overlay.clarify}
t={theme}
diff --git a/ui-tui/src/components/prompts.tsx b/ui-tui/src/components/prompts.tsx
index 9e0f845b195..6a5066d80f9 100644
--- a/ui-tui/src/components/prompts.tsx
+++ b/ui-tui/src/components/prompts.tsx
@@ -3,8 +3,7 @@ import { useEffect, useState } from 'react'
import { messages } from '../i18n/runtime.js'
import { useT } from '../i18n/useT.js'
-import { isMac } from '../lib/platform.js'
-import { clarifyBatchRevisitState } from '../lib/text.js'
+import { clarifyAnswerText, clarifyRevisitState } from '../lib/text.js'
import type { Theme } from '../theme.js'
import type { ApprovalReq, ClarifyReq, ConfirmReq } from '../types.js'
@@ -148,81 +147,87 @@ export function ApprovalPrompt({ cols = 80, onChoice, req, t }: ApprovalPromptPr
)
}
-export function ClarifyPrompt({ cols = 80, onAnswer, onCancel, onQuestionAnswer, req, t }: ClarifyPromptProps) {
+export function ClarifyPrompt({ cols = 80, onCancel, onQuestionAnswer, req, t }: ClarifyPromptProps) {
const T = useT()
const [sel, setSel] = useState(0)
const [custom, setCustom] = useState('')
const [typing, setTyping] = useState(false)
- const choices = req.choices ?? []
- const batch = req.questions ?? []
- const isBatch = batch.length > 0
+ const [picked, setPicked] = useState<string[]>([])
+ const questions = req.questions
// ── Batch (A-compact) state: status list + one expanded active question.
// `active` walks the QUESTION list (Tab/Shift-Tab cycle it, any order);
// `sel` is reused as the cursor within the active question's choice rows.
const answers = req.answers ?? {}
- const firstUnanswered = batch.findIndex(q => answers[q.qid] === undefined)
+ const firstUnanswered = questions.findIndex(q => answers[q.qid] === undefined)
const [active, setActive] = useState(Math.max(0, firstUnanswered))
const moveActive = (delta: number) => {
- const next = (active + delta + batch.length) % batch.length
- const question = batch[next]
+ const next = (active + delta + questions.length) % questions.length
+ const question = questions[next]
+
// Re-visit restore, same model as the CLI panel: a choice answer puts
// the cursor back on its row; a typed answer lands on Other with the
// text staged so Enter edits it instead of retyping.
- const restored = clarifyBatchRevisitState(question?.choices ?? [], question ? answers[question.qid] : undefined)
+ const restored = clarifyRevisitState(
+ question?.choices ?? [],
+ question ? answers[question.qid] : undefined,
+ question?.multiSelect
+ )
setActive(next)
setSel(restored.sel)
setCustom(restored.custom)
setTyping(false)
+ setPicked(restored.picked)
}
// After a lock the overlay is re-patched with the new answers map — jump
// the cursor to the next unanswered question (stay put when editing).
useEffect(() => {
- if (!isBatch) {
- return
- }
-
- const current = batch[active]
+ const current = questions[active]
if (current && answers[current.qid] === undefined) {
return
}
- const next = batch.findIndex(q => answers[q.qid] === undefined)
+ const next = questions.findIndex(q => answers[q.qid] === undefined)
if (next >= 0) {
setActive(next)
setSel(0)
setCustom('')
setTyping(false)
+ setPicked([])
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- keyed by the answers map only
}, [req.answers])
- const heading = (
- <Text bold>
- <Text color={t.color.accent}>ask</Text>
- <Text color={t.color.text}> {isBatch ? `${batch.length} questions` : req.question}</Text>
- </Text>
- )
-
- const activeQuestion = isBatch ? batch[active] : undefined
- const activeChoices = activeQuestion ? (activeQuestion.choices ?? []) : choices
- const answeredCount = isBatch ? batch.filter(q => answers[q.qid] !== undefined).length : 0
- const remainingCount = isBatch ? batch.length - answeredCount : 0
+ const activeQuestion = questions[active]
+ const activeChoices = activeQuestion?.choices ?? []
+ const multi = activeQuestion?.multiSelect ?? false
+ const answeredCount = questions.filter(q => answers[q.qid] !== undefined).length
+ const remainingCount = questions.length - answeredCount
const lockActive = (value: string) => {
if (activeQuestion) {
- onQuestionAnswer?.(activeQuestion.qid, value)
+ onQuestionAnswer(activeQuestion.qid, value)
setSel(0)
setCustom('')
setTyping(false)
+ setPicked([])
}
}
+ const lockPicked = (extra: string[]) => {
+ const values = [...picked, ...extra.map(v => v.trim()).filter(Boolean)]
+
+ lockActive(values.length ? JSON.stringify(values) : '')
+ }
+
+ const togglePick = (choice: string) =>
+ setPicked(current => (current.includes(choice) ? current.filter(v => v !== choice) : [...current, choice]))
+
useInput((ch, key) => {
if (key.escape) {
if (typing) {
@@ -240,54 +245,22 @@ export function ClarifyPrompt({ cols = 80, onAnswer, onCancel, onQuestionAnswer,
return
}
- if (isBatch) {
- // Tab / Shift-Tab cycle the active question (with wrap) — the
- // selected question is always the expanded one, like the CLI panel.
- if (key.tab) {
- moveActive(key.shift ? -1 : 1)
-
- return
- }
-
- if (!activeQuestion) {
- return
- }
-
- if (activeChoices.length === 0) {
- // Open-ended question: any keypress starts typing (TextInput below).
- setTyping(true)
-
- return
- }
-
- if (key.upArrow && sel > 0) {
- setSel(s => s - 1)
- }
-
- if (key.downArrow && sel < activeChoices.length) {
- setSel(s => s + 1)
- }
-
- if (key.return) {
- if (sel === activeChoices.length) {
- setTyping(true)
- } else if (activeChoices[sel]) {
- lockActive(activeChoices[sel]!)
- }
+ // Tab / Shift-Tab cycle the active question (with wrap) — the
+ // selected question is always the expanded one, like the CLI panel.
+ if (key.tab) {
+ moveActive(key.shift ? -1 : 1)
- return
- }
-
- const n = parseInt(ch)
-
- if (n >= 1 && n <= activeChoices.length) {
- lockActive(activeChoices[n - 1]!)
- }
+ return
+ }
+ if (!activeQuestion) {
return
}
- if (!choices.length) {
+ if (activeChoices.length === 0) {
+ // Open-ended question: any keypress starts typing (TextInput below).
+ setTyping(true)
+
return
}
@@ -295,126 +268,115 @@ export function ClarifyPrompt({ cols = 80, onAnswer, onCancel, onQuestionAnswer,
setSel(s => s - 1)
}
- if (key.downArrow && sel < choices.length) {
+ if (key.downArrow && sel < activeChoices.length) {
setSel(s => s + 1)
}
if (key.return) {
- sel === choices.length ? setTyping(true) : choices[sel] && onAnswer(choices[sel]!)
+ if (sel === activeChoices.length) {
+ setTyping(true)
+ } else if (multi) {
+ lockPicked(picked.length ? [] : [activeChoices[sel]!])
+ } else if (activeChoices[sel]) {
+ lockActive(activeChoices[sel]!)
+ }
+
+ return
+ }
+
+ if (multi && ch === ' ' && sel < activeChoices.length) {
+ togglePick(activeChoices[sel]!)
+
+ return
}
const n = parseInt(ch)
- if (n >= 1 && n <= choices.length) {
- onAnswer(choices[n - 1]!)
+ if (n >= 1 && n <= activeChoices.length) {
+ if (multi) {
+ togglePick(activeChoices[n - 1]!)
+ } else {
+ lockActive(activeChoices[n - 1]!)
+ }
}
})
- if (isBatch) {
- const enterAction = remainingCount === 1 ? T.prompt.clarify.confirmAndContinue : T.prompt.clarify.lockAnswer
- const hint = typing ? T.prompt.clarify.batchTypingHint(enterAction) : T.prompt.clarify.batchHint(enterAction)
+ const enterAction = remainingCount === 1 ? T.prompt.clarify.confirmAndContinue : T.prompt.clarify.lockAnswer
- return (
- <Box flexDirection="column">
- {heading}
+ const hint = typing
+ ? T.prompt.clarify.typingHint(enterAction)
+ : multi
+ ? `${T.prompt.clarify.toggle} · ${T.prompt.clarify.hint(enterAction)}`
+ : T.prompt.clarify.hint(enterAction)
- {batch.map((q, i) => {
- const answer = answers[q.qid]
- const isActive = i === active
- const marker = answer !== undefined ? '✓' : isActive ? '▸' : '·'
+ return (
+ <Box flexDirection="column">
+ <Text bold>
+ <Text color={t.color.accent}>ask</Text>
+ <Text color={t.color.text}>
+ {' '}
+ {questions.length === 1
+ ? T.session.main.clarifyQuestionsOne('1')
+ : T.session.main.clarifyQuestionsOther(String(questions.length))}
+ </Text>
+ </Text>
- return (
- <Box flexDirection="column" key={q.qid}>
- <Text>
- <Text bold={isActive} color={isActive ? t.color.text : t.color.muted}>
- {marker} {q.question}
- </Text>
+ {questions.map((q, i) => {
+ const answer = answers[q.qid]
+ const isActive = i === active
+ const marker = answer !== undefined ? '✓' : isActive ? '▸' : '·'
+
+ return (
+ <Box flexDirection="column" key={q.qid}>
+ <Text>
+ <Text bold={isActive} color={isActive ? t.color.text : t.color.muted}>
+ {marker} {q.question}
</Text>
+ </Text>
+
+ {answer !== undefined ? (
+ // The locked answer on its own line, in the ok color, so the
+ // current answers stay readable while Tab walks the list.
+ <Box paddingLeft={2}>
+ <Text color={answer ? t.color.ok : t.color.muted} italic={!answer}>
+ {answer ? clarifyAnswerText(answer, q.multiSelect) : T.prompt.clarify.skipped}
+ </Text>
+ </Box>
+ ) : null}
- {answer !== undefined ? (
- // The locked answer on its own line, in the ok color, so the
- // current answers stay readable while Tab walks the list.
+ {isActive ? (
+ typing || activeChoices.length === 0 ? (
<Box paddingLeft={2}>
- <Text color={answer ? t.color.ok : t.color.muted} italic={!answer}>
- {answer || T.prompt.clarify.skipped}
- </Text>
+ <Text color={t.color.label}>{'> '}</Text>
+ <TextInput
+ color={t.color.text}
+ columns={Math.max(20, cols - 8)}
+ onChange={setCustom}
+ onSubmit={value => (multi ? lockPicked([value]) : lockActive(value))}
+ value={custom}
+ />
</Box>
- ) : null}
-
- {isActive ? (
- typing || activeChoices.length === 0 ? (
- <Box paddingLeft={2}>
- <Text color={t.color.label}>{'> '}</Text>
- <TextInput
- color={t.color.text}
- columns={Math.max(20, cols - 8)}
- onChange={setCustom}
- onSubmit={lockActive}
- value={custom}
- />
- </Box>
- ) : (
- <Box flexDirection="column" paddingLeft={2}>
- {[...activeChoices, T.prompt.clarify.other].map((c, ci) => (
- <Text key={ci}>
- <Text color={t.color.muted} {...chipRowProps(t, sel === ci)}>
- {sel === ci ? '▸ ' : ' '}
- {ci + 1}. {c}
- </Text>
+ ) : (
+ <Box flexDirection="column" paddingLeft={2}>
+ {[...activeChoices, T.prompt.clarify.other].map((c, ci) => (
+ <Text key={ci}>
+ <Text color={t.color.muted} {...chipRowProps(t, sel === ci)}>
+ {sel === ci ? '▸ ' : ' '}
+ {multi && ci < activeChoices.length ? (picked.includes(c) ? '[x] ' : '[ ] ') : ''}
+ {ci + 1}. {c}
</Text>
- ))}
- </Box>
- )
- ) : null}
- </Box>
- )
- })}
-
- <Text color={t.color.muted}>
- {answeredCount}/{batch.length} answered · {hint}
- </Text>
- </Box>
- )
- }
-
- if (typing || !choices.length) {
- return (
- <Box flexDirection="column">
- {heading}
-
- <Box>
- <Text color={t.color.label}>{'> '}</Text>
- <TextInput
- color={t.color.text}
- columns={Math.max(20, cols - 6)}
- onChange={setCustom}
- onSubmit={onAnswer}
- value={custom}
- />
- </Box>
-
- <Text color={t.color.muted}>
- {T.prompt.clarify.typingHint(choices.length ? T.prompt.clarify.back : T.prompt.clarify.cancel)}{' '}
- {isMac ? T.prompt.clarify.macClipboardHint : T.prompt.clarify.ctrlCCancel}
- </Text>
- </Box>
- )
- }
-
- return (
- <Box flexDirection="column">
- {heading}
-
- {[...choices, T.prompt.clarify.other].map((c, i) => (
- <Text key={i}>
- <Text color={t.color.muted} {...chipRowProps(t, sel === i)}>
- {sel === i ? '▸ ' : ' '}
- {i + 1}. {c}
- </Text>
- </Text>
- ))}
-
- <Text color={t.color.muted}>↑/↓ select · Enter confirm · 1-{choices.length} quick pick · Esc/Ctrl+C cancel</Text>
+ </Text>
+ ))}
+ </Box>
+ )
+ ) : null}
+ </Box>
+ )
+ })}
+
+ <Text color={t.color.muted}>
+ {answeredCount}/{questions.length} answered · {hint}
+ </Text>
</Box>
)
}
@@ -491,10 +453,8 @@ interface ApprovalPromptProps {
interface ClarifyPromptProps {
cols?: number
- onAnswer: (s: string) => void
onCancel: () => void
- /** Batch mode: lock one question's answer (clarify.respond + question_id). */
- onQuestionAnswer?: (qid: string, s: string) => void
+ onQuestionAnswer: (qid: string, s: string) => void
req: ClarifyReq
t: Theme
}
diff --git a/ui-tui/src/i18n/en/libText.ts b/ui-tui/src/i18n/en/libText.ts
index fb9af22a2f9..22c55b7c3fa 100644
--- a/ui-tui/src/i18n/en/libText.ts
+++ b/ui-tui/src/i18n/en/libText.ts
@@ -109,18 +109,14 @@ export const libTextEn = {
errorLabel: 'Error',
/** {0} = pre-formatted line count; sits inside a `[[ … ]]` composer token */
pasteLinesChip: (count: string) => `[${count} lines]`,
- /** {0} = the question text */
- clarifyHead: (question: string) => `ask ${question}`,
- /** {0} = why the prompt ended ("timed out", "cancelled") */
- clarifyNoSelection: (reason: string) => `(${reason} — no selection)`,
/** {0} = question count */
- clarifyBatchHead: (count: string) => `ask (${count} questions)`,
+ clarifyHead: (count: string) => `ask (${count} questions)`,
/** {0} = question, {1} = locked answer */
clarifyAnswered: (question: string, answer: string) => `✓ ${question} → ${answer}`,
/** {0} = question */
clarifyUnanswered: (question: string) => `· ${question} (no answer)`,
/** {0} = why the batch ended */
- clarifyBatchReason: (reason: string) => `(${reason})`
+ clarifyReason: (reason: string) => `(${reason})`
},
// lib/agentRows.ts — docked agents panel row fallbacks.
diff --git a/ui-tui/src/i18n/en/overlays.ts b/ui-tui/src/i18n/en/overlays.ts
index 8d43ac2b5c2..4bfee29996a 100644
--- a/ui-tui/src/i18n/en/overlays.ts
+++ b/ui-tui/src/i18n/en/overlays.ts
@@ -15,16 +15,12 @@ export const overlaysEn = {
clarify: {
other: 'Other (type your answer)',
skipped: '(skipped)',
+ toggle: 'Space toggle',
confirmAndContinue: 'confirm and continue',
lockAnswer: 'lock answer',
- batchTypingHint: (enterAction: string) => `Enter ${enterAction} · Esc back`,
- batchHint: (enterAction: string) =>
- `↑/↓ select · Enter ${enterAction} · Tab/Shift+Tab switch question · Esc/Ctrl+C cancel`,
- typingHint: (escAction: string) => `Enter send · Esc ${escAction} ·`,
- back: 'back',
- cancel: 'cancel',
- macClipboardHint: 'Cmd+C copy · Cmd+V paste · Ctrl+C cancel',
- ctrlCCancel: 'Ctrl+C cancel'
+ typingHint: (enterAction: string) => `Enter ${enterAction} · Esc back`,
+ hint: (enterAction: string) =>
+ `↑/↓ select · Enter ${enterAction} · Tab/Shift+Tab switch question · Esc/Ctrl+C cancel`
},
confirm: {
confirm: 'Yes',
diff --git a/ui-tui/src/lib/text.test.ts b/ui-tui/src/lib/text.test.ts
index 3393842dfed..7f45ba6f55e 100644
--- a/ui-tui/src/lib/text.test.ts
+++ b/ui-tui/src/lib/text.test.ts
@@ -2,12 +2,7 @@ import { describe, expect, it } from 'vitest'
import { t } from '../i18n/runtime.js'
-import {
- clarifyBatchRevisitState,
- formatAbandonedClarify,
- formatAbandonedClarifyBatch,
- stripTrailingPasteNewlines
-} from './text.js'
+import { clarifyRevisitState, formatAbandonedClarify, stripTrailingPasteNewlines } from './text.js'
describe('stripTrailingPasteNewlines', () => {
it('removes trailing newline runs from pasted text', () => {
@@ -25,41 +20,8 @@ describe('stripTrailingPasteNewlines', () => {
})
describe('formatAbandonedClarify', () => {
- it('renders the question, numbered options, and reason', () => {
- const out = formatAbandonedClarify('How do you want to scope?', ['Option A', 'Option B', 'Option C'], 'timed out')
-
- expect(out).toBe(
- [
- t('libText.text.clarifyHead', 'How do you want to scope?'),
- ' 1. Option A',
- ' 2. Option B',
- ' 3. Option C',
- ` ${t('libText.text.clarifyNoSelection', 'timed out')}`
- ].join('\n')
- )
- })
-
- it('handles a prompt with no choices (free-text clarify)', () => {
- const out = formatAbandonedClarify('What is the target branch?', null, 'cancelled')
-
- expect(out).toBe(
- [
- t('libText.text.clarifyHead', 'What is the target branch?'),
- ` ${t('libText.text.clarifyNoSelection', 'cancelled')}`
- ].join('\n')
- )
- })
-
- it('trims surrounding whitespace on the question', () => {
- const out = formatAbandonedClarify(' trailing space ', [], 'timed out')
-
- expect(out.split('\n')[0]).toBe(t('libText.text.clarifyHead', 'trailing space'))
- })
-})
-
-describe('formatAbandonedClarifyBatch', () => {
it('shows locked answers and marks unanswered questions', () => {
- const out = formatAbandonedClarifyBatch(
+ const out = formatAbandonedClarify(
[
{ qid: 'q0', question: 'One?' },
{ qid: 'q1', question: 'Two?' }
@@ -70,36 +32,36 @@ describe('formatAbandonedClarifyBatch', () => {
expect(out).toBe(
[
- t('libText.text.clarifyBatchHead', 2),
+ t('libText.text.clarifyHead', 2),
` ${t('libText.text.clarifyAnswered', 'One?', 'alpha')}`,
` ${t('libText.text.clarifyUnanswered', 'Two?')}`,
- ` ${t('libText.text.clarifyBatchReason', 'timed out')}`
+ ` ${t('libText.text.clarifyReason', 'timed out')}`
].join('\n')
)
})
it('treats an empty locked answer as unanswered in the record', () => {
- const out = formatAbandonedClarifyBatch([{ qid: 'q0', question: 'One?' }], { q0: '' }, 'cancelled')
+ const out = formatAbandonedClarify([{ qid: 'q0', question: 'One?' }], { q0: '' }, 'cancelled')
expect(out).toContain(t('libText.text.clarifyUnanswered', 'One?'))
})
})
-describe('clarifyBatchRevisitState', () => {
+describe('clarifyRevisitState', () => {
it('restores the cursor onto a choice answer', () => {
- expect(clarifyBatchRevisitState(['red', 'blue'], 'blue')).toEqual({ custom: '', sel: 1 })
+ expect(clarifyRevisitState(['red', 'blue'], 'blue')).toEqual({ custom: '', picked: [], sel: 1 })
})
it('stages a typed answer on the Other row for editing', () => {
- expect(clarifyBatchRevisitState(['red', 'blue'], 'chartreuse')).toEqual({ custom: 'chartreuse', sel: 2 })
+ expect(clarifyRevisitState(['red', 'blue'], 'chartreuse')).toEqual({ custom: 'chartreuse', picked: [], sel: 2 })
})
it('stages a typed answer for an open-ended question (no choices)', () => {
- expect(clarifyBatchRevisitState([], 'free text')).toEqual({ custom: 'free text', sel: 0 })
+ expect(clarifyRevisitState([], 'free text')).toEqual({ custom: 'free text', picked: [], sel: 0 })
})
it('resets cleanly for unanswered and empty answers', () => {
- expect(clarifyBatchRevisitState(['red'], undefined)).toEqual({ custom: '', sel: 0 })
- expect(clarifyBatchRevisitState(['red'], '')).toEqual({ custom: '', sel: 0 })
+ expect(clarifyRevisitState(['red'], undefined)).toEqual({ custom: '', picked: [], sel: 0 })
+ expect(clarifyRevisitState(['red'], '')).toEqual({ custom: '', picked: [], sel: 0 })
})
})
diff --git a/ui-tui/src/lib/text.ts b/ui-tui/src/lib/text.ts
index 923ef84cfe9..9197a7e7e5c 100644
--- a/ui-tui/src/lib/text.ts
+++ b/ui-tui/src/lib/text.ts
@@ -345,27 +345,13 @@ export const estimateRows = (text: string, w: number, compact = false) => {
/**
* Render an unanswered clarify prompt (timed out, or cancelled with Esc/Ctrl+C)
- * as a persistent transcript block. The live `ClarifyPrompt` overlay is torn
- * down the moment the turn settles, so without this the question + options
- * vanish from the screen while the agent's follow-up still refers to "the
- * options above". Mirrors the option formatting in ClarifyPrompt (the same
- * 1-based numbered list) so the persisted record reads identically to what was
- * on screen. `reason` states why the prompt ended ("timed out", "cancelled").
+ * as a persistent transcript block. Every question on its own line, answered
+ * ones keeping their locked answer (partials survive a timeout server-side, so
+ * the record must show what was actually sent). `reason` states why the
+ * prompt ended ("timed out", "cancelled").
*/
-export const formatAbandonedClarify = (question: string, choices: string[] | null, reason: string) => {
- const head = t('libText.text.clarifyHead', question.trim())
- const opts = (choices ?? []).map((c, i) => ` ${i + 1}. ${c}`)
-
- return [head, ...opts, ` ${t('libText.text.clarifyNoSelection', reason)}`].join('\n')
-}
-
-/**
- * Batch counterpart of `formatAbandonedClarify`: every question on its own
- * line, answered ones keeping their locked answer (partials survive a
- * timeout server-side, so the record must show what was actually sent).
- */
-export const formatAbandonedClarifyBatch = (
- questions: { qid: string; question: string }[],
+export const formatAbandonedClarify = (
+ questions: { multiSelect?: boolean; qid: string; question: string }[],
answers: Record<string, string>,
reason: string
) => {
@@ -373,17 +359,27 @@ export const formatAbandonedClarifyBatch = (
const answer = answers[q.qid]
return answer
- ? ` ${t('libText.text.clarifyAnswered', q.question, answer)}`
+ ? ` ${t('libText.text.clarifyAnswered', q.question, clarifyAnswerText(answer, q.multiSelect))}`
: ` ${t('libText.text.clarifyUnanswered', q.question)}`
})
return [
- t('libText.text.clarifyBatchHead', questions.length),
+ t('libText.text.clarifyHead', questions.length),
...lines,
- ` ${t('libText.text.clarifyBatchReason', reason)}`
+ ` ${t('libText.text.clarifyReason', reason)}`
].join('\n')
}
+const clarifyAnswerItems = (answer: string): null | string[] => {
+ try {
+ const parsed: unknown = JSON.parse(answer)
+
+ return Array.isArray(parsed) ? parsed.map(String) : null
+ } catch {
+ return null
+ }
+}
+
/**
* Cursor/draft restore for re-visiting an answered batch clarify question
* (Tab/Shift-Tab): a choice answer puts the cursor back on its row; an
@@ -391,21 +387,36 @@ export const formatAbandonedClarifyBatch = (
* the Other row (index = choices.length) with the text staged for editing.
* Unanswered questions restore to a clean cursor.
*/
-export const clarifyBatchRevisitState = (
+export const clarifyRevisitState = (
choices: readonly string[],
- answer: string | undefined
-): { custom: string; sel: number } => {
+ answer: string | undefined,
+ multiSelect = false
+): { custom: string; picked: string[]; sel: number } => {
if (answer === undefined || answer === '') {
- return { custom: '', sel: 0 }
+ return { custom: '', picked: [], sel: 0 }
+ }
+
+ const items = multiSelect ? clarifyAnswerItems(answer) : null
+
+ if (items) {
+ const custom = items.filter(item => !choices.includes(item)).join(', ')
+
+ return { custom, picked: items.filter(item => choices.includes(item)), sel: custom ? choices.length : 0 }
}
const choiceIndex = choices.indexOf(answer)
if (choiceIndex >= 0) {
- return { custom: '', sel: choiceIndex }
+ return { custom: '', picked: [], sel: choiceIndex }
}
- return { custom: answer, sel: choices.length > 0 ? choices.length : 0 }
+ return { custom: answer, picked: [], sel: choices.length > 0 ? choices.length : 0 }
+}
+
+export const clarifyAnswerText = (answer: string, multiSelect?: boolean) => {
+ const items = multiSelect ? clarifyAnswerItems(answer) : null
+
+ return items ? items.join(', ') : answer
}
export const flat = (r: Record<string, string[]>) => Object.values(r).flat()
diff --git a/ui-tui/src/types.ts b/ui-tui/src/types.ts
index b44ea9ed834..8da8375ba14 100644
--- a/ui-tui/src/types.ts
+++ b/ui-tui/src/types.ts
@@ -115,7 +115,7 @@ export interface ConfirmReq {
title: string
}
-export interface ClarifyBatchQuestion {
+export interface ClarifyQuestion {
choices: string[] | null
multiSelect?: boolean
qid: string
@@ -123,11 +123,8 @@ export interface ClarifyBatchQuestion {
}
export interface ClarifyReq {
- choices: string[] | null
- question: string
requestId: string
- /** Batch (multi-question) clarify: present instead of question/choices. */
- questions?: ClarifyBatchQuestion[]
+ questions: ClarifyQuestion[]
/** Answers already locked server-side (qid → answer): seeded from the
* reconnect replay, updated as the user locks each question. */
answers?: Record<string, string>
diff --git a/website/docs/developer-guide/programmatic-integration.md b/website/docs/developer-guide/programmatic-integration.md
index 4b050ad8228..828b3151028 100644
--- a/website/docs/developer-guide/programmatic-integration.md
+++ b/website/docs/developer-guide/programmatic-integration.md
@@ -93,7 +93,7 @@ Approvals, clarify questions, sudo/secret prompts, vault unlock, MCP setup and t
→ {"jsonrpc":"2.0","id":"srq-7","result":{"choice":"once"}}
```
-Methods: `approval` → `{choice}`; `clarify` → `{answer}` (single) or `{answers}` / `{}` cancel (batch, with `clarify.lock` to lock one answer early); `sudo`, `secret`, `vault.code`, `vault.unlock_prompt` → `{value}`; `connection` → `{settled_by, targets}` (the `manage_connections` card: one outcome per target); `terminal.read`, `window.read`, `preview.act`, `tour` → `{value}` (JSON text). Respond with a JSON-RPC error (`-32601`) for a method your host does not implement so the agent fails fast instead of waiting out the timeout.
+Methods: `approval` → `{choice}`; `clarify` → `{answers}` keyed by question id, or `{}` to cancel (`clarify.lock` locks one answer early; `null` skips that question); `sudo`, `secret`, `vault.code`, `vault.unlock_prompt` → `{value}`; `connection` → `{settled_by, targets}` (the `manage_connections` card: one outcome per target); `terminal.read`, `window.read`, `preview.act`, `tour` → `{value}` (JSON text). Respond with a JSON-RPC error (`-32601`) for a method your host does not implement so the agent fails fast instead of waiting out the timeout.
**Advertise that you answer them (breaking for existing WebSocket integrations).** Once per connection, after `gateway.ready`, call `client.capabilities` with `{"server_requests": true}`; the result lists the request methods this backend may send. A WebSocket client that never does is treated as a build that predates server→client requests: the gateway fails every such request for it immediately (the agent sees the same "no answer" an error response produces; an approval is withdrawn, not denied) instead of stalling for the full deadline. There is no grace path — a third-party WebSocket client that answered `clarify`/`approval`/`sudo`/… before this change but never sends `client.capabilities` now has every such request refused until it adds the one call. A session with no client attached is not affected — its open questions wait in `open_requests` for the reconnect replay. The stdio TUI, the desktop app and the dashboard advertise through the shared `JsonRpcRequestChannel`.
diff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.md
index 693f6277ed8..28211a8a342 100644
--- a/website/docs/reference/tools-reference.md
+++ b/website/docs/reference/tools-reference.md
@@ -42,19 +42,19 @@ These two tools live in the `browser` toolset but only register when a Chrome De
| Tool | Description | Requires environment |
|------|-------------|----------------------|
-| `clarify` | Ask the user a question when you need clarification, feedback, or a decision before proceeding. Supports three modes: 1. **Single-select multiple choice** — up to 4 choices; the user picks one or types their own answer via a 5th 'Other' option. 2. **Multi-select multiple choice** — `multi_select=true` renders checkboxes and returns a list of selected choices. 3. **Open-ended** — no choices; the user types a free-form response. Choices are ordered best-first, so the first one is labelled `(Recommended)` on every surface and is the default highlight; the label is presentation only and is stripped from the answer the agent reads. On the classic CLI multi-select uses Space-to-toggle checkboxes; on messaging platforms without native checkbox UIs the user replies with comma/space-separated numbers (e.g. "1, 3") or the option text. | — |
+| `clarify` | Ask the user one or more questions when you need clarification, feedback, or a decision before proceeding. Every call passes `questions`, an array of 1–5 entries (a single question is a one-entry array). Each question supports three modes: 1. **Single-select multiple choice** — up to 4 choices; the user picks one or types their own answer via a 5th 'Other' option. 2. **Multi-select multiple choice** — `multi_select=true` renders checkboxes and returns a list of selected choices. 3. **Open-ended** — no choices; the user types a free-form response. Choices are ordered best-first, so the first one is labelled `(Recommended)` on every surface and is the default highlight; the label is presentation only and is stripped from the answer the agent reads. On the classic CLI multi-select uses Space-to-toggle checkboxes; on messaging platforms without native checkbox UIs the user replies with comma/space-separated numbers (e.g. "1, 3") or the option text. | — |
### Asking multiple questions at once
-The `clarify` tool also accepts a `questions` array (2–5 independent questions, each with its own `choices` and `multi_select`) so the agent can batch several clarification needs into a single prompt instead of asking sequentially. The result is a `responses` array in the same order, with each question's `id` (when supplied) echoed back.
+The `clarify` tool takes a `questions` array (1–5 independent questions, each with its own `choices` and `multi_select`) so the agent can batch several clarification needs into a single prompt instead of asking sequentially. The result is `{responses, outcome}`: a `responses` array in the same order, each entry with the question text, `choices_offered`, a `status` (`answered`, `skipped` or `unanswered`) and `user_response` (null unless answered). `outcome` is `submitted`, `cancelled`, `timed_out` or `undelivered`.
Per-surface behavior:
-- **Desktop** shows every question on one card. Picks and typed answers stage locally, and one **Confirm and continue** button (enabled once every question has an answer) submits the whole batch. Staged answers stay editable until that confirm. Skip cancels the whole batch.
-- **TUI and CLI** show a compact status list (`✓` answered / `▸` active / `·` pending) with only the active question's choices expanded. Enter locks the active answer and jumps to the next unanswered question; Tab moves between questions to answer in any order; Esc cancels the batch.
-- **Messaging platforms** (Telegram, Discord, …) fall back to asking the questions one at a time through the existing single-question prompt. If the user stops responding, the remaining questions are not sent.
+- **Desktop** shows every question on one card. Picks and typed answers stage locally, and one **Confirm and continue** button (enabled once at least one question has an answer) submits the whole batch; blank questions are skipped. Staged answers stay editable until that confirm. Skip cancels the whole batch.
+- **TUI and CLI** show a compact status list (`✓` answered / `▸` active / `·` pending) with only the active question's choices expanded. Enter locks the active answer and jumps to the next unanswered question; Tab moves between questions to answer in any order; an empty submit skips that question; Esc cancels the batch.
+- **Messaging platforms** (Telegram, Discord, …) ask the questions one at a time, one card per question. Reply `skip` to skip one question. If the user stops responding, the remaining questions are not sent.
-If the prompt times out part-way, answers the user already locked are kept: the tool result carries them plus `"timed_out": true`, with the unanswered entries left blank, so the agent can distinguish a deliberate skip from an absent user. On messaging platforms the result also carries a `"notice"` saying why the wait ended (`[user did not respond within Nm]`, or `[clarify prompt could not be delivered]` when the platform rejected the card — Hermes first retries the question as a plain numbered-list message, and only reports this when that fails too; `[clarify prompt could not be delivered: no chat surface]` when the run has no chat to prompt in), so an undelivered prompt is never reported as user inactivity.
+If the prompt times out part-way, answers the user already locked are kept: the tool result carries them with `"outcome": "timed_out"` and marks the rest `"status": "unanswered"`, so the agent can distinguish a deliberate skip from an absent user. On messaging platforms the result also carries a `"notice"` saying why the wait ended (`[user did not respond within Nm]`, or `[clarify prompt could not be delivered]` when the platform rejected the card — Hermes first retries the question as a plain numbered-list message, and only reports this when that fails too; `[clarify prompt could not be delivered: no chat surface]` when the run has no chat to prompt in), so an undelivered prompt is never reported as user inactivity.
## `connections` toolset
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index 977f052c497..8a6299d5b8f 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -2987,7 +2987,7 @@ agent:
clarify_timeout: 3600 # Seconds to wait for user clarification response (0 or less = unlimited)
```
-When the timeout expires, the agent unblocks with a "user did not respond" sentinel and continues on its own. A clarify prompt is never cut by the generic per-tool deadline (`timeouts.tools.sequential_call`); only `agent.clarify_timeout` bounds the wait.
+When the timeout expires, the agent unblocks with `"outcome": "timed_out"` (answers the user already locked are kept) and continues on its own. A clarify prompt is never cut by the generic per-tool deadline (`timeouts.tools.sequential_call`); only `agent.clarify_timeout` bounds the wait.
## Context Files (SOUL.md, AGENTS.md)
diff --git a/website/docs/user-guide/messaging/discord.md b/website/docs/user-guide/messaging/discord.md
index d639cea111b..9027d612900 100644
--- a/website/docs/user-guide/messaging/discord.md
+++ b/website/docs/user-guide/messaging/discord.md
@@ -768,7 +768,7 @@ When the agent calls the `clarify` tool — to ask which approach you prefer, ge
Click a numbered button to answer, or click **Other** to type a free-form response (the next message you send in that channel becomes the answer). Open-ended `clarify` calls (no preset choices) skip the buttons and just capture your next message.
-The buttons disable themselves once a choice is made so duplicate clicks don't double-resolve the prompt. Configure the response timeout via `agent.clarify_timeout` in `~/.hermes/config.yaml` (default `3600` seconds; `0` or less = unlimited). If you don't respond within the timeout, the agent unblocks with a sentinel message and adapts rather than hanging.
+The buttons disable themselves once a choice is made so duplicate clicks don't double-resolve the prompt. Configure the response timeout via `agent.clarify_timeout` in `~/.hermes/config.yaml` (default `3600` seconds; `0` or less = unlimited). If you don't respond within the timeout, the agent unblocks with `"outcome": "timed_out"` and adapts rather than hanging. Reply `skip` to skip a question.
### Prompt layout
diff --git a/website/docs/user-guide/messaging/telegram.md b/website/docs/user-guide/messaging/telegram.md
index 2b8cebbe6b6..1c824492dbb 100644
--- a/website/docs/user-guide/messaging/telegram.md
+++ b/website/docs/user-guide/messaging/telegram.md
@@ -1391,7 +1391,7 @@ When the agent calls the `clarify` tool — to ask which approach you prefer, ge
Tap a button to answer, or tap **Other** to type a free-form response (the next message you send becomes the answer). Open-ended `clarify` calls (no preset choices) skip the buttons and just capture your next message.
-Configure the response timeout via `agent.clarify_timeout` in `~/.hermes/config.yaml` (default `3600` seconds). If you don't respond within the timeout, the agent unblocks with a sentinel message and adapts rather than hanging.
+Configure the response timeout via `agent.clarify_timeout` in `~/.hermes/config.yaml` (default `3600` seconds). If you don't respond within the timeout, the agent unblocks with `"outcome": "timed_out"` and adapts rather than hanging. Reply `skip` to skip a question.
If Telegram cannot render the button card (the Bot API rejects it, or the send fails after its 15-second acknowledgement window), Hermes re-asks the same question as a plain numbered-list message and your typed reply (a number or the option text) is taken as the answer. When even that cannot be delivered, the agent is released at once with `[clarify prompt could not be delivered]` instead of waiting out the timeout and mistaking the silence for you not answering.
diff --git a/website/docs/user-guide/skills/bundled/creative/creative-baoyu-infographic.md b/website/docs/user-guide/skills/bundled/creative/creative-baoyu-infographic.md
index e915f2ce63b..f1f241770fa 100644
--- a/website/docs/user-guide/skills/bundled/creative/creative-baoyu-infographic.md
+++ b/website/docs/user-guide/skills/bundled/creative/creative-baoyu-infographic.md
@@ -199,7 +199,7 @@ See `references/structured-content-template.md` for detailed format.
### Step 4: Confirm Options
-Use the `clarify` tool to confirm options with the user. Since `clarify` handles one question at a time, ask the most important question first:
+Use the `clarify` tool to confirm options with the user. Put the independent questions below in one `questions` array (up to 5); ask separately any question whose options depend on an earlier answer:
**Q1 — Combination**: Present 3+ layout×style combos with rationale. Ask user to pick one.
diff --git a/website/docs/user-guide/skills/optional/creative/creative-baoyu-article-illustrator.md b/website/docs/user-guide/skills/optional/creative/creative-baoyu-article-illustrator.md
index 2fbe498b784..6dfdd2019f3 100644
--- a/website/docs/user-guide/skills/optional/creative/creative-baoyu-article-illustrator.md
+++ b/website/docs/user-guide/skills/optional/creative/creative-baoyu-article-illustrator.md
@@ -101,7 +101,7 @@ If the user asks for a different layout (e.g., images alongside the article, or
```
- [ ] Step 1: Detect reference images (if provided)
- [ ] Step 2: Analyze content
-- [ ] Step 3: Confirm settings (clarify tool, one question at a time)
+- [ ] Step 3: Confirm settings (clarify tool)
- [ ] Step 4: Generate outline
- [ ] Step 5: Generate prompts
- [ ] Step 6: Generate images (image_generate)
@@ -133,7 +133,7 @@ Full procedures: [references/workflow.md](https://github.com/NousResearch/hermes
### Step 3: Confirm Settings
-Use the `clarify` tool. Since `clarify` handles one question at a time, ask the most important question first. Skip any question whose answer is already present in the user's request.
+Use the `clarify` tool. Put the independent questions in one `questions` array (up to 5). Skip any question whose answer is already present in the user's request.
| Order | Question | Options |
|-------|----------|---------|
diff --git a/website/docs/user-guide/skills/optional/creative/creative-baoyu-comic.md b/website/docs/user-guide/skills/optional/creative/creative-baoyu-comic.md
index 88fdc93af6a..c4f0a68cec2 100644
--- a/website/docs/user-guide/skills/optional/creative/creative-baoyu-comic.md
+++ b/website/docs/user-guide/skills/optional/creative/creative-baoyu-comic.md
@@ -185,11 +185,11 @@ Input → Analyze → [Check Existing?] → [Confirm: Style + Reviews] → Story
### User Questions
-Use the `clarify` tool to confirm options. Since `clarify` handles one question at a time, ask the most important question first and proceed sequentially. See [references/workflow.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative/baoyu-comic/references/workflow.md) for the full Step 2 question set.
+Use the `clarify` tool to confirm options. Put independent questions in one `questions` array (up to 5); ask separately any question whose options depend on an earlier answer. See [references/workflow.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative/baoyu-comic/references/workflow.md) for the full Step 2 question set.
-**Timeout handling (CRITICAL)**: `clarify` can return `"The user did not provide a response within the time limit. Use your best judgement to make the choice and proceed."` — this is NOT user consent to default everything.
+**Timeout handling (CRITICAL)**: `clarify` can return `"outcome": "timed_out"` with responses marked `"status": "unanswered"` — this is NOT user consent to default everything.
-- Treat it as a default **for that one question only**. Continue asking the remaining Step 2 questions in sequence; each question is an independent consent point.
+- Treat it as a default **for the unanswered questions only**. Each question is an independent consent point.
- **Surface the default to the user visibly** in your next message so they have a chance to correct it: e.g. `"Style: defaulted to ohmsha preset (clarify timed out). Say the word to switch."` — an unreported default is indistinguishable from never having asked.
- Do NOT collapse Step 2 into a single "use all defaults" pass after one timeout. If the user is genuinely absent, they will be equally absent for all five questions — but they can correct visible defaults when they return, and cannot correct invisible ones.
diff --git a/website/docs/user-guide/skills/optional/migration/migration-openclaw-migration.md b/website/docs/user-guide/skills/optional/migration/migration-openclaw-migration.md
index 9789585e86e..dd4bc26368d 100644
--- a/website/docs/user-guide/skills/optional/migration/migration-openclaw-migration.md
+++ b/website/docs/user-guide/skills/optional/migration/migration-openclaw-migration.md
@@ -120,7 +120,7 @@ For every `clarify` call:
- never include fake form fields in the question such as `enter directory here`, blank lines to fill in, or underscores like `_____`
- for open-ended path questions, ask only the plain sentence; the user types in the normal CLI prompt below the panel
-If a `clarify` call returns an error, inspect the error text, correct the payload, and retry once with a valid `question` and clean choices.
+If a `clarify` call returns an error, inspect the error text, correct the payload, and retry once with a valid `questions` array and clean choices.
When `clarify` is available and the dry run reveals any required user decision, your **next action must be a `clarify` tool call**.
Do not end the turn with a normal assistant message such as: