Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): [R5-M1] fence stale environment handoffs
Josuécd1235640add
diff --git a/desktop-app/src/__tests__/appService.entityChanges.test.ts b/desktop-app/src/__tests__/appService.entityChanges.test.tsindex 97c101947..7065c2d0b 100644--- a/desktop-app/src/__tests__/appService.entityChanges.test.ts+++ b/desktop-app/src/__tests__/appService.entityChanges.test.ts@@ -45,6 +45,46 @@ function setSyntheticEntityChangeSession(service: object, value: string, generatstate.entityChangeSessionGeneration = generation}+describe('AppService runtime transition ownership', () => {+ it('rejects a handoff selection from an older session generation before reading profiles', async () => {+ const service = new AppService() as any+ service.sessionGeneration = 9++ await expect(service.selectRuntimeConfigForHandoff('saved-profile', 8)).rejects.toThrow(+ 'stale_session_generation'+ )+ expect(service.getSessionGeneration()).toBe(9)+ })++ it('does not persist an environment selection after another transition supersedes it', async () => {+ const service = new AppService() as any+ service.sessionGeneration = 9+ service.sessionToken = 'synthetic-session-token'+ service.me = { id: 'user-1', teamId: 'team-1' }+ service.beginPrewarmAuthTransition = () => () => undefined+ service.ensureEntityChangeConnection = vi.fn()++ let finishUploadSuspension!: () => void+ service.suspendDesktopGfsUploadsForAuthBoundary = () =>+ new Promise<void>(resolve => {+ finishUploadSuspension = resolve+ })+ const persistEnvironmentSelection = vi.fn(async () => undefined)+ const changing = service.applyRuntimeEnvironmentChange(persistEnvironmentSelection, 9)++ await flushAsyncWork()+ expect(service.getSessionGeneration()).toBe(10)++ // A login or environment selection advances the same native owner revision.+ service.sessionGeneration += 1+ finishUploadSuspension()++ await expect(changing).rejects.toThrow('stale_session_generation')+ expect(persistEnvironmentSelection).not.toHaveBeenCalled()+ expect(service.entityChangeEnvironmentSwitching).toBe(false)+ })+})+describe('AppService entity-change fan-out', () => {it('rebinds a live subscriber after expiry through public Google login', async () => {const service = new AppService() as anydiff --git a/desktop-app/src/__tests__/appService.gfs.test.ts b/desktop-app/src/__tests__/appService.gfs.test.tsindex 5675075a1..37fde754c 100644--- a/desktop-app/src/__tests__/appService.gfs.test.ts+++ b/desktop-app/src/__tests__/appService.gfs.test.ts@@ -927,7 +927,11 @@ describe('AppService GFS upload security scope', () => {let loginSettled = falseconst login = (loginKind === 'password'- ? service.completePasswordLogin('[email protected]', 'password')+ ? service.completePasswordLogin(+ '[email protected]',+ 'password',+ service.getSessionGeneration()+ ): service.googleLogin('google-id-token')).then(result => {loginSettled = truediff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex af6f3b784..0508c30ae 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -52,6 +52,7 @@ import {DesktopAppInfo,DesktopReleaseStatus,DesktopRuntimeConfig,+ DesktopRuntimeConfigHandoffSelection,EntityChangeStreamEvent,ExternalChannelsSummary,HostActivitySnapshot,@@ -1595,10 +1596,11 @@ export class AppService {}}- private async installAuthenticatedLogin(result: {- token: string- me: SessionMe- }): Promise<SessionState> {+ private async installAuthenticatedLogin(+ result: { token: string; me: SessionMe },+ expectedSessionGeneration: number+ ): Promise<SessionState> {+ this.assertSessionGeneration(expectedSessionGeneration)const releasePrewarm = this.beginPrewarmAuthTransition()try {const previousToken = this.sessionToken@@ -1618,6 +1620,7 @@ export class AppService {}throw error}+ this.assertSessionGeneration(expectedSessionGeneration)if (this.sessionGeneration !== previousGeneration ||this.sessionToken !== previousToken ||@@ -1646,9 +1649,14 @@ export class AppService {}}- private async completePasswordLogin(email: string, password: string): Promise<SessionState> {+ private async completePasswordLogin(+ email: string,+ password: string,+ expectedSessionGeneration: number+ ): Promise<SessionState> {+ this.assertSessionGeneration(expectedSessionGeneration)const result = await this.authClient.passwordLogin(email, password)- return this.installAuthenticatedLogin(result)+ return this.installAuthenticatedLogin(result, expectedSessionGeneration)}async getDependenciesHealth(): Promise<DependencyHealth> {@@ -1685,7 +1693,23 @@ export class AppService {return getDesktopRuntimeConfigState()}- private async applyRuntimeEnvironmentChange(operation: () => Promise<void>): Promise<void> {+ getSessionGeneration(): number {+ return this.sessionGeneration+ }++ private assertSessionGeneration(expectedSessionGeneration: number): void {+ if (this.sessionGeneration !== expectedSessionGeneration) {+ throw new Error('stale_session_generation')+ }+ }++ private async applyRuntimeEnvironmentChange(+ operation: () => Promise<void>,+ expectedSessionGeneration?: number+ ): Promise<number> {+ if (expectedSessionGeneration !== undefined) {+ this.assertSessionGeneration(expectedSessionGeneration)+ }const oldEnvKey = getActiveEnvKey()const oldBaseUrl = normalizeDesktopUploadBaseUrl(config.externalRestApiBaseUrl)const oldLegacyEnvKeys = getActiveLegacyEnvKeys()@@ -1697,10 +1721,16 @@ export class AppService {// Invalidate a restore that may still be awaiting keychain/getMe before it// can bind an old-environment token to the newly selected runtime.this.sessionGeneration += 1+ const transitionGeneration = this.sessionGenerationif (hadAuthenticatedScope) await this.suspendDesktopGfsUploadsForAuthBoundary()+ this.assertSessionGeneration(transitionGeneration)try {await operation()+ this.assertSessionGeneration(transitionGeneration)} catch (error) {+ if (this.sessionGeneration !== transitionGeneration) {+ throw new Error('stale_session_generation')+ }const environmentUnchanged =getActiveEnvKey() === oldEnvKey &&normalizeDesktopUploadBaseUrl(config.externalRestApiBaseUrl) === oldBaseUrl@@ -1716,7 +1746,11 @@ export class AppService {await this.tokenStore.clearSessionToken(oldEnvKey, { legacyEnvKeys: oldLegacyEnvKeys })} else if (hadAuthenticatedScope && this.sessionToken && this.me) {this.activateGfsAuthScope()+ this.sessionGeneration += 1+ } else {+ this.sessionGeneration += 1}+ return this.sessionGeneration} finally {this.entityChangeEnvironmentSwitching = falseif (@@ -1730,6 +1764,26 @@ export class AppService {}async selectRuntimeConfig(optionId: string) {+ return (await this.selectRuntimeConfigWithGeneration(optionId)).runtimeConfigState+ }++ async selectRuntimeConfigForHandoff(+ optionId: string,+ expectedSessionGeneration: number+ ): Promise<DesktopRuntimeConfigHandoffSelection> {+ if (!Number.isSafeInteger(expectedSessionGeneration) || expectedSessionGeneration < 0) {+ throw new Error('invalid_session_generation')+ }+ return this.selectRuntimeConfigWithGeneration(optionId, expectedSessionGeneration)+ }++ private async selectRuntimeConfigWithGeneration(+ optionId: string,+ expectedSessionGeneration?: number+ ): Promise<DesktopRuntimeConfigHandoffSelection> {+ if (expectedSessionGeneration !== undefined) {+ this.assertSessionGeneration(expectedSessionGeneration)+ }const state = getDesktopRuntimeConfigState()const selected = state.options.find(option => option.id === String(optionId || '').trim())const nextEnvKey = selected@@ -1740,9 +1794,22 @@ export class AppService {selected !== undefined &&normalizeDesktopUploadBaseUrl(selected.externalRestApiBaseUrl) ===normalizeDesktopUploadBaseUrl(config.externalRestApiBaseUrl)- if (sameUploadBoundary) await selectDesktopRuntimeConfigOption(optionId)- else await this.applyRuntimeEnvironmentChange(() => selectDesktopRuntimeConfigOption(optionId))- return getDesktopRuntimeConfigState()+ if (sameUploadBoundary) {+ this.sessionGeneration += 1+ const transitionGeneration = this.sessionGeneration+ await selectDesktopRuntimeConfigOption(optionId)+ this.assertSessionGeneration(transitionGeneration)+ this.sessionGeneration += 1+ } else {+ await this.applyRuntimeEnvironmentChange(+ () => selectDesktopRuntimeConfigOption(optionId),+ expectedSessionGeneration+ )+ }+ return {+ runtimeConfigState: getDesktopRuntimeConfigState(),+ sessionGeneration: this.sessionGeneration,+ }}async clearRuntimeConfigSelection() {@@ -1771,8 +1838,10 @@ export class AppService {}async googleLogin(idToken: string): Promise<SessionState> {+ if (this.logoutInProgress) throw new Error('auth_transition_in_progress')+ const loginGeneration = ++this.sessionGenerationconst result = await this.authClient.googleLogin(idToken)- return this.installAuthenticatedLogin(result)+ return this.installAuthenticatedLogin(result, loginGeneration)}private async openProfileDesktopSetup(email: string): Promise<{@@ -1886,6 +1955,7 @@ export class AppService {}async completeDesktopSetup(email: string, authorizationToken: string) {+ const setupGeneration = ++this.sessionGenerationconst normalizedEmail = email.trim().toLowerCase()if (!normalizedEmail || !authorizationToken.trim()) {throw new Error('email and authorization token are required')@@ -1899,11 +1969,14 @@ export class AppService {throw new Error('desktop setup configuration mismatch')}+ this.assertSessionGeneration(setupGeneration)await saveDesktopRuntimeConfig({externalRestApiBaseUrl: activation.externalRestApiBaseUrl,rpcProxyBaseUrl: '',appName: activation.appName,})+ this.assertSessionGeneration(setupGeneration)+ this.sessionGeneration += 1await this.resolveRuntimeConfigIfNeeded().catch(() => undefined)return getDesktopRuntimeConfigState()} catch (error) {@@ -1915,14 +1988,17 @@ export class AppService {}async passwordLogin(email: string, password: string): Promise<PasswordLoginResult> {+ if (this.logoutInProgress) throw new Error('auth_transition_in_progress')+ const loginGeneration = ++this.sessionGenerationhydrateDesktopRuntimeConfig()const normalizedEmail = email.trim().toLowerCase()if (!isDesktopRuntimeConfigured()) {throw new Error('desktop_setup_required')}await this.resolveRuntimeConfigIfNeeded()+ this.assertSessionGeneration(loginGeneration)- return this.completePasswordLogin(normalizedEmail, password)+ return this.completePasswordLogin(normalizedEmail, password, loginGeneration)}/**@@ -2071,15 +2147,19 @@ export class AppService {return { opened: true }}- async logout(): Promise<void> {+ async logout(): Promise<number> {this.logoutInProgress = true+ this.sessionGeneration += 1+ const logoutGeneration = this.sessionGenerationconst releasePrewarm = this.beginPrewarmAuthTransition()try {const envKey = getActiveEnvKey()const legacyEnvKeys = getActiveLegacyEnvKeys()await this.suspendDesktopGfsUploadsForAuthBoundary()+ this.assertSessionGeneration(logoutGeneration)try {await this.tokenStore.clearSessionToken(envKey, { legacyEnvKeys })+ this.assertSessionGeneration(logoutGeneration)} catch (error) {if (this.sessionToken && this.me) this.activateGfsAuthScope()throw error@@ -2088,6 +2168,7 @@ export class AppService {// Grants survive logout (they are keyed by userId), but every cached SDK// result must not: the next user of this machine gets nothing of this one's.tryGetPluginSdkRuntime()?.notifySessionChanged(false)+ return this.sessionGeneration} finally {releasePrewarm()this.logoutInProgress = falsediff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex 4b9fc50aa..6ce70af4a 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -294,6 +294,10 @@ export function registerIpcHandlers(service: AppService): void {assertTrustedSender(event)return service.getSessionState()})+ ipcMain.handle('auth:getSessionGeneration', async event => {+ assertTrustedSender(event)+ return service.getSessionGeneration()+ })ipcMain.handle('auth:getDependenciesHealth', async event => {assertTrustedSender(event)return service.getDependenciesHealth()@@ -306,6 +310,24 @@ export function registerIpcHandlers(service: AppService): void {assertTrustedSender(event)return service.selectRuntimeConfig(sanitizeString(payload?.optionId))})+ ipcMain.handle(+ 'auth:selectRuntimeConfigForHandoff',+ async (event, payload: { optionId: string; expectedSessionGeneration: unknown }) => {+ assertTrustedSender(event)+ const expectedSessionGeneration = payload?.expectedSessionGeneration+ if (+ typeof expectedSessionGeneration !== 'number' ||+ !Number.isSafeInteger(expectedSessionGeneration) ||+ expectedSessionGeneration < 0+ ) {+ throw new Error('Invalid session generation')+ }+ return service.selectRuntimeConfigForHandoff(+ sanitizeString(payload?.optionId),+ expectedSessionGeneration+ )+ }+ )ipcMain.handle('auth:clearRuntimeConfigSelection', async event => {assertTrustedSender(event)return service.clearRuntimeConfigSelection()@@ -400,8 +422,8 @@ export function registerIpcHandlers(service: AppService): void {})ipcMain.handle('auth:logout', async event => {assertTrustedSender(event)- await service.logout()- return { ok: true }+ const sessionGeneration = await service.logout()+ return { ok: true, sessionGeneration }})ipcMain.handle('notifications:isSupported', async event => {diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex d145b5e74..6d7092d7b 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -2,6 +2,7 @@ import { contextBridge, ipcRenderer, webUtils } from 'electron'import type { DesktopCommandId, DesktopCommandSource } from './desktopCommands.js'import type { PluginConsentRequest } from './pluginSdkProtocol.js'import type {+ DesktopRuntimeConfigHandoffSelection,EntityChangeStreamEvent,HostMessageRequest,ProfileSettingsOpenOptions,@@ -69,10 +70,16 @@ const clerum = Object.freeze({},auth: {getSessionState: () => ipcRenderer.invoke('auth:getSessionState'),+ getSessionGeneration: () => ipcRenderer.invoke('auth:getSessionGeneration'),getDependenciesHealth: () => ipcRenderer.invoke('auth:getDependenciesHealth'),getRuntimeConfigState: () => ipcRenderer.invoke('auth:getRuntimeConfigState'),selectRuntimeConfig: (optionId: string) =>ipcRenderer.invoke('auth:selectRuntimeConfig', { optionId }),+ selectRuntimeConfigForHandoff: (optionId: string, expectedSessionGeneration: number) =>+ ipcRenderer.invoke('auth:selectRuntimeConfigForHandoff', {+ optionId,+ expectedSessionGeneration,+ }) as Promise<DesktopRuntimeConfigHandoffSelection>,clearRuntimeConfigSelection: () => ipcRenderer.invoke('auth:clearRuntimeConfigSelection'),saveRuntimeConfig: (config: {externalRestApiBaseUrl: stringdiff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex ddbd4456c..e472266ea 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -18,6 +18,7 @@ import {DesktopAppInfo,DesktopReleaseStatus,DesktopRuntimeConfig,+ DesktopRuntimeConfigHandoffSelection,DesktopRuntimeConfigState,EntityChangeStreamEvent,ExternalChannelsSummary,@@ -68,12 +69,17 @@ declare global {}auth: {getSessionState: () => Promise<SessionState>+ getSessionGeneration: () => Promise<number>getDependenciesHealth: () => Promise<{externalRestApi: { ok: boolean; detail?: string }rpcProxy: { ok: boolean; detail?: string }}>getRuntimeConfigState: () => Promise<DesktopRuntimeConfigState>selectRuntimeConfig: (optionId: string) => Promise<DesktopRuntimeConfigState>+ selectRuntimeConfigForHandoff: (+ optionId: string,+ expectedSessionGeneration: number+ ) => Promise<DesktopRuntimeConfigHandoffSelection>clearRuntimeConfigSelection: () => Promise<DesktopRuntimeConfigState>saveRuntimeConfig: (config: DesktopRuntimeConfig) => Promise<DesktopRuntimeConfigState>deleteRuntimeConfig: (optionId: string) => Promise<DesktopRuntimeConfigState>@@ -103,7 +109,7 @@ declare global {getDesktopAppInfo: () => Promise<DesktopAppInfo>openDesktopRelease: (releaseUrl: string) => Promise<{ opened: true }>onExternalLogout: (callback: () => void) => () => void- logout: () => Promise<{ ok: true }>+ logout: () => Promise<{ ok: true; sessionGeneration: number }>}team: {list: () => Promise<{ currentTeamId: string; items: TeamSummary[] }>diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.tsindex 45fde5d7d..a62d1d131 100644--- a/desktop-app/src/types.ts+++ b/desktop-app/src/types.ts@@ -705,6 +705,11 @@ export type DesktopRuntimeConfigState = {options: DesktopRuntimeConfigOption[]}+export type DesktopRuntimeConfigHandoffSelection = {+ runtimeConfigState: DesktopRuntimeConfigState+ sessionGeneration: number+}+export type TokenMetadata = {hasSession: booleanrpcTokenExpiresAtMs: number | nulldiff --git a/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.tsindex 64c129a3d..05f9e3073 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts+++ b/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts@@ -63,21 +63,35 @@ function createHandler(refreshRuntimeConfigState: () => Promise<Awaited<ReturnType<typeof import('../../../../../src/config').getDesktopRuntimeConfigState>>> = async () => runtimeConfigModule!.getDesktopRuntimeConfigState(),- logoutForEnvironmentMismatch: () => Promise<void> = vi.fn(async () => {}),- onSessionNeedsLoad: () => Promise<void> = vi.fn(async () => {})+ logoutForEnvironmentMismatch?: () => Promise<number | null>,+ onSessionNeedsLoad: () => Promise<void> = vi.fn(async () => {}),+ readSessionGeneration?: () => Promise<number>) {- const selectRuntimeConfig = vi.fn(async (optionId: string) => {+ let sessionGeneration = 0+ const getSessionGeneration = readSessionGeneration ?? (async () => sessionGeneration)+ const logout =+ logoutForEnvironmentMismatch ??+ vi.fn(async () => {+ sessionGeneration += 1+ return sessionGeneration+ })+ const selectRuntimeConfig = vi.fn(async (optionId: string, _expectedGeneration?: number) => {await runtimeConfigModule!.selectDesktopRuntimeConfigOption(optionId)- return runtimeConfigModule!.getDesktopRuntimeConfigState()+ sessionGeneration += 1+ return {+ runtimeConfigState: await runtimeConfigModule!.getDesktopRuntimeConfigState(),+ sessionGeneration,+ }})const setPendingDesktopEnvironmentSetup = vi.fn()const setStatus = vi.fn()const handler = createDesktopEnvironmentSetupHandler({getAuthState,+ getSessionGeneration,refreshRuntimeConfigState,handleSelectRuntimeConfig: selectRuntimeConfig,onSessionNeedsLoad,- logoutForEnvironmentMismatch,+ logoutForEnvironmentMismatch: logout,setPendingDesktopEnvironmentSetup,setStatus,})@@ -150,6 +164,7 @@ describe('Desktop environment handoff concurrency', () => {)if (!savedTarget) throw new Error('The config producer did not return the saved REST profile')+ let sessionGeneration = 0let busy = falselet isAuthenticated = truelet finishLogout: () => void = () => {}@@ -166,17 +181,18 @@ describe('Desktop environment handoff concurrency', () => {await logoutFinishedisAuthenticated = falsebusy = false+ sessionGeneration += 1+ return sessionGeneration})const { handler, selectRuntimeConfig, setPendingDesktopEnvironmentSetup } = createHandler(() => ({ booting: false, busy, authTransitioning: false, isAuthenticated }),undefined,- logout+ logout,+ undefined,+ async () => sessionGeneration)- const handling = handler({- ...targetEnvironment,- externalRestApiBaseUrl,- })+ const handling = handler({ ...targetEnvironment, externalRestApiBaseUrl })await logoutStartedexpect(busy).toBe(true)@@ -189,7 +205,7 @@ describe('Desktop environment handoff concurrency', () => {expect(busy).toBe(false)expect(logout).toHaveBeenCalledOnce()if (action === 'select') {- expect(selectRuntimeConfig).toHaveBeenCalledWith(savedTarget.id)+ expect(selectRuntimeConfig).toHaveBeenCalledWith(savedTarget.id, 1)expect(setPendingDesktopEnvironmentSetup).toHaveBeenLastCalledWith(null)} else {expect(selectRuntimeConfig).not.toHaveBeenCalled()@@ -201,78 +217,54 @@ describe('Desktop environment handoff concurrency', () => {}})- it.each([- {- outcome: 'selects the linked saved environment',- externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,- action: 'select',- },- {- outcome: 'prompts to add the linked environment',- externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/other`,- action: 'prompt',- },- ])(- 'refreshes live auth after logout swallows a token-clear failure, then $outcome',- async ({ externalRestApiBaseUrl, action }) => {- const state = await runtimeConfigModule!.getDesktopRuntimeConfigState()- const savedTarget = state.options.find(- option =>- option.externalRestApiBaseUrl === `${targetEnvironment.externalRestApiBaseUrl}/api/v1`- )- if (!savedTarget) throw new Error('The config producer did not return the saved REST profile')+ it('keeps the current environment when token removal fails during handoff logout', async () => {+ let rendererAuthenticated = true+ const clearSessionToken = vi.fn(async () => {+ throw new Error('secure storage unavailable')+ })+ const logoutForEnvironmentMismatch = vi.fn(async () => {+ try {+ await clearSessionToken()+ } catch {+ // AppService retains the active session when durable token removal fails.+ }+ return null+ })+ const onSessionNeedsLoad = vi.fn(async () => {+ rendererAuthenticated = true+ })+ const { handler, selectRuntimeConfig, setPendingDesktopEnvironmentSetup } = createHandler(+ () => ({+ booting: false,+ busy: false,+ authTransitioning: false,+ isAuthenticated: rendererAuthenticated,+ }),+ undefined,+ logoutForEnvironmentMismatch,+ onSessionNeedsLoad+ )- let liveSessionAuthenticated = true- let rendererAuthenticated = true- const clearSessionToken = vi.fn(async () => {- throw new Error('secure storage unavailable')- })- const logoutForEnvironmentMismatch = vi.fn(async () => {- liveSessionAuthenticated = false- try {- await clearSessionToken()- } catch {- // Mirrors handleLogout: report the error and resolve without refreshing auth state.- }- })- const onSessionNeedsLoad = vi.fn(async () => {- rendererAuthenticated = liveSessionAuthenticated- })- const { handler, selectRuntimeConfig, setPendingDesktopEnvironmentSetup } = createHandler(- () => ({- booting: false,- busy: false,- authTransitioning: false,- isAuthenticated: rendererAuthenticated,- }),- undefined,- logoutForEnvironmentMismatch,- onSessionNeedsLoad- )+ await handler({+ ...targetEnvironment,+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,+ })- await handler({ ...targetEnvironment, externalRestApiBaseUrl })-- expect(clearSessionToken).toHaveBeenCalledOnce()- expect(onSessionNeedsLoad).toHaveBeenCalledWith({ preserveNav: true })- expect(rendererAuthenticated).toBe(false)- if (action === 'select') {- expect(selectRuntimeConfig).toHaveBeenCalledWith(savedTarget.id)- expect(setPendingDesktopEnvironmentSetup).toHaveBeenLastCalledWith(null)- } else {- expect(selectRuntimeConfig).not.toHaveBeenCalled()- expect(setPendingDesktopEnvironmentSetup).toHaveBeenLastCalledWith({- ...targetEnvironment,- externalRestApiBaseUrl,- rpcProxyBaseUrl: '',- })- }- }- )+ expect(clearSessionToken).toHaveBeenCalledOnce()+ expect(onSessionNeedsLoad).toHaveBeenCalledWith({ preserveNav: true })+ expect(rendererAuthenticated).toBe(true)+ expect(selectRuntimeConfig).not.toHaveBeenCalled()+ expect(setPendingDesktopEnvironmentSetup).toHaveBeenLastCalledWith(null)+ expect(setPendingDesktopEnvironmentSetup).not.toHaveBeenCalledWith(+ expect.objectContaining({ externalRestApiBaseUrl: expect.any(String) })+ )+ })it('keeps the current environment when a failed logout leaves the live session active', async () => {let rendererAuthenticated = trueconst logoutForEnvironmentMismatch = vi.fn(async () => {// handleLogout reports a failed logout and resolves; the live session remains active.+ return null})const onSessionNeedsLoad = vi.fn(async () => {rendererAuthenticated = true@@ -305,12 +297,97 @@ describe('Desktop environment handoff concurrency', () => {expect(setPendingDesktopEnvironmentSetup).toHaveBeenCalledWith(null)})+ it.each([+ {+ targetKind: 'saved target',+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,+ loginOutcome: 'starts',+ loginState: { busy: true, authTransitioning: true, isAuthenticated: false },+ },+ {+ targetKind: 'saved target',+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,+ loginOutcome: 'completes',+ loginState: { busy: false, authTransitioning: false, isAuthenticated: true },+ },+ {+ targetKind: 'new target',+ externalRestApiBaseUrl: 'https://new-api.example.test',+ loginOutcome: 'starts',+ loginState: { busy: true, authTransitioning: true, isAuthenticated: false },+ },+ {+ targetKind: 'new target',+ externalRestApiBaseUrl: 'https://new-api.example.test',+ loginOutcome: 'completes',+ loginState: { busy: false, authTransitioning: false, isAuthenticated: true },+ },+ ])(+ 'does not continue toward a $targetKind when a newer login $loginOutcome during the second config read',+ async ({ externalRestApiBaseUrl, loginState }) => {+ let sessionGeneration = 0+ let authState = {+ booting: false,+ busy: false,+ authTransitioning: false,+ isAuthenticated: true,+ }+ let refreshCount = 0+ let finishSecondRefresh!: () => void+ let reportSecondRefreshStarted!: () => void+ const secondRefreshStarted = new Promise<void>(resolve => {+ reportSecondRefreshStarted = resolve+ })+ const runtimeConfigState = await runtimeConfigModule!.getDesktopRuntimeConfigState()+ const refreshRuntimeConfigState = () => {+ refreshCount += 1+ if (refreshCount === 1) return Promise.resolve(runtimeConfigState)+ return new Promise<typeof runtimeConfigState>(resolve => {+ finishSecondRefresh = () => resolve(runtimeConfigState)+ reportSecondRefreshStarted()+ })+ }+ const logoutForEnvironmentMismatch = vi.fn(async () => {+ sessionGeneration += 1+ authState = { ...authState, isAuthenticated: false }+ return sessionGeneration+ })+ const onSessionNeedsLoad = vi.fn(async () => {})+ const { handler, selectRuntimeConfig, setPendingDesktopEnvironmentSetup } = createHandler(+ () => authState,+ refreshRuntimeConfigState,+ logoutForEnvironmentMismatch,+ onSessionNeedsLoad,+ async () => sessionGeneration+ )++ const handling = handler({ ...targetEnvironment, externalRestApiBaseUrl })+ await secondRefreshStarted+ sessionGeneration += 1+ authState = { ...authState, ...loginState }+ finishSecondRefresh()+ await handling++ expect(selectRuntimeConfig).not.toHaveBeenCalled()+ expect(setPendingDesktopEnvironmentSetup).toHaveBeenCalledWith(null)+ expect(setPendingDesktopEnvironmentSetup).not.toHaveBeenCalledWith(+ expect.objectContaining({ externalRestApiBaseUrl })+ )+ expect(onSessionNeedsLoad).not.toHaveBeenCalled()+ }+ )+it('keeps the first environment link when another arrives during verification', async () => {const finishRefreshes: Array<() => void> = []const runtimeConfigState = await runtimeConfigModule!.getDesktopRuntimeConfigState()+ let reportRefreshStarted!: () => void+ const refreshStarted = new Promise<void>(resolve => {+ reportRefreshStarted = resolve+ })const refreshRuntimeConfigState = () =>new Promise<typeof runtimeConfigState>(resolve => {finishRefreshes.push(() => resolve(runtimeConfigState))+ reportRefreshStarted()})const { handler } = createHandler(() => ({ booting: false, busy: false, authTransitioning: false, isAuthenticated: false }),@@ -322,6 +399,7 @@ describe('Desktop environment handoff concurrency', () => {externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,})const second = handler(otherEnvironment)+ await refreshStartedfinishRefreshes.forEach(finishRefresh => finishRefresh())await Promise.all([first, second])@@ -385,7 +463,7 @@ describe('Desktop environment REST endpoint matching', () => {externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,})- expect(selectRuntimeConfig).toHaveBeenCalledWith(savedTarget.id)+ expect(selectRuntimeConfig).toHaveBeenCalledWith(savedTarget.id, 0)expect(setPendingDesktopEnvironmentSetup).toHaveBeenCalledWith(null)})@@ -406,7 +484,7 @@ describe('Desktop environment REST endpoint matching', () => {})const finalState = await runtimeConfigModule!.getDesktopRuntimeConfigState()- expect(selectRuntimeConfig).toHaveBeenCalledWith(savedTarget.id)+ expect(selectRuntimeConfig).toHaveBeenCalledWith(savedTarget.id, 0)expect(setPendingDesktopEnvironmentSetup).toHaveBeenCalledWith(null)expect(finalState.options).toHaveLength(state.options.length)expect(finalState.currentConfig?.externalRestApiBaseUrl).toBe(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.tsxindex fb244edd4..b73a9810d 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@@ -10,12 +10,14 @@ import { useAuthController } from '../useAuthController'const mocks = vi.hoisted(() => ({clearQueryCache: vi.fn(),getRuntimeConfigState: vi.fn(),+ getSessionGeneration: vi.fn(),logoutForEnvironmentMismatch: vi.fn(),onDesktopEnvironmentSetup: vi.fn(),onDesktopSetupToken: vi.fn(),onExternalLogout: vi.fn(),saveRuntimeConfig: vi.fn(),selectRuntimeConfig: vi.fn(),+ selectRuntimeConfigForHandoff: vi.fn(),setStatus: vi.fn(),loadSession: vi.fn(),}))@@ -49,6 +51,7 @@ let setBootingForTest: ((value: boolean) => void) | null = nulllet setAuthenticatedForTest: ((value: boolean) => void) | null = nulllet runtimeConfigModule: typeof import('../../../../../src/config') | null = nulllet runtimeConfigDirectory = ''+let nativeSessionGeneration = 0const originalOnboardingPreview = process.env.EVENFIRE_ONBOARDING_PREVIEWfunction Probe() {@@ -103,6 +106,7 @@ beforeEach(async () => {setAuthenticatedForTest = nullruntimeConfigModule = nulldelete process.env.EVENFIRE_ONBOARDING_PREVIEW+ nativeSessionGeneration = 0runtimeConfigDirectory = await fsp.mkdtemp(path.join(os.tmpdir(), 'evenfire-desktop-env-test-'))vi.doUnmock('electron')vi.resetModules()@@ -129,9 +133,25 @@ beforeEach(async () => {await runtimeConfigModule!.selectDesktopRuntimeConfigOption(optionId)return runtimeConfigModule!.getDesktopRuntimeConfigState()})+ mocks.getSessionGeneration.mockImplementation(async () => nativeSessionGeneration)+ mocks.selectRuntimeConfigForHandoff.mockImplementation(+ async (optionId: string, expectedSessionGeneration: number) => {+ if (expectedSessionGeneration !== nativeSessionGeneration) {+ throw new Error('stale_session_generation')+ }+ await runtimeConfigModule!.selectDesktopRuntimeConfigOption(optionId)+ nativeSessionGeneration += 1+ return {+ runtimeConfigState: await runtimeConfigModule!.getDesktopRuntimeConfigState(),+ sessionGeneration: nativeSessionGeneration,+ }+ }+ )mocks.loadSession.mockImplementation(async () => setBootingForTest?.(false))mocks.logoutForEnvironmentMismatch.mockImplementation(async () => {setAuthenticatedForTest?.(false)+ nativeSessionGeneration += 1+ return nativeSessionGeneration})mocks.onDesktopSetupToken.mockReturnValue(() => undefined)mocks.onExternalLogout.mockReturnValue(() => undefined)@@ -146,8 +166,10 @@ beforeEach(async () => {auth: {...window.clerum?.auth,getRuntimeConfigState: mocks.getRuntimeConfigState,+ getSessionGeneration: mocks.getSessionGeneration,saveRuntimeConfig: mocks.saveRuntimeConfig,selectRuntimeConfig: mocks.selectRuntimeConfig,+ selectRuntimeConfigForHandoff: mocks.selectRuntimeConfigForHandoff,onDesktopEnvironmentSetup: mocks.onDesktopEnvironmentSetup,onDesktopSetupToken: mocks.onDesktopSetupToken,onExternalLogout: mocks.onExternalLogout,@@ -176,7 +198,7 @@ describe('Desktop environment handoff', () => {externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,})- expect(mocks.selectRuntimeConfig).toHaveBeenCalledWith(targetOptionId)+ expect(mocks.selectRuntimeConfigForHandoff).toHaveBeenCalledWith(targetOptionId, 0)expect(mocks.clearQueryCache).toHaveBeenCalledOnce()expect(mocks.loadSession).toHaveBeenCalledWith({ preserveNav: true })expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')@@ -199,7 +221,7 @@ describe('Desktop environment handoff', () => {externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,})- expect(mocks.selectRuntimeConfig).not.toHaveBeenCalled()+ expect(mocks.selectRuntimeConfigForHandoff).not.toHaveBeenCalled()expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')expect(mocks.setStatus).toHaveBeenCalledWith('Opening Example tenant in Evenfire Desktop.',@@ -228,7 +250,7 @@ describe('Desktop environment handoff', () => {rpcProxyBaseUrl: 'https://rpc.attacker.test',})- expect(mocks.selectRuntimeConfig).toHaveBeenCalledWith(await savedTargetOptionId())+ expect(mocks.selectRuntimeConfigForHandoff).toHaveBeenCalledWith(await savedTargetOptionId(), 0)expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')expect(screen.getByTestId('pending-rpc')).toHaveTextContent('none')expect(@@ -240,7 +262,10 @@ describe('Desktop environment handoff', () => {})it('selects a saved REST profile without saving or rediscovering its RPC when the link omits RPC', async () => {- await runtimeConfigModule!.saveDesktopRuntimeConfig(targetEnvironment)+ await runtimeConfigModule!.saveDesktopRuntimeConfig({+ ...targetEnvironment,+ appName: 'Example base API',+ })const state = await runtimeConfigModule!.getDesktopRuntimeConfigState()const pathBasedTarget = state.options.find(option =>@@ -291,11 +316,11 @@ describe('Desktop environment handoff', () => {expect(finalState.options.find(option => option.id === savedTarget.id)).toMatchObject({externalRestApiBaseUrl: targetEnvironment.externalRestApiBaseUrl,rpcProxyBaseUrl: targetEnvironment.rpcProxyBaseUrl,- appName: targetEnvironment.appName,+ appName: 'Example base API',})expect(serviceInternals.authClient.getDesktopEnvironment).not.toHaveBeenCalled()expect(mocks.saveRuntimeConfig).not.toHaveBeenCalled()- expect(mocks.selectRuntimeConfig).toHaveBeenCalledWith(savedTarget.id)+ expect(mocks.selectRuntimeConfigForHandoff).toHaveBeenCalledWith(savedTarget.id, 0)expect(finalState.activeOptionId).toBe(savedTarget.id)expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')})@@ -468,7 +493,7 @@ describe('Desktop environment handoff', () => {})expect(mocks.logoutForEnvironmentMismatch).toHaveBeenCalledOnce()- expect(mocks.selectRuntimeConfig).toHaveBeenCalledWith(await savedTargetOptionId())+ expect(mocks.selectRuntimeConfigForHandoff).toHaveBeenCalledWith(await savedTargetOptionId(), 1)expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')})@@ -485,7 +510,7 @@ describe('Desktop environment handoff', () => {rpcProxyBaseUrl: localhostOption.rpcProxyBaseUrl,})- expect(mocks.selectRuntimeConfig).not.toHaveBeenCalled()+ expect(mocks.selectRuntimeConfigForHandoff).not.toHaveBeenCalled()expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')expect(mocks.setStatus).toHaveBeenCalledWith(expect.stringMatching(/Localhost.*cannot be opened from a link/i),@@ -503,7 +528,7 @@ describe('Desktop environment handoff', () => {await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))await dispatchDesktopEnvironmentLink()- expect(mocks.selectRuntimeConfig).not.toHaveBeenCalled()+ expect(mocks.selectRuntimeConfigForHandoff).not.toHaveBeenCalled()expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')expect(mocks.setStatus).toHaveBeenCalledWith('Could not verify the desktop environment. Try opening it again.',diff --git a/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts b/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.tsindex 2b8150691..136789c9e 100644--- a/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts+++ b/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts@@ -3,7 +3,11 @@ import {desktopRestEndpointOrigin,sameDesktopRestEndpoint,} from '../../../../src/desktopEnvironmentUrl'-import type { DesktopRuntimeConfig, DesktopRuntimeConfigState } from '../../../../src/types'+import type {+ DesktopRuntimeConfig,+ DesktopRuntimeConfigHandoffSelection,+ DesktopRuntimeConfigState,+} from '../../../../src/types'import type { SetStatusFn } from './types'const LOCALHOST_OPTION_ID = '__localhost__'@@ -22,10 +26,14 @@ type DesktopEnvironmentSetupPayload = {type DesktopEnvironmentSetupHandlerOptions = {getAuthState: () => DesktopEnvironmentHandoffState+ getSessionGeneration: () => Promise<number>refreshRuntimeConfigState: () => Promise<DesktopRuntimeConfigState>- handleSelectRuntimeConfig: (optionId: string) => Promise<DesktopRuntimeConfigState | null>+ handleSelectRuntimeConfig: (+ optionId: string,+ expectedSessionGeneration: number+ ) => Promise<DesktopRuntimeConfigHandoffSelection | null>onSessionNeedsLoad: (options?: { preserveNav?: boolean }) => Promise<void>- logoutForEnvironmentMismatch: () => Promise<void>+ logoutForEnvironmentMismatch: () => Promise<number | null>setPendingDesktopEnvironmentSetup: (config: DesktopRuntimeConfig | null) => voidsetStatus: SetStatusFn}@@ -68,6 +76,7 @@ function isAuthenticationOperationInProgress(state: DesktopEnvironmentHandoffStaexport function createDesktopEnvironmentSetupHandler({getAuthState,+ getSessionGeneration,refreshRuntimeConfigState,handleSelectRuntimeConfig,onSessionNeedsLoad,@@ -76,6 +85,14 @@ export function createDesktopEnvironmentSetupHandler({setStatus,}: DesktopEnvironmentSetupHandlerOptions) {let linkInProgress = false+ const ownsSessionGeneration = async (expectedSessionGeneration: number): Promise<boolean> => {+ try {+ return (await getSessionGeneration()) === expectedSessionGeneration+ } catch {+ setStatus('Could not verify the desktop session. Try opening the link again.', 'error')+ return false+ }+ }const processLink = async ({externalRestApiBaseUrl,@@ -100,11 +117,11 @@ export function createDesktopEnvironmentSetupHandler({return}- let configState: DesktopRuntimeConfigState+ let sessionGeneration: numbertry {- configState = await refreshRuntimeConfigState()+ sessionGeneration = await getSessionGeneration()} catch {- setStatus('Could not verify the desktop environment. Try opening it again.', 'error')+ setStatus('Could not verify the desktop session. Try opening the link again.', 'error')return}@@ -116,6 +133,16 @@ export function createDesktopEnvironmentSetupHandler({return}+ let configState: DesktopRuntimeConfigState+ try {+ configState = await refreshRuntimeConfigState()+ } catch {+ setStatus('Could not verify the desktop environment. Try opening it again.', 'error')+ return+ }++ if (!(await ownsSessionGeneration(sessionGeneration))) return+let restMatches = getDesktopEnvironmentRestMatches(configState,linkedConfig.externalRestApiBaseUrl@@ -140,8 +167,9 @@ export function createDesktopEnvironmentSetupHandler({)if (authState.isAuthenticated && !activeRestEndpointMatches) {setPendingDesktopEnvironmentSetup(null)+ let logoutGeneration: number | nulltry {- await logoutForEnvironmentMismatch()+ logoutGeneration = await logoutForEnvironmentMismatch()} catch (error) {setStatus(`Could not sign out before switching desktop environments: ${error instanceof Error ? error.message : String(error)}`,@@ -149,20 +177,34 @@ export function createDesktopEnvironmentSetupHandler({)return}+ if (logoutGeneration === null) {+ authState = getAuthState()+ if (authState.isAuthenticated && !isAuthenticationOperationInProgress(authState)) {+ try {+ await onSessionNeedsLoad({ preserveNav: true })+ } catch {+ // A failed logout must leave the current environment in place.+ }+ }+ return+ }+ sessionGeneration = logoutGeneration+ if (!(await ownsSessionGeneration(sessionGeneration))) return+authState = getAuthState()+ if (isAuthenticationOperationInProgress(authState)) returnif (authState.isAuthenticated) {try {await onSessionNeedsLoad({ preserveNav: true })} catch {- authState = getAuthState()- if (authState.isAuthenticated) {- setStatus(- 'Could not verify your sign-in state before switching desktop environments.',- 'error'- )- return- }+ if (!(await ownsSessionGeneration(sessionGeneration))) return+ setStatus(+ 'Could not verify your sign-in state before switching desktop environments.',+ 'error'+ )+ return}+ if (!(await ownsSessionGeneration(sessionGeneration))) returnauthState = getAuthState()if (authState.isAuthenticated) return}@@ -172,6 +214,9 @@ export function createDesktopEnvironmentSetupHandler({setStatus('Could not verify the desktop environment. Try opening it again.', 'error')return}+ if (!(await ownsSessionGeneration(sessionGeneration))) return+ authState = getAuthState()+ if (isAuthenticationOperationInProgress(authState) || authState.isAuthenticated) returnrestMatches = getDesktopEnvironmentRestMatches(configState,linkedConfig.externalRestApiBaseUrl@@ -200,8 +245,11 @@ export function createDesktopEnvironmentSetupHandler({if (restMatches.saved.length === 1) {setPendingDesktopEnvironmentSetup(null)- const selectedState = await handleSelectRuntimeConfig(restMatches.saved[0].id)- if (!selectedState) return+ const selection = await handleSelectRuntimeConfig(restMatches.saved[0].id, sessionGeneration)+ if (!selection) return+ if (!(await ownsSessionGeneration(selection.sessionGeneration))) return+ authState = getAuthState()+ if (isAuthenticationOperationInProgress(authState) || authState.isAuthenticated) returntry {await onSessionNeedsLoad({ preserveNav: true })} catch (error) {@@ -223,6 +271,9 @@ export function createDesktopEnvironmentSetupHandler({}// The backend supplies the RPC endpoint after the user confirms this REST API.+ if (!(await ownsSessionGeneration(sessionGeneration))) return+ authState = getAuthState()+ if (isAuthenticationOperationInProgress(authState) || authState.isAuthenticated) returnsetPendingDesktopEnvironmentSetup({ ...linkedConfig, rpcProxyBaseUrl: '' })}diff --git a/desktop-app/ui/src/hooks/domain/useAuthController.ts b/desktop-app/ui/src/hooks/domain/useAuthController.tsindex 34e36ccee..f7c7c8723 100644--- a/desktop-app/ui/src/hooks/domain/useAuthController.ts+++ b/desktop-app/ui/src/hooks/domain/useAuthController.ts@@ -5,6 +5,7 @@ import type {DependencyHealth,DesktopReleaseStatus,DesktopRuntimeConfig,+ DesktopRuntimeConfigHandoffSelection,DesktopRuntimeConfigState,LoginBackendHint,SessionMe,@@ -19,7 +20,7 @@ import type { SetStatusFn } from './types'interface UseAuthControllerParams {setStatus: SetStatusFnonSessionNeedsLoad: (options?: { preserveNav?: boolean }) => Promise<void>- logoutForEnvironmentMismatch: () => Promise<void>+ logoutForEnvironmentMismatch: () => Promise<number | null>}function isInvitationExpiredError(error: unknown) {@@ -122,6 +123,8 @@ export function useAuthController({return state}, [])+ const getSessionGeneration = useCallback(() => window.clerum.auth.getSessionGeneration(), [])+const completeDesktopSetupWith = useCallback(async (nextEmail: string, nextAuthorizationToken: string) => {const normalizedEmail = nextEmail.trim().toLowerCase()@@ -340,28 +343,65 @@ export function useAuthController({}}+ const applySelectedRuntimeConfigState = useCallback(+ (state: DesktopRuntimeConfigState) => {+ // Switching environment (pre-login) must not carry another env's cached+ // queries forward (spec §5.2 P1). The env is bound to login (D4: no switch+ // without logout), so a full clear is sufficient — no per-env query keys.+ desktopQueryClient.clear()+ setRuntimeConfigState(state)+ setDesktopSetupAuthorizationToken('')+ setDesktopSetupStarted(false)+ const selected = state.options.find(option => option.id === state.activeOptionId)+ setStatus(+ selected ? `Environment selected: ${selected.label}.` : 'Environment selected.',+ 'success',+ undefined,+ { global: false, toast: true }+ )+ },+ [setStatus]+ )+const handleSelectRuntimeConfig = useCallback(async (optionId: string): Promise<DesktopRuntimeConfigState | null> => {try {setBusy(true)setBackendSwitchHint(null)const state = await window.clerum.auth.selectRuntimeConfig(optionId)- // Switching environment (pre-login) must not carry another env's cached- // queries forward (spec §5.2 P1). The env is bound to login (D4: no switch- // without logout), so a full clear is sufficient — no per-env query keys.- desktopQueryClient.clear()- setRuntimeConfigState(state)- setDesktopSetupAuthorizationToken('')- setDesktopSetupStarted(false)- const selected = state.options.find(option => option.id === state.activeOptionId)+ applySelectedRuntimeConfigState(state)+ return state+ } catch (error) {setStatus(- selected ? `Environment selected: ${selected.label}.` : 'Environment selected.',- 'success',- undefined,- { global: false, toast: true }+ `Failed to switch environment: ${error instanceof Error ? error.message : String(error)}`,+ 'error')- return state+ return null+ } finally {+ setBusy(false)+ }+ },+ [applySelectedRuntimeConfigState, setStatus]+ )++ const handleSelectRuntimeConfigForHandoff = useCallback(+ async (+ optionId: string,+ expectedSessionGeneration: number+ ): Promise<DesktopRuntimeConfigHandoffSelection | null> => {+ try {+ setBusy(true)+ setBackendSwitchHint(null)+ const selection = await window.clerum.auth.selectRuntimeConfigForHandoff(+ optionId,+ expectedSessionGeneration+ )+ applySelectedRuntimeConfigState(selection.runtimeConfigState)+ return selection} catch (error) {+ if (error instanceof Error && error.message.includes('stale_session_generation')) {+ return null+ }setStatus(`Failed to switch environment: ${error instanceof Error ? error.message : String(error)}`,'error'@@ -371,15 +411,16 @@ export function useAuthController({setBusy(false)}},- [setStatus]+ [applySelectedRuntimeConfigState, setStatus])useEffect(() => {return window.clerum.auth.onDesktopEnvironmentSetup(createDesktopEnvironmentSetupHandler({getAuthState: getDesktopEnvironmentHandoffAuthState,+ getSessionGeneration,refreshRuntimeConfigState,- handleSelectRuntimeConfig,+ handleSelectRuntimeConfig: handleSelectRuntimeConfigForHandoff,onSessionNeedsLoad,logoutForEnvironmentMismatch,setPendingDesktopEnvironmentSetup,@@ -388,7 +429,9 @@ export function useAuthController({)}, [getDesktopEnvironmentHandoffAuthState,+ getSessionGeneration,handleSelectRuntimeConfig,+ handleSelectRuntimeConfigForHandoff,logoutForEnvironmentMismatch,onSessionNeedsLoad,refreshRuntimeConfigState,diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.tsindex 4fe54c645..c1a331441 100644--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@ -182,7 +182,7 @@ export function useAppController() {const onSessionNeedsLoad = useCallback(async (options?: { preserveNav?: boolean }) => {return loadSessionRef.current(options)}, [])- const logoutForEnvironmentMismatchRef = useRef<() => Promise<void>>(async () => undefined)+ const logoutForEnvironmentMismatchRef = useRef<() => Promise<number | null>>(async () => null)const logoutForEnvironmentMismatch = useCallback(() => logoutForEnvironmentMismatchRef.current(),[]@@ -899,7 +899,7 @@ export function useAppController() {loadSessionRef.current = loadSession// ─── Cross-domain: handleLogout ───- const handleLogout = useCallback(async () => {+ const logoutAndGetSessionGeneration = useCallback(async (): Promise<number | null> => {try {auth.setBusy(true)await chat.stopAllActivityStreams()@@ -918,16 +918,18 @@ export function useAppController() {queryClient.clear()activeAuthenticatedSessionIdentityRef.current = nullauthenticatedSessionIdentityRef.current = null- await window.clerum.auth.logout()+ const logoutResult = await window.clerum.auth.logout()chat.resetChat()notif.resetNotifications()fullSetStatus('Logged out.', 'success')await loadSession()+ return logoutResult.sessionGeneration} catch (error) {fullSetStatus(`Logout failed: ${error instanceof Error ? error.message : String(error)}`,'error')+ return null} finally {auth.setBusy(false)}@@ -946,7 +948,10 @@ export function useAppController() {resetWorkflowsData,teamsData.reset,])- logoutForEnvironmentMismatchRef.current = handleLogout+ const handleLogout = useCallback(async (): Promise<void> => {+ await logoutAndGetSessionGeneration()+ }, [logoutAndGetSessionGeneration])+ logoutForEnvironmentMismatchRef.current = logoutAndGetSessionGeneration// ─── Cross-domain: handleOpenAgentWorkspace ───const openAgentWorkspace = useCallback(