Files
call-recorder/src-tauri/src/state.rs
T
2026-11-10 13:52:26 +01:00

2142 lines
76 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Application state shared by commands, the tray and background threads.
//!
//! Holds the store, the settings, the secret store, the HTTP transport, the
//! recording that is currently running, the call detector, the calls
//! awaiting a decision in the end-of-call prompt, the calls being
//! processed and the cached mixes for playback. Everything here is
//! independent of windows and events; the command layer turns results into
//! UI updates.
use std::collections::{HashMap, HashSet, VecDeque};
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread;
use std::time::{Duration, Instant};
use chrono::{DateTime, Local};
use recorder_audio::RenderSession;
use recorder_core::backend::{BackendClient, KeyInfo, NewKey, StoredKey};
use recorder_core::call_view::{self, CallDetail, CallListItem};
use recorder_core::capture::{CaptureSource, OutputTarget};
use recorder_core::detect::{CallDetector, DetectorEvent, MicSession};
use recorder_core::http::{HttpTransport, ReqwestTransport};
use recorder_core::model::{Call, CallId, CallStatus, Speaker};
use recorder_core::playback;
use recorder_core::recorder::Recorder;
use recorder_core::secrets::{SecretStore, Service};
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.
const TEST_DURATION: Duration = Duration::from_secs(5);
const TEST_POLL: Duration = Duration::from_millis(50);
const ALREADY_PROCESSING: &str = "Wird bereits verarbeitet";
const ALREADY_UPLOADING: &str = "Wird bereits hochgeladen";
/// Why [`AppState::discard_call`] refused.
#[derive(Debug, Clone, PartialEq)]
pub enum DiscardError {
/// DeepScript jobs of the call are still on record; their delete has to
/// succeed first, or the cascade would forget them.
CleanupPending,
Other(String),
}
impl std::fmt::Display for DiscardError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DiscardError::CleanupPending => f.write_str(
"Daten bei DeepScript werden noch gelöscht – bitte später erneut versuchen.",
),
DiscardError::Other(msg) => f.write_str(msg),
}
}
}
impl From<String> for DiscardError {
fn from(msg: String) -> Self {
DiscardError::Other(msg)
}
}
/// Payload of the `recording-state` event.
#[derive(Serialize, Clone, Debug)]
#[serde(tag = "state", rename_all = "lowercase")]
pub enum RecordingState {
Idle,
Recording {
call_id: CallId,
app: String,
started_at: DateTime<Local>,
},
}
/// Payload of the `levels` event.
#[derive(Serialize, Clone, Debug)]
pub struct Levels {
pub mic: f32,
pub out: f32,
pub failed_tracks: Vec<&'static str>,
}
/// Result of [`AppState::test_devices`]: peak rms level per track.
#[derive(Serialize, Clone, Copy, Debug)]
pub struct DeviceLevels {
pub mic: f32,
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_view::duration_secs(call),
}
}
}
/// The call the end-of-call prompt shows, and how many wait behind it.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct PendingPrompt {
#[serde(flatten)]
pub brief: CallBrief,
pub more_waiting: usize,
}
/// A recording that was just stopped or discarded.
#[derive(Debug)]
pub struct Ended {
pub call_id: CallId,
/// 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,
}
pub struct AppState {
pub store: Store,
pub secrets: Box<dyn SecretStore>,
/// The one HTTP client all API calls share.
pub transport: Arc<dyn HttpTransport>,
settings: Mutex<Settings>,
settings_path: PathBuf,
recordings_dir: PathBuf,
/// Where the mixes for playback are cached (`<app cache>/playback`),
/// served to the main window by [`crate::playback`].
playback_dir: PathBuf,
/// The leases on cached mixes. Held while a mix is built or removed,
/// so a call deleted meanwhile never leaves its mix behind.
playback: Mutex<PlaybackLeases>,
current: Mutex<Option<CurrentRecording>>,
detector: Mutex<CallDetector>,
/// Stopped calls awaiting the end-of-call prompt's decision, oldest
/// first. A call leaves the queue when it is decided (discarded or sent
/// to transcription).
pending_prompts: Mutex<VecDeque<CallId>>,
/// Calls a pipeline run is under way for; at most one run per call.
processing: Mutex<HashSet<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,
/// The backend this build talks to ([`crate::backend::BACKEND_URL`]).
backend_url: String,
/// Held while the stored backend key and its login change, so a
/// compare-and-delete never removes a key stored meanwhile.
backend_key_lock: Mutex<()>,
/// Calls whose transcript is being uploaded; one upload per call.
uploading: Mutex<HashSet<CallId>>,
/// Calls whose transcript reached the CRM but could not be recorded
/// locally (`mark_uploaded` failed after a successful upload):
/// `claim_upload` refuses these for the rest of this run, so a retry
/// never creates a second copy at the CRM. In-memory only; a restart
/// forgets it (the row's `crm_transcript_id` is still empty then).
upload_confirmed_unsaved: Mutex<HashSet<CallId>>,
}
/// A mix ready to play, from [`AppState::prepare_playback`].
#[derive(Serialize, Clone, Copy, Debug, PartialEq)]
pub struct PreparedPlayback {
pub duration_secs: f64,
/// Hand back to [`AppState::release_playback`] when the player is done.
pub lease: u64,
}
/// Which player holds each cached mix: the lease of the latest
/// [`AppState::prepare_playback`] per call. A player that lets go of an
/// older lease (it was replaced by a newer one meanwhile) removes nothing.
#[derive(Default)]
struct PlaybackLeases {
next: u64,
latest: HashMap<CallId, u64>,
}
/// An upload reserved with [`AppState::claim_upload`]; released when
/// dropped, also if the upload fails or panics.
pub struct UploadClaim<'a> {
state: &'a AppState,
id: CallId,
}
impl Drop for UploadClaim<'_> {
fn drop(&mut self) {
lock(&self.state.uploading).remove(&self.id);
}
}
/// Releases [`AppState::devices_busy`] when dropped.
struct DevicesClaim<'a>(&'a AtomicBool);
impl Drop for DevicesClaim<'_> {
fn drop(&mut self) {
self.0.store(false, Ordering::SeqCst);
}
}
impl AppState {
pub fn new(
store: Store,
secrets: Box<dyn SecretStore>,
settings_path: PathBuf,
recordings_dir: PathBuf,
playback_dir: PathBuf,
) -> Self {
let settings = Settings::load(&settings_path);
let detector = CallDetector::new(detector_config(&settings));
Self {
store,
secrets,
transport: Arc::new(ReqwestTransport::new()),
settings: Mutex::new(settings),
settings_path,
recordings_dir,
playback_dir,
playback: Mutex::new(PlaybackLeases::default()),
current: Mutex::new(None),
detector: Mutex::new(detector),
pending_prompts: Mutex::new(VecDeque::new()),
processing: Mutex::new(HashSet::new()),
devices_busy: AtomicBool::new(false),
// Defensive: BACKEND_URL itself must never have a trailing
// slash (see backend::tests::backend_urls_have_no_trailing…),
// but a stored key's base_url is compared against this field.
backend_url: crate::backend::BACKEND_URL
.trim_end_matches('/')
.to_string(),
backend_key_lock: Mutex::new(()),
uploading: Mutex::new(HashSet::new()),
upload_confirmed_unsaved: Mutex::new(HashSet::new()),
}
}
pub fn settings(&self) -> Settings {
lock(&self.settings).clone()
}
/// Validates, saves and applies the settings the user edited; the
/// detector picks up the new allowlist and delays immediately. The
/// backend login (managed by the app) is kept.
pub fn save_settings(&self, edited: Settings) -> Result<(), String> {
let mut current = lock(&self.settings);
let settings = current.edited(edited)?;
save(&settings, &self.settings_path)?;
lock(&self.detector).set_config(detector_config(&settings));
*current = settings;
Ok(())
}
/// The backend this build talks to.
pub fn backend_url(&self) -> &str {
&self.backend_url
}
/// Client of this build's backend.
pub fn backend_client(&self) -> BackendClient {
BackendClient::new(self.transport.clone(), &self.backend_url)
}
/// The stored backend key with its expiry, if it was created for this
/// build's backend. A key of another backend is discarded instead (as
/// if expired), so it is never sent anywhere else. Reads the keyring,
/// so call it off the UI thread.
pub fn backend_key(&self) -> Option<StoredKey> {
let _key_lock = lock(&self.backend_key_lock);
let key = self
.secrets
.get(Service::Backend)
.filter(|key| !key.trim().is_empty())?;
let settings = self.settings();
if settings.backend_key_base_url.as_deref() != Some(self.backend_url.as_str()) {
log::info!(
"backend: the stored key belongs to {:?}, not {:?}: discarding it",
settings.backend_key_base_url,
self.backend_url
);
if let Err(e) = self.forget_backend_key() {
log::error!("backend: {e}");
}
return None;
}
Some(StoredKey {
key,
expires_at: settings.backend_key_expires_at,
})
}
/// Stores a key the login created for the backend at `base_url` (in
/// the keyring) with whose it is, when it expires and its backend (in
/// the settings). A key of another backend than this build's is
/// refused and nothing stored.
pub fn store_backend_key(
&self,
key: &NewKey,
base_url: &str,
username: Option<String>,
) -> Result<(), String> {
let base_url = base_url.trim_end_matches('/');
if base_url != self.backend_url {
return Err(format!(
"Der Schlüssel gehört zu einem anderen Server ({base_url}) und wurde nicht gespeichert."
));
}
let _key_lock = lock(&self.backend_key_lock);
self.secrets
.set(Service::Backend, &key.key)
.map_err(|e| format!("Backend-Schlüssel konnte nicht gespeichert werden: {e}"))?;
self.update_settings(|s| {
s.backend_username = username;
s.backend_key_expires_at = Some(key.expires_at);
s.backend_key_base_url = Some(base_url.to_string());
})
}
/// Takes over whose the stored key is and when it expires, as the
/// backend reports it.
pub fn refresh_backend_login(&self, info: &KeyInfo) -> Result<(), String> {
self.update_settings(|s| {
s.backend_username = Some(info.username.clone());
s.backend_key_expires_at = Some(info.expires_at);
})
}
/// "Abmelden": forgets the backend key (keyring) and its login
/// (settings).
pub fn discard_backend_key(&self) -> Result<(), String> {
let _key_lock = lock(&self.backend_key_lock);
self.forget_backend_key()
}
/// Forgets the stored backend key only if it still is `refused`, the
/// key the backend just refused; a key stored meanwhile (by a login)
/// stays. Returns whether it was forgotten.
pub fn discard_refused_backend_key(&self, refused: &str) -> Result<bool, String> {
let _key_lock = lock(&self.backend_key_lock);
if self.secrets.get(Service::Backend).as_deref() != Some(refused) {
return Ok(false);
}
self.forget_backend_key().map(|()| true)
}
/// Deletes the key and its login; the caller holds `backend_key_lock`.
/// The keyring is never called while the settings are locked.
fn forget_backend_key(&self) -> Result<(), String> {
self.secrets
.delete(Service::Backend)
.map_err(|e| format!("Backend-Schlüssel konnte nicht entfernt werden: {e}"))?;
self.update_settings(|s| {
s.backend_username = None;
s.backend_key_expires_at = None;
s.backend_key_base_url = None;
})
}
/// Reserves call `id` for one upload; released when the claim is
/// dropped. A second upload of the same call is refused meanwhile, and
/// so is a call already uploaded to *this build's* backend
/// ([`call_view::uploaded_here`]) — or one the CRM confirmed but whose
/// id could not be saved locally, see
/// [`AppState::note_upload_confirmed_but_unsaved`]: the CRM this build
/// talks to must never get a duplicate. An upload recorded for another
/// backend (e.g. the test backend, read by a release build) is not
/// "uploaded" here and is claimed like any other call. All three checks
/// happen while `uploading` is locked, so a second upload can never
/// slip in between this check and the one upload it allows.
pub fn claim_upload(&self, id: CallId) -> Result<UploadClaim<'_>, String> {
let mut uploading = lock(&self.uploading);
if uploading.contains(&id) {
return Err(ALREADY_UPLOADING.to_string());
}
if lock(&self.upload_confirmed_unsaved).contains(&id) {
return Err("Bereits hochgeladen".to_string());
}
// An upload recorded for another backend (e.g. the test backend,
// read by a release build) does not count: the CRM this build
// talks to has never seen this transcript.
if call_view::uploaded_here(&self.find_call(id)?, &self.backend_url) {
return Err("Bereits hochgeladen".to_string());
}
uploading.insert(id);
Ok(UploadClaim { state: self, id })
}
/// Whether call `id`'s transcript is being uploaded.
pub fn is_uploading(&self, id: CallId) -> bool {
lock(&self.uploading).contains(&id)
}
/// Records that call `id`'s transcript reached the CRM, but saving that
/// locally (`mark_uploaded`) failed: [`AppState::claim_upload`] refuses
/// this call for the rest of the run, so a retry can never send the CRM
/// a second copy. In-memory only; see the field's doc comment.
pub fn note_upload_confirmed_but_unsaved(&self, id: CallId) {
lock(&self.upload_confirmed_unsaved).insert(id);
}
/// Changes and saves settings the app manages itself; saves only if
/// something changed.
fn update_settings(&self, change: impl FnOnce(&mut Settings)) -> Result<(), String> {
let mut current = lock(&self.settings);
let mut settings = current.clone();
change(&mut settings);
if settings != *current {
save(&settings, &self.settings_path)?;
*current = 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 {
call_id: cur.call_id,
app: cur.app.clone(),
started_at: cur.started_at,
},
None => RecordingState::Idle,
}
}
/// Levels of the recording `call_id`, or `None` once it is no longer
/// the current recording.
pub fn levels(&self, call_id: CallId) -> Option<Levels> {
let current = lock(&self.current);
let cur = current.as_ref().filter(|cur| cur.call_id == call_id)?;
let (mic, out) = cur.recorder.levels();
Some(Levels {
mic,
out,
failed_tracks: cur.recorder.failed_tracks(),
})
}
/// 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 (`app` is its display name, `exe`
/// and `root_pid` identify the call app): the configured mic and the
/// output device the call plays on (see [`detected_output_target`]).
pub fn start_detected_recording(
&self,
app: &str,
exe: &str,
root_pid: u32,
) -> Result<CallId, String> {
let sessions = recorder_audio::render_sessions();
log::info!(
"render sessions: [{}]",
recorder_audio::describe_render_sessions(&sessions)
);
let target = detected_output_target(
self.settings().output_device.as_deref(),
&sessions,
exe,
root_pid,
);
self.start_recording(app, true, recorder_audio::output_source(target))
}
/// 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)
.map_err(|e| format!("Aufnahmeordner konnte nicht angelegt werden: {e}"))?;
let started_at = Local::now();
let call_id = self
.store
.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);
let started = self
.store
.set_paths(call_id, &mic_path, &out_path)
.map_err(|e| e.to_string())
.and_then(|()| {
let mic = recorder_audio::mic_source(settings.mic_device.as_deref());
Recorder::start(mic, out, &mic_path, &out_path).map_err(|e| e.to_string())
});
let recorder = match started {
Ok(recorder) => recorder,
Err(err) => {
if let Err(e) = self.store.delete_call(call_id) {
log::error!("could not delete call {call_id} after failed start: {e}");
}
return Err(format!("Aufnahme konnte nicht gestartet werden: {err}"));
}
};
*lock(&self.current) = Some(CurrentRecording {
call_id,
app: app.to_string(),
started_at,
detected,
recorder,
});
Ok(call_id)
}
/// 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;
}
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,
result,
})
}
/// 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,
result,
})
}
/// Queues `id` for the end-of-call prompt (once).
pub fn queue_prompt(&self, id: CallId) {
let mut queue = lock(&self.pending_prompts);
if !queue.contains(&id) {
queue.push_back(id);
}
}
/// The oldest queued call that still exists, with the number of calls
/// queued behind it. Calls deleted elsewhere drop out of the queue.
pub fn pending_prompt(&self) -> Option<PendingPrompt> {
let mut queue = lock(&self.pending_prompts);
loop {
let id = *queue.front()?;
match self.store.get_call(id) {
Ok(Some(call)) => {
return Some(PendingPrompt {
brief: CallBrief::of(&call),
more_waiting: queue.len() - 1,
})
}
Ok(None) => {
queue.pop_front();
}
Err(e) => {
log::error!("could not load call {id} for the prompt: {e}");
return None;
}
}
}
}
/// Takes a decided call out of the prompt queue. Returns the position
/// it had, or `None` if `id` was not queued.
pub fn remove_queued_prompt(&self, id: CallId) -> Option<usize> {
let mut queue = lock(&self.pending_prompts);
let index = queue.iter().position(|&queued| queued == id)?;
queue.remove(index);
Some(index)
}
/// How many calls wait for the end-of-call prompt.
pub fn prompts_waiting(&self) -> usize {
lock(&self.pending_prompts).len()
}
pub fn call_brief(&self, id: CallId) -> Result<CallBrief, String> {
Ok(CallBrief::of(&self.find_call(id)?))
}
/// All calls for the main window's list, newest first.
pub fn call_list(&self) -> Result<Vec<CallListItem>, String> {
let calls = self.store.list_calls().map_err(|e| e.to_string())?;
Ok(calls
.iter()
.map(|call| CallListItem::of(call, &self.backend_url))
.collect())
}
/// The selected call with its transcript (speaker merges applied),
/// speaker names and whether it is being uploaded.
pub fn call_detail(&self, id: CallId) -> Result<CallDetail, String> {
let call = self.find_call(id)?;
let segments = self.store.segments(id).map_err(|e| e.to_string())?;
let names = self.store.speaker_names(id).map_err(|e| e.to_string())?;
let merges = self.store.speaker_merges(id).map_err(|e| e.to_string())?;
let mut detail = CallDetail::of(
&call,
&segments,
names,
&merges,
&self.backend_url,
&self.settings().language,
);
detail.uploading = self.is_uploading(id);
detail.audio_available = playback::audio_available(&call);
Ok(detail)
}
/// Mixes call `id`'s tracks for playback (or reuses the cached mix,
/// see [`playback::prepare`]) under a new lease. Refused while the call
/// is recorded or processed, and once its audio is gone.
pub fn prepare_playback(&self, id: CallId) -> Result<PreparedPlayback, String> {
if lock(&self.current)
.as_ref()
.is_some_and(|cur| cur.call_id == id)
{
return Err(playback::RECORDING.to_string());
}
let mut leases = lock(&self.playback);
// Read under the lock: a call deleted before it is not mixed, one
// deleted meanwhile has its mix removed once the lock is free.
let call = self.find_call(id)?;
let info = playback::prepare(&call, &self.playback_dir)?;
leases.next += 1;
let lease = leases.next;
leases.latest.insert(id, lease);
Ok(PreparedPlayback {
duration_secs: info.duration_secs,
lease,
})
}
/// The player of `lease` is done with call `id`'s mix: removes it,
/// unless a newer lease (another player of the same call) holds it.
pub fn release_playback(&self, id: CallId, lease: u64) {
let mut leases = lock(&self.playback);
if leases.latest.get(&id) == Some(&lease) {
leases.latest.remove(&id);
playback::remove_cached(&self.playback_dir, id);
}
}
/// Removes call `id`'s cached mix whoever holds it: with the call, and
/// once its audio is deleted. The retention job, when it deletes a
/// call's audio, calls this too.
pub fn remove_playback(&self, id: CallId) {
let mut leases = lock(&self.playback);
leases.latest.remove(&id);
playback::remove_cached(&self.playback_dir, id);
}
/// Where the mixes are cached ([`crate::playback`] serves them).
pub fn playback_dir(&self) -> &Path {
&self.playback_dir
}
/// Empties the playback cache (at startup), so mixed customer audio
/// never lingers from an earlier run.
pub fn clear_playback_cache(&self) {
let dir = &self.playback_dir;
match playback::clear_cache(dir) {
Ok(()) => log::info!("cleared the playback cache {}", dir.display()),
Err(e) => log::warn!("could not empty {}: {e}", dir.display()),
}
}
/// Renames a speaker of call `id`; a blank `name` restores the default
/// label ("Ich", "Sprecher N").
pub fn rename_speaker(&self, id: CallId, speaker_key: &str, name: &str) -> Result<(), String> {
if Speaker::from_key(speaker_key).is_none() {
return Err(format!("Unbekannter Sprecher: {speaker_key}"));
}
self.find_call(id)?;
let name = name.trim();
let result = if name.is_empty() {
self.store.remove_speaker_name(id, speaker_key)
} else {
self.store.set_speaker_name(id, speaker_key, name)
};
result.map_err(|e| format!("Name konnte nicht gespeichert werden: {e}"))
}
/// Merges remote speaker `from_key` of call `id` into `into_key`; both
/// must speak in the call's transcript.
pub fn merge_speakers(&self, id: CallId, from_key: &str, into_key: &str) -> Result<(), String> {
self.find_call(id)?;
let segments = self.store.segments(id).map_err(|e| e.to_string())?;
for key in [from_key, into_key] {
if !segments.iter().any(|s| s.speaker.key() == key) {
return Err(format!("Unbekannter Sprecher: {key}"));
}
}
self.store
.set_speaker_merge(id, from_key, into_key)
.map_err(|e| e.to_string())
}
/// Undoes the merge of speaker `from_key` of call `id`.
pub fn unmerge_speaker(&self, id: CallId, from_key: &str) -> Result<(), String> {
self.find_call(id)?;
self.store
.remove_speaker_merge(id, from_key)
.map_err(|e| format!("Zusammenführung konnte nicht aufgehoben werden: {e}"))
}
/// Names call `id`; an empty or missing title clears the name.
pub fn rename_call(&self, id: CallId, title: Option<&str>) -> Result<(), String> {
self.find_call(id)?;
self.store.set_title(id, title).map_err(|e| e.to_string())
}
/// Records that call `id`'s transcript was just uploaded and the CRM
/// gave it `crm_transcript_id`.
pub fn mark_uploaded(&self, id: CallId, crm_transcript_id: &str) -> Result<(), String> {
self.find_call(id)?;
self.store
.set_uploaded(id, crm_transcript_id, &self.backend_url, Local::now())
.map_err(|e| format!("Upload konnte nicht vermerkt werden: {e}"))
}
fn find_call(&self, id: CallId) -> Result<Call, String> {
self.store
.get_call(id)
.map_err(|e| e.to_string())?
.ok_or_else(|| "Gespräch nicht gefunden".to_string())
}
/// Deletes a finished (or still undecided/failed) call: both audio files
/// and the row, cascading to its segments, speaker names, merges and
/// recorded remote jobs — this is also how a transcribed (`Done`) call's
/// "Löschen" removes it. Takes it out of the prompt queue and returns how
/// many calls still wait for it. Refused while the call is being
/// recorded, processed ([`AppState::claim_processing`]/
/// [`AppState::reserve_processing`] or status `Processing`), uploaded
/// ([`AppState::claim_upload`]), or while its DeepScript jobs are still
/// on record ([`DiscardError::CleanupPending`]).
pub fn discard_call(&self, id: CallId) -> Result<usize, DiscardError> {
if lock(&self.current)
.as_ref()
.is_some_and(|cur| cur.call_id == id)
{
return Err("Das Gespräch wird gerade aufgenommen".to_string().into());
}
// Both held until the call is gone, so neither a pipeline run nor an
// upload can claim it meanwhile (same uploading -> store lock order
// as `claim_upload`, so this can never deadlock against it).
let processing = lock(&self.processing);
if processing.contains(&id) {
return Err(ALREADY_PROCESSING.to_string().into());
}
let uploading = lock(&self.uploading);
if uploading.contains(&id) {
return Err(ALREADY_UPLOADING.to_string().into());
}
let call = self
.store
.get_call(id)
.map_err(|e| e.to_string())?
.ok_or_else(|| "Gespräch nicht gefunden".to_string())?;
if call.status == CallStatus::Processing {
return Err(ALREADY_PROCESSING.to_string().into());
}
let remote_jobs = self.store.remote_jobs(id).map_err(|e| e.to_string())?;
if !remote_jobs.is_empty() {
return Err(DiscardError::CleanupPending);
}
// Files first: if one cannot be deleted, the row stays so the user
// can try again instead of leaving orphaned audio behind. Already
// gone (e.g. removed by retention) is not an error.
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}").into())
}
}
}
// Unqueue before deleting the row, so the prompt never sees a queued
// call whose row is gone; put it back if the delete fails.
let position = self.remove_queued_prompt(id);
if let Err(e) = self.store.delete_call(id) {
if let Some(index) = position {
let mut queue = lock(&self.pending_prompts);
if !queue.contains(&id) {
let index = index.min(queue.len());
queue.insert(index, id);
}
}
return Err(format!("Gespräch konnte nicht gelöscht werden: {e}").into());
}
drop(uploading);
drop(processing);
self.remove_playback(id);
Ok(self.prompts_waiting())
}
/// Reserves `id` for one pipeline run; release it with
/// [`AppState::release_processing`] when the run ends. A call that waits
/// for the decision can be processed; a failed one only on `retry`, or
/// while the prompt still shows it (its first attempt failed before
/// anything started, e.g. for lack of an API key).
pub fn claim_processing(&self, id: CallId, retry: bool) -> Result<(), String> {
let mut processing = lock(&self.processing);
if processing.contains(&id) {
return Err(ALREADY_PROCESSING.to_string());
}
let call = self
.store
.get_call(id)
.map_err(|e| e.to_string())?
.ok_or_else(|| "Gespräch nicht gefunden".to_string())?;
match call.status {
CallStatus::AwaitingDecision => {}
CallStatus::Failed if retry || lock(&self.pending_prompts).contains(&id) => {}
CallStatus::Processing => return Err(ALREADY_PROCESSING.to_string()),
CallStatus::Recording => return Err("Das Gespräch wird gerade aufgenommen".to_string()),
CallStatus::Done => return Err("Das Gespräch ist bereits transkribiert".to_string()),
CallStatus::Failed => {
return Err("Das Gespräch wartet nicht auf eine Entscheidung".to_string())
}
}
processing.insert(id);
Ok(())
}
/// Reserves `id` for a cleanup of its remote jobs, whatever its status;
/// `false` if a run or cleanup already has it. Release it with
/// [`AppState::release_processing`].
pub fn reserve_processing(&self, id: CallId) -> bool {
lock(&self.processing).insert(id)
}
/// Ends the pipeline run claimed by [`AppState::claim_processing`] (or
/// the cleanup reserved by [`AppState::reserve_processing`]).
pub fn release_processing(&self, id: CallId) {
lock(&self.processing).remove(&id);
}
/// Whether a recording runs or starts, or a call is being processed (or
/// its remote jobs cleaned up). An update must not be installed then:
/// the installer ends the app.
pub fn recording_or_processing(&self) -> bool {
self.devices_busy.load(Ordering::SeqCst)
|| lock(&self.current).is_some()
|| !lock(&self.processing).is_empty()
}
/// Records both configured devices into a temporary directory for five
/// seconds and returns the peak level of each track.
pub fn test_devices(&self) -> Result<DeviceLevels, String> {
let _claim = self.claim_devices("Während einer Aufnahme ist kein Test möglich")?;
let settings = self.settings();
let dir = tempfile::tempdir()
.map_err(|e| format!("Testordner konnte nicht angelegt werden: {e}"))?;
let mic = recorder_audio::mic_source(settings.mic_device.as_deref());
let out = recorder_audio::output_source(output_target(&settings));
let recorder = Recorder::start(
mic,
out,
&dir.path().join("test-mic.wav"),
&dir.path().join("test-out.wav"),
)
.map_err(|e| format!("Test fehlgeschlagen: {e}"))?;
let mut peak = DeviceLevels { mic: 0.0, out: 0.0 };
let until = Instant::now() + TEST_DURATION;
while Instant::now() < until {
thread::sleep(TEST_POLL);
let (mic, out) = recorder.levels();
peak.mic = peak.mic.max(mic);
peak.out = peak.out.max(out);
}
recorder.discard();
Ok(peak)
}
/// Reserves the audio devices for a recording start or a test. Fails
/// with `recording_msg` while a recording runs.
fn claim_devices(&self, recording_msg: &str) -> Result<DevicesClaim<'_>, String> {
if self.devices_busy.swap(true, Ordering::SeqCst) {
return Err("Die Audiogeräte werden gerade getestet oder gestartet".to_string());
}
let claim = DevicesClaim(&self.devices_busy);
// Checked after claiming: a start that just finished has already
// stored its recording before releasing the claim.
if lock(&self.current).is_some() {
return Err(recording_msg.to_string());
}
Ok(claim)
}
fn track_paths(&self, id: CallId) -> (PathBuf, PathBuf) {
(
self.recordings_dir.join(format!("{id}-mic.wav")),
self.recordings_dir.join(format!("{id}-out.wav")),
)
}
}
/// The output a detected call is recorded from: the configured output
/// device, else the device on which the call app (`exe`, `root_pid`) has an
/// active render session, else the default communications device. Always
/// device loopback: new Teams plays call audio from a process outside the
/// ms-teams.exe tree, so loopback of that process tree recorded silence.
fn detected_output_target(
output_device: Option<&str>,
sessions: &[RenderSession],
exe: &str,
root_pid: u32,
) -> OutputTarget {
if let Some(id) = output_device {
log::info!("out track: configured output device {id}");
return OutputTarget::Device(id.to_string());
}
match recorder_audio::render_endpoint_for(sessions, exe, root_pid) {
Some(session) => {
log::info!(
"out track: call app playing on {} ({})",
session.device_name,
session.device_id
);
OutputTarget::Device(session.device_id.clone())
}
None => {
log::info!("out track: no render session of {exe} found, using communications default");
OutputTarget::DefaultRender
}
}
}
fn save(settings: &Settings, path: &Path) -> Result<(), String> {
settings
.save(path)
.map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))
}
fn output_target(settings: &Settings) -> OutputTarget {
match &settings.output_device {
Some(id) => OutputTarget::Device(id.clone()),
None => OutputTarget::DefaultRender,
}
}
/// Locks ignoring poisoning: a panic in one command must not wedge the app.
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[cfg(test)]
mod tests {
use chrono::TimeZone;
use recorder_core::backend::{KeyInfo, NewKey, StoredKey};
use recorder_core::model::{Segment, Speaker};
use recorder_core::secrets::{MemorySecrets, Service};
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"),
dir.path().join("playback"),
);
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
/// (`<name>-mic.wav`, `<name>-out.wav`).
fn finished_call(f: &Fixture, name: &str) -> (CallId, PathBuf, PathBuf) {
let mic = f.dir.path().join(format!("{name}-mic.wav"));
let out = f.dir.path().join(format!("{name}-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, "a");
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());
}
fn queued(f: &Fixture) -> Option<(CallId, usize)> {
f.state
.pending_prompt()
.map(|prompt| (prompt.brief.id, prompt.more_waiting))
}
#[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, "a");
f.state.queue_prompt(id);
assert_eq!(queued(&f), Some((id, 0)));
assert_eq!(
f.state.pending_prompt().map(|p| p.brief),
Some(f.state.call_brief(id).unwrap())
);
f.state.store.delete_call(id).unwrap();
assert_eq!(f.state.pending_prompt(), None);
}
#[test]
fn prompts_queue_up_in_order() {
let f = fixture();
let (first, _, _) = finished_call(&f, "a");
let (second, _, _) = finished_call(&f, "b");
f.state.queue_prompt(first);
f.state.queue_prompt(second);
f.state.queue_prompt(first); // queued once only
assert_eq!(queued(&f), Some((first, 1)));
// Deciding the first shows the second.
assert_eq!(f.state.discard_call(first), Ok(1));
assert_eq!(queued(&f), Some((second, 0)));
assert_eq!(f.state.discard_call(second), Ok(0));
assert_eq!(queued(&f), None);
}
#[test]
fn a_queued_call_is_decided_by_id_not_by_position() {
let f = fixture();
let (a, _, _) = finished_call(&f, "a");
let (b, _, _) = finished_call(&f, "b");
let (c, _, _) = finished_call(&f, "c");
for id in [a, b, c] {
f.state.queue_prompt(id);
}
assert_eq!(f.state.discard_call(b), Ok(2));
assert_eq!(queued(&f), Some((a, 1)));
assert_eq!(f.state.remove_queued_prompt(a), Some(0));
assert_eq!(queued(&f), Some((c, 0)));
assert_eq!(f.state.remove_queued_prompt(a), None);
}
#[test]
fn a_vanished_call_is_skipped() {
let f = fixture();
let (gone, _, _) = finished_call(&f, "a");
let (next, _, _) = finished_call(&f, "b");
f.state.queue_prompt(gone);
f.state.queue_prompt(next);
f.state.store.delete_call(gone).unwrap();
assert_eq!(queued(&f), Some((next, 0)));
}
#[test]
fn discard_call_deletes_audio_and_row_and_clears_the_prompt() {
let f = fixture();
let (id, mic, out) = finished_call(&f, "a");
f.state.queue_prompt(id);
assert_eq!(f.state.discard_call(id), Ok(0));
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_an_unqueued_call_keeps_the_prompt() {
let f = fixture();
let (pending, _, _) = finished_call(&f, "a");
f.state.queue_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(1));
assert_eq!(f.state.store.get_call(other).unwrap(), None);
assert_eq!(queued(&f), Some((pending, 0)));
}
#[test]
fn discarding_an_unqueued_call_reports_an_empty_queue() {
// The prompt window hides whenever nothing is left, even if the
// discarded call had already dropped out of the queue.
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
assert_eq!(f.state.discard_call(id), Ok(0));
assert_eq!(f.state.prompts_waiting(), 0);
}
#[test]
fn a_call_being_processed_is_not_discarded() {
let f = fixture();
let (id, mic, out) = finished_call(&f, "a");
f.state.queue_prompt(id);
f.state.claim_processing(id, false).unwrap();
assert_eq!(
f.state.discard_call(id),
Err(DiscardError::Other("Wird bereits verarbeitet".to_string()))
);
f.state.release_processing(id);
f.state
.store
.set_status(id, CallStatus::Processing, None)
.unwrap();
assert_eq!(
f.state.discard_call(id),
Err(DiscardError::Other("Wird bereits verarbeitet".to_string()))
);
assert!(mic.exists());
assert!(out.exists());
assert!(f.state.store.get_call(id).unwrap().is_some());
assert_eq!(f.state.prompts_waiting(), 1);
}
#[test]
fn a_call_with_recorded_remote_jobs_is_not_discarded() {
let f = fixture();
let (id, mic, out) = finished_call(&f, "a");
f.state.queue_prompt(id);
f.state
.store
.set_status(id, CallStatus::Failed, Some("Fehler"))
.unwrap();
f.state.store.record_remote_job(id, "mic", "job-1").unwrap();
assert_eq!(f.state.discard_call(id), Err(DiscardError::CleanupPending));
assert_eq!(
DiscardError::CleanupPending.to_string(),
"Daten bei DeepScript werden noch gelöscht – bitte später erneut versuchen."
);
assert!(mic.exists());
assert!(out.exists());
assert!(f.state.store.get_call(id).unwrap().is_some());
assert_eq!(f.state.store.remote_jobs(id).unwrap().len(), 1);
assert_eq!(f.state.prompts_waiting(), 1);
// Not reserved: the cleanup the command starts can take the call.
assert!(f.state.reserve_processing(id));
}
#[test]
fn a_transcribed_call_is_deleted_like_any_other() {
let f = fixture();
let (id, mic, out) = finished_call(&f, "a");
f.state
.store
.set_status(id, CallStatus::Done, None)
.unwrap();
assert_eq!(f.state.discard_call(id), Ok(0));
assert!(!mic.exists());
assert!(!out.exists());
assert_eq!(f.state.store.get_call(id).unwrap(), None);
}
#[test]
fn a_call_being_uploaded_is_not_discarded() {
let f = fixture();
let (id, mic, out) = finished_call(&f, "a");
f.state
.store
.set_status(id, CallStatus::Done, None)
.unwrap();
let claim = f.state.claim_upload(id).unwrap();
assert_eq!(
f.state.discard_call(id),
Err(DiscardError::Other("Wird bereits hochgeladen".to_string()))
);
assert!(mic.exists());
assert!(out.exists());
assert!(f.state.store.get_call(id).unwrap().is_some());
// Once the upload is done, the delete goes through.
drop(claim);
assert_eq!(f.state.discard_call(id), Ok(0));
}
#[test]
fn a_call_already_uploaded_here_is_deleted_without_touching_the_crm() {
let f = fixture();
let (id, mic, out) = finished_call(&f, "a");
f.state
.store
.set_status(id, CallStatus::Done, None)
.unwrap();
f.state.mark_uploaded(id, "4711").unwrap();
assert_eq!(f.state.discard_call(id), Ok(0));
assert!(!mic.exists());
assert!(!out.exists());
assert_eq!(f.state.store.get_call(id).unwrap(), None);
}
#[test]
fn a_cleanup_reserves_a_call_of_any_status() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state
.store
.set_status(id, CallStatus::Done, None)
.unwrap();
assert!(f.state.reserve_processing(id));
assert!(!f.state.reserve_processing(id));
f.state
.store
.set_status(id, CallStatus::Failed, Some("Fehler"))
.unwrap();
assert_eq!(
f.state.claim_processing(id, true),
Err("Wird bereits verarbeitet".to_string())
);
f.state.release_processing(id);
assert!(f.state.reserve_processing(id));
}
#[test]
fn a_call_is_processed_once_at_a_time() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
assert_eq!(f.state.claim_processing(id, false), Ok(()));
assert_eq!(
f.state.claim_processing(id, true),
Err("Wird bereits verarbeitet".to_string())
);
f.state.release_processing(id);
assert_eq!(f.state.claim_processing(id, false), Ok(()));
}
#[test]
fn a_processing_call_is_not_claimed_again() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state
.store
.set_status(id, CallStatus::Processing, None)
.unwrap();
assert_eq!(
f.state.claim_processing(id, true),
Err("Wird bereits verarbeitet".to_string())
);
}
#[test]
fn a_failed_call_is_processed_again_on_retry_or_from_the_prompt() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state
.store
.set_status(id, CallStatus::Failed, Some("Fehler"))
.unwrap();
assert!(f.state.claim_processing(id, false).is_err());
assert_eq!(f.state.claim_processing(id, true), Ok(()));
f.state.release_processing(id);
f.state.queue_prompt(id);
assert_eq!(f.state.claim_processing(id, false), Ok(()));
}
#[test]
fn an_update_waits_while_a_call_is_processed() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
assert!(!f.state.recording_or_processing());
f.state.claim_processing(id, false).unwrap();
assert!(f.state.recording_or_processing());
f.state.release_processing(id);
assert!(!f.state.recording_or_processing());
}
#[test]
fn an_update_waits_while_a_recording_starts() {
let f = fixture();
let claim = f
.state
.claim_devices("Es läuft bereits eine Aufnahme")
.unwrap();
assert!(f.state.recording_or_processing());
drop(claim);
assert!(!f.state.recording_or_processing());
}
#[test]
fn done_and_recording_calls_are_not_processed() {
let f = fixture();
let (done, _, _) = finished_call(&f, "a");
f.state
.store
.set_status(done, CallStatus::Done, None)
.unwrap();
assert!(f.state.claim_processing(done, true).is_err());
let recording = f
.state
.store
.create_call("Manuell", at(9, 0, 0), Path::new(""), Path::new(""))
.unwrap();
assert!(f.state.claim_processing(recording, true).is_err());
assert!(f.state.claim_processing(recording + 1, true).is_err());
}
#[test]
fn call_list_is_newest_first_with_durations() {
let f = fixture();
let (older, _, _) = finished_call(&f, "a");
let newer = f
.state
.store
.create_call("Manuell", at(11, 0, 0), Path::new(""), Path::new(""))
.unwrap();
let list = f.state.call_list().unwrap();
let rows: Vec<_> = list
.iter()
.map(|item| (item.id, item.status, item.duration_secs))
.collect();
assert_eq!(
rows,
[
(newer, CallStatus::Recording, 0),
(older, CallStatus::AwaitingDecision, 32 * 60 + 30),
]
);
}
#[test]
fn call_detail_shows_the_transcript_with_renamed_speakers() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state
.store
.save_segments(
id,
&[
Segment {
speaker: Speaker::Me,
start: 0.0,
end: 1.5,
text: "Guten Tag.".into(),
},
Segment {
speaker: Speaker::Remote(1),
start: 2.0,
end: 3.0,
text: "Hallo.".into(),
},
],
)
.unwrap();
f.state
.rename_speaker(id, "remote:1", "Frau Probe")
.unwrap();
let detail = f.state.call_detail(id).unwrap();
assert_eq!(detail.call.item.id, id);
let labels: Vec<_> = detail.segments.iter().map(|s| s.label.as_str()).collect();
assert_eq!(labels, ["Ich", "Frau Probe"]);
assert!(f.state.call_detail(id + 1).is_err());
}
#[test]
fn renaming_a_speaker_trims_and_an_empty_name_restores_the_default() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
let names = |f: &Fixture| f.state.store.speaker_names(id).unwrap();
f.state
.rename_speaker(id, "remote:2", " Herr Test ")
.unwrap();
assert_eq!(
names(&f).get("remote:2").map(String::as_str),
Some("Herr Test")
);
f.state.rename_speaker(id, "remote:2", " ").unwrap();
assert!(names(&f).is_empty());
}
#[test]
fn renaming_needs_a_known_speaker_and_call() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
assert!(f.state.rename_speaker(id, "remote:x", "Name").is_err());
assert!(f.state.rename_speaker(id + 1, "me", "Name").is_err());
assert!(f.state.store.speaker_names(id).unwrap().is_empty());
}
/// A finished call whose transcript has "Ich" and remote speakers 1 and 2.
fn transcribed_call(f: &Fixture) -> CallId {
let (id, _, _) = finished_call(f, "a");
let line = |speaker, start: f64, text: &str| Segment {
speaker,
start,
end: start + 1.0,
text: text.into(),
};
f.state
.store
.save_segments(
id,
&[
line(Speaker::Remote(1), 0.0, "Guten Tag,"),
line(Speaker::Remote(2), 1.5, "hier Weingut Beispiel."),
line(Speaker::Me, 3.0, "Hallo."),
],
)
.unwrap();
id
}
fn transcript(f: &Fixture, id: CallId) -> Vec<(String, String)> {
f.state
.call_detail(id)
.unwrap()
.segments
.into_iter()
.map(|s| (s.label, s.text))
.collect()
}
#[test]
fn merging_speakers_joins_their_lines_until_undone() {
let f = fixture();
let id = transcribed_call(&f);
let before = transcript(&f, id);
f.state.merge_speakers(id, "remote:2", "remote:1").unwrap();
assert_eq!(
transcript(&f, id),
[
(
"Sprecher 1".into(),
"Guten Tag, hier Weingut Beispiel.".into()
),
("Ich".into(), "Hallo.".into()),
]
);
assert_eq!(f.state.call_detail(id).unwrap().merges.len(), 1);
f.state.unmerge_speaker(id, "remote:2").unwrap();
assert_eq!(transcript(&f, id), before);
assert!(f.state.call_detail(id).unwrap().merges.is_empty());
}
#[test]
fn merging_needs_a_known_call_and_speakers_of_the_call() {
let f = fixture();
let id = transcribed_call(&f);
let merge = |from, into| f.state.merge_speakers(id, from, into);
assert_eq!(
f.state.merge_speakers(id + 1, "remote:2", "remote:1"),
Err("Gespräch nicht gefunden".to_string())
);
assert_eq!(
merge("remote:x", "remote:1"),
Err("Unbekannter Sprecher: remote:x".to_string())
);
assert_eq!(
merge("remote:2", "remote:3"),
Err("Unbekannter Sprecher: remote:3".to_string())
);
assert!(merge("me", "remote:1").is_err());
merge("remote:2", "remote:1").unwrap();
assert_eq!(
merge("remote:1", "remote:2"),
Err("Diese Zuordnung würde eine Schleife ergeben".to_string())
);
assert!(f.state.unmerge_speaker(id + 1, "remote:2").is_err());
assert_eq!(f.state.store.speaker_merges(id).unwrap().len(), 1);
}
#[test]
fn a_call_is_named_and_the_name_cleared() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
let title = |f: &Fixture| f.state.call_list().unwrap()[0].title.clone();
f.state.rename_call(id, Some(" Angebot Rioja ")).unwrap();
assert_eq!(title(&f).as_deref(), Some("Angebot Rioja"));
assert_eq!(
f.state.call_detail(id).unwrap().call.item.title.as_deref(),
Some("Angebot Rioja")
);
assert_eq!(
f.state.rename_call(id, Some(&"x".repeat(121))),
Err("Titel zu lang (max. 120 Zeichen)".to_string())
);
f.state.rename_call(id, Some("")).unwrap();
assert_eq!(title(&f), None);
assert_eq!(
f.state.rename_call(id + 1, Some("Test")),
Err("Gespräch nicht gefunden".to_string())
);
}
#[test]
fn invalid_detection_delays_are_not_saved() {
let f = fixture();
let invalid = Settings {
end_after_secs: 2,
..Settings::default()
};
assert_eq!(
f.state.save_settings(invalid),
Err("Ende nach: 3–120 Sekunden".to_string())
);
assert_eq!(f.state.settings(), Settings::default());
assert!(!f.dir.path().join("settings.json").exists());
let valid = Settings {
end_after_secs: 30,
..Settings::default()
};
assert_eq!(f.state.save_settings(valid.clone()), Ok(()));
assert_eq!(f.state.settings(), valid);
}
fn new_key(key: &str) -> NewKey {
NewKey {
key: key.into(),
expires_at: Local.with_ymd_and_hms(2027, 11, 6, 10, 0, 0).unwrap(),
}
}
const BASE: &str = crate::backend::BACKEND_URL;
#[test]
fn a_stored_backend_key_comes_with_its_login_and_server() {
let f = fixture();
assert_eq!(f.state.backend_key(), None);
f.state
.store_backend_key(
&new_key("euv_k"),
&format!("{BASE}/"),
Some("hinrichs".into()),
)
.unwrap();
let expires_at = Local.with_ymd_and_hms(2027, 11, 6, 10, 0, 0).unwrap();
assert_eq!(
f.state.backend_key(),
Some(StoredKey {
key: "euv_k".into(),
expires_at: Some(expires_at),
})
);
let saved = Settings::load(&f.dir.path().join("settings.json"));
assert_eq!(saved.backend_username.as_deref(), Some("hinrichs"));
assert_eq!(saved.backend_key_expires_at, Some(expires_at));
assert_eq!(saved.backend_key_base_url.as_deref(), Some(BASE));
assert!(!fs::read_to_string(f.dir.path().join("settings.json"))
.unwrap()
.contains("euv_k"));
assert_eq!(f.state.settings(), saved);
}
#[test]
fn a_key_of_another_server_is_not_stored() {
let f = fixture();
let err = f
.state
.store_backend_key(&new_key("euv_k"), "https://other.example", None)
.unwrap_err();
assert!(err.contains("anderen Server"), "{err}");
assert_eq!(f.state.secrets.get(Service::Backend), None);
assert_eq!(f.state.settings(), Settings::default());
}
#[test]
fn a_stored_key_of_another_server_is_discarded_before_use() {
for recorded in [Some("https://other.example"), None] {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
.unwrap();
// As if stored by a build for another backend.
f.state
.update_settings(|s| s.backend_key_base_url = recorded.map(str::to_string))
.unwrap();
assert_eq!(f.state.backend_key(), None, "{recorded:?}");
assert_eq!(f.state.secrets.get(Service::Backend), None);
let settings = f.state.settings();
assert_eq!(settings.backend_username, None);
assert_eq!(settings.backend_key_expires_at, None);
assert_eq!(settings.backend_key_base_url, None);
}
}
/// The real transition the review asked to lock in: a key created while
/// this install talked to the test backend must not work once the same
/// install is a release build talking to the production backend — it is
/// discarded and a fresh login is required, exactly like any other
/// backend mismatch above, but with the two real build-time constants
/// instead of a placeholder domain.
#[test]
fn a_key_from_the_test_backend_does_not_work_for_a_release_build() {
let mut f = fixture();
// A build on the test backend (what `cargo tauri dev` is), whatever
// profile this test itself runs in.
f.state.backend_url = crate::backend::DEV_BACKEND_URL.to_string();
f.state
.store_backend_key(
&new_key("euv_test"),
crate::backend::DEV_BACKEND_URL,
Some("hinrichs".into()),
)
.unwrap();
assert!(f.state.backend_key().is_some());
// Same keyring entry and settings file; now read as a release build
// would (a different `backend_url`, nothing else changed).
f.state.backend_url = crate::backend::RELEASE_BACKEND_URL.to_string();
assert_eq!(
f.state.backend_key(),
None,
"a test-backend key must not work for the release backend"
);
assert_eq!(f.state.secrets.get(Service::Backend), None);
let settings = f.state.settings();
assert_eq!(settings.backend_username, None);
assert_eq!(settings.backend_key_base_url, None);
}
#[test]
fn the_backend_login_is_refreshed_from_the_key_info() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), BASE, None)
.unwrap();
let later = Local.with_ymd_and_hms(2028, 1, 1, 0, 0, 0).unwrap();
f.state
.refresh_backend_login(&KeyInfo {
label: "l".into(),
hint: "h".into(),
username: "hinrichs".into(),
created_at: later,
expires_at: later,
})
.unwrap();
let settings = f.state.settings();
assert_eq!(settings.backend_username.as_deref(), Some("hinrichs"));
assert_eq!(settings.backend_key_expires_at, Some(later));
assert_eq!(settings.backend_key_base_url.as_deref(), Some(BASE));
}
#[test]
fn a_discarded_backend_key_is_gone_with_its_login() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
.unwrap();
f.state.discard_backend_key().unwrap();
assert_eq!(f.state.backend_key(), None);
assert_eq!(f.state.secrets.get(Service::Backend), None);
let settings = f.state.settings();
assert_eq!(settings.backend_username, None);
assert_eq!(settings.backend_key_expires_at, None);
assert_eq!(settings.backend_key_base_url, None);
}
#[test]
fn only_the_refused_key_is_discarded() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_new"), BASE, None)
.unwrap();
// A login stored a new key after the old one was refused.
assert_eq!(f.state.discard_refused_backend_key("euv_old"), Ok(false));
assert_eq!(
f.state.backend_key().map(|k| k.key).as_deref(),
Some("euv_new")
);
assert_eq!(f.state.discard_refused_backend_key("euv_new"), Ok(true));
assert_eq!(f.state.backend_key(), None);
assert_eq!(f.state.settings().backend_key_base_url, None);
}
#[test]
fn saving_settings_keeps_the_backend_login() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
.unwrap();
// The settings page sends what it loaded, maybe before the login.
let edited = Settings {
retention_days: 14,
..Settings::default()
};
assert_eq!(f.state.save_settings(edited), Ok(()));
assert!(f.state.backend_key().is_some());
let settings = f.state.settings();
assert_eq!(settings.backend_username.as_deref(), Some("hinrichs"));
assert_eq!(settings.backend_key_base_url.as_deref(), Some(BASE));
assert_eq!(settings.retention_days, 14);
}
#[test]
fn the_backend_is_fixed_per_build() {
let f = fixture();
// Debug builds (`cargo tauri dev`, `cargo test`) use the test
// backend, release builds the production one.
let expected = if cfg!(debug_assertions) {
"https://test.euvinopro.eu"
} else {
"https://backend.euvinopro.eu"
};
assert_eq!(f.state.backend_url(), expected);
assert_eq!(
f.state.backend_client().login_url(),
format!("{expected}/euvadm")
);
}
#[test]
fn a_call_is_uploaded_once_at_a_time() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
let (other, _, _) = finished_call(&f, "b");
assert!(!f.state.call_detail(id).unwrap().uploading);
let claim = f.state.claim_upload(id).unwrap();
assert!(f.state.is_uploading(id));
assert!(f.state.call_detail(id).unwrap().uploading);
assert_eq!(
f.state.claim_upload(id).err(),
Some("Wird bereits hochgeladen".to_string())
);
assert!(f.state.claim_upload(other).is_ok(), "other calls are free");
drop(claim);
assert!(!f.state.is_uploading(id));
assert!(f.state.claim_upload(id).is_ok());
}
#[test]
fn a_call_already_uploaded_is_not_claimed_again() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state.mark_uploaded(id, "4711").unwrap();
assert_eq!(
f.state.claim_upload(id).err(),
Some("Bereits hochgeladen".to_string())
);
assert!(!f.state.is_uploading(id));
}
/// The real case the review asked to lock in: a call uploaded to the
/// test backend is refused for upload by a build whose own backend is
/// the test backend (the normal case, above), but uploadable again by a
/// build whose backend is the production one — the CRM at that backend
/// has never seen this transcript.
#[test]
fn an_upload_to_another_backend_is_not_counted_as_uploaded_here() {
let mut f = fixture();
let (id, _, _) = finished_call(&f, "a");
// A build on the test backend (what `cargo tauri dev` is), whatever
// profile this test itself runs in: mark_uploaded records it.
f.state.backend_url = crate::backend::DEV_BACKEND_URL.to_string();
f.state.mark_uploaded(id, "4711").unwrap();
assert_eq!(
f.state.find_call(id).unwrap().crm_base_url.as_deref(),
Some(crate::backend::DEV_BACKEND_URL)
);
assert_eq!(
f.state.claim_upload(id).err(),
Some("Bereits hochgeladen".to_string())
);
// The same row, now read as a release build would be: a different
// backend, nothing else changed.
f.state.backend_url = crate::backend::RELEASE_BACKEND_URL.to_string();
assert!(f.state.claim_upload(id).is_ok());
}
#[test]
fn an_upload_confirmed_but_unsaved_is_never_retried() {
// The CRM has the transcript, but mark_uploaded failed: the row
// itself still shows no crm_transcript_id.
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state.note_upload_confirmed_but_unsaved(id);
assert!(f
.state
.call_detail(id)
.unwrap()
.call
.item
.crm_transcript_id
.is_none());
assert_eq!(
f.state.claim_upload(id).err(),
Some("Bereits hochgeladen".to_string())
);
assert!(!f.state.is_uploading(id));
}
#[test]
fn an_upload_is_recorded_on_the_call() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state.mark_uploaded(id, "4711").unwrap();
let call = f.state.store.get_call(id).unwrap().unwrap();
assert_eq!(call.crm_transcript_id.as_deref(), Some("4711"));
assert_eq!(call.crm_base_url.as_deref(), Some(BASE));
assert!(call.uploaded_at.is_some());
assert_eq!(
f.state.mark_uploaded(id + 1, "1"),
Err("Gespräch nicht gefunden".to_string())
);
}
fn render_session(exe: &str, root_pid: u32, device: &str) -> RenderSession {
RenderSession {
exe: exe.to_string(),
pid: root_pid + 1,
root_pid,
active: true,
device_id: format!("id-{device}"),
device_name: device.to_string(),
}
}
#[test]
fn detected_calls_record_the_device_the_call_app_plays_on() {
let sessions = [
render_session("spotify.exe", 50, "Lautsprecher"),
render_session("ms-teams.exe", 100, "Headset"),
];
assert_eq!(
detected_output_target(None, &sessions, "ms-teams.exe", 100),
OutputTarget::Device("id-Headset".into())
);
}
#[test]
fn detected_calls_without_a_render_session_record_the_default_device() {
let sessions = [render_session("spotify.exe", 50, "Lautsprecher")];
assert_eq!(
detected_output_target(None, &sessions, "ms-teams.exe", 100),
OutputTarget::DefaultRender
);
}
#[test]
fn a_configured_output_device_wins_for_detected_calls() {
let sessions = [render_session("ms-teams.exe", 100, "Headset")];
assert_eq!(
detected_output_target(Some("id-Lautsprecher"), &sessions, "ms-teams.exe", 100),
OutputTarget::Device("id-Lautsprecher".into())
);
}
/// A finished call whose tracks hold real audio: one second on the mic,
/// half a second on the output.
fn playable_call(f: &Fixture, name: &str) -> CallId {
let (id, mic, out) = finished_call(f, name);
for (path, samples) in [(&mic, 16_000), (&out, 8_000)] {
let mut writer = recorder_core::audio::TrackWriter::create(path).unwrap();
writer.write(&vec![0.1; samples]).unwrap();
writer.finalize().unwrap();
}
id
}
fn playback_file(f: &Fixture, id: CallId) -> PathBuf {
f.dir.path().join("playback").join(format!("{id}.wav"))
}
#[test]
fn a_finished_call_is_mixed_into_the_playback_cache() {
let f = fixture();
let id = playable_call(&f, "a");
assert!(f.state.call_detail(id).unwrap().audio_available);
let prepared = f.state.prepare_playback(id).unwrap();
assert!((prepared.duration_secs - 1.0).abs() < 1e-9);
assert!(playback_file(&f, id).exists());
}
#[test]
fn the_player_holding_the_latest_lease_removes_the_mix() {
let f = fixture();
let id = playable_call(&f, "a");
let first = f.state.prepare_playback(id).unwrap().lease;
// The call was shown again before the first player let go.
let second = f.state.prepare_playback(id).unwrap().lease;
assert_ne!(first, second);
f.state.release_playback(id, first);
assert!(
playback_file(&f, id).exists(),
"the second player still plays"
);
f.state.release_playback(id, second);
assert!(!playback_file(&f, id).exists());
f.state.release_playback(id, second); // already gone: no error
// A lease of one call never removes another call's mix.
let other = playable_call(&f, "b");
let lease = f.state.prepare_playback(other).unwrap().lease;
f.state.release_playback(id, lease);
assert!(playback_file(&f, other).exists());
}
#[test]
fn missing_files_are_no_audio_but_not_deleted_audio() {
let f = fixture();
let (id, mic, out) = finished_call(&f, "a"); // a few junk bytes each
let detail = f.state.call_detail(id).unwrap();
assert!(!detail.audio_available);
assert!(!detail.audio_deleted);
fs::remove_file(mic).unwrap();
fs::remove_file(out).unwrap();
assert_eq!(
f.state.prepare_playback(id),
Err(playback::AUDIO_MISSING.to_string())
);
}
#[test]
fn recording_and_processing_calls_are_not_played() {
let f = fixture();
let dir = f.dir.path();
let recording = f
.state
.store
.create_call(
"Microsoft Teams",
at(10, 0, 0),
&dir.join("r-mic.wav"),
&dir.join("r-out.wav"),
)
.unwrap();
assert_eq!(
f.state.prepare_playback(recording),
Err(playback::RECORDING.to_string())
);
let processing = playable_call(&f, "p");
f.state
.store
.set_status(processing, CallStatus::Processing, None)
.unwrap();
assert_eq!(
f.state.prepare_playback(processing),
Err(playback::PROCESSING.to_string())
);
assert!(!playback_file(&f, processing).exists());
assert_eq!(
f.state.prepare_playback(999),
Err("Gespräch nicht gefunden".to_string())
);
}
#[test]
fn deleted_audio_is_not_played_and_its_mix_is_removed() {
let f = fixture();
let id = playable_call(&f, "a");
f.state.prepare_playback(id).unwrap();
// What the retention sweep does to a transcribed call's audio.
let call = f.state.store.get_call(id).unwrap().unwrap();
fs::remove_file(&call.mic_path).unwrap();
fs::remove_file(&call.out_path).unwrap();
f.state.store.mark_audio_deleted(id).unwrap();
let detail = f.state.call_detail(id).unwrap();
assert!(!detail.audio_available);
assert!(detail.audio_deleted);
assert_eq!(
f.state.prepare_playback(id),
Err(playback::AUDIO_GONE.to_string())
);
assert!(!playback_file(&f, id).exists());
}
#[test]
fn deleting_a_call_removes_its_mix() {
let f = fixture();
let id = playable_call(&f, "a");
let other = playable_call(&f, "b");
f.state.prepare_playback(id).unwrap();
f.state.prepare_playback(other).unwrap();
f.state.discard_call(id).unwrap();
assert!(!playback_file(&f, id).exists());
assert!(playback_file(&f, other).exists());
assert_eq!(
f.state.prepare_playback(id),
Err("Gespräch nicht gefunden".to_string())
);
}
#[test]
fn the_playback_cache_is_emptied_at_startup() {
let f = fixture();
let id = playable_call(&f, "a");
f.state.prepare_playback(id).unwrap();
f.state.clear_playback_cache();
assert!(!f.dir.path().join("playback").exists());
f.state.clear_playback_cache(); // nothing left: no error
}
}