Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(stt): a dead whisper server heals itself and says so in english

purple24d36800e4f9
diff --git a/public/whisper_server.py b/public/whisper_server.py
index 5f8508aa..6ae16437 100644
--- a/public/whisper_server.py
+++ b/public/whisper_server.py
@@ -17,6 +17,26 @@ import sys
import json
import os
+
+def error_text(e: BaseException) -> str:
+ """One exception, in English.
+
+ An OSError carries the operating system's own sentence in `strerror`, and
+ on a German Windows that sentence is German. This text is not a log line:
+ it travels back to the app in the `error` field and is shown to the user,
+ who set the app to English. So the wording is dropped and the number kept.
+ The number means the same thing in every language and is what anyone
+ searches for. Every other exception's text is Python's own and is already
+ English, so it is passed through untouched.
+ """
+ if isinstance(e, OSError):
+ code = getattr(e, "winerror", None) or e.errno
+ where = " on %s" % e.filename if e.filename else ""
+ if code is None:
+ return "%s%s" % (type(e).__name__, where)
+ return "%s%s (os error %s)" % (type(e).__name__, where, code)
+ return str(e)
+
def main():
# Unbuffered stdout for real-time communication with Node.js
sys.stdout.reconfigure(line_buffering=True)
@@ -35,7 +55,7 @@ def main():
model = WhisperModel("base", device="cpu", compute_type="int8")
print("Model loaded, ready for transcription.", file=sys.stderr, flush=True)
except Exception as e:
- respond({"status": "error", "error": f"Model load failed: {e}"})
+ respond({"status": "error", "error": f"Model load failed: {error_text(e)}"})
sys.exit(1)
# Signal readiness
@@ -69,7 +89,7 @@ def main():
text = " ".join([s.text for s in segments]).strip()
respond({"transcript": text, "language": info.language})
except Exception as e:
- respond({"error": str(e), "transcript": ""})
+ respond({"error": error_text(e), "transcript": ""})
elif action == "quit":
respond({"status": "stopped"})
diff --git a/src-tauri/resources/whisper_server.py b/src-tauri/resources/whisper_server.py
index 5f8508aa..6ae16437 100644
--- a/src-tauri/resources/whisper_server.py
+++ b/src-tauri/resources/whisper_server.py
@@ -17,6 +17,26 @@ import sys
import json
import os
+
+def error_text(e: BaseException) -> str:
+ """One exception, in English.
+
+ An OSError carries the operating system's own sentence in `strerror`, and
+ on a German Windows that sentence is German. This text is not a log line:
+ it travels back to the app in the `error` field and is shown to the user,
+ who set the app to English. So the wording is dropped and the number kept.
+ The number means the same thing in every language and is what anyone
+ searches for. Every other exception's text is Python's own and is already
+ English, so it is passed through untouched.
+ """
+ if isinstance(e, OSError):
+ code = getattr(e, "winerror", None) or e.errno
+ where = " on %s" % e.filename if e.filename else ""
+ if code is None:
+ return "%s%s" % (type(e).__name__, where)
+ return "%s%s (os error %s)" % (type(e).__name__, where, code)
+ return str(e)
+
def main():
# Unbuffered stdout for real-time communication with Node.js
sys.stdout.reconfigure(line_buffering=True)
@@ -35,7 +55,7 @@ def main():
model = WhisperModel("base", device="cpu", compute_type="int8")
print("Model loaded, ready for transcription.", file=sys.stderr, flush=True)
except Exception as e:
- respond({"status": "error", "error": f"Model load failed: {e}"})
+ respond({"status": "error", "error": f"Model load failed: {error_text(e)}"})
sys.exit(1)
# Signal readiness
@@ -69,7 +89,7 @@ def main():
text = " ".join([s.text for s in segments]).strip()
respond({"transcript": text, "language": info.language})
except Exception as e:
- respond({"error": str(e), "transcript": ""})
+ respond({"error": error_text(e), "transcript": ""})
elif action == "quit":
respond({"status": "stopped"})
diff --git a/src-tauri/src/commands/whisper.rs b/src-tauri/src/commands/whisper.rs
index d6f55f0e..73a37357 100644
--- a/src-tauri/src/commands/whisper.rs
+++ b/src-tauri/src/commands/whisper.rs
@@ -35,6 +35,28 @@ fn drain_stale(rx: &mpsc::Receiver<serde_json::Value>) -> usize {
n
}
+/// Does this `send_command` failure mean the server is gone, rather than the
+/// request being bad or merely slow?
+///
+/// Anchored on the prefixes `send_command` writes itself, never on the words
+/// after them: those come from the operating system and are in whatever
+/// language Windows was installed in, so matching on them would work on an
+/// English box and quietly stop working on a German one.
+///
+/// "Whisper transcription timed out" is deliberately NOT in this list. A long
+/// dictation is a living server doing its job, and restarting under it would
+/// throw the take away for nothing.
+pub fn is_pipe_failure(message: &str) -> bool {
+ const GONE: &[&str] = &[
+ "stdin write:",
+ "stdin newline:",
+ "stdin flush:",
+ "No stdin connection",
+ "No response channel",
+ ];
+ GONE.iter().any(|p| message.starts_with(p))
+}
+
impl WhisperServer {
pub fn new() -> Self {
Self {
@@ -167,9 +189,21 @@ impl WhisperServer {
let stdin = self.stdin_tx.as_mut().ok_or("No stdin connection")?;
let json_str = serde_json::to_string(cmd).map_err(|e| e.to_string())?;
- stdin.write_all(json_str.as_bytes()).map_err(|e| format!("stdin write: {}", e))?;
- stdin.write_all(b"\n").map_err(|e| format!("stdin newline: {}", e))?;
- stdin.flush().map_err(|e| format!("stdin flush: {}", e))?;
+ // os_error::english, not the error's own Display. When the python
+ // process dies the write fails with ERROR_NO_DATA, and Windows words
+ // that failure in the language it was installed in: the box showed
+ // "stdin flush: Die Pipe wird gerade geschlossen. (os error 232)" in
+ // the red hint over the microphone, in an app set to English
+ // (B4 Gegenprobe 29.08.). english() never asks the system for words.
+ stdin
+ .write_all(json_str.as_bytes())
+ .map_err(|e| format!("stdin write: {}", os_error::english(&e)))?;
+ stdin
+ .write_all(b"\n")
+ .map_err(|e| format!("stdin newline: {}", os_error::english(&e)))?;
+ stdin
+ .flush()
+ .map_err(|e| format!("stdin flush: {}", os_error::english(&e)))?;
// Wait for response (60s timeout for transcription)
let rx = self.response_rx.as_ref().ok_or("No response channel")?;
@@ -182,6 +216,29 @@ impl WhisperServer {
self.process.is_some()
}
+ /// Has the child gone away?
+ ///
+ /// `try_wait` is the only honest answer. The `Child` value survives the
+ /// process it describes, so `process.is_some()` keeps saying yes to a
+ /// corpse, and that is exactly why a killed whisper server stayed
+ /// registered: `needs_start` saw a process, skipped the start, and every
+ /// take from then on wrote into a pipe nobody holds, until the app was
+ /// restarted (B4 Gegenprobe 29.08.).
+ ///
+ /// Reaps as a side effect, which is the point: `try_wait` collects the
+ /// exit status, so the dead python is not left as a zombie either.
+ pub fn has_exited(&mut self) -> bool {
+ match self.process.as_mut() {
+ Some(child) => match child.try_wait() {
+ Ok(Some(_)) => true,
+ Ok(None) => false,
+ // We cannot ask about it any more, so it is not ours to use.
+ Err(_) => true,
+ },
+ None => true,
+ }
+ }
+
pub fn stop(&mut self) {
if let Some(ref mut stdin) = self.stdin_tx {
let _ = stdin.write_all(b"{\"action\":\"quit\"}\n");
@@ -329,31 +386,37 @@ fn transcribe_blocking(
// Lazy-start Whisper on first use — it is no longer pre-started at launch
// (it kept ~360 MB resident even in Cloud mode). Block until the server is
// spawned; send_command below then waits for the model to finish loading.
- {
- let needs_start = state.whisper.lock().map(|w| w.process.is_none()).unwrap_or(true);
- if needs_start {
- // Resolve the SAME interpreter install_whisper used (ComfyUI venv if
- // present, else system Python). Using state.python_bin here meant a
- // venv install was invisible at runtime → STT silently dead after
- // relaunch on boxes with a ComfyUI venv (#78).
- let python_bin = crate::commands::install::resolve_lu_python(state.inner());
- if python_bin.is_empty() {
- return Err("Whisper unavailable: no Python runtime detected. Install Python in the setup step, then retry.".to_string());
- }
- auto_start_whisper_sync(app, &python_bin, &state.whisper)?;
- }
- }
+ //
+ // Self-healing, first half: this also reaps a server that died since the
+ // last take, so what follows is a real start and not a send into a closed
+ // pipe.
+ ensure_whisper_running(app, state)?;
+
+ let cmd = serde_json::json!({
+ "action": "transcribe",
+ "path": audio_path,
+ });
// Send to persistent whisper server
- let result = {
- let mut whisper = state.whisper.lock().unwrap();
- whisper.send_command(&serde_json::json!({
- "action": "transcribe",
- "path": audio_path,
- }))
- };
+ let mut result = send_to_whisper(state, &cmd);
+
+ // Self-healing, second half: the server died DURING this take, so the send
+ // found a pipe nobody holds any more. Start it again and send the same
+ // audio once more; the user only hears about it if that fails too. Before
+ // this, the first failure was permanent: every later recording hit the
+ // same dead pipe until the app was restarted (B4 Gegenprobe 29.08.).
+ if let Err(ref why) = result {
+ if whisper_is_gone(state, why) {
+ println!("[Whisper] server gone ({}), restarting once and retrying the take", why);
+ info!("whisper restart after a dead pipe");
+ result = match restart_whisper(app, state) {
+ Ok(()) => send_to_whisper(state, &cmd),
+ Err(e) => Err(e),
+ };
+ }
+ }
- // Clean up temp file
+ // Clean up temp file, after the retry, which reads the same file.
let _ = std::fs::remove_file(&tmp_file);
match result {
@@ -373,6 +436,72 @@ fn transcribe_blocking(
}
}
+/// One transcribe request to the running server, with the lock held for no
+/// longer than the send.
+fn send_to_whisper(
+ state: &State<'_, AppState>,
+ cmd: &serde_json::Value,
+) -> Result<serde_json::Value, String> {
+ let mut whisper = state.whisper.lock().unwrap();
+ whisper.send_command(cmd)
+}
+
+/// Clear a whisper child that has exited, then start one if none is running.
+///
+/// The clearing is the new half. `stop()` resets `process`, `stdin_tx`,
+/// `response_rx` and `ready` together, so what starts afterwards is a whole
+/// server and not a fresh process wired to the dead one's channels.
+fn ensure_whisper_running(app: &AppHandle, state: &State<'_, AppState>) -> Result<(), String> {
+ let needs_start = match state.whisper.lock() {
+ Ok(mut w) => {
+ if w.is_running() && w.has_exited() {
+ println!("[Whisper] the server process is gone, clearing it before this take");
+ w.stop();
+ }
+ !w.is_running()
+ }
+ Err(_) => true,
+ };
+ if !needs_start {
+ return Ok(());
+ }
+ // Resolve the SAME interpreter install_whisper used (ComfyUI venv if
+ // present, else system Python). Using state.python_bin here meant a
+ // venv install was invisible at runtime → STT silently dead after
+ // relaunch on boxes with a ComfyUI venv (#78).
+ let python_bin = crate::commands::install::resolve_lu_python(state.inner());
+ if python_bin.is_empty() {
+ return Err("Whisper unavailable: no Python runtime detected. Install Python in the setup step, then retry.".to_string());
+ }
+ auto_start_whisper_sync(app, &python_bin, &state.whisper)
+}
+
+/// Tear the server down and bring it back up, once.
+fn restart_whisper(app: &AppHandle, state: &State<'_, AppState>) -> Result<(), String> {
+ if let Ok(mut w) = state.whisper.lock() {
+ w.stop();
+ }
+ ensure_whisper_running(app, state)
+}
+
+/// Is this failure worth a restart?
+///
+/// Two independent answers, either of which is enough: the message says the
+/// pipe is gone, or the child has actually exited. The second catches a server
+/// that died without the write noticing yet, and the first catches a pipe that
+/// closed under a process still technically alive.
+fn whisper_is_gone(state: &State<'_, AppState>, why: &str) -> bool {
+ if is_pipe_failure(why) {
+ return true;
+ }
+ match state.whisper.lock() {
+ Ok(mut w) => w.has_exited(),
+ // A poisoned lock is not evidence of a dead server, and restarting on
+ // it would hide a panic behind a retry loop.
+ Err(_) => false,
+ }
+}
+
/// Synchronous whisper startup (runs in background thread).
///
/// Returns WHY it could not start. Every failure used to end in a `println!`,
@@ -488,3 +617,232 @@ mod response_channel_tests {
drop(tx);
}
}
+
+/// B4 Gegenprobe, 29.08.: the whisper server was killed mid-session on the
+/// Windows box. Two things went wrong and both are covered here.
+///
+/// 1. The failure reached the red hint over the microphone in German:
+/// "stdin flush: Die Pipe wird gerade geschlossen. (os error 232)".
+/// 2. Nothing healed. Every recording after that hit the same dead pipe until
+/// the app was restarted.
+#[cfg(test)]
+mod dead_server_tests {
+ use super::*;
+ use serde_json::json;
+
+ /// A child that is gone almost at once.
+ fn spawn_quick() -> Child {
+ let mut cmd = if cfg!(windows) {
+ let mut c = Command::new("cmd");
+ c.args(["/C", "exit"]);
+ c
+ } else {
+ let mut c = Command::new("sh");
+ c.args(["-c", "exit 0"]);
+ c
+ };
+ cmd.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null());
+ cmd.spawn().expect("a shell exists on the machine running the tests")
+ }
+
+ /// A child that sits and waits on stdin, the way whisper_server.py does.
+ fn spawn_lingering() -> Child {
+ let mut cmd = if cfg!(windows) {
+ let mut c = Command::new("cmd");
+ c.args(["/C", "pause"]);
+ c
+ } else {
+ let mut c = Command::new("sh");
+ c.args(["-c", "read line"]);
+ c
+ };
+ cmd.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null());
+ cmd.spawn().expect("a shell exists on the machine running the tests")
+ }
+
+ /// A server wired to `child`, in the state it has between two dictations.
+ ///
+ /// The sender comes back with it and has to be kept alive by the caller:
+ /// dropping it would disconnect the response channel, and a disconnected
+ /// channel is a different failure than the one under test.
+ fn server_around(child: Child) -> (WhisperServer, mpsc::Sender<serde_json::Value>) {
+ let mut ws = WhisperServer::new();
+ let mut child = child;
+ if let Some(stdin) = child.stdin.take() {
+ ws.stdin_tx = Some(std::io::BufWriter::new(stdin));
+ }
+ let (tx, rx) = mpsc::channel();
+ ws.response_rx = Some(rx);
+ ws.ready = true;
+ ws.process = Some(child);
+ (ws, tx)
+ }
+
+ #[test]
+ fn a_live_server_does_not_read_as_gone() {
+ let (mut ws, _tx) = server_around(spawn_lingering());
+ assert!(ws.is_running());
+ assert!(!ws.has_exited(), "a waiting server was declared dead");
+ ws.stop();
+ }
+
+ #[test]
+ fn a_dead_server_is_seen_even_though_the_child_value_is_still_there() {
+ let (mut ws, _tx) = server_around(spawn_quick());
+ // The exact trap: the Child outlives the process, so this keeps
+ // answering yes and `needs_start` kept skipping the restart.
+ assert!(ws.is_running(), "the handle is still registered, as it was");
+ let mut saw_it = false;
+ for _ in 0..100 {
+ if ws.has_exited() {
+ saw_it = true;
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ assert!(saw_it, "the exited child was never noticed");
+ ws.stop();
+ }
+
+ #[test]
+ fn a_server_that_was_never_started_counts_as_gone() {
+ let mut ws = WhisperServer::new();
+ assert!(!ws.is_running());
+ assert!(ws.has_exited());
+ }
+
+ /// The whole failure, at the wire: kill the server the way the box did,
+ /// then send a take into it.
+ #[test]
+ fn sending_into_a_killed_server_fails_in_english_and_is_recognised_as_a_dead_pipe() {
+ let (mut ws, _tx) = server_around(spawn_lingering());
+ if let Some(child) = ws.process.as_mut() {
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ assert!(ws.has_exited());
+
+ let err = ws
+ .send_command(&json!({ "action": "transcribe", "path": "/tmp/x.wav" }))
+ .expect_err("writing into a dead pipe must fail");
+
+ // The message is ours all the way through. The operating system's own
+ // sentence for this is German on a German Windows; none of these
+ // assertions care which language it was, because none of it survives.
+ // Printed so a `cargo test -- --nocapture` run shows the exact wording
+ // that replaced the German line, on whatever machine ran the suite.
+ println!("[dead pipe] {}", err);
+ assert!(is_pipe_failure(&err), "not recognised as a dead pipe: {}", err);
+ assert!(err.contains("os error"), "the searchable number is gone: {}", err);
+ assert!(err.is_ascii(), "non ascii in a message we wrote: {}", err);
+ // And it is one of our three prefixes, so the retry above can key on it.
+ assert!(
+ err.starts_with("stdin write:")
+ || err.starts_with("stdin newline:")
+ || err.starts_with("stdin flush:"),
+ "unexpected shape: {}",
+ err
+ );
+ ws.stop();
+ }
+
+ #[test]
+ fn every_way_the_pipe_can_be_gone_asks_for_a_restart() {
+ for m in [
+ "stdin write: the pipe is closing (os error 232)",
+ "stdin newline: broken pipe (os error 32)",
+ "stdin flush: the pipe is closing (os error 232)",
+ "No stdin connection",
+ "No response channel",
+ ] {
+ assert!(is_pipe_failure(m), "should restart on: {}", m);
+ }
+ }
+
+ /// NEGATIVE CONTROL. Restarting on any of these would make things worse:
+ /// a long dictation would lose its take, and a model still loading would be
+ /// thrown away and reloaded for another five minutes.
+ #[test]
+ fn a_slow_or_busy_server_is_left_alone() {
+ for m in [
+ "Whisper transcription timed out",
+ "Whisper server not ready",
+ "Whisper server error: Model load failed: out of memory",
+ "Empty audio data",
+ "base64 decode: invalid byte",
+ "Whisper server did not become ready within 5 minutes",
+ ] {
+ assert!(!is_pipe_failure(m), "must not restart on: {}", m);
+ }
+ }
+
+ /// NEGATIVE CONTROL for the language rule: the German sentence the box
+ /// showed must not be what the check keys on, or the fix works only where
+ /// the bug never appeared.
+ #[test]
+ fn the_check_does_not_depend_on_the_systems_own_words() {
+ let german = "stdin flush: Die Pipe wird gerade geschlossen. (os error 232)";
+ let english = "stdin flush: the pipe is closing (os error 232)";
+ assert!(is_pipe_failure(german));
+ assert!(is_pipe_failure(english));
+ // Same prefix, so the same verdict either way.
+ assert!(!is_pipe_failure("Die Pipe wird gerade geschlossen. (os error 232)"));
+ }
+}
+
+/// The wiring the unit tests above cannot reach: `transcribe_blocking` needs a
+/// Tauri AppHandle and a live AppState, so the ORDER of the healing is guarded
+/// at the source, in the style of the drift guard in os_error.rs.
+#[cfg(test)]
+mod healing_is_wired_in {
+ /// The SHIPPING half of this file, with every `#[cfg(test)]` module cut
+ /// off. Without the cut the guard reads its own assertions and passes on
+ /// the strength of the strings it was written with.
+ fn source() -> String {
+ let all = std::fs::read_to_string(
+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/commands/whisper.rs"),
+ )
+ .expect("this file is readable");
+ match all.find("#[cfg(test)]") {
+ Some(at) => all[..at].to_string(),
+ None => all,
+ }
+ }
+
+ #[test]
+ fn the_guard_reads_only_the_shipping_code() {
+ let s = source();
+ assert!(s.contains("fn transcribe_blocking"), "the cut took too much");
+ assert!(!s.contains("mod healing_is_wired_in"), "the guard is reading itself");
+ }
+
+ #[test]
+ fn a_take_starts_by_clearing_a_dead_server() {
+ let s = source();
+ assert!(s.contains("ensure_whisper_running(app, state)?;"), "the pre-take check is gone");
+ // The old shape, which asked only whether a handle existed.
+ assert!(
+ !s.contains("let needs_start = state.whisper.lock().map(|w| w.process.is_none())"),
+ "the corpse-blind check is back"
+ );
+ }
+
+ #[test]
+ fn a_take_that_hits_a_dead_pipe_is_retried_once() {
+ let s = source();
+ assert!(s.contains("if whisper_is_gone(state, why)"), "the retry gate is gone");
+ assert!(s.contains("Ok(()) => send_to_whisper(state, &cmd),"), "the retry send is gone");
+ // Once, not in a loop: a second failure is the user's answer.
+ assert_eq!(s.matches("restart_whisper(app, state)").count(), 1);
+ }
+
+ #[test]
+ fn the_temp_file_outlives_the_retry() {
+ let s = source();
+ let send = s.find("let mut result = send_to_whisper").expect("the send is gone");
+ let retry = s.find("if whisper_is_gone(state, why)").expect("the retry is gone");
+ let cleanup = s.find("let _ = std::fs::remove_file(&tmp_file);").expect("the cleanup is gone");
+ assert!(send < retry, "the retry must come after the first send");
+ assert!(retry < cleanup, "the audio was deleted before the retry could read it");
+ }
+}
diff --git a/src-tauri/src/os_error.rs b/src-tauri/src/os_error.rs
index ca5286e7..fa356e85 100644
--- a/src-tauri/src/os_error.rs
+++ b/src-tauri/src/os_error.rs
@@ -57,11 +57,24 @@ fn kind_phrase(kind: ErrorKind) -> Option<&'static str> {
/// seen would be inventing an English error to replace a true German one.
fn code_phrase(code: i32) -> Option<&'static str> {
Some(match code {
- // Windows
+ // Windows. The first two are gated because those numbers are also unix
+ // errnos with entirely different meanings: 32 is EPIPE and 33 is EDOM,
+ // so the ungated table told a Mac that a broken pipe was a file in use.
+ // Found while wiring the whisper pipe errors through here, where EPIPE
+ // is the everyday case on Mac and Linux.
+ #[cfg(windows)]
32 => "the file is in use by another process",
+ #[cfg(windows)]
33 => "the file is locked by another process",
+ // No unix errno reaches these, so they need no gate. Linux stops at
+ // 133 and macOS well below that.
145 => "the directory is not empty",
1224 => "the file is open by another process",
+ // The whisper server's stdin, after the python process died: the box
+ // showed "stdin flush: Die Pipe wird gerade geschlossen. (os error 232)"
+ // in the red hint over the microphone (B4 Gegenprobe, 29.08.).
+ // ERROR_NO_DATA, and no unix errno collides with it.
+ 232 => "the pipe is closing",
10013 => "the port is blocked, by permissions or by a firewall",
// hyper-util logs a failed set_nodelay with this one, and that log
// line is what showed German text in lu-app-exit.log on the box.
@@ -229,6 +242,46 @@ mod tests {
assert!(ours.contains(&format!("os error {}", REFUSED)), "got: {}", ours);
}
+ /// The exact code from the box, which must read the same on any machine.
+ ///
+ /// `sanitize_os_wording` cannot help here and this test is why it is not
+ /// used at that call site: it repairs a line by asking THIS machine for the
+ /// code's wording, and a Mac has no German to recognise. `english()` at the
+ /// call site never asks, so the answer is fixed by us on every platform.
+ #[test]
+ fn the_pipe_code_from_the_box_reads_in_our_words_on_every_platform() {
+ let ours = io_english(&Error::from_raw_os_error(232));
+ assert_eq!(ours, "the pipe is closing (os error 232)");
+ }
+
+ /// The whole failure the user saw, rebuilt, and the shape it has now.
+ #[test]
+ fn the_red_hint_over_the_microphone_is_english() {
+ let e = Error::from_raw_os_error(232);
+ // What the three call sites used to write: the error's own Display,
+ // which on a German Windows is "Die Pipe wird gerade geschlossen.".
+ let before = format!("stdin flush: {}", e);
+ // What they write now.
+ let after = format!("stdin flush: {}", io_english(&e));
+ assert_eq!(after, "stdin flush: the pipe is closing (os error 232)");
+ // On a German box `before` is German; here it is only "Unknown error",
+ // so the assertion that says something on every platform is that the
+ // new wording no longer depends on what the system happens to say.
+ assert!(!after.contains(&e.to_string()) || e.to_string() == io_english(&e));
+ }
+
+ /// The gate, from the side that was wrong.
+ #[test]
+ #[cfg(unix)]
+ fn a_broken_pipe_on_unix_is_not_described_as_a_file_in_use() {
+ // errno 32 is EPIPE here and ERROR_SHARING_VIOLATION there. Rust
+ // categorises this one, so the kind carries it.
+ let ours = io_english(&Error::from_raw_os_error(32));
+ assert!(ours.contains("broken pipe"), "got: {}", ours);
+ assert!(!ours.contains("in use by another process"), "got: {}", ours);
+ assert!(ours.contains("os error 32"), "got: {}", ours);
+ }
+
#[test]
fn the_number_survives_even_when_the_code_has_no_name() {
// A code no table knows. It must still be searchable.
@@ -351,7 +404,11 @@ mod tests {
fn every_named_code_reads_as_a_sentence_and_none_is_empty() {
// A guard on the tables: an entry added with an empty or capitalised
// string would read wrong inside "Failed to X: <phrase>".
- for code in [32, 33, 145, 1224, 10013, 10022, 10048, 10049, 10060, 10061] {
+ #[cfg(windows)]
+ const NAMED: &[i32] = &[32, 33, 145, 232, 1224, 10013, 10022, 10048, 10049, 10060, 10061];
+ #[cfg(not(windows))]
+ const NAMED: &[i32] = &[145, 232, 1224, 10013, 10022, 10048, 10049, 10060, 10061];
+ for &code in NAMED {
let p = code_phrase(code).expect("table entry vanished");
assert!(!p.is_empty());
assert!(p.chars().next().unwrap().is_lowercase(), "code {} is capitalised", code);
@@ -389,6 +446,13 @@ mod drift_guard {
// of these: reqwest renders its own source chain, and the leaf of that
// chain on a refused localhost port is the operating system talking.
".send()", ".bytes()", ".chunk()",
+ // The pipe calls. These are how we talk to the sidecars, and the
+ // whisper server's stdin is where the German text came back a second
+ // time: writing to a dead child fails with ERROR_NO_DATA, and the
+ // three call sites rendered that straight into the red hint over the
+ // microphone (B4 Gegenprobe 29.08.). The guard did not look at write
+ // or flush, so nothing complained.
+ ".write_all(", ".flush()", ".read_to_end(", ".read_to_string(",
];
/// How many lines a single call may be spread over.
@@ -514,5 +578,12 @@ mod drift_guard {
r#"json!({"status": "error", "error": os_error::english(&e)})"#
));
assert!(!is_suspect_field(r#"json!({"error": "All search tiers failed"})"#));
+ // The widened list: the three whisper pipe writes are the shape that
+ // slipped past the guard, so they have to fail it now.
+ assert!(is_suspect(r#"stdin.flush().map_err(|e| format!("stdin flush: {}", e))?;"#));
+ assert!(is_suspect(r#"stdin.write_all(b"\n").map_err(|e| format!("stdin newline: {}", e))?;"#));
+ assert!(!is_suspect(
+ r#"stdin.flush().map_err(|e| format!("stdin flush: {}", os_error::english(&e)))?;"#
+ ));
}
}
diff --git a/src/api/__tests__/voice-dead-server-and-silence.test.ts b/src/api/__tests__/voice-dead-server-and-silence.test.ts
new file mode 100644
index 00000000..5f3c0cdb
--- /dev/null
+++ b/src/api/__tests__/voice-dead-server-and-silence.test.ts
@@ -0,0 +1,168 @@
+/**
+ * B4 Gegenprobe, 29.08. (Windows box, 2.6.7). Three side findings on the
+ * dictation path, none of which the #115 tests could see.
+ *
+ * 1. The whisper process was killed mid-session and the red hint over the
+ * microphone read "stdin flush: Die Pipe wird gerade geschlossen.
+ * (os error 232)". German, in an app set to English, because Windows
+ * words its own errors in the language it was installed in.
+ * 2. Nothing healed afterwards. Every later recording hit the same dead pipe
+ * until the app was restarted.
+ * 3. A silent take came back with an empty transcript and the interface said
+ * nothing at all, so a silent room and a dead microphone looked the same.
+ *
+ * The first two live in Rust (src-tauri/src/commands/whisper.rs, covered by
+ * cargo test); what is guarded here is the browser and hook side of the same
+ * journey, plus the two python copies that write the `error` field the user
+ * ends up reading.
+ *
+ * Run: npx vitest run src/api/__tests__/voice-dead-server-and-silence.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'fs'
+import { fileURLToPath } from 'url'
+import { dirname, join } from 'path'
+import { noSpeechMessage, sttErrorMessage } from '../../hooks/useVoice'
+import { LocalSttError } from '../voice'
+
+const __dirname = dirname(fileURLToPath(import.meta.url))
+const repo = join(__dirname, '../../..')
+const read = (p: string) => readFileSync(join(repo, p), 'utf8')
+
+describe('a take with no words in it says so', () => {
+ it('answers a silent recording with an English hint', () => {
+ expect(noSpeechMessage('')).toBe('No speech detected, try again')
+ })
+
+ it('treats whitespace-only as silence, which is what a blank transcript looks like', () => {
+ expect(noSpeechMessage(' \n\t ')).toBe('No speech detected, try again')
+ })
+
+ it('NEGATIVE CONTROL: a take with words in it says nothing, so no bubble covers the text', () => {
+ expect(noSpeechMessage('hello world this is a microphone test')).toBeNull()
+ // A single word is still a word, including the one whisper invents on
+ // silence. That is the model, and we cannot tell it from a real "You".
+ expect(noSpeechMessage('You')).toBeNull()
+ expect(noSpeechMessage(' ok ')).toBeNull()
+ })
+
+ it('is wired into stopRecording, so the hint actually reaches the bubble', () => {
+ const src = read('src/hooks/useVoice.ts')
+ expect(src).toContain('const nothingHeard = noSpeechMessage(transcript);')
+ expect(src).toContain('if (nothingHeard) store.setSttError(nothingHeard);')
+ })
+
+ it('NEGATIVE CONTROL: the hint is not an error, so the transcript is still returned', () => {
+ const src = read('src/hooks/useVoice.ts')
+ const at = src.indexOf('const nothingHeard = noSpeechMessage(transcript);')
+ expect(at).toBeGreaterThan(-1)
+ // The very next thing after the hint is handing the transcript back, not
+ // a throw or an early return that would break the normal path.
+ expect(src.slice(at, at + 220)).toContain('return transcript;')
+ })
+})
+
+describe('the message the user reads is English, whatever language the machine speaks', () => {
+ it('the whisper pipe writes go through os_error, not the error own wording', () => {
+ const src = read('src-tauri/src/commands/whisper.rs')
+ for (const call of ['stdin write:', 'stdin newline:', 'stdin flush:']) {
+ expect(src).toContain(`format!("${call} {}", os_error::english(&e))`)
+ }
+ // The exact shape that produced the German line on the box.
+ expect(src).not.toContain('format!("stdin flush: {}", e)')
+ })
+
+ it('the drift guard now looks at pipe writes, so the next one is caught', () => {
+ const src = read('src-tauri/src/os_error.rs')
+ expect(src).toContain('".write_all(", ".flush()"')
+ // And the code from the box has a name, so the number is not alone.
+ expect(src).toContain('232 => "the pipe is closing"')
+ })
+
+ it('the python server reports an OS failure by number, not by the systems sentence', () => {
+ for (const p of ['public/whisper_server.py', 'src-tauri/resources/whisper_server.py']) {
+ const src = read(p)
+ expect(src).toContain('def error_text(e: BaseException) -> str:')
+ expect(src).toContain('respond({"error": error_text(e), "transcript": ""})')
+ // strerror is the localised half of an OSError and must not be quoted.
+ expect(src).not.toContain('e.strerror')
+ // The old shape, which handed str(OSError) straight to the user.
+ expect(src).not.toContain('respond({"error": str(e), "transcript": ""})')
+ }
+ })
+
+ it('both copies of the python server stay identical, or the app ships the old one', () => {
+ // The bundle reads src-tauri/resources, the dev server reads public. A fix
+ // in one of them only is a fix the packaged app does not have.
+ expect(read('public/whisper_server.py')).toBe(read('src-tauri/resources/whisper_server.py'))
+ })
+})
+
+describe('a refusal is cut at character boundaries, not inside one', () => {
+ /** The historical trap in this corner: whisper.rs panicked on a byte index
+ * that landed inside a multibyte character. The JS side has the same edge
+ * with surrogate pairs, and this is the half character it leaves behind. */
+ const LONE_SURROGATE = /(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])/
+
+ /** One ASCII character in front, so the 200th code unit lands INSIDE a
+ * surrogate pair rather than neatly between two of them. Without the odd
+ * offset the old cut looks correct by accident. */
+ const awkward = 'a' + '𝄞'.repeat(400)
+
+ it('a long reason full of multibyte characters survives the cut intact', async () => {
+ const { transcribeAudio } = await import('../voice')
+ const originalFetch = globalThis.fetch
+ globalThis.fetch = (async () => new Response(JSON.stringify({ error: awkward }), {
+ status: 500,
+ headers: { 'content-type': 'application/json' },
+ })) as typeof fetch
+ try {
+ const err = await transcribeAudio(new Blob(['x'], { type: 'audio/wav' })).then(
+ () => null,
+ (e: unknown) => e,
+ )
+ const msg = (err as Error).message
+ expect(msg).not.toMatch(LONE_SURROGATE)
+ expect(msg.includes('�')).toBe(false)
+ // The cut still happened: 200 characters of reason, not 400.
+ expect(Array.from(msg).length).toBeLessThan(260)
+ } finally {
+ globalThis.fetch = originalFetch
+ }
+ })
+
+ it('NEGATIVE CONTROL: the code-unit cut this replaced does break a character', () => {
+ // The line as it read before, on the same input.
+ expect(awkward.slice(0, 200)).toMatch(LONE_SURROGATE)
+ // And the line as it reads now does not.
+ expect(Array.from(awkward).slice(0, 200).join('')).not.toMatch(LONE_SURROGATE)
+ })
+
+ it('NEGATIVE CONTROL: the cut still happens, a runaway body does not fill the bubble', () => {
+ const src = read('src/api/voice.ts')
+ expect(src).toContain('Array.from(detail).slice(0, 200).join("")')
+ })
+})
+
+describe('the dead-server verdict does not depend on the systems language', () => {
+ it('the Rust check keys on our own prefixes, never on the words after them', () => {
+ const src = read('src-tauri/src/commands/whisper.rs')
+ expect(src).toContain('"stdin write:"')
+ expect(src).toContain('"No stdin connection"')
+ // A timeout is a living server. Restarting under it would lose the take.
+ expect(src).not.toContain('"Whisper transcription timed out",\n ];')
+ })
+
+ it('a whisper failure still reaches the user verbatim instead of the mic hint', () => {
+ const msg = sttErrorMessage(
+ new LocalSttError('stdin flush: the pipe is closing (os error 232)'),
+ )
+ expect(msg).toBe('stdin flush: the pipe is closing (os error 232)')
+ })
+
+ it('NEGATIVE CONTROL: an unrelated JS failure keeps the generic hint', () => {
+ expect(sttErrorMessage(new Error('boom'))).toBe(
+ 'Transcription failed, check the microphone and try again',
+ )
+ })
+})
diff --git a/src/api/voice.ts b/src/api/voice.ts
index 1092f0dd..57fa4415 100644
--- a/src/api/voice.ts
+++ b/src/api/voice.ts
@@ -207,7 +207,11 @@ async function localApiFailure(res: Response, what: string): Promise<LocalSttErr
/* not JSON after all, keep the raw text */
}
}
- detail = detail.slice(0, 200);
+ // Cut at CHARACTER boundaries. whisper.rs once panicked on exactly this
+ // mistake (a byte index landing inside a multibyte character), and in JS the
+ // same cut through a surrogate pair leaves half a character that renders as
+ // a replacement box in the red bubble.
+ detail = Array.from(detail).slice(0, 200).join("");
return new LocalSttError(
detail ? `${what} (HTTP ${res.status}): ${detail}` : `${what} (HTTP ${res.status})`,
res.status,
diff --git a/src/hooks/useVoice.ts b/src/hooks/useVoice.ts
index 6bed4d47..733c0faf 100644
--- a/src/hooks/useVoice.ts
+++ b/src/hooks/useVoice.ts
@@ -53,6 +53,25 @@ export function sttErrorMessage(err: unknown): string {
return "Transcription failed, check the microphone and try again";
}
+/** What to tell the user when a take came back with no words in it.
+ *
+ * B4 Gegenprobe, 29.08.: a silent recording ended in nothing at all. No text,
+ * no hint, the composer simply unchanged, and the user with no way to tell a
+ * silent room from a broken microphone. Whisper answers a silent clip with an
+ * empty transcript and a 200, which is not a failure, so nothing on the error
+ * path ever fired.
+ *
+ * Returns null when there IS something to insert, so the caller can hand the
+ * answer straight to setSttError.
+ *
+ * Whisper itself sometimes invents a word on silence, usually "You". That is
+ * the model, not this code, and a transcript of "You" is indistinguishable
+ * from someone actually saying it, so it is left alone.
+ */
+export function noSpeechMessage(transcript: string): string | null {
+ return transcript.trim() ? null : "No speech detected, try again";
+}
+
// Speak-generation counter + abort plumbing, module-scoped (NOT per hook
// instance) because playback is a process-wide singleton (one HTMLAudioElement
// in api/voice): every SpeakerButton mounts its own useVoice, and a Stop click
@@ -269,6 +288,10 @@ export function useVoice() {
try {
const transcript = cloudVoice ? await transcribeAudioCloud(blob) : await transcribeAudio(blob);
store.setTranscript(transcript);
+ // A silent take is not an error, but it must not be silence in the UI
+ // too: the bubble says so and clears itself after six seconds.
+ const nothingHeard = noSpeechMessage(transcript);
+ if (nothingHeard) store.setSttError(nothingHeard);
return transcript;
} catch (err) {
log.error("Whisper transcription error", { err });