From 1cafdb480a1962938e19df0e01924b877071cec3 Mon Sep 17 00:00:00 2001 From: yyjeqhc <1772413353@qq.com> Date: Sat, 28 Nov 2026 17:42:57 +0800 Subject: [PATCH 1/3] fix(desktop): distinguish settings failures from active operations --- apps/desktop/src-tauri/src/error.rs | 5 +- apps/desktop/src-tauri/src/operation.rs | 27 ++++++---- apps/desktop/src-tauri/src/state/app_state.rs | 22 +------- .../src-tauri/src/state/coding_agents.rs | 6 +-- .../src-tauri/src/state/diagnostics.rs | 17 ++---- .../src/state/managed_instructions.rs | 6 +-- apps/desktop/src-tauri/src/state/tests.rs | 48 +++++++++++++++++ .../src-tauri/src/state/workspace_settings.rs | 54 ++++++++++--------- apps/desktop/src/App.test.tsx | 23 ++++++++ .../src/features/WorkspaceSettings.test.tsx | 2 +- .../settings/ConfigurationDataPanel.test.tsx | 4 +- .../settings/SettingsPanel.races.test.tsx | 35 +++++------- .../src/features/settings/SettingsPanel.tsx | 13 ++--- apps/desktop/src/hooks/useDesktopWorkspace.ts | 25 +++------ apps/desktop/src/i18n/messages/de-DE.json | 6 ++- apps/desktop/src/i18n/messages/en-US.json | 6 ++- apps/desktop/src/i18n/messages/fr-FR.json | 6 ++- apps/desktop/src/i18n/messages/ja-JP.json | 6 ++- apps/desktop/src/i18n/messages/ko-KR.json | 6 ++- apps/desktop/src/i18n/messages/zh-CN.json | 6 ++- apps/desktop/src/i18n/messages/zh-TW.json | 6 ++- apps/desktop/src/i18n/presentation.test.ts | 3 ++ apps/desktop/src/lib/desktop-errors.ts | 25 +++++++-- apps/desktop/src/lib/desktop-observation.ts | 15 ++++-- 24 files changed, 226 insertions(+), 146 deletions(-) diff --git a/apps/desktop/src-tauri/src/error.rs b/apps/desktop/src-tauri/src/error.rs index a10f58b9b..a849ad1d7 100644 --- a/apps/desktop/src-tauri/src/error.rs +++ b/apps/desktop/src-tauri/src/error.rs @@ -298,6 +298,7 @@ impl ErrorDiagnostic { | "desktop_data_dir_invalid" | "desktop_data_dir_unavailable" | "state_io" => (Config, ManualCheck, OpenDiagnostics, false), + "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 +319,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/operation.rs b/apps/desktop/src-tauri/src/operation.rs index 79c132128..cdf1e136b 100644 --- a/apps/desktop/src-tauri/src/operation.rs +++ b/apps/desktop/src-tauri/src/operation.rs @@ -66,6 +66,23 @@ pub(crate) fn cancelled_error() -> DesktopError { ) } +pub(crate) fn busy_error(current: Option<&DesktopOperationSnapshot>) -> DesktopError { + let error = DesktopError::new( + "desktop_operation_busy", + "Another Desktop operation is still running", + "Wait for the current operation to finish or stop it if it is cancellable.", + ); + match current { + Some(current) => 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), + None => error, + } +} + struct ActiveOperation { snapshot: DesktopOperationSnapshot, cancellation: CancellationSignal, @@ -107,15 +124,7 @@ impl OperationController { .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(), - }))); + return Err(busy_error(Some(¤t.snapshot))); } let sequence = self.next_id.fetch_add(1, Ordering::Relaxed) + 1; diff --git a/apps/desktop/src-tauri/src/state/app_state.rs b/apps/desktop/src-tauri/src/state/app_state.rs index ac45786e7..62d9c908d 100644 --- a/apps/desktop/src-tauri/src/state/app_state.rs +++ b/apps/desktop/src-tauri/src/state/app_state.rs @@ -148,16 +148,7 @@ impl AppState { 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)); + return Err(crate::operation::busy_error(Some(¤t))); } if self.get_state().configuration_issue.is_some() { return Err(DesktopError::new( @@ -173,16 +164,7 @@ impl AppState { 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)); + return Err(crate::operation::busy_error(Some(¤t))); } // Coalesce overlapping background refreshes: if another refresh already // published a fresher snapshot while we waited, return it directly. 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/diagnostics.rs b/apps/desktop/src-tauri/src/state/diagnostics.rs index 07b2bbe74..b3e08c757 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(|| crate::operation::busy_error(self.operations.current().as_ref()))?; let settings = core.runtime_settings_snapshot().await; let runtime = core.config.runtime.clone(); let trace_target = core.managed_trace_target().await; 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/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/workspace_settings.rs b/apps/desktop/src-tauri/src/state/workspace_settings.rs index 542669f77..4ac02323f 100644 --- a/apps/desktop/src-tauri/src/state/workspace_settings.rs +++ b/apps/desktop/src-tauri/src/state/workspace_settings.rs @@ -1,5 +1,27 @@ 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, @@ -7,12 +29,8 @@ impl AppState { 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"))?; + .ok_or_else(|| crate::operation::busy_error(self.operations.current().as_ref()))?; + let runtime = core.runner_settings_runtime()?; let can_restart = if core.config.persistent_environment.is_some() { runtime.runner_config.is_some() && runtime.runner_client_id.is_some() } else { @@ -35,11 +53,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 +76,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 +117,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 +207,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..b709e8c64 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) diff --git a/apps/desktop/src/features/WorkspaceSettings.test.tsx b/apps/desktop/src/features/WorkspaceSettings.test.tsx index 69650cddc..3439e906b 100644 --- a/apps/desktop/src/features/WorkspaceSettings.test.tsx +++ b/apps/desktop/src/features/WorkspaceSettings.test.tsx @@ -207,7 +207,7 @@ describe("workspace configuration boundaries", () => { it("retries only the file-access readback when a background refresh temporarily owns the core", async () => { settings.file_access = { ...settings.file_access, configured_roots: ["/fixture/work"], effective_roots: ["/fixture/work"], using_default_roots: false }; - api.runnerSettings.mockRejectedValueOnce({ code: "desktop_state_unavailable", message: "Refreshing", next_action: "Refresh" }); + api.runnerSettings.mockRejectedValueOnce({ code: "desktop_operation_busy", message: "Refreshing", next_action: "Refresh" }); render(wrap()); fireEvent.click(screen.getByRole("button", { name: "Restore default access" })); await screen.findByText("No custom folders configured."); diff --git a/apps/desktop/src/features/settings/ConfigurationDataPanel.test.tsx b/apps/desktop/src/features/settings/ConfigurationDataPanel.test.tsx index eb11f8294..ddeba77db 100644 --- a/apps/desktop/src/features/settings/ConfigurationDataPanel.test.tsx +++ b/apps/desktop/src/features/settings/ConfigurationDataPanel.test.tsx @@ -23,10 +23,10 @@ afterEach(() => { vi.useRealTimers(); }); describe("configuration location observations", () => { - it.each(["desktop_operation_busy", "desktop_state_unavailable"])("recovers a passive refresh collision reported as %s", async code => { + it("recovers a passive refresh collision", async () => { vi.useFakeTimers(); vi.mocked(desktopApi.getState).mockResolvedValue({ ...state, current_operation: { id: "refresh", kind: "runtime_refresh", phase: "running", started_at_ms: 1, cancellable: false } }); - vi.mocked(desktopApi.pathInventory).mockRejectedValueOnce({ code, message: "private refresh detail", next_action: "Wait" }).mockResolvedValueOnce(inventory()); + vi.mocked(desktopApi.pathInventory).mockRejectedValueOnce({ code: "desktop_operation_busy", message: "private refresh detail", next_action: "Wait" }).mockResolvedValueOnce(inventory()); render(view()); await act(async () => {}); await act(async () => { await vi.advanceTimersByTimeAsync(200); }); expect(screen.getByText("/private/desktop.root")).toBeVisible(); diff --git a/apps/desktop/src/features/settings/SettingsPanel.races.test.tsx b/apps/desktop/src/features/settings/SettingsPanel.races.test.tsx index ef0252cdc..1bff33f7e 100644 --- a/apps/desktop/src/features/settings/SettingsPanel.races.test.tsx +++ b/apps/desktop/src/features/settings/SettingsPanel.races.test.tsx @@ -37,7 +37,7 @@ const fixtureSettings: RunnerSettings = { file_access: { configured_roots: [], default_roots: ["/Users/fixture"], effective_roots: ["/Users/fixture"], using_default_roots: true, allow_cwd_anywhere: false }, }; const refreshOperation = { id: "refresh", kind: "runtime_refresh", phase: "running", started_at_ms: 1, cancellable: false } as const; -const busyError = { code: "desktop_state_unavailable", message: "The core is being refreshed.", next_action: "Refresh" }; +const busyError = { code: "desktop_operation_busy", message: "The core is being refreshed.", next_action: "Refresh" }; let state: DesktopState, settings: RunnerSettings; const wrap = (child: React.ReactNode) => {child}; function deferred() { @@ -78,12 +78,8 @@ describe("Settings observation and action ownership", () => { it("recovers file access when a first settings read races with runtime refresh", async () => { vi.useFakeTimers(); - state = { ...state, current_operation: refreshOperation }; api.runnerSettings.mockRejectedValueOnce(busyError); - const view = render(wrap()); - await act(async () => {}); - state = { ...state, current_operation: null }; - view.rerender(wrap()); + render(wrap()); await act(async () => { await vi.advanceTimersByTimeAsync(250); }); expect(api.runnerSettings).toHaveBeenCalledTimes(2); expect(screen.getByRole("button", { name: "Authorize folder" })).toBeEnabled(); @@ -91,11 +87,13 @@ describe("Settings observation and action ownership", () => { expect(screen.queryByRole("alert")).not.toBeInTheDocument(); }); - it("shows a failed settings read and allows recovery without leaving the page", async () => { - api.runnerSettings.mockRejectedValueOnce({ code: "runner_settings_read_failed", message: "Fixture settings could not be read", next_action: "Refresh" }); + it("shows a local state failure until the user refreshes the settings", async () => { + api.runnerSettings.mockRejectedValueOnce({ code: "desktop_state_unavailable", message: "Fixture settings could not be read", next_action: "Check permissions" }); render(wrap()); const alert = await screen.findByRole("alert"); - expect(alert).toHaveTextContent("runner_settings_read_failed"); + expect(alert).toHaveTextContent("Desktop could not access its local state"); + expect(alert).toHaveAttribute("data-error-recovery", "manual_check"); + expect(api.getState).not.toHaveBeenCalled(); expect(screen.queryByRole("status")).not.toBeInTheDocument(); expect(screen.getByRole("button", { name: "Authorize folder" })).toBeDisabled(); fireEvent.click(within(alert).getByRole("button", { name: "Refresh" })); @@ -104,22 +102,15 @@ describe("Settings observation and action ownership", () => { expect(api.runnerSettings).toHaveBeenCalledTimes(2); }); - it("retries a bounded-out settings observation when the published runtime refresh ends", async () => { - vi.useFakeTimers(); - state = { ...state, current_operation: refreshOperation }; - api.runnerSettings.mockRejectedValue(busyError); + it.each(["runtime_refresh", "runtime_resume"] as const)("loads settings once after an active %s finishes", async kind => { + state = { ...state, current_operation: { ...refreshOperation, kind } }; const view = render(wrap()); - await act(async () => { await vi.advanceTimersByTimeAsync(1_500); }); - expect(screen.getByRole("alert")).toHaveTextContent("desktop_state_unavailable"); - expect(screen.queryByRole("status")).not.toBeInTheDocument(); - const attempts = api.runnerSettings.mock.calls.length; - expect(attempts).toBeGreaterThan(1); - api.runnerSettings.mockResolvedValue(settings); + expect(api.runnerSettings).not.toHaveBeenCalled(); + expect(screen.getByRole("button", { name: "Authorize folder" })).toBeDisabled(); state = { ...state, current_operation: null }; view.rerender(wrap()); - await act(async () => {}); - expect(api.runnerSettings).toHaveBeenCalledTimes(attempts + 1); - expect(screen.getByRole("button", { name: "Authorize folder" })).toBeEnabled(); + await waitFor(() => expect(screen.getByRole("button", { name: "Authorize folder" })).toBeEnabled()); + expect(api.runnerSettings).toHaveBeenCalledOnce(); expect(screen.queryByRole("alert")).not.toBeInTheDocument(); }); diff --git a/apps/desktop/src/features/settings/SettingsPanel.tsx b/apps/desktop/src/features/settings/SettingsPanel.tsx index 99930bf1f..939767f25 100644 --- a/apps/desktop/src/features/settings/SettingsPanel.tsx +++ b/apps/desktop/src/features/settings/SettingsPanel.tsx @@ -122,16 +122,11 @@ function SettingsView({ if (current()) setLoadingRunnerSettings(false); } }, [identity, expectedTarget]); - useEffect(() => { void refreshRunnerSettings(); }, [refreshRunnerSettings]); - const previousOperation = useRef(state.current_operation?.kind); useEffect(() => { - const wasRefresh = previousOperation.current === "runtime_refresh"; - previousOperation.current = state.current_operation?.kind; - if (wasRefresh && !operationBusy && runnerSettingsError - && ["desktop_operation_busy", "desktop_state_unavailable"].includes(runnerSettingsError.code)) { - void refreshRunnerSettings(); - } - }, [state.current_operation?.kind, operationBusy, runnerSettingsError, refreshRunnerSettings]); + if (operationBusy) return; + void refreshRunnerSettings(); + return () => reading.current?.abort(); + }, [operationBusy, refreshRunnerSettings]); useEffect(() => { let cancelled = false; void desktopApi.getLaunchAtLogin().then(enabled => { diff --git a/apps/desktop/src/hooks/useDesktopWorkspace.ts b/apps/desktop/src/hooks/useDesktopWorkspace.ts index 701670464..4a965d4e0 100644 --- a/apps/desktop/src/hooks/useDesktopWorkspace.ts +++ b/apps/desktop/src/hooks/useDesktopWorkspace.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { subscribeDesktopNavigation } from "../lib/desktop-navigation"; import { desktopApi } from "../lib/desktop-api"; -import { desktopIdentity, type ChatgptActivityQueryStatus } from "../lib/desktop-observation"; +import { desktopIdentity, refreshOrObserveDesktopState, type ChatgptActivityQueryStatus } from "../lib/desktop-observation"; import { isErrorStaleForState, reconcileDesktopStateErrors } from "../lib/desktop-errors"; import type { ActivityEntry, DesktopError, DesktopState } from "../models/topology"; import { normalizeDesktopError } from "../i18n/presentation"; @@ -180,8 +180,8 @@ export function useDesktopWorkspace() { // it must not restart a service the user explicitly stopped. setRefreshing(true); try { - const observed = await desktopApi.refresh(); - if (!cancelled) commitState(observed); + const observed = await refreshOrObserveDesktopState(); + if (!cancelled && observed) commitState(observed); } catch (value) { if (!cancelled) recordError(value); } finally { @@ -255,9 +255,9 @@ export function useDesktopWorkspace() { if (refreshRuntime) setRuntimeObservations(count => count + 1); try { const next = refreshRuntime - ? await desktopApi.refresh() + ? await refreshOrObserveDesktopState() : await desktopApi.getState(); - if (!cancelled && stateVersionRef.current === observedVersion) { + if (next && !cancelled && stateVersionRef.current === observedVersion) { commitState(next); } } catch { @@ -335,19 +335,10 @@ export function useDesktopWorkspace() { setRefreshing(true); setError(null); try { - commitState(await desktopApi.refresh()); + const next = await refreshOrObserveDesktopState(); + if (next) commitState(next); } catch (value) { - const failure = normalizeDesktopError(value); - if (failure.code === "desktop_operation_busy") { - try { - commitState(await desktopApi.getState()); - } catch { - // The competing operation remains authoritative; a failed observation - // must not turn an ordinary Refresh race into a second error. - } - } else { - await observeFailedOperation(value); - } + await observeFailedOperation(value); } finally { setRefreshing(false); } diff --git a/apps/desktop/src/i18n/messages/de-DE.json b/apps/desktop/src/i18n/messages/de-DE.json index c7adf571e..34dafed71 100644 --- a/apps/desktop/src/i18n/messages/de-DE.json +++ b/apps/desktop/src/i18n/messages/de-DE.json @@ -238,8 +238,12 @@ "error.contractAction": "Sicherstellen, dass Desktop und alle drei WebCodex-Programme dieselbe Quellrevision verwenden.", "error.topologyTitle": "Aktuelle Laufzeittopologie unterstützt diesen Vorgang nicht", "error.topologyAction": "Diesen Computer als Hauptknoten einrichten oder externen Zugriff auf dem Remote-Server verwalten.", + "error.stateUnavailableTitle": "Desktop kann nicht auf den lokalen Zustand zugreifen", + "error.stateUnavailableAction": "Prüfen Sie die lokale Konfiguration und die Lese- und Schreibrechte Ihres Kontos für das Desktop-Datenverzeichnis.", + "error.localRunnerRequiredTitle": "Ein lokaler Runner ist erforderlich", + "error.localRunnerRequiredAction": "Richten Sie einen Runner auf diesem Computer ein, um diese Funktion zu verwenden.", "error.operationBusyTitle": "Ein anderer Desktop-Vorgang läuft noch", - "error.operationBusyAction": "Warten, bis der aktuelle Vorgang endet, oder ihn zuerst stoppen.", + "error.operationBusyAction": "Warten Sie, bis der aktuelle Vorgang abgeschlossen ist. Wenn eine Schaltfläche zum Stoppen angezeigt wird, können Sie den Vorgang dort beenden.", "error.operationStaleTitle": "Der aktuelle Vorgang hat sich geändert", "error.operationStaleAction": "Status aktualisieren, bevor der aktuell angezeigte Vorgang gestoppt wird.", "error.operationCancelledTitle": "Desktop-Vorgang gestoppt", diff --git a/apps/desktop/src/i18n/messages/en-US.json b/apps/desktop/src/i18n/messages/en-US.json index fd2169245..2297bf070 100644 --- a/apps/desktop/src/i18n/messages/en-US.json +++ b/apps/desktop/src/i18n/messages/en-US.json @@ -227,8 +227,12 @@ "error.contractAction": "Make sure Desktop and all three WebCodex programs come from the same source revision.", "error.topologyTitle": "This operation is not supported by the current runtime topology", "error.topologyAction": "Set up this computer as a main node, or manage external access on the remote Server.", + "error.stateUnavailableTitle": "Desktop could not access its local state", + "error.stateUnavailableAction": "Check the local configuration and verify that your account can read and write the Desktop data directory.", + "error.localRunnerRequiredTitle": "A local Runner is required", + "error.localRunnerRequiredAction": "Set up a Runner on this computer to use this feature.", "error.operationBusyTitle": "Another Desktop operation is still running", - "error.operationBusyAction": "Wait for the current operation to finish, or stop it first.", + "error.operationBusyAction": "Wait for the current operation to finish. If it has a Stop button, you can stop it there.", "error.operationStaleTitle": "The current operation has changed", "error.operationStaleAction": "Refresh state before stopping the operation you currently observe.", "error.operationCancelledTitle": "Desktop operation stopped", diff --git a/apps/desktop/src/i18n/messages/fr-FR.json b/apps/desktop/src/i18n/messages/fr-FR.json index 4de3b9aa6..f37e911d5 100644 --- a/apps/desktop/src/i18n/messages/fr-FR.json +++ b/apps/desktop/src/i18n/messages/fr-FR.json @@ -238,8 +238,12 @@ "error.contractAction": "Vérifiez que Desktop et les trois programmes WebCodex proviennent de la même révision du code source.", "error.topologyTitle": "Cette opération n’est pas prise en charge par la topologie actuelle", "error.topologyAction": "Configurez cet ordinateur comme nœud principal ou gérez l’accès externe sur le Server distant.", + "error.stateUnavailableTitle": "Desktop ne peut pas accéder à son état local", + "error.stateUnavailableAction": "Vérifiez la configuration locale et les droits de lecture et d’écriture de votre compte sur le dossier de données de Desktop.", + "error.localRunnerRequiredTitle": "Un Runner local est nécessaire", + "error.localRunnerRequiredAction": "Configurez un Runner sur cet ordinateur pour utiliser cette fonctionnalité.", "error.operationBusyTitle": "Une autre opération Desktop est en cours", - "error.operationBusyAction": "Attendez la fin de l’opération en cours ou arrêtez-la d’abord.", + "error.operationBusyAction": "Attendez la fin de l’opération en cours. Si un bouton d’arrêt est affiché, vous pouvez l’utiliser pour arrêter l’opération.", "error.operationStaleTitle": "L’opération en cours a changé", "error.operationStaleAction": "Actualisez l’état avant d’arrêter l’opération actuellement affichée.", "error.operationCancelledTitle": "Opération Desktop arrêtée", diff --git a/apps/desktop/src/i18n/messages/ja-JP.json b/apps/desktop/src/i18n/messages/ja-JP.json index 10d565ee7..4478db60f 100644 --- a/apps/desktop/src/i18n/messages/ja-JP.json +++ b/apps/desktop/src/i18n/messages/ja-JP.json @@ -238,8 +238,12 @@ "error.contractAction": "Desktop と3つの WebCodex プログラムが同じソースリビジョンであることを確認してください。", "error.topologyTitle": "現在の実行構成ではこの操作に対応していません", "error.topologyAction": "このコンピューターをメインノードとして設定するか、リモート Server で外部接続を管理してください。", + "error.stateUnavailableTitle": "Desktop のローカル状態にアクセスできません", + "error.stateUnavailableAction": "ローカル設定を確認し、現在のアカウントで Desktop のデータディレクトリを読み書きできることを確認してください。", + "error.localRunnerRequiredTitle": "ローカル Runner が必要です", + "error.localRunnerRequiredAction": "この機能を使うには、このコンピューターで Runner を設定してください。", "error.operationBusyTitle": "別の Desktop 操作が実行中です", - "error.operationBusyAction": "現在の操作が終わるまで待つか、先に停止してください。", + "error.operationBusyAction": "現在の操作が完了するまでお待ちください。停止ボタンが表示されている場合は、そのボタンで操作を停止できます。", "error.operationStaleTitle": "現在の操作が変更されました", "error.operationStaleAction": "状態を更新してから、現在の操作を停止してください。", "error.operationCancelledTitle": "Desktop の操作を停止しました", diff --git a/apps/desktop/src/i18n/messages/ko-KR.json b/apps/desktop/src/i18n/messages/ko-KR.json index c25e11031..332501d44 100644 --- a/apps/desktop/src/i18n/messages/ko-KR.json +++ b/apps/desktop/src/i18n/messages/ko-KR.json @@ -238,8 +238,12 @@ "error.contractAction": "Desktop과 세 WebCodex 프로그램이 같은 소스 리비전인지 확인하세요.", "error.topologyTitle": "현재 실행 구성에서 지원하지 않는 작업입니다", "error.topologyAction": "이 컴퓨터를 주 노드로 설정하거나 원격 Server에서 외부 연결을 관리하세요.", + "error.stateUnavailableTitle": "Desktop이 로컬 상태에 접근할 수 없습니다", + "error.stateUnavailableAction": "로컬 설정을 확인하고 현재 계정에 Desktop 데이터 디렉터리의 읽기 및 쓰기 권한이 있는지 확인하세요.", + "error.localRunnerRequiredTitle": "로컬 Runner가 필요합니다", + "error.localRunnerRequiredAction": "이 기능을 사용하려면 이 컴퓨터에서 Runner를 설정하세요.", "error.operationBusyTitle": "다른 Desktop 작업이 실행 중입니다", - "error.operationBusyAction": "현재 작업이 끝날 때까지 기다리거나 먼저 중지하세요.", + "error.operationBusyAction": "현재 작업이 끝날 때까지 기다리세요. 중지 버튼이 표시되면 해당 버튼으로 작업을 중지할 수 있습니다.", "error.operationStaleTitle": "현재 작업이 변경되었습니다", "error.operationStaleAction": "상태를 새로 고친 뒤 현재 작업을 중지하세요.", "error.operationCancelledTitle": "Desktop 작업이 중지되었습니다", diff --git a/apps/desktop/src/i18n/messages/zh-CN.json b/apps/desktop/src/i18n/messages/zh-CN.json index 68adf00c3..1d1acc66f 100644 --- a/apps/desktop/src/i18n/messages/zh-CN.json +++ b/apps/desktop/src/i18n/messages/zh-CN.json @@ -227,8 +227,12 @@ "error.contractAction": "请确保 Desktop 与三个 WebCodex 程序来自同一源码修订。", "error.topologyTitle": "当前运行拓扑不支持此操作", "error.topologyAction": "请将此电脑设置为主节点,或在远程 Server 上管理外部连接。", + "error.stateUnavailableTitle": "Desktop 无法访问本地状态", + "error.stateUnavailableAction": "请检查本地配置,并确认当前账户可以读写 Desktop 数据目录。", + "error.localRunnerRequiredTitle": "需要本机 Runner", + "error.localRunnerRequiredAction": "请先在这台电脑上配置 Runner,再使用此功能。", "error.operationBusyTitle": "另一个 Desktop 操作仍在进行", - "error.operationBusyAction": "请等待当前操作结束,或先停止当前操作。", + "error.operationBusyAction": "请等待当前操作结束。如果操作旁显示“停止当前操作”,也可以点击它来停止。", "error.operationStaleTitle": "当前操作已经变化", "error.operationStaleAction": "请刷新状态后,再停止你当前看到的操作。", "error.operationCancelledTitle": "Desktop 操作已停止", diff --git a/apps/desktop/src/i18n/messages/zh-TW.json b/apps/desktop/src/i18n/messages/zh-TW.json index bb63e34d1..ca002d20b 100644 --- a/apps/desktop/src/i18n/messages/zh-TW.json +++ b/apps/desktop/src/i18n/messages/zh-TW.json @@ -227,8 +227,12 @@ "error.contractAction": "請確保 Desktop 與三個 WebCodex 程式來自同一原始碼修訂。", "error.topologyTitle": "當前執行拓撲不支援此操作", "error.topologyAction": "請將此電腦設定為主節點,或在遠端 Server 上管理外部連線。", + "error.stateUnavailableTitle": "Desktop 無法存取本機狀態", + "error.stateUnavailableAction": "請檢查本機設定,並確認目前的帳號可以讀寫 Desktop 資料目錄。", + "error.localRunnerRequiredTitle": "需要本機 Runner", + "error.localRunnerRequiredAction": "請先在這台電腦上設定 Runner,再使用此功能。", "error.operationBusyTitle": "另一個 Desktop 操作仍在進行", - "error.operationBusyAction": "請等待當前操作結束,或先停止當前操作。", + "error.operationBusyAction": "請等候目前的操作完成。如果操作旁顯示停止按鈕,也可以按下按鈕停止操作。", "error.operationStaleTitle": "當前操作已經變化", "error.operationStaleAction": "請重新整理狀態後,再停止你當前看到的操作。", "error.operationCancelledTitle": "Desktop 操作已停止", diff --git a/apps/desktop/src/i18n/presentation.test.ts b/apps/desktop/src/i18n/presentation.test.ts index 9e010af19..b5b3cf458 100644 --- a/apps/desktop/src/i18n/presentation.test.ts +++ b/apps/desktop/src/i18n/presentation.test.ts @@ -264,6 +264,9 @@ describe("Unified Desktop error normalization, classification, and reconciliatio expect(reconciled.component_errors?.server).toEqual(serverUnreachable); expect(reconciled.runtime_error).toEqual(serverUnreachable); + const unavailable = { code: "desktop_state_unavailable", message: "Could not save", next_action: "Check permissions" }; + expect(isErrorStaleForState(unavailable, { ...stateRunnerRecovered, current_operation: null })).toBe(false); + // Port conflicts are not safe to retry, but a new Server=Ready // observation proves the old error is no longer current. const resolvedPortConflict = { diff --git a/apps/desktop/src/lib/desktop-errors.ts b/apps/desktop/src/lib/desktop-errors.ts index 4666fa635..212fe3226 100644 --- a/apps/desktop/src/lib/desktop-errors.ts +++ b/apps/desktop/src/lib/desktop-errors.ts @@ -767,7 +767,17 @@ function classifyRule(error: DesktopError, diag: { retryAllowed: true, }; } - if (code === "runner_enrollment_required" || code === "local_runner_required" || code === "not_configured" || code === "setup_not_found" || code === "cloudflare_environment_required") { + if (code === "local_runner_required") { + return { + titleKey: "error.localRunnerRequiredTitle", + actionKey: "error.localRunnerRequiredAction", + component: "runner", + recoveryKind: "user_action", + safeAction: "open_setup", + retryAllowed: false, + }; + } + if (code === "runner_enrollment_required" || code === "not_configured" || code === "setup_not_found" || code === "cloudflare_environment_required") { return { titleKey: "error.runtimeTitle", actionKey: "error.runtimeAction", @@ -978,8 +988,18 @@ function classifyRule(error: DesktopError, diag: { }; } + if (code === "desktop_state_unavailable") { + return { + titleKey: "error.stateUnavailableTitle", + actionKey: "error.stateUnavailableAction", + component: "desktop", + recoveryKind: "manual_check", + safeAction: "open_diagnostics", + retryAllowed: false, + }; + } // Contention / stale operation / cancellation - if (code === "desktop_operation_busy" || code === "desktop_state_unavailable" || code === "desktop_operation_not_cancellable") { + if (code === "desktop_operation_busy" || code === "desktop_operation_not_cancellable") { return { titleKey: "error.operationBusyTitle", actionKey: "error.operationBusyAction", @@ -1268,7 +1288,6 @@ export function isTransientErrorResolvedByState(error: DesktopError, state: Desk case "runtime_not_ready": return state.readiness.runtime_ready; case "desktop_operation_busy": - case "desktop_state_unavailable": return !state.current_operation; default: return false; diff --git a/apps/desktop/src/lib/desktop-observation.ts b/apps/desktop/src/lib/desktop-observation.ts index a6077dc51..241b7fd4b 100644 --- a/apps/desktop/src/lib/desktop-observation.ts +++ b/apps/desktop/src/lib/desktop-observation.ts @@ -19,6 +19,17 @@ 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 { + try { + return await desktopApi.refresh(); + } catch (value) { + if (normalizeDesktopError(value).code !== "desktop_operation_busy") throw value; + return desktopApi.getState().catch(() => null); + } +} + function retryDelay(signal: AbortSignal): Promise { signal.throwIfAborted(); return new Promise((resolve, reject) => { @@ -69,9 +80,7 @@ export async function readDesktopObservation( } catch (value) { signal.throwIfAborted(); const error = normalizeDesktopError(value); - // runnerSettings currently uses desktop_state_unavailable while its core - // is borrowed. Real failures retain their original error after this bound. - if ((error.code !== "desktop_operation_busy" && error.code !== "desktop_state_unavailable") + if (error.code !== "desktop_operation_busy" || retries >= 5 || performance.now() >= deadline) throw value; await checkRetry(error); await retryDelay(signal); From 0b067ad5c60877a54a74b70324a88422cfecb1b1 Mon Sep 17 00:00:00 2001 From: yyjeqhc <1772413353@qq.com> Date: Sat, 28 Nov 2026 18:05:23 +0800 Subject: [PATCH 2/3] fix(desktop): release interrupted admissions and bound settings contention --- apps/desktop/src-tauri/Cargo.toml | 1 + apps/desktop/src-tauri/src/error.rs | 4 + apps/desktop/src-tauri/src/models.rs | 1 + apps/desktop/src-tauri/src/operation.rs | 290 +++++++++++++++--- apps/desktop/src-tauri/src/state.rs | 4 + apps/desktop/src-tauri/src/state/app_state.rs | 109 +++++-- .../src-tauri/src/state/desktop_core.rs | 6 +- .../src-tauri/src/state/diagnostics.rs | 12 +- .../src-tauri/src/state/environment.rs | 2 +- .../src/state/environment_invitation.rs | 9 +- .../src/state/operation_lifecycle_tests.rs | 248 +++++++++++++++ .../src-tauri/src/state/path_inventory.rs | 8 +- .../src-tauri/src/state/projectless_tests.rs | 3 +- .../src-tauri/src/state/runtime_shell.rs | 2 +- apps/desktop/src-tauri/src/state/updates.rs | 16 +- .../src-tauri/src/state/workspace_settings.rs | 52 +++- apps/desktop/src/App.test.tsx | 28 ++ apps/desktop/src/App.tsx | 16 +- .../settings/ConfigurationDataPanel.tsx | 2 +- apps/desktop/src/hooks/useDesktopWorkspace.ts | 12 +- apps/desktop/src/i18n/messages/de-DE.json | 6 + apps/desktop/src/i18n/messages/en-US.json | 6 + apps/desktop/src/i18n/messages/fr-FR.json | 6 + apps/desktop/src/i18n/messages/ja-JP.json | 6 + apps/desktop/src/i18n/messages/ko-KR.json | 6 + apps/desktop/src/i18n/messages/zh-CN.json | 6 + apps/desktop/src/i18n/messages/zh-TW.json | 6 + apps/desktop/src/lib/desktop-errors.ts | 21 ++ apps/desktop/src/lib/desktop-observation.ts | 3 +- apps/desktop/src/models/topology.ts | 2 +- .../desktop-completion-ownership.md | 28 +- 31 files changed, 783 insertions(+), 138 deletions(-) create mode 100644 apps/desktop/src-tauri/src/state/operation_lifecycle_tests.rs 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 a849ad1d7..102dbabba 100644 --- a/apps/desktop/src-tauri/src/error.rs +++ b/apps/desktop/src-tauri/src/error.rs @@ -298,6 +298,10 @@ 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" 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 cdf1e136b..395055c76 100644 --- a/apps/desktop/src-tauri/src/operation.rs +++ b/apps/desktop/src-tauri/src/operation.rs @@ -3,39 +3,45 @@ 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::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,37 +75,108 @@ pub(crate) fn cancelled_error() -> DesktopError { ) } -pub(crate) fn busy_error(current: Option<&DesktopOperationSnapshot>) -> DesktopError { - let error = DesktopError::new( - "desktop_operation_busy", - "Another Desktop operation is still running", - "Wait for the current operation to finish or stop it if it is cancellable.", - ); - match current { - Some(current) => 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), - None => error, - } +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, } @@ -108,7 +188,7 @@ impl OperationController { pub(crate) fn new(activity: ActivityLog) -> Self { Self { - active: Mutex::new(None), + active: Mutex::new(OperationSlot::Idle), next_id: AtomicU64::new(0), activity, } @@ -118,13 +198,15 @@ impl OperationController { &self, kind: DesktopOperationKind, cancellable: bool, - ) -> DesktopResult { + ) -> DesktopResult> { let mut active = self .active .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - if let Some(current) = active.as_ref() { - return Err(busy_error(Some(¤t.snapshot))); + match &*active { + OperationSlot::Active(current) => return Err(busy_error(¤t.snapshot())), + OperationSlot::Interrupted(error) => return Err(error.clone()), + OperationSlot::Idle => {} } let sequence = self.next_id.fetch_add(1, Ordering::Relaxed) + 1; @@ -143,11 +225,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, @@ -155,11 +242,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 { @@ -167,7 +267,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 { @@ -185,6 +285,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, @@ -196,7 +299,7 @@ impl OperationController { ), ); } - Ok(current.snapshot.clone()) + Ok(current.snapshot()) } pub(crate) fn cancel_active_for_shutdown(&self) { @@ -204,11 +307,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", @@ -222,12 +328,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 { @@ -257,7 +363,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 { @@ -303,6 +440,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()); @@ -311,12 +500,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()); @@ -336,7 +526,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 62d9c908d..0dad68e51 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,8 +157,8 @@ impl AppState { if self.shutdown_signal.is_cancelled() { return Err(cancelled_error()); } - if let Some(current) = self.operations.current() { - return Err(crate::operation::busy_error(Some(¤t))); + 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( @@ -163,8 +173,8 @@ impl AppState { if self.shutdown_signal.is_cancelled() { return Err(cancelled_error()); } - if let Some(current) = self.operations.current() { - return Err(crate::operation::busy_error(Some(¤t))); + 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. @@ -195,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 } @@ -685,7 +691,7 @@ impl AppState { kind: DesktopOperationKind, cancellable: bool, ) -> DesktopResult<( - OperationAdmission, + OperationAdmission<'_>, CancellationContext, DesktopCore, ProcessBaseline, @@ -702,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, @@ -745,8 +762,23 @@ impl AppState { } let completion = operation_completion::OperationCompletion::new(operation.kind, result.as_ref().err()); + let recovery_error = || { + crate::operation::core_unavailable().with_operation_context( + Some(&operation.id), + None, + None, + None, + ) + }; let cleanup = if completion.requires_process_cleanup() { - Some(self.cleanup_new_owned_processes(&baseline).await) + let mut supervisor = + tokio::time::timeout(OPERATION_SLOT_TIMEOUT, self.supervisor.lock()) + .await + .map_err(|_| recovery_error())?; + Some( + self.cleanup_new_owned_processes(&mut supervisor, &baseline) + .await, + ) } else { None }; @@ -757,10 +789,12 @@ impl AppState { core.publish_snapshot(); } { - let mut slot = self.core.lock().await; + let mut slot = tokio::time::timeout(OPERATION_SLOT_TIMEOUT, self.core.lock()) + .await + .map_err(|_| recovery_error())?; *slot = Some(core); } - self.operations.finish(&operation.id, &result); + operation.finish(&result); match result { Ok(_) => Ok(self.get_state()), Err(error) => Err(error), @@ -789,8 +823,11 @@ impl AppState { } } - async fn cleanup_new_owned_processes(&self, baseline: &ProcessBaseline) -> ProcessCleanup { - let mut supervisor = self.supervisor.lock().await; + async fn cleanup_new_owned_processes( + &self, + supervisor: &mut ProcessSupervisor, + baseline: &ProcessBaseline, + ) -> ProcessCleanup { let mut cleanup = ProcessCleanup::default(); let mut keys = supervisor.keys(); keys.sort_by_key(|key| match key { @@ -885,6 +922,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/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 b3e08c757..53160cdc0 100644 --- a/apps/desktop/src-tauri/src/state/diagnostics.rs +++ b/apps/desktop/src-tauri/src/state/diagnostics.rs @@ -27,7 +27,7 @@ impl AppState { let slot = self.core.lock().await; let core = slot .as_ref() - .ok_or_else(|| crate::operation::busy_error(self.operations.current().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; @@ -139,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 { @@ -281,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 = @@ -346,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/operation_lifecycle_tests.rs b/apps/desktop/src-tauri/src/state/operation_lifecycle_tests.rs new file mode 100644 index 000000000..e58f05b3c --- /dev/null +++ b/apps/desktop/src-tauri/src/state/operation_lifecycle_tests.rs @@ -0,0 +1,248 @@ +use super::*; + +#[tokio::test] +async fn stalled_runner_settings_read_leaves_core_available_and_discards_stale_results() { + let dir = tempfile::tempdir().unwrap(); + let state = AppState::new(dir.path().into(), dir.path().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(dir.path().join("runner.toml")), + user_token_file: None, + runner_client_id: Some("fixture".into()), + project_id: None, + runtime_project_id: None, + }); + } + 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(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 blocked_core_return_fences_a_completed_write_without_replaying_it() { + let dir = tempfile::tempdir().unwrap(); + let state = AppState::new(dir.path().into(), dir.path().join("resources")).unwrap(); + let (operation, cancellation, core, baseline) = state + .begin_operation(DesktopOperationKind::TunnelProxyUpdate, false) + .await + .unwrap(); + let id = operation.id.clone(); + let result = Ok(core.snapshot.clone()); + let blocked = state.core.lock().await; + let error = state + .finish_operation(operation, cancellation, core, baseline, result) + .await + .unwrap_err(); + drop(blocked); + assert_eq!(error.code, "desktop_core_unavailable"); + assert_eq!( + error.diagnostic_ref().unwrap().operation_id.as_ref(), + Some(&id) + ); + assert!(state.get_state().current_operation.is_none()); + assert_eq!(state.refresh_runtime_status().await.unwrap_err(), error); + assert_eq!( + state + .update_tunnel_proxy(TunnelProxyMode::Direct, None) + .await + .unwrap_err(), + error + ); +} + +#[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/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 4ac02323f..b0027012c 100644 --- a/apps/desktop/src-tauri/src/state/workspace_settings.rs +++ b/apps/desktop/src-tauri/src/state/workspace_settings.rs @@ -26,23 +26,55 @@ impl AppState { pub async fn runner_settings( &self, ) -> DesktopResult { - let mut slot = self.core.lock().await; - let core = slot - .as_mut() - .ok_or_else(|| crate::operation::busy_error(self.operations.current().as_ref()))?; - let runtime = core.runner_settings_runtime()?; - 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 core = slot + .as_ref() + .ok_or_else(|| self.operations.missing_core_error())?; + ( + core.runner_settings_runtime()?, + core.config.persistent_environment.clone(), + self.operations.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 core = slot + .as_ref() + .ok_or_else(|| self.operations.missing_core_error())?; + if self.operations.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( diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index b709e8c64..3a46196c2 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -1322,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 && (