mirror of
https://github.com/openai/codex.git
synced 2026-11-20 22:40:37 +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
@@ -0,0 +1,203 @@
|
||||
//! Observe the local graphical session's confirmed lock state through system logind.
|
||||
//!
|
||||
//! Resolve a real session object, subscribe before reading its lock state, and retain individual
|
||||
//! property-change payloads so a quick lock/unlock cannot erase the lock. Unsupported environments
|
||||
//! leave voice available; idle hints and requests to lock are not confirmed locks.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use futures::StreamExt;
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
use zbus::zvariant::OwnedValue;
|
||||
|
||||
use super::Activation;
|
||||
|
||||
const SERVICE: &str = "org.freedesktop.login1";
|
||||
const SESSION: &str = "org.freedesktop.login1.Session";
|
||||
|
||||
pub(super) async fn observe() -> anyhow::Result<Activation> {
|
||||
let setup = async {
|
||||
// SAFETY: geteuid has no preconditions and does not mutate process state.
|
||||
let current_uid = unsafe { libc::geteuid() };
|
||||
let connection = zbus::Connection::system().await?;
|
||||
let manager = zbus::Proxy::new(
|
||||
&connection,
|
||||
SERVICE,
|
||||
"/org/freedesktop/login1",
|
||||
"org.freedesktop.login1.Manager",
|
||||
)
|
||||
.await?;
|
||||
let path: Option<OwnedObjectPath> = match manager
|
||||
.call::<_, _, OwnedObjectPath>("GetSessionByPID", &std::process::id())
|
||||
.await
|
||||
{
|
||||
Ok(path) => {
|
||||
let candidate = session_proxy(&connection, path.clone()).await?;
|
||||
let class: String = candidate.get_property("Class").await?;
|
||||
if class == "manager" || class == "manager-early" {
|
||||
None
|
||||
} else {
|
||||
Some(path)
|
||||
}
|
||||
}
|
||||
Err(zbus::Error::MethodError(name, _, _))
|
||||
if name.as_str() == "org.freedesktop.login1.NoSessionForPID" =>
|
||||
{
|
||||
None
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
let path = if let Some(path) = path {
|
||||
path
|
||||
} else {
|
||||
// Graphical terminals may be launched by the per-user service manager, outside
|
||||
// the login scope. Prefer the client environment's explicit session association.
|
||||
if std::env::var_os("SSH_CONNECTION").is_some() || std::env::var_os("SSH_TTY").is_some()
|
||||
{
|
||||
anyhow::bail!("remote terminal has no graphical session");
|
||||
}
|
||||
match std::env::var("XDG_SESSION_ID") {
|
||||
Ok(session_id) => {
|
||||
anyhow::ensure!(
|
||||
!session_id.is_empty() && !matches!(session_id.as_str(), "self" | "auto"),
|
||||
"no explicit graphical session"
|
||||
);
|
||||
manager.call("GetSession", &session_id).await?
|
||||
}
|
||||
Err(std::env::VarError::NotPresent) => {
|
||||
unique_graphical_session(&connection, &manager, current_uid).await?
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
};
|
||||
let session = session_proxy(&connection, path.clone()).await?;
|
||||
let remote: bool = session.get_property("Remote").await?;
|
||||
let kind: String = session.get_property("Type").await?;
|
||||
let class: String = session.get_property("Class").await?;
|
||||
let (uid, _): (u32, OwnedObjectPath) = session.get_property("User").await?;
|
||||
let (seat, _): (String, OwnedObjectPath) = session.get_property("Seat").await?;
|
||||
anyhow::ensure!(
|
||||
!remote
|
||||
&& is_graphical_user_session(&kind, &class)
|
||||
&& uid == current_uid
|
||||
&& !seat.is_empty(),
|
||||
"process is not in a local graphical user session"
|
||||
);
|
||||
let properties = zbus::Proxy::new(
|
||||
&connection,
|
||||
SERVICE,
|
||||
path,
|
||||
"org.freedesktop.DBus.Properties",
|
||||
)
|
||||
.await?;
|
||||
// Do not use receive_property_changed: zbus coalesces its cached updates, potentially
|
||||
// replacing a queued true with false before the TUI can observe it.
|
||||
let mut changes = properties
|
||||
.receive_signal_with_args("PropertiesChanged", &[(0, SESSION)])
|
||||
.await?;
|
||||
let initially_locked: bool = session.get_property("LockedHint").await?;
|
||||
Ok::<Activation, anyhow::Error>(Box::pin(async move {
|
||||
// Keep the connection and session alive until this explicit voice call ends.
|
||||
let _connection = connection;
|
||||
if initially_locked {
|
||||
return Ok(());
|
||||
}
|
||||
while let Some(signal) = changes.next().await {
|
||||
let (_, changed, invalidated): (String, HashMap<String, OwnedValue>, Vec<String>) =
|
||||
signal.body().deserialize()?;
|
||||
if changed
|
||||
.get("LockedHint")
|
||||
.and_then(|value| bool::try_from(value).ok())
|
||||
== Some(true)
|
||||
|| (invalidated.iter().any(|name| name == "LockedHint")
|
||||
&& session.get_property::<bool>("LockedHint").await?)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
anyhow::bail!("desktop lock observation ended")
|
||||
}))
|
||||
};
|
||||
// Missing logind, unsupported sessions, and unavailable properties must not disable voice.
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(3), setup).await {
|
||||
Ok(Ok(activation)) => Ok(activation),
|
||||
Ok(Err(_)) | Err(_) => Ok(Box::pin(std::future::pending())),
|
||||
}
|
||||
}
|
||||
|
||||
async fn unique_graphical_session(
|
||||
connection: &zbus::Connection,
|
||||
manager: &zbus::Proxy<'_>,
|
||||
current_uid: u32,
|
||||
) -> anyhow::Result<OwnedObjectPath> {
|
||||
// GNOME terminal servers may forward DISPLAY/WAYLAND_DISPLAY without a
|
||||
// session ID. Resolve only an unambiguous graphical login for this user.
|
||||
let display = std::env::var("DISPLAY").ok();
|
||||
let local_display = display.as_deref().and_then(local_x_display);
|
||||
let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some_and(|value| !value.is_empty());
|
||||
anyhow::ensure!(
|
||||
local_display.is_some() || wayland,
|
||||
"no local graphical client environment"
|
||||
);
|
||||
let sessions: Vec<(String, u32, String, String, OwnedObjectPath)> =
|
||||
manager.call("ListSessions", &()).await?;
|
||||
let mut selected = None;
|
||||
for (_, uid, _, _, path) in sessions {
|
||||
if uid != current_uid {
|
||||
continue;
|
||||
}
|
||||
let candidate = session_proxy(connection, path.clone()).await?;
|
||||
let kind: String = candidate.get_property("Type").await?;
|
||||
let class: String = candidate.get_property("Class").await?;
|
||||
if is_graphical_user_session(&kind, &class) {
|
||||
// Remote/seatless graphical logins also make association ambiguous.
|
||||
anyhow::ensure!(selected.is_none(), "ambiguous graphical session");
|
||||
if kind == "x11"
|
||||
&& let Some(client_display) = local_display
|
||||
{
|
||||
let display: String = candidate.get_property("Display").await?;
|
||||
anyhow::ensure!(
|
||||
display.is_empty() || local_x_display(&display) == Some(client_display),
|
||||
"graphical session display does not match client"
|
||||
);
|
||||
}
|
||||
selected = Some(path);
|
||||
}
|
||||
}
|
||||
selected.ok_or_else(|| anyhow::anyhow!("no graphical user session"))
|
||||
}
|
||||
|
||||
fn is_graphical_user_session(kind: &str, class: &str) -> bool {
|
||||
matches!(kind, "x11" | "wayland" | "mir")
|
||||
&& matches!(
|
||||
class,
|
||||
"user" | "user-early" | "user-light" | "user-early-light"
|
||||
)
|
||||
}
|
||||
|
||||
async fn session_proxy(
|
||||
connection: &zbus::Connection,
|
||||
path: OwnedObjectPath,
|
||||
) -> zbus::Result<zbus::Proxy<'static>> {
|
||||
zbus::proxy::Builder::new(connection)
|
||||
.destination(SERVICE)?
|
||||
.path(path)?
|
||||
.interface(SESSION)?
|
||||
.cache_properties(zbus::proxy::CacheProperties::No)
|
||||
.build()
|
||||
.await
|
||||
}
|
||||
|
||||
fn local_x_display(display: &str) -> Option<u32> {
|
||||
let number = display
|
||||
.strip_prefix(':')
|
||||
.or_else(|| display.strip_prefix("unix:"))
|
||||
.or_else(|| display.strip_prefix("unix/:"))?;
|
||||
let number = if let Some((number, screen)) = number.split_once('.') {
|
||||
screen.parse::<u32>().ok()?;
|
||||
number
|
||||
} else {
|
||||
number
|
||||
};
|
||||
number.parse().ok()
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Read the lock state of the calling process's macOS login session.
|
||||
|
||||
use chrono::Utc;
|
||||
use core_foundation::base::CFType;
|
||||
use core_foundation::base::TCFType;
|
||||
use core_foundation::boolean::CFBoolean;
|
||||
use core_foundation::dictionary::CFDictionary;
|
||||
use core_foundation::dictionary::CFDictionaryRef;
|
||||
use core_foundation::number::CFNumber;
|
||||
use core_foundation::string::CFString;
|
||||
|
||||
#[link(name = "CoreGraphics", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn CGSessionCopyCurrentDictionary() -> CFDictionaryRef;
|
||||
}
|
||||
|
||||
pub(super) fn is_locked() -> anyhow::Result<bool> {
|
||||
// SAFETY: The function takes no arguments and returns an owned dictionary or null.
|
||||
let session = unsafe { CGSessionCopyCurrentDictionary() };
|
||||
anyhow::ensure!(!session.is_null(), "macOS login session unavailable");
|
||||
// SAFETY: CGSession follows the CF create rule. The dictionary owns its CF strings and values.
|
||||
let session: CFDictionary<CFString, CFType> =
|
||||
unsafe { TCFType::wrap_under_create_rule(session) };
|
||||
Ok(requires_authentication(&session, Utc::now().timestamp()))
|
||||
}
|
||||
|
||||
fn requires_authentication(session: &CFDictionary<CFString, CFType>, now: i64) -> bool {
|
||||
let lock_screen_active = session
|
||||
.find(CFString::new("CGSSessionScreenIsLocked"))
|
||||
.and_then(|locked| locked.downcast::<CFBoolean>())
|
||||
.is_some_and(bool::from);
|
||||
// loginwindow sets the flag as soon as the saver starts. XNU enforces the password
|
||||
// after this per-session Unix timestamp, including when the grace period expires.
|
||||
let password_required_at = session
|
||||
.find(CFString::new("CGSSessionScreenLockedTime"))
|
||||
.and_then(|time| time.downcast::<CFNumber>())
|
||||
.and_then(|time| time.to_i64());
|
||||
lock_screen_active && password_required_at.is_some_and(|time| (1..=now).contains(&time))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "macos_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,22 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn screen_saver_stops_voice_when_its_password_grace_period_expires() {
|
||||
let password_required_at = 1_793_735_319_i64;
|
||||
let session = CFDictionary::from_CFType_pairs(&[
|
||||
(
|
||||
CFString::new("CGSSessionScreenIsLocked"),
|
||||
CFBoolean::true_value().as_CFType(),
|
||||
),
|
||||
(
|
||||
CFString::new("CGSSessionScreenLockedTime"),
|
||||
CFNumber::from(password_required_at).as_CFType(),
|
||||
),
|
||||
]);
|
||||
let observed = [password_required_at - 1, password_required_at]
|
||||
.map(|now| requires_authentication(&session, now));
|
||||
assert_eq!(observed, [false, true]);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! Snapshot the lock state of the current Windows session.
|
||||
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTS_CURRENT_SERVER_HANDLE;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTS_CURRENT_SESSION;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTS_SESSIONSTATE_LOCK;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTS_SESSIONSTATE_UNLOCK;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTSFreeMemory;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTSINFOEXW;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTSQuerySessionInformationW;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTSSessionInfoEx;
|
||||
|
||||
pub(super) fn is_locked() -> anyhow::Result<bool> {
|
||||
let mut buffer = std::ptr::null_mut();
|
||||
let mut bytes = 0;
|
||||
// SAFETY: The output pointers are valid, and the returned buffer is released below.
|
||||
let succeeded = unsafe {
|
||||
WTSQuerySessionInformationW(
|
||||
WTS_CURRENT_SERVER_HANDLE,
|
||||
WTS_CURRENT_SESSION,
|
||||
WTSSessionInfoEx,
|
||||
&mut buffer,
|
||||
&mut bytes,
|
||||
)
|
||||
};
|
||||
if succeeded == 0 {
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
|
||||
let result = if buffer.is_null() || (bytes as usize) < std::mem::size_of::<WTSINFOEXW>() {
|
||||
Err(anyhow::anyhow!(
|
||||
"invalid Windows session information buffer"
|
||||
))
|
||||
} else {
|
||||
// SAFETY: The API returned a buffer large enough for WTSINFOEXW. Reading
|
||||
// unaligned avoids relying on the allocator's alignment guarantees.
|
||||
let info = unsafe { buffer.cast::<WTSINFOEXW>().read_unaligned() };
|
||||
if info.Level != 1 {
|
||||
Err(anyhow::anyhow!(
|
||||
"unsupported Windows session information level: {}",
|
||||
info.Level
|
||||
))
|
||||
} else {
|
||||
// SAFETY: Level 1 identifies this union member.
|
||||
let flags = unsafe { info.Data.WTSInfoExLevel1.SessionFlags } as u32;
|
||||
match flags {
|
||||
WTS_SESSIONSTATE_LOCK => Ok(true),
|
||||
WTS_SESSIONSTATE_UNLOCK => Ok(false),
|
||||
_ => Err(anyhow::anyhow!(
|
||||
"unknown Windows session lock state: {flags}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
};
|
||||
if !buffer.is_null() {
|
||||
// SAFETY: This buffer was allocated by WTSQuerySessionInformationW.
|
||||
unsafe { WTSFreeMemory(buffer.cast()) };
|
||||
}
|
||||
result
|
||||
}
|
||||
Reference in New Issue
Block a user