fix #14740: attribute teams helper processes, queue end-of-call prompts

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hauke
2026-11-05 15:48:55 +01:00
co-authored by Claude Opus 5.5
parent d631252600
commit bac30205d6
7 changed files with 527 additions and 93 deletions
+13 -12
View File
@@ -16,7 +16,7 @@ use serde::Serialize;
use tauri::{AppHandle, Emitter, Manager, State};
use tauri_plugin_autostart::ManagerExt;
use crate::state::{AppState, CallBrief, DeviceLevels, Ended, RecordingState};
use crate::state::{AppState, CallBrief, DeviceLevels, Ended, PendingPrompt, RecordingState};
const LEVELS_INTERVAL: Duration = Duration::from_millis(100);
@@ -106,7 +106,7 @@ pub async fn discard_current_recording(app: AppHandle) -> CmdResult<()> {
/// 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> {
pub fn get_pending_prompt(state: State<'_, AppState>) -> Option<PendingPrompt> {
state.pending_prompt()
}
@@ -115,12 +115,13 @@ pub fn get_call_brief(state: State<'_, AppState>, id: CallId) -> CmdResult<CallB
state.call_brief(id)
}
/// Deletes a finished call's audio and row; closes the prompt if it asked
/// about this call.
/// Deletes a finished call's audio and row. If that was the last call the
/// prompt was waiting on, closes the prompt; otherwise the prompt reloads
/// and shows the next one.
#[tauri::command]
pub async fn discard_call(app: AppHandle, id: CallId) -> CmdResult<()> {
blocking(app, move |app| {
if app.state::<AppState>().discard_call(id)? {
if app.state::<AppState>().discard_call(id)? == Some(0) {
set_window_visible(app, "prompt", false);
}
Ok(())
@@ -152,13 +153,13 @@ pub fn start_detected(app: &AppHandle, name: &str, root_pid: u32) -> CmdResult<C
Ok(call_id)
}
/// Stops the current recording at the user's request (■ Stopp). Stopping
/// a detected call also keeps detection from restarting it until the call
/// Stops the current recording at the user's request (■ Stopp), manual or
/// detected. Detection then leaves the ongoing call alone 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) {
if ended.is_some() {
state.suppress_detected_call();
}
after_stop(app, ended)
@@ -173,12 +174,12 @@ pub fn end_detected_call(app: &AppHandle) {
}
}
/// Throws the current recording away. Never shows the prompt; a discarded
/// detected call is not detected again until the call app releases the mic.
/// Throws the current recording away. Never shows the prompt; detection
/// then leaves the ongoing call alone until the call app releases the mic.
pub fn discard(app: &AppHandle) -> CmdResult<()> {
let state = app.state::<AppState>();
let ended = state.discard_current_recording();
if ended.as_ref().is_some_and(|ended| ended.detected) {
if ended.is_some() {
state.suppress_detected_call();
}
sync_recorder_window(app);
@@ -202,7 +203,7 @@ fn after_stop(app: &AppHandle, ended: Option<Ended>) -> CmdResult<()> {
};
ended.result?;
let id = ended.call_id;
app.state::<AppState>().set_pending_prompt(id);
app.state::<AppState>().queue_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}");
+130 -12
View File
@@ -3,7 +3,9 @@
//! 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
//! Detection keeps running during a manual recording: a call it finds then
//! is already being recorded by hand, so it is only suppressed (see
//! [`decide`]). Only Windows reports microphone sessions; elsewhere the loop runs but
//! never detects anything.
use std::thread;
@@ -46,27 +48,50 @@ pub fn spawn(app: AppHandle) {
}
}
/// What to do about one detector event.
#[derive(Debug, PartialEq, Eq)]
enum Action {
/// Record the detected call.
Start {
app: String,
root_pid: u32,
},
/// A manual recording already covers the call: only keep the detector
/// from re-detecting it until the app releases the mic.
Suppress,
/// Stop the detected recording (a manual one keeps running).
EndDetected,
Nothing,
}
fn decide(event: Option<DetectorEvent>, manual_recording: bool) -> Action {
match event {
Some(DetectorEvent::CallStarted { .. }) if manual_recording => Action::Suppress,
Some(DetectorEvent::CallStarted { app, root_pid, .. }) => Action::Start { app, root_pid },
Some(DetectorEvent::CallEnded) => Action::EndDetected,
None => Action::Nothing,
}
}
/// 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,
let event = state.detector_tick(Instant::now(), &sessions);
if let Some(DetectorEvent::CallStarted { exe, root_pid, .. }) = &event {
log::info!("call detected: {exe} (process tree {root_pid})");
}
match decide(event, state.manual_recording_running()) {
Action::Start {
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
@@ -74,11 +99,15 @@ fn poll(app: &AppHandle, last_sessions: &mut String) {
state.suppress_detected_call();
}
}
Some(DetectorEvent::CallEnded) => {
Action::Suppress => {
log::info!("call is already recorded manually");
state.suppress_detected_call();
}
Action::EndDetected => {
log::info!("call ended");
commands::end_detected_call(app);
}
None => {}
Action::Nothing => {}
}
}
@@ -95,3 +124,92 @@ fn describe(sessions: &[MicSession]) -> String {
parts.sort();
parts.join(", ")
}
#[cfg(test)]
mod tests {
use recorder_core::detect::{CallDetector, MicSession};
use super::*;
fn started() -> DetectorEvent {
DetectorEvent::CallStarted {
exe: "ms-teams.exe".into(),
app: "Microsoft Teams".into(),
root_pid: 100,
}
}
#[test]
fn a_call_found_during_a_manual_recording_is_only_suppressed() {
assert_eq!(decide(Some(started()), true), Action::Suppress);
assert_eq!(
decide(Some(started()), false),
Action::Start {
app: "Microsoft Teams".into(),
root_pid: 100
}
);
assert_eq!(
decide(Some(DetectorEvent::CallEnded), true),
Action::EndDetected
);
assert_eq!(decide(None, true), Action::Nothing);
}
/// One loop step against the real detector, without devices: returns
/// whether a detected recording would start.
fn step(detector: &mut CallDetector, now: Instant, teams_active: bool, manual: bool) -> bool {
let teams = MicSession {
exe: "ms-teams.exe".into(),
pid: 200,
root_pid: 100,
active: teams_active,
};
match decide(detector.tick(now, &[teams]), manual) {
Action::Start { .. } => true,
Action::Suppress => {
detector.manual_stop();
false
}
Action::EndDetected | Action::Nothing => false,
}
}
/// A manual recording made during a call: started by hand while the
/// detector is still pending, stopped by hand mid-call. No automatic
/// recording may follow until Teams releases the mic.
#[test]
fn manual_stop_mid_call_does_not_start_an_automatic_recording() {
let mut detector = CallDetector::new(detector_config(&Settings::default()));
let t0 = Instant::now();
let at = |secs| t0 + Duration::from_secs(secs);
let mut started = Vec::new();
if step(&mut detector, at(0), true, false) {
started.push(0);
}
// Recording started by hand while pending; detection keeps ticking.
for secs in 1..=10 {
if step(&mut detector, at(secs), true, true) {
started.push(secs);
}
}
// ■ Stopp on the manual recording.
detector.manual_stop();
for secs in 11..=30 {
if step(&mut detector, at(secs), true, false) {
started.push(secs);
}
}
assert!(started.is_empty(), "auto recording started at {started:?}");
// Once Teams releases the mic, the next call is detected again.
step(&mut detector, at(31), false, false);
for secs in 32..=36 {
if step(&mut detector, at(secs), true, false) {
started.push(secs);
}
}
assert_eq!(started, vec![35]);
}
}
+126 -49
View File
@@ -5,6 +5,7 @@
//! the end-of-call prompt. Everything here is independent of windows and
//! events; the command layer turns results into UI updates.
use std::collections::VecDeque;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
@@ -82,12 +83,18 @@ impl CallBrief {
}
}
/// 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,
/// 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>,
@@ -109,9 +116,10 @@ pub struct AppState {
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>>,
/// 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>>,
/// 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,
@@ -143,7 +151,7 @@ impl AppState {
recordings_dir,
current: Mutex::new(None),
detector: Mutex::new(detector),
pending_prompt: Mutex::new(None),
pending_prompts: Mutex::new(VecDeque::new()),
devices_busy: AtomicBool::new(false),
}
}
@@ -303,7 +311,6 @@ impl AppState {
});
Some(Ended {
call_id: id,
detected: cur.detected,
result,
})
}
@@ -320,33 +327,51 @@ impl AppState {
.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);
/// 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 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
/// 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 how many calls
/// are still queued, 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(queue.len())
}
pub fn call_brief(&self, id: CallId) -> Result<CallBrief, String> {
let call = self
.store
@@ -356,9 +381,10 @@ impl AppState {
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> {
/// 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<Option<usize>, String> {
if lock(&self.current)
.as_ref()
.is_some_and(|cur| cur.call_id == id)
@@ -385,12 +411,7 @@ impl AppState {
self.store
.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)
Ok(self.remove_queued_prompt(id))
}
/// Records both configured devices into a temporary directory for five
@@ -486,10 +507,11 @@ mod tests {
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");
/// 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;
@@ -503,7 +525,7 @@ mod tests {
#[test]
fn call_brief_has_app_times_and_duration() {
let f = fixture();
let (id, _, _) = finished_call(&f);
let (id, _, _) = finished_call(&f, "a");
assert_eq!(
f.state.call_brief(id).unwrap(),
CallBrief {
@@ -517,25 +539,80 @@ mod tests {
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);
f.state.set_pending_prompt(id);
assert_eq!(f.state.pending_prompt().map(|b| b.id), Some(id));
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(Some(1)));
assert_eq!(queued(&f), Some((second, 0)));
assert_eq!(f.state.discard_call(second), Ok(Some(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(Some(2)));
assert_eq!(queued(&f), Some((a, 1)));
assert_eq!(f.state.remove_queued_prompt(a), Some(1));
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);
f.state.set_pending_prompt(id);
let (id, mic, out) = finished_call(&f, "a");
f.state.queue_prompt(id);
assert_eq!(f.state.discard_call(id), Ok(true));
assert_eq!(f.state.discard_call(id), Ok(Some(0)));
assert!(!mic.exists());
assert!(!out.exists());
assert_eq!(f.state.store.get_call(id).unwrap(), None);
@@ -543,10 +620,10 @@ mod tests {
}
#[test]
fn discard_call_of_another_call_keeps_the_prompt() {
fn discard_call_of_an_unqueued_call_keeps_the_prompt() {
let f = fixture();
let (pending, _, _) = finished_call(&f);
f.state.set_pending_prompt(pending);
let (pending, _, _) = finished_call(&f, "a");
f.state.queue_prompt(pending);
let other = f
.state
.store
@@ -554,8 +631,8 @@ mod tests {
.unwrap();
// Missing track files are not an error.
assert_eq!(f.state.discard_call(other), Ok(false));
assert_eq!(f.state.discard_call(other), Ok(None));
assert_eq!(f.state.store.get_call(other).unwrap(), None);
assert_eq!(f.state.pending_prompt().map(|b| b.id), Some(pending));
assert_eq!(queued(&f), Some((pending, 0)));
}
}