Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop-app): fence linked setup auth changes (R16-M1)

Josué88a02c81b67b
diff --git a/desktop-app/src/__tests__/appService.nativeCommit.test.ts b/desktop-app/src/__tests__/appService.nativeCommit.test.ts
index 2090c58ed..a2e92fe4a 100644
--- a/desktop-app/src/__tests__/appService.nativeCommit.test.ts
+++ b/desktop-app/src/__tests__/appService.nativeCommit.test.ts
@@ -114,6 +114,65 @@ describe('AppService native auth and environment commit ordering', () => {
expect(service.gfsScopeIdentity).toEqual(gfsScopeBeforeSetup)
})
+ it('rejects handoff environment saves after auth changes or while auth is active', async () => {
+ const { service, runtimeConfig, optionB, restA, restB } = await createNativeCommitTestHarness()
+ const loginStarted = deferred<void>()
+ const loginResponse = deferred<{
+ token: string
+ me: { id: string; email: string; teamId: string }
+ }>()
+ const me = { id: 'user-a', email: '[email protected]', teamId: 'team-a' }
+ service.authClient = {
+ googleLogin: vi.fn(() => {
+ loginStarted.resolve()
+ return loginResponse.promise
+ }),
+ } as never
+
+ const nextConfig = {
+ appName: 'Environment B',
+ externalRestApiBaseUrl: restB,
+ rpcProxyBaseUrl: 'https://rpc-b.example.test',
+ }
+ const saveRuntimeConfigForHandoff = service.saveRuntimeConfig.bind(service) as (
+ config: Parameters<typeof service.saveRuntimeConfig>[0],
+ expectedSessionGeneration: number
+ ) => Promise<unknown>
+ const expectedGeneration = service.getSessionGeneration()
+ const login = service.googleLogin('synthetic-google-token')
+ await loginStarted.promise
+ const generationDuringLogin = service.getSessionGeneration()
+
+ await expect(
+ service.selectRuntimeConfigForHandoff(optionB.id, expectedGeneration)
+ ).rejects.toThrow('stale_session_generation')
+ await expect(
+ service.selectRuntimeConfigForHandoff(optionB.id, generationDuringLogin)
+ ).rejects.toThrow('auth_transition_in_progress')
+ await expect(saveRuntimeConfigForHandoff(nextConfig, expectedGeneration)).rejects.toThrow(
+ 'stale_session_generation'
+ )
+ await expect(saveRuntimeConfigForHandoff(nextConfig, generationDuringLogin)).rejects.toThrow(
+ 'auth_transition_in_progress'
+ )
+ expect(runtimeConfig.config.externalRestApiBaseUrl).toBe(restA)
+
+ loginResponse.resolve({ token: 'synthetic-session-a', me })
+ await expect(login).resolves.toMatchObject({ authenticated: true, me })
+ const authenticatedGeneration = service.getSessionGeneration()
+ await expect(
+ service.selectRuntimeConfigForHandoff(optionB.id, authenticatedGeneration)
+ ).rejects.toThrow('desktop_setup_requires_signout')
+ await expect(saveRuntimeConfigForHandoff(nextConfig, authenticatedGeneration)).rejects.toThrow(
+ 'desktop_setup_requires_signout'
+ )
+ expect(runtimeConfig.config.externalRestApiBaseUrl).toBe(restA)
+ await expect(service.getSessionState()).resolves.toMatchObject({
+ authenticated: true,
+ me,
+ })
+ })
+
it('keeps a pending environment selection ahead of a login commit', async () => {
const { service, runtimeConfig, restA, restB, optionB } = await createNativeCommitTestHarness()
const loginStarted = deferred<void>()
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index dbf11363f..5b5a46211 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -1896,6 +1896,15 @@ export class AppService {
}
}
+ private assertProfileHandoffSessionIsSignedOut(): void {
+ if (this.interactiveLoginAttempts > 0) {
+ throw new Error('auth_transition_in_progress')
+ }
+ if (this.sessionToken || this.me) {
+ throw new Error('desktop_setup_requires_signout')
+ }
+ }
+
private async applyRuntimeEnvironmentChange(
operation: () => Promise<void>,
expectedSessionGeneration?: number
@@ -1988,6 +1997,7 @@ export class AppService {
return this.withNativeAuthEnvironmentCommit(async () => {
if (expectedSessionGeneration !== undefined) {
this.assertSessionGeneration(expectedSessionGeneration)
+ this.assertProfileHandoffSessionIsSignedOut()
}
const state = getDesktopRuntimeConfigState()
const selected = state.options.find(option => option.id === String(optionId || '').trim())
@@ -2025,8 +2035,15 @@ export class AppService {
})
}
- async saveRuntimeConfig(next: DesktopRuntimeConfig) {
+ async saveRuntimeConfig(next: DesktopRuntimeConfig, expectedSessionGeneration?: number) {
await this.withNativeAuthEnvironmentCommit(async () => {
+ if (expectedSessionGeneration !== undefined) {
+ if (!Number.isSafeInteger(expectedSessionGeneration) || expectedSessionGeneration < 0) {
+ throw new Error('invalid_session_generation')
+ }
+ this.assertSessionGeneration(expectedSessionGeneration)
+ this.assertProfileHandoffSessionIsSignedOut()
+ }
const nextEnvKey = resolveEnvKey(next.externalRestApiBaseUrl, next.rpcProxyBaseUrl || '')
const sameUploadBoundary =
nextEnvKey === getActiveEnvKey() &&
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index 4dcecd76c..c2a53412f 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -384,14 +384,30 @@ export function registerIpcHandlers(service: AppService): void {
assertTrustedSender(event)
return service.clearRuntimeConfigSelection()
})
- ipcMain.handle('auth:saveRuntimeConfig', async (event, payload: DesktopRuntimeConfig) => {
- assertTrustedSender(event)
- return service.saveRuntimeConfig({
- externalRestApiBaseUrl: sanitizeString(payload?.externalRestApiBaseUrl),
- rpcProxyBaseUrl: sanitizeString(payload?.rpcProxyBaseUrl),
- appName: sanitizeString(payload?.appName),
- })
- })
+ ipcMain.handle(
+ 'auth:saveRuntimeConfig',
+ async (event, payload: DesktopRuntimeConfig & { expectedSessionGeneration?: unknown }) => {
+ assertTrustedSender(event)
+ const rawExpectedSessionGeneration = payload?.expectedSessionGeneration
+ if (
+ rawExpectedSessionGeneration !== undefined &&
+ (typeof rawExpectedSessionGeneration !== 'number' ||
+ !Number.isSafeInteger(rawExpectedSessionGeneration) ||
+ rawExpectedSessionGeneration < 0)
+ ) {
+ throw new Error('Invalid session generation')
+ }
+ const runtimeConfig = {
+ externalRestApiBaseUrl: sanitizeString(payload?.externalRestApiBaseUrl),
+ rpcProxyBaseUrl: sanitizeString(payload?.rpcProxyBaseUrl),
+ appName: sanitizeString(payload?.appName),
+ }
+ if (rawExpectedSessionGeneration === undefined) {
+ return service.saveRuntimeConfig(runtimeConfig)
+ }
+ return service.saveRuntimeConfig(runtimeConfig, rawExpectedSessionGeneration)
+ }
+ )
ipcMain.handle('auth:deleteRuntimeConfig', async (event, payload: { optionId: string }) => {
assertTrustedSender(event)
return service.deleteRuntimeConfig(sanitizeString(payload?.optionId))
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 6d7092d7b..f9eaae2bb 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -81,11 +81,18 @@ const clerum = Object.freeze({
expectedSessionGeneration,
}) as Promise<DesktopRuntimeConfigHandoffSelection>,
clearRuntimeConfigSelection: () => ipcRenderer.invoke('auth:clearRuntimeConfigSelection'),
- saveRuntimeConfig: (config: {
- externalRestApiBaseUrl: string
- rpcProxyBaseUrl?: string
- appName?: string
- }) => ipcRenderer.invoke('auth:saveRuntimeConfig', config),
+ saveRuntimeConfig: (
+ config: {
+ externalRestApiBaseUrl: string
+ rpcProxyBaseUrl?: string
+ appName?: string
+ },
+ expectedSessionGeneration?: number
+ ) =>
+ ipcRenderer.invoke(
+ 'auth:saveRuntimeConfig',
+ expectedSessionGeneration === undefined ? config : { ...config, expectedSessionGeneration }
+ ),
deleteRuntimeConfig: (optionId: string) =>
ipcRenderer.invoke('auth:deleteRuntimeConfig', { optionId }),
googleLogin: (idToken: string) => ipcRenderer.invoke('auth:googleLogin', { idToken }),
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index e472266ea..09e87db65 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -81,7 +81,10 @@ declare global {
expectedSessionGeneration: number
) => Promise<DesktopRuntimeConfigHandoffSelection>
clearRuntimeConfigSelection: () => Promise<DesktopRuntimeConfigState>
- saveRuntimeConfig: (config: DesktopRuntimeConfig) => Promise<DesktopRuntimeConfigState>
+ saveRuntimeConfig: (
+ config: DesktopRuntimeConfig,
+ expectedSessionGeneration?: number
+ ) => Promise<DesktopRuntimeConfigState>
deleteRuntimeConfig: (optionId: string) => Promise<DesktopRuntimeConfigState>
googleLogin: (idToken: string) => Promise<SessionState>
passwordLogin: (email: string, password: string) => Promise<PasswordLoginResult>
diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.ts
index 98940595b..beb19f6e0 100644
--- a/desktop-app/test/ipc.test.ts
+++ b/desktop-app/test/ipc.test.ts
@@ -530,6 +530,47 @@ describe('ipc host status stream handlers', () => {
expect(result).toMatchObject({ configured: true, activeOptionId: 'prod-1' })
})
+ it('forwards the expected session generation for a handoff runtime config save', async () => {
+ const { event } = makeTrustedEvent()
+ const handler = testState.handlers.get('auth:saveRuntimeConfig')
+ await Promise.resolve(
+ handler?.(event, {
+ externalRestApiBaseUrl: 'https://example.com',
+ rpcProxyBaseUrl: 'https://rpc.example.com',
+ appName: 'Production',
+ expectedSessionGeneration: 7,
+ })
+ )
+
+ expect(service.saveRuntimeConfig).toHaveBeenCalledWith(
+ {
+ externalRestApiBaseUrl: 'https://example.com',
+ rpcProxyBaseUrl: 'https://rpc.example.com',
+ appName: 'Production',
+ },
+ 7
+ )
+ })
+
+ it.each([Number.NaN, -1, 1.5, '7'])(
+ 'rejects invalid handoff generation %s for runtime config save',
+ async expectedSessionGeneration => {
+ const { event } = makeTrustedEvent()
+ const handler = testState.handlers.get('auth:saveRuntimeConfig')
+ await expect(
+ Promise.resolve(
+ handler?.(event, {
+ externalRestApiBaseUrl: 'https://example.com',
+ rpcProxyBaseUrl: 'https://rpc.example.com',
+ appName: 'Production',
+ expectedSessionGeneration,
+ })
+ )
+ ).rejects.toThrow('Invalid session generation')
+ expect(service.saveRuntimeConfig).not.toHaveBeenCalled()
+ }
+ )
+
it('rejects untrusted sender for runtime config save', async () => {
const handler = testState.handlers.get('auth:saveRuntimeConfig')
await expect(
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts
index 8d3712b40..a947024a4 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts
@@ -140,24 +140,43 @@ describe('Desktop environment handoff concurrency', () => {
it('rechecks the auth operation state after runtime configuration loads', async () => {
let finishRefresh: (() => void) | undefined
+ let reportRefreshStarted!: () => void
+ const refreshStarted = new Promise<void>(resolve => {
+ reportRefreshStarted = resolve
+ })
const runtimeConfigState = await runtimeConfigModule!.getDesktopRuntimeConfigState()
- const refreshRuntimeConfigState = () =>
- new Promise<typeof runtimeConfigState>(resolve => {
+ const originalActiveOptionId = runtimeConfigState.activeOptionId
+ const refreshRuntimeConfigState = () => {
+ reportRefreshStarted()
+ return new Promise<typeof runtimeConfigState>(resolve => {
finishRefresh = () => resolve(runtimeConfigState)
})
+ }
let busy = false
- const { handler, selectRuntimeConfig, setPendingDesktopEnvironmentSetup } = createHandler(
- () => ({ booting: false, busy, authTransitioning: false, isAuthenticated: false }),
- refreshRuntimeConfigState
- )
+ const { handler, selectRuntimeConfig, setPendingDesktopEnvironmentSetup, setStatus } =
+ createHandler(
+ () => ({ booting: false, busy, authTransitioning: false, isAuthenticated: false }),
+ refreshRuntimeConfigState
+ )
- const handling = handler(targetEnvironment)
+ const handling = handler({
+ ...targetEnvironment,
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,
+ })
+ await refreshStarted
busy = true
finishRefresh?.()
await handling
expect(selectRuntimeConfig).not.toHaveBeenCalled()
expect(setPendingDesktopEnvironmentSetup).not.toHaveBeenCalled()
+ expect((await runtimeConfigModule!.getDesktopRuntimeConfigState()).activeOptionId).toBe(
+ originalActiveOptionId
+ )
+ expect(setStatus).toHaveBeenCalledWith(
+ 'Finish the current authentication action before continuing this desktop link.',
+ 'info'
+ )
})
it.each([
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAuthController.desktopEnvironment.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAuthController.desktopEnvironment.test.tsx
index 86b2b7ad2..51adc9493 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useAuthController.desktopEnvironment.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAuthController.desktopEnvironment.test.tsx
@@ -6,6 +6,7 @@ import fsp from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import type { AppService } from '../../../../../src/appService'
+import type { DesktopRuntimeConfigState } from '../../../../../src/types'
import { useAuthController } from '../useAuthController'
import { wrapLikeElectronIpc } from './__fixtures__/ipcErrors'
@@ -227,6 +228,65 @@ afterEach(async () => {
})
describe('Desktop environment handoff', () => {
+ it('preserves a session that starts while setup confirmation rereads configuration', async () => {
+ const linkedEnvironment = {
+ appName: 'New tenant',
+ externalRestApiBaseUrl: 'https://new-api.example.test/api/v1',
+ }
+ render(<Probe />)
+ await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
+ await dispatchDesktopEnvironmentLink(linkedEnvironment)
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent(
+ linkedEnvironment.externalRestApiBaseUrl
+ )
+
+ const stateBeforeConfirmation = await runtimeConfigModule!.getDesktopRuntimeConfigState()
+ let finishRefresh: ((state: DesktopRuntimeConfigState) => void) | undefined
+ mocks.getRuntimeConfigState.mockClear()
+ mocks.getRuntimeConfigState.mockImplementationOnce(
+ () =>
+ new Promise(resolve => {
+ finishRefresh = resolve
+ })
+ )
+ mocks.saveRuntimeConfig.mockImplementationOnce(async config => {
+ await runtimeConfigModule!.saveDesktopRuntimeConfig({
+ ...config,
+ rpcProxyBaseUrl: 'https://rpc.new-api.example.test',
+ })
+ return runtimeConfigModule!.getDesktopRuntimeConfigState()
+ })
+
+ let confirmation: Promise<void> | undefined
+ await act(async () => {
+ confirmation = confirmDesktopEnvironmentSetupForTest?.()
+ await Promise.resolve()
+ })
+ await waitFor(() => expect(finishRefresh).toBeTypeOf('function'))
+ await act(async () => setAuthenticatedForTest?.(true))
+ finishRefresh?.(await runtimeConfigModule!.getDesktopRuntimeConfigState())
+ await act(async () => confirmation)
+
+ const saveRuntimeConfigCallCount = mocks.saveRuntimeConfig.mock.calls.length
+ mocks.saveRuntimeConfig.mockReset()
+ const finalState = await runtimeConfigModule!.getDesktopRuntimeConfigState()
+ expect(saveRuntimeConfigCallCount).toBe(0)
+ expect(mocks.selectRuntimeConfig).not.toHaveBeenCalled()
+ expect(mocks.selectRuntimeConfigForHandoff).not.toHaveBeenCalled()
+ expect(finalState.activeOptionId).toBe(stateBeforeConfirmation.activeOptionId)
+ expect(
+ finalState.options.some(
+ option => option.externalRestApiBaseUrl === linkedEnvironment.externalRestApiBaseUrl
+ )
+ ).toBe(false)
+ expect(screen.getByTestId('is-authenticated')).toHaveTextContent('yes')
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
+ expect(mocks.setStatus).toHaveBeenLastCalledWith(
+ 'The desktop session changed while processing this link. Open it again.',
+ 'info'
+ )
+ })
+
it('rejects a same-origin REST path conflict added before setup confirmation', async () => {
const linkedEnvironment = {
appName: 'New tenant',
@@ -451,6 +511,12 @@ describe('Desktop environment handoff', () => {
option => option.externalRestApiBaseUrl === linkedEnvironment.externalRestApiBaseUrl
)
if (!savedOption) throw new Error('The config producer did not return the newly saved profile')
+ const currentOption = (await runtimeConfigModule!.getDesktopRuntimeConfigState()).options.find(
+ option => option.externalRestApiBaseUrl === otherEnvironment.externalRestApiBaseUrl
+ )
+ if (!currentOption) throw new Error('The config producer did not return the current profile')
+ await runtimeConfigModule!.selectDesktopRuntimeConfigOption(currentOption.id)
+ const generationBeforeConfirmation = nativeAppService!.getSessionGeneration()
await act(async () => {
await confirmDesktopEnvironmentSetupForTest?.()
@@ -458,13 +524,19 @@ describe('Desktop environment handoff', () => {
expect(mocks.saveRuntimeConfig).not.toHaveBeenCalled()
expect(mocks.selectRuntimeConfig).not.toHaveBeenCalled()
+ expect(mocks.selectRuntimeConfigForHandoff).toHaveBeenCalledWith(
+ savedOption.id,
+ generationBeforeConfirmation
+ )
expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
expect((await runtimeConfigModule!.getDesktopRuntimeConfigState()).activeOptionId).toBe(
savedOption.id
)
- expect(mocks.setStatus).toHaveBeenLastCalledWith(
- `Opening ${linkedEnvironment.appName} in Evenfire Desktop.`,
- 'success'
+ expect(mocks.setStatus).toHaveBeenCalledWith(
+ expect.stringContaining(`Environment selected: ${linkedEnvironment.appName}`),
+ 'success',
+ undefined,
+ { global: false, toast: true }
)
})
diff --git a/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts b/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts
index 268ccdcfa..e99d8b1ed 100644
--- a/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts
+++ b/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts
@@ -206,6 +206,11 @@ export function createDesktopEnvironmentSetupHandler({
}
if (!(await ownsSessionGeneration(sessionGeneration))) return
+ let authState = getAuthState()
+ if (isAuthenticationOperationInProgress(authState)) {
+ reportAuthenticationStateChanged(authState, setStatus)
+ return
+ }
let restMatches = getDesktopEnvironmentRestMatches(
configState,
@@ -219,7 +224,7 @@ export function createDesktopEnvironmentSetupHandler({
)
return
}
- let authState = getAuthState()
+ authState = getAuthState()
let activeRestEndpointMatches = restMatches.active
if (
!activeRestEndpointMatches &&
diff --git a/desktop-app/ui/src/hooks/domain/useAuthController.ts b/desktop-app/ui/src/hooks/domain/useAuthController.ts
index fb92f1324..a79d8d246 100644
--- a/desktop-app/ui/src/hooks/domain/useAuthController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAuthController.ts
@@ -311,7 +311,8 @@ export function useAuthController({
}
const handleSaveRuntimeConfig = async (
- nextConfig?: DesktopRuntimeConfig
+ nextConfig?: DesktopRuntimeConfig,
+ expectedSessionGeneration?: number
): Promise<DesktopRuntimeConfigState | null> => {
try {
setBusy(true)
@@ -326,11 +327,15 @@ export function useAuthController({
throw new Error('environment name and external REST API are required')
}
- const state = await window.clerum.auth.saveRuntimeConfig({
+ const configToSave = {
externalRestApiBaseUrl,
rpcProxyBaseUrl,
appName: name,
- })
+ }
+ const state =
+ expectedSessionGeneration === undefined
+ ? await window.clerum.auth.saveRuntimeConfig(configToSave)
+ : await window.clerum.auth.saveRuntimeConfig(configToSave, expectedSessionGeneration)
setRuntimeConfigState(state)
setRuntimeConfigSetupName('')
setRuntimeConfigSetupExternalRestApiBaseUrl('')
@@ -344,10 +349,25 @@ export function useAuthController({
)
return state
} catch (error) {
- setStatus(
- `Environment setup failed: ${error instanceof Error ? error.message : String(error)}`,
- 'error'
- )
+ const message = error instanceof Error ? error.message : String(error)
+ if (
+ expectedSessionGeneration !== undefined &&
+ message.includes('auth_transition_in_progress')
+ ) {
+ setStatus(
+ 'Finish the current authentication action before continuing this desktop link.',
+ 'info'
+ )
+ } else if (
+ expectedSessionGeneration !== undefined &&
+ (message.includes('stale_session_generation') ||
+ message.includes('desktop_setup_requires_signout'))
+ ) {
+ setPendingDesktopEnvironmentSetup(null)
+ setStatus('The desktop session changed while processing this link. Open it again.', 'info')
+ } else {
+ setStatus(`Environment setup failed: ${message}`, 'error')
+ }
return null
} finally {
setBusy(false)
@@ -431,17 +451,29 @@ export function useAuthController({
applySelectedRuntimeConfigState(selection.runtimeConfigState)
return selection
} catch (error) {
- if (error instanceof Error && error.message.includes('stale_session_generation')) {
+ const message = error instanceof Error ? error.message : String(error)
+ if (message.includes('stale_session_generation')) {
setStatus(
'The desktop session changed while processing this link. Open it again.',
'info'
)
return null
}
- setStatus(
- `Failed to switch environment: ${error instanceof Error ? error.message : String(error)}`,
- 'error'
- )
+ if (message.includes('auth_transition_in_progress')) {
+ setStatus(
+ 'Finish the current authentication action before continuing this desktop link.',
+ 'info'
+ )
+ return null
+ }
+ if (message.includes('desktop_setup_requires_signout')) {
+ setStatus(
+ 'The desktop session changed while processing this link. Open it again.',
+ 'info'
+ )
+ return null
+ }
+ setStatus(`Failed to switch environment: ${message}`, 'error')
return null
} finally {
setBusy(false)
@@ -531,8 +563,46 @@ export function useAuthController({
const handleConfirmDesktopEnvironmentSetup = async (): Promise<void> => {
const nextConfig = pendingDesktopEnvironmentSetup
if (!nextConfig) return
+
+ const reportSessionChanged = () => {
+ setPendingDesktopEnvironmentSetup(null)
+ setStatus('The desktop session changed while processing this link. Open it again.', 'info')
+ }
+ const reportAuthenticationInProgress = () => {
+ setStatus(
+ 'Finish the current authentication action before continuing this desktop link.',
+ 'info'
+ )
+ }
+
+ if (bootingRef.current || busyRef.current || authTransitioningRef.current) {
+ reportAuthenticationInProgress()
+ return
+ }
+ if (isAuthenticatedRef.current) {
+ reportSessionChanged()
+ return
+ }
+
setAuthTransitioning(true)
try {
+ let expectedSessionGeneration: number
+ try {
+ expectedSessionGeneration = await getSessionGeneration()
+ } catch {
+ setPendingDesktopEnvironmentSetup(null)
+ setStatus('Could not verify the desktop session. Try opening the link again.', 'error')
+ return
+ }
+ if (bootingRef.current || busyRef.current) {
+ reportAuthenticationInProgress()
+ return
+ }
+ if (isAuthenticatedRef.current) {
+ reportSessionChanged()
+ return
+ }
+
let currentConfigState: DesktopRuntimeConfigState
try {
currentConfigState = await refreshRuntimeConfigState()
@@ -541,6 +611,23 @@ export function useAuthController({
return
}
+ let currentSessionGeneration: number
+ try {
+ currentSessionGeneration = await getSessionGeneration()
+ } catch {
+ setPendingDesktopEnvironmentSetup(null)
+ setStatus('Could not verify the desktop session. Try opening the link again.', 'error')
+ return
+ }
+ if (currentSessionGeneration !== expectedSessionGeneration || isAuthenticatedRef.current) {
+ reportSessionChanged()
+ return
+ }
+ if (bootingRef.current || busyRef.current) {
+ reportAuthenticationInProgress()
+ return
+ }
+
const restMatches = getDesktopEnvironmentRestMatches(
currentConfigState,
nextConfig.externalRestApiBaseUrl
@@ -587,8 +674,26 @@ export function useAuthController({
return
}
- const selectedState = await handleSelectRuntimeConfig(savedOption.id)
- if (!selectedState) return
+ const selection = await handleSelectRuntimeConfigForHandoff(
+ savedOption.id,
+ expectedSessionGeneration
+ )
+ if (!selection) return
+ let selectedSessionGeneration: number
+ try {
+ selectedSessionGeneration = await getSessionGeneration()
+ } catch {
+ reportSessionChanged()
+ return
+ }
+ if (selectedSessionGeneration !== selection.sessionGeneration) {
+ reportSessionChanged()
+ return
+ }
+ if (busyRef.current) {
+ reportAuthenticationInProgress()
+ return
+ }
setPendingDesktopEnvironmentSetup(null)
try {
await onSessionNeedsLoad({ preserveNav: true })
@@ -601,7 +706,7 @@ export function useAuthController({
return
}
- const state = await handleSaveRuntimeConfig(nextConfig)
+ const state = await handleSaveRuntimeConfig(nextConfig, expectedSessionGeneration)
if (!state) return
const selectedOption = state.options.find(option => option.id === state.activeOptionId)
const selectedRestMatches = getDesktopEnvironmentRestMatches(