From b31f9d61d92c75c7781cabbaabff5ff182c2774e Mon Sep 17 00:00:00 2001 From: kite8 <3972363+kite8@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:42:29 +0800 Subject: [PATCH] fix(windows): use native service observations and cache display refreshes --- Cargo.lock | 1 + apps/desktop/src-tauri/Cargo.lock | 74 ++- apps/desktop/src-tauri/src/commands/mod.rs | 8 + apps/desktop/src-tauri/src/lib.rs | 1 + apps/desktop/src-tauri/src/state.rs | 2 + apps/desktop/src-tauri/src/state/app_state.rs | 56 +- .../src/state/runtime_observation.rs | 369 ++++++++++++ .../src/state/runtime_observation/tests.rs | 299 ++++++++++ apps/desktop/src-tauri/src/tray.rs | 2 +- apps/desktop/src/App.test.tsx | 16 +- apps/desktop/src/hooks/useDesktopWorkspace.ts | 2 +- apps/desktop/src/lib/desktop-api.ts | 1 + apps/desktop/src/lib/desktop-observation.ts | 8 +- crates/webcodex-environment/Cargo.toml | 3 +- .../webcodex-environment/src/local_status.rs | 188 ++++-- .../webcodex-environment/src/service/mod.rs | 86 ++- .../src/service/windows_user.ps1 | 121 ++-- .../src/service/windows_user.rs | 202 +++---- .../src/service/windows_user/native.rs | 505 ++++++++++++++++ .../service/windows_user/native/process.rs | 556 ++++++++++++++++++ .../windows_user/native/process/tests.rs | 185 ++++++ .../src/service/windows_user/native/tests.rs | 394 +++++++++++++ docs/DESKTOP_DEVELOPMENT.md | 60 ++ docs/DESKTOP_DEVELOPMENT.zh-CN.md | 50 ++ .../test_windows_user_service_identity.ps1 | 18 +- 25 files changed, 2914 insertions(+), 293 deletions(-) create mode 100644 apps/desktop/src-tauri/src/state/runtime_observation.rs create mode 100644 apps/desktop/src-tauri/src/state/runtime_observation/tests.rs create mode 100644 crates/webcodex-environment/src/service/windows_user/native.rs create mode 100644 crates/webcodex-environment/src/service/windows_user/native/process.rs create mode 100644 crates/webcodex-environment/src/service/windows_user/native/process/tests.rs create mode 100644 crates/webcodex-environment/src/service/windows_user/native/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 7cf5d91f4..5e16a64f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5680,6 +5680,7 @@ dependencies = [ "webcodex-openai-tunnel", "webcodex-process", "webcodex-runner-config", + "windows", "windows-sys 0.61.2", "winreg", ] diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 44c40a1b6..78d168e06 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -3897,7 +3897,7 @@ dependencies = [ "tao-macros", "unicode-segmentation", "url", - "windows", + "windows 0.61.3", "windows-core 0.61.2", "windows-version", "x11-dl", @@ -3968,7 +3968,7 @@ dependencies = [ "webkit2gtk", "webview2-com", "window-vibrancy", - "windows", + "windows 0.61.3", ] [[package]] @@ -4158,7 +4158,7 @@ dependencies = [ "url", "webkit2gtk", "webview2-com", - "windows", + "windows 0.61.3", ] [[package]] @@ -4183,7 +4183,7 @@ dependencies = [ "url", "webkit2gtk", "webview2-com", - "windows", + "windows 0.61.3", "wry", ] @@ -5118,6 +5118,7 @@ dependencies = [ "webcodex-openai-tunnel", "webcodex-process", "webcodex-runner-config", + "windows 0.62.2", "windows-sys 0.61.2", "winreg 0.55.0", ] @@ -5217,7 +5218,7 @@ checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a" dependencies = [ "webview2-com-macros", "webview2-com-sys", - "windows", + "windows 0.61.3", "windows-core 0.61.2", "windows-implement", "windows-interface", @@ -5241,7 +5242,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c" dependencies = [ "thiserror 2.0.20", - "windows", + "windows 0.61.3", "windows-core 0.61.2", ] @@ -5303,11 +5304,23 @@ version = "0.61.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" dependencies = [ - "windows-collections", + "windows-collections 0.2.0", "windows-core 0.61.2", - "windows-future", + "windows-future 0.2.1", "windows-link 0.1.3", - "windows-numerics", + "windows-numerics 0.2.0", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", ] [[package]] @@ -5319,6 +5332,15 @@ dependencies = [ "windows-core 0.61.2", ] +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", +] + [[package]] name = "windows-core" version = "0.61.2" @@ -5353,7 +5375,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" dependencies = [ "windows-core 0.61.2", "windows-link 0.1.3", - "windows-threading", + "windows-threading 0.1.0", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -5400,6 +5433,16 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", +] + [[package]] name = "windows-registry" version = "0.6.1" @@ -5549,6 +5592,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-version" version = "0.1.7" @@ -5807,7 +5859,7 @@ dependencies = [ "webkit2gtk", "webkit2gtk-sys", "webview2-com", - "windows", + "windows 0.61.3", "windows-core 0.61.2", "windows-version", "x11-dl", diff --git a/apps/desktop/src-tauri/src/commands/mod.rs b/apps/desktop/src-tauri/src/commands/mod.rs index de391b99c..a33e517a8 100644 --- a/apps/desktop/src-tauri/src/commands/mod.rs +++ b/apps/desktop/src-tauri/src/commands/mod.rs @@ -328,6 +328,14 @@ pub async fn refresh_runtime_status( project_state_result(&app, state.refresh_runtime_status().await) } +#[tauri::command] +pub async fn observe_runtime_status( + app: AppHandle, + state: State<'_, AppState>, +) -> Result { + project_state_result(&app, state.observe_runtime_status().await) +} + #[tauri::command] pub async fn observe_chatgpt_activity( app: AppHandle, diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 8445c9e2a..e6a045c67 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -142,6 +142,7 @@ fn desktop_builder() -> tauri::Builder { commands::get_launch_at_login, commands::set_launch_at_login, commands::refresh_runtime_status, + commands::observe_runtime_status, commands::observe_chatgpt_activity, commands::resume_saved_runtime, commands::resume_saved_connections, diff --git a/apps/desktop/src-tauri/src/state.rs b/apps/desktop/src-tauri/src/state.rs index e64010e85..f471fc822 100644 --- a/apps/desktop/src-tauri/src/state.rs +++ b/apps/desktop/src-tauri/src/state.rs @@ -22,6 +22,7 @@ mod projectless_tests; #[cfg(test)] mod reconfiguration_tests; mod runner_capability_grant; +mod runtime_observation; mod runtime_shell; #[cfg(test)] mod shutdown_tests; @@ -104,6 +105,7 @@ pub struct AppState { activity: ActivityLog, operations: OperationController, refresh_lock: tokio::sync::Mutex<()>, + runtime_observation: runtime_observation::RuntimeObservationCache, runner_settings_reader: Arc>, shutdown_signal: CancellationSignal, shutdown_started: AtomicBool, diff --git a/apps/desktop/src-tauri/src/state/app_state.rs b/apps/desktop/src-tauri/src/state/app_state.rs index 958f4ac00..075b19927 100644 --- a/apps/desktop/src-tauri/src/state/app_state.rs +++ b/apps/desktop/src-tauri/src/state/app_state.rs @@ -33,6 +33,7 @@ impl AppState { connections, operations: OperationController::new(activity.clone()), refresh_lock: tokio::sync::Mutex::new(()), + runtime_observation: runtime_observation::RuntimeObservationCache::default(), runner_settings_reader: Arc::new(Mutex::new(())), activity, shutdown_signal: CancellationSignal::new(), @@ -153,35 +154,11 @@ impl AppState { }) } - pub async fn refresh_runtime_status(&self) -> DesktopResult { - if self.shutdown_signal.is_cancelled() { - return Err(cancelled_error()); - } - if let Some(current) = self.operations.observe()? { - return Err(crate::operation::busy_error(¤t)); - } - if self.get_state().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 before_generation = self.get_state().state_generation; - let _refresh_guard = self.refresh_lock.lock().await; - if self.shutdown_signal.is_cancelled() { - return Err(cancelled_error()); - } - if let Some(current) = self.operations.observe()? { - return Err(crate::operation::busy_error(¤t)); - } - // 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()); - } - + async fn refresh_runtime_status_uncached( + &self, + before_generation: u64, + ) -> DesktopResult { + use runtime_observation::RefreshOutcome; let cancellation = CancellationContext::new(CancellationSignal::new(), self.shutdown_signal.clone()); let start_op_generation = self.operations.generation(); @@ -233,12 +210,12 @@ impl AppState { RefreshPlan::QuickShare | RefreshPlan::Unconfigured => { let mut slot = self.core.lock().await; let Some(core) = slot.as_mut() else { - return Ok(self.get_state()); + return Ok(RefreshOutcome::superseded(self.get_state())); }; if self.operations.current().is_some() || self.operations.generation() != start_op_generation { - return Ok(self.get_state()); + return Ok(RefreshOutcome::superseded(self.get_state())); } core.refresh_runtime_status(&cancellation).await?; if operation_completion::reconcile_runtime_errors_after_observation( @@ -246,7 +223,7 @@ impl AppState { ) { core.publish_snapshot(); } - Ok(self.get_state()) + Ok(RefreshOutcome::applied(self.get_state(), None)) } RefreshPlan::Persistent { environment_id } => { let store = environment::store()?; @@ -260,10 +237,11 @@ impl AppState { Some(self.activity.latest_sequence()), ) })?; + let heartbeat = runtime_observation::RuntimeHeartbeat::from(&observed.observation); cancellation.check()?; let mut slot = self.core.lock().await; let Some(core) = slot.as_mut() else { - return Ok(self.get_state()); + return Ok(RefreshOutcome::superseded(self.get_state())); }; if self.operations.current().is_some() || self.operations.generation() != start_op_generation @@ -271,7 +249,7 @@ impl AppState { || core.config.persistent_environment.as_deref() != Some(environment_id.as_str()) { - return Ok(self.get_state()); + return Ok(RefreshOutcome::superseded(self.get_state())); } core.project_environment_result(&store, observed).await?; if operation_completion::reconcile_runtime_errors_after_observation( @@ -279,7 +257,7 @@ impl AppState { ) { core.publish_snapshot(); } - Ok(self.get_state()) + Ok(RefreshOutcome::applied(self.get_state(), Some(heartbeat))) } RefreshPlan::NonPersistent { mut adapter, @@ -365,14 +343,14 @@ impl AppState { let mut slot = self.core.lock().await; let Some(core) = slot.as_mut() else { - return Ok(self.get_state()); + return Ok(RefreshOutcome::superseded(self.get_state())); }; if self.operations.current().is_some() || self.operations.generation() != start_op_generation || core.config.persistent_environment.is_some() || runner_identity_from_config(&core.config).as_ref() != Some(&identity) { - return Ok(self.get_state()); + return Ok(RefreshOutcome::superseded(self.get_state())); } if let Some(binaries) = resolved_binaries { core.snapshot.binaries = Some(binaries.info()); @@ -395,7 +373,7 @@ impl AppState { &mut core.snapshot, ); core.publish_snapshot(); - Ok(self.get_state()) + Ok(RefreshOutcome::applied(self.get_state(), None)) } } } @@ -709,6 +687,7 @@ impl AppState { )); } let mut operation = self.operations.admit(kind, cancellable)?; + self.runtime_observation.invalidate(); let cancellation = operation.cancellation_context(self.shutdown_signal.clone()); // Both waits precede dispatch. Cancelling either wait cannot lose the // core, leave a queued write, or skip cleanup of an external effect. @@ -774,6 +753,7 @@ impl AppState { core.publish_snapshot(); } *self.core.lock().await = Some(core); + self.runtime_observation.invalidate(); operation.finish(&result); match result { Ok(_) => Ok(self.get_state()), diff --git a/apps/desktop/src-tauri/src/state/runtime_observation.rs b/apps/desktop/src-tauri/src/state/runtime_observation.rs new file mode 100644 index 000000000..1a164cbe2 --- /dev/null +++ b/apps/desktop/src-tauri/src/state/runtime_observation.rs @@ -0,0 +1,369 @@ +//! Short-lived display observations. Service control, ownership checks and +//! Diagnostics never consume this cache; they keep their own fresh evidence. + +use super::*; +use std::sync::Mutex as StdMutex; +use std::time::Instant; + +const DISPLAY_OBSERVATION_TTL: Duration = Duration::from_secs(3); +const DISPLAY_HEARTBEAT_TIMEOUT: Duration = Duration::from_millis(750); + +#[derive(Clone, Debug, PartialEq, Eq)] +struct ObservationKey { + state_generation: u64, + operation_generation: u64, + environment_id: Option, +} + +impl ObservationKey { + fn new(snapshot: &DesktopStateSnapshot, operation_generation: u64) -> Self { + Self { + state_generation: snapshot.state_generation, + operation_generation, + environment_id: snapshot.persistent_environment.clone(), + } + } +} + +/// HTTP liveness only: deliberately excludes ServiceStatus, ownership and PIDs. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct RuntimeHeartbeat { + server_reachable: bool, + authenticated: bool, + runner_online: Option, + projects_visible: Vec, + diagnostics: Vec, +} + +impl From<&webcodex_environment::RuntimeObservation> for RuntimeHeartbeat { + fn from(observation: &webcodex_environment::RuntimeObservation) -> Self { + Self { + server_reachable: observation.server_reachable, + authenticated: observation.authenticated, + runner_online: observation.runner_online, + projects_visible: observation.projects_visible.clone(), + diagnostics: observation.diagnostics.clone(), + } + } +} + +pub(super) struct RefreshOutcome { + snapshot: DesktopStateSnapshot, + heartbeat: Option, + applied: bool, +} + +impl RefreshOutcome { + pub(super) fn applied( + snapshot: DesktopStateSnapshot, + heartbeat: Option, + ) -> Self { + Self { + snapshot, + heartbeat, + applied: true, + } + } + + pub(super) fn superseded(snapshot: DesktopStateSnapshot) -> Self { + Self { + snapshot, + heartbeat: None, + applied: false, + } + } +} + +#[derive(Clone, Copy)] +struct ObservationTicket { + epoch: u64, + completion: u64, +} + +struct CompletedObservation { + key: ObservationKey, + result: DesktopResult<()>, + share_until: Instant, +} + +struct CachedObservation { + key: ObservationKey, + observed_at: Instant, + heartbeat: RuntimeHeartbeat, +} + +#[derive(Default)] +struct ObservationState { + epoch: u64, + completion: u64, + completed: Option, + cached: Option, +} + +#[derive(Default)] +pub(super) struct RuntimeObservationCache { + state: StdMutex, +} + +impl RuntimeObservationCache { + pub(super) fn invalidate(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + state.epoch = state.epoch.wrapping_add(1); + state.completed = None; + state.cached = None; + } + + fn ticket(&self) -> ObservationTicket { + let state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + ObservationTicket { + epoch: state.epoch, + completion: state.completion, + } + } + + fn completed_since( + &self, + ticket: ObservationTicket, + key: &ObservationKey, + now: Instant, + ) -> Option> { + let state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let completed = state.completed.as_ref()?; + (state.completion != ticket.completion + && completed.key == *key + && now < completed.share_until) + .then(|| completed.result.clone()) + } + + fn cached_heartbeat(&self, key: &ObservationKey, now: Instant) -> Option { + let state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let cached = state.cached.as_ref()?; + (cached.key == *key && now.duration_since(cached.observed_at) < DISPLAY_OBSERVATION_TTL) + .then(|| cached.heartbeat.clone()) + } + + fn complete_cached( + &self, + ticket: ObservationTicket, + key: &ObservationKey, + now: Instant, + ) -> bool { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if state.epoch != ticket.epoch + || !state.cached.as_ref().is_some_and(|cached| { + cached.key == *key + && now.duration_since(cached.observed_at) < DISPLAY_OBSERVATION_TTL + }) + { + return false; + } + let share_until = state + .cached + .as_ref() + .expect("checked display observation") + .observed_at + + DISPLAY_OBSERVATION_TTL; + // Joining callers may share this heartbeat, but it never extends the + // original native observation's lifetime. + state.completion = state.completion.wrapping_add(1); + state.completed = Some(CompletedObservation { + key: key.clone(), + result: Ok(()), + share_until, + }); + true + } + + fn complete_fresh( + &self, + ticket: ObservationTicket, + key: ObservationKey, + result: DesktopResult<()>, + heartbeat: Option, + observed_at: Instant, + completed_at: Instant, + ) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if state.epoch != ticket.epoch { + return; + } + state.completion = state.completion.wrapping_add(1); + state.cached = if result.is_ok() && key.environment_id.is_some() { + heartbeat.map(|heartbeat| CachedObservation { + key: key.clone(), + observed_at, + heartbeat, + }) + } else { + None + }; + // A failed request is shared only with callers already waiting for it. + // A later request retries immediately instead of caching the failure. + state.completed = Some(CompletedObservation { + key, + result, + share_until: completed_at + DISPLAY_OBSERVATION_TTL, + }); + } +} + +impl AppState { + /// An explicit refresh invalidates previous display evidence and always + /// performs a new observation, including when a background read is in flight. + pub async fn refresh_runtime_status(&self) -> DesktopResult { + self.runtime_observation.invalidate(); + self.runtime_status_observation(false).await + } + + /// Periodic display only. This method never admits a Desktop operation or + /// lends its cached result to service mutations or ownership verification. + pub async fn observe_runtime_status(&self) -> DesktopResult { + self.runtime_status_observation(true).await + } + + fn check_runtime_observation_admission(&self) -> DesktopResult<()> { + if self.shutdown_signal.is_cancelled() { + return Err(cancelled_error()); + } + if let Some(current) = self.operations.observe()? { + return Err(crate::operation::busy_error(¤t)); + } + if self.get_state().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.", + )); + } + Ok(()) + } + + async fn runtime_status_observation( + &self, + allow_cached: bool, + ) -> DesktopResult { + self.check_runtime_observation_admission()?; + let waiting = self.runtime_observation.ticket(); + let _refresh_guard = self.refresh_lock.lock().await; + self.check_runtime_observation_admission()?; + let key = ObservationKey::new(&self.get_state(), self.operations.generation()); + if allow_cached { + if let Some(result) = + self.runtime_observation + .completed_since(waiting, &key, Instant::now()) + { + return result.map(|()| self.get_state()); + } + if let Some(heartbeat) = self + .runtime_observation + .cached_heartbeat(&key, Instant::now()) + { + let ticket = self.runtime_observation.ticket(); + let unchanged = self.runtime_heartbeat_matches(&key, &heartbeat).await; + self.check_runtime_observation_admission()?; + let current_key = + ObservationKey::new(&self.get_state(), self.operations.generation()); + if unchanged + && current_key == key + && self + .runtime_observation + .complete_cached(ticket, &key, Instant::now()) + { + // Read the canonical published state, not a retained copy. + // A cache hit must not reconcile errors as fresh evidence. + return Ok(self.get_state()); + } + self.runtime_observation.invalidate(); + } + } + + let before = self.get_state(); + let operation_generation = self.operations.generation(); + let before_key = ObservationKey::new(&before, operation_generation); + let ticket = self.runtime_observation.ticket(); + let observation_started = Instant::now(); + let observed = self + .refresh_runtime_status_uncached(before.state_generation) + .await; + let current_key = ObservationKey::new(&self.get_state(), self.operations.generation()); + match &observed { + Ok(outcome) + if outcome.applied + && current_key + == ObservationKey::new(&outcome.snapshot, operation_generation) + && current_key.environment_id == before_key.environment_id => + { + self.runtime_observation.complete_fresh( + ticket, + current_key, + Ok(()), + outcome.heartbeat.clone(), + observation_started, + Instant::now(), + ); + } + Err(error) if current_key == before_key => { + self.runtime_observation.complete_fresh( + ticket, + current_key, + Err(error.clone()), + None, + observation_started, + Instant::now(), + ); + } + _ => self.runtime_observation.invalidate(), + } + observed.map(|outcome| outcome.snapshot) + } + + async fn runtime_heartbeat_matches( + &self, + key: &ObservationKey, + expected: &RuntimeHeartbeat, + ) -> bool { + let probe = async { + let store = environment::store().ok()?; + let record = store.load_environment().ok()??; + if Some(&record.environment_id) != key.environment_id.as_ref() { + return None; + } + let mut native = webcodex_environment::NativeEnvironment::new().ok()?; + // The existing EnvironmentBackend heartbeat uses authenticated HTTP + // only. A changed/failed heartbeat triggers the full native query; + // it never authorizes a service action or projects cached ownership. + let observed = + webcodex_environment::EnvironmentBackend::observe(&mut native, &store, &record) + .await + .ok()?; + Some(RuntimeHeartbeat::from(&observed) == *expected) + }; + tokio::select! { + _ = self.shutdown_signal.cancelled() => false, + result = tokio::time::timeout(DISPLAY_HEARTBEAT_TIMEOUT, probe) => { + matches!(result, Ok(Some(true))) + } + } + } +} + +#[cfg(test)] +mod tests; diff --git a/apps/desktop/src-tauri/src/state/runtime_observation/tests.rs b/apps/desktop/src-tauri/src/state/runtime_observation/tests.rs new file mode 100644 index 000000000..39cd57c97 --- /dev/null +++ b/apps/desktop/src-tauri/src/state/runtime_observation/tests.rs @@ -0,0 +1,299 @@ +use super::*; +use std::future::Future; +use std::task::Poll; + +fn key() -> ObservationKey { + ObservationKey { + state_generation: 7, + operation_generation: 2, + environment_id: Some("fixture-environment".into()), + } +} + +fn heartbeat() -> RuntimeHeartbeat { + RuntimeHeartbeat::from(&webcodex_environment::RuntimeObservation { + server_reachable: true, + authenticated: true, + runner_online: Some(true), + projects_visible: vec!["fixture-project".into()], + ..Default::default() + }) +} + +#[test] +fn unchanged_heartbeats_do_not_extend_native_display_evidence() { + let cache = RuntimeObservationCache::default(); + let now = Instant::now(); + cache.complete_fresh(cache.ticket(), key(), Ok(()), Some(heartbeat()), now, now); + let waiting = cache.ticket(); + let later = now + Duration::from_secs(2); + assert!(cache.cached_heartbeat(&key(), later).is_some()); + assert!(cache.complete_cached(cache.ticket(), &key(), later)); + assert!(cache + .completed_since(waiting, &key(), later) + .unwrap() + .is_ok()); + // A queued caller waking late cannot prolong the hit it was waiting for. + assert!(cache + .completed_since(waiting, &key(), now + DISPLAY_OBSERVATION_TTL) + .is_none()); + assert!(cache + .cached_heartbeat(&key(), now + DISPLAY_OBSERVATION_TTL) + .is_none()); + assert!(!cache.complete_cached(cache.ticket(), &key(), now + DISPLAY_OBSERVATION_TTL)); +} + +#[test] +fn invalidation_rejects_a_late_observation_and_changed_targets_never_reuse_it() { + let cache = RuntimeObservationCache::default(); + let old = cache.ticket(); + cache.invalidate(); + cache.complete_fresh( + old, + key(), + Ok(()), + Some(heartbeat()), + Instant::now(), + Instant::now(), + ); + assert!(cache.cached_heartbeat(&key(), Instant::now()).is_none()); + assert!(cache.completed_since(old, &key(), Instant::now()).is_none()); + + cache.complete_fresh( + cache.ticket(), + key(), + Ok(()), + Some(heartbeat()), + Instant::now(), + Instant::now(), + ); + let variants = [ + ObservationKey { + environment_id: Some("another-environment".into()), + ..key() + }, + ObservationKey { + operation_generation: 3, + ..key() + }, + ObservationKey { + state_generation: 8, + ..key() + }, + ]; + for changed in variants { + assert!(cache.cached_heartbeat(&changed, Instant::now()).is_none()); + assert!(cache + .completed_since(old, &changed, Instant::now()) + .is_none()); + } +} + +#[test] +fn failed_observations_are_shared_only_with_existing_waiters() { + let cache = RuntimeObservationCache::default(); + let waiting = cache.ticket(); + let error = DesktopError::new("fixture_unavailable", "Unavailable", "Retry"); + cache.complete_fresh( + waiting, + key(), + Err(error), + None, + Instant::now(), + Instant::now(), + ); + assert_eq!( + cache + .completed_since(waiting, &key(), Instant::now()) + .unwrap() + .unwrap_err() + .code, + "fixture_unavailable" + ); + assert!(cache.cached_heartbeat(&key(), Instant::now()).is_none()); + assert!(cache + .completed_since(cache.ticket(), &key(), Instant::now()) + .is_none()); +} + +#[test] +fn a_slow_fresh_read_is_shared_with_waiters_but_is_already_expired_for_display_reuse() { + let cache = RuntimeObservationCache::default(); + let waiting = cache.ticket(); + let started = Instant::now(); + let completed = started + Duration::from_secs(10); + cache.complete_fresh( + waiting, + key(), + Ok(()), + Some(heartbeat()), + started, + completed, + ); + assert!(cache.cached_heartbeat(&key(), completed).is_none()); + assert!(cache + .completed_since(waiting, &key(), completed) + .unwrap() + .is_ok()); + assert!(cache + .completed_since(waiting, &key(), completed + DISPLAY_OBSERVATION_TTL) + .is_none()); +} + +#[test] +fn heartbeat_changes_include_server_runner_credentials_and_project_visibility() { + let ready = heartbeat(); + for changed in [ + RuntimeHeartbeat { + server_reachable: false, + ..ready.clone() + }, + RuntimeHeartbeat { + authenticated: false, + ..ready.clone() + }, + RuntimeHeartbeat { + runner_online: Some(false), + ..ready.clone() + }, + RuntimeHeartbeat { + projects_visible: Vec::new(), + ..ready.clone() + }, + RuntimeHeartbeat { + diagnostics: vec![webcodex_environment::SetupDiagnostic::new( + "authentication_required", + "Authentication failed", + "Sign in", + )], + ..ready.clone() + }, + ] { + assert_ne!(changed, ready); + } +} + +#[tokio::test] +async fn overlapping_background_requests_share_one_observation_without_admission() { + let dir = tempfile::tempdir().unwrap(); + let state = AppState::new(dir.path().to_path_buf(), dir.path().join("resources")).unwrap(); + let guard = state.refresh_lock.lock().await; + let mut first = Box::pin(state.observe_runtime_status()); + let mut second = Box::pin(state.observe_runtime_status()); + // Queue both requests before releasing the observer; no sleeps or timing race. + std::future::poll_fn(|cx| { + assert!(first.as_mut().poll(cx).is_pending()); + assert!(second.as_mut().poll(cx).is_pending()); + Poll::Ready(()) + }) + .await; + drop(guard); + let (first, second) = tokio::join!(first, second); + let first = first.unwrap(); + let second = second.unwrap(); + assert_eq!(first.state_generation, second.state_generation); + assert!(first.current_operation.is_none()); + assert!(second.current_operation.is_none()); + assert_eq!(state.runtime_observation.ticket().completion, 1); + let before = second.state_generation; + let refreshed = state.refresh_runtime_status().await.unwrap(); + assert!( + refreshed.state_generation > before, + "explicit refresh must run fresh" + ); + assert_eq!(state.runtime_observation.ticket().completion, 2); +} + +#[tokio::test] +async fn background_observation_keeps_diagnostics_readable() { + let dir = tempfile::tempdir().unwrap(); + let state = AppState::new(dir.path().to_path_buf(), dir.path().join("resources")).unwrap(); + let (observed, diagnostics) = tokio::join!(state.observe_runtime_status(), state.diagnostics()); + assert!(observed.unwrap().current_operation.is_none()); + assert!( + diagnostics.is_ok(), + "observation must not claim an exclusive operation slot" + ); +} + +#[tokio::test] +async fn operation_admission_and_completion_invalidate_display_observations() { + let dir = tempfile::tempdir().unwrap(); + let state = AppState::new(dir.path().to_path_buf(), dir.path().join("resources")).unwrap(); + let cache = &state.runtime_observation; + let old = cache.ticket(); + cache.complete_fresh( + old, + key(), + Ok(()), + Some(heartbeat()), + Instant::now(), + Instant::now(), + ); + let (operation, cancellation, core, baseline) = state + .begin_operation(DesktopOperationKind::RunnerSettingsUpdate, false) + .await + .unwrap(); + assert!(cache.cached_heartbeat(&key(), Instant::now()).is_none()); + assert_eq!( + state.observe_runtime_status().await.unwrap_err().code, + "desktop_operation_busy" + ); + cache.complete_fresh( + old, + key(), + Ok(()), + Some(heartbeat()), + Instant::now(), + Instant::now(), + ); + assert!(cache.cached_heartbeat(&key(), Instant::now()).is_none()); + let during = cache.ticket(); + cache.complete_fresh( + during, + key(), + Ok(()), + Some(heartbeat()), + Instant::now(), + Instant::now(), + ); + state + .finish_operation( + operation, + cancellation, + core, + baseline, + Ok(state.get_state()), + ) + .await + .unwrap(); + assert!(cache.cached_heartbeat(&key(), Instant::now()).is_none()); + assert!(state.get_state().current_operation.is_none()); +} + +#[tokio::test] +async fn superseded_observation_cannot_publish_or_cache_an_old_operation_generation() { + let dir = tempfile::tempdir().unwrap(); + let state = AppState::new(dir.path().to_path_buf(), dir.path().join("resources")).unwrap(); + let core = state.core.lock().await; + let before = state.get_state().state_generation; + let mut observed = Box::pin(state.observe_runtime_status()); + std::future::poll_fn(|cx| { + assert!(observed.as_mut().poll(cx).is_pending()); + Poll::Ready(()) + }) + .await; + let operation = state + .operations + .admit(DesktopOperationKind::RunnerSettingsUpdate, false) + .unwrap(); + drop(core); + let snapshot = observed.await.unwrap(); + assert_eq!(snapshot.state_generation, before); + assert_eq!( + snapshot.current_operation.as_ref().unwrap().kind, + DesktopOperationKind::RunnerSettingsUpdate + ); + assert_eq!(state.runtime_observation.ticket().completion, 0); + operation.finish(&Ok::<(), DesktopError>(())); +} diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs index 1331448b3..6d608195b 100644 --- a/apps/desktop/src-tauri/src/tray.rs +++ b/apps/desktop/src-tauri/src/tray.rs @@ -254,7 +254,7 @@ 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 { + if let Ok(fresh) = state.observe_runtime_status().await { snapshot = fresh; } } diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index 3a46196c2..2b6551ccd 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -21,6 +21,7 @@ const api = vi.hoisted(() => ({ updateTunnelConfig: vi.fn(), openPowerShellInstallGuide: vi.fn(), refresh: vi.fn(), + observeRuntimeStatus: vi.fn(), observeChatgptActivity: vi.fn(), resumeSavedRuntime: vi.fn(), resumeSavedConnections: vi.fn(), @@ -286,6 +287,7 @@ beforeEach(() => { api.configureLocal.mockResolvedValue(projectlessReadyState); api.inspectLocalMigration.mockResolvedValue({ fingerprint: "original", resuming: false }); api.observeChatgptActivity.mockResolvedValue(readyState); + api.observeRuntimeStatus.mockResolvedValue(readyState); api.updateTunnelProxy.mockResolvedValue(readyState); api.startRegularTunnel.mockResolvedValue(readyState); api.stopRegularTunnel.mockResolvedValue(readyState); @@ -410,7 +412,8 @@ beforeEach(() => { const runtime = deferred(); let refreshing = false; let inventoryUpdated = false; - api.refresh.mockImplementation(() => { refreshing = true; return runtime.promise; }); + const readRuntime = trigger === "automatic" ? api.observeRuntimeStatus : api.refresh; + readRuntime.mockImplementation(() => { refreshing = true; return runtime.promise; }); const normal = workspace.invoke.getMockImplementation()!; workspace.invoke.mockImplementation((command, args) => { if (refreshing) return Promise.reject(new Error("workspace_unavailable")); @@ -430,6 +433,9 @@ beforeEach(() => { const before = workspace.invoke.mock.calls.length; if (trigger === "manual") fireEvent.click(screen.getByRole("button", { name: "刷新" })); else await act(async () => { await vi.advanceTimersByTimeAsync(1_500); }); + expect(readRuntime).toHaveBeenCalledTimes(1); + if (trigger === "automatic") expect(api.refresh).toHaveBeenCalledTimes(1); + else expect(api.observeRuntimeStatus).not.toHaveBeenCalled(); await act(async () => { await vi.advanceTimersByTimeAsync(30_000); }); expect(workspace.invoke.mock.calls.length).toBe(before); expect(screen.getByRole("button", {name:/^项目\s*1$/})).toBeInTheDocument(); @@ -459,7 +465,7 @@ beforeEach(() => { const selected = { ...readyState, persistent_environment: "fixture-environment" }; api.getState.mockResolvedValue(selected); api.refresh.mockResolvedValueOnce(selected); - api.refresh.mockImplementation(() => new Promise(resolve => { + api.observeRuntimeStatus.mockImplementation(() => new Promise(resolve => { window.setTimeout(() => resolve(selected), 100); })); vi.useFakeTimers(); @@ -470,7 +476,8 @@ beforeEach(() => { const count = () => workspace.invoke.mock.calls.filter(([, args]) => args.request.kind === "overview").length; expect(count()).toBe(1); await act(async () => { await vi.advanceTimersByTimeAsync(6_000); }); - expect(api.refresh.mock.calls.length).toBeGreaterThan(2); + expect(api.observeRuntimeStatus.mock.calls.length).toBeGreaterThan(2); + expect(api.refresh).toHaveBeenCalledTimes(1); expect(count()).toBe(1); await act(async () => { await vi.advanceTimersByTimeAsync(10_000); }); expect(count()).toBeGreaterThanOrEqual(2); @@ -486,7 +493,8 @@ beforeEach(() => { const running = { ...idle, current_operation: localSetupOperationState().current_operation }; api.getState.mockResolvedValueOnce(idle).mockResolvedValueOnce(running).mockResolvedValue(idle); if (trigger === "poll") api.refresh.mockResolvedValueOnce(idle); - api.refresh.mockRejectedValueOnce({ code: "desktop_operation_busy", message: "Busy", next_action: "Wait" }); + const readRuntime = trigger === "poll" ? api.observeRuntimeStatus : api.refresh; + readRuntime.mockRejectedValueOnce({ code: "desktop_operation_busy", message: "Busy", next_action: "Wait" }); const view = renderApp(); try { await act(async () => {}); diff --git a/apps/desktop/src/hooks/useDesktopWorkspace.ts b/apps/desktop/src/hooks/useDesktopWorkspace.ts index 960fd8205..055b5e76e 100644 --- a/apps/desktop/src/hooks/useDesktopWorkspace.ts +++ b/apps/desktop/src/hooks/useDesktopWorkspace.ts @@ -256,7 +256,7 @@ export function useDesktopWorkspace() { if (refreshRuntime) setRuntimeObservations(count => count + 1); try { const next = refreshRuntime - ? await refreshOrObserveDesktopState() + ? await refreshOrObserveDesktopState("observe") : await desktopApi.getState(); if (next && !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..f797583ef 100644 --- a/apps/desktop/src/lib/desktop-api.ts +++ b/apps/desktop/src/lib/desktop-api.ts @@ -88,6 +88,7 @@ export const desktopApi = { setLaunchAtLogin: (enabled: boolean) => invoke("set_launch_at_login", { request: { enabled } }), refresh: () => invoke("refresh_runtime_status"), + observeRuntimeStatus: () => invoke("observe_runtime_status"), observeChatgptActivity: () => invoke("observe_chatgpt_activity"), resumeSavedRuntime: () => invoke("resume_saved_runtime"), resumeSavedConnections: () => invoke("resume_saved_connections"), diff --git a/apps/desktop/src/lib/desktop-observation.ts b/apps/desktop/src/lib/desktop-observation.ts index 434bebe28..01ff1eb1f 100644 --- a/apps/desktop/src/lib/desktop-observation.ts +++ b/apps/desktop/src/lib/desktop-observation.ts @@ -19,11 +19,11 @@ export function desktopIdentity(state: DesktopState): string { ]); } -// Refresh probes the runtime. The published state remains available while a -// mutation owns it and carries the exact operation the user can observe or stop. -export async function refreshOrObserveDesktopState(): Promise { +// Explicit refreshes always probe the runtime; periodic observation may share +// the native display cache. Published state stays readable during a mutation. +export async function refreshOrObserveDesktopState(mode: "refresh" | "observe" = "refresh"): Promise { try { - return await desktopApi.refresh(); + return await (mode === "observe" ? desktopApi.observeRuntimeStatus() : desktopApi.refresh()); } catch (value) { const { code } = normalizeDesktopError(value); if (code !== "desktop_operation_busy" && code !== "desktop_operation_unsettled") throw value; diff --git a/crates/webcodex-environment/Cargo.toml b/crates/webcodex-environment/Cargo.toml index 709325791..4a4dc7866 100644 --- a/crates/webcodex-environment/Cargo.toml +++ b/crates/webcodex-environment/Cargo.toml @@ -33,8 +33,9 @@ libc = "0.2" [target.'cfg(windows)'.dependencies] winreg = "0.55" webcodex-process = { path = "../webcodex-process" } +windows = { version = "0.62.2", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Ole", "Win32_System_TaskScheduler", "Win32_System_Variant"] } -windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Authentication_Identity", "Win32_Security_Credentials", "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Threading", "Win32_System_Services", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Graphics_Gdi", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Authentication_Identity", "Win32_Security_Credentials", "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_LibraryLoader", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Threading", "Win32_System_Services", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] } [dev-dependencies] tempfile = "3" diff --git a/crates/webcodex-environment/src/local_status.rs b/crates/webcodex-environment/src/local_status.rs index 696228868..31d862b20 100644 --- a/crates/webcodex-environment/src/local_status.rs +++ b/crates/webcodex-environment/src/local_status.rs @@ -39,50 +39,63 @@ struct ServiceProbe { type ServiceProbeResult = SetupResultValue<(ServiceStatus, Option)>; -fn inspect_probe(probe: ServiceProbe) -> ServiceProbeResult { - let spec = probe.spec?; - if probe.with_pid { - ServiceManager::inspect_with_pid(&spec).map_err(crate::native::service_error) - } else { - ServiceManager::inspect(&spec) - .map(|status| (status, None)) - .map_err(crate::native::service_error) - } +fn inspect_probes(probes: Vec) -> Vec { + inspect_probes_with(probes, |requests| { + ServiceManager::inspect_many(requests) + .into_iter() + .map(|result| result.map_err(crate::native::service_error)) + .collect() + }) } -/// Task Scheduler inspection starts a PowerShell process. Keep independent -/// observations concurrent but bounded; the source order remains stable, and a -/// failing query cannot turn an unknown owner into a successful observation. -fn inspect_probes(probes: Vec, windows_user: bool) -> Vec { - if !windows_user { - return probes.into_iter().map(inspect_probe).collect(); - } - - const MAX_CONCURRENT_PROBES: usize = 3; - let mut observations = Vec::with_capacity(probes.len()); - let mut remaining = probes.into_iter(); - loop { - let group: Vec<_> = remaining.by_ref().take(MAX_CONCURRENT_PROBES).collect(); - if group.is_empty() { - break; - } - std::thread::scope(|scope| { - let tasks: Vec<_> = group - .into_iter() - .map(|probe| scope.spawn(move || inspect_probe(probe))) - .collect(); - for task in tasks { - observations.push(task.join().unwrap_or_else(|_| { +/// Collect one native snapshot, coalescing identical saved owners (including +/// embedded Tunnels). Results retain input order and each probe's failure. +fn inspect_probes_with( + probes: Vec, + observe: impl FnOnce(&[(&crate::service::ServiceSpec, bool)]) -> Vec, +) -> Vec { + let mut unique: Vec<(crate::service::ServiceSpec, bool)> = Vec::new(); + let indices: Vec<_> = probes + .iter() + .map(|probe| { + let spec = probe.spec.as_ref().map_err(Clone::clone)?; + let index = if let Some(index) = unique.iter().position(|(owner, _)| owner == spec) { + unique[index].1 |= probe.with_pid; + index + } else { + unique.push((spec.clone(), probe.with_pid)); + unique.len() - 1 + }; + Ok(index) + }) + .collect(); + let requests: Vec<_> = unique + .iter() + .map(|(spec, with_pid)| (spec, *with_pid)) + .collect(); + let observed = if requests.is_empty() { + Vec::new() + } else { + observe(&requests) + }; + indices + .into_iter() + .zip(probes) + .map(|(index, probe)| { + let index = index?; + observed + .get(index) + .cloned() + .unwrap_or_else(|| { Err(SetupDiagnostic::new( "local_observation_unavailable", "Native service status could not be observed", "Inspect the service owner before retrying", )) - })); - } - }); - } - observations + }) + .map(|(status, pid)| (status, probe.with_pid.then_some(pid).flatten())) + }) + .collect() } pub(crate) fn collect( @@ -157,10 +170,7 @@ pub(crate) fn collect( } } - let observed = inspect_probes( - probes, - cfg!(windows) && record.request.service_scope == crate::service::ServiceScope::User, - ); + let observed = inspect_probes(probes); if let Some(index) = server_index { result.components.push(observation( Component::Server.as_str(), @@ -318,6 +328,100 @@ fn linger(record: &EnvironmentRecord) -> Option { mod tests { use super::*; + fn probe_spec(identity: &str) -> crate::service::ServiceSpec { + crate::service::ServiceSpec { + scope: ServiceScope::User, + id: "observation-fixture".into(), + component: Component::Server, + program: std::env::temp_dir().join("observation-fixture"), + args: vec!["--config".into(), "fixture.toml".into()], + working_directory: std::env::temp_dir(), + account: crate::service::ServiceAccount::SystemUser { + name: "fixture".into(), + group: None, + expected_identity: "fixture-identity".into(), + home: None, + }, + config_identity: identity.into(), + env_file: None, + environment: Default::default(), + linux_socket: None, + } + } + + #[test] + fn one_snapshot_coalesces_identical_owners_but_keeps_pid_intent_and_failures() { + let owner = probe_spec("first"); + let other = probe_spec("second"); + let plans = vec![ + ServiceProbe { + spec: Ok(owner.clone()), + with_pid: false, + }, + ServiceProbe { + spec: Err(SetupDiagnostic::new( + "invalid_plan", + "Invalid fixture", + "Inspect", + )), + with_pid: true, + }, + ServiceProbe { + spec: Ok(other), + with_pid: true, + }, + ServiceProbe { + spec: Ok(owner), + with_pid: true, + }, + ]; + let observed = inspect_probes_with(plans, |requests| { + // Same task name with a different saved identity is never merged. + assert_eq!(requests.len(), 2); + assert_eq!(requests[0].0.config_identity, "first"); + assert_eq!(requests[1].0.config_identity, "second"); + assert!(requests[0].1 && requests[1].1); + vec![ + Ok(( + ServiceStatus { + id: "observation-fixture".into(), + ownership: Ownership::Owned, + installed: true, + enabled: Some(true), + running: Some(true), + detail: None, + }, + Some(42), + )), + Err(SetupDiagnostic::new( + "owner_unknown", + "Unknown fixture", + "Inspect", + )), + ] + }); + assert_eq!(observed.len(), 4); + assert_eq!(observed[0].as_ref().unwrap().1, None); + assert_eq!(observed[1].as_ref().unwrap_err().code, "invalid_plan"); + assert_eq!(observed[2].as_ref().unwrap_err().code, "owner_unknown"); + assert_eq!(observed[3].as_ref().unwrap().1, Some(42)); + } + + #[test] + fn missing_batch_results_never_become_successful_observations() { + let observed = inspect_probes_with( + vec![ServiceProbe { + spec: Ok(probe_spec("missing")), + with_pid: true, + }], + |_| Vec::new(), + ); + assert_eq!( + observed[0].as_ref().unwrap_err().code, + "local_observation_unavailable" + ); + } + #[test] fn bounded_service_probes_preserve_order_and_fail_closed() { let codes = [ @@ -338,7 +442,7 @@ mod tests { with_pid: true, }) .collect(); - let results = inspect_probes(plans, true); + let results = inspect_probes(plans); assert_eq!(results.len(), codes.len()); for (actual, code) in results.into_iter().zip(codes) { assert_eq!(actual.err().expect("probe must fail").code, code); diff --git a/crates/webcodex-environment/src/service/mod.rs b/crates/webcodex-environment/src/service/mod.rs index c6ac8f5d6..f64452ea8 100644 --- a/crates/webcodex-environment/src/service/mod.rs +++ b/crates/webcodex-environment/src/service/mod.rs @@ -314,13 +314,75 @@ impl ServiceManager { Ok((status, pid)) } + /// Read one bounded presentation snapshot. Windows user tasks share a + /// native scheduler connection; this never caches mutation authorization. + pub(crate) fn inspect_many( + probes: &[(&ServiceSpec, bool)], + ) -> Vec), ServiceError>> { + // One Server, one Runner, and the existing sixteen-profile limit. + if probes.len() > 18 { + return probes + .iter() + .map(|_| { + Err(ServiceError::new( + ServiceErrorCode::InvalidSpec, + "Service observation exceeds its bounded batch size", + )) + }) + .collect(); + } + #[cfg(windows)] + let mut user_probes = Vec::new(); + let results: Vec<_> = probes + .iter() + .map(|(spec, with_pid)| { + if let Err(error) = validate_spec(spec) { + return Err(error); + } + #[cfg(windows)] + if spec.scope == ServiceScope::User { + user_probes.push((*spec, *with_pid)); + // Replaced by the native batch below, including failures. + return Err(ServiceError::new( + ServiceErrorCode::OwnershipUnknown, + "Native service status has not been observed", + )); + } + if *with_pid { + Self::inspect_with_pid(spec) + } else { + Self::inspect(spec).map(|status| (status, None)) + } + }) + .collect(); + #[cfg(windows)] + { + let mut results = results; + let observations = windows_user::inspect_many(&user_probes); + let mut observed = observations.into_iter(); + for ((spec, _), result) in probes.iter().zip(&mut results) { + if spec.scope == ServiceScope::User && validate_spec(spec).is_ok() { + *result = observed.next().unwrap_or_else(|| { + Err(ServiceError::new( + ServiceErrorCode::OwnershipUnknown, + "Native service observation was incomplete", + )) + }); + } + } + results + } + #[cfg(not(windows))] + results + } + /// Current manager-owned process only. Unsupported managers fail closed. pub fn running_pid(spec: &ServiceSpec) -> Result, ServiceError> { validate_spec(spec)?; #[cfg(windows)] if spec.scope == ServiceScope::User { // The adapter independently verifies the task and its exact live - // action PID; a separate inspect would spawn another PowerShell. + // action PID; a separate inspect would duplicate the observation. return windows_user::running_pid(spec); } let status = Self::inspect(spec)?; @@ -777,6 +839,28 @@ mod tests { ); } + #[test] + fn observation_batch_rejects_invalid_plans_without_native_access() { + let mut invalid = sample_spec(); + invalid.id.clear(); + let observed = ServiceManager::inspect_many(&[(&invalid, false), (&invalid, true)]); + assert_eq!(observed.len(), 2); + assert!(observed + .iter() + .all(|result| result.as_ref().unwrap_err().code == ServiceErrorCode::InvalidSpec)); + } + + #[test] + fn observation_batch_has_the_same_eighteen_component_bound_as_local_status() { + let spec = sample_spec(); + let observed = ServiceManager::inspect_many(&vec![(&spec, true); 19]); + assert_eq!(observed.len(), 19); + assert!(observed + .iter() + .all(|result| result.as_ref().unwrap_err().code == ServiceErrorCode::InvalidSpec)); + assert!(ServiceManager::inspect_many(&[]).is_empty()); + } + pub(super) fn sample_spec() -> ServiceSpec { ServiceSpec { scope: ServiceScope::System, diff --git a/crates/webcodex-environment/src/service/windows_user.ps1 b/crates/webcodex-environment/src/service/windows_user.ps1 index 899e33fc4..ba09aff10 100644 --- a/crates/webcodex-environment/src/service/windows_user.ps1 +++ b/crates/webcodex-environment/src/service/windows_user.ps1 @@ -348,83 +348,74 @@ public static class WebCodexTaskProcessWait { # Leave headroom inside the Rust adapter's 55-second command deadline. $operationDeadline = [DateTime]::UtcNow.AddSeconds(45) $task = Read-Task - if ($inputData.operation -notin @('inspect', 'running_pid')) { - if ($null -ne $task -and !(Owned-Task $task)) { throw 'foreign task' } - switch ($inputData.operation) { - 'install' { - if ($null -eq $task) { - $definition = $scheduler.NewTask(0) - $definition.RegistrationInfo.Description = $inputData.description - $definition.Principal.UserId = $inputData.sid - $definition.Principal.LogonType = 3 - $definition.Principal.RunLevel = 0 - $trigger = $definition.Triggers.Create(9) - $trigger.UserId = $inputData.sid - $trigger.Enabled = $true - $action = $definition.Actions.Create(0) - if ($inputData.host) { - $action.Path = $inputData.host - $action.Arguments = $inputData.host_arguments - } else { - $action.Path = $inputData.program - $action.Arguments = $inputData.arguments - } - $action.WorkingDirectory = $inputData.directory - $definition.Settings.MultipleInstances = 2 - $definition.Settings.ExecutionTimeLimit = 'PT0S' - $definition.Settings.AllowHardTerminate = $true - $definition.Settings.DisallowStartIfOnBatteries = $false - $definition.Settings.StopIfGoingOnBatteries = $false - $definition.Settings.StartWhenAvailable = $true - $definition.Settings.RestartCount = 3 - $definition.Settings.RestartInterval = 'PT1M' - $definition.Settings.Enabled = $true - $null = $folder.RegisterTaskDefinition($inputData.name, $definition, 2, $inputData.sid, $null, 3, $null) + if ($null -ne $task -and !(Owned-Task $task)) { throw 'foreign task' } + switch ($inputData.operation) { + 'install' { + if ($null -eq $task) { + $definition = $scheduler.NewTask(0) + $definition.RegistrationInfo.Description = $inputData.description + $definition.Principal.UserId = $inputData.sid + $definition.Principal.LogonType = 3 + $definition.Principal.RunLevel = 0 + $trigger = $definition.Triggers.Create(9) + $trigger.UserId = $inputData.sid + $trigger.Enabled = $true + $action = $definition.Actions.Create(0) + if ($inputData.host) { + $action.Path = $inputData.host + $action.Arguments = $inputData.host_arguments } else { - if ($task.State -in @(1,3)) { $task = Use-ConsoleFreeAction $task } - if (!$task.Enabled) { $task.Enabled = $true } + $action.Path = $inputData.program + $action.Arguments = $inputData.arguments } + $action.WorkingDirectory = $inputData.directory + $definition.Settings.MultipleInstances = 2 + $definition.Settings.ExecutionTimeLimit = 'PT0S' + $definition.Settings.AllowHardTerminate = $true + $definition.Settings.DisallowStartIfOnBatteries = $false + $definition.Settings.StopIfGoingOnBatteries = $false + $definition.Settings.StartWhenAvailable = $true + $definition.Settings.RestartCount = 3 + $definition.Settings.RestartInterval = 'PT1M' + $definition.Settings.Enabled = $true + $null = $folder.RegisterTaskDefinition($inputData.name, $definition, 2, $inputData.sid, $null, 3, $null) + } else { + if ($task.State -in @(1,3)) { $task = Use-ConsoleFreeAction $task } + if (!$task.Enabled) { $task.Enabled = $true } } - 'start' { - if ($null -eq $task) { throw 'missing task' } - if (!$task.Enabled) { throw 'disabled task' } - if ($task.State -eq 3) { - $task = Use-ConsoleFreeAction $task - $task = Start-OwnedTask $task $operationDeadline $null - } elseif ($task.State -notin @(2,4)) { throw 'start state unknown' } - } - 'stop' { - if ($null -eq $task) { throw 'missing task' } - $task = Stop-OwnedTask $task $operationDeadline - } - 'restart' { - if ($null -eq $task -or !$task.Enabled) { throw 'missing or disabled task' } - if ($task.State -notin @(2,3,4)) { throw 'restart state unknown' } - $task = Restart-OwnedTask $task $operationDeadline - } - 'uninstall' { - if ($null -ne $task) { - if ($task.State -notin @(1,3)) { throw 'stop required' } - $folder.DeleteTask($inputData.name, 0) - } + } + 'start' { + if ($null -eq $task) { throw 'missing task' } + if (!$task.Enabled) { throw 'disabled task' } + if ($task.State -eq 3) { + $task = Use-ConsoleFreeAction $task + $task = Start-OwnedTask $task $operationDeadline $null + } elseif ($task.State -notin @(2,4)) { throw 'start state unknown' } + } + 'stop' { + if ($null -eq $task) { throw 'missing task' } + $task = Stop-OwnedTask $task $operationDeadline + } + 'restart' { + if ($null -eq $task -or !$task.Enabled) { throw 'missing or disabled task' } + if ($task.State -notin @(2,3,4)) { throw 'restart state unknown' } + $task = Restart-OwnedTask $task $operationDeadline + } + 'uninstall' { + if ($null -ne $task) { + if ($task.State -notin @(1,3)) { throw 'stop required' } + $folder.DeleteTask($inputData.name, 0) } - default { throw 'unsupported operation' } } - $task = Read-Task + default { throw 'unsupported operation' } } + $task = Read-Task if ($null -eq $task) { @{ exists=$false } | ConvertTo-Json -Compress } else { $observation = @{ exists=$true; owned=(Owned-Task $task); enabled=[bool]$task.Enabled; state=[int]$task.State } if ($observation.owned -and $task.State -in @(1,3)) { $observation.last_task_result = [int64]$task.LastTaskResult } - if ($inputData.operation -eq 'running_pid') { - $process = Read-ActionProcess $task - if ($null -ne $process) { - $observation.process_id = $process.process_id - $observation.instance_guid = $process.instance_guid - } - } $observation | ConvertTo-Json -Compress } } catch { diff --git a/crates/webcodex-environment/src/service/windows_user.rs b/crates/webcodex-environment/src/service/windows_user.rs index 5872ab738..399475219 100644 --- a/crates/webcodex-environment/src/service/windows_user.rs +++ b/crates/webcodex-environment/src/service/windows_user.rs @@ -1,13 +1,35 @@ //! Per-user interactive Task Scheduler adapter. No password, UAC or SCM account. -//! A fixed native script consumes bounded non-secret JSON as child-local data; +//! Read-only observations use Task Scheduler COM and query-only process handles. +//! Mutations use a fixed script with bounded non-secret JSON as child-local data; //! callers cannot supply script text. New tasks are registered create-only. use super::*; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; +#[cfg(windows)] +mod native; + const SCRIPT: &str = include_str!("windows_user.ps1"); -fn task_request(spec: &ServiceSpec, operation: &str) -> Result { +#[derive(Clone, serde::Serialize)] +struct TaskPlan { + #[cfg(windows)] + #[serde(skip)] + id: String, + #[cfg(windows)] + #[serde(skip)] + home: PathBuf, + name: String, + description: String, + sid: String, + program: String, + arguments: String, + host: Option, + host_arguments: String, + directory: String, +} + +fn task_plan(spec: &ServiceSpec) -> Result { let (sid, _) = scope::user_account(spec)?; let quote = |value: &str| -> String { let mut out = String::from("\""); @@ -59,11 +81,32 @@ fn task_request(spec: &ServiceSpec, operation: &str) -> Result Result { + let mut request = serde_json::to_value(task_plan(spec)?) + .map_err(|_| ServiceError::new(ServiceErrorCode::InvalidSpec, "Cannot encode task plan"))?; + request["operation"] = json!(operation); + Ok(request) } // The installed GUI and its runtime are verified and updated as one package. @@ -188,7 +231,23 @@ fn decode_status(spec: &ServiceSpec, value: &Value) -> Result, + enabled: Option, + last_result: Option, +) -> ServiceStatus { + let running = match state { Some(2 | 4) => Some(true), // queued/running Some(1 | 3) => Some(false), // disabled/ready _ => None, @@ -197,65 +256,24 @@ fn decode_status(spec: &ServiceSpec, value: &Value) -> Result Result, ServiceError> { - let status = decode_status(spec, value)?; - if status.ownership != Ownership::Owned || value["state"].as_u64() != Some(4) { - return Ok(None); - } - if value.get("process_id").is_none_or(Value::is_null) { - return Ok(None); - } - let pid = value["process_id"] - .as_u64() - .and_then(|pid| u32::try_from(pid).ok()) - .filter(|pid| *pid != 0); - let instance = value["instance_guid"] - .as_str() - .and_then(|id| uuid::Uuid::parse_str(id).ok()) - .filter(|id| !id.is_nil()); - match (pid, instance) { - (Some(pid), Some(_)) => Ok(Some(pid)), - _ => Err(ServiceError::new( - ServiceErrorCode::OwnershipUnknown, - "Task Scheduler did not confirm a live action process", - )), } } -#[cfg(any(windows, test))] -fn decode_status_with_pid( - spec: &ServiceSpec, - value: &Value, -) -> Result<(ServiceStatus, Option), ServiceError> { - Ok(( - decode_status(spec, value)?, - decode_running_pid(spec, value)?, - )) -} - #[cfg(windows)] fn call_value(spec: &ServiceSpec, operation: &str) -> Result { use crate::process::CommandOutputExt; @@ -325,20 +343,29 @@ fn call(spec: &ServiceSpec, operation: &str) -> Result Result, ServiceError> { - decode_running_pid(spec, &call_value(spec, "running_pid")?) + inspect_with_pid(spec).map(|(_, pid)| pid) } #[cfg(windows)] pub(super) fn inspect_with_pid( spec: &ServiceSpec, ) -> Result<(ServiceStatus, Option), ServiceError> { - let value = call_value(spec, "running_pid")?; - decode_status_with_pid(spec, &value) + native::inspect_many(&[(spec, true)]).remove(0) } #[cfg(windows)] pub(super) fn inspect(spec: &ServiceSpec) -> Result { - call(spec, "inspect") + native::inspect_many(&[(spec, false)]) + .remove(0) + .map(|(status, _)| status) +} + +/// A fresh batch shares one COM connection, never a cached ownership/PID result. +#[cfg(windows)] +pub(super) fn inspect_many( + probes: &[(&ServiceSpec, bool)], +) -> Vec), ServiceError>> { + native::inspect_many(probes) } #[cfg(windows)] pub(super) fn preflight(spec: &ServiceSpec) -> Result { @@ -435,67 +462,6 @@ mod tests { ); assert!(!request.to_string().contains("--windows-service")); } - #[test] - fn user_task_status_and_pid_share_one_owner_checked_observation() { - let spec = super::super::tests::sample_spec(); - let current = json!({ - "exists": true, "owned": true, "enabled": true, "state": 4, - "process_id": 4312, - "instance_guid": "{723A491B-825B-4C30-BB2B-F86AA98F94AA}" - }); - let (status, pid) = decode_status_with_pid(&spec, ¤t).unwrap(); - assert_eq!(status.ownership, Ownership::Owned); - assert_eq!(status.running, Some(true)); - assert_eq!(pid, Some(4312)); - let mut foreign = current.clone(); - foreign["owned"] = json!(false); - assert_eq!(decode_status_with_pid(&spec, &foreign).unwrap().1, None); - let mut invalid = current; - invalid["instance_guid"] = json!("unknown"); - assert!(decode_status_with_pid(&spec, &invalid).is_err()); - } - - #[test] - fn user_task_running_pid_requires_a_live_owned_action_observation() { - let spec = super::super::tests::sample_spec(); - let current = json!({ - "exists": true, "owned": true, "enabled": true, "state": 4, - "process_id": 4312, - "instance_guid": "{723A491B-825B-4C30-BB2B-F86AA98F94AA}" - }); - assert_eq!(decode_running_pid(&spec, ¤t).unwrap(), Some(4312)); - for state in [0, 1, 2, 3] { - let mut observation = current.clone(); - observation["state"] = json!(state); - assert_eq!(decode_running_pid(&spec, &observation).unwrap(), None); - } - let mut foreign = current.clone(); - foreign["owned"] = json!(false); - assert_eq!(decode_running_pid(&spec, &foreign).unwrap(), None); - let mut missing = current.clone(); - missing.as_object_mut().unwrap().remove("process_id"); - assert_eq!(decode_running_pid(&spec, &missing).unwrap(), None); - for pid in [ - json!(0), - json!(-1), - json!(u64::from(u32::MAX) + 1), - json!("4312"), - ] { - let mut invalid = current.clone(); - invalid["process_id"] = pid; - assert!(decode_running_pid(&spec, &invalid).is_err()); - } - for instance in [ - Value::Null, - json!("unknown"), - json!(uuid::Uuid::nil().to_string()), - ] { - let mut invalid = current.clone(); - invalid["instance_guid"] = instance; - assert!(decode_running_pid(&spec, &invalid).is_err()); - } - } - #[cfg(windows)] #[test] fn console_free_worker_has_no_console_and_preserves_exit_and_redirected_streams() { diff --git a/crates/webcodex-environment/src/service/windows_user/native.rs b/crates/webcodex-environment/src/service/windows_user/native.rs new file mode 100644 index 000000000..fa0e281d4 --- /dev/null +++ b/crates/webcodex-environment/src/service/windows_user/native.rs @@ -0,0 +1,505 @@ +//! Fresh, read-only Task Scheduler observations. No shell, WMI, or PS fallback. +//! +//! COM can block in a local RPC. Exactly one worker and a bounded queue contain +//! that failure: callers have a deadline, expired requests are discarded, and a +//! timed-out worker is never replaced. A permanently blocked COM call therefore +//! leaves observations unknown until this process is restarted, not an unbounded +//! number of abandoned threads. COM interfaces never cross the worker boundary. +use super::{ + observed_status, task_plan, ServiceError, ServiceErrorCode, ServiceSpec, ServiceStatus, + TaskPlan, +}; +use std::sync::{mpsc, OnceLock}; +use std::time::{Duration, Instant}; +use windows::core::{Interface, BSTR}; +use windows::Win32::Foundation::VARIANT_BOOL; +use windows::Win32::System::Com::{ + CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, +}; +use windows::Win32::System::TaskScheduler::*; +use windows::Win32::System::Variant::VARIANT; + +mod process; +#[cfg(test)] +mod tests; + +type Observation = Result<(ServiceStatus, Option), ServiceError>; +const MAX_BATCH_PROBES: usize = 18; // Server, Runner, and sixteen Tunnel profiles. +const MAX_QUEUED_BATCHES: usize = 8; +const OBSERVATION_TIMEOUT: Duration = Duration::from_secs(55); +const MAX_TASKS: i32 = 4096; +const MAX_TEXT: usize = 32767; + +struct Probe { + plan: TaskPlan, + with_pid: bool, +} + +struct Request { + probes: Vec>, + deadline: Instant, + response: mpsc::SyncSender>, +} + +fn unknown() -> ServiceError { + ServiceError::new( + ServiceErrorCode::OutcomeUnknown, + "Native Task Scheduler observation unavailable or incomplete; inspect again before control", + ) +} + +fn check_deadline(deadline: Instant) -> Result<(), ServiceError> { + if Instant::now() < deadline { + Ok(()) + } else { + Err(unknown()) + } +} + +fn make_probe(spec: &ServiceSpec, with_pid: bool) -> Result { + if !spec.environment.is_empty() { + return Err(ServiceError::new( + ServiceErrorCode::InvalidSpec, + "User Task Scheduler does not inject environment values", + )); + } + let plan = task_plan(spec)?; + let fields = [ + &plan.id, + &plan.name, + &plan.description, + &plan.sid, + &plan.program, + &plan.arguments, + &plan.host_arguments, + &plan.directory, + ]; + let size = fields + .iter() + .map(|value| value.encode_utf16().count()) + .sum::() + + plan + .host + .as_deref() + .map_or(0, |host| host.encode_utf16().count()) + + plan + .home + .as_os_str() + .to_string_lossy() + .encode_utf16() + .count(); + if size > 24_000 + || fields.iter().any(|value| value.contains('\0')) + || plan.host.as_deref().is_some_and(|host| host.contains('\0')) + { + return Err(ServiceError::new( + ServiceErrorCode::InvalidSpec, + "Task plan exceeds its native input budget or contains a NUL", + )); + } + Ok(Probe { plan, with_pid }) +} + +pub(super) fn inspect_many(probes: &[(&ServiceSpec, bool)]) -> Vec { + if probes.is_empty() { + return Vec::new(); + } + if probes.len() > MAX_BATCH_PROBES { + return probes + .iter() + .map(|_| { + Err(ServiceError::new( + ServiceErrorCode::InvalidSpec, + "Task observation batch exceeds its native input budget", + )) + }) + .collect(); + } + let prepared = probes + .iter() + .map(|(spec, pid)| make_probe(spec, *pid)) + .collect(); + static WORKER: OnceLock, ()>> = OnceLock::new(); + let worker = WORKER.get_or_init(|| spawn_worker(observe_batch).map_err(|_| ())); + let result = match worker { + Ok(worker) => request(worker, prepared, OBSERVATION_TIMEOUT), + Err(()) => Err(unknown()), + }; + result.unwrap_or_else(|error| probes.iter().map(|_| Err(error.clone())).collect()) +} + +fn request( + worker: &mpsc::SyncSender, + probes: Vec>, + timeout: Duration, +) -> Result, ServiceError> { + let deadline = Instant::now() + timeout; + let (response, receive) = mpsc::sync_channel(1); + // Never block trying to enqueue behind a stalled COM call. + worker + .try_send(Request { + probes, + deadline, + response, + }) + .map_err(|_| unknown())?; + let result = receive + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .map_err(|_| unknown())?; + check_deadline(deadline)?; + Ok(result) +} + +fn spawn_worker( + mut observe: impl FnMut(Vec>, Instant) -> Vec + + Send + + 'static, +) -> std::io::Result> { + let (send, receive) = mpsc::sync_channel::(MAX_QUEUED_BATCHES); + std::thread::Builder::new() + .name("webcodex-task-observer".into()) + .spawn(move || { + while let Ok(request) = receive.recv() { + if check_deadline(request.deadline).is_err() { + continue; + } + let result = observe(request.probes, request.deadline); + if check_deadline(request.deadline).is_ok() { + let _ = request.response.try_send(result); + } + } + })?; + Ok(send) +} + +struct Apartment; +impl Apartment { + fn new() -> Result { + // This is our dedicated thread, never a borrowed UI/STA apartment. + unsafe { CoInitializeEx(None, COINIT_MULTITHREADED).ok() }.map_err(|_| unknown())?; + Ok(Self) + } +} +impl Drop for Apartment { + fn drop(&mut self) { + unsafe { + CoUninitialize(); + } + } +} + +struct Context { + _scheduler: ITaskService, + folder: ITaskFolder, + owner: super::super::CurrentAccount, + computer: String, +} + +fn context() -> Result { + let owner = super::super::current_account()?; + let computer = process::computer_name().ok_or_else(unknown)?; + let scheduler: ITaskService = + unsafe { CoCreateInstance(&TaskScheduler, None, CLSCTX_INPROC_SERVER) } + .map_err(|_| unknown())?; + let empty = VARIANT::default(); + unsafe { scheduler.Connect(&empty, &empty, &empty, &empty) }.map_err(|_| unknown())?; + let folder = unsafe { scheduler.GetFolder(&BSTR::from("\\")) }.map_err(|_| unknown())?; + Ok(Context { + _scheduler: scheduler, + folder, + owner, + computer, + }) +} + +fn observe_batch(probes: Vec>, deadline: Instant) -> Vec { + let apartment = Apartment::new(); + // Apartment is dropped only after every COM object (including Context). + let context = apartment + .as_ref() + .map_err(Clone::clone) + .and_then(|_| context()); + probes.into_iter().map(|probe| { + let probe = probe?; + check_deadline(deadline)?; + let context = context.as_ref().map_err(Clone::clone)?; + if probe.plan.sid != context.owner.identity || probe.plan.home != context.owner.home { + return Err(ServiceError::new(ServiceErrorCode::PermissionDenied, + "Run this user service operation as the saved environment owner; no system fallback is allowed")); + } + observe(context, &probe, deadline) + }).collect() +} + +fn read_task( + folder: &ITaskFolder, + name: &str, + deadline: Instant, +) -> Result, ServiceError> { + check_deadline(deadline)?; + match unsafe { folder.GetTask(&BSTR::from(name)) } { + Ok(task) => return Ok(Some(task)), + Err(error) if missing_task_hresult(error.code().0) => {} + Err(_) => return Err(unknown()), + } + // Enumeration may omit inaccessible tasks. It can corroborate an explicit + // file-not-found result, but must never turn access/RPC failures into absence. + let tasks = unsafe { folder.GetTasks(TASK_ENUM_HIDDEN.0) }.map_err(|_| unknown())?; + let count = unsafe { tasks.Count() }.map_err(|_| unknown())?; + if !(0..=MAX_TASKS).contains(&count) { + return Err(unknown()); + } + for index in 1..=count { + check_deadline(deadline)?; + let task = unsafe { tasks.get_Item(&VARIANT::from(index)) }.map_err(|_| unknown())?; + if process::equal_ignore_case(&text(unsafe { task.Name() })?, name) { + return Err(unknown()); + } + } + if unsafe { tasks.Count() }.map_err(|_| unknown())? != count { + return Err(unknown()); + } + Ok(None) +} + +fn missing_task_hresult(code: i32) -> bool { + code == 0x80070002u32 as i32 // HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) +} + +fn out( + get: impl FnOnce(*mut T) -> windows::core::Result<()>, +) -> Result { + let mut value = T::default(); + get(&mut value).map_err(|_| unknown())?; + Ok(value) +} + +fn text(value: windows::core::Result) -> Result { + let value = value.map_err(|_| unknown())?; + if value.len() > MAX_TEXT || value.iter().any(|ch| *ch == 0) { + return Err(unknown()); + } + String::from_utf16(&value).map_err(|_| unknown()) +} + +fn string( + get: impl FnOnce(*mut BSTR) -> windows::core::Result<()>, +) -> Result { + let value = out(get)?; + text(Ok(value)) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct Action { + program: String, + arguments: String, +} + +fn owned_action( + definition: &ITaskDefinition, + plan: &TaskPlan, + computer: &str, + deadline: Instant, +) -> Result, ServiceError> { + check_deadline(deadline)?; + let info = unsafe { definition.RegistrationInfo() }.map_err(|_| unknown())?; + let principal = unsafe { definition.Principal() }.map_err(|_| unknown())?; + if string(|v| unsafe { info.Description(v) })? != plan.description + || !process::account_matches( + &string(|v| unsafe { principal.UserId(v) })?, + &plan.sid, + computer, + ) + || out(|v| unsafe { principal.LogonType(v) })? != TASK_LOGON_INTERACTIVE_TOKEN + || out(|v| unsafe { principal.RunLevel(v) })? != TASK_RUNLEVEL_LUA + { + return Ok(None); + } + let actions = unsafe { definition.Actions() }.map_err(|_| unknown())?; + if out(|v| unsafe { actions.Count(v) })? != 1 { + return Ok(None); + } + let action = unsafe { actions.get_Item(1) }.map_err(|_| unknown())?; + if out(|v| unsafe { action.Type(v) })? != TASK_ACTION_EXEC { + return Ok(None); + } + let action: IExecAction = action.cast().map_err(|_| unknown())?; + let observed = Action { + program: string(|v| unsafe { action.Path(v) })?, + arguments: string(|v| unsafe { action.Arguments(v) })?, + }; + let direct = observed.program == plan.program && observed.arguments == plan.arguments; + let hosted = + plan.host.as_ref() == Some(&observed.program) && observed.arguments == plan.host_arguments; + if (!direct && !hosted) || string(|v| unsafe { action.WorkingDirectory(v) })? != plan.directory + { + return Ok(None); + } + check_deadline(deadline)?; + let triggers = unsafe { definition.Triggers() }.map_err(|_| unknown())?; + if out(|v| unsafe { triggers.Count(v) })? != 1 { + return Ok(None); + } + let trigger = unsafe { triggers.get_Item(1) }.map_err(|_| unknown())?; + if out(|v| unsafe { trigger.Type(v) })? != TASK_TRIGGER_LOGON + || !boolean(|v| unsafe { trigger.Enabled(v) })? + { + return Ok(None); + } + let trigger: ILogonTrigger = trigger.cast().map_err(|_| unknown())?; + if !process::account_matches( + &string(|v| unsafe { trigger.UserId(v) })?, + &plan.sid, + computer, + ) { + return Ok(None); + } + let settings = unsafe { definition.Settings() }.map_err(|_| unknown())?; + if out(|v| unsafe { settings.MultipleInstances(v) })? != TASK_INSTANCES_IGNORE_NEW + || string(|v| unsafe { settings.ExecutionTimeLimit(v) })? != "PT0S" + || !boolean(|v| unsafe { settings.AllowHardTerminate(v) })? + || out(|v| unsafe { settings.RestartCount(v) })? != 3 + || string(|v| unsafe { settings.RestartInterval(v) })? != "PT1M" + || !boolean(|v| unsafe { settings.StartWhenAvailable(v) })? + || boolean(|v| unsafe { settings.DisallowStartIfOnBatteries(v) })? + || boolean(|v| unsafe { settings.StopIfGoingOnBatteries(v) })? + { + return Ok(None); + } + Ok(Some(observed)) +} + +fn boolean( + get: impl FnOnce(*mut VARIANT_BOOL) -> windows::core::Result<()>, +) -> Result { + Ok(out(get)?.0 != 0) +} + +fn observe(context: &Context, probe: &Probe, deadline: Instant) -> Observation { + let plan = &probe.plan; + let Some(task) = read_task(&context.folder, &plan.name, deadline)? else { + return Ok((ServiceStatus::absent(&plan.id), None)); + }; + let definition = unsafe { task.Definition() }.map_err(|_| unknown())?; + let action = owned_action(&definition, plan, &context.computer, deadline)?; + let state = unsafe { task.State() }.map_err(|_| unknown())?; + let enabled = unsafe { task.Enabled() }.map_err(|_| unknown())?.0 != 0; + let last_result = unsafe { task.LastTaskResult() }.map_err(|_| unknown())?; + let status = observed_status( + &plan.id, + action.is_some(), + Some(i64::from(state.0)), + Some(enabled), + Some(i64::from(last_result)), + ); + let pid = if probe.with_pid && state == TASK_STATE_RUNNING { + match action { + Some(action) => running_process(context, &task, &action, plan, deadline)?, + None => None, + } + } else { + None + }; + check_deadline(deadline)?; + Ok((status, pid)) +} + +#[derive(Debug, PartialEq, Eq)] +struct Instance { + guid: uuid::Uuid, + engine_pid: u32, +} + +fn instance(task: &IRegisteredTask) -> Result, ServiceError> { + let instances = unsafe { task.GetInstances(0) }.map_err(|_| unknown())?; + if unsafe { instances.Count() }.map_err(|_| unknown())? != 1 { + return Ok(None); + } + let instance = unsafe { instances.get_Item(&VARIANT::from(1)) }.map_err(|_| unknown())?; + if unsafe { instance.State() }.map_err(|_| unknown())? != TASK_STATE_RUNNING { + return Ok(None); + } + let guid = uuid::Uuid::parse_str(&text(unsafe { instance.InstanceGuid() })?) + .ok() + .filter(|id| !id.is_nil()); + let engine_pid = unsafe { instance.EnginePID() }.map_err(|_| unknown())?; + Ok(guid + .filter(|_| engine_pid != 0) + .map(|guid| Instance { guid, engine_pid })) +} + +fn running_process( + context: &Context, + task: &IRegisteredTask, + action: &Action, + plan: &TaskPlan, + deadline: Instant, +) -> Result, ServiceError> { + let Some(initial) = instance(task)? else { + return Ok(None); + }; + // EnginePID may be taskeng/svchost. Never search the machine for some other + // matching action: it must itself be our exact process (or packaged host). + let Some(host) = process::Process::open(initial.engine_pid) else { + return Ok(None); + }; + let hosted = plan.host.as_ref() == Some(&action.program); + let worker_action = Action { + program: plan.program.clone(), + arguments: plan.arguments.clone(), + }; + let mut first_host = None; + let mut first_worker = None; + let mut pinned_worker = None; + for _ in 0..2 { + check_deadline(deadline)?; + let Some(host_read) = host.read() else { + return Ok(None); + }; + if !host_read.matches(action, &plan.sid) { + return Ok(None); + } + if first_host.is_some_and(|birth| birth != host_read.created) { + return Ok(None); + } + first_host = Some(host_read.created); + let worker_read = if hosted { + let Some(worker) = + process::matching_child(initial.engine_pid, &worker_action, deadline) + else { + return Ok(None); + }; + let Some(observed) = worker.read() else { + return Ok(None); + }; + if !observed.matches(&worker_action, &plan.sid) || observed.created < host_read.created + { + return Ok(None); + } + pinned_worker = Some(worker); + observed + } else { + host_read + }; + let identity = (worker_read.pid, worker_read.created); + if first_worker.is_some_and(|first| first != identity) { + return Ok(None); + } + first_worker = Some(identity); + } + let Some(current) = read_task(&context.folder, &plan.name, deadline)? else { + return Ok(None); + }; + let definition = unsafe { current.Definition() }.map_err(|_| unknown())?; + if owned_action(&definition, plan, &context.computer, deadline)?.as_ref() != Some(action) + || unsafe { current.State() }.map_err(|_| unknown())? != TASK_STATE_RUNNING + || instance(¤t)?.as_ref() != Some(&initial) + || !host.is_alive() + || pinned_worker + .as_ref() + .is_some_and(|worker| !worker.is_alive()) + { + return Ok(None); + } + Ok(first_worker.map(|(pid, _)| pid)) +} diff --git a/crates/webcodex-environment/src/service/windows_user/native/process.rs b/crates/webcodex-environment/src/service/windows_user/native/process.rs new file mode 100644 index 000000000..13ffd4761 --- /dev/null +++ b/crates/webcodex-environment/src/service/windows_user/native/process.rs @@ -0,0 +1,556 @@ +//! Query-only Windows process/SID observations. Handles pin the observed object; +//! no termination, VM-write, impersonation, or debug privileges are requested. +use super::{Action, MAX_TEXT}; +use std::ffi::c_void; +use std::mem::{size_of, size_of_val, transmute}; +use std::ptr::{null, null_mut}; +use std::time::Instant; +use windows_sys::Win32::Foundation::{ + CloseHandle, GetLastError, LocalFree, ERROR_INSUFFICIENT_BUFFER, ERROR_NO_MORE_FILES, FILETIME, + HANDLE, INVALID_HANDLE_VALUE, WAIT_TIMEOUT, +}; +use windows_sys::Win32::Globalization::CompareStringOrdinal; +use windows_sys::Win32::Security::Authorization::{ConvertSidToStringSidW, ConvertStringSidToSidW}; +use windows_sys::Win32::Security::{ + GetTokenInformation, GetWindowsAccountDomainSid, IsValidSid, LookupAccountNameW, TokenUser, + SID_NAME_USE, TOKEN_QUERY, TOKEN_USER, +}; +use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS, +}; +use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; +use windows_sys::Win32::System::SystemInformation::{ComputerNameNetBIOS, GetComputerNameExW}; +use windows_sys::Win32::System::Threading::{ + GetProcessTimes, OpenProcess, OpenProcessToken, QueryFullProcessImageNameW, + WaitForSingleObject, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, +}; +use windows_sys::Win32::UI::Shell::CommandLineToArgvW; + +#[cfg(test)] +mod tests; + +struct Handle(HANDLE); +impl Drop for Handle { + fn drop(&mut self) { + unsafe { + CloseHandle(self.0); + } + } +} + +struct Local(*mut c_void); +impl Drop for Local { + fn drop(&mut self) { + unsafe { + LocalFree(self.0); + } + } +} + +pub(super) struct Process { + handle: Handle, + pid: u32, +} + +#[derive(Clone, Debug)] +pub(super) struct Observation { + pub pid: u32, + pub created: u64, + owner: String, + image: String, + argv: Vec, +} + +impl Observation { + fn matches_action(&self, action: &Action) -> bool { + let Some(expected) = parse_command(&format!("webcodex {}", action.arguments)) else { + return false; + }; + self.argv.len() == expected.len() + && executable_path_matches(&self.image, &action.program) + && self + .argv + .first() + .is_some_and(|path| executable_path_matches(path, &action.program)) + && self.argv[1..] == expected[1..] + } + + pub(super) fn matches(&self, action: &Action, sid: &str) -> bool { + self.owner == sid && self.created != 0 && self.matches_action(action) + } +} + +impl Process { + pub(super) fn open(pid: u32) -> Option { + if pid == 0 { + return None; + } + let handle = unsafe { + OpenProcess( + PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE, + 0, + pid, + ) + }; + if handle.is_null() { + None + } else { + Some(Self { + handle: Handle(handle), + pid, + }) + } + } + + pub(super) fn is_alive(&self) -> bool { + unsafe { WaitForSingleObject(self.handle.0, 0) == WAIT_TIMEOUT } + } + + pub(super) fn read(&self) -> Option { + if !self.is_alive() { + return None; + } + let mut birth: FILETIME = unsafe { std::mem::zeroed() }; + let mut exit = birth; + let mut kernel = birth; + let mut user = birth; + if unsafe { GetProcessTimes(self.handle.0, &mut birth, &mut exit, &mut kernel, &mut user) } + == 0 + { + return None; + } + let created = (u64::from(birth.dwHighDateTime) << 32) | u64::from(birth.dwLowDateTime); + if created == 0 { + return None; + } + let mut image = vec![0u16; MAX_TEXT + 1]; + let mut size = image.len() as u32; + if unsafe { QueryFullProcessImageNameW(self.handle.0, 0, image.as_mut_ptr(), &mut size) } + == 0 + || size == 0 + || size as usize > MAX_TEXT + { + return None; + } + let image = String::from_utf16(&image[..size as usize]).ok()?; + let argv = parse_command(&command_line(self.handle.0)?)?; + let owner = process_owner(self.handle.0)?; + if !self.is_alive() { + return None; + } + Some(Observation { + pid: self.pid, + created, + owner, + image, + argv, + }) + } +} + +fn process_owner(process: HANDLE) -> Option { + let mut token = null_mut(); + if unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) } == 0 { + return None; + } + let token = Handle(token); + let mut needed = 0; + unsafe { + GetTokenInformation(token.0, TokenUser, null_mut(), 0, &mut needed); + } + if unsafe { GetLastError() } != ERROR_INSUFFICIENT_BUFFER + || needed < size_of::() as u32 + || needed > 4096 + { + return None; + } + // TOKEN_USER contains a pointer, so keep the buffer naturally aligned. + let mut buffer = vec![0usize; (needed as usize).div_ceil(size_of::())]; + let capacity = needed; + if unsafe { + GetTokenInformation( + token.0, + TokenUser, + buffer.as_mut_ptr().cast(), + capacity, + &mut needed, + ) + } == 0 + || needed > capacity + { + return None; + } + let sid = unsafe { (*buffer.as_ptr().cast::()).User.Sid }; + sid_text(sid) +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct UnicodeString { + length: u16, + maximum_length: u16, + buffer: *const u16, +} + +type QueryProcess = unsafe extern "system" fn(HANDLE, i32, *mut c_void, u32, *mut u32) -> i32; + +fn command_line(handle: HANDLE) -> Option { + // ProcessCommandLineInformation (60) is supported on our Windows 10 target, + // but is an internal information class, not a stable Win32 contract. Follow + // Microsoft's dynamic-link guidance. Unavailable/changed ABI means an + // unconfirmed PID; never read arbitrary PEB layouts or launch a fallback. + // https://learn.microsoft.com/windows/win32/api/winternl/nf-winternl-ntqueryinformationprocess + let module = unsafe { GetModuleHandleW(wide("ntdll.dll")?.as_ptr()) }; + if module.is_null() { + return None; + } + let address = unsafe { GetProcAddress(module, c"NtQueryInformationProcess".as_ptr().cast()) }?; + // The exported NT ABI has the fixed signature above on both 32/64-bit Windows. + let query = unsafe { transmute:: isize, QueryProcess>(address) }; + let mut needed = 0u32; + let status = unsafe { query(handle, 60, null_mut(), 0, &mut needed) }; + const LENGTH_MISMATCH: i32 = 0xc0000004u32 as i32; + const BUFFER_TOO_SMALL: i32 = 0xc0000023u32 as i32; + let maximum = size_of::() + (MAX_TEXT + 1) * 2; + if !matches!(status, LENGTH_MISMATCH | BUFFER_TOO_SMALL) + || needed < size_of::() as u32 + || needed as usize > maximum + { + return None; + } + let mut buffer = vec![0usize; (needed as usize).div_ceil(size_of::())]; + let mut returned = 0; + if unsafe { + query( + handle, + 60, + buffer.as_mut_ptr().cast(), + needed, + &mut returned, + ) + } < 0 + || returned < size_of::() as u32 + || returned > needed + { + return None; + } + // Returned pointers must refer into this output buffer, not target memory. + let descriptor = unsafe { *buffer.as_ptr().cast::() }; + let start = buffer.as_ptr() as usize; + let pointer = descriptor.buffer as usize; + let length = usize::from(descriptor.length); + if length == 0 + || length % 2 != 0 + || length / 2 > MAX_TEXT + || descriptor.maximum_length < descriptor.length + || pointer % std::mem::align_of::() != 0 + || pointer < start.checked_add(size_of::())? + || pointer.checked_add(length)? > start.checked_add(returned as usize)? + { + return None; + } + let value = unsafe { std::slice::from_raw_parts(descriptor.buffer, length / 2) }; + if value.contains(&0) { + return None; + } + String::from_utf16(value).ok() +} + +pub(super) fn parse_command(command: &str) -> Option> { + if command.is_empty() || command.encode_utf16().count() > MAX_TEXT { + return None; + } + let command = wide(command)?; + let mut count = 0; + let values = unsafe { CommandLineToArgvW(command.as_ptr(), &mut count) }; + if values.is_null() { + return None; + } + let _allocation = Local(values.cast()); + if !(1..=4096).contains(&count) { + return None; + } + let mut total = 0; + let mut result = Vec::with_capacity(count as usize); + for index in 0..count as usize { + // CommandLineToArgvW owns these NUL-terminated strings until LocalFree. + let pointer = unsafe { *values.add(index) }; + if pointer.is_null() { + return None; + } + let mut len = 0; + while len <= MAX_TEXT && unsafe { *pointer.add(len) } != 0 { + len += 1; + } + total += len; + if total > MAX_TEXT { + return None; + } + result.push(String::from_utf16(unsafe { std::slice::from_raw_parts(pointer, len) }).ok()?); + } + Some(result) +} + +pub(super) fn matching_child(parent: u32, action: &Action, deadline: Instant) -> Option { + let children = child_pids(parent, deadline)?; + let mut matched = None; + for pid in children { + if Instant::now() >= deadline { + return None; + } + // An unreadable direct child can hide another match; fail closed rather + // than treating inaccessible command lines as evidence of non-identity. + let child = Process::open(pid)?; + if child.read()?.matches_action(action) { + if matched.is_some() { + return None; + } + matched = Some(child); + } + } + matched +} + +fn child_pids(parent: u32, deadline: Instant) -> Option> { + let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; + if snapshot == INVALID_HANDLE_VALUE || snapshot.is_null() { + return None; + } + let snapshot = Handle(snapshot); + let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() }; + entry.dwSize = size_of::() as u32; + let mut result = Vec::new(); + let mut available = unsafe { Process32FirstW(snapshot.0, &mut entry) }; + let mut visited = 0; + while available != 0 { + visited += 1; + if visited > 65536 || Instant::now() >= deadline { + return None; + } + if entry.th32ParentProcessID == parent { + if entry.th32ProcessID == 0 || result.len() >= 4096 { + return None; + } + result.push(entry.th32ProcessID); + } + available = unsafe { Process32NextW(snapshot.0, &mut entry) }; + } + if unsafe { GetLastError() } != ERROR_NO_MORE_FILES { + return None; + } + Some(result) +} + +fn wide(value: &str) -> Option> { + if value.contains('\0') || value.encode_utf16().count() > MAX_TEXT { + return None; + } + Some(value.encode_utf16().chain(Some(0)).collect()) +} + +pub(super) fn equal_ignore_case(left: &str, right: &str) -> bool { + let left: Vec = left.encode_utf16().collect(); + let right: Vec = right.encode_utf16().collect(); + if left.len() > MAX_TEXT || right.len() > MAX_TEXT { + return false; + } + // Match .NET OrdinalIgnoreCase, including non-ASCII executable names. + unsafe { + CompareStringOrdinal( + left.as_ptr(), + left.len() as i32, + right.as_ptr(), + right.len() as i32, + 1, + ) == 2 + } +} + +pub(super) fn executable_path_matches(observed: &str, expected: &str) -> bool { + if observed.is_empty() || expected.is_empty() { + return false; + } + if equal_ignore_case(observed, expected) { + return true; + } + let prefix = r"\\?\"; + let (normal, extended) = match (observed.strip_prefix(prefix), expected.strip_prefix(prefix)) { + (Some(extended), None) => (expected, extended), + (None, Some(extended)) => (observed, extended), + _ => return false, + }; + equal_ignore_case(normal, extended) && unambiguous_dos_path(normal) +} + +fn unambiguous_dos_path(path: &str) -> bool { + let bytes = path.as_bytes(); + if bytes.len() < 4 || !bytes[0].is_ascii_alphabetic() || &bytes[1..3] != b":\\" { + return false; + } + path[3..].split('\\').all(|part| { + if part.is_empty() + || part.ends_with(['.', ' ']) + || part + .chars() + .any(|ch| ch <= '\u{1f}' || "<>:\"/|?*".contains(ch)) + { + return false; + } + let name = part + .split('.') + .next() + .unwrap_or_default() + .trim_end_matches(' ') + .to_ascii_uppercase(); + !matches!( + name.as_str(), + "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" + ) && !["COM", "LPT"].iter().any(|prefix| { + name.strip_prefix(prefix).is_some_and(|suffix| { + matches!( + suffix, + "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³" + ) + }) + }) + }) +} + +pub(super) fn computer_name() -> Option { + let mut buffer = [0u16; 256]; + let mut size = buffer.len() as u32; + if unsafe { GetComputerNameExW(ComputerNameNetBIOS, buffer.as_mut_ptr(), &mut size) } == 0 + || size == 0 + || size as usize >= buffer.len() + { + return None; + } + String::from_utf16(&buffer[..size as usize]).ok() +} + +struct Sid { + text: String, + domain: Option, +} + +pub(super) fn account_matches(identity: &str, expected: &str, computer: &str) -> bool { + account_matches_with(identity, expected, computer, resolve_account) +} + +fn account_matches_with( + identity: &str, + expected: &str, + computer: &str, + mut resolve: impl FnMut(&str) -> Option, +) -> bool { + let resolved = resolve(identity); + if resolved.as_ref().is_some_and(|sid| sid.text == expected) { + return true; + } + // Preserve only the bare computer/local-user name collision exception. No + // qualified account, UPN, different user/group, or foreign domain is adopted. + if identity.trim().is_empty() + || identity.contains(['\\', '/', '@']) + || identity + .get(..4) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case("S-1-")) + || !equal_ignore_case(identity, computer) + { + return false; + } + let Some(local) = resolve(&format!("{computer}\\{identity}")) else { + return false; + }; + local.text == expected && resolved.is_none_or(|sid| local.domain.as_ref() == Some(&sid.text)) +} + +fn resolve_account(identity: &str) -> Option { + if identity.trim().is_empty() { + return None; + } + let name = wide(identity)?; + if identity + .get(..4) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case("S-1-")) + { + let mut sid = null_mut(); + if unsafe { ConvertStringSidToSidW(name.as_ptr(), &mut sid) } == 0 { + return None; + } + let _allocation = Local(sid); + return Some(Sid { + text: sid_text(sid)?, + domain: domain_sid(sid), + }); + } + let mut sid_len = 0; + let mut domain_len = 0; + let mut kind: SID_NAME_USE = 0; + unsafe { + LookupAccountNameW( + null(), + name.as_ptr(), + null_mut(), + &mut sid_len, + null_mut(), + &mut domain_len, + &mut kind, + ); + } + if unsafe { GetLastError() } != ERROR_INSUFFICIENT_BUFFER + || sid_len == 0 + || sid_len > 68 + || domain_len as usize > MAX_TEXT + { + return None; + } + let mut sid = vec![0usize; (sid_len as usize).div_ceil(size_of::())]; + let mut domain = vec![0u16; domain_len as usize]; + if unsafe { + LookupAccountNameW( + null(), + name.as_ptr(), + sid.as_mut_ptr().cast(), + &mut sid_len, + domain.as_mut_ptr(), + &mut domain_len, + &mut kind, + ) + } == 0 + { + return None; + } + Some(Sid { + text: sid_text(sid.as_mut_ptr().cast())?, + domain: domain_sid(sid.as_mut_ptr().cast()), + }) +} + +fn domain_sid(sid: *mut c_void) -> Option { + let mut domain = [0usize; 68usize.div_ceil(size_of::())]; + let mut size = size_of_val(&domain) as u32; + if unsafe { GetWindowsAccountDomainSid(sid, domain.as_mut_ptr().cast(), &mut size) } == 0 { + return None; + } + sid_text(domain.as_mut_ptr().cast()) +} + +fn sid_text(sid: *mut c_void) -> Option { + if sid.is_null() || unsafe { IsValidSid(sid) } == 0 { + return None; + } + let mut value = null_mut(); + if unsafe { ConvertSidToStringSidW(sid, &mut value) } == 0 || value.is_null() { + return None; + } + let _allocation = Local(value.cast()); + let mut len = 0; + // A textual SID is at most 184 UTF-16 code units including its terminator. + while len < 184 && unsafe { *value.add(len) } != 0 { + len += 1; + } + if len == 0 || len == 184 { + return None; + } + String::from_utf16(unsafe { std::slice::from_raw_parts(value, len) }).ok() +} diff --git a/crates/webcodex-environment/src/service/windows_user/native/process/tests.rs b/crates/webcodex-environment/src/service/windows_user/native/process/tests.rs new file mode 100644 index 000000000..19e86bd35 --- /dev/null +++ b/crates/webcodex-environment/src/service/windows_user/native/process/tests.rs @@ -0,0 +1,185 @@ +use super::*; + +#[test] +fn native_path_comparison_preserves_the_narrow_extended_dos_equivalence() { + let ordinary = r"C:\Program Files\WebCodex\测试\webcodex-server.exe"; + let extended = format!(r"\\?\{ordinary}"); + for observed in [ordinary, &extended] { + for expected in [ordinary, &extended] { + assert!(executable_path_matches(observed, expected)); + } + } + assert!(executable_path_matches( + r"C:\Äpps\WebCodex.exe", + r"c:\äPPS\WEBCODEX.EXE" + )); + for ordinary in [ + r"C:\CON Tools\WebCodex.exe", + r"D:\COM10\WebCodex.exe", + r"E:\.local\WebCodex.exe", + ] { + assert!(executable_path_matches( + ordinary, + &format!(r"\\?\{ordinary}") + )); + } + for ordinary in [ + r"C:Apps\webcodex.exe", + r"\Apps\webcodex.exe", + r"Apps\webcodex.exe", + "C:/Apps/webcodex.exe", + r"C:\Apps\\webcodex.exe", + r"C:\Apps\.\webcodex.exe", + r"C:\Apps\..\webcodex.exe", + r"C:\Apps.\webcodex.exe", + r"C:\Apps \webcodex.exe", + r"C:\Apps\webcodex.exe.", + r"C:\Apps\webcodex.exe ", + r"C:\Apps\webcodex.exe:other", + "C:\\Apps\\", + "C:\\", + r"C:\CON\webcodex.exe", + r"C:\nul.txt\webcodex.exe", + r"C:\COM1\webcodex.exe", + r"C:\LPT9\webcodex.exe", + r"C:\CONIN$\webcodex.exe", + r"C:\CONOUT$.txt\webcodex.exe", + r"C:\AUX .txt\webcodex.exe", + r"C:\Apps\PRN.txt", + r"C:\Apps\nul.tar.gz", + r"C:\COM¹\webcodex.exe", + r"C:\LPT².txt\webcodex.exe", + ] { + let extended = format!(r"\\?\{ordinary}"); + assert!(!executable_path_matches(ordinary, &extended)); + assert!(!executable_path_matches(&extended, ordinary)); + } + for character in ['<', '>', '"', '|', '?', '*', '\0', '\u{1}', '\u{1f}'] { + let ordinary = format!(r"C:\App{character}s\webcodex.exe"); + assert!(!executable_path_matches( + &ordinary, + &format!(r"\\?\{ordinary}") + )); + } + assert!(!executable_path_matches( + r"\\server\share\webcodex.exe", + r"\\?\UNC\server\share\webcodex.exe" + )); + assert!(!executable_path_matches( + r"\\.\C:\Apps\webcodex.exe", + r"C:\Apps\webcodex.exe" + )); + assert!(!executable_path_matches("", "")); +} + +#[test] +fn native_argv_and_owner_matching_rejects_lookalike_actions() { + let action = Action { + program: r"C:\WebCodex\测试\server.exe".into(), + arguments: r#""--config" "C:\环境\Config.toml" "a\"b" "trailing\\""#.into(), + }; + let command = format!(r#""{}" {}"#, action.program, action.arguments); + let observed = Observation { + pid: 4312, + created: 1234, + owner: "S-1-5-21-1-2-3-1001".into(), + image: action.program.clone(), + argv: parse_command(&command).unwrap(), + }; + assert!(observed.matches(&action, &observed.owner)); + for image in [action.program.clone(), format!(r"\\?\{}", action.program)] { + for argv0 in [action.program.clone(), format!(r"\\?\{}", action.program)] { + let mut value = observed.clone(); + value.image = image.clone(); + value.argv[0] = argv0; + assert!(value.matches(&action, &value.owner)); + } + } + let mut changed = observed.clone(); + changed.argv[1] = "--CONFIG".into(); + assert!(!changed.matches(&action, &changed.owner)); + assert!(!observed.matches(&action, "S-1-5-21-1-2-3-1002")); + changed = observed.clone(); + changed.created = 0; + assert!(!changed.matches(&action, &changed.owner)); + changed = observed.clone(); + changed.image = r"C:\Other\server.exe".into(); + assert!(!changed.matches(&action, &changed.owner)); + assert!(parse_command("").is_none()); + assert!(parse_command("server.exe\0 --config").is_none()); + assert!(parse_command(&"x".repeat(MAX_TEXT + 1)).is_none()); + assert!(parse_command(&format!("server.exe {}", "x ".repeat(4096))).is_none()); +} + +#[test] +fn native_sid_resolution_preserves_only_the_bare_computer_collision_exception() { + let owner = "S-1-5-21-1-2-3-1001"; + let domain = "S-1-5-21-1-2-3"; + let resolve = |name: &str| match name { + "DESKTOP" => Some(Sid { + text: domain.into(), + domain: None, + }), + "DESKTOP\\DESKTOP" => Some(Sid { + text: owner.into(), + domain: Some(domain.into()), + }), + _ => None, + }; + assert!(account_matches_with("DESKTOP", owner, "DESKTOP", resolve)); + assert!(account_matches_with("DESKTOP", owner, "DESKTOP", |name| { + if name == "DESKTOP" { + None + } else { + resolve(name) + } + })); + assert!(!account_matches_with("DESKTOP", owner, "DESKTOP", |name| { + if name == "DESKTOP" { + Some(Sid { + text: "S-1-5-21-1-2-3-9999".into(), + domain: Some(domain.into()), + }) + } else { + resolve(name) + } + })); + for name in [ + "OTHER", + "OTHER\\DESKTOP", + ".\\DESKTOP", + "DESKTOP@example.test", + "S-1-5-21-9-9-9-1001", + ] { + let mut attempts = 0; + assert!(!account_matches_with(name, owner, "DESKTOP", |_| { + attempts += 1; + None + })); + assert_eq!( + attempts, 1, + "qualified or unrelated identities must not be reinterpreted" + ); + } + assert!(account_matches(owner, owner, "DESKTOP")); +} + +#[test] +fn native_current_process_query_reads_stable_creation_sid_image_and_argv() { + let process = Process::open(std::process::id()).expect("query-only self handle"); + let first = process + .read() + .expect("Windows supports bounded native command-line observation"); + let second = process + .read() + .expect("same live process remains observable"); + assert_eq!((first.pid, first.created), (second.pid, second.created)); + assert_eq!(first.owner, second.owner); + assert_eq!(first.argv, std::env::args().collect::>()); + assert!(executable_path_matches( + &first.image, + std::env::current_exe().unwrap().to_str().unwrap() + )); + assert!(process.is_alive()); + assert!(Process::open(0).is_none()); +} diff --git a/crates/webcodex-environment/src/service/windows_user/native/tests.rs b/crates/webcodex-environment/src/service/windows_user/native/tests.rs new file mode 100644 index 000000000..4689cd4b5 --- /dev/null +++ b/crates/webcodex-environment/src/service/windows_user/native/tests.rs @@ -0,0 +1,394 @@ +use super::*; +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, +}; + +fn plan() -> TaskPlan { + TaskPlan { + id: "native-observer-fixture".into(), home: r"C:\Users\Fixture".into(), + name: "WebCodex-native-observer-fixture".into(), + description: "webcodex fixture scope=user".into(), sid: "S-1-5-21-1-2-3-1001".into(), + program: r"C:\WebCodex\webcodex-runtime\server.exe".into(), + arguments: r#""--config" "C:\Fixture\环境.toml""#.into(), + host: Some(r"C:\WebCodex\WebCodex.exe".into()), + host_arguments: r#"--user-task "server" "fixture" "C:\Fixture" "C:\WebCodex\webcodex-runtime\server.exe" "--config" "C:\Fixture\环境.toml""#.into(), + directory: r"C:\Fixture".into(), + } +} + +// Real COM interfaces and setters, but never RegisterTask/Run: the definition +// stays in memory and cannot affect an installed task or start a process. +fn definition(scheduler: &ITaskService, plan: &TaskPlan) -> ITaskDefinition { + unsafe { + let definition = scheduler.NewTask(0).unwrap(); + definition + .RegistrationInfo() + .unwrap() + .SetDescription(&BSTR::from(plan.description.as_str())) + .unwrap(); + let principal = definition.Principal().unwrap(); + principal.SetUserId(&BSTR::from(plan.sid.as_str())).unwrap(); + principal + .SetLogonType(TASK_LOGON_INTERACTIVE_TOKEN) + .unwrap(); + principal.SetRunLevel(TASK_RUNLEVEL_LUA).unwrap(); + let action: IExecAction = definition + .Actions() + .unwrap() + .Create(TASK_ACTION_EXEC) + .unwrap() + .cast() + .unwrap(); + action.SetPath(&BSTR::from(plan.program.as_str())).unwrap(); + action + .SetArguments(&BSTR::from(plan.arguments.as_str())) + .unwrap(); + action + .SetWorkingDirectory(&BSTR::from(plan.directory.as_str())) + .unwrap(); + let trigger: ILogonTrigger = definition + .Triggers() + .unwrap() + .Create(TASK_TRIGGER_LOGON) + .unwrap() + .cast() + .unwrap(); + trigger.SetUserId(&BSTR::from(plan.sid.as_str())).unwrap(); + trigger.SetEnabled(VARIANT_BOOL(-1)).unwrap(); + let settings = definition.Settings().unwrap(); + settings + .SetMultipleInstances(TASK_INSTANCES_IGNORE_NEW) + .unwrap(); + settings.SetExecutionTimeLimit(&BSTR::from("PT0S")).unwrap(); + settings.SetAllowHardTerminate(VARIANT_BOOL(-1)).unwrap(); + settings.SetRestartCount(3).unwrap(); + settings.SetRestartInterval(&BSTR::from("PT1M")).unwrap(); + settings.SetStartWhenAvailable(VARIANT_BOOL(-1)).unwrap(); + settings + .SetDisallowStartIfOnBatteries(VARIANT_BOOL(0)) + .unwrap(); + settings.SetStopIfGoingOnBatteries(VARIANT_BOOL(0)).unwrap(); + definition + } +} + +fn scheduler() -> ITaskService { + let service: ITaskService = + unsafe { CoCreateInstance(&TaskScheduler, None, CLSCTX_INPROC_SERVER) }.unwrap(); + let empty = VARIANT::default(); + unsafe { service.Connect(&empty, &empty, &empty, &empty) }.unwrap(); + service +} + +#[test] +fn native_task_definition_checks_every_existing_ownership_boundary() { + let _apartment = Apartment::new().unwrap(); + let scheduler = scheduler(); + let plan = plan(); + let deadline = Instant::now() + Duration::from_secs(10); + let original = definition(&scheduler, &plan); + assert!(owned_action(&original, &plan, "FIXTURE", deadline) + .unwrap() + .is_some()); + + let changes: &[fn(&ITaskDefinition)] = &[ + |d| unsafe { + d.RegistrationInfo() + .unwrap() + .SetDescription(&BSTR::from("foreign")) + .unwrap(); + }, + |d| unsafe { + d.Principal() + .unwrap() + .SetUserId(&BSTR::from("S-1-5-21-1-2-3-1002")) + .unwrap(); + }, + |d| unsafe { + d.Principal() + .unwrap() + .SetLogonType(TASK_LOGON_PASSWORD) + .unwrap(); + }, + |d| unsafe { + d.Principal() + .unwrap() + .SetRunLevel(TASK_RUNLEVEL_HIGHEST) + .unwrap(); + }, + |d| unsafe { + let _: IAction = d.Actions().unwrap().Create(TASK_ACTION_EXEC).unwrap(); + }, + |d| unsafe { + let actions = d.Actions().unwrap(); + actions.Clear().unwrap(); + let _: IAction = actions.Create(TASK_ACTION_COM_HANDLER).unwrap(); + }, + |d| unsafe { + d.Actions() + .unwrap() + .get_Item(1) + .unwrap() + .cast::() + .unwrap() + .SetPath(&BSTR::from(r"C:\Other\server.exe")) + .unwrap(); + }, + |d| unsafe { + d.Actions() + .unwrap() + .get_Item(1) + .unwrap() + .cast::() + .unwrap() + .SetArguments(&BSTR::from("--other")) + .unwrap(); + }, + |d| unsafe { + d.Actions() + .unwrap() + .get_Item(1) + .unwrap() + .cast::() + .unwrap() + .SetWorkingDirectory(&BSTR::from(r"C:\Other")) + .unwrap(); + }, + |d| unsafe { + let _: ITrigger = d.Triggers().unwrap().Create(TASK_TRIGGER_LOGON).unwrap(); + }, + |d| unsafe { + let triggers = d.Triggers().unwrap(); + triggers.Clear().unwrap(); + let _: ITrigger = triggers.Create(TASK_TRIGGER_TIME).unwrap(); + }, + |d| unsafe { + d.Triggers() + .unwrap() + .get_Item(1) + .unwrap() + .SetEnabled(VARIANT_BOOL(0)) + .unwrap(); + }, + |d| unsafe { + d.Triggers() + .unwrap() + .get_Item(1) + .unwrap() + .cast::() + .unwrap() + .SetUserId(&BSTR::from("S-1-5-21-1-2-3-1002")) + .unwrap(); + }, + |d| unsafe { + d.Settings() + .unwrap() + .SetMultipleInstances(TASK_INSTANCES_PARALLEL) + .unwrap(); + }, + |d| unsafe { + d.Settings() + .unwrap() + .SetExecutionTimeLimit(&BSTR::from("PT1H")) + .unwrap(); + }, + |d| unsafe { + d.Settings() + .unwrap() + .SetAllowHardTerminate(VARIANT_BOOL(0)) + .unwrap(); + }, + |d| unsafe { + d.Settings().unwrap().SetRestartCount(0).unwrap(); + }, + |d| unsafe { + d.Settings() + .unwrap() + .SetRestartInterval(&BSTR::from("PT2M")) + .unwrap(); + }, + |d| unsafe { + d.Settings() + .unwrap() + .SetStartWhenAvailable(VARIANT_BOOL(0)) + .unwrap(); + }, + |d| unsafe { + d.Settings() + .unwrap() + .SetDisallowStartIfOnBatteries(VARIANT_BOOL(-1)) + .unwrap(); + }, + |d| unsafe { + d.Settings() + .unwrap() + .SetStopIfGoingOnBatteries(VARIANT_BOOL(-1)) + .unwrap(); + }, + ]; + for (index, change) in changes.iter().enumerate() { + let changed = definition(&scheduler, &plan); + change(&changed); + assert!( + owned_action(&changed, &plan, "FIXTURE", deadline) + .unwrap() + .is_none(), + "changed ownership field {index}" + ); + } + let hosted = definition(&scheduler, &plan); + let action: IExecAction = unsafe { + hosted + .Actions() + .unwrap() + .get_Item(1) + .unwrap() + .cast() + .unwrap() + }; + unsafe { + action + .SetPath(&BSTR::from(plan.host.as_deref().unwrap())) + .unwrap(); + action + .SetArguments(&BSTR::from(plan.host_arguments.as_str())) + .unwrap(); + } + assert!(owned_action(&hosted, &plan, "FIXTURE", deadline) + .unwrap() + .is_some()); + let mut untrusted_host = plan.clone(); + untrusted_host.host = None; + assert!(owned_action(&hosted, &untrusted_host, "FIXTURE", deadline) + .unwrap() + .is_none()); +} + +#[test] +fn native_scheduler_confirms_absence_by_reading_hidden_task_collection() { + let _apartment = Apartment::new().unwrap(); + let scheduler = scheduler(); + let folder = unsafe { scheduler.GetFolder(&BSTR::from("\\")) }.unwrap(); + let name = format!("WebCodex-unregistered-test-{}", uuid::Uuid::new_v4()); + assert!( + read_task(&folder, &name, Instant::now() + Duration::from_secs(10)) + .unwrap() + .is_none() + ); +} + +#[test] +fn native_task_name_comparison_does_not_classify_a_case_variant_as_absent() { + assert!(process::equal_ignore_case( + "WebCodex-user-abcd-Runner", + "WEBCODEX-USER-ABCD-RUNNER" + )); + assert!(!process::equal_ignore_case( + "WebCodex-user-abcd-Runner", + "WebCodex-user-abce-Runner" + )); +} + +#[test] +fn native_task_absence_requires_explicit_file_not_found_not_access_or_rpc_failure() { + assert!(missing_task_hresult(0x80070002u32 as i32)); + for code in [ + 0x80070005u32, + 0x800706bau32, + 0x80004005u32, + 0x80070003u32, + 0, + ] { + assert!(!missing_task_hresult(code as i32)); + } +} + +#[test] +fn native_worker_timeout_does_not_spawn_replacements_or_observe_expired_queue_entries() { + let calls = Arc::new(AtomicUsize::new(0)); + let observed_calls = calls.clone(); + let (started, receive_started) = mpsc::sync_channel(1); + let (release, wait_release) = mpsc::sync_channel(1); + let worker = spawn_worker(move |_, _| { + if observed_calls.fetch_add(1, Ordering::SeqCst) == 0 { + started.send(()).unwrap(); + wait_release.recv_timeout(Duration::from_secs(2)).unwrap(); + } + vec![Ok((ServiceStatus::absent("fixture"), None))] + }) + .unwrap(); + let (response, _first_receive) = mpsc::sync_channel(1); + assert!(worker + .try_send(Request { + probes: vec![], + deadline: Instant::now() + Duration::from_secs(2), + response, + }) + .is_ok()); + receive_started + .recv_timeout(Duration::from_secs(1)) + .unwrap(); + // The worker is already inside the blocked observation before starting the + // caller deadline; thread-start scheduling cannot invalidate this fixture. + assert!(request(&worker, vec![], Duration::from_millis(20)).is_err()); + for _ in 0..MAX_QUEUED_BATCHES - 2 { + let (response, _) = mpsc::sync_channel(1); + assert!(worker + .try_send(Request { + probes: vec![], + deadline: Instant::now(), + response + }) + .is_ok()); + } + let (response, receive) = mpsc::sync_channel(1); + assert!(worker + .try_send(Request { + probes: vec![], + deadline: Instant::now() + Duration::from_secs(1), + response + }) + .is_ok()); + assert!( + request(&worker, vec![], Duration::from_millis(20)).is_err(), + "a full queue returns unknown without waiting" + ); + assert_eq!( + calls.load(Ordering::SeqCst), + 1, + "timeouts do not replace the blocked worker" + ); + release.send(()).unwrap(); + let result = receive.recv_timeout(Duration::from_secs(1)).unwrap(); + assert!(result[0].is_ok()); + assert_eq!( + calls.load(Ordering::SeqCst), + 2, + "expired queue entries are never observed" + ); +} + +#[test] +fn native_plan_rejects_environment_injection_and_oversized_batches_without_observation() { + let mut spec = super::super::super::tests::sample_spec(); + spec.environment + .insert("NATIVE_TEST_ONLY".into(), "value".into()); + assert!(matches!( + make_probe(&spec, true), + Err(ServiceError { + code: ServiceErrorCode::InvalidSpec, + .. + }) + )); + let probes = vec![(&spec, true); MAX_BATCH_PROBES + 1]; + let errors = inspect_many(&probes); + assert_eq!(errors.len(), probes.len()); + assert!(errors.iter().all(|result| matches!( + result, + Err(ServiceError { + code: ServiceErrorCode::InvalidSpec, + .. + }) + ))); +} diff --git a/docs/DESKTOP_DEVELOPMENT.md b/docs/DESKTOP_DEVELOPMENT.md index 643458589..9bfa9aba2 100644 --- a/docs/DESKTOP_DEVELOPMENT.md +++ b/docs/DESKTOP_DEVELOPMENT.md @@ -123,6 +123,66 @@ cargo test --locked -p webcodex --lib regular_tunnel_real_process_parent_eof_dur This tests the native notification and cleanup boundary, not an actual system reboot. Qualify installed autostart separately when doing a real Windows reboot. +## Windows service observations + +Periodic status reads for Windows user services use Task Scheduler COM and +query-only process handles. They do not start PowerShell, query WMI, or fall back +to a shell after a native read fails. One local snapshot batches Server, Runner, +and Tunnel probes through one scheduler connection; identical saved service +specifications share one result. Embedded Tunnels continue to share their Server +owner. A batch contains at most 18 probes (Server, Runner, and 16 profiles). + +Desktop's periodic UI and tray observers share in-flight work. For a persistent +environment, a published native observation can be reused for three seconds +while an authenticated HTTP heartbeat still agrees. Heartbeats do not extend +that lifetime. A changed or failed heartbeat triggers a fresh native read. +Explicit refresh, operation admission/completion, and changed environment or +operation generations invalidate display evidence. Bootstrap, diagnostics, and +service controls keep their fresh-read paths. Three seconds is a cache lifetime, +not a promise that every external task change is detected within three seconds: +detection also depends on the next observer tick and native query completion. + +The cache is presentation-only. Start, stop, restart, install, and uninstall still +use the existing control adapter and independently verify the saved task and +live process identity. Native observations preserve task metadata, account/SID, +action and arguments, working directory, triggers and settings, instance GUID, +process creation time, and direct host/child ownership checks. An unconfirmed PID +stays unconfirmed. Command-line reads dynamically resolve +`NtQueryInformationProcess`; an unavailable or incompatible information class +does not authorize a process or trigger a PowerShell fallback. + +Task Scheduler RPC can stall. The reader has one worker, a queue of at most eight +batches, and a 55-second caller deadline. Expired queued reads and late results +are discarded. A stuck worker is not replaced with another thread; observations +remain unavailable until the owning process is restarted. Failures never become +evidence that an inaccessible task is absent or belongs to WebCodex. + +Focused Windows checks (in addition to the frontend checks above): +Constructing Desktop's `AppState` can still adopt the default Environment; a +temporary Desktop state directory alone does not isolate it. The child process +below points `APPDATA` / `LOCALAPPDATA` at new test directories without changing +the invoking shell or system environment, or reading an installed Environment. + +```powershell +cargo test --locked --profile dogfood -p webcodex-environment --lib service::windows_user +cargo test --locked --profile dogfood -p webcodex-environment --lib local_status::tests +powershell -NoLogo -NoProfile -NonInteractive -Command { + $testProfile = Join-Path $env:TEMP ('webcodex-observer-' + [guid]::NewGuid()) + $env:APPDATA = Join-Path $testProfile 'Roaming' + $env:LOCALAPPDATA = Join-Path $testProfile 'Local' + New-Item -ItemType Directory -Path $env:APPDATA, $env:LOCALAPPDATA | Out-Null + cargo test --locked --profile dogfood --manifest-path apps/desktop/src-tauri/Cargo.toml --lib runtime_observation + exit $LASTEXITCODE +} +if ($LASTEXITCODE -ne 0) { throw 'Desktop observation tests failed' } +``` + +When dogfooding this path, compare PowerShell process launches and event-log +record growth over matched idle intervals, then verify explicit refresh and a +real service transition. Process I/O write counters also include non-disk I/O; +they are not physical SSD-write measurements. This change does not disable +Windows Event Log, auditing, or PowerShell logging. + ## Build the local WebCodex runtime Desktop debug builds look for the three binaries in the repository's diff --git a/docs/DESKTOP_DEVELOPMENT.zh-CN.md b/docs/DESKTOP_DEVELOPMENT.zh-CN.md index c3c5502fb..1c54cf065 100644 --- a/docs/DESKTOP_DEVELOPMENT.zh-CN.md +++ b/docs/DESKTOP_DEVELOPMENT.zh-CN.md @@ -110,6 +110,56 @@ cargo test --locked -p webcodex --lib regular_tunnel_real_process_parent_eof_dur 这些测试覆盖原生通知与清理边界,不代表实际系统重启验收;真实 Windows 重启时 仍须单独验证已安装的自动启动行为。 +## Windows 服务状态观察 + +Windows 用户服务的周期性状态读取使用 Task Scheduler COM 和只读进程句柄, +不会启动 PowerShell、查询 WMI,也不会在原生读取失败后回退到 shell。 +一次本地快照通过同一个 scheduler connection 批量查询 Server、Runner 和 Tunnel; +完全相同的已保存 service specification 复用同一结果。嵌入式 Tunnel 继续共享其 +Server owner。每批最多 18 个 probe,即 Server、Runner 和 16 个 profile。 + +Desktop 的 UI 周期观察和托盘观察会合并正在执行的读取。对于持久环境,只要经过 +认证的 HTTP heartbeat 未变化,已发布的原生观察结果可以在三秒内复用;heartbeat +不会延长这段有效期。heartbeat 变化或失败会触发新的原生读取。显式刷新、操作准入 +或完成,以及 environment / operation generation 变化,都会使展示证据失效。 +Bootstrap、诊断和服务控制保留实时读取路径。三秒是缓存有效期,并不承诺所有外部 +计划任务变化都在三秒内被发现;发现延迟还取决于下一次观察调度和原生查询完成时间。 + +缓存仅用于展示。启动、停止、重启、安装和卸载继续使用现有控制适配器,独立验证 +已保存任务及实际运行进程的身份。原生观察保留任务元数据、账户 / SID、action 与 +参数、工作目录、trigger 与 settings、instance GUID、进程创建时间,以及直接 +host / child 归属检查。不能确认的 PID 仍保持未确认。命令行读取动态解析 +`NtQueryInformationProcess`;information class 不可用或不兼容时,不会据此授权 +操作进程,也不会触发 PowerShell 回退。 + +Task Scheduler RPC 可能阻塞。读取器固定使用一个 worker,最多排队八批,每个 +调用者有 55 秒 deadline;过期的排队请求和迟到结果会被丢弃。阻塞 worker 不会被 +新线程替换,此时观察保持不可用,直至所属进程重启。失败不能被解释为无权访问的 +任务不存在,或被解释为该任务属于 WebCodex。 + +除前面的 frontend 检查外,Windows 聚焦验证命令为: +Desktop 测试构造 `AppState` 时仍可能自动读取默认 Environment;只给 Desktop state +传入临时目录并不能隔离它。下面在独立子进程中把 `APPDATA` / `LOCALAPPDATA` 指向 +新的测试目录,不改当前 shell 或系统的环境变量,也不读取已安装的 Environment。 + +```powershell +cargo test --locked --profile dogfood -p webcodex-environment --lib service::windows_user +cargo test --locked --profile dogfood -p webcodex-environment --lib local_status::tests +powershell -NoLogo -NoProfile -NonInteractive -Command { + $testProfile = Join-Path $env:TEMP ('webcodex-observer-' + [guid]::NewGuid()) + $env:APPDATA = Join-Path $testProfile 'Roaming' + $env:LOCALAPPDATA = Join-Path $testProfile 'Local' + New-Item -ItemType Directory -Path $env:APPDATA, $env:LOCALAPPDATA | Out-Null + cargo test --locked --profile dogfood --manifest-path apps/desktop/src-tauri/Cargo.toml --lib runtime_observation + exit $LASTEXITCODE +} +if ($LASTEXITCODE -ne 0) { throw 'Desktop observation tests failed' } +``` + +Dogfood 时,在可比的空闲时间段对照 PowerShell 启动次数和事件日志记录增长, +再验证显式刷新和真实服务状态变化。进程 I/O 写入计数还包含非磁盘 I/O,不能直接 +视为 SSD 的实际写入量。这项改动不会关闭 Windows Event Log、审计或 PowerShell 日志。 + ## 构建本地 WebCodex runtime Desktop debug build 默认会到当前仓库的 `target/dogfood` 找三个 binary。因此要从同一个 diff --git a/scripts/tests/test_windows_user_service_identity.ps1 b/scripts/tests/test_windows_user_service_identity.ps1 index e2aecdfd6..b56843ea9 100644 --- a/scripts/tests/test_windows_user_service_identity.ps1 +++ b/scripts/tests/test_windows_user_service_identity.ps1 @@ -159,7 +159,7 @@ if ($NativeRoundtrip) { operation='install'; name=$name; sid=$identity.User.Value; description=$name program=(Join-Path $env:TEMP "$name\missing.exe"); arguments='--identity-fixture'; directory=$env:TEMP } - function Invoke-ServiceScript($operation) { + function Invoke-ServiceScript($operation, [switch]$ExpectFailure) { $request.operation=$operation $start=New-Object Diagnostics.ProcessStartInfo $start.FileName=Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' @@ -180,15 +180,20 @@ if ($NativeRoundtrip) { $null=$process.WaitForExit(5000) throw 'native service fixture timed out' } - if ($process.ExitCode -ne 0) { throw "native service fixture failed: $operation" } - return ($stdout.GetAwaiter().GetResult() | ConvertFrom-Json) + $result=$stdout.GetAwaiter().GetResult() | ConvertFrom-Json + if ($ExpectFailure) { + if ($process.ExitCode -eq 0 -or $result.error -cne 'native_task_operation_unconfirmed') { + throw 'foreign mutation was not rejected' + } + } elseif ($process.ExitCode -ne 0) { throw "native service fixture failed: $operation" } + return $result } finally { $process.Dispose() } } $scheduler=New-Object -ComObject 'Schedule.Service' $scheduler.Connect() $folder=$scheduler.GetFolder('\') try { - foreach ($operation in @('install', 'inspect')) { + foreach ($operation in @('install', 'install')) { $observed=Invoke-ServiceScript $operation if ($observed.exists -ne $true -or $observed.owned -ne $true) { throw "registered task was not owned: $operation" } } @@ -203,8 +208,7 @@ if ($NativeRoundtrip) { if (!$observed.owned) { throw 'repeated install changed task ownership' } # A changed expected marker must not adopt the registered native task. $request.description='foreign' - $observed=Invoke-ServiceScript 'inspect' - if ($observed.exists -ne $true -or $observed.owned -ne $false) { throw 'native foreign task was accepted' } + $null=Invoke-ServiceScript 'install' -ExpectFailure $request.description=$name $observed=Invoke-ServiceScript 'uninstall' if ($observed.exists -ne $false) { throw 'native task uninstall was not confirmed' } @@ -220,5 +224,5 @@ if ($NativeRoundtrip) { $folder.DeleteTask($name, 0) } } - 'PASS: native user Task Scheduler install/inspect/foreign/uninstall roundtrip' + 'PASS: native user Task Scheduler install/idempotence/foreign/uninstall roundtrip' }