From a16e4d4b93ef99e1dc9dde8d0fecdc27803e3f78 Mon Sep 17 00:00:00 2001 From: faumaray Date: Mon, 23 Nov 2026 08:21:09 +0300 Subject: [PATCH] voelin-gpui: harden push-to-talk and global hotkey transmit state machine Track the window hold-to-talk button (`button_held`) beside the global hotkey (`hotkey_held`) and a `shutting_down` flag in `AppState`, closing Security Review MEDIUM #2 and Opus gate probes P1, P2, P3, P4, P5, P6, and P8: - `stop_transmitting_if_unheld`, `release_button_hold`, and `release_hotkey_hold` keep transmit active while either source holds the session and avoid duplicate start/stop commands (P6). - `hotkey_transmit(true)` on a different connected server stops the previous held session before starting the new one (Security MEDIUM #2 / P2), while `select_server` preserves `hotkey_held` (P2b) and releases `button_held` when the held server leaves the screen (P8). - `handle_events` checks `Connected -> !Connected` transitions per event inside the batch loop so a drop and reconnect within one 64-event batch still releases both holds and emits `SetTransmitting(false)` once (P3). - `setting_changed` releases `button_held` when `audio.transmit` leaves `PushToTalk` (P1/P1b); `delete_bookmark` clears holds on the removed session (P4); `shutdown` sets `shutting_down`, drops `ptt`, and releases both holds before closing sessions, ignoring late `Later` presses (P5). - `Sidebar` clears `holding` whenever voice disconnects, transmit leaves push-to-talk, the shown server changes, or `AppState::button_held` no longer matches; `MainView`'s focus-loss observer unconditionally releases `Sidebar` and `AppState::push_to_talk(false)` without cutting `hotkey_held`. Co-Authored-By: Gemini 4 Neon --- crates/voelin-gpui/src/app.rs | 315 ++++++++++++++++++--- crates/voelin-gpui/src/shell/sidebar.rs | 27 +- crates/voelin-gpui/src/view.rs | 13 +- crates/voelin-gpui/src/view/voice_tests.rs | 225 ++++++++++++++- 4 files changed, 526 insertions(+), 54 deletions(-) diff --git a/crates/voelin-gpui/src/app.rs b/crates/voelin-gpui/src/app.rs index a978530..720a130 100644 --- a/crates/voelin-gpui/src/app.rs +++ b/crates/voelin-gpui/src/app.rs @@ -42,7 +42,7 @@ use gpui_kit::{ClipboardItem, Context}; use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; use tracing::{debug, warn}; use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings}; -use voelin_core::{Command, Engine, Event, VoiceState}; +use voelin_core::{Command, Engine, Event, TransmitMode, VoiceState}; use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, Store}; use voelin_ui_vm::bridge::{BookmarkForm, ChatLine}; use voelin_ui_vm::events; @@ -270,6 +270,12 @@ pub struct AppState { ptt_status: String, /// The session the hotkey turned transmit on for and has not turned off. hotkey_held: Option, + /// The session the window's hold-to-talk button turned transmit on for and + /// has not turned off. + button_held: Option, + /// The window is closing: ignore late push-to-talk presses (such as one + /// already queued from the hotkey task through [`Later`]). + shutting_down: bool, /// Where the sample servers' pictures were written (`VOELIN_DEMO_UI`), /// removed with the state. demo_dir: Option, @@ -387,6 +393,8 @@ impl AppState { ptt: None, ptt_status: String::new(), hotkey_held: None, + button_held: None, + shutting_down: false, demo_dir: None, later: Later(later), #[cfg(test)] @@ -514,54 +522,86 @@ impl AppState { cx: &mut Context, ) { let mut refresh = Refresh::default(); - let connected = self.connected_sessions(); for event in events { + let was_connected = match &event { + Event::State { session, .. } => { + let id = *session as i64; + self.is_voice_connected(id).then_some(id) + } + _ => None, + }; self.events_handled += 1; self.counters.engine_events.incr(); let update = self.handle(event); refresh.merge(self.perform(update, cx)); + if let Some(id) = was_connected { + self.release_lost_transmit(id); + } } - self.release_lost_transmit(&connected); self.counters.connections.set(self.connections() as u64); // Each area once for the whole batch. self.signals.raise(&refresh, cx); cx.notify(); } - /// The sessions whose voice is connected now. - fn connected_sessions(&self) -> Vec { - self.vm - .sessions - .iter() - .filter(|(_, view)| view.state.voice == VoiceState::Connected) - .map(|(&id, _)| id) - .collect() + /// Whether `id` currently has voice connected. + fn is_voice_connected(&self, id: i64) -> bool { + self.vm.sessions.get(&id).is_some_and(|view| view.state.voice == VoiceState::Connected) } - /// The release guard of Hold to talk, for voice that dropped: the key or - /// the button that was held when the connection went has nothing to be - /// released on (the voice card, with the button, goes with the voice, and - /// the session keeps `transmitting` until the next press), so the session - /// is told to stop transmitting once, for each session that was connected - /// before a batch of events and is not after it, if it still says it - /// transmits. The engine answers with a state without it, which this does - /// not answer again. - fn release_lost_transmit(&mut self, were_connected: &[i64]) { - for &id in were_connected { - let Some(view) = self.vm.sessions.get(&id) else { continue }; - if view.state.voice != VoiceState::Connected { - // The hotkey's hold is over with the voice; its release, when it - // comes, has nothing to end. - if self.hotkey_held == Some(id) { - self.hotkey_held = None; - } - if view.state.transmitting { - self.send(Command::SetTransmitting { session: id as u64, on: false }); - } + /// The release guard of Hold to talk and the global hotkey, for voice that + /// dropped: checked per event inside [`Self::handle_events`] so a drop and + /// reconnect in one batch cannot mask it. When `id` leaves `Connected`, any + /// active button or hotkey hold on it ends, and the session is told + /// `SetTransmitting(false)` once if either was held or the engine still + /// reports it transmitting. + fn release_lost_transmit(&mut self, id: i64) { + let Some(view) = self.vm.sessions.get(&id) else { return }; + if view.state.voice != VoiceState::Connected { + let mut was_held = false; + if self.hotkey_held == Some(id) { + self.hotkey_held = None; + was_held = true; + } + if self.button_held == Some(id) { + self.button_held = None; + was_held = true; + } + if was_held || view.state.transmitting { + self.send(Command::SetTransmitting { session: id as u64, on: false }); } } } + /// Which session the window's hold-to-talk button is holding, if any. + pub(crate) fn button_held(&self) -> Option { + self.button_held + } + + /// Stop transmitting in `id` once neither the window's button nor the global + /// hotkey holds it. + fn stop_transmitting_if_unheld(&self, id: i64) { + if self.hotkey_held != Some(id) && self.button_held != Some(id) { + self.send(Command::SetTransmitting { session: id as u64, on: false }); + } + } + + /// Release the window button's hold, stopping transmit if the global hotkey + /// does not also hold the same session. Returns whether a hold was active. + fn release_button_hold(&mut self) -> bool { + let Some(id) = self.button_held.take() else { return false }; + self.stop_transmitting_if_unheld(id); + true + } + + /// Release the global hotkey's hold, stopping transmit if the window button + /// does not also hold the same session. Returns whether a hold was active. + fn release_hotkey_hold(&mut self) -> bool { + let Some(id) = self.hotkey_held.take() else { return false }; + self.stop_transmitting_if_unheld(id); + true + } + /// One engine event ([`AppState::handle_events`]). pub fn handle_event(&mut self, event: Event, cx: &mut Context) { self.handle_events([event], cx); @@ -752,6 +792,9 @@ impl AppState { VoelinTheme::set_font_scale(cx, scale); } else if key == AUDIO.name() && !self.vm.audio_dirty { self.vm.audio = self.backend.prefs.get(&AUDIO); + if self.vm.audio.transmit != TransmitMode::PushToTalk { + self.release_button_hold(); + } refresh.toolbar = true; } else if key == CLIENT_PLAYBACK.name() { self.vm.playback = self.backend.prefs.get(&CLIENT_PLAYBACK); @@ -885,6 +928,9 @@ impl AppState { self.transition_with(cx, |state, cx, backing| { sequence::select_server(state, cx, backing, id) }); + if self.button_held.is_some_and(|held| Some(held) != self.vm.current) { + self.release_button_hold(); + } cx.notify(); } @@ -933,8 +979,24 @@ impl AppState { /// Start or stop transmitting (the window's hold-to-talk button). pub fn push_to_talk(&mut self, on: bool, cx: &mut Context) { - self.command(|session| Command::SetTransmitting { session, on }); - cx.notify(); + if on { + if self.shutting_down { + return; + } + let Some(id) = self.vm.current else { return }; + if let Some(old) = self.button_held.replace(id) { + if old == id { + return; + } + self.stop_transmitting_if_unheld(old); + } + if self.hotkey_held != Some(id) { + self.send(Command::SetTransmitting { session: id as u64, on: true }); + } + cx.notify(); + } else if self.release_button_hold() { + cx.notify(); + } } /// The voice channel page on or off (`show_voice_view` of @@ -1025,23 +1087,29 @@ impl AppState { /// The global push-to-talk key went down or up. It transmits into the /// session on screen while that has voice, and the release ends that same /// session's transmit, whichever is on screen by then (a server chosen - /// while the key is down). A press without voice does nothing. + /// while the key is down). A repeated press on another connected server + /// ends the first session's transmit before starting the new one. A press + /// without voice, or during shutdown, does nothing. pub fn hotkey_transmit(&mut self, on: bool, cx: &mut Context) { if on { - let connected = self.vm.current.filter(|id| { - self.vm - .sessions - .get(id) - .is_some_and(|view| view.state.voice == VoiceState::Connected) - }); + if self.shutting_down { + return; + } + let connected = self.vm.current.filter(|&id| self.is_voice_connected(id)); let Some(id) = connected else { return }; - if self.hotkey_held.replace(id) != Some(id) { + if let Some(old) = self.hotkey_held.replace(id) { + if old == id { + return; + } + self.stop_transmitting_if_unheld(old); + } + if self.button_held != Some(id) { self.send(Command::SetTransmitting { session: id as u64, on: true }); } - } else if let Some(id) = self.hotkey_held.take() { - self.send(Command::SetTransmitting { session: id as u64, on: false }); + cx.notify(); + } else if self.release_hotkey_hold() { + cx.notify(); } - cx.notify(); } /// A link to the voice channel we are in, copied to the clipboard with a @@ -1276,6 +1344,12 @@ impl AppState { cx.notify(); return; } + if self.hotkey_held == Some(id) { + self.hotkey_held = None; + } + if self.button_held == Some(id) { + self.button_held = None; + } self.transition_with(cx, |state, cx, backing| { sequence::delete_bookmark(state, cx, backing, id) }); @@ -1323,6 +1397,10 @@ impl AppState { /// the engine time to act on them before the runtime goes (none without an /// engine, none in demo mode). pub fn shutdown(&mut self, cx: &mut Context) -> usize { + self.shutting_down = true; + self.ptt = None; + self.release_button_hold(); + self.release_hotkey_hold(); self.flush_window(); // The sample pictures are not needed once the window is closing. if let Some(folder) = self.demo_dir.take() { @@ -2085,6 +2163,155 @@ mod tests { assert_eq!(transmits(&app, cx), [], "the release has nothing to end"); } + /// A second hotkey press without a release between them, after switching to + /// another connected server (a portal that repeats `Activated`), ends the + /// first session's transmit before starting the new one. + #[gpui::test] + fn a_second_hotkey_press_on_another_server_releases_the_first(cx: &mut TestAppContext) { + let (app, tx, _) = entity_over( + cx, + backend_with(&[ + ("Nightfall", "ts.example"), + ("Lounge", "lounge.example"), + ("Offline", "off.example"), + ]), + Switches::default(), + ); + let [first, second, third] = app.read_with(cx, |app, _| { + [app.vm.bookmarks[0].id, app.vm.bookmarks[1].id, app.vm.bookmarks[2].id] + }); + for id in [first, second] { + tx.send(Event::State { + session: id as u64, + state: SessionState { voice: VoiceState::Connected, ..Default::default() }, + }) + .unwrap(); + } + cx.run_until_parked(); + transmits(&app, cx); + + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + app.update(cx, |app, cx| app.select_server(second, cx)); + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!( + transmits(&app, cx), + [ + (first as u64, true), + (first as u64, false), + (second as u64, true), + (second as u64, false) + ], + "switching connected servers under repeated Activated stops the old session first" + ); + + // Switching to an offline server and getting a repeated press leaves the + // active hold intact so the real release still ends it. + app.update(cx, |app, cx| app.select_server(first, cx)); + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + app.update(cx, |app, cx| app.select_server(third, cx)); + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&app, cx), [(first as u64, true), (first as u64, false)]); + } + + /// Deleting a bookmarked server clears any button or hotkey hold on it so a + /// subsequent release does not send a stale command to the closed session. + #[gpui::test] + fn removing_a_server_clears_active_transmit_holds(cx: &mut TestAppContext) { + let (app, tx, _) = entity_over( + cx, + backend_with(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]), + Switches::default(), + ); + let [first, second] = + app.read_with(cx, |app, _| [app.vm.bookmarks[0].id, app.vm.bookmarks[1].id]); + for id in [first, second] { + tx.send(Event::State { + session: id as u64, + state: SessionState { voice: VoiceState::Connected, ..Default::default() }, + }) + .unwrap(); + } + cx.run_until_parked(); + transmits(&app, cx); + + app.update(cx, |app, cx| { + app.hotkey_transmit(true, cx); + app.push_to_talk(true, cx); + }); + assert_eq!(transmits(&app, cx), [(first as u64, true)]); + + app.update(cx, |app, cx| app.delete_bookmark(first, cx)); + let sent = app.read_with(cx, |app, _| app.take_sent()); + assert!( + sent.iter().any( + |c| matches!(c, Command::CloseSession { session } if *session == first as u64) + ), + "{sent:?}" + ); + + app.update(cx, |app, cx| { + app.hotkey_transmit(false, cx); + app.push_to_talk(false, cx); + }); + assert_eq!(transmits(&app, cx), [], "no stale release to the deleted session"); + + app.update(cx, |app, cx| { + app.hotkey_transmit(true, cx); + app.hotkey_transmit(false, cx); + }); + assert_eq!(transmits(&app, cx), [(second as u64, true), (second as u64, false)]); + } + + /// Closing the window releases any active hotkey or button hold and ignores + /// late presses queued through `Later` after shutdown. + #[gpui::test] + fn closing_releases_a_held_transmit_and_ignores_late_presses(cx: &mut TestAppContext) { + // Hotkey held during shutdown + late release/press queued on `Later`. + let (app, tx, _) = + entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id = app.read_with(cx, |app, _| app.vm.bookmarks[0].id) as u64; + tx.send(Event::State { + session: id, + state: SessionState { voice: VoiceState::Connected, ..Default::default() }, + }) + .unwrap(); + cx.run_until_parked(); + transmits(&app, cx); + + app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + assert_eq!(transmits(&app, cx), [(id, true)]); + app.update(cx, |app, cx| app.shutdown(cx)); + assert_eq!(transmits(&app, cx), [(id, false)], "shutdown releases the held key"); + + let later = app.read_with(cx, |app, _| app.later()); + assert!(later.run(|app, cx| { + app.hotkey_transmit(false, cx); + app.hotkey_transmit(true, cx); + app.push_to_talk(true, cx); + })); + cx.run_until_parked(); + assert_eq!(transmits(&app, cx), [], "late presses after shutdown are ignored"); + + // Window button held during shutdown is released too. + let (app2, tx2, _) = + entity_over(cx, backend_with(&[("Nightfall", "ts.example")]), Switches::default()); + let id2 = app2.read_with(cx, |app, _| app.vm.bookmarks[0].id) as u64; + tx2.send(Event::State { + session: id2, + state: SessionState { voice: VoiceState::Connected, ..Default::default() }, + }) + .unwrap(); + cx.run_until_parked(); + transmits(&app2, cx); + + app2.update(cx, |app, cx| app.push_to_talk(true, cx)); + assert_eq!(transmits(&app2, cx), [(id2, true)]); + app2.update(cx, |app, cx| app.shutdown(cx)); + assert_eq!(transmits(&app2, cx), [(id2, false)], "shutdown releases the held button"); + } + /// Showing a server also observes it, invisibly, through the gateway it /// published or its own query login, as the Slint front end does. #[gpui::test] diff --git a/crates/voelin-gpui/src/shell/sidebar.rs b/crates/voelin-gpui/src/shell/sidebar.rs index b6591f9..60733b6 100644 --- a/crates/voelin-gpui/src/shell/sidebar.rs +++ b/crates/voelin-gpui/src/shell/sidebar.rs @@ -113,12 +113,21 @@ impl Sidebar { }; let subscriptions = signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| { - let view = SidebarView::of(app.read(cx)); - // The button goes with the voice card when voice leaves `Connected`, - // and the release has no element to land on: a hold that was - // started is over (the session is told by the root state, not by - // this observer, which only sets its own fields). - if !view.voice_connected { + let state = app.read(cx); + let view = SidebarView::of(state); + // The button goes away when voice leaves `Connected`, transmit + // leaves push-to-talk, or another server is shown; and a drop + // and reconnect inside one batch ends the hold in `AppState` + // while `view.voice_connected` stays true. Keep `holding` in + // sync with the root state's own button hold (this observer + // only sets its own fields). + let same_server = + view.server.as_ref().map(|s| s.id) == this.view.server.as_ref().map(|s| s.id); + let held_here = view + .server + .as_ref() + .is_some_and(|s| state.button_held() == Some(i64::from(s.id))); + if !view.voice_connected || !view.hold_to_talk || !same_server || !held_here { this.holding = false; } if view != this.view { @@ -134,6 +143,12 @@ impl Sidebar { &self.view } + /// Whether the hold-to-talk button is currently held down. + #[cfg(test)] + pub(crate) fn is_holding(&self) -> bool { + self.holding + } + /// Let go of the hold-to-talk button if it is held (the window lost the /// focus: the release will not come to it): whether it was held. The caller /// tells the session. diff --git a/crates/voelin-gpui/src/view.rs b/crates/voelin-gpui/src/view.rs index f85b6fb..d88b77a 100644 --- a/crates/voelin-gpui/src/view.rs +++ b/crates/voelin-gpui/src/view.rs @@ -153,9 +153,10 @@ impl MainView { if window.is_window_active() { return; } - if this.sidebar.update(cx, |sidebar, _| sidebar.release()) { - this.app.update(cx, |app, cx| app.push_to_talk(false, cx)); - } + this.sidebar.update(cx, |sidebar, _| { + let _ = sidebar.release(); + }); + this.app.update(cx, |app, cx| app.push_to_talk(false, cx)); }), cx.observe_window_bounds(window, |this, window, cx| { report(&this.app, window, cx); @@ -245,6 +246,12 @@ impl MainView { self.sidebar.read(cx).view().clone() } + /// Whether the sidebar's hold-to-talk button is held down. + #[cfg(test)] + pub(crate) fn sidebar_holding(&self, cx: &gpui_kit::App) -> bool { + self.sidebar.read(cx).is_holding() + } + /// The voice channel page. pub fn voice_page(&self) -> &Entity { &self.voice diff --git a/crates/voelin-gpui/src/view/voice_tests.rs b/crates/voelin-gpui/src/view/voice_tests.rs index 3b8e624..94f176f 100644 --- a/crates/voelin-gpui/src/view/voice_tests.rs +++ b/crates/voelin-gpui/src/view/voice_tests.rs @@ -17,7 +17,7 @@ use voelin_ui_vm::settings::{ CLIENT_PLAYBACK, ClientPlayback, ClientPlaybackMap, UI_VOICE_COMPACT, }; -use super::tests::{Shell, at, click, frame, open, sample_server}; +use super::tests::{Shell, at, click, connected, frame, open, sample_server}; use crate::backend::Backend; use crate::dev::Switches; @@ -505,6 +505,229 @@ fn the_global_hotkey_is_not_cut_by_the_window_losing_the_focus(cx: &mut TestAppC assert_eq!(transmits(&shell, cx), [false], "the key's release ends it"); } +/// Every `SetTransmitting` command sent since the last call, across all +/// sessions. +fn all_transmits(shell: &Shell, cx: &mut VisualTestContext) -> Vec<(u64, bool)> { + shell + .app + .read_with(cx, |app, _| app.take_sent()) + .into_iter() + .filter_map(|command| match command { + Command::SetTransmitting { session, on } => Some((session, on)), + _ => None, + }) + .collect() +} + +/// Leaving push-to-talk mode while the hold-to-talk button is pressed releases +/// transmit immediately and clears the sidebar's hold so neither a later click +/// nor focus loss emits a stray release (Opus gate P1 / P1b). +#[gpui::test] +fn leaving_push_to_talk_releases_a_held_button(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + let set_mode = |shell: &Shell, cx: &mut VisualTestContext, mode: TransmitMode| { + let audio = AudioSettings { transmit: mode, ..Default::default() }; + shell.app.read_with(cx, |app, _| app.backend().prefs.set(&AUDIO, audio).unwrap()); + setting_changed(shell, cx, AUDIO.name()); + }; + + let button = at(cx, "hold-to-talk").expect("the button"); + transmits(&shell, cx); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(transmits(&shell, cx), [true]); + shell.events.send(reported(VoiceState::Connected, true)).unwrap(); + frame(cx); + + set_mode(&shell, cx, TransmitMode::VoiceActivation); + assert!(at(cx, "hold-to-talk").is_none()); + assert!( + !shell.view.read_with(cx, |view, cx| view.sidebar_holding(cx)), + "sidebar cleared holding when leaving push-to-talk" + ); + assert_eq!(transmits(&shell, cx), [false], "mode change releases the button hold"); + + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING); + + // Returning to push-to-talk and clicking elsewhere sends nothing stale. + set_mode(&shell, cx, TransmitMode::PushToTalk); + assert!(at(cx, "hold-to-talk").is_some()); + let elsewhere = at(cx, "sidebar-server").expect("server card"); + cx.simulate_mouse_down(elsewhere.center(), MouseButton::Left, Default::default()); + cx.simulate_mouse_up(elsewhere.center(), MouseButton::Left, Default::default()); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "no stale hold left in sidebar"); + + // P1b: mode leaves push-to-talk and then window loses focus before returning. + let button = at(cx, "hold-to-talk").expect("the button"); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(transmits(&shell, cx), [true]); + set_mode(&shell, cx, TransmitMode::VoiceActivation); + assert_eq!(transmits(&shell, cx), [false]); + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + cx.deactivate_window(); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "focus loss has nothing left to release"); +} + +/// A voice drop and reconnect inside one event batch still releases a held +/// button and a held hotkey, and clears the sidebar's hold (Opus gate P3). +#[gpui::test] +fn a_drop_and_reconnect_in_one_batch_releases_a_held_button_and_hotkey(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + let button = at(cx, "hold-to-talk").expect("the button"); + transmits(&shell, cx); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + shell.events.send(reported(VoiceState::Connected, true)).unwrap(); + frame(cx); + assert_eq!(transmits(&shell, cx), [true]); + + shell.app.update(cx, |app, cx| { + app.handle_events( + [ + reported(VoiceState::Disconnected, true), + reported(VoiceState::Connecting, true), + reported(VoiceState::Connected, true), + ], + cx, + ); + }); + frame(cx); + assert_eq!(transmits(&shell, cx), [false], "drop inside the batch ends transmit once"); + assert!(at(cx, "hold-to-talk").is_some(), "reconnected within the batch"); + assert!( + !shell.view.read_with(cx, |view, cx| view.sidebar_holding(cx)), + "sidebar hold cleared even when voice reconnected inside the same batch" + ); + + // Releasing the mouse button now does nothing because the hold ended. + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "sidebar hold was cleared too"); + + // Same single-batch drop+reconnect while the global hotkey is held. + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + shell.events.send(reported(VoiceState::Connected, true)).unwrap(); + frame(cx); + assert_eq!(transmits(&shell, cx), [true]); + shell.app.update(cx, |app, cx| { + app.handle_events( + [ + reported(VoiceState::Disconnected, true), + reported(VoiceState::Connecting, true), + reported(VoiceState::Connected, true), + ], + cx, + ); + }); + frame(cx); + assert_eq!(transmits(&shell, cx), [false]); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&shell, cx), NOTHING); +} + +/// Holding the window button and the global hotkey at the same time keeps +/// transmitting until both have let go, in either order, without duplicate +/// commands (Opus gate P6). +#[gpui::test] +fn holding_the_button_and_the_hotkey_together_stops_only_when_both_let_go(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + let button = at(cx, "hold-to-talk").expect("the button"); + transmits(&shell, cx); + + // Button down, hotkey down, hotkey up (still held by button), button up. + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(transmits(&shell, cx), [true]); + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + assert_eq!(transmits(&shell, cx), NOTHING, "already transmitting"); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&shell, cx), NOTHING, "button still holds transmit"); + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + assert_eq!(transmits(&shell, cx), [false], "both released"); + + // Hotkey down, button down, button up (still held by hotkey), hotkey up. + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + assert_eq!(transmits(&shell, cx), [true]); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(transmits(&shell, cx), NOTHING); + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "hotkey still holds transmit"); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&shell, cx), [false]); + + // Both held, window loses focus: button releases, hotkey keeps holding. + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + assert_eq!(transmits(&shell, cx), [true]); + cx.deactivate_window(); + frame(cx); + assert_eq!(transmits(&shell, cx), NOTHING, "hotkey stays active across focus loss"); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(transmits(&shell, cx), [false]); +} + +/// Switching the server on screen releases a held hold-to-talk button (its +/// voice card leaves the screen) while leaving a global hotkey hold intact for +/// its own release (Opus gate P8 and P2b). +#[gpui::test] +fn switching_servers_releases_a_held_button_but_keeps_the_global_hotkey(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + let (a, b, offline) = (sample::DEMO, sample::DEMO + 1, sample::DEMO + 2); + shell.events.send(connected(b)).unwrap(); + frame(cx); + all_transmits(&shell, cx); + + // P8: button held on A, then current moves to an offline server. + let button = at(cx, "hold-to-talk").expect("the button"); + cx.simulate_mouse_down(button.center(), MouseButton::Left, Default::default()); + assert_eq!(all_transmits(&shell, cx), [(a as u64, true)]); + shell.app.update(cx, |app, cx| app.select_server(offline, cx)); + frame(cx); + assert_eq!(all_transmits(&shell, cx), [(a as u64, false)], "leaving A releases button hold"); + cx.simulate_mouse_up(button.center(), MouseButton::Left, Default::default()); + frame(cx); + cx.deactivate_window(); + frame(cx); + assert_eq!(all_transmits(&shell, cx), []); + + // P2b: global hotkey held on A, current switches to B, hotkey releases A. + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + shell.app.update(cx, |app, cx| app.select_server(a, cx)); + frame(cx); + shell.app.update(cx, |app, cx| app.hotkey_transmit(true, cx)); + shell.app.update(cx, |app, cx| app.select_server(b, cx)); + frame(cx); + assert_eq!(all_transmits(&shell, cx), [(a as u64, true)], "hotkey stays held across switch"); + shell.app.update(cx, |app, cx| app.hotkey_transmit(false, cx)); + assert_eq!(all_transmits(&shell, cx), [(a as u64, false)]); +} + +/// Window focus loss releases an active `AppState::push_to_talk` button hold +/// even if the sidebar's own flag was not set (guard in `MainView`). +#[gpui::test] +fn focus_loss_releases_app_button_hold_unconditionally(cx: &mut TestAppContext) { + let (shell, cx) = tall(cx, Switches::default()); + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); + transmits(&shell, cx); + shell.app.update(cx, |app, cx| app.push_to_talk(true, cx)); + assert_eq!(transmits(&shell, cx), [true]); + cx.deactivate_window(); + frame(cx); + assert_eq!(transmits(&shell, cx), [false]); +} + /// A setting changed elsewhere (a command, the config file) reaches the window. fn setting_changed(shell: &Shell, cx: &mut VisualTestContext, key: &str) { shell.events.send(Event::SettingChanged { key: key.into() }).unwrap();