Enforce a single instance, and stop crashes from vanishing silently

Two gaps that only matter once the app actually lives in the tray, which
closing the window now does on purpose.

Without single-instance enforcement, launching the app again while it is
already tray-resident — the natural thing to try when the window is gone and
nothing suggests it is still running — would start a second process fighting
the first for the same microphone and the same global shortcuts. The plugin
now catches that at the OS level and brings the existing window forward
instead, registered first in the builder chain as the plugin itself requires.

Separately, `windows_subsystem = "windows"` means a release build attaches no
console, so a panic on any thread — including the audio worker — or a
microphone stream error would previously vanish with nothing left behind.
"It just closed" is not something a bug report can act on. Both now append to
a plain text log next to the settings file, installed as early in startup as
there is an app handle to resolve that path from.

Verified end to end rather than just by inspection: built the release bundle,
launched it twice, and confirmed only one process survived.
This commit is contained in:
CRTkafa 2026-08-27 01:29:12 +07:00
parent f659e4a698
commit e8623faf44
5 changed files with 179 additions and 3 deletions

17
Cargo.lock generated
View file

@ -4214,6 +4214,22 @@ dependencies = [
"zbus", "zbus",
] ]
[[package]]
name = "tauri-plugin-single-instance"
version = "2.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3214becf9ef5783c0ae99a3bb25adf5353a7a16ebf53e74b909e29205735c6c"
dependencies = [
"serde",
"serde_json",
"tauri",
"thiserror 2.0.20",
"tokio",
"tracing",
"windows-sys 0.60.2",
"zbus",
]
[[package]] [[package]]
name = "tauri-runtime" name = "tauri-runtime"
version = "2.11.3" version = "2.11.3"
@ -4350,6 +4366,7 @@ dependencies = [
"tauri-plugin-dialog", "tauri-plugin-dialog",
"tauri-plugin-global-shortcut", "tauri-plugin-global-shortcut",
"tauri-plugin-opener", "tauri-plugin-opener",
"tauri-plugin-single-instance",
"ureq", "ureq",
"window-vibrancy 0.8.0", "window-vibrancy 0.8.0",
"windows 0.62.2", "windows 0.62.2",

View file

@ -22,6 +22,7 @@ tauri = { version = "2", features = ["tray-icon", "image-png"] }
tauri-plugin-opener = "2" tauri-plugin-opener = "2"
tauri-plugin-global-shortcut = "2" tauri-plugin-global-shortcut = "2"
tauri-plugin-dialog = "2" tauri-plugin-dialog = "2"
tauri-plugin-single-instance = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"

View file

@ -14,6 +14,7 @@
//! * The **worker thread** does the expensive part — metering, decoding, and //! * The **worker thread** does the expensive part — metering, decoding, and
//! talking to the session behind its mutex. //! talking to the session behind its mutex.
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TrySendError}; use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TrySendError};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@ -116,6 +117,13 @@ impl AudioEngine {
config.sample_format() config.sample_format()
); );
// Best-effort: a device dropping out mid-session is worth a trace in
// the crash log, but failing to resolve that log's own path is not a
// reason to refuse to open the microphone at all.
let log_path = crate::data_root(&app)
.ok()
.map(|root| root.join("textream.log"));
let stop = Arc::new(AtomicBool::new(false)); let stop = Arc::new(AtomicBool::new(false));
let muted = Arc::new(AtomicBool::new(false)); let muted = Arc::new(AtomicBool::new(false));
@ -155,6 +163,7 @@ impl AudioEngine {
channels, channels,
sender, sender,
diagnostics, diagnostics,
log_path,
); );
let Ok(stream) = stream else { return }; let Ok(stream) = stream else { return };
if stream.play().is_err() { if stream.play().is_err() {
@ -216,8 +225,16 @@ fn build_stream(
channels: usize, channels: usize,
sender: SyncSender<Vec<f32>>, sender: SyncSender<Vec<f32>>,
diagnostics: Arc<Diagnostics>, diagnostics: Arc<Diagnostics>,
log_path: Option<PathBuf>,
) -> Result<cpal::Stream, String> { ) -> Result<cpal::Stream, String> {
let on_error = |error| eprintln!("microphone stream error: {error}"); // A stream error is a device dropping out mid-session — driver crash,
// unplugged cable — the kind of thing a presenter needs to have a trace
// of afterwards, not just a Follow mode that quietly stopped moving.
let on_error = move |error| {
if let Some(path) = &log_path {
crate::diagnostics::append(path, &format!("microphone stream error: {error}"));
}
};
let stream = match format { let stream = match format {
SampleFormat::F32 => device.build_input_stream( SampleFormat::F32 => device.build_input_stream(

View file

@ -0,0 +1,115 @@
//! Crash and background-error logging for release builds.
//!
//! `windows_subsystem = "windows"` means a release build attaches no console,
//! so a panic or a background thread's error would otherwise vanish without a
//! trace. "It just closed" is not a bug report anyone can act on; a plain text
//! file next to the settings is.
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// Appends one line to `path`, timestamped in Unix seconds.
///
/// Unix time rather than a formatted date: this crate pulls in no date/time
/// dependency, and a raw timestamp still answers the two questions a log line
/// needs to — how recently, and in what order — which is all a handful of
/// crash reports ever need.
///
/// Failures to write are swallowed. A logging failure must never be the
/// reason something else goes wrong, and by the time one happens there is
/// nowhere left to report it to anyway.
pub fn append(path: &Path, message: &str) {
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) else {
return;
};
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_secs())
.unwrap_or(0);
let _ = writeln!(file, "[{timestamp}] {message}");
}
/// Installs a panic hook that logs to `path` in addition to Rust's default
/// hook — which still reaches stderr whenever a console happens to be
/// attached, as it is for every debug build. This does not stop the panic
/// from unwinding; it only makes sure it leaves a trace on the way out.
pub fn install_panic_hook(path: PathBuf) {
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
append(&path, &format!("panic: {info}"));
default_hook(info);
}));
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("textream-diagnostics-{name}"));
let _ = fs::remove_dir_all(&dir);
dir
}
#[test]
fn appending_creates_the_file_and_any_missing_directories() {
let dir = temp_dir("create");
let path = dir.join("nested").join("textream.log");
append(&path, "hello");
assert!(fs::read_to_string(&path).unwrap().contains("hello"));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn appending_twice_keeps_both_lines_in_order() {
let dir = temp_dir("append");
let path = dir.join("textream.log");
append(&path, "first");
append(&path, "second");
let contents = fs::read_to_string(&path).unwrap();
let lines: Vec<&str> = contents.lines().collect();
assert_eq!(lines.len(), 2);
assert!(lines[0].ends_with("first"));
assert!(lines[1].ends_with("second"));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn every_line_opens_with_a_timestamp() {
let dir = temp_dir("timestamp");
let path = dir.join("textream.log");
append(&path, "hello");
let contents = fs::read_to_string(&path).unwrap();
assert!(contents.starts_with('['));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_message_containing_newlines_does_not_break_the_log_format() {
let dir = temp_dir("multiline");
let path = dir.join("textream.log");
append(&path, "line one\nline two");
append(&path, "next entry");
// Not a claim that embedded newlines are escaped — only that a later,
// well-formed entry is still readable after one that was not.
let contents = fs::read_to_string(&path).unwrap();
assert!(contents.trim_end().ends_with("next entry"));
let _ = fs::remove_dir_all(&dir);
}
}

View file

@ -8,6 +8,7 @@
mod audio; mod audio;
mod backdrop; mod backdrop;
mod diagnostics;
mod document; mod document;
mod model; mod model;
mod overlay; mod overlay;
@ -53,7 +54,7 @@ fn overlay_window(app: &AppHandle) -> Result<WebviewWindow, String> {
} }
/// Root directory for downloaded models. /// Root directory for downloaded models.
fn data_root(app: &AppHandle) -> Result<PathBuf, String> { pub(crate) fn data_root(app: &AppHandle) -> Result<PathBuf, String> {
app.path() app.path()
.app_data_dir() .app_data_dir()
.map_err(|error| format!("no app data directory: {error}")) .map_err(|error| format!("no app data directory: {error}"))
@ -438,6 +439,15 @@ fn build_tray(app: &AppHandle) -> tauri::Result<()> {
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
tauri::Builder::default() tauri::Builder::default()
// Must be the first plugin registered — it has to check for a running
// instance before anything else starts up. Without it, launching the
// app a second time while it sits in the tray (which closing the
// window now does on purpose) would open a second process fighting the
// first one for the same microphone and the same global shortcuts,
// rather than just bringing the existing window forward.
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
show_main_window(app);
}))
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_dialog::init())
.plugin(shortcuts::plugin()) .plugin(shortcuts::plugin())
@ -446,6 +456,17 @@ pub fn run() {
.manage(BackdropState(Mutex::new(Backdrop::None))) .manage(BackdropState(Mutex::new(Backdrop::None)))
.setup(|app| { .setup(|app| {
let handle = app.handle().clone(); let handle = app.handle().clone();
// As early as the setup closure allows, and before anything that
// could plausibly panic. A release build has no console —
// `windows_subsystem = "windows"` sees to that — so without this,
// any panic on any thread, including the audio worker, vanishes
// with nothing left behind to debug from.
let log_path = data_root(&handle).map(|root| root.join("textream.log"));
if let Ok(path) = &log_path {
diagnostics::install_panic_hook(path.clone());
}
build_tray(&handle)?; build_tray(&handle)?;
if let Some(window) = app.get_webview_window("main") { if let Some(window) = app.get_webview_window("main") {
@ -472,7 +493,12 @@ pub fn run() {
let refused = shortcuts::register(&handle); let refused = shortcuts::register(&handle);
if !refused.is_empty() { if !refused.is_empty() {
eprintln!("shortcuts already taken: {}", refused.join(", ")); if let Ok(path) = &log_path {
diagnostics::append(
path,
&format!("shortcuts already taken: {}", refused.join(", ")),
);
}
} }
if let Some(window) = app.get_webview_window(OVERLAY) { if let Some(window) = app.get_webview_window(OVERLAY) {