From 3e5730695e375ab1782950cf14659e9434a50483 Mon Sep 17 00:00:00 2001 From: raihanjs Date: Mon, 12 Oct 2026 20:05:25 +0600 Subject: [PATCH 1/5] feat(tui): add push-to-talk voice input to the prompt composer Port #50549 to V2. Hold the prompt.voice.push_to_talk key to record from the microphone, release to transcribe into the prompt. Recording uses user-installed ffmpeg or sox; transcription runs a user-configured shell command (voice.transcribe_command). Disabled by default. Release bindings need terminal release reporting (see #45423). --- packages/tui/src/component/prompt/index.tsx | 92 +++++++++ packages/tui/src/component/prompt/voice.ts | 160 +++++++++++++++ packages/tui/src/config/index.tsx | 8 + packages/tui/src/config/keybind.ts | 1 + packages/tui/src/config/v1/keybind.ts | 2 + packages/tui/test/config-v2.test.tsx | 1 + packages/tui/test/prompt/voice.test.ts | 190 ++++++++++++++++++ services/www/src/docs/content/cli/config.mdx | 23 +++ .../www/src/docs/content/cli/keybinds.mdx | 1 + 9 files changed, 478 insertions(+) create mode 100644 packages/tui/src/component/prompt/voice.ts create mode 100644 packages/tui/test/prompt/voice.test.ts diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx index 73f61f329cee..1ecc6acbfb98 100644 --- a/packages/tui/src/component/prompt/index.tsx +++ b/packages/tui/src/component/prompt/index.tsx @@ -38,7 +38,15 @@ import { expandPastedTextPlaceholders, expandTrackedPastedText } from "../../pro import { usePromptStash } from "../../prompt/stash" import { DialogStash } from "../dialog-stash" import { type AutocompleteOption, type AutocompleteRef, Autocomplete } from "./autocomplete" +import { + VoiceRecorder, + findRecorder, + transcribeAudio, + shouldDiscardTap, + VOICE_MAX_RECORD_MS, +} from "./voice" import { useRenderer, useTerminalDimensions } from "@opentui/solid" +import { useBindings } from "@opentui/keymap/solid" import { Locale } from "../../util/locale" import { errorMessage } from "../../util/error" import { createColors, createFrames } from "../../ui/spinner" @@ -724,6 +732,8 @@ export function Prompt(props: PromptProps) { onCleanup(() => { disposed = true + voiceRecorder?.dispose() + voiceRecorder = undefined if (store.prompt.text) { saveDraft(stashSessionID, { prompt: unwrap(store.prompt), cursor: input.cursorOffset }) } @@ -939,6 +949,87 @@ export function Prompt(props: PromptProps) { commands: stashCommands(), })) + // Push-to-talk voice input: hold the configured key to record, release to transcribe. + const [voiceRecording, setVoiceRecording] = createSignal(false) + let voiceRecorder: VoiceRecorder | undefined + let voiceStartTime = 0 + let voiceStopTimer: ReturnType | undefined + + function startVoiceRecording() { + if (voiceRecorder?.recording) return + if (!config.voice?.transcribe_command) { + toast.show({ variant: "error", message: "Voice input needs voice.transcribe_command to be set" }) + return + } + const spec = findRecorder() + if (!spec) { + toast.show({ variant: "error", message: "Voice input needs ffmpeg or sox installed to record audio" }) + return + } + voiceRecorder = new VoiceRecorder() + voiceRecorder.start(spec) + voiceStartTime = Date.now() + setVoiceRecording(true) + voiceStopTimer = setTimeout(() => void stopVoiceRecording(""), VOICE_MAX_RECORD_MS) + } + + async function stopVoiceRecording(tapInsert: string) { + if (voiceStopTimer) { + clearTimeout(voiceStopTimer) + voiceStopTimer = undefined + } + const recorder = voiceRecorder + voiceRecorder = undefined + setVoiceRecording(false) + if (!recorder) return + const holdMs = Date.now() - voiceStartTime + try { + const wavFile = await recorder.stop() + if (!wavFile) return + if (shouldDiscardTap(holdMs)) { + if (tapInsert) input.insertText(tapInsert) + return + } + const text = await transcribeAudio(wavFile, config.voice?.transcribe_command ?? "") + if (!text) return + input.insertText(text.endsWith("\n") ? text : text + " ") + setTimeout(() => { + if (!input || input.isDestroyed) return + input.getLayoutNode().markDirty() + renderer.requestRender() + }, 0) + } catch (error) { + toast.error(error) + } finally { + recorder.dispose() + } + } + + useBindings(() => { + const press = config.keybinds.get("prompt.voice.push_to_talk").filter((binding) => binding.event !== "release") + return { + target: inputTarget, + enabled: inputTarget() !== undefined && !disabled() && press.length > 0, + bindings: [ + ...press.map((binding) => ({ + ...binding, + desc: "Start voice recording (release to transcribe)", + group: "Prompt", + cmd: () => startVoiceRecording(), + })), + // Releasing the same key stops the recording, so one configured key + // covers both halves of push-to-talk without extra configuration. + ...press.map((binding) => ({ + ...binding, + event: "release" as const, + desc: "Stop voice recording and transcribe", + group: "Prompt", + cmd: () => stopVoiceRecording(binding.key === "space" ? " " : ""), + })), + ], + } + }) + Keymap.createLayer(() => { return { target: inputTarget, @@ -1591,6 +1682,7 @@ export function Prompt(props: PromptProps) { const placeholderText = createMemo(() => { const value = (() => { + if (voiceRecording()) return "Recording voice… release to transcribe" if (store.mode === "shell") { if (!shell().length) return undefined return `Run a command… "${shell()[store.placeholder % shell().length]}"` diff --git a/packages/tui/src/component/prompt/voice.ts b/packages/tui/src/component/prompt/voice.ts new file mode 100644 index 000000000000..6c755170fc95 --- /dev/null +++ b/packages/tui/src/component/prompt/voice.ts @@ -0,0 +1,160 @@ +/** + * Push-to-talk voice input for the prompt composer. + * + * Recording uses a user-installed audio tool (ffmpeg preferred, sox `rec` as + * fallback) so this feature adds no new native dependencies. Transcription is + * delegated to a user-configured shell command (`tui.voice.transcribe_command`); + * the command's stdout is inserted into the prompt at the cursor. + */ +import { execFile, spawn, type ChildProcess } from "node:child_process" +import { existsSync, unlinkSync } from "node:fs" +import { tmpdir } from "node:os" +import { delimiter, join } from "node:path" + +/** Holds shorter than this are treated as taps, not dictation. */ +export const VOICE_MIN_HOLD_MS = 350 +/** Recordings stop automatically after this long. */ +export const VOICE_MAX_RECORD_MS = 120_000 +/** Placeholder replaced with the recorded wav path in the transcribe command. */ +export const VOICE_FILE_PLACEHOLDER = "{file}" + +export interface RecorderSpec { + command: string + buildArgs: (outputFile: string) => string[] +} + +function commandExists(command: string): boolean { + const extensions = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE").split(";") : [""] + return (process.env.PATH ?? "") + .split(delimiter) + .some((dir) => extensions.some((extension) => existsSync(join(dir, command + extension)))) +} + +/** ffmpeg arguments that record the default microphone to a wav file. */ +export function ffmpegArgs(platform: NodeJS.Platform, outputFile: string): string[] { + const input = + platform === "darwin" + ? ["-f", "avfoundation", "-i", ":default"] + : platform === "win32" + ? ["-f", "dshow", "-i", "audio=default"] + : ["-f", "pulse", "-i", "default"] + return ["-hide_banner", "-loglevel", "error", ...input, "-ar", "16000", "-ac", "1", "-y", outputFile] +} + +/** sox `rec` arguments that record the default microphone to a wav file. */ +export function soxArgs(outputFile: string): string[] { + return ["-r", "16000", "-c", "1", outputFile] +} + +/** Pick the best available microphone recorder, if any. */ +export function findRecorder(platform: NodeJS.Platform = process.platform): RecorderSpec | undefined { + if (commandExists("ffmpeg")) { + return { command: "ffmpeg", buildArgs: (outputFile) => ffmpegArgs(platform, outputFile) } + } + if (commandExists("rec")) { + return { command: "rec", buildArgs: (outputFile) => soxArgs(outputFile) } + } + return undefined +} + +function signal(proc: ChildProcess, sig: NodeJS.Signals): void { + if (proc.exitCode === null && proc.signalCode === null) proc.kill(sig) +} + +/** + * Records microphone audio to a temporary wav file until stopped. + * The recorder is terminated with SIGINT so encoders flush a valid wav + * header; SIGKILL is only a fallback. + */ +export class VoiceRecorder { + private proc: ChildProcess | undefined + private file: string | undefined + + get recording(): boolean { + return this.proc !== undefined + } + + start(spec: RecorderSpec): void { + if (this.proc) return + const file = join(tmpdir(), `opencode-voice-${process.pid}-${Date.now()}.wav`) + const proc = spawn(spec.command, spec.buildArgs(file), { stdio: "ignore" }) + proc.on("error", () => { + if (this.proc === proc) { + this.proc = undefined + this.file = undefined + } + }) + this.proc = proc + this.file = file + } + + /** Stop recording and resolve the wav file path, if one was produced. */ + stop(): Promise { + const proc = this.proc + const file = this.file + this.proc = undefined + if (!proc || !file) { + this.file = undefined + return Promise.resolve(undefined) + } + return new Promise((resolve) => { + const done = () => resolve(existsSync(file) ? file : undefined) + const killTimer = setTimeout(() => signal(proc, "SIGKILL"), 3000) + killTimer.unref() + proc.on("exit", () => { + clearTimeout(killTimer) + // Give the encoder a moment to flush the wav header after SIGINT. + const flushTimer = setTimeout(done, 150) + flushTimer.unref() + }) + signal(proc, "SIGINT") + if (proc.exitCode !== null || proc.signalCode !== null) done() + }) + } + + /** Kill the recorder (if running) and delete the temporary file. */ + dispose(): void { + const proc = this.proc + const file = this.file + this.proc = undefined + this.file = undefined + if (proc) signal(proc, "SIGKILL") + if (file && existsSync(file)) unlinkSync(file) + } +} + +function quoteShellArg(arg: string): string { + return `'${arg.replace(/'/g, `'\\''`)}'` +} + +/** + * Build the shell command that transcribes a recording. The wav path replaces + * every `{file}` placeholder in the template, or is appended as the last + * argument when the template has no placeholder. + */ +export function buildTranscribeShellCommand(template: string, wavFile: string): string { + const quoted = quoteShellArg(wavFile) + if (template.includes(VOICE_FILE_PLACEHOLDER)) return template.split(VOICE_FILE_PLACEHOLDER).join(quoted) + return `${template} ${quoted}` +} + +/** Run the user's transcription command and return its stdout, trimmed. */ +export function transcribeAudio(wavFile: string, template: string): Promise { + const shell = buildTranscribeShellCommand(template, wavFile) + const command = process.platform === "win32" ? "cmd.exe" : "sh" + const args = process.platform === "win32" ? ["/d", "/s", "/c", shell] : ["-c", shell] + return new Promise((resolve, reject) => { + execFile(command, args, { timeout: 120_000, maxBuffer: 4 * 1024 * 1024 }, (error, stdout) => { + if (error) { + reject(new Error(`Voice transcription failed: ${error.message}`)) + return + } + resolve(stdout.trim()) + }) + }) +} + +/** True when the key was held for such a short time it counts as a tap. */ +export function shouldDiscardTap(holdMs: number): boolean { + return holdMs < VOICE_MIN_HOLD_MS +} diff --git a/packages/tui/src/config/index.tsx b/packages/tui/src/config/index.tsx index 92f595aae5b6..b908446d6c22 100644 --- a/packages/tui/src/config/index.tsx +++ b/packages/tui/src/config/index.tsx @@ -146,6 +146,14 @@ export const Info = Schema.Struct({ }), }), ).annotate({ description: "Prompt input behavior" }), + voice: Schema.optional( + Schema.Struct({ + transcribe_command: Schema.optional(Schema.String).annotate({ + description: + "Shell command that transcribes push-to-talk voice recordings. The recorded wav file path replaces {file} in the command, or is appended as the last argument when {file} is absent. The command's stdout is inserted into the prompt.", + }), + }), + ).annotate({ description: "Voice input settings" }), session: Schema.optional( Schema.Struct({ sidebar: Schema.optional(Schema.Literals(["auto", "hide"])).annotate({ diff --git a/packages/tui/src/config/keybind.ts b/packages/tui/src/config/keybind.ts index 2f80c60eadc8..f2ab6096c6a4 100644 --- a/packages/tui/src/config/keybind.ts +++ b/packages/tui/src/config/keybind.ts @@ -200,6 +200,7 @@ export const Definitions = { "prompt.stash": keybind("none", "Stash prompt"), "prompt.stash.pop": keybind("none", "Pop stashed prompt"), "prompt.stash.list": keybind("none", "List stashed prompts"), + "prompt.voice.push_to_talk": keybind("none", "Hold to record voice input, release to transcribe into the prompt"), "prompt.clear": keybind("ctrl+c", "Clear input field"), "prompt.paste": keybind({ key: "ctrl+v", preventDefault: false }, "Paste from clipboard"), diff --git a/packages/tui/src/config/v1/keybind.ts b/packages/tui/src/config/v1/keybind.ts index 0c122a076b22..b68c6efc09ed 100644 --- a/packages/tui/src/config/v1/keybind.ts +++ b/packages/tui/src/config/v1/keybind.ts @@ -170,6 +170,7 @@ export const Definitions = { prompt_stash: keybind("none", "Stash prompt"), prompt_stash_pop: keybind("none", "Pop stashed prompt"), prompt_stash_list: keybind("none", "List stashed prompts"), + prompt_voice_push_to_talk: keybind("none", "Hold to record voice input, release to transcribe into the prompt"), input_clear: keybind("ctrl+c", "Clear input field"), input_paste: keybind({ key: "ctrl+v", preventDefault: false }, "Paste from clipboard"), @@ -369,6 +370,7 @@ export const CommandMap = { prompt_stash: "prompt.stash", prompt_stash_pop: "prompt.stash.pop", prompt_stash_list: "prompt.stash.list", + prompt_voice_push_to_talk: "prompt.voice.push_to_talk", input_clear: "prompt.clear", input_paste: "prompt.paste", input_submit: "input.submit", diff --git a/packages/tui/test/config-v2.test.tsx b/packages/tui/test/config-v2.test.tsx index ae59c8f7bca9..e9e111a623f9 100644 --- a/packages/tui/test/config-v2.test.tsx +++ b/packages/tui/test/config-v2.test.tsx @@ -180,6 +180,7 @@ test("preserves migrated v1 keybind defaults", () => { ["session.delete", "session_delete"], ["session.list", "session_list"], ["agent.list", "agent_list"], + ["prompt.voice.push_to_talk", "prompt_voice_push_to_talk"], ] as const pairs.forEach(([command, name]) => { diff --git a/packages/tui/test/prompt/voice.test.ts b/packages/tui/test/prompt/voice.test.ts new file mode 100644 index 000000000000..328713fab262 --- /dev/null +++ b/packages/tui/test/prompt/voice.test.ts @@ -0,0 +1,190 @@ +import { describe, expect, test, afterEach } from "bun:test" +import { existsSync, mkdtempSync, readdirSync, writeFileSync, chmodSync, rmSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { + VoiceRecorder, + buildTranscribeShellCommand, + ffmpegArgs, + findRecorder, + shouldDiscardTap, + soxArgs, + transcribeAudio, + VOICE_FILE_PLACEHOLDER, + VOICE_MAX_RECORD_MS, + VOICE_MIN_HOLD_MS, +} from "../../src/component/prompt/voice" + +const originalPath = process.env.PATH +afterEach(() => { + process.env.PATH = originalPath +}) + +function fakeBinDir(files: Record): string { + const dir = mkdtempDir() + for (const [name, body] of Object.entries(files)) { + const path = join(dir, name) + writeFileSync(path, body, { mode: 0o755 }) + chmodSync(path, 0o755) + } + return dir +} + +function mkdtempDir(): string { + return mkdtempSync(join(tmpdir(), "opencode-voice-test-")) +} + +describe("component.prompt.voice", () => { + describe("ffmpegArgs", () => { + test("uses avfoundation on darwin", () => { + const args = ffmpegArgs("darwin", "/tmp/a.wav") + expect(args).toContain("avfoundation") + expect(args.at(-1)).toBe("/tmp/a.wav") + }) + + test("uses dshow on win32", () => { + const args = ffmpegArgs("win32", "/tmp/a.wav") + expect(args).toContain("dshow") + expect(args.at(-1)).toBe("/tmp/a.wav") + }) + + test("uses pulse on linux", () => { + const args = ffmpegArgs("linux", "/tmp/a.wav") + expect(args).toContain("pulse") + expect(args.at(-1)).toBe("/tmp/a.wav") + }) + }) + + describe("soxArgs", () => { + test("records 16k mono to the output file", () => { + expect(soxArgs("/tmp/a.wav")).toEqual(["-r", "16000", "-c", "1", "/tmp/a.wav"]) + }) + }) + + describe("findRecorder", () => { + test("prefers ffmpeg over rec", () => { + const dir = fakeBinDir({ ffmpeg: "#!/bin/sh\n", rec: "#!/bin/sh\n" }) + process.env.PATH = dir + expect(findRecorder("linux")?.command).toBe("ffmpeg") + rmSync(dir, { recursive: true }) + }) + + test("falls back to sox rec", () => { + const dir = fakeBinDir({ rec: "#!/bin/sh\n" }) + process.env.PATH = dir + const spec = findRecorder("linux") + expect(spec?.command).toBe("rec") + expect(spec?.buildArgs("/tmp/a.wav")).toEqual(soxArgs("/tmp/a.wav")) + rmSync(dir, { recursive: true }) + }) + + test("returns undefined when no recorder is installed", () => { + process.env.PATH = mkdtempDir() + expect(findRecorder("linux")).toBeUndefined() + }) + }) + + describe("buildTranscribeShellCommand", () => { + test("replaces the {file} placeholder", () => { + expect(buildTranscribeShellCommand(`whisper -f ${VOICE_FILE_PLACEHOLDER} --txt`, "/tmp/a.wav")).toBe( + "whisper -f '/tmp/a.wav' --txt", + ) + }) + + test("appends the file when there is no placeholder", () => { + expect(buildTranscribeShellCommand("whisper", "/tmp/a.wav")).toBe("whisper '/tmp/a.wav'") + }) + + test("quotes paths with spaces and single quotes", () => { + const shell = buildTranscribeShellCommand("cat", "/tmp/my rec's.wav") + expect(shell).toBe(`cat '/tmp/my rec'\\''s.wav'`) + }) + }) + + describe("transcribeAudio", () => { + test("returns the command stdout trimmed", async () => { + const dir = mkdtempDir() + const wav = join(dir, "a.wav") + writeFileSync(wav, "audio") + const text = await transcribeAudio(wav, "cat {file}") + expect(text).toBe("audio") + rmSync(dir, { recursive: true }) + }) + + test("rejects when the command fails", () => { + return expect(transcribeAudio("/tmp/a.wav", "exit 7")).rejects.toThrow("Voice transcription failed") + }) + }) + + describe("shouldDiscardTap", () => { + test("discards holds shorter than the minimum", () => { + expect(shouldDiscardTap(VOICE_MIN_HOLD_MS - 1)).toBe(true) + expect(shouldDiscardTap(0)).toBe(true) + }) + + test("keeps holds at or above the minimum", () => { + expect(shouldDiscardTap(VOICE_MIN_HOLD_MS)).toBe(false) + expect(shouldDiscardTap(VOICE_MAX_RECORD_MS)).toBe(false) + }) + }) + + describe("VoiceRecorder", () => { + const fakeRecorder = "#!/bin/sh\ntouch \"$1\"\nsleep 30\n" + + function listVoiceFiles(): string[] { + return readdirSync(tmpdir()).filter((name) => name.startsWith("opencode-voice-")) + } + + async function waitForNewVoiceFile(before: string[]): Promise { + const deadline = Date.now() + 5000 + while (Date.now() < deadline) { + const fresh = listVoiceFiles().find((name) => !before.includes(name)) + if (fresh) return join(tmpdir(), fresh) + await new Promise((resolve) => setTimeout(resolve, 50)) + } + throw new Error("timed out waiting for the recorder to create its file") + } + + test("starts, stops, and resolves the recorded file", async () => { + const dir = fakeBinDir({ "fake-rec": fakeRecorder }) + const recorder = new VoiceRecorder() + const before = listVoiceFiles() + recorder.start({ command: join(dir, "fake-rec"), buildArgs: (file) => [file] }) + expect(recorder.recording).toBe(true) + + const expected = await waitForNewVoiceFile(before) + const file = await recorder.stop() + expect(recorder.recording).toBe(false) + expect(file).toBe(expected) + + recorder.dispose() + expect(existsSync(file!)).toBe(false) + rmSync(dir, { recursive: true }) + }) + + test("second start while recording is a no-op", async () => { + const dir = fakeBinDir({ "fake-rec": fakeRecorder }) + const recorder = new VoiceRecorder() + const spec = { command: join(dir, "fake-rec"), buildArgs: (file: string) => [file] } + recorder.start(spec) + recorder.start(spec) + expect(recorder.recording).toBe(true) + recorder.dispose() + expect(recorder.recording).toBe(false) + rmSync(dir, { recursive: true }) + }) + + test("stop without start resolves undefined", async () => { + const recorder = new VoiceRecorder() + expect(await recorder.stop()).toBeUndefined() + }) + + test("failed spawn clears the recording state", async () => { + const recorder = new VoiceRecorder() + recorder.start({ command: "opencode-voice-definitely-missing", buildArgs: (file) => [file] }) + await new Promise((resolve) => setTimeout(resolve, 100)) + expect(recorder.recording).toBe(false) + expect(await recorder.stop()).toBeUndefined() + }) + }) +}) diff --git a/services/www/src/docs/content/cli/config.mdx b/services/www/src/docs/content/cli/config.mdx index d47ac65c98df..5a877e43f4eb 100644 --- a/services/www/src/docs/content/cli/config.mdx +++ b/services/www/src/docs/content/cli/config.mdx @@ -109,6 +109,29 @@ Configure mouse capture, scrolling, editor context, pastes, and prompt image pre +## Voice + +Hold the `prompt.voice.push_to_talk` key to record from the microphone; releasing it transcribes the recording into the prompt. Recording needs `ffmpeg` or `sox` installed, and transcription runs your own shell command. Key release must reach the terminal (Kitty keyboard protocol with release reporting) or only the press half fires. + +```json title="cli.json" +{ + "keybinds": { + "prompt.voice.push_to_talk": "ctrl+space" + }, + "voice": { + "transcribe_command": "whisper {file} --output -" + } +} +``` + +
+ +| Setting | Values | Description | +| -------------------------- | ------------------------------- | --------------------------------------------------------------------------- | +| `voice.transcribe_command` | string | Transcribes recordings. The wav path replaces `{file}`, or is appended when `{file}` is absent. Stdout is inserted into the prompt. | + +
+ ## Sessions Configure how full-screen TUI sessions are presented and where new sessions start: diff --git a/services/www/src/docs/content/cli/keybinds.mdx b/services/www/src/docs/content/cli/keybinds.mdx index f3bee823a725..798f149213cf 100644 --- a/services/www/src/docs/content/cli/keybinds.mdx +++ b/services/www/src/docs/content/cli/keybinds.mdx @@ -279,6 +279,7 @@ The retired `diff.toggle`, `diff.expand`, `diff.expand_all`, `diff.collapse`, an | `prompt.stash` | `none` | Stash prompt | | `prompt.stash.pop` | `none` | Pop stashed prompt | | `prompt.stash.list` | `none` | List stashed prompts | +| `prompt.voice.push_to_talk` | `none` | Hold to record voice input, release to transcribe into the prompt | ## Input Editing From b4bb3a27cdebfaa025e8dbb6df87a3c3c69b5ff7 Mon Sep 17 00:00:00 2001 From: raihanjs Date: Mon, 12 Oct 2026 21:07:07 +0600 Subject: [PATCH 2/5] feat(tui): stop voice recording on second press, report recorder failure Review follow-up: without terminal release reporting the recording could not be stopped except by the 120s auto-stop, and a recorder that died immediately left the UI stuck showing recording. Pressing the key while recording now stops and transcribes (toggle fallback alongside hold-to-talk). VoiceRecorder.start takes an onFailure callback fired on spawn failure or spontaneous exit, and the prompt resets its state and shows an error toast. --- packages/tui/src/component/prompt/index.tsx | 17 ++++++-- packages/tui/src/component/prompt/voice.ts | 11 +++-- packages/tui/src/config/keybind.ts | 2 +- packages/tui/src/config/v1/keybind.ts | 2 +- packages/tui/test/prompt/voice.test.ts | 43 +++++++++++++++++++ services/www/src/docs/content/cli/config.mdx | 2 +- .../www/src/docs/content/cli/keybinds.mdx | 2 +- 7 files changed, 68 insertions(+), 11 deletions(-) diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx index 1ecc6acbfb98..0fc1e947c6cd 100644 --- a/packages/tui/src/component/prompt/index.tsx +++ b/packages/tui/src/component/prompt/index.tsx @@ -950,13 +950,17 @@ export function Prompt(props: PromptProps) { })) // Push-to-talk voice input: hold the configured key to record, release to transcribe. + // Where the terminal never reports releases, pressing the key again stops instead. const [voiceRecording, setVoiceRecording] = createSignal(false) let voiceRecorder: VoiceRecorder | undefined let voiceStartTime = 0 let voiceStopTimer: ReturnType | undefined function startVoiceRecording() { - if (voiceRecorder?.recording) return + if (voiceRecorder?.recording) { + void stopVoiceRecording("") + return + } if (!config.voice?.transcribe_command) { toast.show({ variant: "error", message: "Voice input needs voice.transcribe_command to be set" }) return @@ -967,7 +971,12 @@ export function Prompt(props: PromptProps) { return } voiceRecorder = new VoiceRecorder() - voiceRecorder.start(spec) + voiceRecorder.start(spec, () => { + voiceRecorder?.dispose() + voiceRecorder = undefined + setVoiceRecording(false) + toast.show({ variant: "error", message: "Voice recorder stopped unexpectedly" }) + }) voiceStartTime = Date.now() setVoiceRecording(true) voiceStopTimer = setTimeout(() => void stopVoiceRecording(""), VOICE_MAX_RECORD_MS) @@ -1013,7 +1022,7 @@ export function Prompt(props: PromptProps) { bindings: [ ...press.map((binding) => ({ ...binding, - desc: "Start voice recording (release to transcribe)", + desc: "Start voice recording (release or press again to transcribe)", group: "Prompt", cmd: () => startVoiceRecording(), })), @@ -1682,7 +1691,7 @@ export function Prompt(props: PromptProps) { const placeholderText = createMemo(() => { const value = (() => { - if (voiceRecording()) return "Recording voice… release to transcribe" + if (voiceRecording()) return "Recording voice… release or press again to stop" if (store.mode === "shell") { if (!shell().length) return undefined return `Run a command… "${shell()[store.placeholder % shell().length]}"` diff --git a/packages/tui/src/component/prompt/voice.ts b/packages/tui/src/component/prompt/voice.ts index 6c755170fc95..58010c5d2ae1 100644 --- a/packages/tui/src/component/prompt/voice.ts +++ b/packages/tui/src/component/prompt/voice.ts @@ -74,16 +74,21 @@ export class VoiceRecorder { return this.proc !== undefined } - start(spec: RecorderSpec): void { + start(spec: RecorderSpec, onFailure?: () => void): void { if (this.proc) return const file = join(tmpdir(), `opencode-voice-${process.pid}-${Date.now()}.wav`) const proc = spawn(spec.command, spec.buildArgs(file), { stdio: "ignore" }) - proc.on("error", () => { + const failed = () => { if (this.proc === proc) { this.proc = undefined this.file = undefined + onFailure?.() } - }) + } + proc.on("error", failed) + // A recorder that exits on its own (missing device, bad flags) failed; + // normal stops clear this.proc first, so they never reach here. + proc.on("exit", failed) this.proc = proc this.file = file } diff --git a/packages/tui/src/config/keybind.ts b/packages/tui/src/config/keybind.ts index f2ab6096c6a4..e2d98fc4850f 100644 --- a/packages/tui/src/config/keybind.ts +++ b/packages/tui/src/config/keybind.ts @@ -200,7 +200,7 @@ export const Definitions = { "prompt.stash": keybind("none", "Stash prompt"), "prompt.stash.pop": keybind("none", "Pop stashed prompt"), "prompt.stash.list": keybind("none", "List stashed prompts"), - "prompt.voice.push_to_talk": keybind("none", "Hold to record voice input, release to transcribe into the prompt"), + "prompt.voice.push_to_talk": keybind("none", "Record voice input; release or press again to transcribe"), "prompt.clear": keybind("ctrl+c", "Clear input field"), "prompt.paste": keybind({ key: "ctrl+v", preventDefault: false }, "Paste from clipboard"), diff --git a/packages/tui/src/config/v1/keybind.ts b/packages/tui/src/config/v1/keybind.ts index b68c6efc09ed..d393f3506abd 100644 --- a/packages/tui/src/config/v1/keybind.ts +++ b/packages/tui/src/config/v1/keybind.ts @@ -170,7 +170,7 @@ export const Definitions = { prompt_stash: keybind("none", "Stash prompt"), prompt_stash_pop: keybind("none", "Pop stashed prompt"), prompt_stash_list: keybind("none", "List stashed prompts"), - prompt_voice_push_to_talk: keybind("none", "Hold to record voice input, release to transcribe into the prompt"), + prompt_voice_push_to_talk: keybind("none", "Record voice input; release or press again to transcribe"), input_clear: keybind("ctrl+c", "Clear input field"), input_paste: keybind({ key: "ctrl+v", preventDefault: false }, "Paste from clipboard"), diff --git a/packages/tui/test/prompt/voice.test.ts b/packages/tui/test/prompt/voice.test.ts index 328713fab262..26927b0acd78 100644 --- a/packages/tui/test/prompt/voice.test.ts +++ b/packages/tui/test/prompt/voice.test.ts @@ -186,5 +186,48 @@ describe("component.prompt.voice", () => { expect(recorder.recording).toBe(false) expect(await recorder.stop()).toBeUndefined() }) + + test("notifies onFailure when spawn fails", async () => { + const recorder = new VoiceRecorder() + let failures = 0 + recorder.start({ command: "opencode-voice-definitely-missing", buildArgs: (file) => [file] }, () => { + failures += 1 + }) + await new Promise((resolve) => setTimeout(resolve, 200)) + expect(recorder.recording).toBe(false) + expect(failures).toBe(1) + }) + + test("notifies onFailure when the recorder exits on its own", async () => { + const dir = fakeBinDir({ "fake-rec": "#!/bin/sh\nexit 3\n" }) + const recorder = new VoiceRecorder() + let failures = 0 + recorder.start({ command: join(dir, "fake-rec"), buildArgs: (file) => [file] }, () => { + failures += 1 + }) + const deadline = Date.now() + 5000 + while (recorder.recording && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 50)) + } + expect(recorder.recording).toBe(false) + expect(failures).toBe(1) + expect(await recorder.stop()).toBeUndefined() + rmSync(dir, { recursive: true }) + }) + + test("does not notify onFailure on normal stop", async () => { + const dir = fakeBinDir({ "fake-rec": fakeRecorder }) + const recorder = new VoiceRecorder() + let failures = 0 + const before = listVoiceFiles() + recorder.start({ command: join(dir, "fake-rec"), buildArgs: (file) => [file] }, () => { + failures += 1 + }) + const file = await waitForNewVoiceFile(before).then(() => recorder.stop()) + expect(file).not.toBeUndefined() + expect(failures).toBe(0) + recorder.dispose() + rmSync(dir, { recursive: true }) + }) }) }) diff --git a/services/www/src/docs/content/cli/config.mdx b/services/www/src/docs/content/cli/config.mdx index 5a877e43f4eb..5aef4997ab9e 100644 --- a/services/www/src/docs/content/cli/config.mdx +++ b/services/www/src/docs/content/cli/config.mdx @@ -111,7 +111,7 @@ Configure mouse capture, scrolling, editor context, pastes, and prompt image pre ## Voice -Hold the `prompt.voice.push_to_talk` key to record from the microphone; releasing it transcribes the recording into the prompt. Recording needs `ffmpeg` or `sox` installed, and transcription runs your own shell command. Key release must reach the terminal (Kitty keyboard protocol with release reporting) or only the press half fires. +Hold the `prompt.voice.push_to_talk` key to record from the microphone; releasing it (or pressing it again) transcribes the recording into the prompt. Recording needs `ffmpeg` or `sox` installed, and transcription runs your own shell command. Key release must reach the terminal (Kitty keyboard protocol with release reporting) or only the press half fires. ```json title="cli.json" { diff --git a/services/www/src/docs/content/cli/keybinds.mdx b/services/www/src/docs/content/cli/keybinds.mdx index 798f149213cf..dcc99a515cbb 100644 --- a/services/www/src/docs/content/cli/keybinds.mdx +++ b/services/www/src/docs/content/cli/keybinds.mdx @@ -279,7 +279,7 @@ The retired `diff.toggle`, `diff.expand`, `diff.expand_all`, `diff.collapse`, an | `prompt.stash` | `none` | Stash prompt | | `prompt.stash.pop` | `none` | Pop stashed prompt | | `prompt.stash.list` | `none` | List stashed prompts | -| `prompt.voice.push_to_talk` | `none` | Hold to record voice input, release to transcribe into the prompt | +| `prompt.voice.push_to_talk` | `none` | Record voice input; release or press again to transcribe | ## Input Editing From 81c20658e59dc02b6518565b522d0fcc85fa7bcc Mon Sep 17 00:00:00 2001 From: raihanjs Date: Sun, 18 Oct 2026 12:23:58 +0600 Subject: [PATCH 3/5] fix(tui): surface Windows recorder selection and gate the voice layer Review follow-up: dshow has no "default" alias, so Windows recording always failed. findRecorder now enumerates the first DirectShow audio device before recording; without one it falls back to sox rec. The voice layer declares base mode like the other prompt layers, and the recorder lifecycle tests trap SIGINT and write into a scoped temp dir so they are fast and deterministic. --- packages/tui/src/component/prompt/index.tsx | 7 +- packages/tui/src/component/prompt/voice.ts | 42 +++++++++--- packages/tui/test/prompt/voice.test.ts | 72 +++++++++++++++------ 3 files changed, 88 insertions(+), 33 deletions(-) diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx index 0fc1e947c6cd..fa5aaf2229fd 100644 --- a/packages/tui/src/component/prompt/index.tsx +++ b/packages/tui/src/component/prompt/index.tsx @@ -956,7 +956,7 @@ export function Prompt(props: PromptProps) { let voiceStartTime = 0 let voiceStopTimer: ReturnType | undefined - function startVoiceRecording() { + async function startVoiceRecording() { if (voiceRecorder?.recording) { void stopVoiceRecording("") return @@ -965,7 +965,7 @@ export function Prompt(props: PromptProps) { toast.show({ variant: "error", message: "Voice input needs voice.transcribe_command to be set" }) return } - const spec = findRecorder() + const spec = await findRecorder() if (!spec) { toast.show({ variant: "error", message: "Voice input needs ffmpeg or sox installed to record audio" }) return @@ -1018,13 +1018,14 @@ export function Prompt(props: PromptProps) { const press = config.keybinds.get("prompt.voice.push_to_talk").filter((binding) => binding.event !== "release") return { target: inputTarget, + mode: "base", enabled: inputTarget() !== undefined && !disabled() && press.length > 0, bindings: [ ...press.map((binding) => ({ ...binding, desc: "Start voice recording (release or press again to transcribe)", group: "Prompt", - cmd: () => startVoiceRecording(), + cmd: () => void startVoiceRecording(), })), // Releasing the same key stops the recording, so one configured key // covers both halves of push-to-talk without extra configuration. diff --git a/packages/tui/src/component/prompt/voice.ts b/packages/tui/src/component/prompt/voice.ts index 58010c5d2ae1..e6a9c2c96fc8 100644 --- a/packages/tui/src/component/prompt/voice.ts +++ b/packages/tui/src/component/prompt/voice.ts @@ -31,12 +31,12 @@ function commandExists(command: string): boolean { } /** ffmpeg arguments that record the default microphone to a wav file. */ -export function ffmpegArgs(platform: NodeJS.Platform, outputFile: string): string[] { +export function ffmpegArgs(platform: NodeJS.Platform, outputFile: string, audioDevice?: string): string[] { const input = platform === "darwin" ? ["-f", "avfoundation", "-i", ":default"] : platform === "win32" - ? ["-f", "dshow", "-i", "audio=default"] + ? ["-f", "dshow", "-i", `audio=${audioDevice ?? "default"}`] : ["-f", "pulse", "-i", "default"] return ["-hide_banner", "-loglevel", "error", ...input, "-ar", "16000", "-ac", "1", "-y", outputFile] } @@ -46,10 +46,36 @@ export function soxArgs(outputFile: string): string[] { return ["-r", "16000", "-c", "1", outputFile] } +function signal(proc: ChildProcess, sig: NodeJS.Signals): void { + if (proc.exitCode === null && proc.signalCode === null) proc.kill(sig) +} + +/** + * First DirectShow audio device name, for ffmpeg's dshow on Windows. + * dshow has no "default" alias; a concrete device name is required. + */ +export async function firstDshowAudioDevice(ffmpeg: string): Promise { + const proc = spawn(ffmpeg, ["-hide_banner", "-list_devices", "true", "-f", "dshow", "-i", "dummy"]) + const timer = setTimeout(() => signal(proc, "SIGKILL"), 5000) + timer.unref() + const output = await new Promise((resolve) => { + let text = "" + proc.stderr?.on("data", (chunk: Buffer) => { + text += chunk.toString() + }) + proc.on("close", () => resolve(text)) + proc.on("error", () => resolve(text)) + }) + const audio = output.split("DirectShow audio devices")[1] + return audio?.match(/"([^"]+)"/)?.[1] +} + /** Pick the best available microphone recorder, if any. */ -export function findRecorder(platform: NodeJS.Platform = process.platform): RecorderSpec | undefined { +export async function findRecorder(platform: NodeJS.Platform = process.platform): Promise { if (commandExists("ffmpeg")) { - return { command: "ffmpeg", buildArgs: (outputFile) => ffmpegArgs(platform, outputFile) } + if (platform !== "win32") return { command: "ffmpeg", buildArgs: (outputFile) => ffmpegArgs(platform, outputFile) } + const device = await firstDshowAudioDevice("ffmpeg") + if (device) return { command: "ffmpeg", buildArgs: (outputFile) => ffmpegArgs(platform, outputFile, device) } } if (commandExists("rec")) { return { command: "rec", buildArgs: (outputFile) => soxArgs(outputFile) } @@ -57,10 +83,6 @@ export function findRecorder(platform: NodeJS.Platform = process.platform): Reco return undefined } -function signal(proc: ChildProcess, sig: NodeJS.Signals): void { - if (proc.exitCode === null && proc.signalCode === null) proc.kill(sig) -} - /** * Records microphone audio to a temporary wav file until stopped. * The recorder is terminated with SIGINT so encoders flush a valid wav @@ -70,13 +92,15 @@ export class VoiceRecorder { private proc: ChildProcess | undefined private file: string | undefined + constructor(private readonly dir: string = tmpdir()) {} + get recording(): boolean { return this.proc !== undefined } start(spec: RecorderSpec, onFailure?: () => void): void { if (this.proc) return - const file = join(tmpdir(), `opencode-voice-${process.pid}-${Date.now()}.wav`) + const file = join(this.dir, `opencode-voice-${process.pid}-${Date.now()}.wav`) const proc = spawn(spec.command, spec.buildArgs(file), { stdio: "ignore" }) const failed = () => { if (this.proc === proc) { diff --git a/packages/tui/test/prompt/voice.test.ts b/packages/tui/test/prompt/voice.test.ts index 26927b0acd78..b57a479936f4 100644 --- a/packages/tui/test/prompt/voice.test.ts +++ b/packages/tui/test/prompt/voice.test.ts @@ -42,9 +42,10 @@ describe("component.prompt.voice", () => { expect(args.at(-1)).toBe("/tmp/a.wav") }) - test("uses dshow on win32", () => { - const args = ffmpegArgs("win32", "/tmp/a.wav") + test("uses dshow with the enumerated device on win32", () => { + const args = ffmpegArgs("win32", "/tmp/a.wav", "Microphone (Realtek Audio)") expect(args).toContain("dshow") + expect(args).toContain("audio=Microphone (Realtek Audio)") expect(args.at(-1)).toBe("/tmp/a.wav") }) @@ -62,25 +63,47 @@ describe("component.prompt.voice", () => { }) describe("findRecorder", () => { - test("prefers ffmpeg over rec", () => { + test("prefers ffmpeg over rec", async () => { const dir = fakeBinDir({ ffmpeg: "#!/bin/sh\n", rec: "#!/bin/sh\n" }) process.env.PATH = dir - expect(findRecorder("linux")?.command).toBe("ffmpeg") + expect((await findRecorder("linux"))?.command).toBe("ffmpeg") rmSync(dir, { recursive: true }) }) - test("falls back to sox rec", () => { + test("falls back to sox rec", async () => { const dir = fakeBinDir({ rec: "#!/bin/sh\n" }) process.env.PATH = dir - const spec = findRecorder("linux") + const spec = await findRecorder("linux") expect(spec?.command).toBe("rec") expect(spec?.buildArgs("/tmp/a.wav")).toEqual(soxArgs("/tmp/a.wav")) rmSync(dir, { recursive: true }) }) - test("returns undefined when no recorder is installed", () => { + test("returns undefined when no recorder is installed", async () => { process.env.PATH = mkdtempDir() - expect(findRecorder("linux")).toBeUndefined() + expect(await findRecorder("linux")).toBeUndefined() + }) + + test("enumerates a dshow audio device on win32", async () => { + const dir = fakeBinDir({ + ffmpeg: `#!/bin/sh\necho '[dshow @ x] DirectShow video devices:' >&2\necho '[dshow @ x] "Integrated Camera"' >&2\necho '[dshow @ x] DirectShow audio devices (some may be both video and audio devices):' >&2\necho '[dshow @ x] 0 "Microphone (Realtek Audio)"' >&2\n`, + }) + // Prepend: spawn() resolves "ffmpeg" through the child PATH, so the + // fake dir must sit in front of the real one rather than replace it. + process.env.PATH = `${dir}:${process.env.PATH}` + const spec = await findRecorder("win32") + expect(spec?.command).toBe("ffmpeg") + expect(spec?.buildArgs("/tmp/a.wav")).toContain("audio=Microphone (Realtek Audio)") + process.env.PATH = originalPath + rmSync(dir, { recursive: true }) + }) + + test("falls back to rec when dshow lists no audio device", async () => { + const dir = fakeBinDir({ ffmpeg: "#!/bin/sh\n", rec: "#!/bin/sh\n" }) + process.env.PATH = `${dir}:${process.env.PATH}` + expect((await findRecorder("win32"))?.command).toBe("rec") + process.env.PATH = originalPath + rmSync(dir, { recursive: true }) }) }) @@ -129,17 +152,18 @@ describe("component.prompt.voice", () => { }) describe("VoiceRecorder", () => { - const fakeRecorder = "#!/bin/sh\ntouch \"$1\"\nsleep 30\n" + // Exits cleanly on SIGINT so stop() resolves without the SIGKILL fallback. + const fakeRecorder = "#!/bin/sh\ntrap 'exit 0' INT\ntouch \"$1\"\nsleep 30\n" - function listVoiceFiles(): string[] { - return readdirSync(tmpdir()).filter((name) => name.startsWith("opencode-voice-")) + function listVoiceFiles(dir: string): string[] { + return readdirSync(dir).filter((name) => name.startsWith("opencode-voice-")) } - async function waitForNewVoiceFile(before: string[]): Promise { + async function waitForNewVoiceFile(dir: string, before: string[]): Promise { const deadline = Date.now() + 5000 while (Date.now() < deadline) { - const fresh = listVoiceFiles().find((name) => !before.includes(name)) - if (fresh) return join(tmpdir(), fresh) + const fresh = listVoiceFiles(dir).find((name) => !before.includes(name)) + if (fresh) return join(dir, fresh) await new Promise((resolve) => setTimeout(resolve, 50)) } throw new Error("timed out waiting for the recorder to create its file") @@ -147,12 +171,13 @@ describe("component.prompt.voice", () => { test("starts, stops, and resolves the recorded file", async () => { const dir = fakeBinDir({ "fake-rec": fakeRecorder }) - const recorder = new VoiceRecorder() - const before = listVoiceFiles() + const recordings = mkdtempDir() + const recorder = new VoiceRecorder(recordings) + const before = listVoiceFiles(recordings) recorder.start({ command: join(dir, "fake-rec"), buildArgs: (file) => [file] }) expect(recorder.recording).toBe(true) - const expected = await waitForNewVoiceFile(before) + const expected = await waitForNewVoiceFile(recordings, before) const file = await recorder.stop() expect(recorder.recording).toBe(false) expect(file).toBe(expected) @@ -160,11 +185,13 @@ describe("component.prompt.voice", () => { recorder.dispose() expect(existsSync(file!)).toBe(false) rmSync(dir, { recursive: true }) + rmSync(recordings, { recursive: true }) }) test("second start while recording is a no-op", async () => { const dir = fakeBinDir({ "fake-rec": fakeRecorder }) - const recorder = new VoiceRecorder() + const recordings = mkdtempDir() + const recorder = new VoiceRecorder(recordings) const spec = { command: join(dir, "fake-rec"), buildArgs: (file: string) => [file] } recorder.start(spec) recorder.start(spec) @@ -172,6 +199,7 @@ describe("component.prompt.voice", () => { recorder.dispose() expect(recorder.recording).toBe(false) rmSync(dir, { recursive: true }) + rmSync(recordings, { recursive: true }) }) test("stop without start resolves undefined", async () => { @@ -217,17 +245,19 @@ describe("component.prompt.voice", () => { test("does not notify onFailure on normal stop", async () => { const dir = fakeBinDir({ "fake-rec": fakeRecorder }) - const recorder = new VoiceRecorder() + const recordings = mkdtempDir() + const recorder = new VoiceRecorder(recordings) let failures = 0 - const before = listVoiceFiles() + const before = listVoiceFiles(recordings) recorder.start({ command: join(dir, "fake-rec"), buildArgs: (file) => [file] }, () => { failures += 1 }) - const file = await waitForNewVoiceFile(before).then(() => recorder.stop()) + const file = await waitForNewVoiceFile(recordings, before).then(() => recorder.stop()) expect(file).not.toBeUndefined() expect(failures).toBe(0) recorder.dispose() rmSync(dir, { recursive: true }) + rmSync(recordings, { recursive: true }) }) }) }) From d570acd28e8774ec0d4be0833d5848b17f419b36 Mon Sep 17 00:00:00 2001 From: raihanjs Date: Sun, 18 Oct 2026 13:32:55 +0600 Subject: [PATCH 4/5] fix(tui): ignore key repeats and re-entry in voice push-to-talk Review follow-up: holding the key fired the press binding on every key repeat, toggling the recorder on and off; presses during device enumeration raced past the recording check. Key repeats are now ignored via the event type, and a starting flag guards the enumeration window. The fake test recorder backgrounds its sleep so the INT trap fires immediately. --- packages/tui/src/component/prompt/index.tsx | 14 ++++++++++++-- packages/tui/test/prompt/voice.test.ts | 6 ++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx index fa5aaf2229fd..f0250640c6fa 100644 --- a/packages/tui/src/component/prompt/index.tsx +++ b/packages/tui/src/component/prompt/index.tsx @@ -6,7 +6,9 @@ import { PasteEvent, decodePasteBytes, type KeyEvent, + type Renderable, } from "@opentui/core" +import type { CommandContext } from "@opentui/keymap" import { createEffect, createMemo, onMount, createSignal, onCleanup, on, Show, Switch, Match, For } from "solid-js" import path from "path" import { useLocal } from "../../context/local" @@ -955,17 +957,25 @@ export function Prompt(props: PromptProps) { let voiceRecorder: VoiceRecorder | undefined let voiceStartTime = 0 let voiceStopTimer: ReturnType | undefined + let voiceStarting = false - async function startVoiceRecording() { + async function startVoiceRecording(event?: KeyEvent) { + // Key repeat fires the press binding while the key is held; only a real + // press may start or stop, so holding the key records without toggling. + if (event?.eventType === "repeat") return if (voiceRecorder?.recording) { void stopVoiceRecording("") return } + if (voiceStarting) return if (!config.voice?.transcribe_command) { toast.show({ variant: "error", message: "Voice input needs voice.transcribe_command to be set" }) return } + // findRecorder awaits device enumeration on Windows; guard re-entry. + voiceStarting = true const spec = await findRecorder() + voiceStarting = false if (!spec) { toast.show({ variant: "error", message: "Voice input needs ffmpeg or sox installed to record audio" }) return @@ -1025,7 +1035,7 @@ export function Prompt(props: PromptProps) { ...binding, desc: "Start voice recording (release or press again to transcribe)", group: "Prompt", - cmd: () => void startVoiceRecording(), + cmd: (context: CommandContext) => void startVoiceRecording(context.event), })), // Releasing the same key stops the recording, so one configured key // covers both halves of push-to-talk without extra configuration. diff --git a/packages/tui/test/prompt/voice.test.ts b/packages/tui/test/prompt/voice.test.ts index b57a479936f4..a13846a1fec8 100644 --- a/packages/tui/test/prompt/voice.test.ts +++ b/packages/tui/test/prompt/voice.test.ts @@ -152,8 +152,10 @@ describe("component.prompt.voice", () => { }) describe("VoiceRecorder", () => { - // Exits cleanly on SIGINT so stop() resolves without the SIGKILL fallback. - const fakeRecorder = "#!/bin/sh\ntrap 'exit 0' INT\ntouch \"$1\"\nsleep 30\n" + // Foreground sleep would delay the INT trap until it finishes; backgrounding + // it lets the trap exit immediately so stop() resolves without the SIGKILL + // fallback. + const fakeRecorder = "#!/bin/sh\ntrap 'exit 0' INT\ntouch \"$1\"\nsleep 30 & wait\n" function listVoiceFiles(dir: string): string[] { return readdirSync(dir).filter((name) => name.startsWith("opencode-voice-")) From 27433c0c6ac2c66c996ed9f040e3d05df70707a5 Mon Sep 17 00:00:00 2001 From: raihanjs Date: Sun, 18 Oct 2026 15:38:04 +0600 Subject: [PATCH 5/5] fix(tui): guard voice key against auto-repeat by timing, document toggle Review follow-up: the repeat filter never fired. The keyboard parser does not emit a repeat event type, and without event reporting a held key arrives as ordinary presses with no marker. Presses within a second of the previous one now count as key repeat (chained, so a whole hold is ignored); the terminal's repeated flag is honored too. An end-to-end test drives the real app with a fake recorder and asserts one recorder starts per simulated hold. Descriptions and docs now say press to start, press again to stop, since release events are not enabled. --- packages/tui/src/component/prompt/index.tsx | 17 +++-- packages/tui/src/component/prompt/voice.ts | 13 ++++ packages/tui/src/config/keybind.ts | 2 +- packages/tui/src/config/v1/keybind.ts | 2 +- packages/tui/test/prompt/voice-keys.test.ts | 63 +++++++++++++++++++ packages/tui/test/prompt/voice.test.ts | 26 ++++++++ services/www/src/docs/content/cli/config.mdx | 2 +- .../www/src/docs/content/cli/keybinds.mdx | 2 +- 8 files changed, 118 insertions(+), 9 deletions(-) create mode 100644 packages/tui/test/prompt/voice-keys.test.ts diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx index f0250640c6fa..cf1169e06485 100644 --- a/packages/tui/src/component/prompt/index.tsx +++ b/packages/tui/src/component/prompt/index.tsx @@ -45,6 +45,7 @@ import { findRecorder, transcribeAudio, shouldDiscardTap, + isRepeatPress, VOICE_MAX_RECORD_MS, } from "./voice" import { useRenderer, useTerminalDimensions } from "@opentui/solid" @@ -958,11 +959,17 @@ export function Prompt(props: PromptProps) { let voiceStartTime = 0 let voiceStopTimer: ReturnType | undefined let voiceStarting = false + let voiceLastPress = 0 async function startVoiceRecording(event?: KeyEvent) { - // Key repeat fires the press binding while the key is held; only a real - // press may start or stop, so holding the key records without toggling. - if (event?.eventType === "repeat") return + // Holding the key fires this binding again for every auto-repeat, and the + // TUI does not enable terminal event reporting, so repeats carry no marker. + // Presses that follow the previous one closely are the key being held; only + // a fresh press (after a quiet gap) may start or stop a recording. + const now = Date.now() + const repeating = isRepeatPress(now - voiceLastPress, event?.repeated) + voiceLastPress = now + if (repeating) return if (voiceRecorder?.recording) { void stopVoiceRecording("") return @@ -1033,7 +1040,7 @@ export function Prompt(props: PromptProps) { bindings: [ ...press.map((binding) => ({ ...binding, - desc: "Start voice recording (release or press again to transcribe)", + desc: "Start voice recording (press again to transcribe)", group: "Prompt", cmd: (context: CommandContext) => void startVoiceRecording(context.event), })), @@ -1702,7 +1709,7 @@ export function Prompt(props: PromptProps) { const placeholderText = createMemo(() => { const value = (() => { - if (voiceRecording()) return "Recording voice… release or press again to stop" + if (voiceRecording()) return "Recording voice… press the key again to stop" if (store.mode === "shell") { if (!shell().length) return undefined return `Run a command… "${shell()[store.placeholder % shell().length]}"` diff --git a/packages/tui/src/component/prompt/voice.ts b/packages/tui/src/component/prompt/voice.ts index e6a9c2c96fc8..5a64469b494f 100644 --- a/packages/tui/src/component/prompt/voice.ts +++ b/packages/tui/src/component/prompt/voice.ts @@ -13,6 +13,8 @@ import { delimiter, join } from "node:path" /** Holds shorter than this are treated as taps, not dictation. */ export const VOICE_MIN_HOLD_MS = 350 +/** Presses closer together than this are the key repeating, not new presses. */ +export const VOICE_REPEAT_GUARD_MS = 1000 /** Recordings stop automatically after this long. */ export const VOICE_MAX_RECORD_MS = 120_000 /** Placeholder replaced with the recorded wav path in the transcribe command. */ @@ -187,3 +189,14 @@ export function transcribeAudio(wavFile: string, template: string): Promise { + process.env.PATH = originalPath +}) + +// Drives the real app: a held key reaches the prompt as rapid ordinary presses +// (terminals send no repeat marker without event reporting), and recording must +// neither toggle off nor restart while it is held. The fake recorder logs each +// start, so the assertion counts recorders instead of depending on the final +// toggle state (an odd number of toggles would otherwise look correct). +test("holding the voice key records once; a press after a quiet gap stops", async () => { + const bin = mkdtempSync(join(tmpdir(), "opencode-voice-keys-")) + const log = join(bin, "starts.log") + const ffmpeg = join(bin, "ffmpeg") + // Last argument is the output file, as ffmpegArgs builds it. Exit cleanly on INT. + writeFileSync( + ffmpeg, + `#!/bin/sh\ntrap 'exit 0' INT\necho started >> '${log}'\nfor a in "$@"; do last="$a"; done\ntouch "$last"\nsleep 30 & wait\n`, + ) + chmodSync(ffmpeg, 0o755) + // Prepend: spawn() resolves ffmpeg through the child PATH. + process.env.PATH = `${bin}:${originalPath}` + const starts = () => (existsSync(log) ? readFileSync(log, "utf8").split("\n").filter(Boolean).length : 0) + + await using setup = await createAppFixture({ + config: { + animations: false, + keybinds: { "prompt.voice.push_to_talk": "f7" }, + voice: { transcribe_command: "echo transcribed" }, + }, + }) + await setup.ready + await setup.waitForFrame((frame) => frame.includes("ctrl+p commands")) + + setup.mockInput.pressKey("F7") + await setup.waitForFrame((frame) => frame.includes("Recording voice")) + expect(starts()).toBe(1) + + // Simulated hold: auto-repeat every ~33ms after the OS initial delay. + for (let index = 0; index < 8; index++) { + await Bun.sleep(33) + setup.mockInput.pressKey("F7") + } + await Bun.sleep(200) + await setup.renderOnce() + expect(starts()).toBe(1) + expect(setup.captureCharFrame()).toContain("Recording voice") + + // A fresh press after a quiet gap stops and transcribes. + await Bun.sleep(1100) + setup.mockInput.pressKey("F7") + await setup.waitForFrame((frame) => frame.includes("transcribed")) + expect(setup.captureCharFrame()).not.toContain("Recording voice") + expect(starts()).toBe(1) + + rmSync(bin, { recursive: true }) +}, 30_000) diff --git a/packages/tui/test/prompt/voice.test.ts b/packages/tui/test/prompt/voice.test.ts index a13846a1fec8..b994ecfa11f6 100644 --- a/packages/tui/test/prompt/voice.test.ts +++ b/packages/tui/test/prompt/voice.test.ts @@ -7,12 +7,14 @@ import { buildTranscribeShellCommand, ffmpegArgs, findRecorder, + isRepeatPress, shouldDiscardTap, soxArgs, transcribeAudio, VOICE_FILE_PLACEHOLDER, VOICE_MAX_RECORD_MS, VOICE_MIN_HOLD_MS, + VOICE_REPEAT_GUARD_MS, } from "../../src/component/prompt/voice" const originalPath = process.env.PATH @@ -139,6 +141,30 @@ describe("component.prompt.voice", () => { }) }) + describe("isRepeatPress", () => { + test("treats a press right after the previous one as key repeat", () => { + expect(isRepeatPress(33)).toBe(true) + expect(isRepeatPress(VOICE_REPEAT_GUARD_MS - 1)).toBe(true) + }) + + test("treats a press after a quiet gap as a fresh press", () => { + expect(isRepeatPress(VOICE_REPEAT_GUARD_MS)).toBe(false) + expect(isRepeatPress(60_000)).toBe(false) + }) + + test("honors the terminal's repeat marker regardless of timing", () => { + expect(isRepeatPress(60_000, true)).toBe(true) + expect(isRepeatPress(60_000, false)).toBe(false) + }) + + test("a held key chains: each repeat restarts the window", () => { + // First press at 0, OS initial delay 660ms, then repeats every 33ms. + const presses = [0, 660, 693, 726, 759] + const results = presses.map((now, index) => (index === 0 ? false : isRepeatPress(now - presses[index - 1]!))) + expect(results).toEqual([false, true, true, true, true]) + }) + }) + describe("shouldDiscardTap", () => { test("discards holds shorter than the minimum", () => { expect(shouldDiscardTap(VOICE_MIN_HOLD_MS - 1)).toBe(true) diff --git a/services/www/src/docs/content/cli/config.mdx b/services/www/src/docs/content/cli/config.mdx index 5aef4997ab9e..f56a881fed6f 100644 --- a/services/www/src/docs/content/cli/config.mdx +++ b/services/www/src/docs/content/cli/config.mdx @@ -111,7 +111,7 @@ Configure mouse capture, scrolling, editor context, pastes, and prompt image pre ## Voice -Hold the `prompt.voice.push_to_talk` key to record from the microphone; releasing it (or pressing it again) transcribes the recording into the prompt. Recording needs `ffmpeg` or `sox` installed, and transcription runs your own shell command. Key release must reach the terminal (Kitty keyboard protocol with release reporting) or only the press half fires. +Press the `prompt.voice.push_to_talk` key to start recording from the microphone, and press it again to stop and transcribe the recording into the prompt. Presses within a second of the previous one are treated as key repeat, so holding the key does not toggle. Recording needs `ffmpeg` or `sox` installed, and transcription runs your own shell command. OpenCode does not enable terminal key-release reporting, so releasing the key does not stop a recording today. ```json title="cli.json" { diff --git a/services/www/src/docs/content/cli/keybinds.mdx b/services/www/src/docs/content/cli/keybinds.mdx index dcc99a515cbb..555401c2dc0e 100644 --- a/services/www/src/docs/content/cli/keybinds.mdx +++ b/services/www/src/docs/content/cli/keybinds.mdx @@ -279,7 +279,7 @@ The retired `diff.toggle`, `diff.expand`, `diff.expand_all`, `diff.collapse`, an | `prompt.stash` | `none` | Stash prompt | | `prompt.stash.pop` | `none` | Pop stashed prompt | | `prompt.stash.list` | `none` | List stashed prompts | -| `prompt.voice.push_to_talk` | `none` | Record voice input; release or press again to transcribe | +| `prompt.voice.push_to_talk` | `none` | Press to record voice input, press again to transcribe | ## Input Editing