diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index ab0f98d..a177f60 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -5,6 +5,7 @@ use std::fs; use std::io; +use std::ops::RangeInclusive; use std::path::Path; use serde::{Deserialize, Serialize}; @@ -19,6 +20,12 @@ const DEFAULT_ALLOWLIST: [&str; 6] = [ "firefox.exe", ]; +/// Allowed continuous mic use before a call counts as started, in seconds. +pub const START_AFTER_SECS: RangeInclusive = 1..=30; +/// Allowed mic release before a call counts as ended, in seconds. Too short +/// splits a call, e.g. when the headset is switched. +pub const END_AFTER_SECS: RangeInclusive = 3..=120; + #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[serde(default)] pub struct Settings { @@ -50,6 +57,25 @@ impl Default for Settings { } impl Settings { + /// Checks the values the user can type in; the error is shown as is. + pub fn validate(&self) -> Result<(), String> { + if !START_AFTER_SECS.contains(&self.start_after_secs) { + return Err(format!( + "Start nach: {}–{} Sekunden", + START_AFTER_SECS.start(), + START_AFTER_SECS.end() + )); + } + if !END_AFTER_SECS.contains(&self.end_after_secs) { + return Err(format!( + "Ende nach: {}–{} Sekunden", + END_AFTER_SECS.start(), + END_AFTER_SECS.end() + )); + } + Ok(()) + } + /// Reads the settings file. A missing or unreadable file yields the /// defaults; fields missing from the file take their default value. pub fn load(path: &Path) -> Settings { @@ -100,6 +126,41 @@ mod tests { assert_eq!(s.end_after_secs, 10); } + #[test] + fn validate_accepts_the_defaults_and_the_bounds() { + assert_eq!(Settings::default().validate(), Ok(())); + for (start, end) in [(1, 3), (30, 120)] { + let s = Settings { + start_after_secs: start, + end_after_secs: end, + ..Settings::default() + }; + assert_eq!(s.validate(), Ok(()), "start {start}, end {end}"); + } + } + + #[test] + fn validate_rejects_start_after_out_of_range() { + for start in [0, 31] { + let s = Settings { + start_after_secs: start, + ..Settings::default() + }; + assert_eq!(s.validate(), Err("Start nach: 1–30 Sekunden".to_string())); + } + } + + #[test] + fn validate_rejects_end_after_out_of_range() { + for end in [2, 121] { + let s = Settings { + end_after_secs: end, + ..Settings::default() + }; + assert_eq!(s.validate(), Err("Ende nach: 3–120 Sekunden".to_string())); + } + } + #[test] fn settings_load_missing_file_returns_default() { let dir = tempfile::tempdir().unwrap(); diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 11125c8..5459a5a 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -115,13 +115,12 @@ pub fn get_call_brief(state: State<'_, AppState>, id: CallId) -> CmdResult CmdResult<()> { blocking(app, move |app| { - if app.state::().discard_call(id)? == Some(0) { + if app.state::().discard_call(id)? == 0 { set_window_visible(app, "prompt", false); } Ok(()) diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 5808320..8a8e5fd 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -160,7 +160,10 @@ impl AppState { lock(&self.settings).clone() } + /// Validates, saves and applies the settings; the detector picks up the + /// new allowlist and delays immediately. pub fn save_settings(&self, settings: Settings) -> Result<(), String> { + settings.validate()?; settings .save(&self.settings_path) .map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))?; @@ -363,13 +366,18 @@ impl AppState { } } - /// Takes a decided call out of the prompt queue. Returns how many calls - /// are still queued, or `None` if `id` was not queued. + /// 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 { let mut queue = lock(&self.pending_prompts); let index = queue.iter().position(|&queued| queued == id)?; queue.remove(index); - Some(queue.len()) + 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 { @@ -382,9 +390,9 @@ impl AppState { } /// Deletes a finished call: both audio files and the row, and takes it - /// out of the prompt queue. Returns what - /// [`AppState::remove_queued_prompt`] returns. - pub fn discard_call(&self, id: CallId) -> Result, String> { + /// out of the prompt queue. Returns how many calls still wait for the + /// prompt. + pub fn discard_call(&self, id: CallId) -> Result { if lock(&self.current) .as_ref() .is_some_and(|cur| cur.call_id == id) @@ -408,10 +416,20 @@ impl AppState { Err(e) => return Err(format!("Audiodatei konnte nicht gelöscht werden: {e}")), } } - self.store - .delete_call(id) - .map_err(|e| format!("Gespräch konnte nicht gelöscht werden: {e}"))?; - Ok(self.remove_queued_prompt(id)) + // 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}")); + } + Ok(self.prompts_waiting()) } /// Records both configured devices into a temporary directory for five @@ -572,9 +590,9 @@ mod tests { assert_eq!(queued(&f), Some((first, 1))); // Deciding the first shows the second. - assert_eq!(f.state.discard_call(first), Ok(Some(1))); + assert_eq!(f.state.discard_call(first), Ok(1)); assert_eq!(queued(&f), Some((second, 0))); - assert_eq!(f.state.discard_call(second), Ok(Some(0))); + assert_eq!(f.state.discard_call(second), Ok(0)); assert_eq!(queued(&f), None); } @@ -588,9 +606,9 @@ mod tests { f.state.queue_prompt(id); } - assert_eq!(f.state.discard_call(b), Ok(Some(2))); + 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(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); } @@ -612,7 +630,7 @@ mod tests { let (id, mic, out) = finished_call(&f, "a"); f.state.queue_prompt(id); - assert_eq!(f.state.discard_call(id), Ok(Some(0))); + 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); @@ -631,8 +649,40 @@ mod tests { .unwrap(); // Missing track files are not an error. - assert_eq!(f.state.discard_call(other), Ok(None)); + 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 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); + } } diff --git a/ui/src/routes/Settings.svelte b/ui/src/routes/Settings.svelte index da9dd83..7a65888 100644 --- a/ui/src/routes/Settings.svelte +++ b/ui/src/routes/Settings.svelte @@ -80,8 +80,20 @@ if (settings) settings.allowlist = settings.allowlist.filter((a) => a !== name) } + /** Inline message for a delay in whole seconds outside `min`–`max`. */ + function delayError(value: number | null, min: number, max: number, label: string): string { + if (value !== null && Number.isInteger(value) && value >= min && value <= max) return '' + return `${label}: ${min}–${max} Sekunden` + } + + let startError = $derived( + settings ? delayError(settings.start_after_secs, 1, 30, 'Start nach') : '', + ) + let endError = $derived(settings ? delayError(settings.end_after_secs, 3, 120, 'Ende nach') : '') + async function persist() { if (!settings) return + if (startError || endError) throw startError || endError if (!Number.isInteger(settings.retention_days) || settings.retention_days < 1) { throw 'Aufbewahrung: bitte eine ganze Zahl ab 1 eingeben' } @@ -198,6 +210,44 @@ +
+

Anrufe erkennen

+
+ + + s + + {#if startError} + {startError} + {/if} + + + s + + + Zu kurz kann ein Gespräch aufteilen, z. B. beim Headset-Wechsel. + {#if endError} + {endError} + {/if} +
+
+

Allgemein

@@ -258,6 +308,10 @@ width: 70px; } + .grid input[aria-invalid='true'] { + border-color: var(--rec); + } + .grid input[type='checkbox'] { justify-self: start; }