The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(voice): add configurable TUI draft submission
khanhngoof1c45f572751
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 8424677d34d..3a1ed048719 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -1919,6 +1919,20 @@ def validate_config_structure(config: Optional[Dict[str, Any]] = None) -> List["issues: List[ConfigIssue] = []+ # ── voice.submit_mode: direct | draft ────────────────────────────────+ voice_cfg = config.get("voice")+ if isinstance(voice_cfg, dict) and "submit_mode" in voice_cfg:+ submit_mode = voice_cfg.get("submit_mode")+ normalized_submit_mode = (+ submit_mode.strip().lower() if isinstance(submit_mode, str) else None+ )+ if normalized_submit_mode not in {"direct", "draft"}:+ issues.append(ConfigIssue(+ "error",+ f"voice.submit_mode must be 'direct' or 'draft', got {submit_mode!r}",+ "Set voice.submit_mode to direct (submit immediately) or draft (edit before sending)",+ ))+# ── custom_providers must be a list, not a dict ──────────────────────cp = config.get("custom_providers")if cp is not None:diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 8a083744d13..423cb66f1b8 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1627,6 +1627,7 @@ DEFAULT_CONFIG = {"voice": {"record_key": "ctrl+b",+ "submit_mode": "direct", # TUI: direct submits immediately; draft leaves an editable transcript"max_recording_seconds": 120,"auto_tts": False,"beep_enabled": True, # Play record start/stop beeps in CLI voice modediff --git a/tests/hermes_cli/test_config_validation.py b/tests/hermes_cli/test_config_validation.pyindex 3cdfbd07edd..8f5746eda29 100644--- a/tests/hermes_cli/test_config_validation.py+++ b/tests/hermes_cli/test_config_validation.py@@ -90,6 +90,27 @@ class TestConfigIssueDataclass:assert a == b+class TestVoiceSubmitModeValidation:+ def test_default_is_direct(self):+ assert DEFAULT_CONFIG["voice"]["submit_mode"] == "direct"++ def test_direct_and_draft_are_valid(self):+ for mode in ("direct", "draft"):+ issues = validate_config_structure({"voice": {"submit_mode": mode}})+ assert not any("voice.submit_mode" in issue.message for issue in issues)++ def test_invalid_mode_is_reported(self):+ issues = validate_config_structure({"voice": {"submit_mode": "refine"}})++ assert any(+ issue.severity == "error"+ and "voice.submit_mode" in issue.message+ and "direct" in issue.hint+ and "draft" in issue.hint+ for issue in issues+ )++class TestUnknownTopLevelKeys:"""Arbitrary top-level keys must NOT warn — they are bridged to os.environ.diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.test.tsindex 404aac38603..f44cb9246c8 100644--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts@@ -893,6 +893,35 @@ describe('createGatewayEventHandler', () => {expect(ctx.voice.setVoiceEnabled).not.toHaveBeenCalled()})+ it('leaves voice transcripts editable when voice.submit_mode is draft', async () => {+ const ctx = buildCtx([])++ ctx.gateway.rpc = vi.fn(async (method: string) =>+ method === 'config.get' ? { config: { voice: { submit_mode: 'draft' } } } : null+ )+ const onEvent = createGatewayEventHandler(ctx)++ onEvent({ payload: { text: ' edit this first ' }, type: 'voice.transcript' } as any)++ await vi.waitFor(() => expect(ctx.composer.setInput).toHaveBeenCalledWith('edit this first'))+ expect(ctx.submission.submitRef.current).not.toHaveBeenCalled()+ expect(ctx.gateway.rpc).toHaveBeenCalledWith('config.get', { key: 'full' })+ })++ it('falls back to direct submit for an invalid voice.submit_mode', async () => {+ const ctx = buildCtx([])++ ctx.gateway.rpc = vi.fn(async (method: string) =>+ method === 'config.get' ? { config: { voice: { submit_mode: 'refine' } } } : null+ )+ const onEvent = createGatewayEventHandler(ctx)++ onEvent({ payload: { text: 'send safely' }, type: 'voice.transcript' } as any)++ await vi.waitFor(() => expect(ctx.submission.submitRef.current).toHaveBeenCalledWith('send safely'))+ expect(ctx.composer.setInput).toHaveBeenCalledWith('')+ })+it('opens a fresh session before starting voice after wake detection', async () => {const ctx = buildCtx([])ctx.session.newSession = vi.fn(async () => patchUiState({ sid: 'wake-session' }))diff --git a/ui-tui/src/__tests__/voiceSubmitModeRenderer.test.tsx b/ui-tui/src/__tests__/voiceSubmitModeRenderer.test.tsxnew file mode 100644index 00000000000..6ceb9eb7900--- /dev/null+++ b/ui-tui/src/__tests__/voiceSubmitModeRenderer.test.tsx@@ -0,0 +1,96 @@+import { PassThrough } from 'stream'++import { renderSync, Text } from '@hermes/ink'+import React, { useMemo, useState } from 'react'+import { describe, expect, it, vi } from 'vitest'++import { createGatewayEventHandler } from '../app/createGatewayEventHandler.js'++const ref = <T,>(current: T) => ({ current })+const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))++describe('voice.submit_mode live composer rendering', () => {+ it('renders a draft transcript in the real React composer state without submitting it', async () => {+ const exposed = { current: null as null | ((event: any) => void) }+ const submit = vi.fn()++ function Harness() {+ const [input, setInput] = useState('')++ const handler = useMemo(+ () =>+ createGatewayEventHandler({+ composer: {+ dequeue: () => undefined,+ queueEditRef: ref<null | number>(null),+ sendQueued: vi.fn(),+ setInput+ },+ gateway: {+ gw: { request: vi.fn() },+ rpc: vi.fn(async (method: string) =>+ method === 'config.get' ? { config: { voice: { submit_mode: 'draft' } } } : null+ )+ },+ session: {+ STARTUP_RESUME_ID: '',+ colsRef: ref(80),+ newSession: vi.fn(),+ resetSession: vi.fn(),+ resumeById: vi.fn(),+ setCatalog: vi.fn()+ },+ submission: { submitRef: ref(submit) },+ system: { bellOnComplete: false, sys: vi.fn() },+ transcript: {+ appendMessage: vi.fn(),+ panel: vi.fn(),+ setHistoryItems: vi.fn()+ },+ voice: {+ setProcessing: vi.fn(),+ setRecording: vi.fn(),+ setVoiceEnabled: vi.fn()+ }+ } as any),+ []+ )++ exposed.current = handler++ return <Text>{input || 'empty composer'}</Text>+ }++ const stdin = new PassThrough()+ const stdout = new PassThrough()+ const stderr = new PassThrough()+ let output = ''++ Object.assign(stdin, { isTTY: false })+ Object.assign(stdout, { columns: 80, isTTY: false, rows: 20 })+ stdout.on('data', chunk => {+ output += chunk.toString()+ })++ const instance = renderSync(<Harness />, {+ patchConsole: false,+ stderr: stderr as NodeJS.WriteStream,+ stdin: stdin as NodeJS.ReadStream,+ stdout: stdout as NodeJS.WriteStream+ })++ try {+ expect(exposed.current).not.toBeNull()+ exposed.current!({ payload: { text: 'editable voice draft' }, type: 'voice.transcript' })++ for (let i = 0; i < 20 && !output.includes('editable voice draft'); i += 1) {+ await delay(10)+ }++ expect(output).toContain('editable voice draft')+ expect(submit).not.toHaveBeenCalled()+ } finally {+ instance.unmount()+ }+ })+})diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.tsindex 55a31f97ddd..070178ccd08 100644--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@ -36,6 +36,11 @@ import { isWakeUserDisabled } from './wakeState.js'const NO_PROVIDER_RE = /\bNo (?:LLM|inference) provider configured\b/i+type VoiceSubmitMode = 'direct' | 'draft'++const normalizeVoiceSubmitMode = (value: unknown): VoiceSubmitMode =>+ typeof value === 'string' && value.trim().toLowerCase() === 'draft' ? 'draft' : 'direct'+const statusFromBusy = () => (getUiState().busy ? 'running…' : 'ready')// The last gateway skin, kept so the theme can be re-derived when the OSC-11@@ -944,16 +949,21 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:return}- // CLI parity: _pending_input.put(transcript) unconditionally feeds- // the transcript to the agent as its next turn — draft handling- // doesn't apply because voice-mode users are speaking, not typing.- //- // We can't branch on composer input from inside a setInput updater- // (React strict mode double-invokes it, duplicating the submit).- // Just clear + defer submit so the cleared input is committed before- // submit reads it.- setInput('')- setTimeout(() => submitRef.current(text), 0)+ void getFullConfigOnce().then(cfg => {+ const submitMode = normalizeVoiceSubmitMode(cfg?.config?.voice?.submit_mode)++ if (submitMode === 'draft') {+ setInput(text)++ return+ }++ // Default to CLI parity. Clear + defer submit so the cleared input+ // is committed before submit reads it; invalid config also falls+ // back to this established direct-submit behavior.+ setInput('')+ setTimeout(() => submitRef.current(text), 0)+ })return}diff --git a/ui-tui/src/gatewayTypes.ts b/ui-tui/src/gatewayTypes.tsindex c5bb9ff0d37..ba8e85c42af 100644--- a/ui-tui/src/gatewayTypes.ts+++ b/ui-tui/src/gatewayTypes.ts@@ -113,9 +113,10 @@ export interface ConfigDisplayConfig {}export interface ConfigVoiceConfig {- // Raw `yaml.safe_load()` value from config; may be non-string if hand-edited.- // Callers must normalize/validate at runtime (parseVoiceRecordKey()).+ // Raw `yaml.safe_load()` values from config may be non-string if hand-edited.+ // Callers must normalize/validate at runtime.record_key?: unknown+ submit_mode?: unknown}export interface ConfigFullResponse {diff --git a/website/docs/guides/use-voice-mode-with-hermes.md b/website/docs/guides/use-voice-mode-with-hermes.mdindex b13baca4af1..996f0167b0d 100644--- a/website/docs/guides/use-voice-mode-with-hermes.md+++ b/website/docs/guides/use-voice-mode-with-hermes.md@@ -166,6 +166,7 @@ If you skip that install or it fails, the wizard falls back to Edge TTS.```yamlvoice:record_key: "ctrl+b"+ submit_mode: "direct" # TUI: direct | draftmax_recording_seconds: 120auto_tts: falsebeep_enabled: true@@ -185,6 +186,18 @@ tts:This is a good conservative default for most people.+In the TUI, `voice.submit_mode` controls what happens after transcription:++- `direct` (default) submits the transcript immediately.+- `draft` puts the transcript in the composer so you can edit or cancel it before pressing Enter.++For editable voice drafts, set:++```yaml+voice:+ submit_mode: "draft"+```+If you want local TTS instead, switch the `tts` block to:```yamldiff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/use-voice-mode-with-hermes.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/use-voice-mode-with-hermes.mdindex 5df1eea252f..99bbe53fa7c 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/use-voice-mode-with-hermes.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/use-voice-mode-with-hermes.md@@ -162,6 +162,7 @@ python -m pip install -U neutts[all]```yamlvoice:record_key: "ctrl+b"+ submit_mode: "direct" # TUI:direct | draftmax_recording_seconds: 120auto_tts: falsebeep_enabled: true@@ -181,6 +182,18 @@ tts:这是适合大多数人的保守默认配置。+在 TUI 中,`voice.submit_mode` 控制转写完成后的行为:++- `direct`(默认)会立即提交转写文本。+- `draft` 会把转写文本放入输入框,供你编辑或取消,按 Enter 后才发送。++如需可编辑的语音草稿,请设置:++```yaml+voice:+ submit_mode: "draft"+```+如果想改用本地 TTS,将 `tts` 块替换为:```yaml