mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:50:52 +00:00
Stop TUI voice calls when the OS session locks (#59330)
## What changed - Monitor session lock state on Linux, macOS, and Windows, checking the initial state before starting audio. - Abort local media on lock, including while connecting, retrying, or running a parked call, and display why voice stopped. - Keep lock monitoring across startup retries and ignore stale lock notifications after a call restarts. - Document lock behavior and platform limitations. After unlocking, users must run `/voice` to start a new call. ## Testing Add lifecycle tests for already-locked startup, parked-call media shutdown, stale notifications, and locks during retry cleanup, plus a macOS test for password grace-period expiry. GitOrigin-RevId: fea4b4a7903a48727c546ee3b7bd06e957a9b885
This commit is contained in:
committed by
copyberry
parent
19438adcb6
commit
93b4e5b4c6
@@ -5,6 +5,7 @@
|
||||
|
||||
mod failure_metrics;
|
||||
mod recording_controls;
|
||||
mod session_lock;
|
||||
mod transcript_replay;
|
||||
|
||||
pub(crate) use failure_metrics::RealtimeFailureCause;
|
||||
@@ -138,6 +139,7 @@ enum StartupRetry {
|
||||
#[derive(Default)]
|
||||
pub(super) struct RealtimeConversationUiState {
|
||||
startup_retry: StartupRetry,
|
||||
session_lock: Option<session_lock::SessionLock>,
|
||||
pub(super) phase: RealtimeConversationPhase,
|
||||
recover_late_transcripts: bool,
|
||||
attempt_id: u64,
|
||||
@@ -319,11 +321,18 @@ impl ChatWidget {
|
||||
NEXT_REALTIME_ATTEMPT_ID.fetch_add(1, Ordering::Relaxed);
|
||||
self.realtime_conversation.thread_id = Some(thread_id);
|
||||
let attempt_id = self.realtime_conversation.attempt_id;
|
||||
let (startup_abort, abort_registration) = AbortHandle::new_pair();
|
||||
self.realtime_conversation.startup_abort = Some(startup_abort);
|
||||
self.realtime_conversation.phase = RealtimeConversationPhase::Starting;
|
||||
self.update_realtime_footer();
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
let session_lock = self
|
||||
.realtime_conversation
|
||||
.session_lock
|
||||
.get_or_insert_with(|| {
|
||||
session_lock::SessionLock::observe(
|
||||
thread_id,
|
||||
self.app_event_tx.clone(),
|
||||
crate::session_lock::observe(),
|
||||
)
|
||||
});
|
||||
let selection = codex_realtime_webrtc::AudioDeviceSelection {
|
||||
microphone: audio.microphone,
|
||||
speaker: audio.speaker,
|
||||
@@ -331,7 +340,8 @@ impl ChatWidget {
|
||||
.microphone_channel
|
||||
.map(|channels| channels.as_slice().to_vec()),
|
||||
};
|
||||
std::thread::spawn(move || {
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
let startup_abort = session_lock.start_media(move |abort_registration| {
|
||||
let result =
|
||||
RealtimeWebrtcSession::start(abort_registration, selection).map_err(|error| {
|
||||
RealtimeWebrtcStartupFailure {
|
||||
@@ -348,10 +358,12 @@ impl ChatWidget {
|
||||
result,
|
||||
});
|
||||
});
|
||||
self.realtime_conversation.startup_abort = Some(startup_abort);
|
||||
self.request_redraw();
|
||||
}
|
||||
|
||||
pub(crate) fn stop_realtime_conversation(&mut self) {
|
||||
self.realtime_conversation.session_lock.take();
|
||||
self.realtime_conversation.startup_retry = StartupRetry::Used;
|
||||
if matches!(
|
||||
self.realtime_conversation.phase,
|
||||
@@ -392,6 +404,7 @@ impl ChatWidget {
|
||||
attempt_id: u64,
|
||||
result: Result<StartedRealtimeWebrtcSession, RealtimeWebrtcStartupFailure>,
|
||||
) {
|
||||
self.stop_if_session_locked();
|
||||
if self.realtime_conversation.phase != RealtimeConversationPhase::Starting
|
||||
|| self.realtime_conversation.attempt_id != attempt_id
|
||||
{
|
||||
@@ -478,6 +491,7 @@ impl ChatWidget {
|
||||
attempt_id: u64,
|
||||
result: Result<(), codex_realtime_webrtc::ConnectionError>,
|
||||
) {
|
||||
self.stop_if_session_locked();
|
||||
if self.realtime_conversation.phase != RealtimeConversationPhase::Starting
|
||||
|| self.realtime_conversation.attempt_id != attempt_id
|
||||
{
|
||||
@@ -1716,6 +1730,7 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
pub(super) fn on_realtime_conversation_closed(&mut self, reason: Option<String>) {
|
||||
self.stop_if_session_locked();
|
||||
if self.realtime_conversation.phase == RealtimeConversationPhase::Inactive {
|
||||
if self.realtime_conversation.recover_late_transcripts {
|
||||
self.finish_realtime_partial_transcripts();
|
||||
@@ -1757,8 +1772,11 @@ impl ChatWidget {
|
||||
self.record_realtime_failure(cause);
|
||||
}
|
||||
let failed = self.realtime_conversation.failure_recorded;
|
||||
let session_lock =
|
||||
retry_thread_id.and_then(|_| self.realtime_conversation.session_lock.take());
|
||||
self.reset_realtime_conversation();
|
||||
if let Some(thread_id) = retry_thread_id {
|
||||
self.realtime_conversation.session_lock = session_lock;
|
||||
// The old backend is closed. A late peer result belongs to its attempt ID.
|
||||
self.realtime_conversation.startup_retry = StartupRetry::Used;
|
||||
self.realtime_conversation.microphone_muted = muted;
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Owns one desktop observer across a call's startup retry and widget parking.
|
||||
//! Activation aborts local media before the TUI handles the wakeup; only current state may stop a call.
|
||||
|
||||
use super::ChatWidget;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_event_sender::AppEventSender;
|
||||
use crate::session_lock::Activation;
|
||||
use codex_protocol::ThreadId;
|
||||
use futures::FutureExt;
|
||||
use futures::future::AbortHandle;
|
||||
use futures::future::AbortRegistration;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum State {
|
||||
Initializing,
|
||||
Ready,
|
||||
Stopped(&'static str),
|
||||
}
|
||||
|
||||
pub(super) struct SessionLock {
|
||||
state: tokio::sync::watch::Receiver<State>,
|
||||
task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl SessionLock {
|
||||
pub(super) fn observe(
|
||||
thread_id: ThreadId,
|
||||
tx: AppEventSender,
|
||||
setup: impl Future<Output = anyhow::Result<Activation>> + Send + 'static,
|
||||
) -> Self {
|
||||
let (state_tx, state) = tokio::sync::watch::channel(State::Initializing);
|
||||
let task = tokio::spawn(async move {
|
||||
let result = match setup.await {
|
||||
Ok(mut activation) => match activation.as_mut().now_or_never() {
|
||||
Some(result) => result,
|
||||
None => {
|
||||
state_tx.send_replace(State::Ready);
|
||||
activation.await
|
||||
}
|
||||
},
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
let message = match result {
|
||||
Ok(()) => "Voice stopped because your session locked.",
|
||||
Err(error) => {
|
||||
tracing::debug!(%error, "session lock observer failed");
|
||||
"Voice conversation stopped because session lock monitoring failed."
|
||||
}
|
||||
};
|
||||
state_tx.send_replace(State::Stopped(message));
|
||||
tx.send(AppEvent::RealtimeSessionLockStopped { thread_id });
|
||||
});
|
||||
Self { state, task }
|
||||
}
|
||||
|
||||
/// Gate the attempt on the initial snapshot and abort its media actor on activation,
|
||||
/// even if the TUI is still waiting for an app-server operation.
|
||||
pub(super) fn start_media(
|
||||
&self,
|
||||
start: impl FnOnce(AbortRegistration) + Send + 'static,
|
||||
) -> AbortHandle {
|
||||
let mut state = self.state.clone();
|
||||
let (abort, registration) = AbortHandle::new_pair();
|
||||
let media = abort.clone();
|
||||
tokio::spawn(async move {
|
||||
let ready = state
|
||||
.wait_for(|state| *state != State::Initializing)
|
||||
.await
|
||||
.is_ok_and(|state| *state == State::Ready);
|
||||
if ready {
|
||||
std::thread::spawn(move || start(registration));
|
||||
let _ = state.changed().await;
|
||||
}
|
||||
media.abort();
|
||||
});
|
||||
abort
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SessionLock {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatWidget {
|
||||
pub(crate) fn stop_if_session_locked(&mut self) {
|
||||
let Some(observer) = &self.realtime_conversation.session_lock else {
|
||||
return;
|
||||
};
|
||||
let State::Stopped(message) = *observer.state.borrow() else {
|
||||
return;
|
||||
};
|
||||
self.stop_realtime_conversation();
|
||||
self.add_realtime_error(message.into());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Voice startup, shutdown, and retry maintain one active owned session.
|
||||
|
||||
use super::super::session_lock::SessionLock;
|
||||
use super::*;
|
||||
use crate::app_event::RealtimeWebrtcStartupFailure;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -408,6 +409,120 @@ async fn startup_retry_is_cancelled_while_waiting_for_backend_close() {
|
||||
);
|
||||
}
|
||||
|
||||
fn watch_session_lock(
|
||||
chat: &ChatWidget,
|
||||
thread_id: ThreadId,
|
||||
) -> (SessionLock, tokio::sync::oneshot::Sender<()>) {
|
||||
let (activate, activated) = tokio::sync::oneshot::channel();
|
||||
let observer = SessionLock::observe(thread_id, chat.app_event_tx.clone(), async {
|
||||
Ok(Box::pin(async { Ok(activated.await?) }) as crate::session_lock::Activation)
|
||||
});
|
||||
(observer, activate)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn already_locked_session_prevents_microphone_startup() {
|
||||
let (chat, _, _events, _ops) = make_chatwidget_manual_with_sender().await;
|
||||
let observer = SessionLock::observe(ThreadId::new(), chat.app_event_tx.clone(), async {
|
||||
Ok(Box::pin(async { Ok(()) }) as crate::session_lock::Activation)
|
||||
});
|
||||
let (opened, microphone) = tokio::sync::oneshot::channel();
|
||||
let abort = observer.start_media(move |_| {
|
||||
let _ = opened.send(());
|
||||
});
|
||||
assert!(microphone.await.is_err());
|
||||
assert!(abort.is_aborted());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_lock_stops_a_parked_call_and_ignores_its_late_notice_after_restart() {
|
||||
let (mut chat, _, mut events, mut ops) = make_chatwidget_manual_with_sender().await;
|
||||
let thread_id = activate_voice(&mut chat);
|
||||
let (observer, activate) = watch_session_lock(&chat, thread_id);
|
||||
let (opened, microphone) = tokio::sync::oneshot::channel();
|
||||
observer.start_media(move |registration| {
|
||||
let _ = opened.send(registration);
|
||||
});
|
||||
chat.realtime_conversation.session_lock = Some(observer);
|
||||
let microphone =
|
||||
futures::future::Abortable::new(std::future::pending::<()>(), microphone.await.unwrap());
|
||||
chat.park_voice();
|
||||
activate.send(()).unwrap();
|
||||
// Media shuts down even before the UI dispatches the notice to the parked widget.
|
||||
assert!(microphone.await.is_err());
|
||||
let event = events.recv().await.unwrap();
|
||||
assert!(
|
||||
matches!(event, AppEvent::RealtimeSessionLockStopped { thread_id: owner } if owner == thread_id)
|
||||
);
|
||||
chat.stop_if_session_locked();
|
||||
assert_eq!(
|
||||
(chat.realtime_conversation.phase, ops.try_recv().ok()),
|
||||
(
|
||||
RealtimeConversationPhase::Inactive,
|
||||
Some(AppCommand::RealtimeConversationStop { thread_id })
|
||||
)
|
||||
);
|
||||
assert!(
|
||||
std::iter::from_fn(|| events.try_recv().ok()).any(|event| matches!(
|
||||
event, AppEvent::BackgroundVoiceError { thread_id: owner, message: reason }
|
||||
if owner == thread_id && reason.contains("session locked")
|
||||
))
|
||||
);
|
||||
|
||||
chat.start_realtime_conversation(thread_id);
|
||||
chat.stop_if_session_locked();
|
||||
assert_eq!(
|
||||
chat.realtime_conversation.phase,
|
||||
RealtimeConversationPhase::Starting
|
||||
);
|
||||
chat.reset_realtime_conversation();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_lock_during_retry_cleanup_keeps_the_microphone_off() {
|
||||
let (mut chat, _, mut events, mut ops) = make_chatwidget_manual_with_sender().await;
|
||||
let thread_id = activate_voice(&mut chat);
|
||||
let first_attempt = chat.realtime_conversation.attempt_id;
|
||||
let (observer, activate) = watch_session_lock(&chat, thread_id);
|
||||
chat.realtime_conversation.session_lock = Some(observer);
|
||||
chat.realtime_conversation.phase = RealtimeConversationPhase::Starting;
|
||||
chat.on_realtime_webrtc_connected(
|
||||
first_attempt,
|
||||
Err(codex_realtime_webrtc::ConnectionError::NegotiationTimedOut),
|
||||
);
|
||||
assert_eq!(
|
||||
ops.try_recv().unwrap(),
|
||||
AppCommand::RealtimeConversationStop { thread_id }
|
||||
);
|
||||
activate.send(()).unwrap();
|
||||
while !matches!(
|
||||
events.recv().await.unwrap(),
|
||||
AppEvent::RealtimeSessionLockStopped { .. }
|
||||
) {}
|
||||
// The close response can overtake dispatch of the queued session-lock event.
|
||||
chat.on_realtime_conversation_closed(Some("requested".into()));
|
||||
chat.stop_if_session_locked();
|
||||
assert_eq!(
|
||||
(
|
||||
chat.realtime_conversation.phase,
|
||||
chat.realtime_conversation.attempt_id
|
||||
),
|
||||
(RealtimeConversationPhase::Inactive, first_attempt)
|
||||
);
|
||||
assert!(ops.try_recv().is_err());
|
||||
commit_realtime_history_events(&mut chat, &mut events);
|
||||
let rendered = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.filter_map(|event| match event {
|
||||
AppEvent::InsertHistoryCell(cell) => Some(cell.display_lines(/*width*/ 80)),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.map(|line| line.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!("voice_session_lock_stop", rendered);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_transport_close_before_peer_timeout_retries_once_and_ignores_old_result() {
|
||||
let (mut chat, _sender, mut events, mut ops) = make_chatwidget_manual_with_sender().await;
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: tui/src/chatwidget/realtime_tests/lifecycle.rs
|
||||
expression: rendered
|
||||
---
|
||||
■ Voice stopped because your session locked.
|
||||
• Voice conversation ended: requested
|
||||
Reference in New Issue
Block a user