-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
430 lines (385 loc) · 15.7 KB
/
Copy pathmain.rs
File metadata and controls
430 lines (385 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// Logging behavior:
// - Writes logs to both stderr and a daily-rotated file at logs/coldvox.log.
// - Log level is controlled via the RUST_LOG environment variable (e.g., "info", "debug").
// - The logs/ directory is created on startup if missing; file output uses a non-blocking writer.
// - File layer disables ANSI to keep logs clean for analysis.
use std::fs;
use std::path::Path;
use std::time::Duration;
use std::time::SystemTime;
use clap::Parser;
use tracing_appender::rolling::{RollingFileAppender, Rotation};
use tracing_subscriber::{fmt, prelude::*, EnvFilter};
use coldvox_app::Settings;
use coldvox_app::runtime::{self as app_runtime, ActivationMode as RuntimeMode, AppRuntimeOptions};
use coldvox_audio::{DeviceManager, ResamplerQuality};
use coldvox_foundation::{AppState, HealthMonitor, ShutdownHandler, StateManager};
#[cfg(feature = "tui")]
use coldvox_app::tui;
fn init_logging() -> Result<tracing_appender::non_blocking::WorkerGuard, Box<dyn std::error::Error>>
{
std::fs::create_dir_all("logs")?;
let file_appender = RollingFileAppender::new(Rotation::DAILY, "logs", "coldvox.log");
let (non_blocking_file, guard) = tracing_appender::non_blocking(file_appender);
let log_level = std::env::var("RUST_LOG").unwrap_or_else(|_| "debug".to_string());
let env_filter = EnvFilter::try_new(log_level).unwrap_or_else(|_| EnvFilter::new("debug"));
let stderr_layer = fmt::layer().with_writer(std::io::stderr);
let file_layer = fmt::layer().with_writer(non_blocking_file).with_ansi(false);
tracing_subscriber::registry()
.with(env_filter)
.with(stderr_layer)
.with(file_layer)
.init();
Ok(guard)
}
/// Prune rotated log files in `logs/` older than `retention_days` days.
/// If `retention_days` is `Some(0)` pruning is disabled. Default is 7 days when `None`.
fn prune_old_logs(retention_days: Option<u64>) {
let retention = retention_days.unwrap_or(7);
if retention == 0 {
tracing::debug!("Log retention disabled (retention_days=0)");
return;
}
let cutoff = match SystemTime::now().checked_sub(Duration::from_secs(retention * 24 * 60 * 60))
{
Some(t) => t,
None => return,
};
let logs_dir = Path::new("logs");
if !logs_dir.exists() {
return;
}
match fs::read_dir(logs_dir) {
Ok(entries) => {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|s| s.to_str()) {
// Only consider rotated files with date suffix like `coldvox.log.YYYY-MM-DD`
if name.starts_with("coldvox.log.") {
if let Ok(meta) = entry.metadata() {
if let Ok(modified) = meta.modified() {
if modified < cutoff {
if let Err(e) = fs::remove_file(&path) {
tracing::warn!(
"Failed to remove old log {}: {}",
path.display(),
e
);
} else {
tracing::info!("Removed old log file: {}", path.display());
}
}
}
}
}
}
}
}
Err(e) => tracing::warn!("Failed to read logs directory for pruning: {}", e),
}
}
#[derive(Parser, Debug)]
#[command(name = "coldvox", author, version, about = "ColdVox voice pipeline")]
struct Cli {
/// List available input devices and exit
#[arg(long = "list-devices")]
list_devices: bool,
/// Enable TUI dashboard
#[arg(long = "tui")]
tui: bool,
/// Exit immediately if all injection methods fail
#[arg(long = "injection-fail-fast")]
injection_fail_fast: bool,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Give PipeWire better routing hints if using its ALSA bridge (Linux only)
#[cfg(target_os = "linux")]
std::env::set_var(
"PIPEWIRE_PROPS",
"{ application.name=ColdVox media.role=capture }",
);
let _log_guard = init_logging()?;
// Prune old rotated logs. Set COLDVOX_LOG_RETENTION_DAYS=0 to disable pruning.
let retention_days = std::env::var("COLDVOX_LOG_RETENTION_DAYS")
.ok()
.and_then(|s| s.parse::<u64>().ok());
prune_old_logs(retention_days);
tracing::info!("Starting ColdVox application");
let cli = Cli::parse();
let mut settings = Settings::new().unwrap_or_else(|e| {
tracing::error!("Failed to load settings: {}", e);
Settings::default()
});
// Override settings with CLI flags
if cli.injection_fail_fast {
settings.injection.fail_fast = true;
}
if cli.list_devices {
let dm = DeviceManager::new()?;
tracing::info!("CPAL host: {:?}", dm.host_id());
let devices = dm.enumerate_devices();
println!("Input devices (host: {:?}):", dm.host_id());
for d in devices {
let def = if d.is_default { " (default)" } else { "" };
println!("- {}{}", d.name, def);
}
return Ok(());
}
// Unified runtime start
let state_manager = StateManager::new();
let _health_monitor = HealthMonitor::new(Duration::from_secs(10)).start();
let shutdown = ShutdownHandler::new().install().await;
state_manager.transition(AppState::Running)?;
tracing::info!("Application state: Running");
// Build STT configuration from settings
let stt_selection = {
use coldvox_stt::plugin::{FailoverConfig, GcPolicy, MetricsConfig, PluginSelectionConfig};
let failover = FailoverConfig {
failover_threshold: settings.stt.failover_threshold,
failover_cooldown_secs: settings.stt.failover_cooldown_secs,
};
let gc_policy = GcPolicy {
model_ttl_secs: settings.stt.model_ttl_secs,
enabled: !settings.stt.disable_gc,
};
let metrics = MetricsConfig {
log_interval_secs: if settings.stt.metrics_log_interval_secs == 0 {
None
} else {
Some(settings.stt.metrics_log_interval_secs)
},
debug_dump_events: settings.stt.debug_dump_events,
};
Some(PluginSelectionConfig {
preferred_plugin: settings.stt.preferred,
fallback_plugins: settings.stt.fallbacks,
require_local: settings.stt.require_local,
max_memory_mb: settings.stt.max_mem_mb,
required_language: settings.stt.language,
failover: Some(failover),
gc_policy: Some(gc_policy),
metrics: Some(metrics),
auto_extract_model: settings.stt.auto_extract,
})
};
let device = settings.device.clone();
let resampler_quality = match settings.resampler_quality.to_lowercase().as_str() {
"fast" => ResamplerQuality::Fast,
"quality" => ResamplerQuality::Quality,
_ => ResamplerQuality::Balanced,
};
let activation_mode = match settings.activation_mode.as_str() {
"vad" => RuntimeMode::Vad,
"hotkey" => RuntimeMode::Hotkey,
_ => RuntimeMode::Vad,
};
let mut opts = AppRuntimeOptions {
device,
resampler_quality,
activation_mode,
stt_selection,
enable_device_monitor: settings.enable_device_monitor,
..Default::default()
};
#[cfg(feature = "text-injection")]
{
opts.injection = if cfg!(feature = "text-injection") {
Some(coldvox_app::runtime::InjectionOptions {
enable: true, // Assuming text injection is enabled if the feature is on
allow_kdotool: settings.injection.allow_kdotool,
allow_enigo: settings.injection.allow_enigo,
inject_on_unknown_focus: settings.injection.inject_on_unknown_focus,
max_total_latency_ms: Some(settings.injection.max_total_latency_ms),
per_method_timeout_ms: Some(settings.injection.per_method_timeout_ms),
cooldown_initial_ms: Some(settings.injection.cooldown_initial_ms),
fail_fast: settings.injection.fail_fast,
})
} else {
None
};
}
let app = app_runtime::start(opts)
.await
.map_err(|e| e as Box<dyn std::error::Error>)?;
// make sharable for spawn + shutdown
let app = std::sync::Arc::new(app);
// Spawn TUI if requested
#[cfg(feature = "tui")]
if cli.tui {
tracing::info!("Starting TUI dashboard...");
tracing::debug!("About to call tui::run_tui - validating module import");
let tui_app = app.clone();
let tui_handle = tokio::spawn(async move {
if let Err(e) = tui::run_tui(tui_app).await {
tracing::error!("TUI error: {}", e);
}
});
// Wait for TUI to complete
if let Err(e) = tui_handle.await {
tracing::error!("TUI task error: {}", e);
}
} else {
// Standard mode: periodic stats log
let mut stats_interval = tokio::time::interval(Duration::from_secs(30));
let metrics = app.metrics.clone();
tokio::select! {
_ = shutdown.wait() => {
tracing::debug!("Shutdown signal received");
}
_ = async {
loop {
stats_interval.tick().await;
let cap_fps = metrics.capture_fps.load(std::sync::atomic::Ordering::Relaxed);
let chk_fps = metrics.chunker_fps.load(std::sync::atomic::Ordering::Relaxed);
let vad_fps = metrics.vad_fps.load(std::sync::atomic::Ordering::Relaxed);
let cap_fill = metrics.capture_buffer_fill.load(std::sync::atomic::Ordering::Relaxed);
let chk_fill = metrics.chunker_buffer_fill.load(std::sync::atomic::Ordering::Relaxed);
tracing::info!(
capture_fps = cap_fps,
chunker_fps = chk_fps,
vad_fps = vad_fps,
capture_buffer_fill_pct = cap_fill,
chunker_buffer_fill_pct = chk_fill,
"Pipeline running..."
);
}
} => {}
}
}
#[cfg(not(feature = "tui"))]
{
// Standard mode: periodic stats log
let mut stats_interval = tokio::time::interval(Duration::from_secs(30));
let metrics = app.metrics.clone();
tokio::select! {
_ = shutdown.wait() => {
tracing::debug!("Shutdown signal received");
}
_ = async {
loop {
stats_interval.tick().await;
let cap_fps = metrics.capture_fps.load(std::sync::atomic::Ordering::Relaxed);
let chk_fps = metrics.chunker_fps.load(std::sync::atomic::Ordering::Relaxed);
let vad_fps = metrics.vad_fps.load(std::sync::atomic::Ordering::Relaxed);
let cap_fill = metrics.capture_buffer_fill.load(std::sync::atomic::Ordering::Relaxed);
let chk_fill = metrics.chunker_buffer_fill.load(std::sync::atomic::Ordering::Relaxed);
tracing::info!(
capture_fps = cap_fps,
chunker_fps = chk_fps,
vad_fps = vad_fps,
capture_buffer_fill_pct = cap_fill,
chunker_buffer_fill_pct = chk_fill,
"Pipeline running..."
);
}
} => {}
}
}
// Shutdown
tracing::debug!("Beginning graceful shutdown");
state_manager.transition(AppState::Stopping)?;
// Shutdown directly on the Arc<AppHandle>
app.shutdown().await;
state_manager.transition(AppState::Stopped)?;
tracing::debug!("Shutdown complete");
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::field_reassign_with_default)]
use super::*;
use std::env;
struct EnvVarGuard {
key: &'static str,
previous: Option<String>,
}
impl EnvVarGuard {
fn set(key: &'static str, value: &str) -> Self {
let previous = env::var(key).ok();
env::set_var(key, value);
Self { key, previous }
}
}
impl Drop for EnvVarGuard {
fn drop(&mut self) {
if let Some(prev) = self.previous.take() {
env::set_var(self.key, prev);
} else {
env::remove_var(self.key);
}
}
}
#[test]
fn test_settings_new_default() {
// Test default loading without file
let settings = Settings::new().unwrap();
assert_eq!(settings.resampler_quality.to_lowercase(), "balanced");
assert_eq!(settings.activation_mode.to_lowercase(), "vad");
assert_eq!(settings.injection.max_total_latency_ms, 800);
assert!(settings.stt.failover_threshold > 0);
}
#[test]
fn test_settings_new_invalid_env_var_deserial() {
let _guard = EnvVarGuard::set("COLDVOX_INJECTION__MAX_TOTAL_LATENCY_MS", "abc"); // Invalid for u64
let result = Settings::new();
let err = result.expect_err("expected invalid env var to cause error");
assert!(
err.contains("deserialize"),
"unexpected error message: {err}"
);
}
#[test]
fn test_settings_validate_zero_timeout() {
let mut settings = Settings::default();
settings.injection.max_total_latency_ms = 0;
let result = settings.validate();
assert!(result.is_err());
assert!(result.unwrap_err().contains("max_total_latency_ms"));
}
#[test]
fn test_settings_validate_invalid_mode() {
let mut settings = Settings::new().unwrap();
settings.resampler_quality = "invalid".to_string();
let result = settings.validate();
assert!(result.is_ok()); // Warns but defaults applied
assert_eq!(settings.resampler_quality, "balanced");
}
#[test]
fn test_settings_validate_invalid_rate() {
let mut settings = Settings::new().unwrap();
settings.injection.keystroke_rate_cps = 200; // Too high
let result = settings.validate();
assert!(result.is_ok()); // Warns and clamps
assert_eq!(settings.injection.keystroke_rate_cps, 20);
}
#[test]
fn test_settings_validate_success_rate() {
let mut settings = Settings::new().unwrap();
settings.injection.min_success_rate = 1.5;
let result = settings.validate();
assert!(result.is_ok()); // Warns and clamps
assert_eq!(settings.injection.min_success_rate, 0.3);
}
#[test]
fn test_settings_validate_zero_validation() {
let mut settings = Settings::default();
settings.stt.failover_threshold = 0;
let result = settings.validate();
assert!(result.is_err());
assert!(result.unwrap_err().contains("failover_threshold"));
}
#[test]
fn test_settings_new_with_env_override() {
let _guard = EnvVarGuard::set("COLDVOX_ACTIVATION_MODE", "hotkey");
let settings = Settings::new().unwrap();
assert_eq!(settings.activation_mode, "hotkey");
}
#[test]
fn test_settings_new_validation_err() {
let _guard = EnvVarGuard::set("COLDVOX_INJECTION__MAX_TOTAL_LATENCY_MS", "0");
let result = Settings::new();
assert!(result.is_err());
assert!(result.unwrap_err().contains("max_total_latency_ms"));
}
}