diff --git a/crates/core/src/pipeline.rs b/crates/core/src/pipeline.rs index 0ba42b0..282d02e 100644 --- a/crates/core/src/pipeline.rs +++ b/crates/core/src/pipeline.rs @@ -217,13 +217,14 @@ pub async fn delete_remote_jobs(store: &Store, tr: &dyn Transcriber, id: CallId) /// in this run, in case recording one failed). Forgets the recorded jobs /// only if all of them were deleted, so a later run tries again. async fn delete_jobs(store: &Store, tr: &dyn Transcriber, id: CallId, known: &[String]) { - let mut jobs: Vec = match store.remote_jobs(id) { + let recorded: Vec = match store.remote_jobs(id) { Ok(jobs) => jobs.into_iter().map(|(_, remote_id)| remote_id).collect(), Err(e) => { log::error!("call {id}: could not read remote jobs: {e}"); Vec::new() } }; + let mut jobs = recorded.clone(); for job in known { if !jobs.contains(job) { jobs.push(job.clone()); @@ -237,10 +238,18 @@ async fn delete_jobs(store: &Store, tr: &dyn Transcriber, id: CallId, known: &[S for job in &jobs { if let Err(e) = tr.delete(job).await { all_deleted = false; - log::warn!( - "call {id}: deleting remote job {job} failed: {}", - e.user_message() - ); + if recorded.contains(job) { + log::warn!( + "call {id}: deleting remote job {job} failed: {}", + e.user_message() + ); + } else { + // Not on record: nothing will try again. + log::error!( + "call {id}: deleting unrecorded remote job {job} failed, it stays at DeepScript: {}", + e.user_message() + ); + } } } if all_deleted { diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index db91f29..8ff1821 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -17,7 +17,9 @@ use tauri::{AppHandle, Emitter, Manager, State}; use tauri_plugin_autostart::ManagerExt; use crate::processing; -use crate::state::{AppState, CallBrief, DeviceLevels, Ended, PendingPrompt, RecordingState}; +use crate::state::{ + AppState, CallBrief, DeviceLevels, DiscardError, Ended, PendingPrompt, RecordingState, +}; const LEVELS_INTERVAL: Duration = Duration::from_millis(100); @@ -118,10 +120,19 @@ pub fn get_call_brief(state: State<'_, AppState>, id: CallId) -> CmdResult CmdResult<()> { blocking(app, move |app| { - app.state::().discard_call(id)?; + match app.state::().discard_call(id) { + Ok(_) => {} + Err(e @ DiscardError::CleanupPending) => { + processing::delete_leftover_jobs(app, vec![id]); + return Err(e.to_string()); + } + Err(e @ DiscardError::Other(_)) => return Err(e.to_string()), + } prompt_queue_changed(app); Ok(()) }) diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 5a33195..a442349 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -35,6 +35,32 @@ const TEST_DURATION: Duration = Duration::from_secs(5); const TEST_POLL: Duration = Duration::from_millis(50); const ALREADY_PROCESSING: &str = "Wird bereits verarbeitet"; +/// 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 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")] @@ -400,18 +426,20 @@ impl AppState { /// Deletes a finished call: both audio files and the row, and takes it /// out of the prompt queue. Returns how many calls still wait for the - /// prompt. A call that is being processed is not deleted. - pub fn discard_call(&self, id: CallId) -> Result { + /// prompt. A call that is being processed, or whose DeepScript jobs + /// are still on record ([`DiscardError::CleanupPending`]), is not + /// deleted. + pub fn discard_call(&self, id: CallId) -> Result { if lock(&self.current) .as_ref() .is_some_and(|cur| cur.call_id == id) { - return Err("Das Gespräch wird gerade aufgenommen".to_string()); + return Err("Das Gespräch wird gerade aufgenommen".to_string().into()); } // Held until the call is gone, so no run can claim it meanwhile. let processing = lock(&self.processing); if processing.contains(&id) { - return Err(ALREADY_PROCESSING.to_string()); + return Err(ALREADY_PROCESSING.to_string().into()); } let call = self .store @@ -419,7 +447,11 @@ impl AppState { .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()); + 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. @@ -430,7 +462,9 @@ impl AppState { 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}")), + 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 @@ -444,7 +478,7 @@ impl AppState { queue.insert(index, id); } } - return Err(format!("Gespräch konnte nicht gelöscht werden: {e}")); + return Err(format!("Gespräch konnte nicht gelöscht werden: {e}").into()); } drop(processing); Ok(self.prompts_waiting()) @@ -733,7 +767,7 @@ mod tests { assert_eq!( f.state.discard_call(id), - Err("Wird bereits verarbeitet".to_string()) + Err(DiscardError::Other("Wird bereits verarbeitet".to_string())) ); f.state.release_processing(id); f.state @@ -742,7 +776,7 @@ mod tests { .unwrap(); assert_eq!( f.state.discard_call(id), - Err("Wird bereits verarbeitet".to_string()) + Err(DiscardError::Other("Wird bereits verarbeitet".to_string())) ); assert!(mic.exists()); @@ -751,6 +785,32 @@ mod tests { 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_cleanup_reserves_a_call_of_any_status() { let f = fixture();