From e854dcce603248b0748ea3b45b69f670e5661d1a Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 01:27:49 +0700 Subject: [PATCH 001/205] persist toast --- lib/stt.js | 76 +++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 69 insertions(+), 7 deletions(-) diff --git a/lib/stt.js b/lib/stt.js index 2a6ed34..bf74116 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -219,6 +219,57 @@ let soxStderr = ""; let recording = false; let processing = false; +// ---- Sticky recording toast (Option A: polling to simulate persistence) ---- + +let recordingToastTimer = null; +let recordingToastFn = null; +const RECORDING_TOAST_MESSAGE = "🎙 Recording · Ctrl+R to stop"; +const RECORDING_TOAST_DURATION = 3000; +const RECORDING_TOAST_INTERVAL = 2500; + +export function __setRecordingToastFn(fn) { + recordingToastFn = fn; +} + +export function __clearRecordingToastState() { + if (recordingToastTimer) { + clearInterval(recordingToastTimer); + recordingToastTimer = null; + } + recordingToastFn = null; +} + +export function isRecordingToastActive() { + return recordingToastTimer !== null; +} + +export function showRecordingToast() { + clearRecordingToast(); + if (recordingToastFn) { + recordingToastFn({ + message: RECORDING_TOAST_MESSAGE, + variant: "info", + duration: RECORDING_TOAST_DURATION, + }); + } + recordingToastTimer = setInterval(() => { + if (recordingToastFn) { + recordingToastFn({ + message: RECORDING_TOAST_MESSAGE, + variant: "info", + duration: RECORDING_TOAST_DURATION, + }); + } + }, RECORDING_TOAST_INTERVAL); +} + +export function clearRecordingToast() { + if (recordingToastTimer) { + clearInterval(recordingToastTimer); + recordingToastTimer = null; + } +} + function forceKillSox(logger) { if (soxProc) { try { @@ -271,6 +322,7 @@ function startRecording(kv, backend, toast, logger) { logger?.log("STT", `Recording failed: ${err.message}`, "error"); if (recording) { recording = false; + clearRecordingToast(); toast(`Recording failed: ${err.message}${audioFailureSuffix(backend)}`, "error"); } }); @@ -282,13 +334,16 @@ function startRecording(kv, backend, toast, logger) { `sox exited code=${code} stderr=${soxStderr.trim()}`, code === 0 || code === null ? "debug" : "warn", ); - if (recording && code !== 0 && code !== null && !processing) { + if (recording && !processing) { recording = false; - const errLine = soxStderr.trim().split("\n").pop(); - toast( - `Recording error: ${errLine || `sox exited (code=${code})`}${audioFailureSuffix(backend)}`, - "error", - ); + clearRecordingToast(); + if (code !== 0 && code !== null) { + const errLine = soxStderr.trim().split("\n").pop(); + toast( + `Recording error: ${errLine || `sox exited (code=${code})`}${audioFailureSuffix(backend)}`, + "error", + ); + } } }); @@ -564,6 +619,7 @@ async function doTranscribePipeline( logger, ) { processing = true; + clearRecordingToast(); try { logger?.log("STT", `Pipeline started submit=${submit}`, "debug"); stopRecording(logger); @@ -623,6 +679,9 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { api.ui.toast({ message, variant, duration: 3000 }); } + __setRecordingToastFn((input) => api.ui.toast(input)); + api.lifecycle?.onDispose?.(() => clearRecordingToast()); + if (opts?.sttEndpoint) { sttApiEndpoint = opts.sttEndpoint; sttApiModel = opts.sttModel || "whisper-large-v3-turbo"; @@ -662,11 +721,12 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { return; } if (recording) { + clearRecordingToast(); toast("Stopping, transcribing..."); doTranscribePipeline(kv, complete, client, toast, systemPrompt, false, logger); } else { startRecording(kv, backend, toast, logger); - if (recording) toast("Recording... press again to transcribe"); + if (recording) showRecordingToast(); } }, }, @@ -687,6 +747,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { toast("No recording in progress", "warning"); return; } + clearRecordingToast(); toast("Stopping, transcribing..."); doTranscribePipeline(kv, complete, client, toast, systemPrompt, true, logger); }, @@ -699,6 +760,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { onSelect() { if (recording) { recording = false; + clearRecordingToast(); forceKillSox(logger); logger?.log("STT", "Recording cancelled", "debug"); toast("Recording cancelled"); From dd7f3063da85630f7645899746dde05a928cff7b Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 01:33:44 +0700 Subject: [PATCH 002/205] wave --- lib/stt.js | 100 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 94 insertions(+), 6 deletions(-) diff --git a/lib/stt.js b/lib/stt.js index bf74116..bc39cce 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -223,9 +223,17 @@ let processing = false; let recordingToastTimer = null; let recordingToastFn = null; -const RECORDING_TOAST_MESSAGE = "🎙 Recording · Ctrl+R to stop"; +const RECORDING_TOAST_BASE = "🎙 Recording"; const RECORDING_TOAST_DURATION = 3000; const RECORDING_TOAST_INTERVAL = 2500; +// Live wave + timer config (PR2) +let recordingStartMs = null; +let waveHistory = []; +const WAVE_CHARS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"]; +const WAVE_LEN = 14; +const WAVE_INTERVAL = 120; +const WAVE_DURATION = 350; +let useWave = true; export function __setRecordingToastFn(fn) { recordingToastFn = fn; @@ -237,30 +245,109 @@ export function __clearRecordingToastState() { recordingToastTimer = null; } recordingToastFn = null; + recordingStartMs = null; + waveHistory = []; +} + +export function __setUseWave(v) { + useWave = !!v; } export function isRecordingToastActive() { return recordingToastTimer !== null; } +export function formatElapsed(ms) { + const totalSec = Math.floor(ms / 1000); + const m = String(Math.floor(totalSec / 60)).padStart(2, "0"); + const s = String(totalSec % 60).padStart(2, "0"); + return `${m}:${s}`; +} + +export function rmsToChar(rms) { + // more sensitive: quiet speech ~0.015 now hits mid bars + if (rms < 0.005) return WAVE_CHARS[0]; + if (rms < 0.012) return WAVE_CHARS[1]; + if (rms < 0.025) return WAVE_CHARS[2]; + if (rms < 0.05) return WAVE_CHARS[3]; + if (rms < 0.085) return WAVE_CHARS[4]; + if (rms < 0.13) return WAVE_CHARS[5]; + if (rms < 0.2) return WAVE_CHARS[6]; + return WAVE_CHARS[7]; +} + +function fakePulseChar() { + // faster, multi-frequency pulse so still looks alive when mic silent + const t = Date.now() / 120; + const v = (Math.sin(t) + 0.5 * Math.sin(t * 2.3) + 1.5) / 3; + const idx = Math.floor(v * (WAVE_CHARS.length - 1)); + return WAVE_CHARS[idx]; +} + +export function computeWaveChar() { + const wavFile = path.join(tmpDir, WAV_FILENAME); + try { + const data = fs.readFileSync(wavFile); + if (data.length <= 44) return fakePulseChar(); + // shorter window ~0.08s = 2560 bytes → much more instant response + const windowSize = 2560; + const start = Math.max(44, data.length - windowSize); + const slice = data.subarray(start); + const samples = Math.floor(slice.length / 2); + if (samples === 0) return fakePulseChar(); + let sum = 0; + for (let i = 0; i < slice.length - 1; i += 2) { + const s = slice.readInt16LE(i); + const n = s / 32768; + sum += n * n; + } + const rms = Math.sqrt(sum / samples); + // very quiet (<0.003) still pulse; 0.003-0.005 already maps to ▁/▂ so keep real + if (rms < 0.003) return fakePulseChar(); + return rmsToChar(rms); + } catch { + return fakePulseChar(); + } +} + +export function getWaveString() { + const ch = computeWaveChar(); + waveHistory.push(ch); + if (waveHistory.length > WAVE_LEN) waveHistory.shift(); + // pad with low blocks at start + while (waveHistory.length < WAVE_LEN) waveHistory.unshift(WAVE_CHARS[0]); + return waveHistory.join(""); +} + +export function buildRecordingMessage() { + if (!useWave || recordingStartMs === null) return `${RECORDING_TOAST_BASE} · Ctrl+R to stop`; + const elapsed = formatElapsed(Date.now() - recordingStartMs); + const wave = getWaveString(); + return `${RECORDING_TOAST_BASE} ${wave} ${elapsed} · Ctrl+R to stop`; +} + export function showRecordingToast() { clearRecordingToast(); + recordingStartMs = Date.now(); + waveHistory = Array(WAVE_LEN).fill(WAVE_CHARS[0]); + const interval = useWave ? WAVE_INTERVAL : RECORDING_TOAST_INTERVAL; + const duration = useWave ? WAVE_DURATION : RECORDING_TOAST_DURATION; if (recordingToastFn) { recordingToastFn({ - message: RECORDING_TOAST_MESSAGE, + message: buildRecordingMessage(), variant: "info", - duration: RECORDING_TOAST_DURATION, + duration, }); } recordingToastTimer = setInterval(() => { if (recordingToastFn) { recordingToastFn({ - message: RECORDING_TOAST_MESSAGE, + message: buildRecordingMessage(), variant: "info", - duration: RECORDING_TOAST_DURATION, + duration, }); } - }, RECORDING_TOAST_INTERVAL); + }, interval); } export function clearRecordingToast() { @@ -268,6 +355,7 @@ export function clearRecordingToast() { clearInterval(recordingToastTimer); recordingToastTimer = null; } + recordingStartMs = null; } function forceKillSox(logger) { From 0e4e8e8233a74c5d5eedb1d651a0bea0b7e5544f Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 01:34:30 +0700 Subject: [PATCH 003/205] suffix endpoints --- lib/llm-client.js | 111 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 96 insertions(+), 15 deletions(-) diff --git a/lib/llm-client.js b/lib/llm-client.js index f71b495..0d6b376 100644 --- a/lib/llm-client.js +++ b/lib/llm-client.js @@ -23,6 +23,55 @@ const DEFAULTS = { retries: 2, }; +function isResponsesEndpoint(endpoint, explicitFlag) { + if (explicitFlag === true) return true; + if (explicitFlag === false) return false; + const trimmed = (endpoint || "").replace(/\/+$/, ""); + return trimmed.endsWith("/responses"); +} + +function isChatCompletionsEndpoint(endpoint) { + const trimmed = (endpoint || "").replace(/\/+$/, ""); + return trimmed.endsWith("/chat/completions"); +} + +function resolveEndpoint(raw, useResponses) { + const trimmed = (raw || "").replace(/\/+$/, ""); + if (!trimmed) return trimmed; + if ( + isChatCompletionsEndpoint(trimmed) || + (isResponsesEndpoint(trimmed, useResponses === true ? true : null) && + trimmed.endsWith("/responses")) + ) { + // already a full path — use as-is + if (trimmed.endsWith("/chat/completions") || trimmed.endsWith("/responses")) return trimmed; + } + if (isResponsesEndpoint(raw, useResponses)) return `${trimmed}/responses`; + return `${trimmed}/chat/completions`; +} + +function extractResponsesText(data) { + if (!data) return null; + if (typeof data.output_text === "string" && data.output_text.trim()) return data.output_text; + // output: [{ type:"message", content:[{type:"output_text", text:"..."}] }] + const out = data.output; + if (Array.isArray(out)) { + for (const item of out) { + const content = item?.content; + if (Array.isArray(content)) { + for (const c of content) { + if (typeof c?.text === "string" && c.text.trim()) return c.text; + if (typeof c?.output_text === "string" && c.output_text.trim()) return c.output_text; + } + } else if (typeof content?.text === "string" && content.text.trim()) { + return content.text; + } + } + } + // some gateways return choices like chat + return data?.choices?.[0]?.message?.content || null; +} + function normalizeRetries(value) { const parsed = Number(value); if (!Number.isFinite(parsed) || parsed < 0) return DEFAULTS.retries; @@ -57,6 +106,18 @@ function wait(ms) { */ export function createClient(pluginOptions, logger) { function getConfig() { + const rawUseResponses = + pluginOptions?.useResponsesApi ?? + pluginOptions?.responsesApi ?? + pluginOptions?.useResponses ?? + null; + // allow explicit apiMode: "responses" | "chat" + const modeFlag = + pluginOptions?.apiMode === "responses" + ? true + : pluginOptions?.apiMode === "chat" + ? false + : rawUseResponses; return { endpoint: pluginOptions?.endpoint, model: pluginOptions?.model, @@ -67,6 +128,7 @@ export function createClient(pluginOptions, logger) { pluginOptions?.chatTemplateKwargs ?? DEFAULTS.chatTemplateKwargs, ), retries: normalizeRetries(pluginOptions?.retries ?? DEFAULTS.retries), + useResponsesApi: modeFlag, }; } @@ -91,19 +153,32 @@ export function createClient(pluginOptions, logger) { } const apiKey = cfg.apiKeyEnv ? process.env[cfg.apiKeyEnv] : null; - const endpoint = cfg.endpoint.replace(/\/+$/, "") + "/chat/completions"; - - const messages = []; - if (system) messages.push({ role: "system", content: system }); - messages.push({ role: "user", content: prompt }); - - const body = { - model: cfg.model, - max_tokens: cfg.maxTokens, - messages, - }; - if (cfg.reasoningEffort) body.reasoning_effort = cfg.reasoningEffort; - if (cfg.chatTemplateKwargs) body.chat_template_kwargs = cfg.chatTemplateKwargs; + const useResponses = isResponsesEndpoint(cfg.endpoint, cfg.useResponsesApi); + const endpoint = resolveEndpoint(cfg.endpoint, cfg.useResponsesApi); + + let body; + if (useResponses) { + body = { + model: cfg.model, + input: prompt, + instructions: system || undefined, + max_output_tokens: cfg.maxTokens, + }; + if (cfg.reasoningEffort) body.reasoning = { effort: cfg.reasoningEffort }; + // chat_template_kwargs not standard for responses, but pass through if needed + if (cfg.chatTemplateKwargs) body.chat_template_kwargs = cfg.chatTemplateKwargs; + } else { + const messages = []; + if (system) messages.push({ role: "system", content: system }); + messages.push({ role: "user", content: prompt }); + body = { + model: cfg.model, + max_tokens: cfg.maxTokens, + messages, + }; + if (cfg.reasoningEffort) body.reasoning_effort = cfg.reasoningEffort; + if (cfg.chatTemplateKwargs) body.chat_template_kwargs = cfg.chatTemplateKwargs; + } for (let attempt = 0; attempt <= cfg.retries; attempt++) { try { @@ -135,9 +210,15 @@ export function createClient(pluginOptions, logger) { } const data = await response.json(); - const text = data?.choices?.[0]?.message?.content || null; + const text = useResponses + ? extractResponsesText(data) + : data?.choices?.[0]?.message?.content || null; if (text) { - logger?.log?.("LLM", `Completion succeeded chars=${text.length}`, "debug"); + logger?.log?.( + "LLM", + `Completion succeeded chars=${text.length} mode=${useResponses ? "responses" : "chat"}`, + "debug", + ); return { text }; } From 21751fb6fb093a54f3f4d1c84801ee8da410c13e Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 01:45:40 +0700 Subject: [PATCH 004/205] halluciation --- lib/llm-client.js | 9 ++++++ lib/stt.js | 76 ++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 74 insertions(+), 11 deletions(-) diff --git a/lib/llm-client.js b/lib/llm-client.js index 0d6b376..f51bfa6 100644 --- a/lib/llm-client.js +++ b/lib/llm-client.js @@ -21,6 +21,7 @@ const DEFAULTS = { reasoningEffort: null, chatTemplateKwargs: null, retries: 2, + temperature: null, }; function isResponsesEndpoint(endpoint, explicitFlag) { @@ -128,6 +129,10 @@ export function createClient(pluginOptions, logger) { pluginOptions?.chatTemplateKwargs ?? DEFAULTS.chatTemplateKwargs, ), retries: normalizeRetries(pluginOptions?.retries ?? DEFAULTS.retries), + temperature: + pluginOptions?.temperature != null + ? Number(pluginOptions.temperature) + : DEFAULTS.temperature, useResponsesApi: modeFlag, }; } @@ -164,6 +169,8 @@ export function createClient(pluginOptions, logger) { instructions: system || undefined, max_output_tokens: cfg.maxTokens, }; + if (cfg.temperature != null && Number.isFinite(cfg.temperature)) + body.temperature = cfg.temperature; if (cfg.reasoningEffort) body.reasoning = { effort: cfg.reasoningEffort }; // chat_template_kwargs not standard for responses, but pass through if needed if (cfg.chatTemplateKwargs) body.chat_template_kwargs = cfg.chatTemplateKwargs; @@ -176,6 +183,8 @@ export function createClient(pluginOptions, logger) { max_tokens: cfg.maxTokens, messages, }; + if (cfg.temperature != null && Number.isFinite(cfg.temperature)) + body.temperature = cfg.temperature; if (cfg.reasoningEffort) body.reasoning_effort = cfg.reasoningEffort; if (cfg.chatTemplateKwargs) body.chat_template_kwargs = cfg.chatTemplateKwargs; } diff --git a/lib/stt.js b/lib/stt.js index bc39cce..768a9ae 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -545,17 +545,36 @@ function transcribe(kv, logger) { }); } -const STT_SYSTEM_PROMPT = `You are a speech-to-text normalizer for a coding assistant CLI. - -Clean up raw whisper transcription into a clear, well-punctuated prompt. Rules: -- Fix punctuation, capitalization, and grammar -- Remove filler words (um, uh, like, you know, etc.) -- Keep technical terms, file names, and code references exact -- If the user is dictating code, format it appropriately -- Use the session context above to resolve ambiguous references (e.g. "that function", "the file", "it") -- Output ONLY the cleaned text, nothing else -- Do not add any commentary or explanation -- Keep the user's intent and meaning intact +const STT_SYSTEM_PROMPT = `You are a DETERMINISTIC speech-to-text normalizer for a coding assistant CLI. You are NOT a chatbot. You NEVER answer, explain, greet back, or introduce yourself. + +Task: Return ONLY the cleaned version of the user's spoken words — exactly what they said, with punctuation and homophone fixes. No reply. No extra sentences. + +Strict rules: +- Output is the user's utterance, cleaned. It is NOT a response to the user. +- Fix punctuation, capitalization, grammar minimally. +- Remove filler words (um, uh, like, you know, etc.). +- Keep technical terms, file names, and code references exact. +- If the user is dictating code, format it appropriately. +- Use session context only to resolve ambiguous pronouns (that function, the file, it) — do not invent new content. +- Output ONLY the cleaned text, nothing else. No quotes, no prefixes, no suffixes. +- Do NOT add greetings, introductions, offers to help, questions, or commentary. +- Do NOT expand short inputs. Keep output length close to input length; do not add paragraphs. +- If input is a short greeting/noise like "hey", "hello", "hi", "hey there", output exactly that greeting capitalized with a period (e.g., "hey" -> "Hey.") — DO NOT expand to "Hello! I am an AI..." or add self-introduction. + +Examples (follow exactly): +Input: "hey" +Output: Hey. + +Input: "hello there" +Output: Hello there. + +Input: "umm add tests for the a sink user service" +Output: Add tests for the async user service. + +Input: "check the locks for the doc container" +Output: Check the logs for the Docker container. + +If you cannot normalize, return the input trimmed. CRITICAL DOMAIN CORRECTIONS - Fix common STT homophone errors in software engineering contexts: - "locks" -> "logs" (unless explicitly talking about mutexes/concurrency) @@ -577,6 +596,32 @@ CRITICAL DOMAIN CORRECTIONS - Fix common STT homophone errors in software engine Rely heavily on context to fix words that sound similar to programming terminology.`; +const STT_HALLUCINATION_PATTERNS = [ + /I am (an )?AI/i, + /as an AI/i, + /language model/i, + /nice to meet you/i, + /how can I help/i, + /hello! I am/i, + /I'm here to help/i, +]; + +function isHallucinated(raw, normalized) { + if (!normalized) return false; + if (STT_HALLUCINATION_PATTERNS.some((re) => re.test(normalized))) return true; + // blow-up: short input -> long output is hallucination (e.g., "hey" -> paragraph) + if (raw.length <= 20 && normalized.length > raw.length * 4 + 20) return true; + if (raw.length <= 10 && normalized.split(/\s+/).length > 10) return true; + return false; +} + +function fallbackForRaw(raw) { + const t = raw.trim(); + if (!t) return t; + // minimal cleanup: capitalize first letter, ensure trailing period for greetings + return t.charAt(0).toUpperCase() + t.slice(1); +} + async function normalizeTranscription(complete, rawText, sessionTitle, systemPrompt, logger) { const contextLine = sessionTitle ? ` The user is currently working on: "${sessionTitle}"` : ""; const system = `${systemPrompt}${contextLine}`; @@ -585,7 +630,16 @@ async function normalizeTranscription(complete, rawText, sessionTitle, systemPro const result = await complete({ system, prompt: `Clean up this speech-to-text transcription:\n\n${rawText}`, + config: { temperature: 0 }, }); + if (result.text && isHallucinated(rawText, result.text)) { + logger?.log( + "STT", + `Hallucination detected raw="${rawText.slice(0, 30)}" normalized="${result.text.slice(0, 80)}" -> fallback`, + "warn", + ); + return { text: fallbackForRaw(rawText) }; + } return result; } From 5d1a6af3fa4224b487837f039743404a20045550 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 01:53:24 +0700 Subject: [PATCH 005/205] better wave UI --- lib/stt.js | 99 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 69 insertions(+), 30 deletions(-) diff --git a/lib/stt.js b/lib/stt.js index 768a9ae..dc2aa8c 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -228,11 +228,11 @@ const RECORDING_TOAST_DURATION = 3000; const RECORDING_TOAST_INTERVAL = 2500; // Live wave + timer config (PR2) let recordingStartMs = null; -let waveHistory = []; +let prevWaveLevels = []; const WAVE_CHARS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"]; -const WAVE_LEN = 14; -const WAVE_INTERVAL = 120; -const WAVE_DURATION = 350; +const WAVE_LEN = 16; +const WAVE_INTERVAL = 80; +const WAVE_DURATION = 280; let useWave = true; export function __setRecordingToastFn(fn) { @@ -246,7 +246,7 @@ export function __clearRecordingToastState() { } recordingToastFn = null; recordingStartMs = null; - waveHistory = []; + prevWaveLevels = []; } export function __setUseWave(v) { @@ -265,36 +265,39 @@ export function formatElapsed(ms) { } export function rmsToChar(rms) { - // more sensitive: quiet speech ~0.015 now hits mid bars - if (rms < 0.005) return WAVE_CHARS[0]; - if (rms < 0.012) return WAVE_CHARS[1]; - if (rms < 0.025) return WAVE_CHARS[2]; - if (rms < 0.05) return WAVE_CHARS[3]; - if (rms < 0.085) return WAVE_CHARS[4]; + // tuned for 16kHz mono: quiet 0.008→▂, normal 0.03→▅, loud 0.15→█ + if (rms < 0.004) return WAVE_CHARS[0]; + if (rms < 0.01) return WAVE_CHARS[1]; + if (rms < 0.022) return WAVE_CHARS[2]; + if (rms < 0.045) return WAVE_CHARS[3]; + if (rms < 0.08) return WAVE_CHARS[4]; if (rms < 0.13) return WAVE_CHARS[5]; if (rms < 0.2) return WAVE_CHARS[6]; return WAVE_CHARS[7]; } -function fakePulseChar() { - // faster, multi-frequency pulse so still looks alive when mic silent - const t = Date.now() / 120; - const v = (Math.sin(t) + 0.5 * Math.sin(t * 2.3) + 1.5) / 3; - const idx = Math.floor(v * (WAVE_CHARS.length - 1)); - return WAVE_CHARS[idx]; +export function rmsToLevel(rms) { + if (rms < 0.004) return 0; + if (rms < 0.01) return 1; + if (rms < 0.022) return 2; + if (rms < 0.045) return 3; + if (rms < 0.08) return 4; + if (rms < 0.13) return 5; + if (rms < 0.2) return 6; + return 7; } export function computeWaveChar() { + // kept for tests / fallback single-char const wavFile = path.join(tmpDir, WAV_FILENAME); try { const data = fs.readFileSync(wavFile); - if (data.length <= 44) return fakePulseChar(); - // shorter window ~0.08s = 2560 bytes → much more instant response + if (data.length <= 44) return WAVE_CHARS[0]; const windowSize = 2560; const start = Math.max(44, data.length - windowSize); const slice = data.subarray(start); const samples = Math.floor(slice.length / 2); - if (samples === 0) return fakePulseChar(); + if (samples === 0) return WAVE_CHARS[0]; let sum = 0; for (let i = 0; i < slice.length - 1; i += 2) { const s = slice.readInt16LE(i); @@ -302,21 +305,57 @@ export function computeWaveChar() { sum += n * n; } const rms = Math.sqrt(sum / samples); - // very quiet (<0.003) still pulse; 0.003-0.005 already maps to ▁/▂ so keep real - if (rms < 0.003) return fakePulseChar(); + if (rms < 0.003) return WAVE_CHARS[0]; return rmsToChar(rms); } catch { - return fakePulseChar(); + return WAVE_CHARS[0]; } } export function getWaveString() { - const ch = computeWaveChar(); - waveHistory.push(ch); - if (waveHistory.length > WAVE_LEN) waveHistory.shift(); - // pad with low blocks at start - while (waveHistory.length < WAVE_LEN) waveHistory.unshift(WAVE_CHARS[0]); - return waveHistory.join(""); + // Fixed-column snapshot: each column = RMS of sub-slice of last ~0.16s window + const wavFile = path.join(tmpDir, WAV_FILENAME); + try { + const data = fs.readFileSync(wavFile); + if (data.length <= 44) { + prevWaveLevels = Array(WAVE_LEN).fill(0); + return WAVE_CHARS[0].repeat(WAVE_LEN); + } + const windowSize = 5120; // ~0.16s at 16kHz mono 16-bit + const start = Math.max(44, data.length - windowSize); + const slice = data.subarray(start); + const chunkBytes = Math.max(2, Math.floor(slice.length / WAVE_LEN)); + const levels = []; + for (let c = 0; c < WAVE_LEN; c++) { + const off = c * chunkBytes; + const chunk = slice.subarray(off, Math.min(off + chunkBytes, slice.length)); + const samples = Math.floor(chunk.length / 2); + if (samples === 0) { + levels.push(0); + continue; + } + let sum = 0; + for (let i = 0; i < chunk.length - 1; i += 2) { + const s = chunk.readInt16LE(i); + const n = s / 32768; + sum += n * n; + } + const rms = Math.sqrt(sum / samples); + levels.push(rmsToLevel(rms)); + } + // decay smoothing: fast attack, slow decay for punchy feel + if (prevWaveLevels.length !== WAVE_LEN) prevWaveLevels = Array(WAVE_LEN).fill(0); + const smoothed = levels.map((lvl, i) => { + const prev = prevWaveLevels[i] || 0; + const decayed = Math.floor(prev * 0.55); + return lvl > prev ? lvl : Math.max(lvl, decayed); + }); + prevWaveLevels = smoothed.slice(); + return smoothed.map((l) => WAVE_CHARS[l]).join(""); + } catch { + prevWaveLevels = Array(WAVE_LEN).fill(0); + return WAVE_CHARS[0].repeat(WAVE_LEN); + } } export function buildRecordingMessage() { @@ -329,7 +368,7 @@ export function buildRecordingMessage() { export function showRecordingToast() { clearRecordingToast(); recordingStartMs = Date.now(); - waveHistory = Array(WAVE_LEN).fill(WAVE_CHARS[0]); + prevWaveLevels = Array(WAVE_LEN).fill(0); const interval = useWave ? WAVE_INTERVAL : RECORDING_TOAST_INTERVAL; const duration = useWave ? WAVE_DURATION : RECORDING_TOAST_DURATION; if (recordingToastFn) { From 9e5daaf2b342be9323af757ab699dd19c470fdc4 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 02:04:03 +0700 Subject: [PATCH 006/205] keybind fix -> using command palette --- index.js | 23 +++++++------- lib/stt.js | 91 +++++++++++++++++++++++++++++++++++++++--------------- lib/tts.js | 15 ++++++--- 3 files changed, 89 insertions(+), 40 deletions(-) diff --git a/index.js b/index.js index 3a324b1..675329f 100644 --- a/index.js +++ b/index.js @@ -15,17 +15,18 @@ // // Runtime state (model, mic, voice, tts mode) persisted via api.kv. // -// Commands: -// /stt-record (ctrl+r) - start/stop recording + transcribe -// /stt-submit (leader+r)- stop recording + transcribe + submit -// /stt-stop - cancel recording -// /stt-model - select whisper model -// /stt-language - select transcription language -// /stt-mic - select microphone -// /tts-speak (leader+s)- read last response aloud -// /tts-mode (leader+v) - toggle auto TTS on/off -// /tts-stop (escape) - stop playback +// Commands (palette + slash, no default keybind — set via plugin options `keybinds` if needed): +// /stt-record - start/stop recording + transcribe +// /stt-submit - stop recording + transcribe + submit +// /stt-stop - cancel recording +// /stt-model - select whisper model +// /stt-language - select transcription language +// /stt-mic - select microphone +// /tts-speak - read last response aloud +// /tts-mode - toggle auto TTS on/off +// /tts-stop - stop playback // /tts-voice - select TTS voice +// Example keybinds: { "keybinds": { "stt.record": "ctrl+r", "tts.speak-last": "s" } } import fs from "node:fs"; import os from "node:os"; @@ -66,7 +67,7 @@ export default { }; const sttCommands = registerSTT(api, kv, complete, prompts, options, logger); - const ttsCommands = registerTTS(api, kv, complete, prompts, logger); + const ttsCommands = registerTTS(api, kv, complete, prompts, options, logger); api.command.register(() => [...sttCommands, ...ttsCommands]); }, diff --git a/lib/stt.js b/lib/stt.js index dc2aa8c..634c04f 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -229,10 +229,12 @@ const RECORDING_TOAST_INTERVAL = 2500; // Live wave + timer config (PR2) let recordingStartMs = null; let prevWaveLevels = []; +let noiseFloorRms = null; +let calibrationEndMs = null; const WAVE_CHARS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"]; const WAVE_LEN = 16; -const WAVE_INTERVAL = 80; -const WAVE_DURATION = 280; +const WAVE_INTERVAL = 60; +const WAVE_DURATION = 220; let useWave = true; export function __setRecordingToastFn(fn) { @@ -247,6 +249,8 @@ export function __clearRecordingToastState() { recordingToastFn = null; recordingStartMs = null; prevWaveLevels = []; + noiseFloorRms = null; + calibrationEndMs = null; } export function __setUseWave(v) { @@ -265,25 +269,24 @@ export function formatElapsed(ms) { } export function rmsToChar(rms) { - // tuned for 16kHz mono: quiet 0.008→▂, normal 0.03→▅, loud 0.15→█ - if (rms < 0.004) return WAVE_CHARS[0]; - if (rms < 0.01) return WAVE_CHARS[1]; - if (rms < 0.022) return WAVE_CHARS[2]; - if (rms < 0.045) return WAVE_CHARS[3]; - if (rms < 0.08) return WAVE_CHARS[4]; - if (rms < 0.13) return WAVE_CHARS[5]; - if (rms < 0.2) return WAVE_CHARS[6]; + if (rms < 0.008) return WAVE_CHARS[0]; + if (rms < 0.018) return WAVE_CHARS[1]; + if (rms < 0.035) return WAVE_CHARS[2]; + if (rms < 0.06) return WAVE_CHARS[3]; + if (rms < 0.1) return WAVE_CHARS[4]; + if (rms < 0.16) return WAVE_CHARS[5]; + if (rms < 0.24) return WAVE_CHARS[6]; return WAVE_CHARS[7]; } export function rmsToLevel(rms) { - if (rms < 0.004) return 0; - if (rms < 0.01) return 1; - if (rms < 0.022) return 2; - if (rms < 0.045) return 3; - if (rms < 0.08) return 4; - if (rms < 0.13) return 5; - if (rms < 0.2) return 6; + if (rms < 0.008) return 0; + if (rms < 0.018) return 1; + if (rms < 0.035) return 2; + if (rms < 0.06) return 3; + if (rms < 0.1) return 4; + if (rms < 0.16) return 5; + if (rms < 0.24) return 6; return 7; } @@ -313,7 +316,7 @@ export function computeWaveChar() { } export function getWaveString() { - // Fixed-column snapshot: each column = RMS of sub-slice of last ~0.16s window + // Fixed-column snapshot: each column = noise-gated RMS of sub-slice of last ~0.08s window const wavFile = path.join(tmpDir, WAV_FILENAME); try { const data = fs.readFileSync(wavFile); @@ -321,16 +324,18 @@ export function getWaveString() { prevWaveLevels = Array(WAVE_LEN).fill(0); return WAVE_CHARS[0].repeat(WAVE_LEN); } - const windowSize = 5120; // ~0.16s at 16kHz mono 16-bit + const windowSize = 2560; // ~0.08s at 16kHz mono 16-bit → very instant const start = Math.max(44, data.length - windowSize); const slice = data.subarray(start); const chunkBytes = Math.max(2, Math.floor(slice.length / WAVE_LEN)); + const rawRms = []; const levels = []; for (let c = 0; c < WAVE_LEN; c++) { const off = c * chunkBytes; const chunk = slice.subarray(off, Math.min(off + chunkBytes, slice.length)); const samples = Math.floor(chunk.length / 2); if (samples === 0) { + rawRms.push(0); levels.push(0); continue; } @@ -341,14 +346,39 @@ export function getWaveString() { sum += n * n; } const rms = Math.sqrt(sum / samples); - levels.push(rmsToLevel(rms)); + rawRms.push(rms); } - // decay smoothing: fast attack, slow decay for punchy feel + // calibration: first 350ms after recording start estimates fan noise floor + const now = Date.now(); + if (calibrationEndMs && now < calibrationEndMs) { + const minRms = Math.min(...rawRms); + if (noiseFloorRms === null || minRms < noiseFloorRms) noiseFloorRms = minRms; + // during calibration show flat low so user sees not yet sensitive + prevWaveLevels = Array(WAVE_LEN).fill(0); + return WAVE_CHARS[0].repeat(WAVE_LEN); + } + if (noiseFloorRms === null) noiseFloorRms = Math.min(...rawRms); + else { + // slowly adapt noise floor down (fan may vary) but never jump up quickly + const minRms = Math.min(...rawRms); + // if we see a consistently lower min for 500ms, drift down 5% + noiseFloorRms = Math.min(noiseFloorRms, minRms); + noiseFloorRms = noiseFloorRms * 0.995 + minRms * 0.005; + } + // console.log(`[wave] noiseFloor=${noiseFloorRms?.toFixed(4)} rawMin=${Math.min(...rawRms).toFixed(4)} rawMax=${Math.max(...rawRms).toFixed(4)}`); + for (const rms of rawRms) { + const effective = Math.max(0, rms - noiseFloorRms * 1.15); + // gate: very small effective still flat — fan residue + if (effective < 0.005) levels.push(0); + else levels.push(rmsToLevel(effective * 1.6)); // 1.6x gain makes voice pop higher + } + // instant attack, very fast decay (0.2) → fan doesn't linger, voice explicit if (prevWaveLevels.length !== WAVE_LEN) prevWaveLevels = Array(WAVE_LEN).fill(0); const smoothed = levels.map((lvl, i) => { const prev = prevWaveLevels[i] || 0; - const decayed = Math.floor(prev * 0.55); - return lvl > prev ? lvl : Math.max(lvl, decayed); + if (lvl > prev) return lvl; // instant rise + const decayed = Math.floor(prev * 0.2); + return lvl > decayed ? lvl : decayed; }); prevWaveLevels = smoothed.slice(); return smoothed.map((l) => WAVE_CHARS[l]).join(""); @@ -369,6 +399,8 @@ export function showRecordingToast() { clearRecordingToast(); recordingStartMs = Date.now(); prevWaveLevels = Array(WAVE_LEN).fill(0); + noiseFloorRms = null; + calibrationEndMs = Date.now() + 350; const interval = useWave ? WAVE_INTERVAL : RECORDING_TOAST_INTERVAL; const duration = useWave ? WAVE_DURATION : RECORDING_TOAST_DURATION; if (recordingToastFn) { @@ -395,6 +427,8 @@ export function clearRecordingToast() { recordingToastTimer = null; } recordingStartMs = null; + noiseFloorRms = null; + calibrationEndMs = null; } function forceKillSox(logger) { @@ -887,6 +921,13 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { } logger?.log("STT", `STT temp dir=${tmpDir}`, "debug"); + function kb(value) { + const v = opts?.keybinds?.[value]; + if (v === undefined) return undefined; + if (!v || v === "none") return undefined; + return v; + } + return [ { title: sttApiEndpoint ? "STT: record/transcribe (API)" : "STT: record/transcribe", @@ -894,7 +935,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { description: sttApiEndpoint ? "Toggle recording; press again to stop and transcribe via API" : "Toggle recording; press again to stop and transcribe", - keybind: "ctrl+r", + ...(kb("stt.record") ? { keybind: kb("stt.record") } : {}), slash: { name: "stt-record" }, onSelect() { if (processing) { @@ -917,7 +958,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { description: sttApiEndpoint ? "Stop recording, transcribe via API, and submit prompt" : "Stop recording, transcribe, and submit prompt", - keybind: "r", + ...(kb("stt.submit") ? { keybind: kb("stt.submit") } : {}), slash: { name: "stt-submit" }, onSelect() { if (processing) { diff --git a/lib/tts.js b/lib/tts.js index c97967b..12a96d3 100644 --- a/lib/tts.js +++ b/lib/tts.js @@ -104,7 +104,7 @@ async function getTurnAssistantText(client, api) { // ---- Public API for TUI plugin ---- -export function registerTTS(api, kv, complete, prompts, logger) { +export function registerTTS(api, kv, complete, prompts, opts, logger) { const client = api.client; const systemAuto = prompts?.ttsAuto || SYSTEM_AUTO; const systemManual = prompts?.ttsManual || SYSTEM_MANUAL; @@ -338,6 +338,13 @@ export function registerTTS(api, kv, complete, prompts, logger) { await speak(llmResult.text); } + function kb(value) { + const v = opts?.keybinds?.[value]; + if (v === undefined) return undefined; + if (!v || v === "none") return undefined; + return v; + } + // ---- Commands ---- return [ @@ -345,7 +352,7 @@ export function registerTTS(api, kv, complete, prompts, logger) { title: "TTS: speak last response", value: "tts.speak-last", description: "Read the last assistant response aloud (detailed)", - keybind: "s", + ...(kb("tts.speak-last") ? { keybind: kb("tts.speak-last") } : {}), slash: { name: "tts-speak" }, onSelect() { speakLastResponse(); @@ -355,7 +362,7 @@ export function registerTTS(api, kv, complete, prompts, logger) { title: "TTS: toggle", value: "tts.mode", description: "Toggle auto text-to-speech on/off", - keybind: "v", + ...(kb("tts.mode") ? { keybind: kb("tts.mode") } : {}), slash: { name: "tts-mode" }, onSelect() { const current = kv.get("tts.mode", "off"); @@ -371,7 +378,7 @@ export function registerTTS(api, kv, complete, prompts, logger) { title: "TTS: stop playback", value: "tts.stop", description: "Stop current TTS playback", - keybind: "escape", + ...(kb("tts.stop") ? { keybind: kb("tts.stop") } : {}), slash: { name: "tts-stop" }, onSelect() { if (stopSpeech()) toast("TTS stopped"); From 3b6db637a6385d8aa4808a3326f64f80cbe6711d Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 02:21:39 +0700 Subject: [PATCH 007/205] add keybinding --- index.js | 18 ++++++++++-------- lib/stt.js | 23 +++++++++++++++++------ lib/tts.js | 14 ++++++++++---- 3 files changed, 37 insertions(+), 18 deletions(-) diff --git a/index.js b/index.js index 675329f..8e09450 100644 --- a/index.js +++ b/index.js @@ -15,18 +15,20 @@ // // Runtime state (model, mic, voice, tts mode) persisted via api.kv. // -// Commands (palette + slash, no default keybind — set via plugin options `keybinds` if needed): -// /stt-record - start/stop recording + transcribe -// /stt-submit - stop recording + transcribe + submit -// /stt-stop - cancel recording +// Commands (palette + slash; default shortcuts use rare leader combos to avoid collisions): +// /stt-record - start/stop recording + transcribe (default: [ = ctrl+x, [) +// /stt-submit - stop recording + transcribe + submit (palette-only) +// /stt-stop - cancel recording (palette-only) // /stt-model - select whisper model // /stt-language - select transcription language // /stt-mic - select microphone -// /tts-speak - read last response aloud -// /tts-mode - toggle auto TTS on/off -// /tts-stop - stop playback +// /tts-speak - read last response aloud (default: ] = ctrl+x, ]) +// /tts-mode - toggle auto TTS on/off (palette-only) +// /tts-stop - stop playback (default: ; , also palette) // /tts-voice - select TTS voice -// Example keybinds: { "keybinds": { "stt.record": "ctrl+r", "tts.speak-last": "s" } } +// All also palette-accessible via Ctrl+P or /slash. Override via plugin options `keybinds`: +// { "keybinds": { "stt.record": "R", "tts.speak-last": "none" } } +// Weird keys [ ] ; were chosen because opencode doesn't use them and uppercase/shift was ignored. import fs from "node:fs"; import os from "node:os"; diff --git a/lib/stt.js b/lib/stt.js index 634c04f..536400a 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -388,11 +388,16 @@ export function getWaveString() { } } +let currentRecordKeybind = "["; +export function __setRecordKeybind(kb) { + if (kb) currentRecordKeybind = kb.replace(/^/, "leader+"); +} export function buildRecordingMessage() { - if (!useWave || recordingStartMs === null) return `${RECORDING_TOAST_BASE} · Ctrl+R to stop`; + if (!useWave || recordingStartMs === null) + return `${RECORDING_TOAST_BASE} · ${currentRecordKeybind} to stop`; const elapsed = formatElapsed(Date.now() - recordingStartMs); const wave = getWaveString(); - return `${RECORDING_TOAST_BASE} ${wave} ${elapsed} · Ctrl+R to stop`; + return `${RECORDING_TOAST_BASE} ${wave} ${elapsed} · ${currentRecordKeybind} to stop`; } export function showRecordingToast() { @@ -921,12 +926,18 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { } logger?.log("STT", `STT temp dir=${tmpDir}`, "debug"); + const DEFAULT_KEYBINDS = { + "stt.record": "[", + }; function kb(value) { - const v = opts?.keybinds?.[value]; - if (v === undefined) return undefined; - if (!v || v === "none") return undefined; - return v; + if (opts?.keybinds && value in opts.keybinds) { + const v = opts.keybinds[value]; + if (!v || v === "none") return undefined; + return v; + } + return DEFAULT_KEYBINDS[value]; } + __setRecordKeybind(kb("stt.record") || "["); return [ { diff --git a/lib/tts.js b/lib/tts.js index 12a96d3..87bbfad 100644 --- a/lib/tts.js +++ b/lib/tts.js @@ -338,11 +338,17 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { await speak(llmResult.text); } + const DEFAULT_KEYBINDS = { + "tts.speak-last": "]", + "tts.stop": ";", + }; function kb(value) { - const v = opts?.keybinds?.[value]; - if (v === undefined) return undefined; - if (!v || v === "none") return undefined; - return v; + if (opts?.keybinds && value in opts.keybinds) { + const v = opts.keybinds[value]; + if (!v || v === "none") return undefined; + return v; + } + return DEFAULT_KEYBINDS[value]; } // ---- Commands ---- From 0d692f38899d0be8fcb4e7b53de73523ac4d9114 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 03:29:56 +0700 Subject: [PATCH 008/205] =?UTF-8?q?fix:=20address=20copilot=20reviews=20?= =?UTF-8?q?=E2=80=94=20sticky,=20wave,=20llm,=20keybinds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.js | 4 +-- lib/llm-client.js | 2 +- lib/stt.js | 69 ++++++++++++++++++++++++++++------------------- lib/tts.js | 12 ++++----- 4 files changed, 51 insertions(+), 36 deletions(-) diff --git a/index.js b/index.js index 8e09450..dd02b09 100644 --- a/index.js +++ b/index.js @@ -27,8 +27,8 @@ // /tts-stop - stop playback (default: ; , also palette) // /tts-voice - select TTS voice // All also palette-accessible via Ctrl+P or /slash. Override via plugin options `keybinds`: -// { "keybinds": { "stt.record": "R", "tts.speak-last": "none" } } -// Weird keys [ ] ; were chosen because opencode doesn't use them and uppercase/shift was ignored. +// { "keybinds": { "stt.record": "ctrl+r", "tts.speak-last": "none" } } +// Weird keys [ ] ; were chosen because opencode doesn't use them and shift variants were ignored in terminals. import fs from "node:fs"; import os from "node:os"; diff --git a/lib/llm-client.js b/lib/llm-client.js index f51bfa6..31c0fa0 100644 --- a/lib/llm-client.js +++ b/lib/llm-client.js @@ -158,8 +158,8 @@ export function createClient(pluginOptions, logger) { } const apiKey = cfg.apiKeyEnv ? process.env[cfg.apiKeyEnv] : null; - const useResponses = isResponsesEndpoint(cfg.endpoint, cfg.useResponsesApi); const endpoint = resolveEndpoint(cfg.endpoint, cfg.useResponsesApi); + const useResponses = endpoint.endsWith("/responses"); let body; if (useResponses) { diff --git a/lib/stt.js b/lib/stt.js index 536400a..c09b08b 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -319,14 +319,32 @@ export function getWaveString() { // Fixed-column snapshot: each column = noise-gated RMS of sub-slice of last ~0.08s window const wavFile = path.join(tmpDir, WAV_FILENAME); try { - const data = fs.readFileSync(wavFile); - if (data.length <= 44) { - prevWaveLevels = Array(WAVE_LEN).fill(0); - return WAVE_CHARS[0].repeat(WAVE_LEN); + let slice; + try { + const fd = fs.openSync(wavFile, "r"); + const stat = fs.fstatSync(fd); + const fileSize = stat.size; + if (fileSize <= 44) { + fs.closeSync(fd); + prevWaveLevels = Array(WAVE_LEN).fill(0); + return WAVE_CHARS[0].repeat(WAVE_LEN); + } + const windowSize = 2560; // ~0.08s at 16kHz mono 16-bit → very instant + const readSize = Math.min(windowSize, fileSize - 44); + const buf = Buffer.alloc(readSize); + fs.readSync(fd, buf, 0, readSize, fileSize - readSize); + fs.closeSync(fd); + slice = buf; + } catch { + const data = fs.readFileSync(wavFile); + if (data.length <= 44) { + prevWaveLevels = Array(WAVE_LEN).fill(0); + return WAVE_CHARS[0].repeat(WAVE_LEN); + } + const windowSize = 2560; + const start = Math.max(44, data.length - windowSize); + slice = data.subarray(start); } - const windowSize = 2560; // ~0.08s at 16kHz mono 16-bit → very instant - const start = Math.max(44, data.length - windowSize); - const slice = data.subarray(start); const chunkBytes = Math.max(2, Math.floor(slice.length / WAVE_LEN)); const rawRms = []; const levels = []; @@ -336,7 +354,6 @@ export function getWaveString() { const samples = Math.floor(chunk.length / 2); if (samples === 0) { rawRms.push(0); - levels.push(0); continue; } let sum = 0; @@ -402,19 +419,18 @@ export function buildRecordingMessage() { export function showRecordingToast() { clearRecordingToast(); + if (!recordingToastFn) return; recordingStartMs = Date.now(); prevWaveLevels = Array(WAVE_LEN).fill(0); noiseFloorRms = null; calibrationEndMs = Date.now() + 350; const interval = useWave ? WAVE_INTERVAL : RECORDING_TOAST_INTERVAL; const duration = useWave ? WAVE_DURATION : RECORDING_TOAST_DURATION; - if (recordingToastFn) { - recordingToastFn({ - message: buildRecordingMessage(), - variant: "info", - duration, - }); - } + recordingToastFn({ + message: buildRecordingMessage(), + variant: "info", + duration, + }); recordingToastTimer = setInterval(() => { if (recordingToastFn) { recordingToastFn({ @@ -509,6 +525,8 @@ function startRecording(kv, backend, toast, logger) { `Recording error: ${errLine || `sox exited (code=${code})`}${audioFailureSuffix(backend)}`, "error", ); + } else { + toast("Recording stopped unexpectedly", "warning"); } } }); @@ -694,10 +712,7 @@ function isHallucinated(raw, normalized) { } function fallbackForRaw(raw) { - const t = raw.trim(); - if (!t) return t; - // minimal cleanup: capitalize first letter, ensure trailing period for greetings - return t.charAt(0).toUpperCase() + t.slice(1); + return raw.trim(); } async function normalizeTranscription(complete, rawText, sessionTitle, systemPrompt, logger) { @@ -713,7 +728,7 @@ async function normalizeTranscription(complete, rawText, sessionTitle, systemPro if (result.text && isHallucinated(rawText, result.text)) { logger?.log( "STT", - `Hallucination detected raw="${rawText.slice(0, 30)}" normalized="${result.text.slice(0, 80)}" -> fallback`, + `Hallucination detected rawLen=${rawText.length} normalizedLen=${result.text.length} -> fallback`, "warn", ); return { text: fallbackForRaw(rawText) }; @@ -900,7 +915,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { } __setRecordingToastFn((input) => api.ui.toast(input)); - api.lifecycle?.onDispose?.(() => clearRecordingToast()); + api.lifecycle?.onDispose?.(() => __clearRecordingToastState()); if (opts?.sttEndpoint) { sttApiEndpoint = opts.sttEndpoint; @@ -930,12 +945,12 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { "stt.record": "[", }; function kb(value) { - if (opts?.keybinds && value in opts.keybinds) { - const v = opts.keybinds[value]; - if (!v || v === "none") return undefined; - return v; - } - return DEFAULT_KEYBINDS[value]; + const kb = opts?.keybinds; + if (!kb || typeof kb !== "object" || Array.isArray(kb)) return DEFAULT_KEYBINDS[value]; + if (!Object.prototype.hasOwnProperty.call(kb, value)) return DEFAULT_KEYBINDS[value]; + const v = kb[value]; + if (!v || v === "none") return undefined; + return v; } __setRecordKeybind(kb("stt.record") || "["); diff --git a/lib/tts.js b/lib/tts.js index 87bbfad..922a3aa 100644 --- a/lib/tts.js +++ b/lib/tts.js @@ -343,12 +343,12 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { "tts.stop": ";", }; function kb(value) { - if (opts?.keybinds && value in opts.keybinds) { - const v = opts.keybinds[value]; - if (!v || v === "none") return undefined; - return v; - } - return DEFAULT_KEYBINDS[value]; + const kb = opts?.keybinds; + if (!kb || typeof kb !== "object" || Array.isArray(kb)) return DEFAULT_KEYBINDS[value]; + if (!Object.prototype.hasOwnProperty.call(kb, value)) return DEFAULT_KEYBINDS[value]; + const v = kb[value]; + if (!v || v === "none") return undefined; + return v; } // ---- Commands ---- From 78d25d17dc14af29645748ce2f7eb467d9b9fa59 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 14:01:00 +0700 Subject: [PATCH 009/205] UX react enhance --- lib/stt.js | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/lib/stt.js b/lib/stt.js index c09b08b..bafc46d 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -233,8 +233,8 @@ let noiseFloorRms = null; let calibrationEndMs = null; const WAVE_CHARS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"]; const WAVE_LEN = 16; -const WAVE_INTERVAL = 60; -const WAVE_DURATION = 220; +const WAVE_INTERVAL = 35; +const WAVE_DURATION = 70; let useWave = true; export function __setRecordingToastFn(fn) { @@ -329,7 +329,7 @@ export function getWaveString() { prevWaveLevels = Array(WAVE_LEN).fill(0); return WAVE_CHARS[0].repeat(WAVE_LEN); } - const windowSize = 2560; // ~0.08s at 16kHz mono 16-bit → very instant + const windowSize = 1024; // ~0.032s — ultra instant for toast const readSize = Math.min(windowSize, fileSize - 44); const buf = Buffer.alloc(readSize); fs.readSync(fd, buf, 0, readSize, fileSize - readSize); @@ -341,7 +341,7 @@ export function getWaveString() { prevWaveLevels = Array(WAVE_LEN).fill(0); return WAVE_CHARS[0].repeat(WAVE_LEN); } - const windowSize = 2560; + const windowSize = 1024; const start = Math.max(44, data.length - windowSize); slice = data.subarray(start); } @@ -365,14 +365,11 @@ export function getWaveString() { const rms = Math.sqrt(sum / samples); rawRms.push(rms); } - // calibration: first 350ms after recording start estimates fan noise floor + // calibration: first 120ms estimates fan noise floor, but still show live wave const now = Date.now(); if (calibrationEndMs && now < calibrationEndMs) { const minRms = Math.min(...rawRms); if (noiseFloorRms === null || minRms < noiseFloorRms) noiseFloorRms = minRms; - // during calibration show flat low so user sees not yet sensitive - prevWaveLevels = Array(WAVE_LEN).fill(0); - return WAVE_CHARS[0].repeat(WAVE_LEN); } if (noiseFloorRms === null) noiseFloorRms = Math.min(...rawRms); else { @@ -423,7 +420,7 @@ export function showRecordingToast() { recordingStartMs = Date.now(); prevWaveLevels = Array(WAVE_LEN).fill(0); noiseFloorRms = null; - calibrationEndMs = Date.now() + 350; + calibrationEndMs = Date.now() + 120; const interval = useWave ? WAVE_INTERVAL : RECORDING_TOAST_INTERVAL; const duration = useWave ? WAVE_DURATION : RECORDING_TOAST_DURATION; recordingToastFn({ @@ -488,7 +485,7 @@ function startRecording(kv, backend, toast, logger) { soxProc = spawn( "sox", - [...inputArgs, "-r", "16000", "-c", "1", "-b", "16", wavFile, "silence", "1", "0.1", "1%"], + [...inputArgs, "-r", "16000", "-c", "1", "-b", "16", wavFile, "silence", "1", "0.05", "1%"], { stdio: ["ignore", "ignore", "pipe"], detached: false, From 88fdbd5db53dd8e59505bfaeff24cb3e7217842c Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 16:38:22 +0700 Subject: [PATCH 010/205] vi TTS --- lib/tts.js | 71 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 60 insertions(+), 11 deletions(-) diff --git a/lib/tts.js b/lib/tts.js index 922a3aa..ea47831 100644 --- a/lib/tts.js +++ b/lib/tts.js @@ -11,8 +11,12 @@ const VOICES_DIR = path.join(os.homedir(), ".local", "share", "piper-voices"); const TTS_VOICES = { ryan: { label: "Ryan (high)", file: "en_US-ryan-high.onnx" }, bryce: { label: "Bryce (medium)", file: "en_US-bryce-medium.onnx" }, + vi: { label: "Vais (vi_VN medium)", file: "vi_VN-vais1000-medium.onnx" }, + vi_vivo: { label: "Vivos (vi_VN x_low)", file: "vi_VN-vivos-x_low.onnx" }, }; const DEFAULT_TTS_VOICE = "ryan"; +// Vietnamese diacritics — used for auto vi/en detection +const VI_REGEX = /[àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđĐ]/; const PIPER_RATE = 22050; const PIPER_BITS = 16; @@ -113,10 +117,34 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { api.ui.toast({ message, variant, duration: 3000 }); } - function getVoiceModel() { + function detectLang(text) { + if (!text) return "en"; + if (VI_REGEX.test(text)) return "vi"; + return "en"; + } + + function getVoiceModel(text) { + const lang = detectLang(text); + if (lang === "vi") { + // prefer explicit vi voice from kv, else default vi + const viKey = kv.get("tts.voice.vi", "vi"); + const viEntry = TTS_VOICES[viKey] || TTS_VOICES.vi; + const viPath = path.join(VOICES_DIR, viEntry.file); + if (fs.existsSync(viPath)) return viPath; + // fallback: any vi file present + for (const k of ["vi", "vi_vivo"]) { + const p = path.join(VOICES_DIR, TTS_VOICES[k].file); + if (fs.existsSync(p)) return p; + } + } const voice = kv.get("tts.voice", DEFAULT_TTS_VOICE); - const entry = TTS_VOICES[voice] || TTS_VOICES[DEFAULT_TTS_VOICE]; - return path.join(VOICES_DIR, entry.file); + // if voice is a vi key but text is en, still respect en + const entry = TTS_VOICES[voice]; + // if current kv is vi but text is en, use en default + if (entry && entry.file.includes("vi_VN") && lang === "en") { + return path.join(VOICES_DIR, TTS_VOICES[DEFAULT_TTS_VOICE].file); + } + return path.join(VOICES_DIR, (entry || TTS_VOICES[DEFAULT_TTS_VOICE]).file); } function piperOnPath() { @@ -133,6 +161,15 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { }); } + function getVoiceRate(voicePath) { + try { + const j = JSON.parse(fs.readFileSync(`${voicePath}.json`, "utf-8")); + return j?.audio?.sample_rate || PIPER_RATE; + } catch { + return PIPER_RATE; + } + } + // ---- Audio pipeline ---- let piperProc = null; @@ -160,7 +197,7 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { killProcs(); - const voiceModel = getVoiceModel(); + const voiceModel = getVoiceModel(line); logger?.log?.("TTS", `Speak requested chars=${line.length} voice=${voiceModel}`, "debug"); if (!piperOnPath()) { logger?.log?.("TTS", `Piper binary not found on PATH`, "warn"); @@ -176,13 +213,14 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { return new Promise((resolve) => { let piperStderr = ""; let playStderr = ""; + const rate = getVoiceRate(voiceModel); playProc = spawn( "play", [ "-t", "raw", "-r", - String(PIPER_RATE), + String(rate), "-e", "signed", "-b", @@ -375,9 +413,19 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { const next = current === "on" ? "off" : "on"; kv.set("tts.mode", next); if (next === "off") stopSpeech(); - const voice = - TTS_VOICES[kv.get("tts.voice", DEFAULT_TTS_VOICE)] || TTS_VOICES[DEFAULT_TTS_VOICE]; - toast(next === "on" ? `TTS on (${voice.label})` : "TTS off"); + if (next === "on") { + const enVoice = + TTS_VOICES[kv.get("tts.voice", DEFAULT_TTS_VOICE)] || TTS_VOICES[DEFAULT_TTS_VOICE]; + const viPath = path.join(VOICES_DIR, TTS_VOICES.vi.file); + const hasVi = fs.existsSync(viPath); + toast( + hasVi + ? `TTS on (auto: ${enVoice.label} / ${TTS_VOICES.vi.label})` + : `TTS on (${enVoice.label})`, + ); + } else { + toast("TTS off"); + } }, }, { @@ -399,14 +447,15 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { const current = kv.get("tts.voice", DEFAULT_TTS_VOICE); api.ui.dialog.replace(() => api.ui.DialogSelect({ - title: "Select voice", + title: "Select voice (auto vi/en)", current, options: Object.entries(TTS_VOICES).map(([key, v]) => ({ title: v.label, value: key, onSelect() { - kv.set("tts.voice", key); - toast(`Voice: ${v.label}`); + if (key.startsWith("vi")) kv.set("tts.voice.vi", key); + else kv.set("tts.voice", key); + toast(`Voice: ${v.label} (auto vi/en)`); api.ui.dialog.clear(); }, })), From 08306a0e2cc3be19e9f189cc6527c8fda1c937b2 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 16:51:28 +0700 Subject: [PATCH 011/205] enhance tts and stt model --- lib/stt.js | 22 ++++++++- lib/tts.js | 130 ++++++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 131 insertions(+), 21 deletions(-) diff --git a/lib/stt.js b/lib/stt.js index bafc46d..268e542 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -42,6 +42,7 @@ const DEFAULT_LANGUAGE = "auto"; const LANGUAGES = { auto: { label: "Auto-detect" }, en: { label: "English" }, + vi: { label: "Tiếng Việt" }, zh: { label: "Chinese" }, yue: { label: "Cantonese" }, ja: { label: "Japanese" }, @@ -568,6 +569,21 @@ function transcribe(kv, logger) { const wavFile = path.join(tmpDir, WAV_FILENAME); const mp = getModelPath(kv); const lang = getLanguage(kv); + try { + const freeGB = (os.freemem() / 1024 / 1024 / 1024).toFixed(1); + const totalGB = (os.totalmem() / 1024 / 1024 / 1024).toFixed(0); + logger?.log( + "STT", + `Local transcription model=${mp} lang=${lang} mem free=${freeGB}GB/${totalGB}GB`, + "debug", + ); + if (parseFloat(freeGB) < 4) + logger?.log( + "STT", + `Low free RAM ${freeGB}GB — large models may swap, consider sttModel medium or sttEndpoint API`, + "warn", + ); + } catch {} logger?.log("STT", `Local transcription requested model=${mp} language=${lang}`, "debug"); if (!fs.existsSync(mp)) { logger?.log("STT", `Whisper model missing: ${mp}`, "error"); @@ -687,7 +703,11 @@ CRITICAL DOMAIN CORRECTIONS - Fix common STT homophone errors in software engine - "int" -> "Int" - "bullion" -> "boolean" -Rely heavily on context to fix words that sound similar to programming terminology.`; +For Vietnamese (vi): keep diacritics exact (e.g., "tim" vs "tìm", "doc" vs "đọc", "sua" vs "sửa") and do not strip tones. + +Rely heavily on context to fix words that sound similar to programming terminology. + +Model/RAM note: on 36GB Mac with ~30GB used, ~6GB free fits large-v3-turbo-q5_0 (~0.8GB) but q8_0/full (~1.1-3GB) may swap. If whisper encode >2s, consider tui.json "sttEndpoint" API offload to save RAM.`; const STT_HALLUCINATION_PATTERNS = [ /I am (an )?AI/i, diff --git a/lib/tts.js b/lib/tts.js index ea47831..b353f38 100644 --- a/lib/tts.js +++ b/lib/tts.js @@ -123,6 +123,54 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { return "en"; } + function segmentByLang(text) { + if (!text) return []; + const segments = []; + let curLang = null; + let curText = ""; + // split into tokens: keep words, punctuation, code, spaces + // heuristic: each token classified, consecutive same lang merged + const tokens = text.split( + new RegExp( + "(\\s+|[a-zA-Z_][a-zA-Z0-9_./]*|[àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđĐ]+)", + "g", + ), + ); + for (const tok of tokens) { + if (!tok) continue; + const lang = VI_REGEX.test(tok) ? "vi" : /^[a-zA-Z]/.test(tok) ? "en" : curLang || "en"; + // for punctuation/spaces, keep with previous lang + const tokLang = tok.trim() === "" || /^[\s.,!?;:()"'`]+$/.test(tok) ? curLang || lang : lang; + if (tokLang !== curLang && curText) { + segments.push({ text: curText, lang: curLang }); + curText = tok; + curLang = tokLang; + } else { + if (!curLang) curLang = tokLang; + curText += tok; + } + } + if (curText) segments.push({ text: curText, lang: curLang || "en" }); + // merge single-char segments to avoid choppy synthesis + const merged = []; + for (const s of segments) { + if (merged.length && s.text.length <= 2 && s.lang === merged[merged.length - 1].lang) { + merged[merged.length - 1].text += s.text; + } else if (merged.length && s.text.trim().length <= 1) { + merged[merged.length - 1].text += s.text; + } else { + merged.push(s); + } + } + // fallback: if only one segment, keep as is + if (merged.length === 0) return [{ text, lang: detectLang(text) }]; + // if mixed but all en or all vi, keep single + if (merged.length > 1 && merged.every((s) => s.lang === merged[0].lang)) { + return [{ text, lang: merged[0].lang }]; + } + return merged; + } + function getVoiceModel(text) { const lang = detectLang(text); if (lang === "vi") { @@ -190,26 +238,7 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { } } - function speak(text) { - if (!text) return Promise.resolve(); - const line = text.replace(/\n/g, " ").trim(); - if (!line) return Promise.resolve(); - - killProcs(); - - const voiceModel = getVoiceModel(line); - logger?.log?.("TTS", `Speak requested chars=${line.length} voice=${voiceModel}`, "debug"); - if (!piperOnPath()) { - logger?.log?.("TTS", `Piper binary not found on PATH`, "warn"); - toast(`Piper binary not found on PATH`, "warning"); - return Promise.resolve(); - } - if (!fs.existsSync(voiceModel)) { - logger?.log?.("TTS", `Voice model not found: ${voiceModel}`, "warn"); - toast(`Voice model not found: ${voiceModel}`, "warning"); - return Promise.resolve(); - } - + async function speakOne(line, voiceModel) { return new Promise((resolve) => { let piperStderr = ""; let playStderr = ""; @@ -288,6 +317,67 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { }); } + async function speak(text) { + if (!text) return Promise.resolve(); + const line = text.replace(/\n/g, " ").trim(); + if (!line) return Promise.resolve(); + + killProcs(); + + // mixed vi+en: split and speak sequentially with correct voices + const segments = segmentByLang(line); + const isMixed = + segments.length > 1 && + segments.some((s) => s.lang === "vi") && + segments.some((s) => s.lang === "en"); + if (isMixed) { + logger?.log?.( + "TTS", + `Mixed vi/en detected segments=${segments.map((s) => `${s.lang}:${s.text.slice(0, 20)}`).join(" | ")}`, + "debug", + ); + for (const seg of segments) { + const voiceModel = getVoiceModel(seg.text); + logger?.log?.( + "TTS", + `Speak segment lang=${seg.lang} chars=${seg.text.length} voice=${voiceModel}`, + "debug", + ); + if (!piperOnPath()) { + logger?.log?.("TTS", `Piper binary not found on PATH`, "warn"); + toast(`Piper binary not found on PATH`, "warning"); + return; + } + if (!fs.existsSync(voiceModel)) { + logger?.log?.("TTS", `Voice model not found: ${voiceModel}`, "warn"); + toast(`Voice model not found: ${voiceModel}`, "warning"); + return; + } + await speakOne(seg.text, voiceModel); + // check if stop was requested mid-sequence + if (!piperProc && !playProc && segments.indexOf(seg) !== segments.length - 1) { + // continue to next + } + } + return; + } + + const voiceModel = getVoiceModel(line); + logger?.log?.("TTS", `Speak requested chars=${line.length} voice=${voiceModel}`, "debug"); + if (!piperOnPath()) { + logger?.log?.("TTS", `Piper binary not found on PATH`, "warn"); + toast(`Piper binary not found on PATH`, "warning"); + return Promise.resolve(); + } + if (!fs.existsSync(voiceModel)) { + logger?.log?.("TTS", `Voice model not found: ${voiceModel}`, "warn"); + toast(`Voice model not found: ${voiceModel}`, "warning"); + return Promise.resolve(); + } + + return speakOne(line, voiceModel); + } + // ---- Session-prefixed announcements ---- async function speakWithSessionPrefix(sessionID, message, suffix) { From 5e842e9ee30bffd7b3d6e98909d81fb43d3fe506 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Mon, 31 Aug 2026 22:42:59 +0700 Subject: [PATCH 012/205] input to focus fields not always primary chat box --- lib/stt.js | 51 +++++++++---------- lib/tts.js | 130 ++++++++--------------------------------------- test/stt.test.js | 24 +++++++++ 3 files changed, 69 insertions(+), 136 deletions(-) diff --git a/lib/stt.js b/lib/stt.js index 268e542..b27cd6c 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -42,7 +42,6 @@ const DEFAULT_LANGUAGE = "auto"; const LANGUAGES = { auto: { label: "Auto-detect" }, en: { label: "English" }, - vi: { label: "Tiếng Việt" }, zh: { label: "Chinese" }, yue: { label: "Cantonese" }, ja: { label: "Japanese" }, @@ -569,21 +568,6 @@ function transcribe(kv, logger) { const wavFile = path.join(tmpDir, WAV_FILENAME); const mp = getModelPath(kv); const lang = getLanguage(kv); - try { - const freeGB = (os.freemem() / 1024 / 1024 / 1024).toFixed(1); - const totalGB = (os.totalmem() / 1024 / 1024 / 1024).toFixed(0); - logger?.log( - "STT", - `Local transcription model=${mp} lang=${lang} mem free=${freeGB}GB/${totalGB}GB`, - "debug", - ); - if (parseFloat(freeGB) < 4) - logger?.log( - "STT", - `Low free RAM ${freeGB}GB — large models may swap, consider sttModel medium or sttEndpoint API`, - "warn", - ); - } catch {} logger?.log("STT", `Local transcription requested model=${mp} language=${lang}`, "debug"); if (!fs.existsSync(mp)) { logger?.log("STT", `Whisper model missing: ${mp}`, "error"); @@ -703,11 +687,7 @@ CRITICAL DOMAIN CORRECTIONS - Fix common STT homophone errors in software engine - "int" -> "Int" - "bullion" -> "boolean" -For Vietnamese (vi): keep diacritics exact (e.g., "tim" vs "tìm", "doc" vs "đọc", "sua" vs "sửa") and do not strip tones. - -Rely heavily on context to fix words that sound similar to programming terminology. - -Model/RAM note: on 36GB Mac with ~30GB used, ~6GB free fits large-v3-turbo-q5_0 (~0.8GB) but q8_0/full (~1.1-3GB) may swap. If whisper encode >2s, consider tui.json "sttEndpoint" API offload to save RAM.`; +Rely heavily on context to fix words that sound similar to programming terminology.`; const STT_HALLUCINATION_PATTERNS = [ /I am (an )?AI/i, @@ -843,7 +823,24 @@ async function transcribeApi(kv, logger) { } } -async function appendTranscription(client, text, submit) { +export function insertIntoFocusedInput(renderer, text, submit = false) { + const focused = renderer?.currentFocusedRenderable; + if (!focused || typeof focused.insertText !== "function") return false; + + try { + focused.insertText(text); + if (submit && typeof focused.submit === "function") focused.submit(); + return true; + } catch { + return false; + } +} + +async function appendTranscription(client, renderer, text, submit) { + if (insertIntoFocusedInput(renderer, text, submit)) { + return; + } + let appendResult = await client.tui.appendPrompt({ body: { text } }); if (appendResult?.error?.data?.message === "Expected object, got undefined") { @@ -869,6 +866,7 @@ async function doTranscribePipeline( systemPrompt, submit = false, logger, + renderer, ) { processing = true; clearRecordingToast(); @@ -904,11 +902,11 @@ async function doTranscribePipeline( if (!llmResult.text) { logger?.log("STT", `Normalization failed, using raw input: ${llmResult.error}`, "warn"); toast(`Normalization failed, using raw input: ${llmResult.error}`, "warning"); - await appendTranscription(client, result.text, submit); + await appendTranscription(client, renderer, result.text, submit); return; } - await appendTranscription(client, llmResult.text, submit); + await appendTranscription(client, renderer, llmResult.text, submit); logger?.log("STT", `Pipeline completed normalizedChars=${llmResult.text.length}`, "debug"); toast(submit ? "Transcription submitted" : "Transcription added to prompt", "success"); } catch (err) { @@ -924,6 +922,7 @@ async function doTranscribePipeline( export function registerSTT(api, kv, complete, prompts, opts, logger) { const client = api.client; + const renderer = opts?.focusMode === "primary" ? null : api.renderer; const systemPrompt = prompts?.stt || STT_SYSTEM_PROMPT; const backend = detectAudioBackend(); logger?.log("STT", `Audio backend=${backend}`, "debug"); @@ -988,7 +987,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { if (recording) { clearRecordingToast(); toast("Stopping, transcribing..."); - doTranscribePipeline(kv, complete, client, toast, systemPrompt, false, logger); + doTranscribePipeline(kv, complete, client, toast, systemPrompt, false, logger, renderer); } else { startRecording(kv, backend, toast, logger); if (recording) showRecordingToast(); @@ -1014,7 +1013,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { } clearRecordingToast(); toast("Stopping, transcribing..."); - doTranscribePipeline(kv, complete, client, toast, systemPrompt, true, logger); + doTranscribePipeline(kv, complete, client, toast, systemPrompt, true, logger, renderer); }, }, { diff --git a/lib/tts.js b/lib/tts.js index b353f38..ea47831 100644 --- a/lib/tts.js +++ b/lib/tts.js @@ -123,54 +123,6 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { return "en"; } - function segmentByLang(text) { - if (!text) return []; - const segments = []; - let curLang = null; - let curText = ""; - // split into tokens: keep words, punctuation, code, spaces - // heuristic: each token classified, consecutive same lang merged - const tokens = text.split( - new RegExp( - "(\\s+|[a-zA-Z_][a-zA-Z0-9_./]*|[àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđĐ]+)", - "g", - ), - ); - for (const tok of tokens) { - if (!tok) continue; - const lang = VI_REGEX.test(tok) ? "vi" : /^[a-zA-Z]/.test(tok) ? "en" : curLang || "en"; - // for punctuation/spaces, keep with previous lang - const tokLang = tok.trim() === "" || /^[\s.,!?;:()"'`]+$/.test(tok) ? curLang || lang : lang; - if (tokLang !== curLang && curText) { - segments.push({ text: curText, lang: curLang }); - curText = tok; - curLang = tokLang; - } else { - if (!curLang) curLang = tokLang; - curText += tok; - } - } - if (curText) segments.push({ text: curText, lang: curLang || "en" }); - // merge single-char segments to avoid choppy synthesis - const merged = []; - for (const s of segments) { - if (merged.length && s.text.length <= 2 && s.lang === merged[merged.length - 1].lang) { - merged[merged.length - 1].text += s.text; - } else if (merged.length && s.text.trim().length <= 1) { - merged[merged.length - 1].text += s.text; - } else { - merged.push(s); - } - } - // fallback: if only one segment, keep as is - if (merged.length === 0) return [{ text, lang: detectLang(text) }]; - // if mixed but all en or all vi, keep single - if (merged.length > 1 && merged.every((s) => s.lang === merged[0].lang)) { - return [{ text, lang: merged[0].lang }]; - } - return merged; - } - function getVoiceModel(text) { const lang = detectLang(text); if (lang === "vi") { @@ -238,7 +190,26 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { } } - async function speakOne(line, voiceModel) { + function speak(text) { + if (!text) return Promise.resolve(); + const line = text.replace(/\n/g, " ").trim(); + if (!line) return Promise.resolve(); + + killProcs(); + + const voiceModel = getVoiceModel(line); + logger?.log?.("TTS", `Speak requested chars=${line.length} voice=${voiceModel}`, "debug"); + if (!piperOnPath()) { + logger?.log?.("TTS", `Piper binary not found on PATH`, "warn"); + toast(`Piper binary not found on PATH`, "warning"); + return Promise.resolve(); + } + if (!fs.existsSync(voiceModel)) { + logger?.log?.("TTS", `Voice model not found: ${voiceModel}`, "warn"); + toast(`Voice model not found: ${voiceModel}`, "warning"); + return Promise.resolve(); + } + return new Promise((resolve) => { let piperStderr = ""; let playStderr = ""; @@ -317,67 +288,6 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { }); } - async function speak(text) { - if (!text) return Promise.resolve(); - const line = text.replace(/\n/g, " ").trim(); - if (!line) return Promise.resolve(); - - killProcs(); - - // mixed vi+en: split and speak sequentially with correct voices - const segments = segmentByLang(line); - const isMixed = - segments.length > 1 && - segments.some((s) => s.lang === "vi") && - segments.some((s) => s.lang === "en"); - if (isMixed) { - logger?.log?.( - "TTS", - `Mixed vi/en detected segments=${segments.map((s) => `${s.lang}:${s.text.slice(0, 20)}`).join(" | ")}`, - "debug", - ); - for (const seg of segments) { - const voiceModel = getVoiceModel(seg.text); - logger?.log?.( - "TTS", - `Speak segment lang=${seg.lang} chars=${seg.text.length} voice=${voiceModel}`, - "debug", - ); - if (!piperOnPath()) { - logger?.log?.("TTS", `Piper binary not found on PATH`, "warn"); - toast(`Piper binary not found on PATH`, "warning"); - return; - } - if (!fs.existsSync(voiceModel)) { - logger?.log?.("TTS", `Voice model not found: ${voiceModel}`, "warn"); - toast(`Voice model not found: ${voiceModel}`, "warning"); - return; - } - await speakOne(seg.text, voiceModel); - // check if stop was requested mid-sequence - if (!piperProc && !playProc && segments.indexOf(seg) !== segments.length - 1) { - // continue to next - } - } - return; - } - - const voiceModel = getVoiceModel(line); - logger?.log?.("TTS", `Speak requested chars=${line.length} voice=${voiceModel}`, "debug"); - if (!piperOnPath()) { - logger?.log?.("TTS", `Piper binary not found on PATH`, "warn"); - toast(`Piper binary not found on PATH`, "warning"); - return Promise.resolve(); - } - if (!fs.existsSync(voiceModel)) { - logger?.log?.("TTS", `Voice model not found: ${voiceModel}`, "warn"); - toast(`Voice model not found: ${voiceModel}`, "warning"); - return Promise.resolve(); - } - - return speakOne(line, voiceModel); - } - // ---- Session-prefixed announcements ---- async function speakWithSessionPrefix(sessionID, message, suffix) { diff --git a/test/stt.test.js b/test/stt.test.js index 5418a59..5183215 100644 --- a/test/stt.test.js +++ b/test/stt.test.js @@ -6,12 +6,36 @@ import { buildOpenRouterTranscriptionRequest, buildRecordArgs, buildWhisperArgs, + insertIntoFocusedInput, isOpenRouterEndpoint, isWSL, parsePactlSources, parsePactlSourcesShort, } from "../lib/stt.js"; +test("inserts transcription into the focused OpenTUI input", () => { + const calls = []; + const input = { + insertText(text) { + calls.push(["insert", text]); + }, + submit() { + calls.push(["submit"]); + }, + }; + + assert.equal(insertIntoFocusedInput({ currentFocusedRenderable: input }, "hello", true), true); + assert.deepEqual(calls, [["insert", "hello"], ["submit"]]); +}); + +test("does not claim non-editable focused renderables", () => { + assert.equal( + insertIntoFocusedInput({ currentFocusedRenderable: { focus() {} } }, "hello"), + false, + ); + assert.equal(insertIntoFocusedInput({ currentFocusedRenderable: null }, "hello"), false); +}); + test("detects OpenRouter STT endpoints", () => { assert.equal(isOpenRouterEndpoint("https://openrouter.ai/api/v1"), true); assert.equal(isOpenRouterEndpoint("https://openrouter.ai/api/v1/"), true); From f197a6957ea3b0cff3df5c63ca5df9a7302abf07 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Sun, 20 Sep 2026 03:25:11 +0700 Subject: [PATCH 013/205] fix(llm): send x-opencode-session for session-scoped gateways The zen/go gateway rejects requests without the x-opencode-session header (401/400 MissingSessionID). Resolve the live session ID from api.route.current at call time and send it; per-call config.sessionID can override. Add regression tests for header present/absent. --- index.js | 7 ++++- lib/llm-client.js | 13 ++++++++- test/llm-client.test.js | 60 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index dd02b09..465a9d2 100644 --- a/index.js +++ b/index.js @@ -60,7 +60,12 @@ export default { const { kv } = api; const logger = createLogger(api.client); logger.log("plugin", "Initializing", "debug"); - const { complete } = createClient(options, logger); + // Session-scoped gateways (opencode.ai/zen/go) require x-opencode-session. + // Read the live route at call time so normalize works in any session. + const { complete } = createClient(options, logger, () => { + const route = api?.route?.current; + return route?.name === "session" ? route?.params?.sessionID : undefined; + }); const prompts = { stt: loadPromptFile(options?.sttPrompt, logger, "STT"), diff --git a/lib/llm-client.js b/lib/llm-client.js index 31c0fa0..a8134cf 100644 --- a/lib/llm-client.js +++ b/lib/llm-client.js @@ -103,9 +103,13 @@ function wait(ms) { * * @param {object} [pluginOptions] - Static config from tui.json plugin options * @param {{ log?: (scope: string, message: string, level?: string) => void }} [logger] + * @param {() => string | undefined} [getSessionID] - Resolver for the live opencode + * session ID. Sent as `x-opencode-session` so session-scoped gateways + * (e.g. opencode.ai/zen/go) can route the request. Omit when the endpoint + * needs no session binding. * @returns {{ complete: (opts: { system?: string, prompt: string, config?: object }) => Promise<{ text: string | null, error?: string }> }} */ -export function createClient(pluginOptions, logger) { +export function createClient(pluginOptions, logger, getSessionID) { function getConfig() { const rawUseResponses = pluginOptions?.useResponsesApi ?? @@ -157,6 +161,12 @@ export function createClient(pluginOptions, logger) { return { text: null, error: "LLM model not configured" }; } const apiKey = cfg.apiKeyEnv ? process.env[cfg.apiKeyEnv] : null; + // Per-call override wins, otherwise ask the live session resolver. + // The zen/go gateway rejects requests without x-opencode-session (401/400). + const sessionID = + cfg.sessionID ?? + (typeof getSessionID === "function" ? getSessionID() : null) ?? + null; const endpoint = resolveEndpoint(cfg.endpoint, cfg.useResponsesApi); const useResponses = endpoint.endsWith("/responses"); @@ -201,6 +211,7 @@ export function createClient(pluginOptions, logger) { headers: { "Content-Type": "application/json", ...(apiKey ? { Authorization: "Bearer " + apiKey } : {}), + ...(sessionID ? { "x-opencode-session": sessionID } : {}), }, body: JSON.stringify(body), }); diff --git a/test/llm-client.test.js b/test/llm-client.test.js index b70d108..f4d1dbe 100644 --- a/test/llm-client.test.js +++ b/test/llm-client.test.js @@ -264,3 +264,63 @@ test("retries transient failures and eventually returns the response text", asyn } } }); + +test("sends x-opencode-session header from session resolver", async () => { + const previousFetch = globalThis.fetch; + const requests = []; + + globalThis.fetch = async (url, options) => { + requests.push({ url, options }); + return createJsonResponse(200, { output_text: "normalized text" }); + }; + + try { + const client = createClient( + { + endpoint: "https://example.test/v1", + model: "test-model", + useResponsesApi: true, + retries: 0, + }, + undefined, + () => "ses_test123", + ); + + const result = await client.complete({ prompt: "User prompt" }); + + assert.equal(result.text, "normalized text"); + assert.equal(requests.length, 1); + assert.equal(requests[0].url, "https://example.test/v1/responses"); + assert.equal(requests[0].options.headers["x-opencode-session"], "ses_test123"); + } finally { + globalThis.fetch = previousFetch; + } +}); + +test("omits x-opencode-session header without session", async () => { + const previousFetch = globalThis.fetch; + const requests = []; + + globalThis.fetch = async (url, options) => { + requests.push({ url, options }); + return createJsonResponse(200, { + choices: [{ message: { content: "text" } }], + }); + }; + + try { + const client = createClient({ + endpoint: "https://example.test/v1", + model: "test-model", + retries: 0, + }); + + const result = await client.complete({ prompt: "User prompt" }); + + assert.equal(result.text, "text"); + assert.equal(requests.length, 1); + assert.ok(!("x-opencode-session" in requests[0].options.headers)); + } finally { + globalThis.fetch = previousFetch; + } +}); From 8633403fc42ac11f94aa5772732a105d877b9016 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Sun, 20 Sep 2026 15:04:08 +0700 Subject: [PATCH 014/205] fix(stt): keep Transcribing/Normalizing toast visible until stage completes --- lib/stt.js | 85 ++++++++++++++++++++++++++++++++++++++++++++++-- test/stt.test.js | 26 +++++++++++++++ 2 files changed, 108 insertions(+), 3 deletions(-) diff --git a/lib/stt.js b/lib/stt.js index 2634559..6804c4f 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -220,6 +220,16 @@ let recording = false; let processing = false; // ---- Sticky recording toast (Option A: polling to simulate persistence) ---- +// ---- Sticky processing toast (Transcribing... / Normalizing...) ---- +// Single-shot toasts (duration 3000ms) expire long before whisper/LLM finish, +// leaving a silent gap where the user thinks STT died. Poll like the recording +// toast so the stage stays visible until it completes. + +let processingToastTimer = null; +let processingToastFn = null; +let processingMessage = ""; +const PROCESSING_TOAST_DURATION = 3000; +const PROCESSING_TOAST_INTERVAL = 2500; let recordingToastTimer = null; let recordingToastFn = null; @@ -261,6 +271,65 @@ export function isRecordingToastActive() { return recordingToastTimer !== null; } +export function __setProcessingToastFn(fn) { + processingToastFn = fn; +} + +export function __clearProcessingToastState() { + if (processingToastTimer) { + clearInterval(processingToastTimer); + processingToastTimer = null; + } + processingToastFn = null; + processingMessage = ""; +} + +export function isProcessingToastActive() { + return processingToastTimer !== null; +} + +export function showProcessingToast(message) { + clearProcessingToast(); + processingMessage = message; + if (!processingToastFn) return; + processingToastFn({ + message: processingMessage, + variant: "info", + duration: PROCESSING_TOAST_DURATION, + }); + processingToastTimer = setInterval(() => { + if (processingToastFn) { + processingToastFn({ + message: processingMessage, + variant: "info", + duration: PROCESSING_TOAST_DURATION, + }); + } + }, PROCESSING_TOAST_INTERVAL); +} + +export function updateProcessingToast(message) { + if (!isProcessingToastActive()) { + showProcessingToast(message); + return; + } + processingMessage = message; + if (processingToastFn) { + processingToastFn({ + message: processingMessage, + variant: "info", + duration: PROCESSING_TOAST_DURATION, + }); + } +} + +export function clearProcessingToast() { + if (processingToastTimer) { + clearInterval(processingToastTimer); + processingToastTimer = null; + } +} + export function formatElapsed(ms) { const totalSec = Math.floor(ms / 1000); const m = String(Math.floor(totalSec / 60)).padStart(2, "0"); @@ -876,21 +945,23 @@ async function doTranscribePipeline( stopRecording(logger); await waitForSoxExit(logger); - toast("Transcribing..."); + showProcessingToast("Transcribing..."); const result = sttApiEndpoint ? await transcribeApi(kv, logger) : await transcribe(kv, logger); if (result.error) { + clearProcessingToast(); logger?.log("STT", `Transcription failed: ${result.error}`, "error"); toast(result.error, "error"); return; } if (!result.text) { + clearProcessingToast(); logger?.log("STT", "Transcription produced no text", "warn"); toast("No speech detected", "warning"); return; } - toast("Normalizing..."); + updateProcessingToast("Normalizing..."); const sessionTitle = await getActiveSessionTitle(client); const llmResult = await normalizeTranscription( complete, @@ -901,6 +972,7 @@ async function doTranscribePipeline( ); if (!llmResult.text) { + clearProcessingToast(); logger?.log("STT", `Normalization failed, using raw input: ${llmResult.error}`, "warn"); toast(`Normalization failed, using raw input: ${llmResult.error}`, "warning"); await appendTranscription(client, renderer, result.text, submit); @@ -908,12 +980,15 @@ async function doTranscribePipeline( } await appendTranscription(client, renderer, llmResult.text, submit); + clearProcessingToast(); logger?.log("STT", `Pipeline completed normalizedChars=${llmResult.text.length}`, "debug"); toast(submit ? "Transcription submitted" : "Transcription added to prompt", "success"); } catch (err) { + clearProcessingToast(); logger?.log("STT", `Pipeline error: ${err.message}`, "error"); toast(`STT error: ${err.message}`, "error"); } finally { + clearProcessingToast(); processing = false; recording = false; } @@ -932,7 +1007,11 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { } __setRecordingToastFn((input) => api.ui.toast(input)); - api.lifecycle?.onDispose?.(() => __clearRecordingToastState()); + __setProcessingToastFn((input) => api.ui.toast(input)); + api.lifecycle?.onDispose?.(() => { + __clearRecordingToastState(); + __clearProcessingToastState(); + }); if (opts?.sttEndpoint) { sttApiEndpoint = opts.sttEndpoint; diff --git a/test/stt.test.js b/test/stt.test.js index 5183215..c892707 100644 --- a/test/stt.test.js +++ b/test/stt.test.js @@ -2,15 +2,21 @@ import assert from "node:assert/strict"; import test from "node:test"; import { + __clearProcessingToastState, + __setProcessingToastFn, buildAudioHint, buildOpenRouterTranscriptionRequest, buildRecordArgs, buildWhisperArgs, + clearProcessingToast, insertIntoFocusedInput, isOpenRouterEndpoint, + isProcessingToastActive, isWSL, parsePactlSources, parsePactlSourcesShort, + showProcessingToast, + updateProcessingToast, } from "../lib/stt.js"; test("inserts transcription into the focused OpenTUI input", () => { @@ -36,6 +42,26 @@ test("does not claim non-editable focused renderables", () => { assert.equal(insertIntoFocusedInput({ currentFocusedRenderable: null }, "hello"), false); }); +test("processing toast stays active until cleared", () => { + const seen = []; + __setProcessingToastFn((input) => seen.push(input)); + try { + showProcessingToast("Transcribing..."); + assert.equal(isProcessingToastActive(), true); + assert.equal(seen.length, 1); + assert.equal(seen[0].message, "Transcribing..."); + + updateProcessingToast("Normalizing..."); + assert.equal(isProcessingToastActive(), true); + assert.equal(seen.at(-1).message, "Normalizing..."); + + clearProcessingToast(); + assert.equal(isProcessingToastActive(), false); + } finally { + __clearProcessingToastState(); + } +}); + test("detects OpenRouter STT endpoints", () => { assert.equal(isOpenRouterEndpoint("https://openrouter.ai/api/v1"), true); assert.equal(isOpenRouterEndpoint("https://openrouter.ai/api/v1/"), true); From 9dacbcc6c253c4c0748e58284073285d8a822266 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Wed, 23 Sep 2026 03:39:28 +0700 Subject: [PATCH 015/205] feat(voice): hands-free conversation mode + context-aware STT normalization Conversation mode (/voice-conversation, v): record, auto-submit, wait reply, speak, repeat. Barge-in to interrupt, stop phrases to exit. STT normalization now receives last 8 turns / 3000 chars as so names and pronouns resolve from conversation. --- README.md | 30 +++- index.js | 21 ++- lib/conversation.js | 341 ++++++++++++++++++++++++++++++++++++++ lib/session.js | 72 ++++++++ lib/stt.js | 258 +++++++++++++++++++++++----- lib/tts.js | 58 ++++++- test/conversation.test.js | 35 ++++ test/session.test.js | 67 ++++++++ 8 files changed, 831 insertions(+), 51 deletions(-) create mode 100644 lib/conversation.js create mode 100644 test/conversation.test.js create mode 100644 test/session.test.js diff --git a/README.md b/README.md index b2ed2c4..edc6c01 100644 --- a/README.md +++ b/README.md @@ -334,6 +334,8 @@ up or how responses are spoken. } ``` +- `sttContextMessages` _(optional)_ - recent turns sent as knowledge with STT normalization (default `8`) +- `sttContextChars` _(optional)_ - max chars of that context (default `3000`, tail kept) - `sttPrompt` _(optional)_ - system prompt for cleaning up whisper transcriptions - `ttsAutoPrompt` _(optional)_ - system prompt for auto-speaking assistant responses - `ttsManualPrompt` _(optional)_ - system prompt for manually reading responses aloud @@ -369,10 +371,36 @@ then `s`. | Command | Keybind | Description | | ------------ | ---------- | ------------------------ | | `/tts-speak` | `leader+s` | Read last response aloud | -| `/tts-mode` | `leader+v` | Toggle auto TTS on/off | +| `/tts-mode` | | Toggle auto TTS on/off | | `/tts-stop` | `escape` | Stop playback | | `/tts-voice` | | Select TTS voice | +### Voice conversation + +| Command | Keybind | Description | +| -------------------------- | ---------- | ----------------------------------------- | +| `/voice-conversation` | `leader+v` | Toggle hands-free voice conversation mode | +| `/voice-conversation-stop` | | Exit voice conversation mode | + +Press the conversation key to enter the mode, speak, then press again to +send. The turn is transcribed, normalized, submitted immediately, the reply +is waited on and spoken aloud, and recording restarts automatically: + +``` +record -> transcribe -> normalize -> submit -> wait reply -> speak -> record ... +``` + +While the reply is speaking, press the key to barge in (stop speech, record +the next turn). While waiting/processing, the key exits the mode. Saying a +stop phrase (`stop`, `goodbye`, `dừng lại`, ...) ends the mode without +submitting. While the mode is on, the plain `/stt-record` keys finish the +current turn and auto TTS stays silent (the loop speaks the reply itself). + +Options: `conversationMaxTurns` (default `50`), `conversationTimeoutMs` +(default `300000`), `conversationRestartDelayMs` (default `350`), +`conversationStopPhrases` (custom stop-phrase list). Keybind override: +`"keybinds": { "voice.conversation": "none" }`. + ## How it works ### STT pipeline diff --git a/index.js b/index.js index 465a9d2..fbe2299 100644 --- a/index.js +++ b/index.js @@ -26,14 +26,18 @@ // /tts-mode - toggle auto TTS on/off (palette-only) // /tts-stop - stop playback (default: ; , also palette) // /tts-voice - select TTS voice +// /voice-conversation - toggle hands-free voice conversation (default: v = ctrl+x, v) +// /voice-conversation-stop - exit voice conversation mode (palette-only) // All also palette-accessible via Ctrl+P or /slash. Override via plugin options `keybinds`: -// { "keybinds": { "stt.record": "ctrl+r", "tts.speak-last": "none" } } +// { "keybinds": { "stt.record": "ctrl+r", "tts.speak-last": "none", "voice.conversation": "none" } } // Weird keys [ ] ; were chosen because opencode doesn't use them and shift variants were ignored in terminals. +// v is free in opencode defaults (c/e/s/m/a/y/u/r/h etc. are taken) and mnemonic for voice. import fs from "node:fs"; import os from "node:os"; import { registerSTT } from "./lib/stt.js"; import { registerTTS } from "./lib/tts.js"; +import { registerConversation } from "./lib/conversation.js"; import { createClient } from "./lib/llm-client.js"; import { createLogger } from "./lib/logger.js"; @@ -73,9 +77,18 @@ export default { ttsManual: loadPromptFile(options?.ttsManualPrompt, logger, "TTS manual"), }; - const sttCommands = registerSTT(api, kv, complete, prompts, options, logger); - const ttsCommands = registerTTS(api, kv, complete, prompts, options, logger); + const shared = {}; + const stt = registerSTT(api, kv, complete, prompts, options, logger, { + isConversationActive: () => shared.conversation?.isActive() === true, + onConversationKey: (source) => shared.conversation?.onKey(source), + }); + const tts = registerTTS(api, kv, complete, prompts, options, logger); + const conversation = registerConversation(api, options, logger, { + stt: stt.controller, + tts: tts.controller, + }); + shared.conversation = conversation.controller; - api.command.register(() => [...sttCommands, ...ttsCommands]); + api.command.register(() => [...stt.commands, ...tts.commands, ...conversation.commands]); }, }; diff --git a/lib/conversation.js b/lib/conversation.js new file mode 100644 index 0000000..a51c2a9 --- /dev/null +++ b/lib/conversation.js @@ -0,0 +1,341 @@ +// Voice conversation mode: hands-free talk loop with OpenCode. +// +// Press the conversation key to enter the mode, speak, press again to send. +// The turn is transcribed, normalized, submitted immediately, the reply is +// waited on, spoken aloud, and recording restarts automatically: +// +// record -> transcribe -> normalize -> submit -> wait reply -> speak -> record ... +// +// Press the key while speaking to barge in (stop speech, record next turn). +// Press the key while waiting/processing to exit. Saying a stop phrase +// ("stop", "dừng lại", ...) ends the mode without submitting. + +import { clearProcessingToast, showProcessingToast } from "./stt.js"; + +export const DEFAULT_STOP_PHRASES = [ + "stop", + "exit", + "quit", + "stop conversation", + "exit conversation", + "end conversation", + "goodbye", + "bye", + "dừng lại", + "dừng", + "kết thúc", + "kết thúc hội thoại", + "thoát", + "tạm biệt", +]; + +export function normalizePhrase(text) { + return (text || "") + .trim() + .toLowerCase() + .replace(/[.!…?]+$/u, "") + .replace(/\s+/g, " "); +} + +export function matchesStopPhrase(text, phrases = DEFAULT_STOP_PHRASES) { + const normalized = normalizePhrase(text); + if (!normalized) return false; + return phrases.some((p) => normalizePhrase(p) === normalized); +} + +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +export function registerConversation(api, opts, logger, { stt, tts }) { + const maxTurns = Number(opts?.conversationMaxTurns) > 0 ? Number(opts.conversationMaxTurns) : 50; + const replyTimeoutMs = + Number(opts?.conversationTimeoutMs) > 0 ? Number(opts.conversationTimeoutMs) : 300000; + const restartDelayMs = + Number(opts?.conversationRestartDelayMs) >= 0 ? Number(opts.conversationRestartDelayMs) : 350; + const stopPhrases = Array.isArray(opts?.conversationStopPhrases) + ? opts.conversationStopPhrases + : DEFAULT_STOP_PHRASES; + + let active = false; + let phase = "idle"; // idle | recording | processing | waiting | speaking + let turn = 0; + let consecErrors = 0; + let generation = 0; + let waitCancel = null; + + function toast(message, variant = "info") { + api.ui.toast({ message, variant, duration: 3000 }); + } + + function currentSessionID() { + const route = api?.route?.current; + return route?.name === "session" ? route?.params?.sessionID : null; + } + + function isActive() { + return active; + } + + function beginTurn() { + if (!active) return; + if (turn >= maxTurns) { + stop("done"); + toast(`Conversation off - reached ${maxTurns} turns`); + return; + } + if (stt.isRecording() || stt.isProcessing()) return; + turn += 1; + phase = "recording"; + logger?.log("VOICE", `Conversation turn ${turn} listening`, "debug"); + if (!stt.start()) { + phase = "idle"; + stop("busy"); + toast("STT busy, conversation off", "warning"); + } + } + + function stop(reason) { + if (!active) return; + active = false; + generation += 1; + phase = "idle"; + if (waitCancel) { + waitCancel("stopped"); + waitCancel = null; + } + if (stt.isRecording() || stt.isProcessing()) stt.cancel(); + clearProcessingToast(); + tts.stop(); + tts.setConversationActive(false); + logger?.log("VOICE", `Conversation stopped reason=${reason}`, "debug"); + } + + // Wait for the submitted turn to finish: idle, a permission/question gate, + // or timeout. Resolves early when stop() cancels the wait. + + function waitForReply(sessionID) { + let settled = false; + let unsubs = []; + let timer = null; + + let cancelFn = null; + const done = (outcome) => { + if (settled) return null; + settled = true; + if (timer) clearTimeout(timer); + for (const unsub of unsubs) { + try { + unsub(); + } catch {} + } + unsubs = []; + if (waitCancel === cancelFn) waitCancel = null; + return outcome; + }; + + const promise = new Promise((resolve) => { + const finish = (outcome) => { + const result = done(outcome); + if (result !== null) resolve(result); + }; + cancelFn = (outcome) => finish(outcome || "stopped"); + waitCancel = cancelFn; + + const forSession = (props) => + !sessionID || !props?.sessionID || props.sessionID === sessionID; + + unsubs = [ + api.event.on("session.idle", (event) => { + if (forSession(event.properties)) finish("idle"); + }), + api.event.on("session.status", (event) => { + if (event.properties?.status?.type === "idle" && forSession(event.properties)) { + finish("idle"); + } + }), + api.event.on("permission.asked", (event) => { + if (forSession(event.properties)) finish("permission"); + }), + api.event.on("question.asked", (event) => { + if (forSession(event.properties)) finish("question"); + }), + ]; + timer = setTimeout(() => finish("timeout"), replyTimeoutMs); + }); + + return promise; + } + + async function finishTurnFlow() { + if (!active || phase !== "recording") return; + const myGen = generation; + phase = "processing"; + + const res = await stt.transcribeTurn(); + if (!active || myGen !== generation) return; + + if (res.error) { + consecErrors += 1; + logger?.log("VOICE", `Conversation turn error consec=${consecErrors}`, "warn"); + if (consecErrors >= 2) { + stop("error"); + return; + } + beginTurn(); + return; + } + if (!res.text) { + consecErrors = 0; + beginTurn(); + return; + } + consecErrors = 0; + + if (matchesStopPhrase(res.text, stopPhrases)) { + stt.discard(); + stop("stop phrase"); + toast("Conversation off"); + return; + } + + const submitted = await stt.submitTurnText(res.text); + if (!active || myGen !== generation) return; + if (submitted.error) { + stop("submit failed"); + return; + } + + phase = "waiting"; + const sessionID = currentSessionID(); + showProcessingToast("Waiting for reply..."); + const outcome = await waitForReply(sessionID); + if (!active || myGen !== generation) return; + + if (outcome === "timeout") { + stop("timeout"); + toast("No reply in time, conversation off", "warning"); + return; + } + if (outcome === "permission" || outcome === "question") { + phase = "speaking"; + showProcessingToast("Speaking..."); + await tts.speak( + outcome === "permission" + ? "Permission requested. Please check your screen." + : "A question needs your answer. Please check your screen.", + ); + clearProcessingToast(); + if (!active || myGen !== generation || phase !== "speaking") return; + beginTurn(); + return; + } + if (outcome === "stopped") return; + + phase = "speaking"; + const spoken = await tts.speakAssistantTurn(); + if (!active || myGen !== generation || phase !== "speaking") return; + if (!spoken.spoken) { + toast("No reply to speak, listening again", "warning"); + } + await delay(restartDelayMs); + if (!active || myGen !== generation || phase !== "speaking") return; + beginTurn(); + } + + function bargeIn() { + if (!active || phase !== "speaking") return; + logger?.log("VOICE", "Conversation barge-in", "debug"); + tts.stop(); + beginTurn(); + } + + function onKey(source) { + if (!active) { + start(); + return; + } + if (phase === "recording") { + finishTurnFlow(); + return; + } + if (phase === "speaking") { + if (source === "toggle") { + bargeIn(); + } else { + toast("Speaking - press the conversation key to interrupt", "warning"); + } + return; + } + // processing | waiting | idle + if (source === "toggle") { + stop("cancelled"); + toast("Conversation off"); + } else { + toast("Conversation busy, please wait...", "warning"); + } + } + + function start() { + if (active) return; + if (stt.isRecording() || stt.isProcessing()) { + toast("STT busy, try again shortly", "warning"); + return; + } + active = true; + generation += 1; + turn = 0; + consecErrors = 0; + phase = "idle"; + tts.setConversationActive(true); + logger?.log("VOICE", "Conversation started", "debug"); + toast("Conversation on - speak, press the key to send"); + beginTurn(); + } + + api.lifecycle?.onDispose?.(() => stop("dispose")); + + const DEFAULT_KEYBINDS = { + "voice.conversation": "v", + }; + function kb(value) { + const overrides = opts?.keybinds; + if (!overrides || typeof overrides !== "object" || Array.isArray(overrides)) { + return DEFAULT_KEYBINDS[value]; + } + if (!Object.prototype.hasOwnProperty.call(overrides, value)) return DEFAULT_KEYBINDS[value]; + const v = overrides[value]; + if (!v || v === "none") return undefined; + return v; + } + + const commands = [ + { + title: "Voice: conversation mode", + value: "voice.conversation", + description: + "Toggle hands-free voice conversation (record, auto-submit, speak reply, repeat)", + ...(kb("voice.conversation") ? { keybind: kb("voice.conversation") } : {}), + slash: { name: "voice-conversation" }, + onSelect() { + onKey("toggle"); + }, + }, + { + title: "Voice: stop conversation", + value: "voice.conversation-stop", + description: "Exit voice conversation mode", + slash: { name: "voice-conversation-stop" }, + onSelect() { + if (active) { + stop("command"); + toast("Conversation off"); + } + }, + }, + ]; + + const controller = { isActive, onKey, start, stop }; + + return { commands, controller }; +} diff --git a/lib/session.js b/lib/session.js index aa23946..d21966c 100644 --- a/lib/session.js +++ b/lib/session.js @@ -28,3 +28,75 @@ export async function getActiveSessionTitle(client) { return ""; } } + +async function resolveSessionID(client, api) { + const route = api?.route?.current; + if (route?.name === "session" && route?.params?.sessionID) { + return route.params.sessionID; + } + try { + const result = await client.session.list(); + if (!result.data || result.data.length === 0) return null; + const active = result.data.sort((a, b) => b.time.updated - a.time.updated)[0]; + return active?.id || null; + } catch { + return null; + } +} + +function messageText(api, msg) { + try { + const parts = api?.state?.part?.(msg.id) || []; + const text = parts + .filter((p) => p?.type === "text" && p?.text) + .map((p) => p.text.trim()) + .filter(Boolean) + .join("\n"); + if (text) return text; + } catch {} + // Compact sessions may only carry summaries on the message itself. + const summary = msg?.summary + ? [msg.summary.title, msg.summary.body].filter(Boolean).join(" — ") + : ""; + return summary || ""; +} + +/** + * Get a compact, bounded slice of recent conversation turns for LLM context + * (e.g. STT normalization that must resolve names/pronouns like Cristina). + * + * Returns "user: ...\nassistant: ..." lines, newest last, capped at + * maxMessages turns and maxChars total (tail kept on overflow). Returns "" + * whenever context is unavailable - callers must treat that as "no context" + * and proceed without it. + */ +export async function getRecentConversationContext(client, api, options = {}) { + const maxMessages = Number(options.maxMessages) > 0 ? Math.floor(Number(options.maxMessages)) : 8; + const maxChars = Number(options.maxChars) > 0 ? Math.floor(Number(options.maxChars)) : 3000; + const PER_MESSAGE_CHARS = 800; + try { + const sessionID = await resolveSessionID(client, api); + if (!sessionID) return ""; + const messages = api?.state?.session?.messages?.(sessionID) || []; + if (!Array.isArray(messages) || messages.length === 0) return ""; + const lines = []; + for (const msg of messages.slice(-maxMessages)) { + const role = msg?.role === "assistant" ? "assistant" : "user"; + let text = messageText(api, msg).trim().replace(/\s+/g, " "); + if (!text) continue; + if (text.length > PER_MESSAGE_CHARS) text = text.slice(0, PER_MESSAGE_CHARS) + "…"; + lines.push(`${role}: ${text}`); + } + if (lines.length === 0) return ""; + let joined = lines.join("\n"); + if (joined.length > maxChars) { + let cut = joined.slice(joined.length - maxChars); + const newline = cut.indexOf("\n"); + if (newline !== -1) cut = cut.slice(newline + 1); + joined = cut; + } + return joined; + } catch { + return ""; + } +} diff --git a/lib/stt.js b/lib/stt.js index 6804c4f..195aadc 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -4,7 +4,7 @@ import fs from "node:fs"; import path from "node:path"; import os from "node:os"; import { spawn, execSync } from "node:child_process"; -import { getActiveSessionTitle } from "./session.js"; +import { getActiveSessionTitle, getRecentConversationContext } from "./session.js"; let sttApiEndpoint = null; let sttApiModel = null; @@ -54,6 +54,9 @@ const LANGUAGES = { it: { label: "Italian" }, }; let sttDefaultLanguage = DEFAULT_LANGUAGE; +// Bounds for the recent-turns knowledge block sent with normalization. +let sttContextMessages = 8; +let sttContextChars = 3000; export function isOpenRouterEndpoint(endpoint) { return /(^https?:\/\/)?([^/]+\.)?openrouter\.ai(\/|$)/i.test(endpoint || ""); @@ -219,6 +222,24 @@ let soxStderr = ""; let recording = false; let processing = false; +// ---- Conversation-mode hooks (wired by index.js) ---- +// When voice conversation is active, the plain record/submit keys defer to the +// conversation loop instead of running the one-shot pipeline. + +let conversationHooks = { isActive: null, onKey: null }; + +export function __setConversationHooks(hooks) { + conversationHooks = { ...conversationHooks, ...hooks }; +} + +function conversationActive() { + try { + return conversationHooks.isActive?.() === true; + } catch { + return false; + } +} + // ---- Sticky recording toast (Option A: polling to simulate persistence) ---- // ---- Sticky processing toast (Transcribing... / Normalizing...) ---- // Single-shot toasts (duration 3000ms) expire long before whisper/LLM finish, @@ -718,7 +739,7 @@ Strict rules: - Remove filler words (um, uh, like, you know, etc.). - Keep technical terms, file names, and code references exact. - If the user is dictating code, format it appropriately. -- Use session context only to resolve ambiguous pronouns (that function, the file, it) — do not invent new content. +- Use the conversation context only to resolve ambiguous names, pronouns, and references (that function, the file, it; e.g. Cristina uses he/him if the conversation says so) — do not invent new content and never copy facts from the context into the output. - Output ONLY the cleaned text, nothing else. No quotes, no prefixes, no suffixes. - Do NOT add greetings, introductions, offers to help, questions, or commentary. - Do NOT expand short inputs. Keep output length close to input length; do not add paragraphs. @@ -782,14 +803,18 @@ function fallbackForRaw(raw) { return raw.trim(); } -async function normalizeTranscription(complete, rawText, sessionTitle, systemPrompt, logger) { - const contextLine = sessionTitle ? ` The user is currently working on: "${sessionTitle}"` : ""; - const system = `${systemPrompt}${contextLine}`; - - logger?.log("STT", `Normalizing transcription chars=${rawText.length}`, "debug"); +async function normalizeTranscription(complete, rawText, contextBlock, systemPrompt, logger) { + logger?.log( + "STT", + `Normalizing transcription chars=${rawText.length} contextChars=${contextBlock?.length || 0}`, + "debug", + ); + const prompt = contextBlock + ? `\n${contextBlock}\n\nClean up this speech-to-text transcription:\n\n${rawText}` + : `Clean up this speech-to-text transcription:\n\n${rawText}`; const result = await complete({ - system, - prompt: `Clean up this speech-to-text transcription:\n\n${rawText}`, + system: systemPrompt, + prompt, config: { temperature: 0 }, }); if (result.text && isHallucinated(rawText, result.text)) { @@ -928,75 +953,162 @@ async function appendTranscription(client, renderer, text, submit) { } } -async function doTranscribePipeline( - kv, - complete, - client, - toast, - systemPrompt, - submit = false, - logger, - renderer, -) { +// Transcribe the finished recording and normalize it, without touching the +// prompt. Leaves the sticky "Normalizing..." toast up on success so the caller +// can submit/speak without a silent gap; error/empty paths clear it and reset +// the flags themselves. + +async function transcribeTurn(kv, complete, client, api, toast, systemPrompt, logger) { processing = true; clearRecordingToast(); - try { - logger?.log("STT", `Pipeline started submit=${submit}`, "debug"); - stopRecording(logger); - await waitForSoxExit(logger); + logger?.log("STT", "Turn transcription started", "debug"); + stopRecording(logger); + await waitForSoxExit(logger); + try { showProcessingToast("Transcribing..."); const result = sttApiEndpoint ? await transcribeApi(kv, logger) : await transcribe(kv, logger); if (result.error) { clearProcessingToast(); + processing = false; + recording = false; logger?.log("STT", `Transcription failed: ${result.error}`, "error"); toast(result.error, "error"); - return; + return { error: result.error }; } if (!result.text) { clearProcessingToast(); + processing = false; + recording = false; logger?.log("STT", "Transcription produced no text", "warn"); toast("No speech detected", "warning"); - return; + return { text: null, empty: true }; } updateProcessingToast("Normalizing..."); - const sessionTitle = await getActiveSessionTitle(client); + const [sessionTitle, recent] = await Promise.all([ + getActiveSessionTitle(client), + getRecentConversationContext(client, api, { + maxMessages: sttContextMessages, + maxChars: sttContextChars, + }), + ]); + const contextBlock = [sessionTitle ? `[session: "${sessionTitle}"]` : null, recent || null] + .filter(Boolean) + .join("\n"); const llmResult = await normalizeTranscription( complete, result.text, - sessionTitle, + contextBlock, systemPrompt, logger, ); if (!llmResult.text) { clearProcessingToast(); + processing = false; + recording = false; logger?.log("STT", `Normalization failed, using raw input: ${llmResult.error}`, "warn"); toast(`Normalization failed, using raw input: ${llmResult.error}`, "warning"); - await appendTranscription(client, renderer, result.text, submit); - return; + return { text: result.text, fallback: true }; } - await appendTranscription(client, renderer, llmResult.text, submit); + logger?.log("STT", `Turn transcription ready chars=${llmResult.text.length}`, "debug"); + return { text: llmResult.text }; + } catch (err) { + clearProcessingToast(); + processing = false; + recording = false; + logger?.log("STT", `Turn transcription error: ${err.message}`, "error"); + toast(`STT error: ${err.message}`, "error"); + return { error: err.message }; + } +} + +async function submitTurnText(client, renderer, toast, text, logger) { + try { + await appendTranscription(client, renderer, text, true); clearProcessingToast(); - logger?.log("STT", `Pipeline completed normalizedChars=${llmResult.text.length}`, "debug"); - toast(submit ? "Transcription submitted" : "Transcription added to prompt", "success"); + logger?.log("STT", `Turn submitted chars=${text.length}`, "debug"); + toast("Transcription submitted", "success"); + return { text }; } catch (err) { clearProcessingToast(); - logger?.log("STT", `Pipeline error: ${err.message}`, "error"); + logger?.log("STT", `Turn submit failed: ${err.message}`, "error"); toast(`STT error: ${err.message}`, "error"); + return { error: err.message }; } finally { + processing = false; + recording = false; + } +} + +async function appendTurnText(client, renderer, toast, text, logger) { + try { + await appendTranscription(client, renderer, text, false); clearProcessingToast(); + logger?.log("STT", `Turn appended chars=${text.length}`, "debug"); + toast("Transcription added to prompt", "success"); + return { text }; + } catch (err) { + clearProcessingToast(); + logger?.log("STT", `Turn append failed: ${err.message}`, "error"); + toast(`STT error: ${err.message}`, "error"); + return { error: err.message }; + } finally { processing = false; recording = false; } } +// Drop a transcribed turn without submitting (e.g. voice stop phrase). +// Clears the sticky toast left up by transcribeTurn and resets the flags. + +function discardTurn() { + clearProcessingToast(); + processing = false; + recording = false; +} + +// Cancel an in-progress recording without transcribing. + +function cancelRecording(logger) { + recording = false; + clearRecordingToast(); + forceKillSox(logger); +} + +async function doTranscribePipeline( + kv, + complete, + client, + api, + toast, + systemPrompt, + submit = false, + logger, + renderer, +) { + logger?.log("STT", `Pipeline started submit=${submit}`, "debug"); + const turn = await transcribeTurn(kv, complete, client, api, toast, systemPrompt, logger); + if (!turn.text) return; + if (submit) { + await submitTurnText(client, renderer, toast, turn.text, logger); + } else { + await appendTurnText(client, renderer, toast, turn.text, logger); + } +} + // ---- Public API for TUI plugin ---- -export function registerSTT(api, kv, complete, prompts, opts, logger) { +export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) { + if (deps.isConversationActive || deps.onConversationKey) { + __setConversationHooks({ + isActive: deps.isConversationActive, + onKey: deps.onConversationKey, + }); + } const client = api.client; const renderer = opts?.focusMode === "primary" ? null : api.renderer; const systemPrompt = prompts?.stt || STT_SYSTEM_PROMPT; @@ -1029,6 +1141,18 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { } logger?.log("STT", `Default language=${sttDefaultLanguage}`, "debug"); + if (Number(opts?.sttContextMessages) > 0) { + sttContextMessages = Math.floor(Number(opts.sttContextMessages)); + } + if (Number(opts?.sttContextChars) > 0) { + sttContextChars = Math.floor(Number(opts.sttContextChars)); + } + logger?.log( + "STT", + `Normalize context messages=${sttContextMessages} chars=${sttContextChars}`, + "debug", + ); + tmpDir = opts?.tmpDir || "/tmp"; try { fs.mkdirSync(tmpDir, { recursive: true }); @@ -1050,7 +1174,26 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { } __setRecordKeybind(kb("stt.record") || "["); - return [ + // Start a recording for the voice-conversation loop. Returns false when busy. + + function startLoopRecording() { + if (recording || processing) return false; + startRecording(kv, backend, toast, logger, opts?.trimSilence); + if (recording) showRecordingToast(); + return recording; + } + + const controller = { + isRecording: () => recording, + isProcessing: () => processing, + start: startLoopRecording, + cancel: () => cancelRecording(logger), + discard: () => discardTurn(), + transcribeTurn: () => transcribeTurn(kv, complete, client, api, toast, systemPrompt, logger), + submitTurnText: (text) => submitTurnText(client, renderer, toast, text, logger), + }; + + const commands = [ { title: sttApiEndpoint ? "STT: record/transcribe (API)" : "STT: record/transcribe", value: "stt.record", @@ -1060,6 +1203,10 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { ...(kb("stt.record") ? { keybind: kb("stt.record") } : {}), slash: { name: "stt-record" }, onSelect() { + if (conversationActive()) { + conversationHooks.onKey?.("record"); + return; + } if (processing) { toast("STT busy, please wait..."); return; @@ -1067,10 +1214,19 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { if (recording) { clearRecordingToast(); toast("Stopping, transcribing..."); - doTranscribePipeline(kv, complete, client, toast, systemPrompt, false, logger, renderer); + doTranscribePipeline( + kv, + complete, + client, + api, + toast, + systemPrompt, + false, + logger, + renderer, + ); } else { - startRecording(kv, backend, toast, logger, opts?.trimSilence); - if (recording) showRecordingToast(); + startLoopRecording(); } }, }, @@ -1083,6 +1239,10 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { ...(kb("stt.submit") ? { keybind: kb("stt.submit") } : {}), slash: { name: "stt-submit" }, onSelect() { + if (conversationActive()) { + conversationHooks.onKey?.("submit"); + return; + } if (processing) { toast("STT busy, please wait..."); return; @@ -1093,7 +1253,17 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { } clearRecordingToast(); toast("Stopping, transcribing..."); - doTranscribePipeline(kv, complete, client, toast, systemPrompt, true, logger, renderer); + doTranscribePipeline( + kv, + complete, + client, + api, + toast, + systemPrompt, + true, + logger, + renderer, + ); }, }, { @@ -1102,10 +1272,12 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { description: "Cancel current recording", slash: { name: "stt-stop" }, onSelect() { + if (conversationActive()) { + toast("Conversation mode is on - use the conversation key to exit", "warning"); + return; + } if (recording) { - recording = false; - clearRecordingToast(); - forceKillSox(logger); + cancelRecording(logger); logger?.log("STT", "Recording cancelled", "debug"); toast("Recording cancelled"); } @@ -1224,4 +1396,6 @@ export function registerSTT(api, kv, complete, prompts, opts, logger) { }, }, ]; + + return { commands, controller }; } diff --git a/lib/tts.js b/lib/tts.js index ea47831..dafe093 100644 --- a/lib/tts.js +++ b/lib/tts.js @@ -5,6 +5,7 @@ import path from "node:path"; import os from "node:os"; import { spawn } from "node:child_process"; import { getSessionTitle } from "./session.js"; +import { clearProcessingToast, showProcessingToast, updateProcessingToast } from "./stt.js"; const VOICES_DIR = path.join(os.homedir(), ".local", "share", "piper-voices"); @@ -309,12 +310,19 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { let lastSpokenMessageID = null; let wasBusy = false; + // Set by the voice-conversation loop while it owns speaking. Auto TTS stays + // out of the way (and consumes the busy flag) so replies are not spoken twice. + let conversationActive = false; api.event.on("session.status", (event) => { if (event.properties?.status?.type === "busy") wasBusy = true; }); api.event.on("session.idle", async (event) => { + if (conversationActive) { + wasBusy = false; + return; + } if (kv.get("tts.mode", "off") !== "on") return; if (!wasBusy) return; wasBusy = false; @@ -326,15 +334,17 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { if (result.lastMessageID === lastSpokenMessageID) return; lastSpokenMessageID = result.lastMessageID; - toast("Normalizing response..."); + showProcessingToast("Normalizing response..."); const llmResult = await normalizeForSpeech(result.text, systemAuto); if (!llmResult.text) { + clearProcessingToast(); logger?.log?.("TTS", `Auto normalization failed: ${llmResult.error}`, "warn"); toast(`TTS normalization failed: ${llmResult.error}`, "warning"); return; } logger?.log?.("TTS", `Auto normalization succeeded chars=${llmResult.text.length}`, "debug"); + clearProcessingToast(); await speakWithSessionPrefix(sessionID, llmResult.text, "Ready for your input."); }); @@ -363,17 +373,45 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { return; } - toast("Normalizing response..."); + showProcessingToast("Normalizing response..."); const llmResult = await normalizeForSpeech(result.text, systemManual); if (!llmResult.text) { + clearProcessingToast(); logger?.log?.("TTS", `Manual normalization failed: ${llmResult.error}`, "warn"); toast(`TTS normalization failed: ${llmResult.error}`, "warning"); return; } logger?.log?.("TTS", `Manual normalization succeeded chars=${llmResult.text.length}`, "debug"); - toast("Speaking last response"); + updateProcessingToast("Speaking..."); await speak(llmResult.text); + clearProcessingToast(); + } + + // Speak the current assistant turn for the voice-conversation loop. Uses the + // auto (narrate/summarize) prompt and no session prefix - the loop already + // announces its own state via toasts. + + async function speakAssistantTurn() { + const result = await getTurnAssistantText(client, api); + if (!result || !result.text) { + logger?.log?.("TTS", "Conversation: no assistant text to speak", "warn"); + return { spoken: false }; + } + + showProcessingToast("Normalizing response..."); + const llmResult = await normalizeForSpeech(result.text, systemAuto); + if (!llmResult.text) { + clearProcessingToast(); + logger?.log?.("TTS", `Conversation normalization failed: ${llmResult.error}`, "warn"); + toast(`TTS normalization failed: ${llmResult.error}`, "warning"); + return { spoken: false, error: llmResult.error }; + } + + updateProcessingToast("Speaking..."); + await speak(llmResult.text); + clearProcessingToast(); + return { spoken: true }; } const DEFAULT_KEYBINDS = { @@ -389,9 +427,19 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { return v; } + const controller = { + speak: (text) => speak(text), + speakAssistantTurn, + stop: () => stopSpeech(), + isSpeaking: () => piperProc !== null || playProc !== null, + setConversationActive: (v) => { + conversationActive = !!v; + }, + }; + // ---- Commands ---- - return [ + const commands = [ { title: "TTS: speak last response", value: "tts.speak-last", @@ -464,4 +512,6 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { }, }, ]; + + return { commands, controller }; } diff --git a/test/conversation.test.js b/test/conversation.test.js new file mode 100644 index 0000000..043a363 --- /dev/null +++ b/test/conversation.test.js @@ -0,0 +1,35 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { DEFAULT_STOP_PHRASES, matchesStopPhrase, normalizePhrase } from "../lib/conversation.js"; + +test("normalizes phrases for comparison", () => { + assert.equal(normalizePhrase(" Stop... "), "stop"); + assert.equal(normalizePhrase("DỪNG LẠI!"), "dừng lại"); + assert.equal(normalizePhrase("Exit Conversation "), "exit conversation"); +}); + +test("matches exact stop phrases only", () => { + assert.equal(matchesStopPhrase("stop"), true); + assert.equal(matchesStopPhrase("Stop."), true); + assert.equal(matchesStopPhrase("dừng lại"), true); + assert.equal(matchesStopPhrase("KẾT THÚC"), true); + assert.equal(matchesStopPhrase("goodbye!"), true); +}); + +test("does not match speech containing stop words", () => { + assert.equal(matchesStopPhrase("please stop the server"), false); + assert.equal(matchesStopPhrase("do not stop"), false); + assert.equal(matchesStopPhrase(""), false); + assert.equal(matchesStopPhrase(null), false); +}); + +test("supports custom phrase lists", () => { + assert.equal(matchesStopPhrase("halt", ["halt"]), true); + assert.equal(matchesStopPhrase("stop", ["halt"]), false); +}); + +test("default list covers both languages", () => { + assert.ok(DEFAULT_STOP_PHRASES.includes("stop")); + assert.ok(DEFAULT_STOP_PHRASES.includes("dừng lại")); +}); diff --git a/test/session.test.js b/test/session.test.js new file mode 100644 index 0000000..15dfc6c --- /dev/null +++ b/test/session.test.js @@ -0,0 +1,67 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { getRecentConversationContext } from "../lib/session.js"; + +function makeApi(messages, partsByMessage) { + return { + route: { current: { name: "session", params: { sessionID: "s1" } } }, + state: { + session: { messages: () => messages }, + part: (messageID) => partsByMessage[messageID] || [], + }, + }; +} + +const client = { session: { list: async () => ({ data: [] }) } }; + +test("formats recent turns newest-last with roles", async () => { + const api = makeApi( + [ + { id: "m1", role: "user" }, + { id: "m2", role: "assistant" }, + ], + { + m1: [{ type: "text", text: "Cristina is a guy" }], + m2: [{ type: "text", text: "Got it, what about him?" }], + }, + ); + const ctx = await getRecentConversationContext(client, api); + assert.equal(ctx, "user: Cristina is a guy\nassistant: Got it, what about him?"); +}); + +test("caps message count and total chars keeping the tail", async () => { + const messages = Array.from({ length: 10 }, (_, i) => ({ id: `m${i}`, role: "user" })); + const parts = {}; + messages.forEach((m, i) => { + parts[m.id] = [{ type: "text", text: `turn${i} ${"x".repeat(50)}` }]; + }); + const api = makeApi(messages, parts); + const ctx = await getRecentConversationContext(client, api, { maxMessages: 3, maxChars: 100 }); + assert.ok(ctx.length <= 100); + assert.match(ctx, /turn9/); + assert.doesNotMatch(ctx, /turn0/); +}); + +test("falls back to message summaries when parts are empty", async () => { + const api = makeApi([{ id: "m1", role: "user", summary: { title: "Auth work" } }], {}); + const ctx = await getRecentConversationContext(client, api); + assert.equal(ctx, "user: Auth work"); +}); + +test("returns empty string when context is unavailable", async () => { + const empty = makeApi([], {}); + assert.equal(await getRecentConversationContext(client, empty), ""); + const broken = { + route: { current: { name: "session", params: { sessionID: "s1" } } }, + state: { + session: { + messages: () => { + throw new Error("boom"); + }, + }, + }, + }; + assert.equal(await getRecentConversationContext(client, broken), ""); + assert.equal(await getRecentConversationContext(client, null), ""); +}); From 51dc4698a3a3a79a140e48bccf94d1698d6cb0d3 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Wed, 23 Sep 2026 04:35:00 +0700 Subject: [PATCH 016/205] convo --- lib/conversation.js | 31 +++++++++++++++++++++++++++++-- lib/stt.js | 30 +++++++++++++++++++++++++++++- lib/tts.js | 4 ++++ test/conversation.test.js | 9 +++++++++ 4 files changed, 71 insertions(+), 3 deletions(-) diff --git a/lib/conversation.js b/lib/conversation.js index a51c2a9..0e62256 100644 --- a/lib/conversation.js +++ b/lib/conversation.js @@ -37,10 +37,33 @@ export function normalizePhrase(text) { .replace(/\s+/g, " "); } -export function matchesStopPhrase(text, phrases = DEFAULT_STOP_PHRASES) { +// Small vocabulary so stuttered/short stop commands ("stop stop", "please stop +// the conversation now", "dừng lại đi") still match, while real sentences +// ("stop the server", "do not stop") fall through and get submitted. + +const STOP_VOCAB = new Set( + ( + "stop stops stopping please now exit quit quits quitting end ends ending finish " + + "conversation voice chat goodbye bye good the this that it turn off mode " + + "dừng lại kết thúc hội thoại thoát tạm biệt đi ra ngừng ngưng thôi" + ).split(" "), +); +const MAX_STOP_WORDS = 5; + +export function matchesStopPhrase(text, phrases) { const normalized = normalizePhrase(text); if (!normalized) return false; - return phrases.some((p) => normalizePhrase(p) === normalized); + if ((phrases ?? DEFAULT_STOP_PHRASES).some((p) => normalizePhrase(p) === normalized)) return true; + // Lenient vocab match only applies to the default list; a custom list takes + // full control with exact matching. + if (phrases !== undefined) return false; + const words = normalized + .replace(/[^\p{L}\p{N}\s]/gu, "") + .split(/\s+/) + .filter(Boolean); + return ( + words.length > 0 && words.length <= MAX_STOP_WORDS && words.every((w) => STOP_VOCAB.has(w)) + ); } function delay(ms) { @@ -104,6 +127,7 @@ export function registerConversation(api, opts, logger, { stt, tts }) { waitCancel("stopped"); waitCancel = null; } + stt.setStopHint(null); if (stt.isRecording() || stt.isProcessing()) stt.cancel(); clearProcessingToast(); tts.stop(); @@ -288,6 +312,7 @@ export function registerConversation(api, opts, logger, { stt, tts }) { consecErrors = 0; phase = "idle"; tts.setConversationActive(true); + stt.setStopHint("v"); logger?.log("VOICE", "Conversation started", "debug"); toast("Conversation on - speak, press the key to send"); beginTurn(); @@ -313,6 +338,7 @@ export function registerConversation(api, opts, logger, { stt, tts }) { { title: "Voice: conversation mode", value: "voice.conversation", + category: "opencode-voice", description: "Toggle hands-free voice conversation (record, auto-submit, speak reply, repeat)", ...(kb("voice.conversation") ? { keybind: kb("voice.conversation") } : {}), @@ -324,6 +350,7 @@ export function registerConversation(api, opts, logger, { stt, tts }) { { title: "Voice: stop conversation", value: "voice.conversation-stop", + category: "opencode-voice", description: "Exit voice conversation mode", slash: { name: "voice-conversation-stop" }, onSelect() { diff --git a/lib/stt.js b/lib/stt.js index 195aadc..8042dde 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -254,7 +254,7 @@ const PROCESSING_TOAST_INTERVAL = 2500; let recordingToastTimer = null; let recordingToastFn = null; -const RECORDING_TOAST_BASE = "🎙 Recording"; +const RECORDING_TOAST_BASE = "● Recording"; const RECORDING_TOAST_DURATION = 3000; const RECORDING_TOAST_INTERVAL = 2500; // Live wave + timer config (PR2) @@ -496,6 +496,20 @@ let currentRecordKeybind = "["; export function __setRecordKeybind(kb) { if (kb) currentRecordKeybind = kb.replace(/^/, "leader+"); } + +// Temporary stop-hint override for voice conversation mode, whose key differs +// from stt.record. Pass null to restore the previous hint. + +let savedRecordKeybind = null; +export function __setStopHint(hint) { + if (hint) { + if (savedRecordKeybind === null) savedRecordKeybind = currentRecordKeybind; + __setRecordKeybind(hint); + } else if (savedRecordKeybind !== null) { + currentRecordKeybind = savedRecordKeybind; + savedRecordKeybind = null; + } +} export function buildRecordingMessage() { if (!useWave || recordingStartMs === null) return `${RECORDING_TOAST_BASE} · ${currentRecordKeybind} to stop`; @@ -567,6 +581,7 @@ function startRecording(kv, backend, toast, logger, trimSilence = true) { soxStderr = ""; const mic = kv.get("stt.mic", "") || null; const inputArgs = buildRecordArgs(backend, mic); + const spawnT0 = Date.now(); logger?.log( "STT", `Starting recording backend=${backend} mic=${mic || "system default"}`, @@ -582,8 +597,14 @@ function startRecording(kv, backend, toast, logger, trimSilence = true) { detached: false, }, ); + logger?.log("STT", `sox spawned pid=${soxProc?.pid} after ${Date.now() - spawnT0}ms`, "debug"); + let firstStderrLogged = false; soxProc.stderr.on("data", (chunk) => { + if (!firstStderrLogged) { + firstStderrLogged = true; + logger?.log("STT", `sox first output after ${Date.now() - spawnT0}ms`, "debug"); + } soxStderr += chunk.toString(); }); @@ -1187,6 +1208,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) isRecording: () => recording, isProcessing: () => processing, start: startLoopRecording, + setStopHint: (hint) => __setStopHint(hint), cancel: () => cancelRecording(logger), discard: () => discardTurn(), transcribeTurn: () => transcribeTurn(kv, complete, client, api, toast, systemPrompt, logger), @@ -1197,6 +1219,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) { title: sttApiEndpoint ? "STT: record/transcribe (API)" : "STT: record/transcribe", value: "stt.record", + category: "opencode-voice", description: sttApiEndpoint ? "Toggle recording; press again to stop and transcribe via API" : "Toggle recording; press again to stop and transcribe", @@ -1233,6 +1256,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) { title: sttApiEndpoint ? "STT: submit recording (API)" : "STT: submit recording", value: "stt.submit", + category: "opencode-voice", description: sttApiEndpoint ? "Stop recording, transcribe via API, and submit prompt" : "Stop recording, transcribe, and submit prompt", @@ -1269,6 +1293,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) { title: "STT: cancel recording", value: "stt.stop", + category: "opencode-voice", description: "Cancel current recording", slash: { name: "stt-stop" }, onSelect() { @@ -1286,6 +1311,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) { title: sttApiEndpoint ? "STT: select model (API)" : "STT: select model", value: "stt.model", + category: "opencode-voice", description: sttApiEndpoint ? "Choose whisper model via API" : "Choose whisper model", slash: { name: "stt-model" }, async onSelect() { @@ -1331,6 +1357,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) { title: "STT: select language", value: "stt.language", + category: "opencode-voice", description: "Choose transcription language (local whisper-cli only)", slash: { name: "stt-language" }, onSelect() { @@ -1355,6 +1382,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) { title: "STT: select microphone", value: "stt.mic", + category: "opencode-voice", description: "Choose audio input device", slash: { name: "stt-mic" }, onSelect() { diff --git a/lib/tts.js b/lib/tts.js index dafe093..fb6366b 100644 --- a/lib/tts.js +++ b/lib/tts.js @@ -443,6 +443,7 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { { title: "TTS: speak last response", value: "tts.speak-last", + category: "opencode-voice", description: "Read the last assistant response aloud (detailed)", ...(kb("tts.speak-last") ? { keybind: kb("tts.speak-last") } : {}), slash: { name: "tts-speak" }, @@ -453,6 +454,7 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { { title: "TTS: toggle", value: "tts.mode", + category: "opencode-voice", description: "Toggle auto text-to-speech on/off", ...(kb("tts.mode") ? { keybind: kb("tts.mode") } : {}), slash: { name: "tts-mode" }, @@ -479,6 +481,7 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { { title: "TTS: stop playback", value: "tts.stop", + category: "opencode-voice", description: "Stop current TTS playback", ...(kb("tts.stop") ? { keybind: kb("tts.stop") } : {}), slash: { name: "tts-stop" }, @@ -489,6 +492,7 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { { title: "TTS: select voice", value: "tts.voice", + category: "opencode-voice", description: "Choose TTS voice", slash: { name: "tts-voice" }, onSelect() { diff --git a/test/conversation.test.js b/test/conversation.test.js index 043a363..41e643e 100644 --- a/test/conversation.test.js +++ b/test/conversation.test.js @@ -17,9 +17,18 @@ test("matches exact stop phrases only", () => { assert.equal(matchesStopPhrase("goodbye!"), true); }); +test("matches stuttered and padded stop commands", () => { + assert.equal(matchesStopPhrase("stop stop"), true); + assert.equal(matchesStopPhrase("stop stop stopping"), true); + assert.equal(matchesStopPhrase("please stop the conversation now"), true); + assert.equal(matchesStopPhrase("dừng lại đi"), true); + assert.equal(matchesStopPhrase("thôi"), true); +}); + test("does not match speech containing stop words", () => { assert.equal(matchesStopPhrase("please stop the server"), false); assert.equal(matchesStopPhrase("do not stop"), false); + assert.equal(matchesStopPhrase("stop the deployment right now please sir"), false); assert.equal(matchesStopPhrase(""), false); assert.equal(matchesStopPhrase(null), false); }); From b4ff45fb9b2453495d1b2f7bfc7b76777adfdb25 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Wed, 23 Sep 2026 11:41:39 +0700 Subject: [PATCH 017/205] feat(voice): single-key conversation states, grouping, latency cuts - Palette grouping: category opencode-voice on all 12 commands (like opencode-quota). - Conversation option B: one key (send / pause speech / resume / exit), new paused state, empty turns pause instead of re-recording, tts-stop pauses the loop. - Recording toast shows leader+v hint in conversation mode, tofu-safe icon. - Lenient stop-phrase vocab (stuttered/padded commands stop, real sentences submit). - Latency: per-stage timing logs, normalize token caps (1024/2048), context prefetch during recording, conditional context attach, 15s normalize timeout with raw fallback. --- README.md | 24 ++++-- index.js | 5 +- lib/conversation.js | 66 ++++++++++----- lib/stt.js | 118 ++++++++++++++++++++++---- lib/tts.js | 46 +++++++++- test/conversation.test.js | 174 +++++++++++++++++++++++++++++++++++++- test/stt.test.js | 11 +++ 7 files changed, 394 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index edc6c01..194866a 100644 --- a/README.md +++ b/README.md @@ -336,6 +336,7 @@ up or how responses are spoken. - `sttContextMessages` _(optional)_ - recent turns sent as knowledge with STT normalization (default `8`) - `sttContextChars` _(optional)_ - max chars of that context (default `3000`, tail kept) +- `sttNormalizeTimeoutMs` _(optional)_ - worst-case budget per normalize call, raw transcript used on timeout (default `15000`) - `sttPrompt` _(optional)_ - system prompt for cleaning up whisper transcriptions - `ttsAutoPrompt` _(optional)_ - system prompt for auto-speaking assistant responses - `ttsManualPrompt` _(optional)_ - system prompt for manually reading responses aloud @@ -382,19 +383,26 @@ then `s`. | `/voice-conversation` | `leader+v` | Toggle hands-free voice conversation mode | | `/voice-conversation-stop` | | Exit voice conversation mode | -Press the conversation key to enter the mode, speak, then press again to -send. The turn is transcribed, normalized, submitted immediately, the reply -is waited on and spoken aloud, and recording restarts automatically: +One key drives the whole loop - its meaning follows the toast on screen: ``` record -> transcribe -> normalize -> submit -> wait reply -> speak -> record ... ``` -While the reply is speaking, press the key to barge in (stop speech, record -the next turn). While waiting/processing, the key exits the mode. Saying a -stop phrase (`stop`, `goodbye`, `dừng lại`, ...) ends the mode without -submitting. While the mode is on, the plain `/stt-record` keys finish the -current turn and auto TTS stays silent (the loop speaks the reply itself). +| Toast shows | Pressing the key does | +| ------------------------- | ------------------------------------ | +| ● Recording | Finish the turn and submit | +| Speaking... | Pause speech (press again to record) | +| Paused | Record again | +| Waiting / Transcribing... | Exit the mode | + +Empty or failed turns pause instead of re-recording, so the key never +surprises. Saying only a stop phrase (`stop`, `stop stop`, `dừng lại đi`, +...) ends the mode without submitting - full sentences mentioning stop still +submit normally. `/tts-stop` pauses a speaking reply; `/voice-conversation-stop` +exits from anywhere. While the mode is on, the plain `/stt-record` keys act +as the conversation key and auto TTS stays silent (the loop speaks the reply +itself). Options: `conversationMaxTurns` (default `50`), `conversationTimeoutMs` (default `300000`), `conversationRestartDelayMs` (default `350`), diff --git a/index.js b/index.js index fbe2299..178d377 100644 --- a/index.js +++ b/index.js @@ -82,7 +82,10 @@ export default { isConversationActive: () => shared.conversation?.isActive() === true, onConversationKey: (source) => shared.conversation?.onKey(source), }); - const tts = registerTTS(api, kv, complete, prompts, options, logger); + const tts = registerTTS(api, kv, complete, prompts, options, logger, { + isConversationActive: () => shared.conversation?.isActive() === true, + onConversationStopKey: () => shared.conversation?.onTtsStop() === true, + }); const conversation = registerConversation(api, options, logger, { stt: stt.controller, tts: tts.controller, diff --git a/lib/conversation.js b/lib/conversation.js index 0e62256..4a87e0c 100644 --- a/lib/conversation.js +++ b/lib/conversation.js @@ -1,14 +1,18 @@ // Voice conversation mode: hands-free talk loop with OpenCode. // -// Press the conversation key to enter the mode, speak, press again to send. -// The turn is transcribed, normalized, submitted immediately, the reply is -// waited on, spoken aloud, and recording restarts automatically: +// One key drives the whole loop; its meaning depends on the state shown in +// the toast: // // record -> transcribe -> normalize -> submit -> wait reply -> speak -> record ... // -// Press the key while speaking to barge in (stop speech, record next turn). -// Press the key while waiting/processing to exit. Saying a stop phrase -// ("stop", "dừng lại", ...) ends the mode without submitting. +// - recording + key: finish the turn and submit +// - speaking + key: pause speech (press again to record the next turn) +// - paused + key: record again +// - waiting/processing + key: exit the mode +// +// Saying a stop phrase ("stop", "dừng lại", ...) ends the mode without +// submitting. Empty or failed turns pause instead of auto-recording, so the +// key never surprises. import { clearProcessingToast, showProcessingToast } from "./stt.js"; @@ -81,7 +85,7 @@ export function registerConversation(api, opts, logger, { stt, tts }) { : DEFAULT_STOP_PHRASES; let active = false; - let phase = "idle"; // idle | recording | processing | waiting | speaking + let phase = "idle"; // idle | recording | processing | waiting | speaking | paused let turn = 0; let consecErrors = 0; let generation = 0; @@ -206,12 +210,12 @@ export function registerConversation(api, opts, logger, { stt, tts }) { stop("error"); return; } - beginTurn(); + pauseForRetry("Paused - press the key to retry"); return; } if (!res.text) { consecErrors = 0; - beginTurn(); + pauseForRetry("No speech heard - press the key to try again"); return; } consecErrors = 0; @@ -267,11 +271,32 @@ export function registerConversation(api, opts, logger, { stt, tts }) { beginTurn(); } - function bargeIn() { + // Pause instead of auto-recording so an empty or failed turn never feels + // like the keypress was ignored. + + function pauseForRetry(message) { + if (!active) return; + phase = "paused"; + if (message) toast(message, "warning"); + } + + // Stop speech and hold the mode. The next keypress records again. + + function pauseSpeech() { if (!active || phase !== "speaking") return; - logger?.log("VOICE", "Conversation barge-in", "debug"); + logger?.log("VOICE", "Conversation speech paused", "debug"); tts.stop(); - beginTurn(); + phase = "paused"; + toast("Paused - press the key to speak"); + } + + // Called by the TTS stop command while the mode is on. Returns true when the + // keypress was consumed (speech paused), so TTS skips its own handling. + + function onTtsStop() { + if (!active || phase !== "speaking") return false; + pauseSpeech(); + return true; } function onKey(source) { @@ -284,11 +309,11 @@ export function registerConversation(api, opts, logger, { stt, tts }) { return; } if (phase === "speaking") { - if (source === "toggle") { - bargeIn(); - } else { - toast("Speaking - press the conversation key to interrupt", "warning"); - } + pauseSpeech(); + return; + } + if (phase === "paused") { + beginTurn(); return; } // processing | waiting | idle @@ -314,7 +339,7 @@ export function registerConversation(api, opts, logger, { stt, tts }) { tts.setConversationActive(true); stt.setStopHint("v"); logger?.log("VOICE", "Conversation started", "debug"); - toast("Conversation on - speak, press the key to send"); + toast("Conversation on - one key: send, pause speech, resume"); beginTurn(); } @@ -339,8 +364,7 @@ export function registerConversation(api, opts, logger, { stt, tts }) { title: "Voice: conversation mode", value: "voice.conversation", category: "opencode-voice", - description: - "Toggle hands-free voice conversation (record, auto-submit, speak reply, repeat)", + description: "Toggle voice conversation (one key: send, pause speech, resume, exit)", ...(kb("voice.conversation") ? { keybind: kb("voice.conversation") } : {}), slash: { name: "voice-conversation" }, onSelect() { @@ -362,7 +386,7 @@ export function registerConversation(api, opts, logger, { stt, tts }) { }, ]; - const controller = { isActive, onKey, start, stop }; + const controller = { isActive, onKey, onTtsStop, start, stop }; return { commands, controller }; } diff --git a/lib/stt.js b/lib/stt.js index 8042dde..bf790eb 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -57,6 +57,54 @@ let sttDefaultLanguage = DEFAULT_LANGUAGE; // Bounds for the recent-turns knowledge block sent with normalization. let sttContextMessages = 8; let sttContextChars = 3000; +// Worst-case budget for one normalize call; on timeout the raw transcript is +// used so a stalled LLM never blocks the turn. +let sttNormalizeTimeoutMs = 15000; + +// Pronouns, demonstratives, and capitalized words signal that the transcript +// may reference the conversation (he/she/Cristina/...). Without them the +// knowledge block only adds input tokens, so it is skipped. + +const CONTEXT_SIGNALS = + /\b(he|him|his|she|her|hers|they|them|their|it|its|this|that|these|those|anh|chị|em|cô|chú|bác|ông|bà|nó|họ|này|kia|đó|ấy)\b|[A-ZÀ-ỴĐ][a-zà-ỹ]{1,}/u; + +export function needsContext(rawText) { + if (!rawText || rawText.length < 3) return false; + return CONTEXT_SIGNALS.test(rawText); +} + +// Prefetched conversation context, kicked off while the user is still +// speaking so the fetch usually finishes before the turn ends. + +let prefetchedContext = null; // { at, sessionID, promise } + +function currentRouteSessionID(api) { + const route = api?.route?.current; + return route?.name === "session" ? route?.params?.sessionID || null : null; +} + +async function fetchContextParts(client, api) { + const [sessionTitle, recent] = await Promise.all([ + getActiveSessionTitle(client), + getRecentConversationContext(client, api, { + maxMessages: sttContextMessages, + maxChars: sttContextChars, + }), + ]); + return { sessionTitle, recent }; +} + +function prefetchContextParts(client, api) { + try { + prefetchedContext = { + at: Date.now(), + sessionID: currentRouteSessionID(api), + promise: fetchContextParts(client, api), + }; + } catch { + prefetchedContext = null; + } +} export function isOpenRouterEndpoint(endpoint) { return /(^https?:\/\/)?([^/]+\.)?openrouter\.ai(\/|$)/i.test(endpoint || ""); @@ -833,11 +881,29 @@ async function normalizeTranscription(complete, rawText, contextBlock, systemPro const prompt = contextBlock ? `\n${contextBlock}\n\nClean up this speech-to-text transcription:\n\n${rawText}` : `Clean up this speech-to-text transcription:\n\n${rawText}`; - const result = await complete({ - system: systemPrompt, - prompt, - config: { temperature: 0 }, - }); + const result = await Promise.race([ + complete({ + system: systemPrompt, + prompt, + // Spoken turns are short; a tight cap bounds worst-case latency so a + // rambling model cannot stall the turn (overrides global maxTokens). + config: { temperature: 0, maxTokens: 1024 }, + }), + new Promise((resolve) => + setTimeout( + () => + resolve({ + text: null, + error: `Normalization timed out after ${sttNormalizeTimeoutMs}ms`, + timedOut: true, + }), + sttNormalizeTimeoutMs, + ), + ), + ]); + if (result?.timedOut) { + logger?.log("STT", `Normalization timeout after ${sttNormalizeTimeoutMs}ms, using raw`, "warn"); + } if (result.text && isHallucinated(rawText, result.text)) { logger?.log( "STT", @@ -988,7 +1054,9 @@ async function transcribeTurn(kv, complete, client, api, toast, systemPrompt, lo try { showProcessingToast("Transcribing..."); + const tTranscribe = Date.now(); const result = sttApiEndpoint ? await transcribeApi(kv, logger) : await transcribe(kv, logger); + const transcribeMs = Date.now() - tTranscribe; if (result.error) { clearProcessingToast(); @@ -1008,16 +1076,23 @@ async function transcribeTurn(kv, complete, client, api, toast, systemPrompt, lo } updateProcessingToast("Normalizing..."); - const [sessionTitle, recent] = await Promise.all([ - getActiveSessionTitle(client), - getRecentConversationContext(client, api, { - maxMessages: sttContextMessages, - maxChars: sttContextChars, - }), - ]); - const contextBlock = [sessionTitle ? `[session: "${sessionTitle}"]` : null, recent || null] + const tContext = Date.now(); + const sessionID = currentRouteSessionID(api); + const pref = prefetchedContext; + prefetchedContext = null; + const { sessionTitle, recent } = + pref && Date.now() - pref.at < 60000 && pref.sessionID === sessionID + ? await pref.promise + : await fetchContextParts(client, api); + const contextMs = Date.now() - tContext; + const withTurns = needsContext(result.text); + const contextBlock = [ + sessionTitle ? `[session: "${sessionTitle}"]` : null, + withTurns && recent ? recent : null, + ] .filter(Boolean) .join("\n"); + const tNormalize = Date.now(); const llmResult = await normalizeTranscription( complete, result.text, @@ -1025,6 +1100,7 @@ async function transcribeTurn(kv, complete, client, api, toast, systemPrompt, lo systemPrompt, logger, ); + const normalizeMs = Date.now() - tNormalize; if (!llmResult.text) { clearProcessingToast(); @@ -1035,7 +1111,11 @@ async function transcribeTurn(kv, complete, client, api, toast, systemPrompt, lo return { text: result.text, fallback: true }; } - logger?.log("STT", `Turn transcription ready chars=${llmResult.text.length}`, "debug"); + logger?.log( + "STT", + `Turn timings transcribeMs=${transcribeMs} contextMs=${contextMs} contextTurns=${withTurns ? 1 : 0} normalizeMs=${normalizeMs} rawChars=${result.text.length}`, + "debug", + ); return { text: llmResult.text }; } catch (err) { clearProcessingToast(); @@ -1168,6 +1248,9 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) if (Number(opts?.sttContextChars) > 0) { sttContextChars = Math.floor(Number(opts.sttContextChars)); } + if (Number(opts?.sttNormalizeTimeoutMs) > 0) { + sttNormalizeTimeoutMs = Math.floor(Number(opts.sttNormalizeTimeoutMs)); + } logger?.log( "STT", `Normalize context messages=${sttContextMessages} chars=${sttContextChars}`, @@ -1200,7 +1283,12 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) function startLoopRecording() { if (recording || processing) return false; startRecording(kv, backend, toast, logger, opts?.trimSilence); - if (recording) showRecordingToast(); + if (recording) { + showRecordingToast(); + // Fetch title + recent turns while the user speaks, so the context is + // usually ready before the turn ends instead of on the critical path. + prefetchContextParts(client, api); + } return recording; } diff --git a/lib/tts.js b/lib/tts.js index fb6366b..c650906 100644 --- a/lib/tts.js +++ b/lib/tts.js @@ -23,6 +23,24 @@ const PIPER_RATE = 22050; const PIPER_BITS = 16; const PIPER_CHANNELS = 1; +// ---- Conversation-mode hooks (wired by index.js) ---- +// While voice conversation owns speaking, the TTS stop key pauses the loop +// instead of just silencing (which would auto-record again). + +let conversationTtsHooks = { isActive: null, onStopKey: null }; + +export function __setConversationTtsHooks(hooks) { + conversationTtsHooks = { ...conversationTtsHooks, ...hooks }; +} + +function conversationTtsActive() { + try { + return conversationTtsHooks.isActive?.() === true; + } catch { + return false; + } +} + // ---- System prompts ---- const SYSTEM_AUTO = `You are a text-to-speech narrator for a coding assistant CLI. Your job is to convert the assistant's markdown output into natural spoken text that is useful and pleasant to listen to. @@ -109,7 +127,13 @@ async function getTurnAssistantText(client, api) { // ---- Public API for TUI plugin ---- -export function registerTTS(api, kv, complete, prompts, opts, logger) { +export function registerTTS(api, kv, complete, prompts, opts, logger, deps = {}) { + if (deps.isConversationActive || deps.onConversationStopKey) { + __setConversationTtsHooks({ + isActive: deps.isConversationActive, + onStopKey: deps.onConversationStopKey, + }); + } const client = api.client; const systemAuto = prompts?.ttsAuto || SYSTEM_AUTO; const systemManual = prompts?.ttsManual || SYSTEM_MANUAL; @@ -153,12 +177,12 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { return pathDirs.some((dir) => fs.existsSync(path.join(dir, "piper"))); } - async function normalizeForSpeech(text, systemPrompt) { + async function normalizeForSpeech(text, systemPrompt, maxTokens = 4096) { logger?.log?.("TTS", `Normalizing speech chars=${text.length}`, "debug"); return complete({ system: systemPrompt, prompt: `Convert for text-to-speech:\n\n${text}`, - config: { maxTokens: 4096 }, + config: { maxTokens }, }); } @@ -393,14 +417,20 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { // announces its own state via toasts. async function speakAssistantTurn() { + const tFetch = Date.now(); const result = await getTurnAssistantText(client, api); if (!result || !result.text) { logger?.log?.("TTS", "Conversation: no assistant text to speak", "warn"); return { spoken: false }; } + const fetchMs = Date.now() - tFetch; showProcessingToast("Normalizing response..."); - const llmResult = await normalizeForSpeech(result.text, systemAuto); + const tNormalize = Date.now(); + // Auto replies are narrated/summarized, so a tight cap is safe here (the + // manual read-aloud keeps the full 4096). + const llmResult = await normalizeForSpeech(result.text, systemAuto, 2048); + const normalizeMs = Date.now() - tNormalize; if (!llmResult.text) { clearProcessingToast(); logger?.log?.("TTS", `Conversation normalization failed: ${llmResult.error}`, "warn"); @@ -409,8 +439,15 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { } updateProcessingToast("Speaking..."); + const tSpeak = Date.now(); await speak(llmResult.text); + const speakMs = Date.now() - tSpeak; clearProcessingToast(); + logger?.log?.( + "TTS", + `Conversation timings fetchMs=${fetchMs} normalizeMs=${normalizeMs} speakMs=${speakMs} replyChars=${result.text.length}`, + "debug", + ); return { spoken: true }; } @@ -486,6 +523,7 @@ export function registerTTS(api, kv, complete, prompts, opts, logger) { ...(kb("tts.stop") ? { keybind: kb("tts.stop") } : {}), slash: { name: "tts-stop" }, onSelect() { + if (conversationTtsActive() && conversationTtsHooks.onStopKey?.()) return; if (stopSpeech()) toast("TTS stopped"); }, }, diff --git a/test/conversation.test.js b/test/conversation.test.js index 41e643e..fe56b51 100644 --- a/test/conversation.test.js +++ b/test/conversation.test.js @@ -1,7 +1,12 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { DEFAULT_STOP_PHRASES, matchesStopPhrase, normalizePhrase } from "../lib/conversation.js"; +import { + DEFAULT_STOP_PHRASES, + matchesStopPhrase, + normalizePhrase, + registerConversation, +} from "../lib/conversation.js"; test("normalizes phrases for comparison", () => { assert.equal(normalizePhrase(" Stop... "), "stop"); @@ -42,3 +47,170 @@ test("default list covers both languages", () => { assert.ok(DEFAULT_STOP_PHRASES.includes("stop")); assert.ok(DEFAULT_STOP_PHRASES.includes("dừng lại")); }); + +const tick = (ms = 10) => new Promise((r) => setTimeout(r, ms)); + +function makeHarness({ transcribe = { text: "hello" } } = {}) { + const toasts = []; + const handlers = {}; + const api = { + ui: { toast: (input) => toasts.push(input?.message ?? input) }, + route: { current: { name: "session", params: { sessionID: "s1" } } }, + event: { + on: (type, handler) => { + (handlers[type] ??= []).push(handler); + return () => {}; + }, + }, + lifecycle: {}, + }; + const calls = { sttStart: 0, ttsStop: 0, speakTurn: 0, submitted: [] }; + let speakGate = null; + const stt = { + isRecording: () => false, + isProcessing: () => false, + start: () => { + calls.sttStart += 1; + return true; + }, + setStopHint: () => {}, + cancel: () => {}, + discard: () => {}, + transcribeTurn: () => + transcribe && typeof transcribe.then === "function" + ? transcribe + : Promise.resolve({ ...transcribe }), + submitTurnText: async (text) => { + calls.submitted.push(text); + return { text }; + }, + }; + const tts = { + speak: async () => {}, + speakAssistantTurn: async () => { + calls.speakTurn += 1; + if (speakGate) await speakGate; + return { spoken: true }; + }, + stop: () => { + calls.ttsStop += 1; + return true; + }, + isSpeaking: () => false, + setConversationActive: () => {}, + }; + const { controller } = registerConversation( + api, + { conversationTimeoutMs: 60, conversationRestartDelayMs: 5 }, + null, + { stt, tts }, + ); + return { + api, + toasts, + handlers, + calls, + controller, + setSpeakGate: (p) => { + speakGate = p; + }, + }; +} + +function fireIdle(h, sessionID = "s1") { + for (const handler of h["session.idle"] || []) { + handler({ properties: { sessionID } }); + } +} + +test("full turn loops back to recording", async () => { + const h = makeHarness(); + h.controller.onKey("toggle"); + assert.equal(h.calls.sttStart, 1); + h.controller.onKey("toggle"); + await tick(30); + assert.deepEqual(h.calls.submitted, ["hello"]); + fireIdle(h.handlers); + await tick(30); + assert.equal(h.calls.speakTurn, 1); + assert.equal(h.calls.sttStart, 2); + h.controller.stop("test"); +}); + +test("speaking + key pauses, next key records again", async () => { + const h = makeHarness(); + let release; + h.setSpeakGate(new Promise((r) => (release = r))); + h.controller.onKey("toggle"); + h.controller.onKey("toggle"); + await tick(30); + fireIdle(h.handlers); + await tick(20); + assert.equal(h.calls.speakTurn, 1); + h.controller.onKey("toggle"); + assert.equal(h.calls.ttsStop, 1); + assert.ok(h.toasts.some((t) => t.includes("Paused"))); + release(); + await tick(20); + assert.equal(h.calls.sttStart, 1); + h.controller.onKey("toggle"); + assert.equal(h.calls.sttStart, 2); + h.controller.stop("test"); +}); + +test("empty turn pauses instead of re-recording", async () => { + const h = makeHarness({ transcribe: { text: null, empty: true } }); + h.controller.onKey("toggle"); + h.controller.onKey("toggle"); + await tick(20); + assert.equal(h.calls.sttStart, 1); + assert.ok(h.toasts.some((t) => t.includes("No speech"))); + h.controller.onKey("toggle"); + assert.equal(h.calls.sttStart, 2); + h.controller.stop("test"); +}); + +test("toggle while waiting exits and drops the late reply", async () => { + const h = makeHarness(); + h.controller.onKey("toggle"); + h.controller.onKey("toggle"); + await tick(30); + assert.deepEqual(h.calls.submitted, ["hello"]); + h.controller.onKey("toggle"); + assert.ok(h.toasts.includes("Conversation off")); + fireIdle(h.handlers); + await tick(30); + assert.equal(h.calls.speakTurn, 0); +}); + +test("exit during processing cancels the turn", async () => { + let resolveTranscribe; + const pending = new Promise((r) => (resolveTranscribe = r)); + const h = makeHarness({ transcribe: pending }); + h.controller.onKey("toggle"); + h.controller.onKey("toggle"); + await tick(10); + h.controller.onKey("toggle"); + assert.ok(h.toasts.includes("Conversation off")); + resolveTranscribe({ text: "late hello" }); + await tick(20); + assert.deepEqual(h.calls.submitted, []); +}); + +test("tts stop key pauses speaking, ignored when inactive", async () => { + const h = makeHarness(); + assert.equal(h.controller.onTtsStop(), false); + let release; + h.setSpeakGate(new Promise((r) => (release = r))); + h.controller.onKey("toggle"); + h.controller.onKey("toggle"); + await tick(30); + fireIdle(h.handlers); + await tick(20); + assert.equal(h.controller.onTtsStop(), true); + assert.equal(h.calls.ttsStop, 1); + release(); + await tick(20); + assert.equal(h.calls.sttStart, 1); + h.controller.stop("test"); +}); diff --git a/test/stt.test.js b/test/stt.test.js index c892707..5a7cc90 100644 --- a/test/stt.test.js +++ b/test/stt.test.js @@ -13,12 +13,23 @@ import { isOpenRouterEndpoint, isProcessingToastActive, isWSL, + needsContext, parsePactlSources, parsePactlSourcesShort, showProcessingToast, updateProcessingToast, } from "../lib/stt.js"; +test("detects transcripts that need conversation context", () => { + assert.equal(needsContext("ask him about it"), true); + assert.equal(needsContext("Cristina đi đâu?"), true); + assert.equal(needsContext("fix this file"), true); + assert.equal(needsContext("run the tests"), false); + assert.equal(needsContext("mở file log"), false); + assert.equal(needsContext(""), false); + assert.equal(needsContext(null), false); +}); + test("inserts transcription into the focused OpenTUI input", () => { const calls = []; const input = { From 1bf05f91566cf776760891fdec1a28a3536fc314 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Wed, 23 Sep 2026 16:55:24 +0700 Subject: [PATCH 018/205] convo --- README.md | 15 +++++ index.js | 24 ++++++-- lib/llm-client.js | 48 ++++++++++++--- lib/stt.js | 24 ++++++-- lib/voice-model.js | 122 +++++++++++++++++++++++++++++++++++++++ test/llm-client.test.js | 90 ++++++++++++++++++++++++++++- test/voice-model.test.js | 56 ++++++++++++++++++ 7 files changed, 360 insertions(+), 19 deletions(-) create mode 100644 lib/voice-model.js create mode 100644 test/voice-model.test.js diff --git a/README.md b/README.md index 194866a..f830e9b 100644 --- a/README.md +++ b/README.md @@ -313,6 +313,20 @@ plugin on a machine without whisper-cpp installed. OpenRouter note: when `sttEndpoint` points at `https://openrouter.ai/api/v1`, the plugin automatically uses OpenRouter's JSON/base64 transcription request format instead of multipart upload. +### Voice LLM selection + +Instead of hand-editing `endpoint`/`model` in `tui.json`, run `/voice-model` +(palette group `opencode-voice`) to pick from OpenCode's own provider catalog +— the same providers you connected in OpenCode, no file editing: + +- The selection (`voice.providerID` + `voice.modelID` in kv) fills in whatever + `endpoint`/`model`/`apiKeyEnv` the plugin options leave out. Explicit + options always win; `/voice-model-clear` goes back to options-only. +- Only env-key providers work (key read live from the provider's env list, + e.g. `OPENROUTER_API_KEY`). OAuth/Console-managed credentials are invisible + to plugins — for those, keep explicit `endpoint` options. +- The picker warns when no key is exported yet. + ### Custom prompts The LLM system prompts used for normalization can be fully replaced by pointing @@ -337,6 +351,7 @@ up or how responses are spoken. - `sttContextMessages` _(optional)_ - recent turns sent as knowledge with STT normalization (default `8`) - `sttContextChars` _(optional)_ - max chars of that context (default `3000`, tail kept) - `sttNormalizeTimeoutMs` _(optional)_ - worst-case budget per normalize call, raw transcript used on timeout (default `15000`) +- `sttAutoSubmit` _(optional)_ - one-shot `/stt-record` submits immediately instead of appending for edit (default `false`; conversation mode always submits) - `sttPrompt` _(optional)_ - system prompt for cleaning up whisper transcriptions - `ttsAutoPrompt` _(optional)_ - system prompt for auto-speaking assistant responses - `ttsManualPrompt` _(optional)_ - system prompt for manually reading responses aloud diff --git a/index.js b/index.js index 178d377..5939fad 100644 --- a/index.js +++ b/index.js @@ -38,6 +38,7 @@ import os from "node:os"; import { registerSTT } from "./lib/stt.js"; import { registerTTS } from "./lib/tts.js"; import { registerConversation } from "./lib/conversation.js"; +import { registerVoiceModel, resolveVoiceProviderModel } from "./lib/voice-model.js"; import { createClient } from "./lib/llm-client.js"; import { createLogger } from "./lib/logger.js"; @@ -66,10 +67,17 @@ export default { logger.log("plugin", "Initializing", "debug"); // Session-scoped gateways (opencode.ai/zen/go) require x-opencode-session. // Read the live route at call time so normalize works in any session. - const { complete } = createClient(options, logger, () => { - const route = api?.route?.current; - return route?.name === "session" ? route?.params?.sessionID : undefined; - }); + // The voice-selected provider (/voice-model) fills endpoint/model only + // when the explicit options leave them out. + const { complete } = createClient( + options, + logger, + () => { + const route = api?.route?.current; + return route?.name === "session" ? route?.params?.sessionID : undefined; + }, + () => resolveVoiceProviderModel(api, kv), + ); const prompts = { stt: loadPromptFile(options?.sttPrompt, logger, "STT"), @@ -91,7 +99,13 @@ export default { tts: tts.controller, }); shared.conversation = conversation.controller; + const voiceModel = registerVoiceModel(api, kv, options, logger); - api.command.register(() => [...stt.commands, ...tts.commands, ...conversation.commands]); + api.command.register(() => [ + ...stt.commands, + ...tts.commands, + ...conversation.commands, + ...voiceModel.commands, + ]); }, }; diff --git a/lib/llm-client.js b/lib/llm-client.js index a8134cf..2f60dbc 100644 --- a/lib/llm-client.js +++ b/lib/llm-client.js @@ -79,6 +79,30 @@ function normalizeRetries(value) { return Math.floor(parsed); } +/** + * Resolve an OpenCode provider + model (as picked via /voice-model) into + * OpenAI-compatible call config. Explicit plugin options always win; this is + * only the fallback when endpoint/model are not configured. + * + * Auth caveat: only env-key providers work (key read live from provider.env). + * OAuth/Console-managed credentials are not visible to plugins. + */ +export function resolveProviderConfig(provider, model) { + if (!provider || !model) return null; + const options = provider.options || {}; + const endpoint = + (typeof options.baseURL === "string" && options.baseURL) || + (typeof options.endpoint === "string" && options.endpoint) || + model?.api?.url || + null; + const envVars = Array.isArray(provider.env) ? provider.env : []; + return { + endpoint, + model: model.id, + apiKeyEnv: envVars[0] || null, + }; +} + function normalizeChatTemplateKwargs(value) { if (!value) return null; if (typeof value === "object") return value; @@ -107,9 +131,12 @@ function wait(ms) { * session ID. Sent as `x-opencode-session` so session-scoped gateways * (e.g. opencode.ai/zen/go) can route the request. Omit when the endpoint * needs no session binding. + * @param {() => ({ provider: object, model: object } | null)} [getProviderModel] - + * Resolver for the voice-selected OpenCode provider + model (see + * /voice-model). Used only when endpoint/model are not set explicitly. * @returns {{ complete: (opts: { system?: string, prompt: string, config?: object }) => Promise<{ text: string | null, error?: string }> }} */ -export function createClient(pluginOptions, logger, getSessionID) { +export function createClient(pluginOptions, logger, getSessionID, getProviderModel) { function getConfig() { const rawUseResponses = pluginOptions?.useResponsesApi ?? @@ -123,10 +150,19 @@ export function createClient(pluginOptions, logger, getSessionID) { : pluginOptions?.apiMode === "chat" ? false : rawUseResponses; + // Voice-selected OpenCode provider (via /voice-model) fills whatever the + // explicit options leave out. Explicit endpoint/model/apiKeyEnv win. + let providerResolved = null; + try { + const selection = typeof getProviderModel === "function" ? getProviderModel() : null; + providerResolved = resolveProviderConfig(selection?.provider, selection?.model); + } catch { + providerResolved = null; + } return { - endpoint: pluginOptions?.endpoint, - model: pluginOptions?.model, - apiKeyEnv: pluginOptions?.apiKeyEnv, + endpoint: pluginOptions?.endpoint ?? providerResolved?.endpoint, + model: pluginOptions?.model ?? providerResolved?.model, + apiKeyEnv: pluginOptions?.apiKeyEnv ?? providerResolved?.apiKeyEnv, maxTokens: pluginOptions?.maxTokens ?? DEFAULTS.maxTokens, reasoningEffort: pluginOptions?.reasoningEffort ?? DEFAULTS.reasoningEffort, chatTemplateKwargs: normalizeChatTemplateKwargs( @@ -164,9 +200,7 @@ export function createClient(pluginOptions, logger, getSessionID) { // Per-call override wins, otherwise ask the live session resolver. // The zen/go gateway rejects requests without x-opencode-session (401/400). const sessionID = - cfg.sessionID ?? - (typeof getSessionID === "function" ? getSessionID() : null) ?? - null; + cfg.sessionID ?? (typeof getSessionID === "function" ? getSessionID() : null) ?? null; const endpoint = resolveEndpoint(cfg.endpoint, cfg.useResponsesApi); const useResponses = endpoint.endsWith("/responses"); diff --git a/lib/stt.js b/lib/stt.js index bf790eb..2dff74b 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -559,11 +559,14 @@ export function __setStopHint(hint) { } } export function buildRecordingMessage() { + // When the conversation loop overrides the stop hint, the toast says so + // explicitly - otherwise users wonder why it names a key they did not press. + const mode = savedRecordKeybind !== null ? " (conversation)" : ""; if (!useWave || recordingStartMs === null) - return `${RECORDING_TOAST_BASE} · ${currentRecordKeybind} to stop`; + return `${RECORDING_TOAST_BASE}${mode} · ${currentRecordKeybind} to stop`; const elapsed = formatElapsed(Date.now() - recordingStartMs); const wave = getWaveString(); - return `${RECORDING_TOAST_BASE} ${wave} ${elapsed} · ${currentRecordKeybind} to stop`; + return `${RECORDING_TOAST_BASE}${mode} ${wave} ${elapsed} · ${currentRecordKeybind} to stop`; } export function showRecordingToast() { @@ -1303,14 +1306,23 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) submitTurnText: (text) => submitTurnText(client, renderer, toast, text, logger), }; + // One-shot auto-submit: speak, press again, and the text submits itself + // without landing in the box first. Off by default (append-then-edit). + const autoSubmit = opts?.sttAutoSubmit === true; + const commands = [ { title: sttApiEndpoint ? "STT: record/transcribe (API)" : "STT: record/transcribe", value: "stt.record", category: "opencode-voice", - description: sttApiEndpoint - ? "Toggle recording; press again to stop and transcribe via API" - : "Toggle recording; press again to stop and transcribe", + description: + sttApiEndpoint && autoSubmit + ? "Toggle recording; press again to stop, transcribe via API and submit" + : sttApiEndpoint + ? "Toggle recording; press again to stop and transcribe via API" + : autoSubmit + ? "Toggle recording; press again to stop, transcribe and submit" + : "Toggle recording; press again to stop and transcribe", ...(kb("stt.record") ? { keybind: kb("stt.record") } : {}), slash: { name: "stt-record" }, onSelect() { @@ -1332,7 +1344,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) api, toast, systemPrompt, - false, + autoSubmit, logger, renderer, ); diff --git a/lib/voice-model.js b/lib/voice-model.js new file mode 100644 index 0000000..a03b8fc --- /dev/null +++ b/lib/voice-model.js @@ -0,0 +1,122 @@ +// Voice LLM picker: reuse OpenCode's own provider/model catalog instead of +// hand-editing endpoint + model in tui.json. +// +// /voice-model lists api.state.provider (the same ~70 providers OpenCode +// connects) then the chosen provider's models, and stores the selection in +// kv. llm-client resolves it to endpoint + model + key env at call time. +// Explicit endpoint/model/apiKeyEnv plugin options always win. +// +// Auth caveat: only env-key providers work (key read live from the provider's +// env list). OAuth/Console-managed credentials are invisible to plugins - for +// those, keep explicit endpoint options. + +export function getVoiceProviderSelection(kv) { + const providerID = kv.get("voice.providerID", null); + const modelID = kv.get("voice.modelID", null); + return providerID && modelID ? { providerID, modelID } : null; +} + +export function resolveVoiceProviderModel(api, kv) { + const selection = getVoiceProviderSelection(kv); + if (!selection) return null; + const providers = api?.state?.provider || []; + const provider = providers.find((p) => p?.id === selection.providerID); + const model = provider?.models?.[selection.modelID]; + if (!provider || !model) return null; + return { provider, model }; +} + +export function registerVoiceModel(api, kv, opts, logger) { + function toast(message, variant = "info") { + api.ui.toast({ message, variant, duration: 3000 }); + } + + function pickModel(provider) { + const models = Object.values(provider.models || {}); + if (models.length === 0) { + toast(`Provider ${provider.name} has no models`, "warning"); + return; + } + const current = kv.get("voice.modelID", null); + api.ui.dialog.replace(() => + api.ui.DialogSelect({ + title: `Voice LLM model (${provider.name})`, + current, + options: models.map((m) => ({ + title: m.name || m.id, + value: m.id, + description: m.id, + onSelect() { + kv.set("voice.providerID", provider.id); + kv.set("voice.modelID", m.id); + const envVars = Array.isArray(provider.env) ? provider.env : []; + const hasKey = envVars.some((e) => e && process.env[e]); + logger?.log( + "VOICE", + `Voice LLM selected provider=${provider.id} model=${m.id}`, + "debug", + ); + toast( + hasKey + ? `Voice LLM: ${provider.name} / ${m.name || m.id}` + : `Voice LLM: ${provider.name} / ${m.name || m.id} (no key in ${envVars.join(", ") || "env"} - export one)`, + hasKey ? "success" : "warning", + ); + api.ui.dialog.clear(); + }, + })), + }), + ); + } + + const commands = [ + { + title: "Voice: select LLM", + value: "voice.model", + category: "opencode-voice", + description: "Choose the LLM for voice normalization from OpenCode providers", + slash: { name: "voice-model" }, + onSelect() { + const providers = [...(api?.state?.provider || [])].sort((a, b) => + (a?.name || a?.id || "").localeCompare(b?.name || b?.id || ""), + ); + if (providers.length === 0) { + toast("No OpenCode providers available", "warning"); + return; + } + if (opts?.endpoint && opts?.model) { + toast("Explicit endpoint/model options override the voice selection", "warning"); + } + const current = kv.get("voice.providerID", null); + api.ui.dialog.replace(() => + api.ui.DialogSelect({ + title: "Voice LLM provider", + current, + options: providers.map((p) => ({ + title: p.name || p.id, + value: p.id, + description: [p.id, (p.env || []).join(", ")].filter(Boolean).join(" · "), + onSelect() { + pickModel(p); + }, + })), + }), + ); + }, + }, + { + title: "Voice: clear LLM selection", + value: "voice.model-clear", + category: "opencode-voice", + description: "Clear the voice LLM selection (back to endpoint options)", + slash: { name: "voice-model-clear" }, + onSelect() { + kv.set("voice.providerID", null); + kv.set("voice.modelID", null); + toast("Voice LLM selection cleared"); + }, + }, + ]; + + return { commands }; +} diff --git a/test/llm-client.test.js b/test/llm-client.test.js index f4d1dbe..febab67 100644 --- a/test/llm-client.test.js +++ b/test/llm-client.test.js @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createClient } from "../lib/llm-client.js"; +import { createClient, resolveProviderConfig } from "../lib/llm-client.js"; function createJsonResponse(status, data) { return { @@ -297,6 +297,94 @@ test("sends x-opencode-session header from session resolver", async () => { } }); +test("resolves voice-selected provider to endpoint config", () => { + const provider = { + id: "openrouter", + name: "OpenRouter", + env: ["OPENROUTER_API_KEY"], + options: { baseURL: "https://openrouter.ai/api/v1" }, + }; + const model = { id: "openai/gpt-4o-mini", api: { url: "https://openrouter.ai/api/v1" } }; + assert.deepEqual(resolveProviderConfig(provider, model), { + endpoint: "https://openrouter.ai/api/v1", + model: "openai/gpt-4o-mini", + apiKeyEnv: "OPENROUTER_API_KEY", + }); + assert.equal(resolveProviderConfig(null, model), null); +}); + +test("falls back to model api url when provider has no baseURL", () => { + const provider = { id: "custom", env: [], options: {} }; + const model = { id: "m1", api: { url: "https://llm.test/v1" } }; + const resolved = resolveProviderConfig(provider, model); + assert.equal(resolved.endpoint, "https://llm.test/v1"); + assert.equal(resolved.apiKeyEnv, null); +}); + +test("uses voice-selected provider when explicit options are missing", async () => { + const previousFetch = globalThis.fetch; + const previousKey = process.env.VOICE_TEST_KEY; + const requests = []; + process.env.VOICE_TEST_KEY = "secret"; + globalThis.fetch = async (url, options) => { + requests.push({ url, options }); + return createJsonResponse(200, { + choices: [{ message: { content: "ok" } }], + }); + }; + + try { + const provider = { + id: "p1", + env: ["VOICE_TEST_KEY"], + options: { baseURL: "https://llm.test/v1" }, + }; + const model = { id: "fast-one", api: { url: "https://llm.test/v1" } }; + const client = createClient({}, null, null, () => ({ provider, model })); + const result = await client.complete({ prompt: "hi" }); + assert.equal(result.text, "ok"); + assert.equal(requests[0].url, "https://llm.test/v1/chat/completions"); + assert.equal(JSON.parse(requests[0].options.body).model, "fast-one"); + assert.equal(requests[0].options.headers["Authorization"], "Bearer secret"); + } finally { + globalThis.fetch = previousFetch; + if (previousKey === undefined) delete process.env.VOICE_TEST_KEY; + else process.env.VOICE_TEST_KEY = previousKey; + } +}); + +test("explicit endpoint options win over voice-selected provider", async () => { + const previousFetch = globalThis.fetch; + const requests = []; + globalThis.fetch = async (url, options) => { + requests.push({ url, options }); + return createJsonResponse(200, { + choices: [{ message: { content: "ok" } }], + }); + }; + + try { + const provider = { + id: "p1", + env: [], + options: { baseURL: "https://provider.test/v1" }, + }; + const model = { id: "provider-model", api: { url: "https://provider.test/v1" } }; + const client = createClient( + { endpoint: "https://explicit.test/v1", model: "explicit-model", retries: 0 }, + null, + null, + () => ({ provider, model }), + ); + const result = await client.complete({ prompt: "hi" }); + assert.equal(result.text, "ok"); + assert.equal(requests[0].url, "https://explicit.test/v1/chat/completions"); + assert.equal(JSON.parse(requests[0].options.body).model, "explicit-model"); + } finally { + globalThis.fetch = previousFetch; + } +}); + test("omits x-opencode-session header without session", async () => { const previousFetch = globalThis.fetch; const requests = []; diff --git a/test/voice-model.test.js b/test/voice-model.test.js new file mode 100644 index 0000000..cce275e --- /dev/null +++ b/test/voice-model.test.js @@ -0,0 +1,56 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { getVoiceProviderSelection, resolveVoiceProviderModel } from "../lib/voice-model.js"; + +function makeKv(store = {}) { + return { + get: (key, fallback = null) => (key in store ? store[key] : fallback), + set: (key, value) => { + store[key] = value; + }, + }; +} + +const api = { + state: { + provider: [ + { + id: "p1", + name: "Provider One", + env: ["P1_KEY"], + options: {}, + models: { + m1: { id: "m1", name: "Model One", api: { url: "https://p1.test/v1" } }, + }, + }, + ], + }, +}; + +test("reads the voice provider selection from kv", () => { + assert.deepEqual(getVoiceProviderSelection(makeKv({})), null); + assert.deepEqual( + getVoiceProviderSelection(makeKv({ "voice.providerID": "p1", "voice.modelID": "m1" })), + { providerID: "p1", modelID: "m1" }, + ); +}); + +test("resolves the selection against live providers", () => { + const kv = makeKv({ "voice.providerID": "p1", "voice.modelID": "m1" }); + const resolved = resolveVoiceProviderModel(api, kv); + assert.equal(resolved.provider.id, "p1"); + assert.equal(resolved.model.id, "m1"); +}); + +test("returns null for stale selections", () => { + assert.equal( + resolveVoiceProviderModel(api, makeKv({ "voice.providerID": "nope", "voice.modelID": "m1" })), + null, + ); + assert.equal( + resolveVoiceProviderModel(api, makeKv({ "voice.providerID": "p1", "voice.modelID": "nope" })), + null, + ); + assert.equal(resolveVoiceProviderModel(api, makeKv({})), null); +}); From 9be1ecb38345cd73dbf499c3baf764da1ee622f3 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Wed, 23 Sep 2026 17:36:32 +0700 Subject: [PATCH 019/205] fix(tts): single-voice-per-utterance language detection, streaming replies - Root cause of the vi/en voice inversion: detectLang flipped the whole reply to vi on ANY diacritic character present, so one stray Vietnamese word in an English reply (or a Vietnamese reply with normalized-away diacritics) misrouted the entire utterance. Replaced with a majority-vote-over-words heuristic (>=15% of words carry diacritics), exported + tested. - Tried per-word mixed-language segmentation (splicing separate WAV clips per run) first; reverted - splicing sounds jarring (clicks/gaps on every language switch). Kept the fast single-process raw-streaming speak() path, one voice decided per call. - Conversation mode: assistant reply text now streams from message.part.delta while waiting, spoken sentence-by-sentence through a serial speak() queue (local markdown cleanup, no LLM) so the answer starts before the agent turn finishes. Falls back to the full LLM-narrated speak when nothing streamable arrives (e.g. tool-only turns). tts-stop mid-stream exits the mode instead of leaving a half-heard reply. --- README.md | 28 +++- lib/conversation.js | 131 +++++++++++++++++- lib/tts.js | 273 ++++++++++++++++++++++++++------------ test/conversation.test.js | 58 +++++++- test/tts.test.js | 61 +++++++++ 5 files changed, 460 insertions(+), 91 deletions(-) create mode 100644 test/tts.test.js diff --git a/README.md b/README.md index f830e9b..29a8e6f 100644 --- a/README.md +++ b/README.md @@ -216,7 +216,8 @@ pip install piper-tts The plugin looks for `piper` on your `PATH` (`~/.local/bin` is typically on `PATH`). -Download a voice model to `~/.local/share/piper-voices/`: +Download voice models to `~/.local/share/piper-voices/` (English + Vietnamese +for mixed-language replies): ```bash mkdir -p ~/.local/share/piper-voices @@ -224,8 +225,24 @@ curl -L -o ~/.local/share/piper-voices/en_US-ryan-high.onnx \ https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_US/ryan/high/en_US-ryan-high.onnx curl -L -o ~/.local/share/piper-voices/en_US-ryan-high.onnx.json \ https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_US/ryan/high/en_US-ryan-high.onnx.json +curl -L -o ~/.local/share/piper-voices/vi_VN-vais1000-medium.onnx \ + https://huggingface.co/rhasspy/piper-voices/resolve/main/vi/vi_VN/vais1000/medium/vi_VN-vais1000-medium.onnx +curl -L -o ~/.local/share/piper-voices/vi_VN-vais1000-medium.onnx.json \ + https://huggingface.co/rhasspy/piper-voices/resolve/main/vi/vi_VN/vais1000/medium/vi_VN-vais1000-medium.onnx.json ``` +### Vietnamese/English voice selection + +Each call to speak (one full reply, or one sentence during conversation +streaming) picks a single voice for the whole thing - no mid-utterance +switching, since splicing separately synthesized clips sounds jarring. +The language is decided by majority vote over words: text is routed to the +Vietnamese voice only when a meaningful share of its words carry Vietnamese +diacritics, so a single stray Vietnamese word (e.g. a name) in an otherwise +English reply no longer flips the whole thing to the Vietnamese voice, and +vice versa. Toneless Vietnamese (no diacritics) still reads as English - +that is not distinguishable from English by this heuristic. + ### LLM endpoint An OpenAI-compatible LLM endpoint is required for text normalization. For @@ -419,6 +436,15 @@ exits from anywhere. While the mode is on, the plain `/stt-record` keys act as the conversation key and auto TTS stays silent (the loop speaks the reply itself). +While waiting, assistant text is spoken sentence by sentence as it streams in +(local cleanup, no LLM), so the answer starts before the agent turn finishes. +Code-like sentences are skipped; replies with nothing streamable fall back to +the full narrated speak. Pressing the key mid-stream exits the mode. + +- `ttsNormalizeMode` _(optional)_ - `"llm"` (default, polished narration) or + `"local"` (instant deterministic cleanup, no network). Streaming speech + always uses the local path. + Options: `conversationMaxTurns` (default `50`), `conversationTimeoutMs` (default `300000`), `conversationRestartDelayMs` (default `350`), `conversationStopPhrases` (custom stop-phrase list). Keybind override: diff --git a/lib/conversation.js b/lib/conversation.js index 4a87e0c..373ca0a 100644 --- a/lib/conversation.js +++ b/lib/conversation.js @@ -13,8 +13,14 @@ // Saying a stop phrase ("stop", "dừng lại", ...) ends the mode without // submitting. Empty or failed turns pause instead of auto-recording, so the // key never surprises. +// +// Latency: while waiting, assistant text deltas are spoken sentence by +// sentence (local cleanup, no LLM), so the answer starts before the turn +// completes. Replies with nothing streamable fall back to the full +// LLM-narrated speak. import { clearProcessingToast, showProcessingToast } from "./stt.js"; +import { isSpeakableSentence, localSpeechCleanup, splitSpokenSentences } from "./tts.js"; export const DEFAULT_STOP_PHRASES = [ "stop", @@ -86,6 +92,25 @@ export function registerConversation(api, opts, logger, { stt, tts }) { let active = false; let phase = "idle"; // idle | recording | processing | waiting | speaking | paused + + // Reply streaming state: text deltas heard while the agent works are spoken + // sentence by sentence through a serial queue, so the answer starts before + // the turn completes and every sentence gets its own vi/en voice. + + let streamBuffer = ""; + let streamSpokenChars = 0; + let streamUnsubs = []; + let speakTail = Promise.resolve(); + let speakGen = 0; + + function queueSpeak(sentence) { + const g = speakGen; + speakTail = speakTail.then(() => { + if (g !== speakGen || !active || phase !== "waiting") return null; + return tts.speak(sentence); + }); + return speakTail; + } let turn = 0; let consecErrors = 0; let generation = 0; @@ -122,6 +147,25 @@ export function registerConversation(api, opts, logger, { stt, tts }) { } } + function endReplyStream() { + for (const unsub of streamUnsubs) { + try { + unsub(); + } catch {} + } + streamUnsubs = []; + } + + // Kill streamed audio without touching the loop state. Queued sentences + // are invalidated so they never resume after a stop. The caller decides + // what happens next (legacy speak, notification, or exit). + + function discardStreamAudio() { + endReplyStream(); + speakGen += 1; + tts.stop(); + } + function stop(reason) { if (!active) return; active = false; @@ -131,6 +175,8 @@ export function registerConversation(api, opts, logger, { stt, tts }) { waitCancel("stopped"); waitCancel = null; } + endReplyStream(); + speakGen += 1; stt.setStopHint(null); if (stt.isRecording() || stt.isProcessing()) stt.cancel(); clearProcessingToast(); @@ -139,6 +185,47 @@ export function registerConversation(api, opts, logger, { stt, tts }) { logger?.log("VOICE", `Conversation stopped reason=${reason}`, "debug"); } + function startReplyStream(sessionID, turnStart) { + streamBuffer = ""; + streamSpokenChars = 0; + const unsub = api.event.on("message.part.delta", (event) => { + try { + if (!active || phase !== "waiting") return; + const props = event.properties || {}; + if (sessionID && props.sessionID && props.sessionID !== sessionID) return; + if (typeof props.delta !== "string" || !props.delta) return; + if (props.field && props.field !== "text") return; + const lookupID = props.sessionID || sessionID; + const messages = api?.state?.session?.messages?.(lookupID) || []; + const msg = messages.find((m) => m?.id === props.messageID); + if (!msg || msg.role !== "assistant") return; + if ((msg.time?.created || 0) < turnStart) return; + const parts = api?.state?.part?.(props.messageID) || []; + const part = parts.find((p) => p?.id === props.partID); + if (part && part.type !== "text") return; + streamBuffer += props.delta; + flushStream(false); + } catch {} + }); + streamUnsubs.push(unsub); + } + + function flushStream(final = false) { + const { sentences, rest } = splitSpokenSentences(streamBuffer); + const ready = final && rest.trim() ? [...sentences, rest] : sentences; + if (ready.length > 0 && streamSpokenChars === 0) { + showProcessingToast("Speaking..."); + } + for (const sentence of ready) { + if (!isSpeakableSentence(sentence)) continue; + const cleaned = localSpeechCleanup(sentence); + if (!cleaned) continue; + queueSpeak(cleaned); + streamSpokenChars += cleaned.length; + } + streamBuffer = final ? "" : rest; + } + // Wait for the submitted turn to finish: idle, a permission/question gate, // or timeout. Resolves early when stop() cancels the wait. @@ -236,16 +323,28 @@ export function registerConversation(api, opts, logger, { stt, tts }) { phase = "waiting"; const sessionID = currentSessionID(); + const turnStart = Date.now(); showProcessingToast("Waiting for reply..."); + startReplyStream(sessionID, turnStart); + const tWait = Date.now(); const outcome = await waitForReply(sessionID); + const waitMs = Date.now() - tWait; + endReplyStream(); + logger?.log( + "VOICE", + `Conversation wait outcome=${outcome} waitMs=${waitMs} streamedChars=${streamSpokenChars}`, + "debug", + ); if (!active || myGen !== generation) return; if (outcome === "timeout") { + discardStreamAudio(); stop("timeout"); toast("No reply in time, conversation off", "warning"); return; } if (outcome === "permission" || outcome === "question") { + discardStreamAudio(); phase = "speaking"; showProcessingToast("Speaking..."); await tts.speak( @@ -260,6 +359,22 @@ export function registerConversation(api, opts, logger, { stt, tts }) { } if (outcome === "stopped") return; + // Streamed path: sentences already queued; flush the tail and let the + // audio finish before listening again. Fall back to the full + // LLM-narrated speak only when nothing streamable arrived. + + if (streamSpokenChars > 0) { + phase = "speaking"; + flushStream(true); + await speakTail; + clearProcessingToast(); + if (!active || myGen !== generation || phase !== "speaking") return; + await delay(restartDelayMs); + if (!active || myGen !== generation || phase !== "speaking") return; + beginTurn(); + return; + } + phase = "speaking"; const spoken = await tts.speakAssistantTurn(); if (!active || myGen !== generation || phase !== "speaking") return; @@ -294,9 +409,19 @@ export function registerConversation(api, opts, logger, { stt, tts }) { // keypress was consumed (speech paused), so TTS skips its own handling. function onTtsStop() { - if (!active || phase !== "speaking") return false; - pauseSpeech(); - return true; + if (!active) return false; + if (phase === "speaking") { + pauseSpeech(); + return true; + } + // Mid-stream the agent is still working and cannot pause, so the stop key + // exits the mode instead of leaving a half-heard reply behind. + if (phase === "waiting" && tts.isSpeaking?.()) { + stop("cancelled"); + toast("Conversation off"); + return true; + } + return false; } function onKey(source) { diff --git a/lib/tts.js b/lib/tts.js index c650906..7fe9d79 100644 --- a/lib/tts.js +++ b/lib/tts.js @@ -23,6 +23,94 @@ const PIPER_RATE = 22050; const PIPER_BITS = 16; const PIPER_CHANNELS = 1; +// ---- Local (no-LLM) speech cleanup ---- +// Deterministic markdown -> spoken-text transform. Zero network latency, so it +// backs streaming speech and ttsNormalizeMode "local". Less polished than the +// LLM narrator (no summarization), but instant. + +function splitIdentifier(token) { + return token + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2") + .replace(/[_-]+/g, " "); +} + +export function localSpeechCleanup(text) { + if (!text) return ""; + let out = text; + out = out.replace(/```[\s\S]*?```/g, " code snippet "); + out = out.replace(/`([^`]+)`/g, (_, code) => ` ${splitIdentifier(code)} `); + out = out.replace(/!\[([^\]]*)\]\([^)]+\)/g, "$1"); + out = out.replace(/\[([^\]]+)\]\(([^)]+)\)/g, "$1"); + out = out.replace(/<[^>]+>/g, " "); + out = out.replace(/^#{1,6}\s+/gm, ""); + out = out.replace(/^[>\s]*[-*+]\s+/gm, ""); + out = out.replace(/(\*\*|__)(.*?)\1/g, "$2"); + out = out.replace(/(^|\W)\*([^*\n]+)\*(?=\W|$)/g, "$1$2"); + out = out + .split(/(\s+)/) + .map((tok) => { + if (/^\s+$/.test(tok) || !tok) return tok; + if (/^https?:\/\//i.test(tok)) { + const domain = tok.replace(/^https?:\/\/([^/]+).*$/i, "$1"); + return domain.replace(/\./g, " dot "); + } + const base = tok.includes("/") ? tok.slice(tok.lastIndexOf("/") + 1) : tok; + if (/^\w[\w.-]*\.[a-z0-9]{1,4}$/i.test(base)) { + const dot = base.lastIndexOf("."); + return `${splitIdentifier(base.slice(0, dot))} dot ${base.slice(dot + 1)}`; + } + return splitIdentifier(tok); + }) + .join(""); + return out.replace(/\s+/g, " ").trim(); +} + +// Split streamed text into complete spoken sentences. Returns what is ready +// plus the trailing incomplete fragment to keep buffering. Sentences that +// look like code dumps (overlong, backticks) are skipped by the caller. + +export function splitSpokenSentences(text) { + const flat = (text || "").replace(/\s+/g, " "); + const parts = flat.split(/(?<=[.!?…])\s+/); + if (parts.length === 0) return { sentences: [], rest: "" }; + const lastComplete = /[.!?…]\s*$/.test(flat); + if (lastComplete) return { sentences: parts.filter(Boolean), rest: "" }; + const rest = parts.pop() || ""; + return { sentences: parts.filter(Boolean), rest }; +} + +export function isSpeakableSentence(sentence) { + const s = (sentence || "").trim(); + if (!s || s.length > 400 || s.includes("`")) return false; + return true; +} + +// Decide ONE language for the whole call (utterance or, during streaming, +// one completed sentence) and speak all of it with that single voice - no +// mid-utterance voice switching, since splicing separately synthesized clips +// sounds jarring (clicks/gaps between voices). +// +// Root-cause fix: the old rule was "any Vietnamese diacritic anywhere in the +// text -> vi voice". A single stray diacritic word in an English-dominant +// reply (e.g. a name) flipped the ENTIRE text to the Vietnamese voice, which +// then mispronounced every English word - and conversely, if the diacritics +// got normalized away, a Vietnamese reply flipped to the English voice. That +// is the "speaks Vietnamese with English (voice) and English with Vietnamese +// (voice)" bug. Fix: majority vote over words - only route to "vi" when a +// meaningful share of words actually carry Vietnamese diacritics, so one +// stray word can no longer flip the whole utterance. + +const VI_LANG_WORD_THRESHOLD = 0.15; + +export function detectLang(text) { + if (!text) return "en"; + const words = text.split(/\s+/).filter(Boolean); + if (words.length === 0) return "en"; + const viWords = words.filter((w) => VI_REGEX.test(w)).length; + return viWords / words.length >= VI_LANG_WORD_THRESHOLD ? "vi" : "en"; +} + // ---- Conversation-mode hooks (wired by index.js) ---- // While voice conversation owns speaking, the TTS stop key pauses the loop // instead of just silencing (which would auto-record again). @@ -142,12 +230,6 @@ export function registerTTS(api, kv, complete, prompts, opts, logger, deps = {}) api.ui.toast({ message, variant, duration: 3000 }); } - function detectLang(text) { - if (!text) return "en"; - if (VI_REGEX.test(text)) return "vi"; - return "en"; - } - function getVoiceModel(text) { const lang = detectLang(text); if (lang === "vi") { @@ -215,97 +297,110 @@ export function registerTTS(api, kv, complete, prompts, opts, logger, deps = {}) } } - function speak(text) { - if (!text) return Promise.resolve(); - const line = text.replace(/\n/g, " ").trim(); - if (!line) return Promise.resolve(); + // Spawn piper -> play and wire them. Resolves onDone when playback ends. + + function spawnPlayback(voiceModel, onDone) { + let piperStderr = ""; + let playStderr = ""; + const rate = getVoiceRate(voiceModel); + playProc = spawn( + "play", + [ + "-t", + "raw", + "-r", + String(rate), + "-e", + "signed", + "-b", + String(PIPER_BITS), + "-c", + String(PIPER_CHANNELS), + "-q", + "-", + ], + { stdio: ["pipe", "ignore", "pipe"] }, + ); - killProcs(); + piperProc = spawn("piper", ["-m", voiceModel, "--output_raw"], { + stdio: ["pipe", "pipe", "pipe"], + }); + + piperProc.stderr.on("data", (chunk) => { + piperStderr += chunk.toString(); + }); + playProc.stderr.on("data", (chunk) => { + playStderr += chunk.toString(); + }); + + piperProc.stdout.on("data", (chunk) => { + if (playProc?.stdin && !playProc.stdin.destroyed) { + playProc.stdin.write(chunk); + } + }); + + piperProc.on("close", (code) => { + if (code !== 0 && code !== null) { + logger?.log?.("TTS", `piper exited code=${code} stderr=${piperStderr.trim()}`, "error"); + } + if (playProc?.stdin && !playProc.stdin.destroyed) { + playProc.stdin.end(); + } + }); + + playProc.on("close", (code) => { + if (code !== 0 && code !== null) { + logger?.log?.("TTS", `play exited code=${code} stderr=${playStderr.trim()}`, "error"); + } else { + logger?.log?.("TTS", "playback finished", "debug"); + } + piperProc = null; + playProc = null; + onDone(); + }); + piperProc.on("error", (err) => { + logger?.log?.("TTS", `piper error: ${err.message}`, "error"); + killProcs(); + onDone(); + }); + playProc.on("error", (err) => { + logger?.log?.("TTS", `play error: ${err.message}`, "error"); + killProcs(); + onDone(); + }); + } + + function resolveVoiceOrWarn(line) { const voiceModel = getVoiceModel(line); - logger?.log?.("TTS", `Speak requested chars=${line.length} voice=${voiceModel}`, "debug"); if (!piperOnPath()) { logger?.log?.("TTS", `Piper binary not found on PATH`, "warn"); toast(`Piper binary not found on PATH`, "warning"); - return Promise.resolve(); + return null; } if (!fs.existsSync(voiceModel)) { logger?.log?.("TTS", `Voice model not found: ${voiceModel}`, "warn"); toast(`Voice model not found: ${voiceModel}`, "warning"); - return Promise.resolve(); + return null; } + return voiceModel; + } - return new Promise((resolve) => { - let piperStderr = ""; - let playStderr = ""; - const rate = getVoiceRate(voiceModel); - playProc = spawn( - "play", - [ - "-t", - "raw", - "-r", - String(rate), - "-e", - "signed", - "-b", - String(PIPER_BITS), - "-c", - String(PIPER_CHANNELS), - "-q", - "-", - ], - { stdio: ["pipe", "ignore", "pipe"] }, - ); - - piperProc = spawn("piper", ["-m", voiceModel, "--output_raw"], { - stdio: ["pipe", "pipe", "pipe"], - }); - - piperProc.stderr.on("data", (chunk) => { - piperStderr += chunk.toString(); - }); - playProc.stderr.on("data", (chunk) => { - playStderr += chunk.toString(); - }); - - piperProc.stdout.on("data", (chunk) => { - if (playProc?.stdin && !playProc.stdin.destroyed) { - playProc.stdin.write(chunk); - } - }); + function speak(text) { + if (!text) return Promise.resolve(); + const line = text.replace(/\n/g, " ").trim(); + if (!line) return Promise.resolve(); - piperProc.on("close", (code) => { - if (code !== 0 && code !== null) { - logger?.log?.("TTS", `piper exited code=${code} stderr=${piperStderr.trim()}`, "error"); - } - if (playProc?.stdin && !playProc.stdin.destroyed) { - playProc.stdin.end(); - } - }); + killProcs(); - playProc.on("close", (code) => { - if (code !== 0 && code !== null) { - logger?.log?.("TTS", `play exited code=${code} stderr=${playStderr.trim()}`, "error"); - } else { - logger?.log?.("TTS", "playback finished", "debug"); - } - piperProc = null; - playProc = null; - resolve(); - }); - - piperProc.on("error", (err) => { - logger?.log?.("TTS", `piper error: ${err.message}`, "error"); - killProcs(); - resolve(); - }); - playProc.on("error", (err) => { - logger?.log?.("TTS", `play error: ${err.message}`, "error"); - killProcs(); - resolve(); - }); + // One voice for the whole call (see detectLang) - no mid-utterance + // switching. + const voiceModel = resolveVoiceOrWarn(line); + if (!voiceModel) return Promise.resolve(); + logger?.log?.("TTS", `Speak requested chars=${line.length} voice=${voiceModel}`, "debug"); + return new Promise((resolve) => { + spawnPlayback(voiceModel, resolve); if (piperProc?.stdin && !piperProc.stdin.destroyed) { piperProc.stdin.write(line + "\n"); piperProc.stdin.end(); @@ -359,7 +454,7 @@ export function registerTTS(api, kv, complete, prompts, opts, logger, deps = {}) lastSpokenMessageID = result.lastMessageID; showProcessingToast("Normalizing response..."); - const llmResult = await normalizeForSpeech(result.text, systemAuto); + const llmResult = await normalizeOrLocal(result.text, systemAuto, 4096); if (!llmResult.text) { clearProcessingToast(); logger?.log?.("TTS", `Auto normalization failed: ${llmResult.error}`, "warn"); @@ -398,7 +493,7 @@ export function registerTTS(api, kv, complete, prompts, opts, logger, deps = {}) } showProcessingToast("Normalizing response..."); - const llmResult = await normalizeForSpeech(result.text, systemManual); + const llmResult = await normalizeOrLocal(result.text, systemManual, 4096); if (!llmResult.text) { clearProcessingToast(); logger?.log?.("TTS", `Manual normalization failed: ${llmResult.error}`, "warn"); @@ -416,6 +511,14 @@ export function registerTTS(api, kv, complete, prompts, opts, logger, deps = {}) // auto (narrate/summarize) prompt and no session prefix - the loop already // announces its own state via toasts. + // ttsNormalizeMode "local" skips the LLM entirely (instant, less polished). + const ttsLocal = opts?.ttsNormalizeMode === "local"; + + async function normalizeOrLocal(text, systemPrompt, maxTokens) { + if (ttsLocal) return { text: localSpeechCleanup(text) }; + return normalizeForSpeech(text, systemPrompt, maxTokens); + } + async function speakAssistantTurn() { const tFetch = Date.now(); const result = await getTurnAssistantText(client, api); @@ -429,7 +532,7 @@ export function registerTTS(api, kv, complete, prompts, opts, logger, deps = {}) const tNormalize = Date.now(); // Auto replies are narrated/summarized, so a tight cap is safe here (the // manual read-aloud keeps the full 4096). - const llmResult = await normalizeForSpeech(result.text, systemAuto, 2048); + const llmResult = await normalizeOrLocal(result.text, systemAuto, 2048); const normalizeMs = Date.now() - tNormalize; if (!llmResult.text) { clearProcessingToast(); diff --git a/test/conversation.test.js b/test/conversation.test.js index fe56b51..61fad31 100644 --- a/test/conversation.test.js +++ b/test/conversation.test.js @@ -53,6 +53,7 @@ const tick = (ms = 10) => new Promise((r) => setTimeout(r, ms)); function makeHarness({ transcribe = { text: "hello" } } = {}) { const toasts = []; const handlers = {}; + const stateData = { messages: [], parts: {} }; const api = { ui: { toast: (input) => toasts.push(input?.message ?? input) }, route: { current: { name: "session", params: { sessionID: "s1" } } }, @@ -62,9 +63,20 @@ function makeHarness({ transcribe = { text: "hello" } } = {}) { return () => {}; }, }, + state: { + session: { messages: () => stateData.messages }, + part: (messageID) => stateData.parts[messageID] || [], + }, lifecycle: {}, }; - const calls = { sttStart: 0, ttsStop: 0, speakTurn: 0, submitted: [] }; + const calls = { + sttStart: 0, + ttsStop: 0, + speakTurn: 0, + speakFull: 0, + speakCalls: [], + submitted: [], + }; let speakGate = null; const stt = { isRecording: () => false, @@ -86,9 +98,12 @@ function makeHarness({ transcribe = { text: "hello" } } = {}) { }, }; const tts = { - speak: async () => {}, + speak: async (text) => { + calls.speakCalls.push(text); + }, speakAssistantTurn: async () => { calls.speakTurn += 1; + calls.speakFull += 1; if (speakGate) await speakGate; return { spoken: true }; }, @@ -110,6 +125,7 @@ function makeHarness({ transcribe = { text: "hello" } } = {}) { toasts, handlers, calls, + stateData, controller, setSpeakGate: (p) => { speakGate = p; @@ -197,6 +213,44 @@ test("exit during processing cancels the turn", async () => { assert.deepEqual(h.calls.submitted, []); }); +test("streams reply deltas while waiting, skips full speak", async () => { + const h = makeHarness(); + h.controller.onKey("toggle"); + h.controller.onKey("toggle"); + await tick(30); + h.stateData.messages.push({ id: "a1", role: "assistant", time: { created: Date.now() } }); + h.stateData.parts["a1"] = [ + { id: "p1", type: "text", text: "" }, + { id: "p2", type: "reasoning", text: "" }, + ]; + const delta = (partID, text) => ({ + properties: { sessionID: "s1", messageID: "a1", partID, field: "text", delta: text }, + }); + for (const handler of h.handlers["message.part.delta"] || []) { + handler(delta("p1", "Hello world. How are ")); + handler(delta("p2", "secret thinking")); + handler(delta("p1", "you?")); + } + await tick(20); + assert.deepEqual(h.calls.speakCalls, ["Hello world.", "How are you?"]); + fireIdle(h.handlers); + await tick(30); + assert.equal(h.calls.speakFull, 0); + assert.equal(h.calls.sttStart, 2); +}); + +test("falls back to full speak when nothing streamable arrives", async () => { + const h = makeHarness(); + h.controller.onKey("toggle"); + h.controller.onKey("toggle"); + await tick(30); + fireIdle(h.handlers); + await tick(30); + assert.equal(h.calls.speakFull, 1); + assert.equal(h.calls.sttStart, 2); + h.controller.stop("test"); +}); + test("tts stop key pauses speaking, ignored when inactive", async () => { const h = makeHarness(); assert.equal(h.controller.onTtsStop(), false); diff --git a/test/tts.test.js b/test/tts.test.js new file mode 100644 index 0000000..305a5e7 --- /dev/null +++ b/test/tts.test.js @@ -0,0 +1,61 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + detectLang, + isSpeakableSentence, + localSpeechCleanup, + splitSpokenSentences, +} from "../lib/tts.js"; + +test("cleans markdown for speech", () => { + assert.equal(localSpeechCleanup("Hello **world**!"), "Hello world!"); + assert.equal( + localSpeechCleanup("See parseConfig in src/utils/helpers.ts"), + "See parse Config in helpers dot ts", + ); + assert.equal(localSpeechCleanup("Run `npm test` now"), "Run npm test now"); + assert.equal(localSpeechCleanup("```js\nconst x = 1;\n```\nDone."), "code snippet Done."); + assert.equal( + localSpeechCleanup("Details at https://example.com/docs?q=1"), + "Details at example dot com", + ); +}); + +test("splits streamed text into complete sentences", () => { + assert.deepEqual(splitSpokenSentences("Hello world. How are"), { + sentences: ["Hello world."], + rest: "How are", + }); + assert.deepEqual(splitSpokenSentences("Done. Next."), { + sentences: ["Done.", "Next."], + rest: "", + }); + assert.deepEqual(splitSpokenSentences("Partial no punctuation"), { + sentences: [], + rest: "Partial no punctuation", + }); + assert.deepEqual(splitSpokenSentences(""), { sentences: [], rest: "" }); +}); + +test("decides one language for a whole utterance by word majority", () => { + // Vietnamese-dominant instruction with English tech loanwords -> vi voice + // reads the whole thing (was the original mixed-voice request). + assert.equal(detectLang("Tìm symbol, search text, đọc file cụ thể"), "vi"); + // Pure English. + assert.equal(detectLang("Run the build and check logs"), "en"); + // A single stray Vietnamese word must NOT flip an English-dominant reply - + // this was the root cause of "speaks English with the Vietnamese voice". + assert.equal(detectLang("Please check with Nguyễn about the API before you deploy it"), "en"); + // Pure Vietnamese greeting. + assert.equal(detectLang("Xin chào, bạn khỏe không?"), "vi"); + assert.equal(detectLang(""), "en"); + assert.equal(detectLang(null), "en"); +}); + +test("skips code-like sentences", () => { + assert.equal(isSpeakableSentence("Hello there."), true); + assert.equal(isSpeakableSentence("Use `npm test`."), false); + assert.equal(isSpeakableSentence(`x${"y".repeat(500)}`), false); + assert.equal(isSpeakableSentence(""), false); +}); From a9c6bb7df002a5b2a74834743451b14f43895a5b Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Thu, 24 Sep 2026 02:46:51 +0700 Subject: [PATCH 020/205] feat(stt): interpretive normalization by default, strict opt-out - Normalize now returns what the user meant: fixes acoustically-close mishearings (they face -> database, bait -> page) when similar-sounding + context/domain-supported + clearly more sensible, instead of transcribing exactly. - New WORKFLOW VOCABULARY glossary (Notion page/database, master, commit) next to coding homophones. - Guardrails kept: length within ~30%, no new facts/answers, blow-up detector, raw fallback, 15s timeout. - sttNormalizeMode strict restores old behavior; custom sttPrompt file still wins. --- README.md | 1 + lib/stt.js | 85 ++++++++++++++++++++++++++++++++++++++++++++++-- test/stt.test.js | 18 ++++++++++ 3 files changed, 102 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 29a8e6f..06ba2b7 100644 --- a/README.md +++ b/README.md @@ -368,6 +368,7 @@ up or how responses are spoken. - `sttContextMessages` _(optional)_ - recent turns sent as knowledge with STT normalization (default `8`) - `sttContextChars` _(optional)_ - max chars of that context (default `3000`, tail kept) - `sttNormalizeTimeoutMs` _(optional)_ - worst-case budget per normalize call, raw transcript used on timeout (default `15000`) +- `sttNormalizeMode` _(optional)_ - `"interpretive"` (default: fix misheard words like "they face" → "database" using conversation context + workflow vocabulary) or `"strict"` (transcribe exactly, old behavior). A custom `sttPrompt` file overrides both. - `sttAutoSubmit` _(optional)_ - one-shot `/stt-record` submits immediately instead of appending for edit (default `false`; conversation mode always submits) - `sttPrompt` _(optional)_ - system prompt for cleaning up whisper transcriptions - `ttsAutoPrompt` _(optional)_ - system prompt for auto-speaking assistant responses diff --git a/lib/stt.js b/lib/stt.js index 2dff74b..f1bd663 100644 --- a/lib/stt.js +++ b/lib/stt.js @@ -57,6 +57,8 @@ let sttDefaultLanguage = DEFAULT_LANGUAGE; // Bounds for the recent-turns knowledge block sent with normalization. let sttContextMessages = 8; let sttContextChars = 3000; +// interpretive (default): fix misheard words using context; strict: transcribe exactly. +let sttNormalizeMode = "interpretive"; // Worst-case budget for one normalize call; on timeout the raw transcript is // used so a stalled LLM never blocks the turn. let sttNormalizeTimeoutMs = 15000; @@ -801,7 +803,76 @@ function transcribe(kv, logger) { }); } -const STT_SYSTEM_PROMPT = `You are a DETERMINISTIC speech-to-text normalizer for a coding assistant CLI. You are NOT a chatbot. You NEVER answer, explain, greet back, or introduce yourself. +export const STT_SYSTEM_PROMPT = `You are a DETERMINISTIC speech-to-text normalizer for a coding assistant CLI. You are NOT a chatbot. You NEVER answer, explain, greet back, or introduce yourself. + +Task: Return ONLY what the user meant to say, cleaned up for use as their message. Fix what the speech recognizer misheard, not just punctuation. No reply. No extra sentences. + +Strict rules: +- Output is the user's utterance, cleaned. It is NOT a response to the user. +- Fix punctuation, capitalization, grammar. +- Remove filler words (um, uh, like, you know, etc.). +- Keep technical terms, file names, and code references exact. +- If the user is dictating code, format it appropriately. +- INTERPRET misheard words: speech recognition often produces acoustically-close-but-wrong words ("they face" for "database", "bait" for "page"). Replace a word or short phrase ONLY when ALL of these hold: (1) it sounds similar to the replacement, (2) the conversation context or the domain lists below support the replacement, (3) the sentence makes clearly more sense with it. Otherwise leave the original words untouched. +- Use the conversation context to resolve ambiguous names, pronouns, references, AND misheard content words (that function, the file, it; e.g. Cristina uses he/him if the conversation says so) - never copy unrelated facts from the context into the output. +- Output ONLY the cleaned text, nothing else. No quotes, no prefixes, no suffixes. +- Do NOT add greetings, introductions, offers to help, questions, or commentary. +- Do NOT expand short inputs. Keep output length close to input length (within ~30%); do not add paragraphs or new requests the user did not make. +- If input is a short greeting/noise like "hey", "hello", "hi", "hey there", output exactly that greeting capitalized with a period (e.g., "hey" -> "Hey.") — DO NOT expand to "Hello! I am an AI..." or add self-introduction. + +Examples (follow exactly): +Input: "hey" +Output: Hey. + +Input: "hello there" +Output: Hello there. + +Input: "umm add tests for the a sink user service" +Output: Add tests for the async user service. + +Input: "check the locks for the doc container" +Output: Check the logs for the Docker container. + +Input: "craft a notion bait tracking our work items" +Output: Craft a Notion page tracking our work items. + +Input: "check the notion they face for the next phase target" +Output: Check the Notion database for the next phase target. + +If you cannot normalize, return the input trimmed. + +CRITICAL DOMAIN CORRECTIONS - Fix common STT homophone errors in software engineering contexts: +- "locks" -> "logs" (unless explicitly talking about mutexes/concurrency) +- "note" / "no" -> "node" +- "app and" -> "append" +- "sink" -> "sync" +- "a sink" -> "async" +- "doc" / "talker" -> "docker" +- "cash" -> "cache" +- "rap" -> "wrap" +- "Jason" -> "JSON" +- "get" -> "Git" +- "react" -> "React" +- "types creep" / "type script" -> "TypeScript" +- "bite" -> "byte" +- "string" -> "String" +- "int" -> "Int" +- "bullion" -> "boolean" + +WORKFLOW VOCABULARY - the user works with these tools; prefer these terms when the transcript sounds similar: +- "bait" / "paid" -> "page" (in Notion contexts) +- "they face" / "data base" -> "database" +- "phase target" - keep as-is (not "face target") +- "master" - keep as-is (git branch, not "muster") +- "commit" - keep as-is (not "comet") +- "notion" - keep as-is (not "motion" / "ocean") + +Rely heavily on context to fix words that sound similar to programming terminology.`; + +// Strict mode: the old transcribe-exactly behavior (no reinterpretation). +// Opt in via "sttNormalizeMode": "strict". + +export const STT_SYSTEM_PROMPT_STRICT = `You are a DETERMINISTIC speech-to-text normalizer for a coding assistant CLI. You are NOT a chatbot. You NEVER answer, explain, greet back, or introduce yourself. Task: Return ONLY the cleaned version of the user's spoken words — exactly what they said, with punctuation and homophone fixes. No reply. No extra sentences. @@ -852,6 +923,11 @@ CRITICAL DOMAIN CORRECTIONS - Fix common STT homophone errors in software engine Rely heavily on context to fix words that sound similar to programming terminology.`; +export function selectSttSystemPrompt(mode, custom) { + if (custom) return custom; + return mode === "strict" ? STT_SYSTEM_PROMPT_STRICT : STT_SYSTEM_PROMPT; +} + const STT_HALLUCINATION_PATTERNS = [ /I am (an )?AI/i, /as an AI/i, @@ -1215,7 +1291,7 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) } const client = api.client; const renderer = opts?.focusMode === "primary" ? null : api.renderer; - const systemPrompt = prompts?.stt || STT_SYSTEM_PROMPT; + const systemPrompt = selectSttSystemPrompt(sttNormalizeMode, prompts?.stt); const backend = detectAudioBackend(); logger?.log("STT", `Audio backend=${backend}`, "debug"); function toast(message, variant = "info") { @@ -1245,6 +1321,11 @@ export function registerSTT(api, kv, complete, prompts, opts, logger, deps = {}) } logger?.log("STT", `Default language=${sttDefaultLanguage}`, "debug"); + if (opts?.sttNormalizeMode === "strict") { + sttNormalizeMode = "strict"; + } + logger?.log("STT", `Normalize mode=${sttNormalizeMode}`, "debug"); + if (Number(opts?.sttContextMessages) > 0) { sttContextMessages = Math.floor(Number(opts.sttContextMessages)); } diff --git a/test/stt.test.js b/test/stt.test.js index 5a7cc90..00476d3 100644 --- a/test/stt.test.js +++ b/test/stt.test.js @@ -4,6 +4,8 @@ import test from "node:test"; import { __clearProcessingToastState, __setProcessingToastFn, + STT_SYSTEM_PROMPT, + STT_SYSTEM_PROMPT_STRICT, buildAudioHint, buildOpenRouterTranscriptionRequest, buildRecordArgs, @@ -16,10 +18,26 @@ import { needsContext, parsePactlSources, parsePactlSourcesShort, + selectSttSystemPrompt, showProcessingToast, updateProcessingToast, } from "../lib/stt.js"; +test("interpretive prompt reinterprets mishearings, strict does not", () => { + assert.match(STT_SYSTEM_PROMPT, /INTERPRET misheard words/); + assert.match(STT_SYSTEM_PROMPT, /they face/); + assert.match(STT_SYSTEM_PROMPT, /WORKFLOW VOCABULARY/); + assert.doesNotMatch(STT_SYSTEM_PROMPT_STRICT, /INTERPRET misheard words/); + assert.match(STT_SYSTEM_PROMPT_STRICT, /exactly what they said/); +}); + +test("selects normalize prompt by mode, custom file wins", () => { + assert.equal(selectSttSystemPrompt("strict", null), STT_SYSTEM_PROMPT_STRICT); + assert.equal(selectSttSystemPrompt("interpretive", null), STT_SYSTEM_PROMPT); + assert.equal(selectSttSystemPrompt(undefined, null), STT_SYSTEM_PROMPT); + assert.equal(selectSttSystemPrompt("strict", "custom"), "custom"); +}); + test("detects transcripts that need conversation context", () => { assert.equal(needsContext("ask him about it"), true); assert.equal(needsContext("Cristina đi đâu?"), true); From 2b23889b19022d35311f7905df7f20325a64bd41 Mon Sep 17 00:00:00 2001 From: Bojackduy Date: Thu, 24 Sep 2026 12:29:09 +0700 Subject: [PATCH 021/205] feat(live-notes): continuous meeting transcription with voice preprocessing - New: /voice-notes-start|stop|cancel|status - mic stays on, background lane transcribes+normalizes, ordered Markdown + raw JSONL sidecar - lib/audio-chunker.js: silence-aware chunking with forced 20s cut + overlap carry - lib/audio-enhance.js: per-chunk voice-only preprocessing (adaptive gain to target RMS + highpass, limiter on); stats in JSONL - lib/whisper-server.js: persistent whisper-server with whisper-cli fallback - Hallucination filter: VI YouTube-outro patterns, cap 60->140 chars, 3x repetition gate; skipped chunks stay out of Markdown - Chunker learns room noise floor (notesCalibrationMs) or explicit notesSilenceRms - Mutual exclusion: live-notes vs one-shot STT vs conversation vs auto-TTS --- README.md | 90 ++++++ index.js | 13 + lib/audio-chunker.js | 231 ++++++++++++++ lib/audio-enhance.js | 135 +++++++++ lib/conversation.js | 6 +- lib/live-notes.js | 589 ++++++++++++++++++++++++++++++++++++ lib/notes-writer.js | 181 +++++++++++ lib/stt.js | 160 ++++++++-- lib/tts.js | 15 +- lib/whisper-server.js | 158 ++++++++++ test/audio-chunker.test.js | 183 +++++++++++ test/audio-enhance.test.js | 109 +++++++ test/notes-writer.test.js | 239 +++++++++++++++ test/stt.test.js | 87 ++++++ test/whisper-server.test.js | 28 ++ 15 files changed, 2198 insertions(+), 26 deletions(-) create mode 100644 lib/audio-chunker.js create mode 100644 lib/audio-enhance.js create mode 100644 lib/live-notes.js create mode 100644 lib/notes-writer.js create mode 100644 lib/whisper-server.js create mode 100644 test/audio-chunker.test.js create mode 100644 test/audio-enhance.test.js create mode 100644 test/notes-writer.test.js create mode 100644 test/whisper-server.test.js diff --git a/README.md b/README.md index 06ba2b7..6aa8c12 100644 --- a/README.md +++ b/README.md @@ -451,6 +451,96 @@ Options: `conversationMaxTurns` (default `50`), `conversationTimeoutMs` `conversationStopPhrases` (custom stop-phrase list). Keybind override: `"keybinds": { "voice.conversation": "none" }`. +### Live voice notes + +Continuous meeting/lecture transcription: the mic stays on and keeps +recording while a background lane transcribes and cleans up what was already +said, so a 30-minute meeting never blocks on waiting for whisper or the LLM. + +| Command | Description | +| --------------------- | --------------------------------------------------------- | +| `/voice-notes-start` | Start continuous recording with background transcription | +| `/voice-notes-stop` | Stop, flush the last bit of audio, and wait for the save | +| `/voice-notes-cancel` | Stop capturing immediately; finishes saving in background | +| `/voice-notes-status` | Show elapsed time, chunks written/queued, and write lag | + +No default keybind (palette/slash only, to avoid clashing with one-shot STT +or conversation mode - only one of the three can be active at a time). + +Output goes to `voice-notes/-