Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions desktop/src-tauri/src/connections/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ pub struct DesktopState {
pub profiles: Vec<ProfileView>,
pub reports: Vec<CheckReport>,
pub active: Option<ActiveView>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub retry_generation: Option<u32>,
pub compatibility_profiles: Vec<CompatibilityProfile>,
pub pending_credential_cleanup: usize,
pub last_write: Option<WriteRecord>,
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -382,7 +389,7 @@ impl ConnectionManager {
pub async fn check(&self, id: &str, activate: bool) -> Result<DesktopState, ApiFailure> {
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<DesktopState, ApiFailure> {
let _permit = self.probes.try_acquire().map_err(|_| SafeError::Busy)?;
let (mut interrupted, expected, mut cancelled) = {
Expand All @@ -408,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)
})
Expand All @@ -418,10 +431,11 @@ 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) {
inner.interrupted = None;
// Publish a new generation when the retry handle is retired.
self.invalidate(&mut inner)?;
}
return Err(error);
}
Comment on lines 435 to 441

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep the verified service active when the original Scope is revoked on retry (blocking)

Follow-up on #2963 (comment): after verify_identity confirms the deployment and principal are unchanged (line 417), if interrupted.api.scope(scope_id) returns Forbidden or NotFound, this branch calls self.invalidate(&mut inner)? and leaves active = None, dropping the verified service instead of allowing the user to pick another authorized Scope (inconsistent with check_expected at session.rs:785-797).

Required outcome: when identity verification succeeds but the original Scope returns Forbidden/NotFound, retire interrupted and restore active with scope: None (advancing generation) so the user can choose another authorized Scope on the verified service.

Expand Down
80 changes: 79 additions & 1 deletion desktop/src-tauri/tests/deployment_identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ struct State {
readiness_status: u16,
capabilities: (u16, Value),
principal: Option<String>,
scope_a_status: u16,
pause: Option<String>,
requests: Vec<String>,
lose_write_response: bool,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -703,11 +708,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");
Expand All @@ -720,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;
Expand All @@ -730,9 +805,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]
Expand Down
41 changes: 33 additions & 8 deletions desktop/ui/src/app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -222,14 +222,20 @@ export function App() {
setPendingConnections((current) => current + (pending ? 1 : -1));
}
const receiveState = useCallback(
(next: DesktopState) => {
if (
currentState.current &&
next.generation < currentState.current.generation
)
return false;
(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);
}
Comment on lines +230 to +238

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Stale invalidation banner stays visible after reconnecting via Quick Connect

After permanent invalidation sets nativeError and returns Home to FirstRunHome, reconnecting via "Connect an existing service" calls receiveState(selected) with previous.active == null and previous.retryGeneration === undefined. Because line 230 only clears nativeError when previous?.retryGeneration !== undefined, the old invalidation error stays pinned above the newly connected workspace.

Please clear nativeError whenever a connection transitions from disconnected to active (if (next.active && !previous?.active)), which covers both retry recovery and Quick Connect while keeping target-scope errors on an active connection.

if (!previewMode && next.active?.scope) {
globalThis.localStorage?.setItem(
"active-connection-id",
Expand All @@ -239,6 +245,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);
Expand Down Expand Up @@ -286,7 +302,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",
);
Expand Down Expand Up @@ -593,6 +614,7 @@ export function App() {
contextPending={contextPending || quickConnectPending}
preview={previewMode}
hideContent={page === "connections" || page === "settings"}
onState={receiveState}
onManageConnections={(profileId) =>
navigate("connections", { profileId })
}
Expand All @@ -614,7 +636,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);
})
Comment on lines +639 to +642

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Clear stale switch error after Retry read recovers the connection (non-blocking)

When a scope switch triggers a transient interruption, setNativeError(error) stores the outage globally. After Retry read restores the original scope via onState(next) -> receiveState, nativeError is never cleared, so the outage banner and Manage connections link remain visible across all pages.

Required outcome: clear nativeError in receiveState when transitioning out of an interrupted state back to an active connection (while keeping nativeError intact when a target scope is denied without interrupting the current scope).

.finally(() => connectionPending(false));
}}
onCreateScope={(trigger) => {
Expand Down
Loading
Loading