feat #14740: automatic call detection on windows

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hauke
2026-11-05 15:38:55 +01:00
co-authored by Claude Opus 5.5
parent 61bf18e47f
commit d631252600
15 changed files with 1255 additions and 71 deletions
+129 -21
View File
@@ -1,4 +1,5 @@
//! Tauri commands and the UI side effects of recording (windows, events).
//! Tauri commands and the UI side effects of recording (windows, events),
//! shared by the UI, the tray and call detection.
//!
//! The handlers stay thin: the work happens in [`AppState`]. Anything that
//! blocks (audio devices, stopping a recorder, the keyring) runs on the
@@ -11,15 +12,22 @@ use recorder_core::capture::Devices;
use recorder_core::model::CallId;
use recorder_core::secrets::Service;
use recorder_core::settings::Settings;
use serde::Serialize;
use tauri::{AppHandle, Emitter, Manager, State};
use tauri_plugin_autostart::ManagerExt;
use crate::state::{AppState, DeviceLevels, RecordingState};
use crate::state::{AppState, CallBrief, DeviceLevels, Ended, RecordingState};
const LEVELS_INTERVAL: Duration = Duration::from_millis(100);
type CmdResult<T> = Result<T, String>;
/// Payload of the `call-ended` event: a call awaits the prompt's decision.
#[derive(Serialize, Clone)]
struct CallEnded {
id: CallId,
}
#[tauri::command]
pub fn get_settings(state: State<'_, AppState>) -> Settings {
state.settings()
@@ -95,32 +103,122 @@ pub async fn discard_current_recording(app: AppHandle) -> CmdResult<()> {
blocking(app, discard).await
}
/// The call the end-of-call prompt asks about, so the prompt can render even
/// if it missed the `call-ended` event.
#[tauri::command]
pub fn get_pending_prompt(state: State<'_, AppState>) -> Option<CallBrief> {
state.pending_prompt()
}
#[tauri::command]
pub fn get_call_brief(state: State<'_, AppState>, id: CallId) -> CmdResult<CallBrief> {
state.call_brief(id)
}
/// Deletes a finished call's audio and row; closes the prompt if it asked
/// about this call.
#[tauri::command]
pub async fn discard_call(app: AppHandle, id: CallId) -> CmdResult<()> {
blocking(app, move |app| {
if app.state::<AppState>().discard_call(id)? {
set_window_visible(app, "prompt", false);
}
Ok(())
})
.await
}
/// Placeholder until transcription exists; the prompt shows the error.
#[tauri::command]
pub fn transcribe_call(id: CallId) -> CmdResult<()> {
let _ = id;
Err("Transkription ist noch nicht verfügbar".to_string())
}
/// Starts a manual recording, shows the floating window and streams levels.
pub fn start_manual(app: &AppHandle) -> CmdResult<CallId> {
let state = app.state::<AppState>().start_manual_recording()?;
let RecordingState::Recording { call_id, .. } = state else {
return Err("Aufnahme wurde nicht gestartet".to_string());
};
spawn_level_emitter(app.clone(), call_id);
set_window_visible(app, "recorder", true);
emit_state(app, &state);
let call_id = app.state::<AppState>().start_manual_recording()?;
on_started(app, call_id);
Ok(call_id)
}
/// Stops the current recording and hides the floating window.
pub fn stop(app: &AppHandle) -> CmdResult<()> {
let result = app.state::<AppState>().stop_recording();
set_window_visible(app, "recorder", false);
emit_state(app, &RecordingState::Idle);
result.map(|_| ())
/// Starts recording a call that detection found (`app` is its display
/// name, `root_pid` the process tree whose audio is the far end).
pub fn start_detected(app: &AppHandle, name: &str, root_pid: u32) -> CmdResult<CallId> {
let call_id = app
.state::<AppState>()
.start_detected_recording(name, root_pid)?;
on_started(app, call_id);
Ok(call_id)
}
/// Throws the current recording away and hides the floating window.
/// Stops the current recording at the user's request (■ Stopp). Stopping
/// a detected call also keeps detection from restarting it until the call
/// app releases the mic.
pub fn stop(app: &AppHandle) -> CmdResult<()> {
let state = app.state::<AppState>();
let ended = state.stop_recording();
if ended.as_ref().is_some_and(|ended| ended.detected) {
state.suppress_detected_call();
}
after_stop(app, ended)
}
/// Stops the current recording because detection saw the call end. A
/// manual recording is left running.
pub fn end_detected_call(app: &AppHandle) {
let ended = app.state::<AppState>().stop_detected_recording();
if let Err(e) = after_stop(app, ended) {
log::error!("finishing the detected call failed: {e}");
}
}
/// Throws the current recording away. Never shows the prompt; a discarded
/// detected call is not detected again until the call app releases the mic.
pub fn discard(app: &AppHandle) -> CmdResult<()> {
let result = app.state::<AppState>().discard_current_recording();
set_window_visible(app, "recorder", false);
emit_state(app, &RecordingState::Idle);
result
let state = app.state::<AppState>();
let ended = state.discard_current_recording();
if ended.as_ref().is_some_and(|ended| ended.detected) {
state.suppress_detected_call();
}
sync_recorder_window(app);
ended.map_or(Ok(()), |ended| ended.result)
}
/// Streams levels, shows the floating window and announces a recording
/// that just started.
fn on_started(app: &AppHandle, call_id: CallId) {
spawn_level_emitter(app.clone(), call_id);
set_window_visible(app, "recorder", true);
emit_state(app, &app.state::<AppState>().recording_state());
}
/// After a recording stopped: updates the floating window and, if the call
/// was saved, asks what to do with it in the prompt window.
fn after_stop(app: &AppHandle, ended: Option<Ended>) -> CmdResult<()> {
sync_recorder_window(app);
let Some(ended) = ended else {
return Ok(());
};
ended.result?;
let id = ended.call_id;
app.state::<AppState>().set_pending_prompt(id);
show_and_focus(app, "prompt");
if let Err(e) = app.emit("call-ended", CallEnded { id }) {
log::error!("could not emit call-ended: {e}");
}
Ok(())
}
/// Announces the actual recording state and hides the floating window only
/// if nothing records any more: detection may already have started the
/// next recording.
fn sync_recorder_window(app: &AppHandle) {
let state = app.state::<AppState>().recording_state();
if matches!(state, RecordingState::Idle) {
set_window_visible(app, "recorder", false);
}
emit_state(app, &state);
}
/// Enables or disables launching at login. Debug builds leave the login
@@ -142,7 +240,17 @@ pub fn apply_autostart(app: &AppHandle, enabled: bool) {
}
pub fn show_main(app: &AppHandle) {
if let Some(window) = app.get_webview_window("main") {
show_and_focus(app, "main");
}
/// Brings the floating window to the front (tray "Aufnahme manuell
/// starten" while a recording runs).
pub fn show_recorder(app: &AppHandle) {
show_and_focus(app, "recorder");
}
fn show_and_focus(app: &AppHandle, label: &str) {
if let Some(window) = app.get_webview_window(label) {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
+97
View File
@@ -0,0 +1,97 @@
//! Automatic call detection: once a second, asks which processes hold a
//! microphone and drives the [`CallDetector`](recorder_core::detect::CallDetector)
//! kept in [`AppState`]. A detected call is recorded until the detector
//! sees it end; then the end-of-call prompt asks what to do with it.
//!
//! Only Windows reports microphone sessions; elsewhere the loop runs but
//! never detects anything.
use std::thread;
use std::time::{Duration, Instant};
use recorder_core::detect::{DetectorConfig, DetectorEvent, MicSession};
use recorder_core::settings::Settings;
use tauri::{AppHandle, Manager};
use crate::commands;
use crate::state::AppState;
const POLL_INTERVAL: Duration = Duration::from_secs(1);
/// The detector configuration the settings ask for. The app's own process
/// is always ignored.
pub fn detector_config(settings: &Settings) -> DetectorConfig {
DetectorConfig {
allowlist: settings.allowlist.clone(),
own_pid: std::process::id(),
start_after: Duration::from_secs(settings.start_after_secs),
end_after: Duration::from_secs(settings.end_after_secs),
}
}
/// Starts the detection loop on its own thread. Session enumeration
/// initialises COM on that thread, so it must not be a UI thread.
pub fn spawn(app: AppHandle) {
let spawned = thread::Builder::new()
.name("call-detection".into())
.spawn(move || {
let mut last_sessions = String::new();
loop {
thread::sleep(POLL_INTERVAL);
poll(&app, &mut last_sessions);
}
});
if let Err(e) = spawned {
log::error!("could not start call detection: {e}");
}
}
/// One detection step. `last_sessions` is the previous [`describe`] output,
/// so the log shows each change of who holds the mic exactly once.
fn poll(app: &AppHandle, last_sessions: &mut String) {
let state = app.state::<AppState>();
// A recording started by hand owns the devices; detection waits.
if state.manual_recording_running() {
return;
}
let sessions = recorder_audio::mic_sessions();
let described = describe(&sessions);
if described != *last_sessions {
log::info!("mic sessions: [{described}]");
*last_sessions = described;
}
match state.detector_tick(Instant::now(), &sessions) {
Some(DetectorEvent::CallStarted {
exe,
app: name,
root_pid,
}) => {
log::info!("call detected: {exe} (process tree {root_pid})");
if let Err(e) = commands::start_detected(app, &name, root_pid) {
log::error!("recording the detected call failed: {e}");
// Otherwise the detector would stay in the call and never
// retry; suppressing waits for the app to release the mic.
state.suppress_detected_call();
}
}
Some(DetectorEvent::CallEnded) => {
log::info!("call ended");
commands::end_detected_call(app);
}
None => {}
}
}
/// "exe pid N root N active" per session, sorted; for diagnosing detection
/// on a user's machine from the log.
fn describe(sessions: &[MicSession]) -> String {
let mut parts: Vec<String> = sessions
.iter()
.map(|s| {
let state = if s.active { "active" } else { "inactive" };
format!("{} pid {} root {} {state}", s.exe, s.pid, s.root_pid)
})
.collect();
parts.sort();
parts.join(", ")
}
+23 -5
View File
@@ -1,4 +1,5 @@
mod commands;
mod detection;
mod state;
mod tray;
@@ -6,12 +7,15 @@ use recorder_core::secrets::KeyringSecrets;
use recorder_core::store::Store;
use tauri::{Manager, WindowEvent};
use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy};
use crate::state::AppState;
/// Command-line flag the login item starts the app with; the main window
/// then stays hidden in the tray.
const AUTOSTART_ARG: &str = "--autostart";
/// Size at which the log file is rotated; two old files are kept.
const LOG_FILE_SIZE: u128 = 1_000_000;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
@@ -25,13 +29,22 @@ pub fn run() {
Some(vec![AUTOSTART_ARG]),
))
.setup(|app| {
// Release builds log to a file in the app log directory (on
// Windows %LOCALAPPDATA%\eu.euvino.callrecorder\logs), debug
// builds to stdout as well. Never log API keys or transcripts.
let mut targets = vec![Target::new(TargetKind::LogDir { file_name: None })];
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
targets.push(Target::new(TargetKind::Stdout));
}
app.handle().plugin(
tauri_plugin_log::Builder::new()
.targets(targets)
.level(log::LevelFilter::Info)
.max_file_size(LOG_FILE_SIZE)
.rotation_strategy(RotationStrategy::KeepSome(2))
.timezone_strategy(TimezoneStrategy::UseLocal)
.build(),
)?;
let data_dir = app.path().app_data_dir()?;
let config_dir = app.path().app_config_dir()?;
@@ -51,6 +64,7 @@ pub fn run() {
commands::apply_autostart(app.handle(), autostart);
tray::create(app.handle())?;
detection::spawn(app.handle().clone());
if !std::env::args().any(|arg| arg == AUTOSTART_ARG) {
commands::show_main(app.handle());
}
@@ -75,6 +89,10 @@ pub fn run() {
commands::start_manual_recording,
commands::stop_recording,
commands::discard_current_recording,
commands::get_pending_prompt,
commands::get_call_brief,
commands::discard_call,
commands::transcribe_call,
])
.run(tauri::generate_context!())
.expect("error while building tauri application");
+320 -38
View File
@@ -1,10 +1,12 @@
//! Application state shared by commands, the tray and background threads.
//!
//! Holds the store, the settings, the secret store and the recording that is
//! currently running. Everything here is independent of windows and events;
//! the command layer turns results into UI updates.
//! Holds the store, the settings, the secret store, the recording that is
//! currently running, the call detector and the call awaiting a decision in
//! the end-of-call prompt. Everything here is independent of windows and
//! events; the command layer turns results into UI updates.
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, MutexGuard};
@@ -12,14 +14,17 @@ use std::thread;
use std::time::{Duration, Instant};
use chrono::{DateTime, Local};
use recorder_core::capture::OutputTarget;
use recorder_core::model::{CallId, CallStatus};
use recorder_core::capture::{CaptureSource, OutputTarget};
use recorder_core::detect::{CallDetector, DetectorEvent, MicSession};
use recorder_core::model::{Call, CallId, CallStatus};
use recorder_core::recorder::Recorder;
use recorder_core::secrets::SecretStore;
use recorder_core::settings::Settings;
use recorder_core::store::Store;
use serde::Serialize;
use crate::detection::detector_config;
/// `app` value of calls started from the tray or UI instead of detection.
const MANUAL_APP: &str = "Manuell";
/// How long [`AppState::test_devices`] records.
@@ -53,10 +58,46 @@ pub struct DeviceLevels {
pub out: f32,
}
/// What the end-of-call prompt shows about a call.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct CallBrief {
pub id: CallId,
pub app: String,
pub started_at: DateTime<Local>,
pub ended_at: Option<DateTime<Local>>,
pub duration_secs: i64,
}
impl CallBrief {
fn of(call: &Call) -> Self {
Self {
id: call.id,
app: call.app.clone(),
started_at: call.started_at,
ended_at: call.ended_at,
duration_secs: call
.ended_at
.map_or(0, |end| (end - call.started_at).num_seconds().max(0)),
}
}
}
/// A recording that was just stopped or discarded.
#[derive(Debug)]
pub struct Ended {
pub call_id: CallId,
/// Started by call detection rather than by hand.
pub detected: bool,
/// Whether stopping (finalizing the files and the row) or discarding
/// worked.
pub result: Result<(), String>,
}
struct CurrentRecording {
call_id: CallId,
app: String,
started_at: DateTime<Local>,
detected: bool,
recorder: Recorder,
}
@@ -67,6 +108,10 @@ pub struct AppState {
settings_path: PathBuf,
recordings_dir: PathBuf,
current: Mutex<Option<CurrentRecording>>,
detector: Mutex<CallDetector>,
/// The last stopped call the end-of-call prompt asks about, until it is
/// decided (discarded or sent to transcription).
pending_prompt: Mutex<Option<CallId>>,
/// Set while a recording starts or the devices are tested, so neither
/// runs twice and `current` is never locked for longer than a moment.
devices_busy: AtomicBool,
@@ -89,6 +134,7 @@ impl AppState {
recordings_dir: PathBuf,
) -> Self {
let settings = Settings::load(&settings_path);
let detector = CallDetector::new(detector_config(&settings));
Self {
store,
secrets,
@@ -96,6 +142,8 @@ impl AppState {
settings_path,
recordings_dir,
current: Mutex::new(None),
detector: Mutex::new(detector),
pending_prompt: Mutex::new(None),
devices_busy: AtomicBool::new(false),
}
}
@@ -108,10 +156,29 @@ impl AppState {
settings
.save(&self.settings_path)
.map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))?;
lock(&self.detector).set_config(detector_config(&settings));
*lock(&self.settings) = settings;
Ok(())
}
/// Advances the call detector by one poll.
pub fn detector_tick(&self, now: Instant, sessions: &[MicSession]) -> Option<DetectorEvent> {
lock(&self.detector).tick(now, sessions)
}
/// Ends the detector's current call without an event and keeps it from
/// detecting the same app again until that app releases the mic.
pub fn suppress_detected_call(&self) {
lock(&self.detector).manual_stop();
}
/// Whether a recording started by hand (not by detection) is running.
pub fn manual_recording_running(&self) -> bool {
lock(&self.current)
.as_ref()
.is_some_and(|cur| !cur.detected)
}
pub fn recording_state(&self) -> RecordingState {
match lock(&self.current).as_ref() {
Some(cur) => RecordingState::Recording {
@@ -136,9 +203,28 @@ impl AppState {
})
}
/// Creates a call row and starts recording the configured mic and
/// output device into `recordings/<id>-mic.wav` / `<id>-out.wav`.
pub fn start_manual_recording(&self) -> Result<RecordingState, String> {
/// Starts recording the configured mic and output device.
pub fn start_manual_recording(&self) -> Result<CallId, String> {
let out = recorder_audio::output_source(output_target(&self.settings()));
self.start_recording(MANUAL_APP, false, out)
}
/// Starts recording a detected call: the configured mic and the audio
/// of the call app's process tree (or, if that cannot be captured, the
/// default output).
pub fn start_detected_recording(&self, app: &str, root_pid: u32) -> Result<CallId, String> {
let out = recorder_audio::output_source_with_fallback(OutputTarget::Process { root_pid });
self.start_recording(app, true, out)
}
/// Creates a call row and records the configured mic and `out` into
/// `recordings/<id>-mic.wav` / `<id>-out.wav`.
fn start_recording(
&self,
app: &str,
detected: bool,
out: Box<dyn CaptureSource>,
) -> Result<CallId, String> {
let _claim = self.claim_devices("Es läuft bereits eine Aufnahme")?;
let settings = self.settings();
fs::create_dir_all(&self.recordings_dir)
@@ -147,7 +233,7 @@ impl AppState {
let started_at = Local::now();
let call_id = self
.store
.create_call(MANUAL_APP, started_at, Path::new(""), Path::new(""))
.create_call(app, started_at, Path::new(""), Path::new(""))
.map_err(|e| format!("Gespräch konnte nicht angelegt werden: {e}"))?;
let (mic_path, out_path) = self.track_paths(call_id);
@@ -157,7 +243,6 @@ impl AppState {
.map_err(|e| e.to_string())
.and_then(|()| {
let mic = recorder_audio::mic_source(settings.mic_device.as_deref());
let out = recorder_audio::output_source(output_target(&settings));
Recorder::start(mic, out, &mic_path, &out_path).map_err(|e| e.to_string())
});
let recorder = match started {
@@ -172,44 +257,140 @@ impl AppState {
*lock(&self.current) = Some(CurrentRecording {
call_id,
app: MANUAL_APP.to_string(),
app: app.to_string(),
started_at,
detected,
recorder,
});
Ok(self.recording_state())
Ok(call_id)
}
/// Stops the current recording and finalizes its row. Returns `Ok(false)`
/// if nothing was recording. A recorder error still finishes the row and
/// marks the call as failed.
pub fn stop_recording(&self) -> Result<bool, String> {
let Some(cur) = lock(&self.current).take() else {
return Ok(false);
};
let result = cur.recorder.stop();
let id = cur.call_id;
self.store
.finish_recording(id, Local::now(), false)
.map_err(|e| format!("Gespräch konnte nicht gespeichert werden: {e}"))?;
if let Err(err) = result {
let msg = format!("Aufnahme fehlerhaft: {err}");
if let Err(e) = self.store.set_status(id, CallStatus::Failed, Some(&msg)) {
log::error!("could not mark call {id} as failed: {e}");
/// Stops the current recording, if any, and finalizes its row. A
/// recorder error still finishes the row and marks the call as failed.
pub fn stop_recording(&self) -> Option<Ended> {
self.stop_where(|_| true)
}
/// Like [`AppState::stop_recording`], but only stops a recording that
/// call detection started; a manual recording keeps running.
pub fn stop_detected_recording(&self) -> Option<Ended> {
self.stop_where(|cur| cur.detected)
}
fn stop_where(&self, matches: impl Fn(&CurrentRecording) -> bool) -> Option<Ended> {
let cur = {
let mut current = lock(&self.current);
if !current.as_ref().is_some_and(matches) {
return None;
}
return Err(msg);
}
Ok(true)
current.take()?
};
let id = cur.call_id;
let recorded = cur.recorder.stop();
let result = self
.store
.finish_recording(id, Local::now(), false)
.map_err(|e| format!("Gespräch konnte nicht gespeichert werden: {e}"))
.and_then(|()| {
let Err(err) = recorded else {
return Ok(());
};
let msg = format!("Aufnahme fehlerhaft: {err}");
if let Err(e) = self.store.set_status(id, CallStatus::Failed, Some(&msg)) {
log::error!("could not mark call {id} as failed: {e}");
}
Err(msg)
});
Some(Ended {
call_id: id,
detected: cur.detected,
result,
})
}
/// Discards the current recording: deletes both WAVs and the call row.
pub fn discard_current_recording(&self) -> Result<(), String> {
let Some(cur) = lock(&self.current).take() else {
return Ok(());
};
/// Discards the current recording, if any: deletes both WAVs and the
/// call row.
pub fn discard_current_recording(&self) -> Option<Ended> {
let cur = lock(&self.current).take()?;
let id = cur.call_id;
cur.recorder.discard();
let result = self
.store
.delete_call(id)
.map_err(|e| format!("Gespräch konnte nicht gelöscht werden: {e}"));
Some(Ended {
call_id: id,
detected: cur.detected,
result,
})
}
/// Remembers `id` as the call the end-of-call prompt asks about.
pub fn set_pending_prompt(&self, id: CallId) {
*lock(&self.pending_prompt) = Some(id);
}
/// The call the end-of-call prompt asks about, if it still exists.
pub fn pending_prompt(&self) -> Option<CallBrief> {
let mut pending = lock(&self.pending_prompt);
let id = (*pending)?;
match self.store.get_call(id) {
Ok(Some(call)) => Some(CallBrief::of(&call)),
Ok(None) => {
*pending = None;
None
}
Err(e) => {
log::error!("could not load call {id} for the prompt: {e}");
None
}
}
}
pub fn call_brief(&self, id: CallId) -> Result<CallBrief, String> {
let call = self
.store
.get_call(id)
.map_err(|e| e.to_string())?
.ok_or_else(|| "Gespräch nicht gefunden".to_string())?;
Ok(CallBrief::of(&call))
}
/// Deletes a finished call: both audio files and the row. Returns
/// whether it was the call the end-of-call prompt asked about.
pub fn discard_call(&self, id: CallId) -> Result<bool, String> {
if lock(&self.current)
.as_ref()
.is_some_and(|cur| cur.call_id == id)
{
return Err("Das Gespräch wird gerade aufgenommen".to_string());
}
let call = self
.store
.get_call(id)
.map_err(|e| e.to_string())?
.ok_or_else(|| "Gespräch nicht gefunden".to_string())?;
// Files first: if one cannot be deleted, the row stays so the user
// can try again instead of leaving orphaned audio behind.
for path in [&call.mic_path, &call.out_path] {
if path.as_os_str().is_empty() {
continue;
}
match fs::remove_file(path) {
Ok(()) => {}
Err(e) if e.kind() == ErrorKind::NotFound => {}
Err(e) => return Err(format!("Audiodatei konnte nicht gelöscht werden: {e}")),
}
}
self.store
.delete_call(cur.call_id)
.map_err(|e| format!("Gespräch konnte nicht gelöscht werden: {e}"))
.delete_call(id)
.map_err(|e| format!("Gespräch konnte nicht gelöscht werden: {e}"))?;
let mut pending = lock(&self.pending_prompt);
let was_pending = *pending == Some(id);
if was_pending {
*pending = None;
}
Ok(was_pending)
}
/// Records both configured devices into a temporary directory for five
@@ -277,3 +458,104 @@ fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[cfg(test)]
mod tests {
use chrono::TimeZone;
use recorder_core::secrets::MemorySecrets;
use super::*;
struct Fixture {
state: AppState,
dir: tempfile::TempDir,
}
fn fixture() -> Fixture {
let dir = tempfile::tempdir().unwrap();
let state = AppState::new(
Store::open_in_memory().unwrap(),
Box::new(MemorySecrets::default()),
dir.path().join("settings.json"),
dir.path().join("recordings"),
);
Fixture { state, dir }
}
fn at(h: u32, m: u32, s: u32) -> DateTime<Local> {
Local.with_ymd_and_hms(2026, 11, 5, h, m, s).unwrap()
}
/// A finished call from 10:14:00 to 10:46:30 with both track files.
fn finished_call(f: &Fixture) -> (CallId, PathBuf, PathBuf) {
let mic = f.dir.path().join("mic.wav");
let out = f.dir.path().join("out.wav");
fs::write(&mic, b"mic").unwrap();
fs::write(&out, b"out").unwrap();
let store = &f.state.store;
let id = store
.create_call("Microsoft Teams", at(10, 14, 0), &mic, &out)
.unwrap();
store.finish_recording(id, at(10, 46, 30), false).unwrap();
(id, mic, out)
}
#[test]
fn call_brief_has_app_times_and_duration() {
let f = fixture();
let (id, _, _) = finished_call(&f);
assert_eq!(
f.state.call_brief(id).unwrap(),
CallBrief {
id,
app: "Microsoft Teams".into(),
started_at: at(10, 14, 0),
ended_at: Some(at(10, 46, 30)),
duration_secs: 32 * 60 + 30,
}
);
assert!(f.state.call_brief(id + 1).is_err());
}
#[test]
fn pending_prompt_shows_the_call_until_it_is_gone() {
let f = fixture();
assert_eq!(f.state.pending_prompt(), None);
let (id, _, _) = finished_call(&f);
f.state.set_pending_prompt(id);
assert_eq!(f.state.pending_prompt().map(|b| b.id), Some(id));
f.state.store.delete_call(id).unwrap();
assert_eq!(f.state.pending_prompt(), None);
}
#[test]
fn discard_call_deletes_audio_and_row_and_clears_the_prompt() {
let f = fixture();
let (id, mic, out) = finished_call(&f);
f.state.set_pending_prompt(id);
assert_eq!(f.state.discard_call(id), Ok(true));
assert!(!mic.exists());
assert!(!out.exists());
assert_eq!(f.state.store.get_call(id).unwrap(), None);
assert_eq!(f.state.pending_prompt(), None);
}
#[test]
fn discard_call_of_another_call_keeps_the_prompt() {
let f = fixture();
let (pending, _, _) = finished_call(&f);
f.state.set_pending_prompt(pending);
let other = f
.state
.store
.create_call("MicroSIP", at(9, 0, 0), Path::new(""), Path::new(""))
.unwrap();
// Missing track files are not an error.
assert_eq!(f.state.discard_call(other), Ok(false));
assert_eq!(f.state.store.get_call(other).unwrap(), None);
assert_eq!(f.state.pending_prompt().map(|b| b.id), Some(pending));
}
}
+13 -2
View File
@@ -7,7 +7,7 @@ use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}
use tauri::{AppHandle, Manager};
use crate::commands;
use crate::state::AppState;
use crate::state::{AppState, RecordingState};
const OPEN: &str = "open";
const RECORD: &str = "record";
@@ -34,6 +34,13 @@ pub fn create(app: &AppHandle) -> tauri::Result<()> {
commands::show_recorder_if_recording(app);
}
RECORD => {
if matches!(
app.state::<AppState>().recording_state(),
RecordingState::Recording { .. }
) {
commands::show_recorder(app);
return;
}
// Opening the audio devices can take a moment; keep the
// event loop free.
let app = app.clone();
@@ -67,7 +74,11 @@ pub fn create(app: &AppHandle) -> tauri::Result<()> {
fn quit(app: &AppHandle) {
let app = app.clone();
thread::spawn(move || {
if let Err(e) = app.state::<AppState>().stop_recording() {
if let Some(Err(e)) = app
.state::<AppState>()
.stop_recording()
.map(|ended| ended.result)
{
log::error!("stopping the recording on quit failed: {e}");
}
app.exit(0);