From 9b3a86744c201790750b5379f21618032368b372 Mon Sep 17 00:00:00 2001 From: jackie_cqz <88996311+jackie-cqz@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:29:54 +0800 Subject: [PATCH 1/3] fix(desktop): recover invalid connection context --- desktop/src-tauri/src/connections/session.rs | 10 +- .../src-tauri/tests/deployment_identity.rs | 14 +- desktop/ui/src/app/App.tsx | 29 +- desktop/ui/src/app/Overview.tsx | 77 +++-- desktop/ui/src/generated/ipc.ts | 2 +- desktop/ui/tests/app.test.tsx | 271 ++++++++++++++++-- 6 files changed, 348 insertions(+), 55 deletions(-) diff --git a/desktop/src-tauri/src/connections/session.rs b/desktop/src-tauri/src/connections/session.rs index 34b2f645cc..38a0e9a22b 100644 --- a/desktop/src-tauri/src/connections/session.rs +++ b/desktop/src-tauri/src/connections/session.rs @@ -121,6 +121,9 @@ pub struct DesktopState { pub profiles: Vec, pub reports: Vec, pub active: Option, + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub retry_generation: Option, pub compatibility_profiles: Vec, pub pending_credential_cleanup: usize, pub last_write: Option, @@ -319,6 +322,10 @@ impl ConnectionManager { profiles: inner.profiles.views(), reports: inner.reports.values().cloned().collect(), active: inner.active.as_ref().map(|a| a.view.clone()), + retry_generation: inner + .interrupted + .as_ref() + .map(|active| active.view.generation), compatibility_profiles: self.compatibility.clone(), pending_credential_cleanup: inner.profiles.pending_cleanup(), last_write: inner.last_write.clone(), @@ -421,7 +428,8 @@ impl ConnectionManager { Ok(scope) => interrupted.view.scope = Some(scope), Err(error) => { if !Self::retryable_interruption(error.code) { - inner.interrupted = None; + // Publish a new generation when the retry handle is retired. + self.invalidate(&mut inner)?; } return Err(error); } diff --git a/desktop/src-tauri/tests/deployment_identity.rs b/desktop/src-tauri/tests/deployment_identity.rs index 1150ef0260..8767b37421 100644 --- a/desktop/src-tauri/tests/deployment_identity.rs +++ b/desktop/src-tauri/tests/deployment_identity.rs @@ -703,11 +703,20 @@ async fn retry_reopens_the_original_scope_after_an_outage() { let failed = fixture.manager.search_memory(generation, "query").await; assert_eq!(failed.err().unwrap().code, SafeError::Server); fixture.assert_disconnected(generation); + assert_eq!( + fixture.manager.state().unwrap().retry_generation, + Some(generation) + ); let still_down = fixture.manager.retry_connection(generation).await; assert_eq!(still_down.err().unwrap().code, SafeError::Server); + assert_eq!( + fixture.manager.state().unwrap().retry_generation, + Some(generation) + ); fixture.state.lock().unwrap().identity_response = None; let restored = fixture.manager.retry_connection(generation).await.unwrap(); + assert_eq!(restored.retry_generation, None); let active = restored.active.unwrap(); assert_eq!(active.connection_id, fixture.id); assert_eq!(active.scope.unwrap().scope_id, "scope-b"); @@ -730,9 +739,12 @@ async fn retry_never_reopens_a_scope_on_a_replacement_service() { fixture.state.lock().unwrap().identity_response = None; fixture.replace(); + let interrupted = fixture.manager.state().unwrap(); + assert_eq!(interrupted.retry_generation, Some(generation)); let retry = fixture.manager.retry_connection(generation).await; assert_eq!(retry.err().unwrap().code, SafeError::StaleContext); - fixture.assert_disconnected(generation); + fixture.assert_disconnected(interrupted.generation); + assert_eq!(fixture.manager.state().unwrap().retry_generation, None); } #[tokio::test] diff --git a/desktop/ui/src/app/App.tsx b/desktop/ui/src/app/App.tsx index 15fd57a407..ceb3d205ab 100644 --- a/desktop/ui/src/app/App.tsx +++ b/desktop/ui/src/app/App.tsx @@ -223,11 +223,8 @@ export function App() { } const receiveState = useCallback( (next: DesktopState) => { - if ( - currentState.current && - next.generation < currentState.current.generation - ) - return false; + const previous = currentState.current; + if (previous && next.generation < previous.generation) return false; currentState.current = next; setDesktop(next); if (!previewMode && next.active?.scope) { @@ -239,6 +236,16 @@ export function App() { "active-scope-id", next.active.scope.scope_id, ); + } else if ( + !previewMode && + !next.active && + (previous?.active?.scope || + previous?.retryGeneration !== undefined || + next.retryGeneration !== undefined) + ) { + // Only native retry can verify the original identity after interruption. + globalThis.localStorage?.removeItem("active-connection-id"); + globalThis.localStorage?.removeItem("active-scope-id"); } if (previewMode && next.active?.connectionId.startsWith("preview-")) { setPreviewConnected(true); @@ -286,7 +293,12 @@ export function App() { } } async function restoreSavedContext(next: DesktopState) { - if (next.active?.scope || next.profiles.length === 0) return next; + if ( + next.active?.scope || + next.retryGeneration !== undefined || + next.profiles.length === 0 + ) + return next; const storedConnectionId = globalThis.localStorage?.getItem( "active-connection-id", ); @@ -614,7 +626,10 @@ export function App() { setNativeError(null); void desktopApi .selectScope(desktop.active.generation, scope.scope_id) - .then(receiveState, setNativeError) + .then(receiveState, async (error: unknown) => { + setNativeError(error); + await refreshConnectionState(receiveState); + }) .finally(() => connectionPending(false)); }} onCreateScope={(trigger) => { diff --git a/desktop/ui/src/app/Overview.tsx b/desktop/ui/src/app/Overview.tsx index 21be46213b..b13af8f50b 100644 --- a/desktop/ui/src/app/Overview.tsx +++ b/desktop/ui/src/app/Overview.tsx @@ -20,7 +20,7 @@ import { FieldError, FieldLabel, } from "@/components/ui/field"; -import { useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { isTauri } from "@tauri-apps/api/core"; import type { Authentication, @@ -630,6 +630,7 @@ const copy = { active: "使用中", inactive: "已停用", loading: "正在读取当前空间的统计…", + interrupted: "连接已中断。请重试以返回原空间。", initial: "读取统计后,可查看当前空间的使用价值和活跃情况。", unavailable: "当前服务暂不支持空间统计。Agent 接入和记忆功能仍可按实际能力使用。", @@ -695,6 +696,8 @@ const copy = { active: "Active", inactive: "Inactive", loading: "Loading statistics for this Scope…", + interrupted: + "The connection was interrupted. Retry to return to your space.", initial: "Load statistics to see value and activity for this Scope.", unavailable: "This service does not currently support Space statistics. Agent connection and memory features remain available according to actual capabilities.", @@ -704,7 +707,8 @@ const copy = { export function Overview(props: Props) { if (!props.state) return null; - if (!props.state.active?.scope) return ; + if (!props.state.active?.scope && props.state.retryGeneration === undefined) + return ; return ; } @@ -1195,6 +1199,8 @@ function UsageDashboard({ state, language, contextPending, onState }: Props) { const active = state?.active; const report = activeCheckReport(state); const generation = active?.generation; + const interrupted = state?.retryGeneration !== undefined; + const retryGeneration = state?.retryGeneration ?? generation; const preview = import.meta.env.DEV && active?.connectionId.startsWith("preview-"); const enabled = @@ -1213,6 +1219,20 @@ function UsageDashboard({ state, language, contextPending, onState }: Props) { "authorized" | "bindingChanged" | "captureSaved" | "deleted" | null >(null); const request = useRef(0); + const handleReadFailure = useCallback( + async (ticket: number, failure: unknown) => { + if (ticket !== request.current) return; + setData(null); + setError(failure); + if (!onState) return; + await refreshConnectionState((next) => { + if (ticket !== request.current) return; + setBusy(false); + onState(next); + }); + }, + [onState], + ); const currentBinding = preview ? active?.scope?.scope_id === previewDataScopeId ? { @@ -1237,9 +1257,7 @@ function UsageDashboard({ state, language, contextPending, onState }: Props) { .then((next) => { if (ticket === request.current) setData(next); }) - .catch((failure) => { - if (ticket === request.current) setError(failure); - }) + .catch((failure: unknown) => handleReadFailure(ticket, failure)) .finally(() => { if (ticket === request.current) setBusy(false); }); @@ -1247,19 +1265,25 @@ function UsageDashboard({ state, language, contextPending, onState }: Props) { request.current++; void desktopApi.cancelStats(generation).catch(() => {}); }; - }, [enabled, generation, period, preview, reload]); + }, [enabled, generation, handleReadFailure, period, preview, reload]); async function retryRead() { - if (!enabled || generation === undefined || busy) return; + if ( + contextPending || + (!enabled && !interrupted) || + retryGeneration === undefined || + busy + ) + return; const ticket = ++request.current; setBusy(true); try { - const next = await desktopApi.retryConnection(generation); - if (onState?.(next) === false || ticket !== request.current) return; - if (next.active?.generation === generation) + const next = await desktopApi.retryConnection(retryGeneration); + if (ticket !== request.current || onState?.(next) === false) return; + if (next.active?.generation === retryGeneration) setReload((value) => value + 1); } catch (failure) { - if (ticket === request.current) setError(failure); + await handleReadFailure(ticket, failure); } finally { if (ticket === request.current) setBusy(false); } @@ -1282,6 +1306,26 @@ function UsageDashboard({ state, language, contextPending, onState }: Props) { summary.inactiveMemory === 0, ); + const retryAction = ( + + ); + + if (interrupted) + return ( + + ); + return (
@@ -1348,16 +1392,7 @@ function UsageDashboard({ state, language, contextPending, onState }: Props) { className="rounded-none border-x-0 py-12" kind="error" title={connectionError(error, language)} - action={ - - } + action={retryAction} /> ) : summary ? ( <> diff --git a/desktop/ui/src/generated/ipc.ts b/desktop/ui/src/generated/ipc.ts index b4045cf384..aa638ad9da 100644 --- a/desktop/ui/src/generated/ipc.ts +++ b/desktop/ui/src/generated/ipc.ts @@ -92,7 +92,7 @@ export type MemoryContext = { connectionId: string, endpoint: string, serverId: export type WriteStatus = "pending" | "succeeded" | "failed" | "unknown"; export type WriteRecord = { operationId: string, context: MemoryContext, status: WriteStatus, references: Array, error: ApiFailure | null, }; export type WriteOutcome = { record: WriteRecord, result: MemorySaveResponse | null, }; -export type DesktopState = { generation: number, profiles: Array, reports: Array, active: ActiveView | null, compatibilityProfiles: Array, pendingCredentialCleanup: number, lastWrite: WriteRecord | null, }; +export type DesktopState = { generation: number, profiles: Array, reports: Array, active: ActiveView | null, retryGeneration?: number, compatibilityProfiles: Array, pendingCredentialCleanup: number, lastWrite: WriteRecord | null, }; export type ApiFailure = { code: SafeError, requestId: string | null, /** * Conservatively true once handed to the HTTP client, even if delivery is uncertain. diff --git a/desktop/ui/tests/app.test.tsx b/desktop/ui/tests/app.test.tsx index 5bd85c8123..8cb8216f09 100644 --- a/desktop/ui/tests/app.test.tsx +++ b/desktop/ui/tests/app.test.tsx @@ -49,6 +49,7 @@ vi.mock("../src/shared/ipc", () => ({ save: vi.fn(), retryConnection: vi.fn(), defaultScope: vi.fn(), + scopes: vi.fn(), selectScope: vi.fn(), stats: vi.fn(), cancelStats: vi.fn(async () => undefined), @@ -522,25 +523,16 @@ test("closing the existing-service dialog restores focus without scrolling the p focus.mockRestore(); }); -test("Retry read restores Home in the same space after a service outage", async () => { - globalThis.localStorage.setItem("desktop-language", "en"); - const connected = connectedMemoryState(); - const active = connected.active!; - active.report.supportedOperations.push("get_stats"); - const restored = { - ...connected, - generation: 3, - active: { ...active, generation: 3 }, - }; +function homeStatistics(scopeId: string): ExactScopeStatistics { const period = { preset: "30d", start_date: "2026-11-01", end_date: "2026-11-30", timezone: "UTC", } as const; - const scopeIds = [active.scope!.scope_id]; + const scopeIds = [scopeId]; const modelUsage = { requests: 0, input_tokens: 0, output_tokens: 0 }; - const statistics: ExactScopeStatistics = { + return { selection: { mode: "exact", scope_ids: scopeIds }, scope_ids: scopeIds, as_of: "2026-11-30T00:00:00Z", @@ -577,23 +569,254 @@ test("Retry read restores Home in the same space after a service outage", async }, by_scope: [], }; - vi.mocked(desktopApi.state).mockResolvedValueOnce(connected); - vi.mocked(desktopApi.retryConnection).mockResolvedValueOnce(restored); - vi.mocked(desktopApi.stats) - .mockRejectedValueOnce({ code: "server" }) - .mockImplementationOnce(async (generation) => { - if (generation !== restored.generation) throw { code: "not_connected" }; - return statistics; +} + +async function selectOtherSpace( + user: ReturnType, + connected: DesktopState, +) { + vi.mocked(desktopApi.scopes).mockResolvedValue({ + items: [ + connected.active!.scope!, + { + ...connected.active!.scope!, + scope_id: "other-space", + title: "Other space", + }, + ], + }); + await user.click( + await screen.findByRole("button", { + name: "Current memory space: Original space", + }), + ); + await user.click( + await screen.findByRole("menuitemradio", { name: /Other space/ }), + ); +} + +test.each(["statistics read", "Retry read", "space switch"] as const)( + "clears the replaced Server's context after a failed %s", + async (action) => { + globalThis.localStorage.setItem("desktop-language", "en"); + const connected = connectedMemoryState(); + const active = connected.active!; + active.report.supportedOperations.push("get_stats", "list_scopes"); + const disconnected = { + ...connected, + generation: action === "Retry read" ? 3 : 2, + active: null, + reports: [], + }; + const stale = { + code: "stale_context", + requestId: null, + dispatched: false, + }; + let nativeState: DesktopState = connected; + async function rejectReplacedConnection(): Promise { + nativeState = disconnected; + throw stale; + } + vi.mocked(desktopApi.state).mockImplementation(async () => nativeState); + if (action === "statistics read") { + vi.mocked(desktopApi.stats).mockImplementationOnce( + rejectReplacedConnection, + ); + } else if (action === "Retry read") { + vi.mocked(desktopApi.stats).mockImplementationOnce(async () => { + nativeState = { + ...disconnected, + generation: 2, + retryGeneration: active.generation, + }; + throw { code: "server" }; + }); + vi.mocked(desktopApi.retryConnection).mockImplementationOnce( + rejectReplacedConnection, + ); + } else { + vi.mocked(desktopApi.stats).mockImplementation(async () => { + if (!nativeState.active) throw stale; + return homeStatistics(active.scope!.scope_id); + }); + vi.mocked(desktopApi.selectScope).mockImplementationOnce( + rejectReplacedConnection, + ); + } + + const user = userEvent.setup(); + render(); + if (action === "Retry read") { + await user.click( + await screen.findByRole("button", { name: "Retry read" }), + ); + } else if (action === "space switch") { + expect(await screen.findByText("12")).toBeTruthy(); + await selectOtherSpace(user, connected); + } + + await screen.findByRole("heading", { + name: "Do you already have a service?", }); + expect( + screen.queryByRole("button", { + name: "Current memory space: Original space", + }), + ).toBeNull(); + expect(screen.queryByText("12")).toBeNull(); + expect(screen.queryByRole("button", { name: "Retry read" })).toBeNull(); + expect(globalThis.localStorage.getItem("active-connection-id")).toBeNull(); + expect(globalThis.localStorage.getItem("active-scope-id")).toBeNull(); - render(); - await userEvent.click( - await screen.findByRole("button", { name: "Retry read" }), + await user.click(screen.getByRole("button", { name: "Services & Agents" })); + await user.click( + await screen.findByRole("button", { name: "More actions" }), + ); + expect( + screen.getByRole("menuitem", { name: "Use this connection" }), + ).toBeTruthy(); + expect(desktopApi.check).not.toHaveBeenCalled(); + }, +); + +test("keeps the current space and its statistics when the target space denies access", async () => { + globalThis.localStorage.setItem("desktop-language", "en"); + const connected = connectedMemoryState(); + const active = connected.active!; + active.report.supportedOperations.push("get_stats", "list_scopes"); + vi.mocked(desktopApi.state).mockResolvedValue(connected); + vi.mocked(desktopApi.stats).mockResolvedValue( + homeStatistics(active.scope!.scope_id), ); + vi.mocked(desktopApi.selectScope).mockRejectedValueOnce({ + code: "forbidden", + requestId: null, + dispatched: true, + }); + const user = userEvent.setup(); + render(); expect(await screen.findByText("12")).toBeTruthy(); - expect(screen.getByText("Original space")).toBeTruthy(); - expect(screen.queryByRole("button", { name: "Retry read" })).toBeNull(); + await selectOtherSpace(user, connected); + + expect( + await screen.findByText("This identity cannot perform this operation."), + ).toBeTruthy(); + expect( + screen.getByRole("button", { + name: "Current memory space: Original space", + }), + ).toBeTruthy(); + expect(screen.getByText("12")).toBeTruthy(); + expect(desktopApi.selectScope).toHaveBeenCalledWith( + active.generation, + "other-space", + ); +}); + +test.each(["statistics read", "space switch"] as const)( + "Retry read restores the original space after a transient %s failure", + async (action) => { + globalThis.localStorage.setItem("desktop-language", "en"); + const connected = connectedMemoryState(); + const active = connected.active!; + active.report.supportedOperations.push("get_stats", "list_scopes"); + const restored = { + ...connected, + generation: 3, + active: { ...active, generation: 3 }, + }; + const interrupted = { + ...connected, + generation: 2, + active: null, + reports: [], + retryGeneration: active.generation, + }; + const unavailable = { code: "server", requestId: null, dispatched: false }; + let nativeState: DesktopState = connected; + vi.mocked(desktopApi.state).mockImplementation(async () => nativeState); + vi.mocked(desktopApi.retryConnection) + .mockRejectedValueOnce(unavailable) + .mockImplementationOnce(async () => { + nativeState = restored; + return restored; + }); + async function interruptConnection(): Promise { + nativeState = interrupted; + throw unavailable; + } + vi.mocked(desktopApi.stats).mockImplementation(async (generation) => { + if (generation !== nativeState.active?.generation) + throw { code: "not_connected" }; + return homeStatistics(active.scope!.scope_id); + }); + if (action === "statistics read") { + vi.mocked(desktopApi.stats).mockImplementationOnce(interruptConnection); + } else { + vi.mocked(desktopApi.selectScope).mockImplementationOnce( + interruptConnection, + ); + } + + const user = userEvent.setup(); + render(); + if (action === "space switch") { + expect(await screen.findByText("12")).toBeTruthy(); + await selectOtherSpace(user, connected); + } + await screen.findByText( + "The connection was interrupted. Retry to return to your space.", + ); + expect(screen.queryByText("12")).toBeNull(); + expect( + screen.queryByRole("button", { + name: "Current memory space: Original space", + }), + ).toBeNull(); + await user.click(await screen.findByRole("button", { name: "Retry read" })); + expect(desktopApi.retryConnection).toHaveBeenCalledWith(active.generation); + await user.click(await screen.findByRole("button", { name: "Retry read" })); + + expect(await screen.findByText("12")).toBeTruthy(); + expect(screen.getByText("Original space")).toBeTruthy(); + expect(screen.queryByRole("button", { name: "Retry read" })).toBeNull(); + expect(desktopApi.retryConnection).toHaveBeenLastCalledWith( + active.generation, + ); + expect(desktopApi.stats).toHaveBeenLastCalledWith( + restored.generation, + "30d", + ); + expect(desktopApi.check).not.toHaveBeenCalled(); + }, +); + +test("uses the native retry handle when Home starts during an outage", async () => { + globalThis.localStorage.setItem("desktop-language", "en"); + const connected = connectedMemoryState(); + const active = connected.active!; + globalThis.localStorage.setItem("active-connection-id", active.connectionId); + globalThis.localStorage.setItem("active-scope-id", active.scope!.scope_id); + vi.mocked(desktopApi.state).mockResolvedValue({ + ...connected, + active: null, + generation: 2, + reports: [], + retryGeneration: active.generation, + }); + vi.mocked(desktopApi.retryConnection).mockRejectedValueOnce({ + code: "server", + }); + + const user = userEvent.setup(); + render(); + await user.click(await screen.findByRole("button", { name: "Retry read" })); + + expect(desktopApi.retryConnection).toHaveBeenCalledWith(active.generation); + expect(desktopApi.check).not.toHaveBeenCalled(); + expect(screen.getByRole("button", { name: "Retry read" })).toBeTruthy(); }); test("restores a saved service directly into its default space", async () => { From 0f6666bf789145bbc6cd3c3d90f050d55568ff01 Mon Sep 17 00:00:00 2001 From: jackie_cqz <88996311+jackie-cqz@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:25:05 +0800 Subject: [PATCH 2/3] fix(desktop): reset busy after stats cancellation --- desktop/ui/src/app/Overview.tsx | 2 ++ desktop/ui/tests/app.test.tsx | 18 +++++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/desktop/ui/src/app/Overview.tsx b/desktop/ui/src/app/Overview.tsx index b13af8f50b..c6f941c8e5 100644 --- a/desktop/ui/src/app/Overview.tsx +++ b/desktop/ui/src/app/Overview.tsx @@ -1263,6 +1263,8 @@ function UsageDashboard({ state, language, contextPending, onState }: Props) { }); return () => { request.current++; + // The canceled read no longer owns the busy flag. + setBusy(false); void desktopApi.cancelStats(generation).catch(() => {}); }; }, [enabled, generation, handleReadFailure, period, preview, reload]); diff --git a/desktop/ui/tests/app.test.tsx b/desktop/ui/tests/app.test.tsx index 8cb8216f09..543304c4ca 100644 --- a/desktop/ui/tests/app.test.tsx +++ b/desktop/ui/tests/app.test.tsx @@ -715,7 +715,11 @@ test("keeps the current space and its statistics when the target space denies ac ); }); -test.each(["statistics read", "space switch"] as const)( +test.each([ + "statistics read", + "space switch", + "space switch with statistics pending", +] as const)( "Retry read restores the original space after a transient %s failure", async (action) => { globalThis.localStorage.setItem("desktop-language", "en"); @@ -760,10 +764,18 @@ test.each(["statistics read", "space switch"] as const)( ); } + if (action === "space switch with statistics pending") { + vi.mocked(desktopApi.stats).mockImplementationOnce( + () => new Promise(() => {}), + ); + } + const user = userEvent.setup(); render(); - if (action === "space switch") { - expect(await screen.findByText("12")).toBeTruthy(); + if (action !== "statistics read") { + await screen.findByText( + action === "space switch" ? "12" : "Loading statistics for this Scope…", + ); await selectOtherSpace(user, connected); } await screen.findByText( From 3b58fe0f2e6a166835d467f77f6d99c8118ebd32 Mon Sep 17 00:00:00 2001 From: jackie_cqz <88996311+jackie-cqz@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:06:25 +0800 Subject: [PATCH 3/3] fix(desktop): recover after scope access changes --- desktop/src-tauri/src/connections/session.rs | 12 ++- .../src-tauri/tests/deployment_identity.rs | 66 +++++++++++++ desktop/ui/src/app/App.tsx | 12 ++- desktop/ui/src/app/Overview.tsx | 21 +++- desktop/ui/src/app/TopBar.tsx | 13 ++- desktop/ui/tests/app.test.tsx | 98 ++++++++++++++++++- 6 files changed, 208 insertions(+), 14 deletions(-) diff --git a/desktop/src-tauri/src/connections/session.rs b/desktop/src-tauri/src/connections/session.rs index 38a0e9a22b..c4e5c49ed8 100644 --- a/desktop/src-tauri/src/connections/session.rs +++ b/desktop/src-tauri/src/connections/session.rs @@ -389,7 +389,7 @@ impl ConnectionManager { pub async fn check(&self, id: &str, activate: bool) -> Result { self.check_expected(id, activate, None, None).await } - /// Resume a temporarily interrupted selection after verifying its original identity and Scope. + /// Resume the verified service, retaining the original Scope if it is still available. pub async fn retry_connection(&self, generation: u32) -> Result { let _permit = self.probes.try_acquire().map_err(|_| SafeError::Busy)?; let (mut interrupted, expected, mut cancelled) = { @@ -415,7 +415,13 @@ impl ConnectionManager { let identity = NativeIdentity::from_report(report)?; let result = Self::cancellable(&mut cancelled, async { Self::verify_identity(&interrupted.api, &identity, report.server_id()).await?; - let scope = interrupted.api.scope(scope_id).await?; + let scope = match interrupted.api.scope(scope_id).await { + Ok(scope) => Some(scope), + Err(error) if matches!(error.code, SafeError::Forbidden | SafeError::NotFound) => { + None + } + Err(error) => return Err(error), + }; Self::verify_identity(&interrupted.api, &identity, report.server_id()).await?; Ok(scope) }) @@ -425,7 +431,7 @@ impl ConnectionManager { return Err(SafeError::StaleContext.into()); } match result { - Ok(scope) => interrupted.view.scope = Some(scope), + Ok(scope) => interrupted.view.scope = scope, Err(error) => { if !Self::retryable_interruption(error.code) { // Publish a new generation when the retry handle is retired. diff --git a/desktop/src-tauri/tests/deployment_identity.rs b/desktop/src-tauri/tests/deployment_identity.rs index 8767b37421..7136527048 100644 --- a/desktop/src-tauri/tests/deployment_identity.rs +++ b/desktop/src-tauri/tests/deployment_identity.rs @@ -42,6 +42,7 @@ struct State { readiness_status: u16, capabilities: (u16, Value), principal: Option, + scope_a_status: u16, pause: Option, requests: Vec, lose_write_response: bool, @@ -102,6 +103,7 @@ impl Fixture { readiness_status: 200, capabilities: (403, json!({})), principal: authenticated.then(|| "same-principal".into()), + scope_a_status: 200, pause: None, requests: vec![], lose_write_response: false, @@ -171,6 +173,9 @@ impl Fixture { "access_mode":if state.principal.is_some() {"enforced"} else {"disabled"}}}), ), "/v1/capabilities" => state.capabilities.clone(), + "/v1/scopes/scope-a" if state.scope_a_status != 200 => { + (state.scope_a_status, json!({})) + } "/v1/scopes/default" | "/v1/scopes/scope-a" => (200, scope()), "/v1/scopes/scope-b" => { let mut selected = scope(); @@ -729,6 +734,67 @@ async fn retry_reopens_the_original_scope_after_an_outage() { assert_eq!(result.hits[0].text, "private result"); } +#[tokio::test] +async fn retry_keeps_the_verified_service_when_the_original_scope_is_unavailable() { + for status in [403, 404] { + let fixture = Fixture::new(true).await; + let generation = fixture.select().await; + fixture.state.lock().unwrap().identity_response = Some((502, json!({}))); + let failed = fixture.manager.search_memory(generation, "query").await; + assert_eq!(failed.err().unwrap().code, SafeError::Server); + let interrupted = fixture.manager.state().unwrap(); + assert_eq!(interrupted.retry_generation, Some(generation)); + + { + let mut state = fixture.state.lock().unwrap(); + state.identity_response = None; + state.scope_a_status = status; + } + let restored = fixture.manager.retry_connection(generation).await.unwrap(); + assert!(restored.generation > interrupted.generation); + assert_eq!(restored.retry_generation, None); + let active = restored.active.unwrap(); + assert_eq!(active.connection_id, fixture.id); + assert!(active.report.compatibility_verified); + assert!(active.scope.is_none()); + let selected = fixture + .manager + .select_scope(restored.generation, "scope-b") + .await + .unwrap(); + assert_eq!(selected.active.unwrap().scope.unwrap().scope_id, "scope-b"); + } +} + +#[tokio::test] +async fn retry_rechecks_the_service_after_the_original_scope_denies_access() { + let fixture = Fixture::new(true).await; + let generation = fixture.select().await; + fixture.state.lock().unwrap().identity_response = Some((502, json!({}))); + let failed = fixture.manager.search_memory(generation, "query").await; + assert_eq!(failed.err().unwrap().code, SafeError::Server); + let interrupted = fixture.manager.state().unwrap(); + { + let mut state = fixture.state.lock().unwrap(); + state.identity_response = None; + state.scope_a_status = 403; + state.pause = Some("/v1/scopes/scope-a".into()); + } + + let manager = fixture.manager.clone(); + let retry = tokio::spawn(async move { manager.retry_connection(generation).await }); + fixture.entered().await; + fixture.replace(); + fixture.release.notify_one(); + let result = timeout(Duration::from_secs(5), retry) + .await + .unwrap() + .unwrap(); + assert_eq!(result.err().unwrap().code, SafeError::StaleContext); + fixture.assert_disconnected(interrupted.generation); + assert_eq!(fixture.manager.state().unwrap().retry_generation, None); +} + #[tokio::test] async fn retry_never_reopens_a_scope_on_a_replacement_service() { let fixture = Fixture::new(true).await; diff --git a/desktop/ui/src/app/App.tsx b/desktop/ui/src/app/App.tsx index ceb3d205ab..19b0241378 100644 --- a/desktop/ui/src/app/App.tsx +++ b/desktop/ui/src/app/App.tsx @@ -222,11 +222,20 @@ export function App() { setPendingConnections((current) => current + (pending ? 1 : -1)); } const receiveState = useCallback( - (next: DesktopState) => { + (next: DesktopState, readError?: unknown) => { const previous = currentState.current; if (previous && next.generation < previous.generation) return false; currentState.current = next; setDesktop(next); + if (next.active && previous?.retryGeneration !== undefined) { + setNativeError(null); + } else if ( + readError != null && + !next.active && + next.retryGeneration === undefined + ) { + setNativeError(readError); + } if (!previewMode && next.active?.scope) { globalThis.localStorage?.setItem( "active-connection-id", @@ -605,6 +614,7 @@ export function App() { contextPending={contextPending || quickConnectPending} preview={previewMode} hideContent={page === "connections" || page === "settings"} + onState={receiveState} onManageConnections={(profileId) => navigate("connections", { profileId }) } diff --git a/desktop/ui/src/app/Overview.tsx b/desktop/ui/src/app/Overview.tsx index c6f941c8e5..74801c9760 100644 --- a/desktop/ui/src/app/Overview.tsx +++ b/desktop/ui/src/app/Overview.tsx @@ -80,7 +80,7 @@ import localAgentIllustration from "../assets/local-agent-gradient-c.png"; type Props = { state: DesktopState | null; language: Language; - onState?: (state: DesktopState) => boolean | void; + onState?: (state: DesktopState, readError?: unknown) => boolean | void; onOpenLocalServer: () => void; onOpenExistingServer: () => void; contextPending: boolean; @@ -707,7 +707,22 @@ const copy = { export function Overview(props: Props) { if (!props.state) return null; - if (!props.state.active?.scope && props.state.retryGeneration === undefined) + if (props.state.active && !props.state.active.scope) { + const zh = props.language === "zh"; + return ( + +

+ {zh + ? "请使用顶部的空间选择器继续。" + : "Use the space picker above to continue."} +

+
+ ); + } + if (!props.state.active && props.state.retryGeneration === undefined) return ; return ; } @@ -1228,7 +1243,7 @@ function UsageDashboard({ state, language, contextPending, onState }: Props) { await refreshConnectionState((next) => { if (ticket !== request.current) return; setBusy(false); - onState(next); + onState(next, failure); }); }, [onState], diff --git a/desktop/ui/src/app/TopBar.tsx b/desktop/ui/src/app/TopBar.tsx index 647c639963..810cc36500 100644 --- a/desktop/ui/src/app/TopBar.tsx +++ b/desktop/ui/src/app/TopBar.tsx @@ -37,6 +37,7 @@ import { activeCheckReport, connectionCheckReport, connectionVerified, + refreshConnectionState, } from "./context"; import { messages, type Language } from "./messages"; import { previewScopes } from "./preview-data"; @@ -48,6 +49,7 @@ type Props = { contextPending?: boolean; preview?: boolean; onManageConnections: (profileId?: string) => void; + onState?: (state: DesktopState) => void; onSelectConnection?: (profileId: string) => void; onSelectScope?: (scope: ScopeDescriptor) => void; onCreateScope?: (trigger: HTMLElement) => void; @@ -64,6 +66,7 @@ export function TopBar({ contextPending = false, preview = false, onManageConnections, + onState, onSelectConnection, onSelectScope, onCreateScope, @@ -116,8 +119,8 @@ export function TopBar({ }[serviceStatus]; useEffect(() => { - if (hideContent) setOpen(null); - }, [hideContent]); + if (hideContent || !hasService) setOpen(null); + }, [hasService, hideContent]); useEffect(() => { const element = wrap.current; @@ -225,6 +228,7 @@ export function TopBar({ list={canListSpaces && open === "scope"} preview={preview} language={language} + onState={onState} onSelect={(scope) => onSelectScope?.(scope)} onCreate={() => { const trigger = scopeTrigger.current; @@ -327,6 +331,7 @@ function ScopeMenu({ list, preview, language, + onState, onSelect, onCreate, }: { @@ -335,6 +340,7 @@ function ScopeMenu({ list: boolean; preview: boolean; language: Language; + onState?: (state: DesktopState) => void; onSelect: (scope: ScopeDescriptor) => void; onCreate: () => void; }) { @@ -356,12 +362,13 @@ function ScopeMenu({ }, (reason: unknown) => { if (current) setError(reason); + if (onState) void refreshConnectionState(onState); }, ); return () => { current = false; }; - }, [cursor, generation, list, preview]); + }, [cursor, generation, list, onState, preview]); const scopes = preview ? previewScopes(language) : (page?.items ?? []); const choices = diff --git a/desktop/ui/tests/app.test.tsx b/desktop/ui/tests/app.test.tsx index 071529c0fa..5ec488d5f7 100644 --- a/desktop/ui/tests/app.test.tsx +++ b/desktop/ui/tests/app.test.tsx @@ -605,7 +605,12 @@ async function selectOtherSpace( ); } -test.each(["statistics read", "Retry read", "space switch"] as const)( +test.each([ + "statistics read", + "Retry read", + "space switch", + "space list", +] as const)( "clears the replaced Server's context after a failed %s", async (action) => { globalThis.localStorage.setItem("desktop-language", "en"); @@ -650,9 +655,15 @@ test.each(["statistics read", "Retry read", "space switch"] as const)( if (!nativeState.active) throw stale; return homeStatistics(active.scope!.scope_id); }); - vi.mocked(desktopApi.selectScope).mockImplementationOnce( - rejectReplacedConnection, - ); + if (action === "space list") { + vi.mocked(desktopApi.scopes).mockImplementationOnce( + rejectReplacedConnection, + ); + } else { + vi.mocked(desktopApi.selectScope).mockImplementationOnce( + rejectReplacedConnection, + ); + } } const user = userEvent.setup(); @@ -664,11 +675,25 @@ test.each(["statistics read", "Retry read", "space switch"] as const)( } else if (action === "space switch") { expect(await screen.findByText("12")).toBeTruthy(); await selectOtherSpace(user, connected); + } else if (action === "space list") { + expect(await screen.findByText("12")).toBeTruthy(); + await user.click( + screen.getByRole("button", { + name: "Current memory space: Original space", + }), + ); } await screen.findByRole("heading", { name: "Do you already have a service?", }); + if (action === "Retry read") { + expect( + screen.getByText( + "The connection or scope changed. Try the operation again.", + ), + ).toBeTruthy(); + } expect( screen.queryByRole("button", { name: "Current memory space: Original space", @@ -803,6 +828,9 @@ test.each([ expect(await screen.findByText("12")).toBeTruthy(); expect(screen.getByText("Original space")).toBeTruthy(); + expect( + screen.queryByText("The Server cannot complete this request right now."), + ).toBeNull(); expect(screen.queryByRole("button", { name: "Retry read" })).toBeNull(); expect(desktopApi.retryConnection).toHaveBeenLastCalledWith( active.generation, @@ -815,6 +843,68 @@ test.each([ }, ); +test("lets the user pick another space after retry restores only the verified service", async () => { + globalThis.localStorage.setItem("desktop-language", "en"); + const connected = connectedMemoryState(); + const active = connected.active!; + active.report.supportedOperations.push("get_stats", "list_scopes"); + const other = { + ...active.scope!, + scope_id: "other-space", + title: "Other space", + }; + const restored = { + ...connected, + generation: 3, + active: { ...active, generation: 3, scope: null }, + }; + vi.mocked(desktopApi.state).mockResolvedValue({ + ...connected, + generation: 2, + active: null, + reports: [], + retryGeneration: active.generation, + }); + vi.mocked(desktopApi.retryConnection).mockResolvedValue(restored); + vi.mocked(desktopApi.scopes).mockResolvedValue({ items: [other] }); + vi.mocked(desktopApi.selectScope).mockResolvedValue({ + ...connected, + generation: 4, + active: { ...active, generation: 4, scope: other }, + }); + vi.mocked(desktopApi.stats).mockResolvedValue(homeStatistics(other.scope_id)); + + const user = userEvent.setup(); + render(); + await user.click(await screen.findByRole("button", { name: "Retry read" })); + + expect( + await screen.findByRole("heading", { name: "Choose a memory space" }), + ).toBeTruthy(); + expect( + screen.getByRole("button", { name: /^Current service: Memory service/ }), + ).toBeTruthy(); + expect( + screen.queryByRole("button", { + name: "Current memory space: Original space", + }), + ).toBeNull(); + await user.click( + screen.getByRole("button", { name: "Select a memory space" }), + ); + await user.click( + await screen.findByRole("menuitemradio", { name: /Other space/ }), + ); + + expect( + await screen.findByRole("button", { + name: "Current memory space: Other space", + }), + ).toBeTruthy(); + expect(desktopApi.selectScope).toHaveBeenCalledWith(3, other.scope_id); + expect(desktopApi.check).not.toHaveBeenCalled(); +}); + test("uses the native retry handle when Home starts during an outage", async () => { globalThis.localStorage.setItem("desktop-language", "en"); const connected = connectedMemoryState();