diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index a684024f8..fe97298aa 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -49,6 +49,7 @@ winreg = "0.55" [dev-dependencies] +tokio = { version = "1", features = ["test-util"] } tempfile = "3" [profile.dogfood] diff --git a/apps/desktop/src-tauri/src/error.rs b/apps/desktop/src-tauri/src/error.rs index a10f58b9b..102dbabba 100644 --- a/apps/desktop/src-tauri/src/error.rs +++ b/apps/desktop/src-tauri/src/error.rs @@ -298,6 +298,11 @@ impl ErrorDiagnostic { | "desktop_data_dir_invalid" | "desktop_data_dir_unavailable" | "state_io" => (Config, ManualCheck, OpenDiagnostics, false), + "desktop_core_unavailable" | "desktop_operation_unsettled" => { + (Desktop, ManualCheck, OpenActivity, false) + } + "desktop_operation_start_timeout" => (Desktop, UserAction, OpenActivity, true), + "desktop_state_unavailable" => (Desktop, ManualCheck, OpenDiagnostics, false), "not_configured" | "setup_not_found" => (Environment, UserAction, OpenSetup, false), "runtime_switch_jobs_confirmation_required" | "full_trace_confirmation_required" @@ -318,9 +323,7 @@ impl ErrorDiagnostic { "pairing_recovery_required" => (Auth, ManualCheck, ObserveBeforeRetry, false), // 12. Background operation contention - "desktop_operation_busy" - | "desktop_state_unavailable" - | "desktop_operation_not_cancellable" => { + "desktop_operation_busy" | "desktop_operation_not_cancellable" => { (Desktop, AutoRecovering, WaitAutoRecovery, true) } "desktop_operation_not_current" => (Desktop, UserAction, RefreshState, false), diff --git a/apps/desktop/src-tauri/src/models.rs b/apps/desktop/src-tauri/src/models.rs index 12da33e20..8a2b0cabe 100644 --- a/apps/desktop/src-tauri/src/models.rs +++ b/apps/desktop/src-tauri/src/models.rs @@ -323,6 +323,7 @@ impl DesktopOperationKind { pub enum DesktopOperationPhase { Running, Cancelling, + Overdue, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] diff --git a/apps/desktop/src-tauri/src/operation.rs b/apps/desktop/src-tauri/src/operation.rs index 79c132128..7f513013b 100644 --- a/apps/desktop/src-tauri/src/operation.rs +++ b/apps/desktop/src-tauri/src/operation.rs @@ -2,40 +2,46 @@ use crate::activity::{ActivityEventKind, ActivityLevel, ActivityLog}; use crate::error::{DesktopError, DesktopResult}; use crate::models::{DesktopOperationKind, DesktopOperationPhase, DesktopOperationSnapshot}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Mutex; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::sync::{Mutex, MutexGuard}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio::time::Instant; +// This is an outer backstop for cooperative Desktop operations, including +// multi-step setup. Individual commands keep their shorter deadlines. +const OPERATION_BUDGET: Duration = Duration::from_secs(10 * 60); +const STOP_OBSERVATION_BUDGET: Duration = Duration::from_secs(30); + pub(crate) use webcodex_environment::unified_update::CancellationSignal; #[derive(Clone)] pub(crate) struct CancellationContext { - operation: Option, + operation: CancellationSignal, shutdown: CancellationSignal, + deadline: Option, } impl CancellationContext { pub(crate) fn new(operation: CancellationSignal, shutdown: CancellationSignal) -> Self { Self { - operation: Some(operation), + operation, shutdown, + deadline: None, } } #[cfg(test)] pub(crate) fn never() -> Self { Self { - operation: None, + operation: CancellationSignal::new(), shutdown: CancellationSignal::new(), + deadline: None, } } pub(crate) fn is_cancelled(&self) -> bool { - self.shutdown.is_cancelled() - || self - .operation - .as_ref() - .is_some_and(CancellationSignal::is_cancelled) + self.deadline.is_some_and(|at| Instant::now() >= at) + || self.shutdown.is_cancelled() + || self.operation.is_cancelled() } pub(crate) fn check(&self) -> DesktopResult<()> { @@ -47,13 +53,16 @@ impl CancellationContext { } pub(crate) async fn cancelled(&self) { - if let Some(operation) = &self.operation { + let signals = async { tokio::select! { - _ = operation.cancelled() => {}, + _ = self.operation.cancelled() => {}, _ = self.shutdown.cancelled() => {}, } + }; + if let Some(at) = self.deadline { + let _ = tokio::time::timeout_at(at, signals).await; } else { - self.shutdown.cancelled().await; + signals.await; } } } @@ -66,20 +75,108 @@ pub(crate) fn cancelled_error() -> DesktopError { ) } +pub(crate) fn core_unavailable() -> DesktopError { + DesktopError::new( + "desktop_core_unavailable", + "Desktop cannot verify its internal operation state", + "Fully quit and reopen Desktop, then check the runtime and Activity before repeating the operation.", + ) +} + +pub(crate) fn busy_error(current: &DesktopOperationSnapshot) -> DesktopError { + let error = if current.phase == DesktopOperationPhase::Overdue { + DesktopError::new( + "desktop_operation_unsettled", + "The Desktop operation has not confirmed completion within its time budget", + "Check Activity and the affected service before taking further action.", + ) + } else { + DesktopError::new( + "desktop_operation_busy", + "Another Desktop operation is still running", + "Check the current operation in Desktop.", + ) + }; + error + .with_details(serde_json::json!({ + "operation_id": current.id, + "operation_kind": current.kind.as_str(), + })) + .with_operation_context(Some(¤t.id), None, None, None) +} + struct ActiveOperation { snapshot: DesktopOperationSnapshot, cancellation: CancellationSignal, + report_delay_at: Instant, } -#[derive(Clone)] -pub(crate) struct OperationAdmission { +impl ActiveOperation { + fn snapshot(&self) -> DesktopOperationSnapshot { + let mut snapshot = self.snapshot.clone(); + if Instant::now() >= self.report_delay_at { + snapshot.phase = DesktopOperationPhase::Overdue; + // A cooperative operation's deadline or an explicit Stop has + // already requested cancellation. Its owner still settles effects. + snapshot.cancellable = false; + } + snapshot + } +} + +enum OperationSlot { + Idle, + Active(ActiveOperation), + Interrupted(DesktopError), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum AdmissionPhase { + Preparing, + Dispatched, + Finished, +} + +pub(crate) struct OperationAdmission<'a> { + controller: &'a OperationController, pub(crate) id: String, pub(crate) kind: DesktopOperationKind, - pub(crate) cancellation: CancellationSignal, + cancellation: CancellationSignal, + cancel_at: Option, + phase: AdmissionPhase, +} + +impl OperationAdmission<'_> { + pub(crate) fn cancellation_context(&self, shutdown: CancellationSignal) -> CancellationContext { + CancellationContext { + operation: self.cancellation.clone(), + shutdown, + deadline: self.cancel_at, + } + } + + pub(crate) fn mark_dispatched(&mut self) { + self.phase = AdmissionPhase::Dispatched; + } + + pub(crate) fn finish(mut self, result: &DesktopResult) { + self.controller.finish(&self.id, result); + self.phase = AdmissionPhase::Finished; + } +} + +impl Drop for OperationAdmission<'_> { + fn drop(&mut self) { + if self.phase != AdmissionPhase::Finished { + self.cancellation.cancel(); + self.controller + .abandon(&self.id, self.phase == AdmissionPhase::Dispatched); + } + } } pub(crate) struct OperationController { - active: Mutex>, + active: Mutex, next_id: AtomicU64, activity: ActivityLog, } @@ -89,35 +186,38 @@ impl OperationController { self.next_id.load(Ordering::Relaxed) } + pub(crate) fn idle_generation(&self) -> DesktopResult { + // Sample the counter under the same lock that admits a writer. + let _idle = self.idle_slot()?; + Ok(self.generation()) + } + pub(crate) fn new(activity: ActivityLog) -> Self { Self { - active: Mutex::new(None), + active: Mutex::new(OperationSlot::Idle), next_id: AtomicU64::new(0), activity, } } - pub(crate) fn admit( - &self, - kind: DesktopOperationKind, - cancellable: bool, - ) -> DesktopResult { - let mut active = self + fn idle_slot(&self) -> DesktopResult> { + let slot = self .active .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - if let Some(current) = active.as_ref() { - return Err(DesktopError::new( - "desktop_operation_busy", - "Another Desktop operation is still running", - "Wait for the current operation to finish or stop it before starting another one.", - ) - .with_details(serde_json::json!({ - "operation_id": current.snapshot.id, - "operation_kind": current.snapshot.kind.as_str(), - }))); + match &*slot { + OperationSlot::Idle => Ok(slot), + OperationSlot::Active(current) => Err(busy_error(¤t.snapshot())), + OperationSlot::Interrupted(error) => Err(error.clone()), } + } + pub(crate) fn admit( + &self, + kind: DesktopOperationKind, + cancellable: bool, + ) -> DesktopResult> { + let mut active = self.idle_slot()?; let sequence = self.next_id.fetch_add(1, Ordering::Relaxed) + 1; let id = format!("desktop-operation-{sequence}"); let snapshot = DesktopOperationSnapshot { @@ -134,11 +234,16 @@ impl OperationController { ActivityLevel::Info, format!("Desktop operation started: {}", kind.as_str()), ); - *active = Some(ActiveOperation { + let deadline = Instant::now() + OPERATION_BUDGET; + *active = OperationSlot::Active(ActiveOperation { + report_delay_at: deadline, snapshot, cancellation: cancellation.clone(), }); Ok(OperationAdmission { + controller: self, + cancel_at: cancellable.then_some(deadline), + phase: AdmissionPhase::Preparing, id, kind, cancellation, @@ -146,11 +251,24 @@ impl OperationController { } pub(crate) fn current(&self) -> Option { - self.active - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .as_ref() - .map(|operation| operation.snapshot.clone()) + self.observe().ok().flatten() + } + + pub(crate) fn observe(&self) -> DesktopResult> { + let slot = self.active.lock().unwrap_or_else(|p| p.into_inner()); + match &*slot { + OperationSlot::Idle => Ok(None), + OperationSlot::Active(current) => Ok(Some(current.snapshot())), + OperationSlot::Interrupted(error) => Err(error.clone()), + } + } + + pub(crate) fn missing_core_error(&self) -> DesktopError { + match self.observe() { + Ok(Some(current)) => busy_error(¤t), + Ok(None) => core_unavailable(), + Err(error) => error, + } } pub(crate) fn cancel(&self, observed_id: &str) -> DesktopResult { @@ -158,7 +276,7 @@ impl OperationController { .active .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - let Some(current) = active.as_mut() else { + let OperationSlot::Active(current) = &mut *active else { return Err(operation_not_current(observed_id, None)); }; if current.snapshot.id != observed_id { @@ -176,6 +294,9 @@ impl OperationController { } if current.snapshot.phase != DesktopOperationPhase::Cancelling { current.snapshot.phase = DesktopOperationPhase::Cancelling; + current.report_delay_at = current + .report_delay_at + .min(Instant::now() + STOP_OBSERVATION_BUDGET); current.cancellation.cancel(); self.activity.push( ActivityEventKind::OperationCancelRequested, @@ -187,7 +308,7 @@ impl OperationController { ), ); } - Ok(current.snapshot.clone()) + Ok(current.snapshot()) } pub(crate) fn cancel_active_for_shutdown(&self) { @@ -195,11 +316,14 @@ impl OperationController { .active .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - let Some(current) = active.as_mut() else { + let OperationSlot::Active(current) = &mut *active else { return; }; if current.snapshot.phase != DesktopOperationPhase::Cancelling { current.snapshot.phase = DesktopOperationPhase::Cancelling; + current.report_delay_at = current + .report_delay_at + .min(Instant::now() + STOP_OBSERVATION_BUDGET); self.activity.push( ActivityEventKind::OperationCancelRequested, "desktop", @@ -213,12 +337,12 @@ impl OperationController { current.cancellation.cancel(); } - pub(crate) fn finish(&self, operation_id: &str, result: &DesktopResult) { + fn finish(&self, operation_id: &str, result: &DesktopResult) { let mut active = self .active .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - let Some(current) = active.as_ref() else { + let OperationSlot::Active(current) = &*active else { return; }; if current.snapshot.id != operation_id { @@ -248,7 +372,38 @@ impl OperationController { ); } } - *active = None; + *active = OperationSlot::Idle; + } + + fn abandon(&self, id: &str, dispatched: bool) { + let mut slot = self.active.lock().unwrap_or_else(|p| p.into_inner()); + let OperationSlot::Active(current) = &*slot else { + return; + }; + if current.snapshot.id != id { + return; + } + self.activity.push( + ActivityEventKind::OperationFailed, + "desktop", + ActivityLevel::Error, + format!( + "Desktop operation owner exited: {}", + current.snapshot.kind.as_str() + ), + ); + *slot = if dispatched { + // A worker or an external effect can outlive its caller. A new + // Desktop process must re-observe the durable owners before retry. + OperationSlot::Interrupted(core_unavailable().with_operation_context( + Some(id), + None, + None, + None, + )) + } else { + OperationSlot::Idle + }; } pub(crate) async fn wait_until_idle(&self, deadline: Instant) -> bool { @@ -294,6 +449,58 @@ fn now_ms() -> u64 { mod tests { use super::*; + #[tokio::test(start_paused = true)] + async fn overdue_owners_keep_their_slot_until_settlement() { + for cancellable in [true, false] { + let controller = OperationController::new(ActivityLog::default()); + let mut operation = controller + .admit(DesktopOperationKind::LocalSetup, cancellable) + .unwrap(); + operation.mark_dispatched(); + let context = operation.cancellation_context(CancellationSignal::new()); + assert!(!context.is_cancelled()); + tokio::time::advance(OPERATION_BUDGET).await; + assert_eq!(context.is_cancelled(), cancellable); + if cancellable { + context.cancelled().await; + } + let observed = controller.current().unwrap(); + assert_eq!(observed.phase, DesktopOperationPhase::Overdue); + assert!(!observed.cancellable); + let competing = controller + .admit(DesktopOperationKind::LocalSetup, true) + .err() + .unwrap(); + assert_eq!(competing.code, "desktop_operation_unsettled"); + assert_eq!( + competing.diagnostic_ref().unwrap().operation_id.as_ref(), + Some(&operation.id) + ); + operation.finish(&Ok::<_, DesktopError>(())); + assert!(controller + .admit(DesktopOperationKind::LocalSetup, true) + .is_ok()); + } + } + + #[tokio::test(start_paused = true)] + async fn repeated_stop_requests_do_not_extend_a_stalled_cleanup() { + let controller = OperationController::new(ActivityLog::default()); + let operation = controller + .admit(DesktopOperationKind::RuntimeResume, true) + .unwrap(); + controller.cancel(&operation.id).unwrap(); + tokio::time::advance(STOP_OBSERVATION_BUDGET / 2).await; + controller.cancel(&operation.id).unwrap(); + tokio::time::advance(STOP_OBSERVATION_BUDGET / 2).await; + assert_eq!( + controller.current().unwrap().phase, + DesktopOperationPhase::Overdue + ); + operation.finish(&Err::<(), _>(cancelled_error())); + assert!(controller.observe().unwrap().is_none()); + } + #[test] fn stale_cancel_never_targets_the_newer_operation() { let controller = OperationController::new(ActivityLog::default()); @@ -302,12 +509,13 @@ mod tests { .unwrap(); controller.cancel(&first.id).unwrap(); let first_result: DesktopResult<()> = Err(cancelled_error()); - controller.finish(&first.id, &first_result); + let first_id = first.id.clone(); + first.finish(&first_result); let second = controller .admit(DesktopOperationKind::QuickShareStart, true) .unwrap(); - let error = controller.cancel(&first.id).unwrap_err(); + let error = controller.cancel(&first_id).unwrap_err(); assert_eq!(error.code, "desktop_operation_not_current"); assert_eq!(controller.current().unwrap().id, second.id); assert!(!second.cancellation.is_cancelled()); @@ -327,7 +535,7 @@ mod tests { assert_eq!(busy.code, "desktop_operation_busy"); let first_result: DesktopResult<()> = Err(cancelled_error()); - controller.finish(&first.id, &first_result); + first.finish(&first_result); assert!(controller .admit(DesktopOperationKind::RemoteSetup, true) .is_ok()); diff --git a/apps/desktop/src-tauri/src/state.rs b/apps/desktop/src-tauri/src/state.rs index b1c168e58..e64010e85 100644 --- a/apps/desktop/src-tauri/src/state.rs +++ b/apps/desktop/src-tauri/src/state.rs @@ -11,6 +11,8 @@ pub use environment_invitation::{InvitationRequest, InvitationResponse}; mod managed_instructions; mod mcp_providers; mod operation_completion; +#[cfg(test)] +mod operation_lifecycle_tests; mod path_inventory; pub use path_inventory::{ExportInventoryRequest, OpenInventoryRequest}; #[cfg(all(test, windows, desktop_native_smoke))] @@ -63,6 +65,7 @@ use std::sync::{Arc, RwLock}; use std::time::Duration; use tokio::sync::Mutex; +const OPERATION_SLOT_TIMEOUT: Duration = Duration::from_secs(30); const SERVER_READY_TIMEOUT: Duration = Duration::from_secs(20); const STALE_LOOPBACK_PROBE_TIMEOUT: Duration = Duration::from_secs(2); const RUNNER_READY_TIMEOUT: Duration = Duration::from_secs(30); @@ -101,6 +104,7 @@ pub struct AppState { activity: ActivityLog, operations: OperationController, refresh_lock: tokio::sync::Mutex<()>, + runner_settings_reader: Arc>, shutdown_signal: CancellationSignal, shutdown_started: AtomicBool, shutdown_complete: CancellationSignal, diff --git a/apps/desktop/src-tauri/src/state/app_state.rs b/apps/desktop/src-tauri/src/state/app_state.rs index ac45786e7..958f4ac00 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(()), + runner_settings_reader: Arc::new(Mutex::new(())), activity, shutdown_signal: CancellationSignal::new(), shutdown_started: AtomicBool::new(false), @@ -78,7 +79,16 @@ impl AppState { self.connections .project(&mut snapshot.connections, snapshot.readiness.runtime_ready); } - snapshot.current_operation = self.operations.current(); + match self.operations.observe() { + Ok(current) => snapshot.current_operation = current, + Err(error) => { + snapshot.current_operation = None; + snapshot + .component_errors + .insert(error.component(), error.clone()); + snapshot.runtime_error = Some(error); + } + } snapshot.environment_setup = environment_invitation::setup_snapshot(&snapshot); snapshot.activity_sequence = self.activity.latest_sequence(); if snapshot.persistent_environment.is_none() @@ -147,17 +157,8 @@ impl AppState { if self.shutdown_signal.is_cancelled() { return Err(cancelled_error()); } - if let Some(current) = self.operations.current() { - return Err(DesktopError::new( - "desktop_operation_busy", - "Another Desktop operation is still running", - "Wait for the current operation to finish or stop it before starting another one.", - ) - .with_details(serde_json::json!({ - "operation_id": current.id, - "operation_kind": current.kind.as_str(), - })) - .with_operation_context(Some(¤t.id), None, None, None)); + 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( @@ -172,17 +173,8 @@ impl AppState { if self.shutdown_signal.is_cancelled() { return Err(cancelled_error()); } - if let Some(current) = self.operations.current() { - return Err(DesktopError::new( - "desktop_operation_busy", - "Another Desktop operation is still running", - "Wait for the current operation to finish or stop it before starting another one.", - ) - .with_details(serde_json::json!({ - "operation_id": current.id, - "operation_kind": current.kind.as_str(), - })) - .with_operation_context(Some(¤t.id), None, None, None)); + 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. @@ -213,11 +205,7 @@ impl AppState { let plan = { let slot = self.core.lock().await; let Some(core) = slot.as_ref() else { - return Err(DesktopError::new( - "desktop_operation_busy", - "Desktop mutation state is already in use", - "Wait for the current operation to finish.", - )); + return Err(self.operations.missing_core_error()); }; if let Some(environment_id) = core.config.persistent_environment.clone() { RefreshPlan::Persistent { environment_id } @@ -703,7 +691,7 @@ impl AppState { kind: DesktopOperationKind, cancellable: bool, ) -> DesktopResult<( - OperationAdmission, + OperationAdmission<'_>, CancellationContext, DesktopCore, ProcessBaseline, @@ -720,30 +708,41 @@ impl AppState { "Open Diagnostics or explicitly restore the previous known-good configuration.", )); } - let operation = self.operations.admit(kind, cancellable)?; - let cancellation = - CancellationContext::new(operation.cancellation.clone(), self.shutdown_signal.clone()); - let baseline = self.capture_process_baseline().await; - let core = { + let mut operation = self.operations.admit(kind, cancellable)?; + 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. + let start_deadline = Deadline::after(OPERATION_SLOT_TIMEOUT); + let prepare = async { + let baseline = self.capture_process_baseline().await; let mut slot = self.core.lock().await; - slot.take() + cancellation.check()?; + if start_deadline.is_elapsed() { + return Err(operation_start_timeout()); + } + let core = slot.take().ok_or_else(crate::operation::core_unavailable)?; + Ok((core, baseline)) }; - let Some(core) = core else { - let error = DesktopError::new( - "desktop_operation_busy", - "Desktop mutation state is already in use", - "Wait for the current operation to finish.", - ); - let result: DesktopResult<()> = Err(error.clone()); - self.operations.finish(&operation.id, &result); - return Err(error); + let prepared = tokio::select! { + biased; + _ = cancellation.cancelled() => Err(cancelled_error()), + _ = tokio::time::sleep_until(start_deadline.instant()) => Err(operation_start_timeout()), + result = prepare => result, + }; + let (core, baseline) = match prepared { + Ok(prepared) => prepared, + Err(error) => { + operation.finish(&Err::<(), _>(error.clone())); + return Err(error); + } }; + operation.mark_dispatched(); Ok((operation, cancellation, core, baseline)) } async fn finish_operation( &self, - operation: OperationAdmission, + operation: OperationAdmission<'_>, cancellation: CancellationContext, mut core: DesktopCore, baseline: ProcessBaseline, @@ -774,11 +773,8 @@ impl AppState { if completion.apply_runtime_error(&mut core.snapshot, core.runtime_last_switch.as_ref()) { core.publish_snapshot(); } - { - let mut slot = self.core.lock().await; - *slot = Some(core); - } - self.operations.finish(&operation.id, &result); + *self.core.lock().await = Some(core); + operation.finish(&result); match result { Ok(_) => Ok(self.get_state()), Err(error) => Err(error), @@ -903,6 +899,14 @@ impl ProcessCleanup { } } +fn operation_start_timeout() -> DesktopError { + DesktopError::new( + "desktop_operation_start_timeout", + "Desktop timed out waiting to start the operation", + "Check Activity and try again. The operation did not start.", + ) +} + fn project_not_loaded_error() -> DesktopError { readiness_timeout_error( "project_not_loaded", diff --git a/apps/desktop/src-tauri/src/state/coding_agents.rs b/apps/desktop/src-tauri/src/state/coding_agents.rs index bcb447afc..dba1be27f 100644 --- a/apps/desktop/src-tauri/src/state/coding_agents.rs +++ b/apps/desktop/src-tauri/src/state/coding_agents.rs @@ -34,11 +34,7 @@ impl AppState { .begin_operation(DesktopOperationKind::RunnerSettingsUpdate, false) .await?; let result = async { - let runtime = core - .config - .runtime - .clone() - .ok_or_else(|| desktop_state_unavailable("Configure a Runner first"))?; + let runtime = core.runner_settings_runtime()?; crate::webcodex::settings::verify_target(&runtime, &target)?; let mut candidate = core.coding_agents.clone(); let candidate = tokio::task::spawn_blocking(move || { diff --git a/apps/desktop/src-tauri/src/state/desktop_core.rs b/apps/desktop/src-tauri/src/state/desktop_core.rs index 5dbc2c1ae..ab91044a3 100644 --- a/apps/desktop/src-tauri/src/state/desktop_core.rs +++ b/apps/desktop/src-tauri/src/state/desktop_core.rs @@ -1289,7 +1289,11 @@ impl DesktopCore { cancellation: &CancellationContext, ) -> DesktopResult> { cancellation.check()?; - let mut supervisor = self.supervisor.lock().await; + let mut supervisor = tokio::select! { + biased; + _ = cancellation.cancelled() => return Err(cancelled_error()), + supervisor = self.supervisor.lock() => supervisor, + }; cancellation.check()?; supervisor.spawn_owned(kind, command, machine_stdout).await } diff --git a/apps/desktop/src-tauri/src/state/diagnostics.rs b/apps/desktop/src-tauri/src/state/diagnostics.rs index 07b2bbe74..53160cdc0 100644 --- a/apps/desktop/src-tauri/src/state/diagnostics.rs +++ b/apps/desktop/src-tauri/src/state/diagnostics.rs @@ -22,23 +22,12 @@ fn valid_console_user_credential(value: &str) -> bool { } impl AppState { - fn busy_diagnostic_error(&self) -> DesktopError { - let mut error = diagnostics::diagnostic_error("desktop_operation_busy"); - if let Some(current) = self.operations.current() { - error = error - .with_details(serde_json::json!({ - "operation_id": current.id, - "operation_kind": current.kind.as_str(), - })) - .with_operation_context(Some(¤t.id), None, None, None); - } - error - } - pub async fn diagnostics(&self) -> DesktopResult { let (settings, runtime, trace_target, recovery, mut resources, identity_fence) = { let slot = self.core.lock().await; - let core = slot.as_ref().ok_or_else(|| self.busy_diagnostic_error())?; + let core = slot + .as_ref() + .ok_or_else(|| self.operations.missing_core_error())?; let settings = core.runtime_settings_snapshot().await; let runtime = core.config.runtime.clone(); let trace_target = core.managed_trace_target().await; @@ -150,7 +139,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| diagnostics::diagnostic_error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; if core.config.runtime.as_ref().map(runtime_fence) != identity_fence || core.config.runtime_selection_revision != settings.selection_revision { @@ -292,7 +281,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| diagnostics::diagnostic_error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; let location = match kind { ResourceKind::RuntimeConsole => { let runtime = @@ -357,9 +346,9 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| diagnostics::diagnostic_error("desktop_operation_busy"))?; - if self.operations.current().is_some() { - return Err(diagnostics::diagnostic_error("desktop_operation_busy")); + .ok_or_else(|| self.operations.missing_core_error())?; + if let Some(current) = self.operations.current() { + return Err(crate::operation::busy_error(¤t)); } let runtime = core .config diff --git a/apps/desktop/src-tauri/src/state/environment.rs b/apps/desktop/src-tauri/src/state/environment.rs index 0ba0bd44e..270367eca 100644 --- a/apps/desktop/src-tauri/src/state/environment.rs +++ b/apps/desktop/src-tauri/src/state/environment.rs @@ -598,7 +598,7 @@ impl AppState { let mut slot = self.core.lock().await; let core = slot .as_mut() - .ok_or_else(|| crate::runtime_selection::error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; if core.configuration_issue.is_some() || persisted_environment(&core.config) || !core.config.topology.as_ref().is_some_and(|t| { diff --git a/apps/desktop/src-tauri/src/state/environment_invitation.rs b/apps/desktop/src-tauri/src/state/environment_invitation.rs index caaa930e7..9988a3855 100644 --- a/apps/desktop/src-tauri/src/state/environment_invitation.rs +++ b/apps/desktop/src-tauri/src/state/environment_invitation.rs @@ -125,7 +125,7 @@ impl AppState { if self.shutdown_signal.is_cancelled() { return Err(cancelled_error()); } - let operation = self + let mut operation = self .operations .admit(DesktopOperationKind::EnvironmentInvite, false)?; // This operation cannot launch or replace runtime processes. Do not @@ -139,8 +139,9 @@ impl AppState { )); } verify_target(&self.get_state(), store, &request.environment_id)?; - let code = NativeEnvironment::new() - .map_err(environment::desktop_error)? + let native = NativeEnvironment::new().map_err(environment::desktop_error)?; + operation.mark_dispatched(); + let code = native .invite_for_environment(store, &request.environment_id) .await .map_err(environment::desktop_error)?; @@ -154,7 +155,7 @@ impl AppState { }) } .await; - self.operations.finish(&operation.id, &result); + operation.finish(&result); result } } diff --git a/apps/desktop/src-tauri/src/state/managed_instructions.rs b/apps/desktop/src-tauri/src/state/managed_instructions.rs index c93295d20..d138c8cd8 100644 --- a/apps/desktop/src-tauri/src/state/managed_instructions.rs +++ b/apps/desktop/src-tauri/src/state/managed_instructions.rs @@ -28,11 +28,7 @@ impl AppState { .begin_operation(DesktopOperationKind::RunnerSettingsUpdate, false) .await?; let result = async { - let runtime = core - .config - .runtime - .clone() - .ok_or_else(|| desktop_state_unavailable("Configure a Runner first"))?; + let runtime = core.runner_settings_runtime()?; crate::webcodex::settings::verify_target(&runtime, &request.target)?; let managed = Arc::clone(&self.managed_instructions); let edit = tokio::task::spawn_blocking({ diff --git a/apps/desktop/src-tauri/src/state/operation_lifecycle_tests.rs b/apps/desktop/src-tauri/src/state/operation_lifecycle_tests.rs new file mode 100644 index 000000000..f44e8c990 --- /dev/null +++ b/apps/desktop/src-tauri/src/state/operation_lifecycle_tests.rs @@ -0,0 +1,382 @@ +use super::*; + +async fn state_with_runner(dir: &Path) -> AppState { + let path = dir.join("runner.toml"); + std::fs::write( + &path, + "server_url = 'http://127.0.0.1:8080'\nclient_id = 'fixture'\nmax_concurrent_jobs = 2\n", + ) + .unwrap(); + let state = AppState::new(dir.into(), dir.join("resources")).unwrap(); + let mut slot = state.core.lock().await; + let core = slot.as_mut().unwrap(); + core.config.persistent_environment = None; + core.config.runtime = Some(StoredRuntime { + server_url: "http://127.0.0.1:8080".into(), + server_env_file: None, + runner_config: Some(path), + user_token_file: None, + runner_client_id: Some("fixture".into()), + project_id: None, + runtime_project_id: None, + }); + drop(slot); + state +} + +#[tokio::test] +async fn stalled_runner_settings_read_leaves_core_available_and_discards_stale_results() { + let dir = tempfile::tempdir().unwrap(); + let state = state_with_runner(dir.path()).await; + let supervisor = state.supervisor.lock().await; + let mut read = Box::pin(state.runner_settings()); + tokio::select! { + biased; + _ = &mut read => panic!("the runner ownership observation is blocked"), + _ = std::future::ready(()) => {} + } + // Simulate a target change while the old reader waits on the supervisor. + state + .core + .try_lock() + .unwrap() + .as_mut() + .unwrap() + .config + .runtime + .as_mut() + .unwrap() + .runner_client_id = Some("replacement".into()); + drop(supervisor); + assert_eq!(read.await.err().unwrap().code, "runtime_selection_changed"); + + // A previous filesystem worker still has its permit. Another read must + // time out without borrowing the Core or spawning another filesystem worker. + tokio::time::pause(); + let _reader = state.runner_settings_reader.lock().await; + let mut read = Box::pin(state.runner_settings()); + tokio::select! { + biased; + _ = &mut read => panic!("the fixture owns the read permit"), + _ = std::future::ready(()) => {} + } + state + .update_tunnel_proxy(TunnelProxyMode::Direct, None) + .await + .unwrap(); + assert_eq!(read.await.err().unwrap().code, "desktop_state_unavailable"); + assert!(state.get_state().current_operation.is_none()); +} + +#[tokio::test] +async fn settings_read_checks_admission_before_and_after_file_inspection() { + let dir = tempfile::tempdir().unwrap(); + let state = state_with_runner(dir.path()).await; + let reader = state.runner_settings_reader.lock().await; + let mut started_idle = Box::pin(state.runner_settings()); + tokio::select! { + biased; + _ = &mut started_idle => panic!("file reader permit is held"), + _ = std::future::ready(()) => {} + } + // Admission precedes Core checkout. The Core and its target still look valid. + let owner = state + .operations + .admit(DesktopOperationKind::RunnerSettingsUpdate, false) + .unwrap(); + let started_busy = tokio::select! { + biased; + result = state.runner_settings() => result, + _ = std::future::ready(()) => panic!("a read behind an admitted writer waited for file I/O"), + }; + drop(reader); + let finished_busy = started_idle.await; + for result in [started_busy, finished_busy] { + let error = result.err().expect("the admitted writer must be reported"); + assert_eq!(error.code, "desktop_operation_busy"); + assert_eq!( + error.diagnostic_ref().unwrap().operation_id.as_ref(), + Some(&owner.id) + ); + } + owner.finish(&Ok::<(), DesktopError>(())); + assert_eq!( + state.runner_settings().await.unwrap().max_concurrent_jobs, + Some(2) + ); +} + +#[tokio::test] +async fn settings_read_discards_a_candidate_rolled_back_by_a_completed_write() { + use crate::webcodex::settings::{stage_job_concurrency, target, JobConcurrencyUpdate}; + + let dir = tempfile::tempdir().unwrap(); + let state = state_with_runner(dir.path()).await; + let permit = state.runner_settings_reader.lock().await; + let mut read = Box::pin(state.runner_settings()); + tokio::select! { + biased; + _ = &mut read => panic!("file reader permit is held"), + _ = std::future::ready(()) => {} + } + let (owner, _cancellation, core, _baseline) = state + .begin_operation(DesktopOperationKind::RunnerSettingsUpdate, false) + .await + .unwrap(); + let runtime = core.runner_settings_runtime().unwrap(); + let edit = stage_job_concurrency( + &runtime, + JobConcurrencyUpdate { + target: target(&runtime).unwrap(), + expected: Some(2), + limit: 4, + }, + ) + .unwrap(); + let mut slot = state.core.lock().await; + drop(permit); + tokio::select! { + biased; + _ = &mut read => panic!("the final Core check is blocked"), + _ = state.runner_settings_reader.lock() => {} + } + // The worker has read 4 and released its permit. Roll back before allowing + // that result to be checked against the same Runner identity. + assert!(edit.rollback_if_unchanged().unwrap()); + *slot = Some(core); + owner.finish(&Err::<(), _>(cancelled_error())); + drop(slot); + assert_eq!(read.await.err().unwrap().code, "runtime_selection_changed"); + assert_eq!( + state.runner_settings().await.unwrap().max_concurrent_jobs, + Some(2) + ); +} + +#[tokio::test(start_paused = true)] +async fn preparation_releases_admission_on_drop_stop_and_timeout() { + let dir = tempfile::tempdir().unwrap(); + let state = AppState::new(dir.path().to_owned(), dir.path().join("resources")).unwrap(); + let core = state.core.lock().await; + for end in ["drop", "stop", "timeout"] { + let mut preparing = + Box::pin(state.begin_operation(DesktopOperationKind::RuntimeProbe, true)); + tokio::select! { + biased; + _ = &mut preparing => panic!("the fixture still owns the core lock"), + _ = std::future::ready(()) => {} + } + let observed = state.get_state().current_operation.unwrap(); + match end { + "drop" => drop(preparing), + "stop" => { + state.cancel_operation(&observed.id).unwrap(); + assert_eq!( + preparing.await.err().unwrap().code, + "desktop_operation_cancelled" + ); + } + _ => { + tokio::time::advance(OPERATION_SLOT_TIMEOUT).await; + assert_eq!( + preparing.await.err().unwrap().code, + "desktop_operation_start_timeout" + ); + } + } + assert!(state.operations.observe().unwrap().is_none()); + assert!(core.is_some()); + } + drop(core); + let (operation, cancellation, core, baseline) = state + .begin_operation(DesktopOperationKind::RuntimeProbe, true) + .await + .unwrap(); + let result = Ok(core.snapshot.clone()); + state + .finish_operation(operation, cancellation, core, baseline, result) + .await + .unwrap(); +} + +#[tokio::test(start_paused = true)] +async fn stop_interrupts_a_dispatched_operation_waiting_to_spawn() { + let dir = tempfile::tempdir().unwrap(); + let state = AppState::new(dir.path().into(), dir.path().join("resources")).unwrap(); + let (owner, cancellation, core, baseline) = state + .begin_operation(DesktopOperationKind::RuntimeResume, true) + .await + .unwrap(); + let supervisor = state.supervisor.lock().await; + let mut spawn = Box::pin(core.spawn_owned( + ProcessKey::LocalRunner, + std::process::Command::new(dir.path().join("must-not-launch")), + false, + &cancellation, + )); + tokio::select! { + biased; + _ = &mut spawn => panic!("the supervisor is still locked"), + _ = std::future::ready(()) => {} + } + state.cancel_operation(&owner.id).unwrap(); + let error = tokio::time::timeout(Duration::from_secs(1), spawn) + .await + .expect("Stop must interrupt the lock wait") + .err() + .unwrap(); + assert_eq!(error.code, "desktop_operation_cancelled"); + drop(supervisor); + let error = state + .finish_operation(owner, cancellation, core, baseline, Err(error)) + .await + .unwrap_err(); + assert_eq!(error.code, "desktop_operation_cancelled"); + assert!(state.get_state().current_operation.is_none()); + assert!(state.core.lock().await.is_some()); +} + +#[tokio::test(start_paused = true)] +async fn completed_write_returns_its_core_after_prolonged_lock_contention() { + let dir = tempfile::tempdir().unwrap(); + let state = AppState::new(dir.path().into(), dir.path().join("resources")).unwrap(); + let (operation, cancellation, mut core, baseline) = state + .begin_operation(DesktopOperationKind::TunnelProxyUpdate, false) + .await + .unwrap(); + let id = operation.id.clone(); + let result = core + .update_tunnel_proxy(TunnelProxyMode::Direct, None, &cancellation) + .await; + let blocked = state.core.lock().await; + let (result, ()) = tokio::join!( + state.finish_operation(operation, cancellation, core, baseline, result), + async { + tokio::time::sleep(OPERATION_SLOT_TIMEOUT + Duration::from_secs(1)).await; + assert_eq!(state.operations.current().map(|op| op.id), Some(id)); + drop(blocked); + } + ); + assert!(result.unwrap().current_operation.is_none()); + assert_eq!( + state + .core + .lock() + .await + .as_ref() + .unwrap() + .config + .tunnel_proxy + .mode, + TunnelProxyMode::Direct + ); + state + .update_tunnel_proxy(TunnelProxyMode::Auto, None) + .await + .unwrap(); +} + +#[tokio::test(start_paused = true)] +async fn delayed_failure_cleanup_returns_the_original_error_and_releases_admission() { + let dir = tempfile::tempdir().unwrap(); + let state = AppState::new(dir.path().into(), dir.path().join("resources")).unwrap(); + let (owner, cancellation, core, baseline) = state + .begin_operation(DesktopOperationKind::RuntimeResume, true) + .await + .unwrap(); + let id = owner.id.clone(); + let supervisor = state.supervisor.lock().await; + let (result, ()) = tokio::join!( + state.finish_operation(owner, cancellation, core, baseline, Err(cancelled_error())), + async { + tokio::time::sleep(OPERATION_SLOT_TIMEOUT + Duration::from_secs(1)).await; + assert_eq!(state.operations.current().map(|op| op.id), Some(id.clone())); + drop(supervisor); + } + ); + let error = result.unwrap_err(); + assert_eq!(error.code, "desktop_operation_cancelled"); + assert_eq!( + error.diagnostic_ref().unwrap().operation_id.as_ref(), + Some(&id) + ); + assert!(state.get_state().current_operation.is_none()); + state + .update_tunnel_proxy(TunnelProxyMode::Direct, None) + .await + .unwrap(); +} + +#[tokio::test] +async fn abandoned_dispatched_owner_reports_uncertainty_and_fences_later_writes() { + for panic in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let state = + Arc::new(AppState::new(dir.path().into(), dir.path().join("resources")).unwrap()); + let (started, observed) = tokio::sync::oneshot::channel(); + let worker_state = Arc::clone(&state); + let worker = tokio::spawn(async move { + let (owner, _cancel, _core, _baseline) = worker_state + .begin_operation(DesktopOperationKind::LocalSetup, true) + .await + .unwrap(); + started.send(owner.id.clone()).unwrap(); + if panic { + panic!("injected owner failure"); + } + std::future::pending::<()>().await; + }); + let id = observed.await.unwrap(); + if !panic { + worker.abort(); + } + let ended = worker.await.unwrap_err(); + assert_eq!(ended.is_panic(), panic); + let snapshot = state.get_state(); + assert!(snapshot.current_operation.is_none()); + let error = snapshot.runtime_error.unwrap(); + assert_eq!(error.code, "desktop_core_unavailable"); + assert_eq!( + error.diagnostic_ref().unwrap().operation_id.as_ref(), + Some(&id) + ); + assert!(!error.diagnostic_ref().unwrap().retry_allowed); + assert_eq!( + state.runner_settings().await.err().unwrap().code, + error.code + ); + assert_eq!( + state + .update_tunnel_proxy(TunnelProxyMode::Direct, None) + .await + .unwrap_err(), + error + ); + assert_eq!( + state.cancel_operation(&id).unwrap_err().code, + "desktop_operation_not_current" + ); + } +} + +#[tokio::test] +async fn missing_core_without_an_owner_is_an_internal_error_for_reads_and_writes() { + let dir = tempfile::tempdir().unwrap(); + let state = AppState::new(dir.path().into(), dir.path().join("resources")).unwrap(); + let _missing = state.core.lock().await.take().unwrap(); + for error in [ + state.diagnostics().await.err().unwrap(), + state.runner_settings().await.err().unwrap(), + state.runtime_settings().await.err().unwrap(), + state.path_inventory().await.err().unwrap(), + state.refresh_runtime_status().await.unwrap_err(), + state + .update_tunnel_proxy(TunnelProxyMode::Direct, None) + .await + .unwrap_err(), + ] { + assert_eq!(error.code, "desktop_core_unavailable"); + assert!(error.diagnostic_ref().unwrap().operation_id.is_none()); + } + assert!(state.operations.current().is_none()); +} diff --git a/apps/desktop/src-tauri/src/state/path_inventory.rs b/apps/desktop/src-tauri/src/state/path_inventory.rs index 75f72de37..9799f0957 100644 --- a/apps/desktop/src-tauri/src/state/path_inventory.rs +++ b/apps/desktop/src-tauri/src/state/path_inventory.rs @@ -48,7 +48,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| inventory_error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; let root = webcodex_environment::default_environment_dir().map_err(environment::desktop_error)?; let inventory = desktop_inventory(core, &root, self.desktop_data_dir.source.label()); @@ -65,7 +65,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| inventory_error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; let root = webcodex_environment::default_environment_dir().map_err(environment::desktop_error)?; let inventory = desktop_inventory(core, &root, self.desktop_data_dir.source.label()); @@ -80,7 +80,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| inventory_error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; let root = webcodex_environment::default_environment_dir().map_err(environment::desktop_error)?; let inventory = desktop_inventory(core, &root, self.desktop_data_dir.source.label()); @@ -101,7 +101,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| inventory_error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; let root = webcodex_environment::default_environment_dir().map_err(environment::desktop_error)?; let inventory = desktop_inventory(core, &root, self.desktop_data_dir.source.label()); diff --git a/apps/desktop/src-tauri/src/state/projectless_tests.rs b/apps/desktop/src-tauri/src/state/projectless_tests.rs index 2b89580a4..27fa86446 100644 --- a/apps/desktop/src-tauri/src/state/projectless_tests.rs +++ b/apps/desktop/src-tauri/src/state/projectless_tests.rs @@ -263,8 +263,7 @@ async fn workspace_observation_fences_completed_concurrent_operations_and_persis .operations .admit(DesktopOperationKind::RuntimeRefresh, false) .unwrap(); - app.operations - .finish(&operation.id, &Ok::<_, DesktopError>(())); + operation.finish(&Ok::<_, DesktopError>(())); } release_tx.send(()).unwrap(); let result = query.await.unwrap(); diff --git a/apps/desktop/src-tauri/src/state/runtime_shell.rs b/apps/desktop/src-tauri/src/state/runtime_shell.rs index 0894548af..71e4960a5 100644 --- a/apps/desktop/src-tauri/src/state/runtime_shell.rs +++ b/apps/desktop/src-tauri/src/state/runtime_shell.rs @@ -48,7 +48,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| runtime_selection::error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; ( core.runtime_settings_snapshot().await, core.config.clone(), diff --git a/apps/desktop/src-tauri/src/state/tests.rs b/apps/desktop/src-tauri/src/state/tests.rs index 19c580c80..81ca69291 100644 --- a/apps/desktop/src-tauri/src/state/tests.rs +++ b/apps/desktop/src-tauri/src/state/tests.rs @@ -841,6 +841,38 @@ WEBCODEX_WINDOWS ); } + #[test] + fn failed_settings_save_across_reopen_is_not_operation_contention() { + use crate::error::SafeRecoveryAction; + + let dir = tempfile::tempdir().unwrap(); + let primary = dir.path().join("desktop-state.json"); + let backup = desktop_state_backup_path(&primary); + let activity = ActivityLog::default(); + let save = || { + let mut config = load_config(&primary, &activity)?; + config.tunnel_proxy.mode = TunnelProxyMode::Direct; + save_config_atomically(&primary, &serde_json::to_vec(&config).unwrap()) + }; + + let original = serde_json::to_vec(&StoredDesktopConfig::default()).unwrap(); + std::fs::write(&primary, &original).unwrap(); + // A directory at the backup destination makes replacement fail even as root. + std::fs::create_dir(&backup).unwrap(); + for _ in 0..2 { + let error = save().unwrap_err(); + assert_eq!(error.code, "desktop_state_unavailable"); + let diagnostic = error.diagnostic_ref().unwrap(); + assert_eq!(diagnostic.safe_action, SafeRecoveryAction::OpenDiagnostics); + assert!(!diagnostic.retry_allowed); + assert_eq!(std::fs::read(&primary).unwrap(), original); + } + std::fs::remove_dir(backup).unwrap(); + save().unwrap(); + let reloaded = load_config(&primary, &activity).unwrap(); + assert_eq!(reloaded.tunnel_proxy.mode, TunnelProxyMode::Direct); + } + #[tokio::test] async fn diagnostics_contention_keeps_the_competing_operation_observable() { let data_dir = tempfile::tempdir().unwrap(); @@ -849,6 +881,8 @@ WEBCODEX_WINDOWS data_dir.path().join("test-resources"), ) .unwrap(); + // Model a Desktop with no configured Runner regardless of the host environment. + state.core.lock().await.as_mut().unwrap().config.runtime = None; for kind in [ DesktopOperationKind::RuntimeRefresh, DesktopOperationKind::RuntimeSwitch, @@ -865,6 +899,16 @@ WEBCODEX_WINDOWS let competing = observed.current_operation.as_ref().unwrap(); assert_eq!(competing.id, operation.id); assert_eq!(competing.kind, kind); + let settings_error = state.runner_settings().await.err().unwrap(); + assert_eq!(settings_error.code, "desktop_operation_busy"); + assert_eq!( + settings_error + .diagnostic_ref() + .unwrap() + .operation_id + .as_ref(), + Some(&operation.id) + ); state .finish_operation(operation, cancellation, core, baseline, Ok(observed)) @@ -872,6 +916,10 @@ WEBCODEX_WINDOWS .unwrap(); assert!(state.get_state().current_operation.is_none()); assert!(state.diagnostics().await.is_ok()); + assert_eq!( + state.runner_settings().await.err().unwrap().code, + "local_runner_required" + ); } } diff --git a/apps/desktop/src-tauri/src/state/updates.rs b/apps/desktop/src-tauri/src/state/updates.rs index 8372c5b73..525380963 100644 --- a/apps/desktop/src-tauri/src/state/updates.rs +++ b/apps/desktop/src-tauri/src/state/updates.rs @@ -27,7 +27,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| runtime_selection::error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; ( core.adapter.binaries().ok().cloned(), core.config.runtime_binary_source.clone(), @@ -63,7 +63,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| runtime_selection::error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; ( core.config.runtime_selection_revision, core.adapter.binaries().ok().cloned(), @@ -82,7 +82,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| runtime_selection::error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; let binaries_unchanged = match (binaries.as_ref(), core.adapter.binaries().ok()) { (None, None) => true, (Some(before), Some(current)) => { @@ -146,7 +146,7 @@ impl AppState { let cache = { let slot = self.core.lock().await; slot.as_ref() - .ok_or_else(|| runtime_selection::error("desktop_operation_busy"))? + .ok_or_else(|| self.operations.missing_core_error())? .config .update_cache .clone() @@ -164,7 +164,7 @@ impl AppState { &cache, now, false, - manual.then(|| "update_check_not_saved_runtime_busy".into()), + manual.then(|| self.operations.missing_core_error().code), )); }; if core.configuration_issue.is_some() { @@ -226,7 +226,7 @@ impl AppState { let mut slot = self.core.lock().await; let core = slot .as_mut() - .ok_or_else(|| runtime_selection::error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; if core.configuration_issue.is_some() { return Err(runtime_selection::error("configuration_migration_failed")); } @@ -310,7 +310,7 @@ impl AppState { let mut slot = self.core.lock().await; let core = slot .as_mut() - .ok_or_else(|| runtime_selection::error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; if core.configuration_issue.is_some() { return Err(runtime_selection::error("configuration_migration_failed")); } @@ -329,7 +329,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| runtime_selection::error("desktop_operation_busy"))?; + .ok_or_else(|| self.operations.missing_core_error())?; let notice = core .config .update_cache diff --git a/apps/desktop/src-tauri/src/state/workspace_settings.rs b/apps/desktop/src-tauri/src/state/workspace_settings.rs index 542669f77..a68b9b143 100644 --- a/apps/desktop/src-tauri/src/state/workspace_settings.rs +++ b/apps/desktop/src-tauri/src/state/workspace_settings.rs @@ -1,30 +1,82 @@ use super::*; +impl DesktopCore { + pub(super) fn runner_settings_runtime(&self) -> DesktopResult { + let has_runner = self + .config + .topology + .as_ref() + .is_none_or(|topology| topology.runner == RunnerTopology::Local); + self.config + .runtime + .as_ref() + .filter(|_| has_runner) + .cloned() + .ok_or_else(|| { + DesktopError::new( + "local_runner_required", + "These settings require a local Runner", + "Configure a Runner on this computer to use its settings.", + ) + }) + } +} + impl AppState { pub async fn runner_settings( &self, ) -> DesktopResult { - let mut slot = self.core.lock().await; - let core = slot - .as_mut() - .ok_or_else(|| desktop_state_unavailable("Desktop is busy"))?; - let runtime = core - .config - .runtime - .clone() - .ok_or_else(|| desktop_state_unavailable("Configure a Runner first"))?; - let can_restart = if core.config.persistent_environment.is_some() { + tokio::time::timeout(OPERATION_SLOT_TIMEOUT, self.inspect_runner_settings()) + .await + .map_err(|_| desktop_state_unavailable("Runner settings inspection timed out"))? + } + + async fn inspect_runner_settings( + &self, + ) -> DesktopResult { + let (runtime, environment, generation) = { + let slot = self.core.lock().await; + let generation = self.operations.idle_generation()?; + let core = slot + .as_ref() + .ok_or_else(crate::operation::core_unavailable)?; + ( + core.runner_settings_runtime()?, + core.config.persistent_environment.clone(), + generation, + ) + }; + // A slow supervisor or configuration file must not hold the mutation slot. + let reader = Arc::clone(&self.runner_settings_reader).lock_owned().await; + let can_restart = if environment.is_some() { runtime.runner_config.is_some() && runtime.runner_client_id.is_some() } else { - core.process_snapshot(ProcessKey::LocalRunner) + self.supervisor + .lock() .await + .snapshot(ProcessKey::LocalRunner) .is_some_and(|p| p.owned_by_desktop && p.phase == ProcessPhase::Running) }; - tokio::task::spawn_blocking(move || { - crate::webcodex::settings::inspect(&runtime, can_restart) + let target = runtime.clone(); + let settings = tokio::task::spawn_blocking(move || { + // Keep at most one file inspection running even if the caller times out. + let _reader = reader; + crate::webcodex::settings::inspect(&target, can_restart) }) .await - .map_err(|_| desktop_state_unavailable("Settings worker stopped"))? + .map_err(|_| desktop_state_unavailable("Settings worker stopped"))?; + let slot = self.core.lock().await; + let current_generation = self.operations.idle_generation()?; + let core = slot + .as_ref() + .ok_or_else(crate::operation::core_unavailable)?; + if current_generation != generation + || core.config.runtime.as_ref() != Some(&runtime) + || core.config.persistent_environment != environment + { + return Err(crate::runtime_selection::error("runtime_selection_changed")); + } + settings } pub async fn update_runner_settings( @@ -35,11 +87,7 @@ impl AppState { .begin_operation(DesktopOperationKind::RunnerSettingsUpdate, false) .await?; let result = async { - let runtime = core - .config - .runtime - .clone() - .ok_or_else(|| desktop_state_unavailable("Configure a Runner first"))?; + let runtime = core.runner_settings_runtime()?; let edit = tokio::task::spawn_blocking({ let runtime = runtime.clone(); move || crate::webcodex::settings::stage_paths_update(&runtime, request) @@ -62,11 +110,7 @@ impl AppState { .begin_operation(DesktopOperationKind::RunnerSettingsUpdate, false) .await?; let result = async { - let runtime = core - .config - .runtime - .clone() - .ok_or_else(|| desktop_state_unavailable("Configure a Runner first"))?; + let runtime = core.runner_settings_runtime()?; let edit = tokio::task::spawn_blocking({ let runtime = runtime.clone(); move || crate::webcodex::settings::stage_allowed_roots_update(&runtime, request) @@ -107,11 +151,7 @@ impl AppState { "Change the configuration through the Runner's actual process owner.", )); } - let runtime = core - .config - .runtime - .clone() - .ok_or_else(|| desktop_state_unavailable("Configure a Runner first"))?; + let runtime = core.runner_settings_runtime()?; let edit = tokio::task::spawn_blocking({ let runtime = runtime.clone(); move || crate::webcodex::settings::stage_job_concurrency(&runtime, request) @@ -201,11 +241,7 @@ impl AppState { .begin_operation(DesktopOperationKind::RunnerSettingsUpdate, false) .await?; let result = async { - let runtime = core - .config - .runtime - .clone() - .ok_or_else(|| desktop_state_unavailable("Configure a Runner first"))?; + let runtime = core.runner_settings_runtime()?; tokio::task::spawn_blocking(move || { crate::webcodex::settings::add_plugin(&runtime, request) }) diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index 4ad096fba..3a46196c2 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -480,6 +480,29 @@ beforeEach(() => { } }); + it.each(["startup", "poll"] as const)("shows the competing operation after a persistent %s refresh collision", async trigger => { + vi.useFakeTimers(); + const idle = { ...readyState, persistent_environment: "fixture-environment" }; + 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 view = renderApp(); + try { + await act(async () => {}); + if (trigger === "poll") await act(async () => { await vi.advanceTimersByTimeAsync(1_500); }); + expect(screen.getByRole("status", { name: "当前 Desktop 操作" })).toHaveAttribute("data-webcodex-operation", "local_setup"); + expect(screen.getByRole("button", { name: "停止当前操作" })).toBeEnabled(); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + await act(async () => { await vi.advanceTimersByTimeAsync(1_000); }); + expect(screen.queryByRole("status", { name: "当前 Desktop 操作" })).not.toBeInTheDocument(); + expect(api.cancelOperation).not.toHaveBeenCalled(); + } finally { + view.unmount(); + vi.useRealTimers(); + } + }); + it("treats a Refresh collision with an already running Desktop operation as state observation", async () => { api.getState .mockResolvedValueOnce(readyState) @@ -1299,6 +1322,34 @@ beforeEach(() => { expect(api.cancelOperation).toHaveBeenCalledTimes(1); }); + it("shows recovery guidance while an overdue owner retains the operation", async () => { + const running = localSetupOperationState(); + api.getState.mockResolvedValueOnce(readyState).mockResolvedValue({ + ...running, current_operation: { ...running.current_operation!, phase: "overdue", cancellable: false }, + }); + api.refresh.mockRejectedValueOnce({ code: "desktop_operation_unsettled", message: "Operation overdue", next_action: "Check Activity" }); + renderApp(); + fireEvent.click(await screen.findByRole("button", { name: "刷新" })); + const status = await screen.findByRole("status", { name: "当前 Desktop 操作" }); + expect(status).toHaveTextContent("操作用时超出预期"); + expect(status).toHaveTextContent("核实操作结果"); + expect(screen.queryByRole("button", { name: "停止当前操作" })).not.toBeInTheDocument(); + expect(api.cancelOperation).not.toHaveBeenCalled(); + }); + + it("shows an interrupted first-run owner without resuming setup or offering Stop", async () => { + api.getState.mockResolvedValue({ ...firstRunState, runtime_error: { + code: "desktop_core_unavailable", message: "Desktop state unavailable", next_action: "Check Activity", + } }); + renderApp(); + const alert = await screen.findByRole("alert"); + expect(alert).toHaveTextContent("Desktop 内部操作状态不可用"); + expect(alert).toHaveTextContent("完全退出并重新打开"); + expect(screen.queryByRole("button", { name: "停止当前操作" })).not.toBeInTheDocument(); + expect(api.configureEnvironment).not.toHaveBeenCalled(); + expect(api.resumeSavedRuntime).not.toHaveBeenCalled(); + }); + it("does not let an older polling response resurrect a completed operation", async () => { vi.useFakeTimers(); try { diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index ff30baba6..6bc143adb 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -34,7 +34,8 @@ function DesktopApp() { const [extensionTab, setExtensionTab] = useState(); const [settingsSection, setSettingsSection] = useState<"diagnostics" | "runtime" | "network" | "access" | undefined>(); const { state, activity, chatgptActivityQueryStatus, navigation, previousPage, setNavigation, refreshing, preserveWorkspacePollDeadline, error, setError, cancelSubmittingId, showSetup, setupOrigin, closeSetup, setStartupAttempt, mainRef, commitState, openSetup, refresh, resumeRuntime, cancelCurrentOperation, runStateOperation } = useDesktopWorkspace(); - const updates = useRuntimeUpdates(Boolean(state && !state.current_operation && !state.configuration_issue)); + const coreFailure = state?.runtime_error?.code === "desktop_core_unavailable" ? state.runtime_error : null; + const updates = useRuntimeUpdates(Boolean(state && !state.current_operation && !state.configuration_issue && !coreFailure)); const openSettings = (section: "diagnostics" | "runtime" | "network" | "access") => { setSettingsSection(section); setNavigation("settings"); }; if (!state) { return ( @@ -63,6 +64,7 @@ function DesktopApp() { } const needsSetup = !state.topology || showSetup; + const shellError = coreFailure ?? error; const shellErrorActions: DesktopErrorActions = { onRefresh: () => void refresh(), onRetry: () => void refresh(), @@ -105,12 +107,10 @@ function DesktopApp() { >
- {state.current_operation.phase === "cancelling" - ? t("operation.cancelling") - : t("operation.running")} + {t(`operation.${state.current_operation.phase}`)} {operationLabel(state.current_operation.kind, t)} - {t("operation.cancelNote")} + {t(state.current_operation.phase === "overdue" ? "operation.overdueHelp" : "operation.cancelNote")}
{state.current_operation.cancellable && (