diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx index 73f61f329cee..cf1169e06485 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" @@ -38,7 +40,16 @@ 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, + isRepeatPress, + 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 +735,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 +952,111 @@ export function Prompt(props: PromptProps) { commands: stashCommands(), })) + // 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 + let voiceStarting = false + let voiceLastPress = 0 + + async function startVoiceRecording(event?: KeyEvent) { + // 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 + } + 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 + } + voiceRecorder = new VoiceRecorder() + 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) + } + + 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, + mode: "base", + enabled: inputTarget() !== undefined && !disabled() && press.length > 0, + bindings: [ + ...press.map((binding) => ({ + ...binding, + desc: "Start voice recording (press again to transcribe)", + group: "Prompt", + 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. + ...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 +1709,7 @@ export function Prompt(props: PromptProps) { const placeholderText = createMemo(() => { const value = (() => { + 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 new file mode 100644 index 000000000000..5a64469b494f --- /dev/null +++ b/packages/tui/src/component/prompt/voice.ts @@ -0,0 +1,202 @@ +/** + * 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 +/** 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. */ +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, audioDevice?: string): string[] { + const input = + platform === "darwin" + ? ["-f", "avfoundation", "-i", ":default"] + : platform === "win32" + ? ["-f", "dshow", "-i", `audio=${audioDevice ?? "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] +} + +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 async function findRecorder(platform: NodeJS.Platform = process.platform): Promise { + if (commandExists("ffmpeg")) { + 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) } + } + return undefined +} + +/** + * 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 + + 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(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) { + 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 + } + + /** 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 +} + +/** + * True when a press is the key being held down rather than a fresh press. + * Without terminal event reporting, auto-repeat arrives as ordinary presses + * with no marker, so presses closer together than the guard window count as + * repeats. The window must outlast the OS initial repeat delay (about 500 to + * 660ms by default) and chains: every press, repeat or not, restarts it. + */ +export function isRepeatPress(sinceLastPressMs: number, repeated?: boolean): boolean { + return repeated === true || sinceLastPressMs < VOICE_REPEAT_GUARD_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..18c56fcc9525 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", "Press to record voice input, 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 0c122a076b22..3022aad4501b 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", "Press to record voice input, press again to transcribe"), 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-keys.test.ts b/packages/tui/test/prompt/voice-keys.test.ts new file mode 100644 index 000000000000..1dced1c4ff24 --- /dev/null +++ b/packages/tui/test/prompt/voice-keys.test.ts @@ -0,0 +1,63 @@ +import { afterEach, expect, test } from "bun:test" +import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { createAppFixture } from "../fixture/app" + +const originalPath = process.env.PATH +afterEach(() => { + 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 new file mode 100644 index 000000000000..b994ecfa11f6 --- /dev/null +++ b/packages/tui/test/prompt/voice.test.ts @@ -0,0 +1,291 @@ +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, + 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 +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 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") + }) + + 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", async () => { + const dir = fakeBinDir({ ffmpeg: "#!/bin/sh\n", rec: "#!/bin/sh\n" }) + process.env.PATH = dir + expect((await findRecorder("linux"))?.command).toBe("ffmpeg") + rmSync(dir, { recursive: true }) + }) + + test("falls back to sox rec", async () => { + const dir = fakeBinDir({ rec: "#!/bin/sh\n" }) + process.env.PATH = dir + 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", async () => { + process.env.PATH = mkdtempDir() + 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 }) + }) + }) + + 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("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) + 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", () => { + // 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-")) + } + + async function waitForNewVoiceFile(dir: string, before: string[]): Promise { + const deadline = Date.now() + 5000 + while (Date.now() < deadline) { + 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") + } + + test("starts, stops, and resolves the recorded file", async () => { + const dir = fakeBinDir({ "fake-rec": fakeRecorder }) + 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(recordings, 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 }) + rmSync(recordings, { recursive: true }) + }) + + test("second start while recording is a no-op", async () => { + const dir = fakeBinDir({ "fake-rec": fakeRecorder }) + 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) + expect(recorder.recording).toBe(true) + recorder.dispose() + expect(recorder.recording).toBe(false) + rmSync(dir, { recursive: true }) + rmSync(recordings, { 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() + }) + + 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 recordings = mkdtempDir() + const recorder = new VoiceRecorder(recordings) + let failures = 0 + const before = listVoiceFiles(recordings) + recorder.start({ command: join(dir, "fake-rec"), buildArgs: (file) => [file] }, () => { + failures += 1 + }) + 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 }) + }) + }) +}) diff --git a/services/www/src/docs/content/cli/config.mdx b/services/www/src/docs/content/cli/config.mdx index d47ac65c98df..f56a881fed6f 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 + +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" +{ + "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..555401c2dc0e 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` | Press to record voice input, press again to transcribe | ## Input Editing