From 41644a9a9ff7ec5eb1e858e453a82e6dad7f6094 Mon Sep 17 00:00:00 2001 From: lucha Date: Fri, 27 Nov 2026 00:44:56 -0800 Subject: [PATCH 1/2] Avoid repeated process snapshots in Windows browser native host (cherry picked from commit 26047cf30cd2babe5521da317f06b6dd7f69627e) --- crates/webcodex-browser/src/bridge/native.rs | 104 ++++++- .../src/bridge/native/tests.rs | 271 ++++++++++++++++++ 2 files changed, 370 insertions(+), 5 deletions(-) create mode 100644 crates/webcodex-browser/src/bridge/native/tests.rs diff --git a/crates/webcodex-browser/src/bridge/native.rs b/crates/webcodex-browser/src/bridge/native.rs index 8b6cc03bf..4e2dda2f6 100644 --- a/crates/webcodex-browser/src/bridge/native.rs +++ b/crates/webcodex-browser/src/bridge/native.rs @@ -1,5 +1,7 @@ //! Native Messaging host. Authentication stays in this process, never in the //! extension, stdout diagnostics, browser pages or model-visible output. +#[cfg(all(test, windows))] +mod tests; use super::{profiles, protocol, Hello, Rendezvous}; use protocol::{EXTENSION_ID, MAX_COMMAND, MAX_RESPONSE, VERSION}; use serde_json::json; @@ -53,6 +55,100 @@ fn parent_pid() -> io::Result { } } +struct ParentProcess { + pid: u32, + #[cfg(windows)] + process: std::os::windows::io::OwnedHandle, +} + +impl ParentProcess { + fn capture() -> io::Result { + let pid = parent_pid()?; + let parent = Self { + pid, + #[cfg(windows)] + process: open_parent_process(pid)?, + }; + parent.ensure_alive()?; + Ok(parent) + } + + fn ensure_alive(&self) -> io::Result<()> { + #[cfg(windows)] + { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::{ + Foundation::{WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT}, + System::Threading::WaitForSingleObject, + }; + // The handle keeps the original process identity even after exit. + // A repeated Toolhelp snapshot is expensive and only returns the + // immutable creation-time parent PID; it cannot detect parent exit. + match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) } { + WAIT_TIMEOUT => Ok(()), + WAIT_OBJECT_0 => Err(protocol::invalid()), + WAIT_FAILED => Err(io::Error::last_os_error()), + _ => Err(protocol::invalid()), + } + } + #[cfg(not(windows))] + { + if parent_pid()? == self.pid { + Ok(()) + } else { + Err(protocol::invalid()) + } + } + } +} + +#[cfg(windows)] +fn open_parent_process(pid: u32) -> io::Result { + use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle}; + use windows_sys::Win32::{ + Foundation::{FILETIME, HANDLE}, + System::Threading::{ + GetCurrentProcess, GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, + PROCESS_SYNCHRONIZE, + }, + }; + + fn created_at(process: HANDLE) -> io::Result { + let mut created = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; + let mut exited = created; + let mut kernel = created; + let mut user = created; + if unsafe { GetProcessTimes(process, &mut created, &mut exited, &mut kernel, &mut user) } + == 0 + { + return Err(io::Error::last_os_error()); + } + Ok((u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime)) + } + + let handle = unsafe { + OpenProcess( + PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, + 0, + pid, + ) + }; + if handle.is_null() { + return Err(io::Error::last_os_error()); + } + // Own immediately so errors during identity validation also close it. + let handle = unsafe { OwnedHandle::from_raw_handle(handle as RawHandle) }; + // If the original parent exited before OpenProcess, its PID may now name a + // later process. That object cannot be our parent; fail closed. + if created_at(handle.as_raw_handle())? > created_at(unsafe { GetCurrentProcess() })? { + return Err(protocol::invalid()); + } + Ok(handle) +} + /// Called only by the dedicated Native Messaging binary, not by a tool gateway. /// The manifest supplies the allowed caller origin; no endpoint/token argument is /// accepted. Stdio framing and caller identity are validated before connecting. @@ -86,7 +182,7 @@ fn run_inner() -> io::Result<()> { { return Err(protocol::invalid()); } - let parent = parent_pid()?; + let parent = ParentProcess::capture()?; let mut socket = TcpStream::connect_timeout(&config.address, Duration::from_secs(2))?; socket.set_read_timeout(Some(Duration::from_millis(100)))?; socket.set_write_timeout(Some(Duration::from_secs(1)))?; @@ -96,7 +192,7 @@ fn run_inner() -> io::Result<()> { instance: config.instance, token: config.token, extension_id: EXTENSION_ID.into(), - parent_pid: parent, + parent_pid: parent.pid, }; protocol::write_frame( &mut socket, @@ -141,9 +237,7 @@ fn run_inner() -> io::Result<()> { )?; loop { // Exact parent lifetime, not an untrusted PID reported by JavaScript. - if parent_pid()? != parent { - return Err(protocol::invalid()); - } + parent.ensure_alive()?; if let Some(value) = frames.poll(&mut socket)? { protocol::write_frame(&mut stdout, &value, MAX_COMMAND, true)?; } diff --git a/crates/webcodex-browser/src/bridge/native/tests.rs b/crates/webcodex-browser/src/bridge/native/tests.rs new file mode 100644 index 000000000..8ec19db0c --- /dev/null +++ b/crates/webcodex-browser/src/bridge/native/tests.rs @@ -0,0 +1,271 @@ +//! Real Windows host lifecycle regression. Only fixture processes are terminated. +use super::{open_parent_process, profiles, protocol, run, ParentProcess, Rendezvous}; +use std::{ + io::{BufRead, BufReader, Write}, + net::{TcpListener, TcpStream}, + os::windows::io::{AsHandle, AsRawHandle, FromRawHandle, OwnedHandle, RawHandle}, + process::{Child, Command, Stdio}, + sync::mpsc, + thread, + time::{Duration, Instant}, +}; +use windows_sys::Win32::{ + Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT}, + System::Threading::{ + OpenProcess, TerminateProcess, WaitForSingleObject, PROCESS_QUERY_LIMITED_INFORMATION, + PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, + }, +}; + +const CASE: &str = + "bridge::native::tests::native_host_exits_when_parent_exits_with_input_still_open"; +const ROLE: &str = "WEBCODEX_NATIVE_HOST_LIFETIME_FIXTURE"; + +struct ChildCleanup(Child); +impl ChildCleanup { + fn stop(&mut self) -> std::io::Result<()> { + if self.0.try_wait()?.is_some() { + return Ok(()); + } + let _ = self.0.kill(); + let state = unsafe { WaitForSingleObject(self.0.as_raw_handle(), 5_000) }; + if state != WAIT_OBJECT_0 { + return Err(std::io::Error::new( + std::io::ErrorKind::TimedOut, + format!("fixture cleanup did not complete: wait result {state}"), + )); + } + self.0.try_wait()?; + Ok(()) + } +} +impl Drop for ChildCleanup { + fn drop(&mut self) { + if let Err(error) = self.stop() { + cleanup_failure(&error.to_string()); + } + } +} + +fn cleanup_failure(message: &str) { + if thread::panicking() { + eprintln!("fixture cleanup failed during unwinding: {message}"); + } else { + panic!("fixture cleanup failed: {message}"); + } +} + +// This handle is opened for a PID reported by our still-live fixture parent, +// before that parent exits. Cleanup never looks up a PID again. +struct HostCleanup(OwnedHandle); +impl Drop for HostCleanup { + fn drop(&mut self) { + let handle = self.0.as_raw_handle(); + unsafe { + if WaitForSingleObject(handle, 0) != WAIT_OBJECT_0 { + TerminateProcess(handle, 99); + let state = WaitForSingleObject(handle, 5_000); + if state != WAIT_OBJECT_0 { + cleanup_failure(&format!("native host wait result {state}")); + } + } + } + } +} + +fn fixture_command(role: &str) -> Command { + let mut command = Command::new(std::env::current_exe().unwrap()); + command + .args(["--exact", CASE, "--ignored", "--nocapture"]) + .env(ROLE, role) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + command +} + +fn accept(listener: &TcpListener) -> TcpStream { + listener.set_nonblocking(true).unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + loop { + match listener.accept() { + Ok((stream, _)) => { + // Windows accepted sockets inherit the listener's mode. + stream.set_nonblocking(false).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(5))) + .unwrap(); + return stream; + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + assert!(Instant::now() < deadline, "fixture host did not connect"); + thread::sleep(Duration::from_millis(10)); + } + Err(error) => panic!("fixture accept failed: {error}"), + } + } +} + +#[test] +fn invalid_parent_process_fails_closed() { + assert!(open_parent_process(0).is_err()); +} + +#[test] +#[ignore = "spawns an owned Windows process; run explicitly"] +fn fixed_parent_handle_detects_exit() { + let mut child = ChildCleanup( + fixture_command("holder") + .stdin(Stdio::null()) + .spawn() + .unwrap(), + ); + let parent = ParentProcess { + pid: child.0.id(), + process: child.0.as_handle().try_clone_to_owned().unwrap(), + }; + assert!(parent.ensure_alive().is_ok()); + child.stop().unwrap(); + assert!( + parent.ensure_alive().is_err(), + "an exited parent's retained handle must not authorize more work" + ); +} + +#[test] +#[ignore = "spawns an owned Windows process; run explicitly"] +fn newer_process_cannot_substitute_for_parent() { + let child = ChildCleanup( + fixture_command("holder") + .stdin(Stdio::null()) + .spawn() + .unwrap(), + ); + assert!( + open_parent_process(child.0.id()).is_err(), + "a process created after this host cannot be its original parent" + ); +} + +#[test] +#[ignore = "spawns native Windows host and parent fixtures; run explicitly"] +fn native_host_exits_when_parent_exits_with_input_still_open() { + match std::env::var(ROLE).as_deref() { + Ok("holder") => { + thread::sleep(Duration::from_secs(20)); + return; + } + Ok("host") => { + let result = run(&[format!("chrome-extension://{}/", protocol::EXTENSION_ID)]); + std::process::exit(i32::from(result.is_ok())); + } + Ok("parent") => { + let child = fixture_command("host") + .stdin(Stdio::inherit()) + .spawn() + .unwrap(); + let _cleanup = ChildCleanup(child); + println!("fixture-host-pid:{}", _cleanup.0.id()); + std::io::stdout().flush().unwrap(); + // The test terminates this exact parent after the host handshake. + // This fallback bounds the helper even if the outer test fails. + thread::sleep(Duration::from_secs(20)); + return; + } + _ => {} + } + + let temporary = tempfile::tempdir().unwrap(); + let local_appdata = temporary.path().canonicalize().unwrap(); + let record = local_appdata.join("webcodex/browser/extension/bridge.json"); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let config = Rendezvous { + version: protocol::VERSION, + address: listener.local_addr().unwrap(), + instance: uuid::Uuid::new_v4().simple().to_string(), + token: format!( + "{}{}", + uuid::Uuid::new_v4().simple(), + uuid::Uuid::new_v4().simple() + ), + }; + let mut file = profiles::private_file(&record, true).unwrap(); + serde_json::to_writer(&mut file, &config).unwrap(); + file.flush().unwrap(); + drop(file); + + let mut parent = ChildCleanup( + fixture_command("parent") + .env("LOCALAPPDATA", &local_appdata) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(), + ); + // The host inherits the read end. Keeping our write end alive rules out + // stdin EOF as the reason for its exit after the fixture parent terminates. + let _keep_stdin_open = parent.0.stdin.take().unwrap(); + let stdout = parent.0.stdout.take().unwrap(); + let (sender, receiver) = mpsc::channel(); + let output = thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + let Ok(line) = line else { break }; + if let Some((_, pid)) = line.split_once("fixture-host-pid:") { + let _ = sender.send(pid.trim().parse::().unwrap()); + break; + } + } + }); + let host_pid = receiver + .recv_timeout(Duration::from_secs(10)) + .expect("fixture parent did not report its host"); + let handle = unsafe { + OpenProcess( + PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE | PROCESS_TERMINATE, + 0, + host_pid, + ) + }; + assert!( + !handle.is_null(), + "could not bind exact fixture host handle" + ); + let handle = unsafe { OwnedHandle::from_raw_handle(handle as RawHandle) }; + // The parent retains its Child handle until it exits, preventing PID reuse. + // Do not grant cleanup/termination ownership if the parent already left. + assert!( + parent.0.try_wait().unwrap().is_none(), + "fixture parent exited before host identity was bound" + ); + let host = HostCleanup(handle); + + let mut stream = accept(&listener); + let hello = protocol::read_blocking(&mut stream, 4096, false).unwrap(); + assert_eq!(hello["parent_pid"].as_u64(), Some(parent.0.id() as u64)); + assert_eq!(hello["instance"], config.instance); + assert_eq!(hello["token"], config.token); + protocol::write_frame( + &mut stream, + &serde_json::json!({"kind":"ready", "version":protocol::VERSION}), + 4096, + false, + ) + .unwrap(); + + output.join().unwrap(); + assert_eq!( + unsafe { WaitForSingleObject(host.0.as_raw_handle(), 0) }, + WAIT_TIMEOUT, + "fixture host exited before its parent" + ); + parent.stop().unwrap(); + // Both pipes and the authenticated socket are still open. The host must + // observe the original parent's lifetime, not keep re-reading its fixed PID. + let state = unsafe { WaitForSingleObject(host.0.as_raw_handle(), 5_000) }; + assert_eq!( + state, WAIT_OBJECT_0, + "native host outlived its parent while stdin and socket stayed open" + ); +} From c39f6b61f8609bad979f33f9079fbdccb91383cf Mon Sep 17 00:00:00 2001 From: lucha Date: Fri, 27 Nov 2026 03:13:02 -0800 Subject: [PATCH 2/2] Bound automatic Desktop runtime status polling (cherry picked from commit 7fb5463108cb802dbeaa32e557c4493320c3972d) --- apps/desktop/src-tauri/src/commands/mod.rs | 9 +- apps/desktop/src-tauri/src/state.rs | 16 +- apps/desktop/src-tauri/src/state/app_state.rs | 84 +++++- apps/desktop/src-tauri/src/state/tests.rs | 270 +++++++++++++++++- apps/desktop/src-tauri/src/tray.rs | 4 +- apps/desktop/src/App.test.tsx | 4 + apps/desktop/src/hooks/useDesktopWorkspace.ts | 2 +- apps/desktop/src/lib/desktop-api.ts | 2 +- 8 files changed, 370 insertions(+), 21 deletions(-) diff --git a/apps/desktop/src-tauri/src/commands/mod.rs b/apps/desktop/src-tauri/src/commands/mod.rs index de391b99c..6355e8006 100644 --- a/apps/desktop/src-tauri/src/commands/mod.rs +++ b/apps/desktop/src-tauri/src/commands/mod.rs @@ -324,8 +324,15 @@ pub async fn set_launch_at_login( pub async fn refresh_runtime_status( app: AppHandle, state: State<'_, AppState>, + automatic: Option, ) -> Result { - project_state_result(&app, state.refresh_runtime_status().await) + // Omitted by existing/manual callers: always request a fresh observation. + let result = if automatic.unwrap_or(false) { + state.observe_runtime_status().await + } else { + state.refresh_runtime_status().await + }; + project_state_result(&app, result) } #[tauri::command] diff --git a/apps/desktop/src-tauri/src/state.rs b/apps/desktop/src-tauri/src/state.rs index b1c168e58..96088dcdd 100644 --- a/apps/desktop/src-tauri/src/state.rs +++ b/apps/desktop/src-tauri/src/state.rs @@ -60,7 +60,7 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::AtomicU64; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, RwLock}; -use std::time::Duration; +use std::time::{Duration, Instant}; use tokio::sync::Mutex; const SERVER_READY_TIMEOUT: Duration = Duration::from_secs(20); @@ -91,6 +91,18 @@ struct ChatGptActivityProbe { runtime_selection_revision: u64, } +// Presentation-only budget shared by renderer and native tray observations. +// Neither this record nor a cached snapshot authorizes a service operation. +struct RuntimeRefreshAttempt { + environment_id: Option, + operation_generation: u64, + runtime_selection_revision: u64, + started_at: Instant, + completed: Option<(Instant, u64)>, +} + +const AUTOMATIC_RUNTIME_REFRESH_INTERVAL: Duration = Duration::from_secs(30); + pub struct AppState { core: Mutex>, desktop_data_dir: crate::desktop_data_dir::DesktopDataDir, @@ -100,7 +112,7 @@ pub struct AppState { supervisor: SharedSupervisor, activity: ActivityLog, operations: OperationController, - refresh_lock: tokio::sync::Mutex<()>, + refresh_lock: tokio::sync::Mutex>, shutdown_signal: CancellationSignal, shutdown_started: AtomicBool, shutdown_complete: CancellationSignal, diff --git a/apps/desktop/src-tauri/src/state/app_state.rs b/apps/desktop/src-tauri/src/state/app_state.rs index 70908bf47..488b9ff7c 100644 --- a/apps/desktop/src-tauri/src/state/app_state.rs +++ b/apps/desktop/src-tauri/src/state/app_state.rs @@ -32,7 +32,7 @@ impl AppState { supervisor, connections, operations: OperationController::new(activity.clone()), - refresh_lock: tokio::sync::Mutex::new(()), + refresh_lock: tokio::sync::Mutex::new(None), activity, shutdown_signal: CancellationSignal::new(), shutdown_started: AtomicBool::new(false), @@ -141,7 +141,19 @@ impl AppState { }) } + pub async fn observe_runtime_status(&self) -> DesktopResult { + self.refresh_runtime_status_with_policy(true).await + } + pub async fn refresh_runtime_status(&self) -> DesktopResult { + self.refresh_runtime_status_with_policy(false).await + } + + async fn refresh_runtime_status_with_policy( + &self, + automatic: bool, + ) -> DesktopResult { + let requested_at = Instant::now(); if self.shutdown_signal.is_cancelled() { return Err(cancelled_error()); } @@ -166,7 +178,7 @@ impl AppState { } let before_generation = self.get_state().state_generation; - let _refresh_guard = self.refresh_lock.lock().await; + let mut refresh_guard = self.refresh_lock.lock().await; if self.shutdown_signal.is_cancelled() { return Err(cancelled_error()); } @@ -182,12 +194,6 @@ impl AppState { })) .with_operation_context(Some(¤t.id), None, None, None)); } - // Coalesce overlapping background refreshes: if another refresh already - // published a fresher snapshot while we waited, return it directly. - if self.get_state().state_generation != before_generation { - return Ok(self.get_state()); - } - let cancellation = CancellationContext::new(CancellationSignal::new(), self.shutdown_signal.clone()); let start_op_generation = self.operations.generation(); @@ -208,7 +214,7 @@ impl AppState { }, } - let plan = { + let (plan, environment_id, runtime_selection_revision) = { let slot = self.core.lock().await; let Some(core) = slot.as_ref() else { return Err(DesktopError::new( @@ -217,7 +223,14 @@ impl AppState { "Wait for the current operation to finish.", )); }; - if let Some(environment_id) = core.config.persistent_environment.clone() { + if core.configuration_issue.is_some() { + return Err(DesktopError::new( + "configuration_migration_failed", + "Configuration could not be migrated", + "Open Diagnostics or explicitly restore the previous known-good configuration.", + )); + } + let plan = if let Some(environment_id) = core.config.persistent_environment.clone() { RefreshPlan::Persistent { environment_id } } else if core.snapshot.quick_share.is_some() { RefreshPlan::QuickShare @@ -236,10 +249,45 @@ impl AppState { } } else { RefreshPlan::Unconfigured - } + }; + ( + plan, + core.config.persistent_environment.clone(), + core.config.runtime_selection_revision, + ) }; - match plan { + // All automatic callers share this gate, including a recreated renderer + // and the no-window tray observer. Ordinary presentation publications + // neither invalidate nor extend the full-observation budget. + if let Some(previous) = refresh_guard.as_ref().filter(|previous| { + previous.environment_id == environment_id + && previous.operation_generation == start_op_generation + && previous.runtime_selection_revision == runtime_selection_revision + }) { + let last_attempt = previous.completed.map_or(previous.started_at, |(at, _)| at); + let current = self.get_state(); + let completed_since_request = previous.completed.is_some_and(|(at, generation)| { + at >= requested_at && generation == current.state_generation + }); + if (automatic && last_attempt.elapsed() < AUTOMATIC_RUNTIME_REFRESH_INTERVAL) + || completed_since_request + { + return Ok(current); + } + } + + // A failure cools down automatic retries, but never becomes a successful + // full observation that could satisfy a fresh manual request. + *refresh_guard = Some(RuntimeRefreshAttempt { + environment_id: environment_id.clone(), + operation_generation: start_op_generation, + runtime_selection_revision, + started_at: Instant::now(), + completed: None, + }); + + let observed: DesktopResult = match plan { RefreshPlan::QuickShare | RefreshPlan::Unconfigured => { let mut slot = self.core.lock().await; let Some(core) = slot.as_mut() else { @@ -407,7 +455,19 @@ impl AppState { core.publish_snapshot(); Ok(self.get_state()) } + }; + let observed = observed?; + // Every stale-result branch above returns before recording completion. + // Keep the identity captured at the beginning; never rebind late work. + if self.operations.current().is_none() + && self.operations.generation() == start_op_generation + && observed.persistent_environment == environment_id + { + if let Some(attempt) = refresh_guard.as_mut() { + attempt.completed = Some((Instant::now(), observed.state_generation)); + } } + Ok(observed) } pub async fn observe_chatgpt_activity(&self) -> DesktopResult { diff --git a/apps/desktop/src-tauri/src/state/tests.rs b/apps/desktop/src-tauri/src/state/tests.rs index 19c580c80..31b22e392 100644 --- a/apps/desktop/src-tauri/src/state/tests.rs +++ b/apps/desktop/src-tauri/src/state/tests.rs @@ -1584,14 +1584,280 @@ WEBCODEX_WINDOWS ); } - #[tokio::test] - async fn readonly_refresh_does_not_claim_exclusive_operation_slot_or_block_diagnostics() { + async fn unconfigured_refresh_state() -> (tempfile::TempDir, AppState) { let data_dir = tempfile::tempdir().unwrap(); let state = AppState::new( data_dir.path().to_path_buf(), data_dir.path().join("test-resources"), ) .unwrap(); + { + // Construction may adopt this machine's saved Environment. Keep + // these observation fixtures entirely in memory and unconfigured. + let mut slot = state.core.lock().await; + let core = slot.as_mut().unwrap(); + core.config = StoredDesktopConfig::default(); + core.configuration_issue = None; + core.snapshot = DesktopStateSnapshot::default(); + core.publish_snapshot(); + } + (data_dir, state) + } + + #[tokio::test] + async fn automatic_runtime_refresh_reuses_one_full_observation_and_manual_stays_fresh() { + let (_data_dir, state) = unconfigured_refresh_state().await; + // The unconfigured full-observation path publishes once, without native + // services or network fixtures. get_state never publishes by itself. + let first = state.observe_runtime_status().await.unwrap(); + for _ in 0..4 { + let observed = state.observe_runtime_status().await.unwrap(); + assert_eq!(observed.state_generation, first.state_generation); + } + let manual = state.refresh_runtime_status().await.unwrap(); + assert!(manual.state_generation > first.state_generation); + let observed = state.observe_runtime_status().await.unwrap(); + assert_eq!(observed.state_generation, manual.state_generation); + } + + #[tokio::test] + async fn automatic_runtime_refresh_keeps_budget_across_presentation_publication() { + let (_data_dir, state) = unconfigured_refresh_state().await; + state.observe_runtime_status().await.unwrap(); + let published = { + let mut slot = state.core.lock().await; + let core = slot.as_mut().unwrap(); + core.snapshot.chatgpt_activity = Some(ChatGptActivitySnapshot { + observed: true, + last_meaningful_activity_at_ms: Some(123), + }); + core.publish_snapshot() + }; + let observed = state.observe_runtime_status().await.unwrap(); + assert_eq!(observed.state_generation, published.state_generation); + assert_eq!( + observed + .chatgpt_activity + .unwrap() + .last_meaningful_activity_at_ms, + Some(123), + ); + } + + #[tokio::test] + async fn manual_runtime_refresh_does_not_coalesce_unrelated_publication() { + use std::future::Future; + let (_data_dir, state) = unconfigured_refresh_state().await; + state.observe_runtime_status().await.unwrap(); + let guard = state.refresh_lock.lock().await; + let mut manual = Box::pin(state.refresh_runtime_status()); + std::future::poll_fn(|cx| { + assert!(manual.as_mut().poll(cx).is_pending()); + std::task::Poll::Ready(()) + }) + .await; + let published = state.core.lock().await.as_mut().unwrap().publish_snapshot(); + drop(guard); + let refreshed = manual.await.unwrap(); + assert!(refreshed.state_generation > published.state_generation); + } + + #[tokio::test] + async fn runtime_refresh_coalesces_concurrent_automatic_and_fresh_requests() { + use std::future::Future; + let (_data_dir, state) = unconfigured_refresh_state().await; + let before = state.get_state().state_generation; + let core_guard = state.core.lock().await; + let mut first = Box::pin(state.observe_runtime_status()); + let mut second = Box::pin(state.observe_runtime_status()); + let mut manual = Box::pin(state.refresh_runtime_status()); + std::future::poll_fn(|cx| { + assert!(first.as_mut().poll(cx).is_pending()); + assert!(second.as_mut().poll(cx).is_pending()); + assert!(manual.as_mut().poll(cx).is_pending()); + std::task::Poll::Ready(()) + }) + .await; + drop(core_guard); + let (first, second, manual) = tokio::join!(first, second, manual); + let first = first.unwrap(); + assert_eq!(first.state_generation, before + 1); + assert_eq!(second.unwrap().state_generation, first.state_generation); + assert_eq!(manual.unwrap().state_generation, first.state_generation); + } + + #[tokio::test] + async fn runtime_refresh_operation_generation_invalidates_budget_and_busy_stays_visible() { + let (_data_dir, state) = unconfigured_refresh_state().await; + let first = state.observe_runtime_status().await.unwrap(); + let operation = state + .operations + .admit(DesktopOperationKind::RuntimeResume, true) + .unwrap(); + let error = + tokio::time::timeout(Duration::from_millis(250), state.observe_runtime_status()) + .await + .expect("cached observation must not wait for a busy operation") + .unwrap_err(); + assert_eq!(error.code, "desktop_operation_busy"); + state.operations.finish(&operation.id, &Ok(())); + let refreshed = state.observe_runtime_status().await.unwrap(); + assert!(refreshed.state_generation > first.state_generation); + state.shutdown_signal.cancel(); + assert_eq!( + state.observe_runtime_status().await.unwrap_err().code, + "desktop_operation_cancelled", + ); + } + + #[tokio::test] + async fn automatic_runtime_refresh_expires_after_thirty_seconds() { + let (_data_dir, state) = unconfigured_refresh_state().await; + let first = state.observe_runtime_status().await.unwrap(); + { + let mut guard = state.refresh_lock.lock().await; + guard.as_mut().unwrap().completed.as_mut().unwrap().0 = + Instant::now() - Duration::from_secs(29); + } + assert_eq!( + state + .observe_runtime_status() + .await + .unwrap() + .state_generation, + first.state_generation, + ); + { + let mut guard = state.refresh_lock.lock().await; + guard.as_mut().unwrap().completed.as_mut().unwrap().0 = + Instant::now() - Duration::from_secs(31); + } + assert!( + state + .observe_runtime_status() + .await + .unwrap() + .state_generation + > first.state_generation + ); + } + + #[tokio::test] + async fn runtime_refresh_does_not_reuse_another_environment_or_runtime_revision() { + let (_data_dir, state) = unconfigured_refresh_state().await; + let first = state.observe_runtime_status().await.unwrap(); + // Model the retained result of the previous environment without opening + // either a real Environment store or a native service fixture. + state + .refresh_lock + .lock() + .await + .as_mut() + .unwrap() + .environment_id = Some("previous-environment".to_string()); + let switched = state.observe_runtime_status().await.unwrap(); + assert!(switched.state_generation > first.state_generation); + let published = { + let mut slot = state.core.lock().await; + let core = slot.as_mut().unwrap(); + core.config.runtime_selection_revision += 1; + core.publish_snapshot() + }; + assert!( + state + .observe_runtime_status() + .await + .unwrap() + .state_generation + > published.state_generation, + ); + } + + #[tokio::test] + async fn runtime_refresh_failed_attempt_cools_automatic_retries_but_not_manual_refresh() { + let (_data_dir, state) = unconfigured_refresh_state().await; + let before = state.get_state().state_generation; + // Retain the exact gate state left by an unsuccessful observation. The + // native error itself is not synthesized by launching real services. + *state.refresh_lock.lock().await = Some(RuntimeRefreshAttempt { + environment_id: None, + operation_generation: state.operations.generation(), + runtime_selection_revision: 0, + started_at: Instant::now(), + completed: None, + }); + assert_eq!( + state + .observe_runtime_status() + .await + .unwrap() + .state_generation, + before + ); + assert!(state + .refresh_lock + .lock() + .await + .as_ref() + .unwrap() + .completed + .is_none()); + let manual = state.refresh_runtime_status().await.unwrap(); + assert!(manual.state_generation > before); + { + let mut guard = state.refresh_lock.lock().await; + let attempt = guard.as_mut().unwrap(); + attempt.completed = None; + attempt.started_at = Instant::now() - Duration::from_secs(31); + } + assert!( + state + .observe_runtime_status() + .await + .unwrap() + .state_generation + > manual.state_generation + ); + } + + #[tokio::test] + async fn runtime_refresh_intervening_operation_cannot_complete_the_new_identity_budget() { + use std::future::Future; + let (_data_dir, state) = unconfigured_refresh_state().await; + let before = state.get_state().state_generation; + let core_guard = state.core.lock().await; + let mut observed = Box::pin(state.observe_runtime_status()); + std::future::poll_fn(|cx| { + assert!(observed.as_mut().poll(cx).is_pending()); + std::task::Poll::Ready(()) + }) + .await; + let operation = state + .operations + .admit(DesktopOperationKind::RuntimeResume, true) + .unwrap(); + state.operations.finish(&operation.id, &Ok(())); + drop(core_guard); + assert_eq!(observed.await.unwrap().state_generation, before); + { + let guard = state.refresh_lock.lock().await; + let attempt = guard.as_ref().unwrap(); + assert!(attempt.completed.is_none()); + assert_ne!(attempt.operation_generation, state.operations.generation()); + } + assert!( + state + .observe_runtime_status() + .await + .unwrap() + .state_generation + > before + ); + } + + #[tokio::test] + async fn readonly_refresh_does_not_claim_exclusive_operation_slot_or_block_diagnostics() { + let (_data_dir, state) = unconfigured_refresh_state().await; let before_gen = state.get_state().state_generation; let (refresh_result, diag_result) = tokio::join!(state.refresh_runtime_status(), state.diagnostics()); diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs index 1331448b3..f8f0533fd 100644 --- a/apps/desktop/src-tauri/src/tray.rs +++ b/apps/desktop/src-tauri/src/tray.rs @@ -254,8 +254,8 @@ pub fn start_background_observer(app: &AppHandle) { let state = app.state::(); let mut snapshot = state.get_state(); if should_refresh_persistent_status(&snapshot) { - if let Ok(fresh) = state.refresh_runtime_status().await { - snapshot = fresh; + if let Ok(observed) = state.observe_runtime_status().await { + snapshot = observed; } } refresh_from_snapshot(&app, &snapshot); diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index 4ad096fba..0b69c2819 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -471,6 +471,9 @@ beforeEach(() => { expect(count()).toBe(1); await act(async () => { await vi.advanceTimersByTimeAsync(6_000); }); expect(api.refresh.mock.calls.length).toBeGreaterThan(2); + // Repeated automatic observation must opt into the shared native budget; + // the startup/manual refresh remains explicitly fresh. + expect(api.refresh.mock.calls.slice(1).every(args => args[0] === true)).toBe(true); expect(count()).toBe(1); await act(async () => { await vi.advanceTimersByTimeAsync(10_000); }); expect(count()).toBeGreaterThanOrEqual(2); @@ -505,6 +508,7 @@ beforeEach(() => { expect(screen.getByRole("button", { name: "启动 WebCodex" })).toBeEnabled(); fireEvent.click(screen.getByRole("button", { name: "刷新" })); await waitFor(() => expect(api.refresh).toHaveBeenCalledTimes(1)); + expect(api.refresh).toHaveBeenCalledWith(); expect(screen.getByRole("status")).toHaveTextContent("WebCodex · 已停止"); expect(api.resumeSavedRuntime).not.toHaveBeenCalled(); }); diff --git a/apps/desktop/src/hooks/useDesktopWorkspace.ts b/apps/desktop/src/hooks/useDesktopWorkspace.ts index 701670464..32a56f17a 100644 --- a/apps/desktop/src/hooks/useDesktopWorkspace.ts +++ b/apps/desktop/src/hooks/useDesktopWorkspace.ts @@ -255,7 +255,7 @@ export function useDesktopWorkspace() { if (refreshRuntime) setRuntimeObservations(count => count + 1); try { const next = refreshRuntime - ? await desktopApi.refresh() + ? await desktopApi.refresh(true) : await desktopApi.getState(); if (!cancelled && stateVersionRef.current === observedVersion) { commitState(next); diff --git a/apps/desktop/src/lib/desktop-api.ts b/apps/desktop/src/lib/desktop-api.ts index 6cff24374..6e5af274c 100644 --- a/apps/desktop/src/lib/desktop-api.ts +++ b/apps/desktop/src/lib/desktop-api.ts @@ -87,7 +87,7 @@ export const desktopApi = { getLaunchAtLogin: () => invoke("get_launch_at_login"), setLaunchAtLogin: (enabled: boolean) => invoke("set_launch_at_login", { request: { enabled } }), - refresh: () => invoke("refresh_runtime_status"), + refresh: (automatic = false) => invoke("refresh_runtime_status", { automatic }), observeChatgptActivity: () => invoke("observe_chatgpt_activity"), resumeSavedRuntime: () => invoke("resume_saved_runtime"), resumeSavedConnections: () => invoke("resume_saved_connections"),