Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): migrate session after late RPC discovery (R17-L5)
Josué5032172cd9be
diff --git a/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.ts b/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.tsindex 96317254a..41f2ca27b 100644--- a/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.ts+++ b/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.ts@@ -4,6 +4,7 @@ import {createNativeCommitTestHarness,deferred,} from '../../testSupport/appService.nativeCommitTestHarness.js'+import { testLoginResult, testSessionMe } from '../../testSupport/authTestFixtures.js'afterEach(cleanupNativeCommitTestHarness)@@ -14,6 +15,133 @@ type DesktopEnvironmentDiscovery = {}describe('AppService runtime config discovery ownership', () => {+ it('rebinds the live session when a retry discovers RPC for its selected REST profile', async () => {+ const { service, runtimeConfig, restA } = await createNativeCommitTestHarness()+ await runtimeConfig.saveDesktopRuntimeConfig({+ externalRestApiBaseUrl: restA,+ rpcProxyBaseUrl: '',+ appName: 'Environment A',+ })+ const restOnlyEnvKey = runtimeConfig.getDesktopRuntimeConfigState().envKey+ const me = testSessionMe()+ const getDesktopEnvironment = vi+ .fn()+ .mockRejectedValueOnce(new Error('temporary discovery failure'))+ .mockResolvedValue({+ externalRestApiBaseUrl: restA,+ rpcProxyBaseUrl: 'https://rpc-discovered.example.test',+ appName: 'Environment A',+ })+ const app = service as unknown as {+ authClient: {+ getDesktopEnvironment: typeof getDesktopEnvironment+ googleLogin: ReturnType<typeof vi.fn>+ health: ReturnType<typeof vi.fn>+ }+ rpcClient: { health: ReturnType<typeof vi.fn> }+ getDependenciesHealth: () => Promise<unknown>+ getChatDeletionFenceAuthority: () => {+ authorityScope: { environmentKey: string }+ sessionGeneration: number+ }+ }+ app.authClient = {+ getDesktopEnvironment,+ googleLogin: vi.fn().mockResolvedValue(testLoginResult('session-token-a', me)),+ health: vi.fn().mockResolvedValue({ status: 'ok' }),+ }+ app.rpcClient = { health: vi.fn().mockResolvedValue({ status: 'ok' }) }++ await service.googleLogin('google-token-a')+ const generation = service.getSessionGeneration()+ expect(service.tokenStore.setSessionToken).toHaveBeenCalledWith(+ 'session-token-a',+ restOnlyEnvKey+ )++ await app.getDependenciesHealth()++ const rpcConfiguredEnvKey = runtimeConfig.getDesktopRuntimeConfigState().envKey+ const { bindChatStoreForUser } = await import('../chatStoreBinding.js')+ expect(rpcConfiguredEnvKey).not.toBe(restOnlyEnvKey)+ expect(service.tokenStore.setSessionToken).toHaveBeenLastCalledWith(+ 'session-token-a',+ rpcConfiguredEnvKey+ )+ expect(bindChatStoreForUser).toHaveBeenLastCalledWith(+ 'user-a',+ rpcConfiguredEnvKey,+ expect.objectContaining({ legacyEnvKeys: [restOnlyEnvKey] })+ )+ expect(app.getChatDeletionFenceAuthority().authorityScope.environmentKey).toBe(+ rpcConfiguredEnvKey+ )+ expect(service.getSessionGeneration()).toBe(generation)+ expect(service.getCachedUserId()).toBe('user-a')+ })++ it('rolls back RPC metadata when a live session chat binding cannot migrate', async () => {+ const { service, runtimeConfig, restA } = await createNativeCommitTestHarness()+ await runtimeConfig.saveDesktopRuntimeConfig({+ externalRestApiBaseUrl: restA,+ rpcProxyBaseUrl: '',+ appName: 'Environment A',+ })+ const restOnlyEnvKey = runtimeConfig.getDesktopRuntimeConfigState().envKey+ const me = testSessionMe()+ const getDesktopEnvironment = vi+ .fn()+ .mockRejectedValueOnce(new Error('temporary discovery failure'))+ .mockResolvedValue({+ externalRestApiBaseUrl: restA,+ rpcProxyBaseUrl: 'https://rpc-discovered.example.test',+ appName: 'Environment A',+ })+ const app = service as unknown as {+ authClient: {+ getDesktopEnvironment: typeof getDesktopEnvironment+ googleLogin: ReturnType<typeof vi.fn>+ health: ReturnType<typeof vi.fn>+ }+ rpcClient: { health: ReturnType<typeof vi.fn> }+ getDependenciesHealth: () => Promise<unknown>+ getChatDeletionFenceAuthority: () => {+ authorityScope: { environmentKey: string }+ }+ }+ app.authClient = {+ getDesktopEnvironment,+ googleLogin: vi.fn().mockResolvedValue(testLoginResult('session-token-a', me)),+ health: vi.fn().mockResolvedValue({ status: 'ok' }),+ }+ app.rpcClient = { health: vi.fn().mockResolvedValue({ status: 'ok' }) }+ const { bindChatStoreForUser } = await import('../chatStoreBinding.js')++ await service.googleLogin('google-token-a')+ const generation = service.getSessionGeneration()+ vi.mocked(bindChatStoreForUser).mockRejectedValueOnce(new Error('chat migration failed'))++ await expect(app.getDependenciesHealth()).resolves.toBeDefined()++ const rpcConfiguredEnvKey = runtimeConfig.resolveEnvKey(+ restA,+ 'https://rpc-discovered.example.test'+ )+ expect(runtimeConfig.getDesktopRuntimeConfigState().envKey).toBe(restOnlyEnvKey)+ expect(app.getChatDeletionFenceAuthority().authorityScope.environmentKey).toBe(restOnlyEnvKey)+ expect(bindChatStoreForUser).toHaveBeenLastCalledWith(+ 'user-a',+ restOnlyEnvKey,+ expect.objectContaining({ legacyEnvKeys: [rpcConfiguredEnvKey] })+ )+ expect(service.tokenStore.setSessionToken).toHaveBeenLastCalledWith(+ 'session-token-a',+ restOnlyEnvKey+ )+ expect(service.getSessionGeneration()).toBe(generation)+ expect(service.getCachedUserId()).toBe('user-a')+ })+it('shares a pending discovery for the same profile and REST endpoint', async () => {const { service, runtimeConfig, restA } = await createNativeCommitTestHarness()await runtimeConfig.saveDesktopRuntimeConfig({diff --git a/desktop-app/src/__tests__/tokenStore.test.ts b/desktop-app/src/__tests__/tokenStore.test.tsindex 26793f821..298f4cb93 100644--- a/desktop-app/src/__tests__/tokenStore.test.ts+++ b/desktop-app/src/__tests__/tokenStore.test.ts@@ -94,6 +94,17 @@ describe('TokenStore per-environment slots (spec §5.2)', () => {expect(await store.getSessionToken(ENV_A)).toBeNull()})+ it('can clear one environment without touching the legacy global token slot', async () => {+ keychain.set(keyOf(SERVICE, LEGACY_ACCOUNT), 'legacy-token')+ await new TokenStore().setSessionToken('rest-only-token', ENV_A)+ const store = new TokenStore()++ await store.clearSessionToken(ENV_A, { clearLegacyGlobalSlot: false })++ expect(keychain.has(keyOf(SERVICE, `${LEGACY_ACCOUNT}::${ENV_A}`))).toBe(false)+ expect(keychain.get(keyOf(SERVICE, LEGACY_ACCOUNT))).toBe('legacy-token')+ })+it('migrates a legacy global-slot token into the active env slot, then deletes it', async () => {// Simulate a pre-per-env install: token in the single global account.keychain.set(keyOf(SERVICE, LEGACY_ACCOUNT), 'legacy-tok')diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex a3d0478c1..cb4b53157 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -2437,6 +2437,14 @@ export class AppService {this.assertAuthEnvironmentBinding(request.environmentBinding)hydrateDesktopRuntimeConfig()if (!isDesktopRuntimeConfigured() || config.rpcProxyBaseUrl?.trim()) return+ const previousConfig = {+ externalRestApiBaseUrl: config.externalRestApiBaseUrl,+ rpcProxyBaseUrl: config.rpcProxyBaseUrl,+ appName: config.appName,+ }+ const previousEnvKey = getActiveEnvKey()+ const sessionToken = this.sessionToken+ const sessionUser = this.meawait saveDesktopRuntimeConfig({// Discovery is scoped to the configured REST endpoint; it may provide// RPC details but must never switch or overwrite another REST profile.@@ -2444,6 +2452,44 @@ export class AppService {rpcProxyBaseUrl: discovered.rpcProxyBaseUrl,appName: discovered.appName || request.appName,})+ const nextEnvKey = getActiveEnvKey()+ if (+ nextEnvKey !== previousEnvKey &&+ sessionToken &&+ sessionUser &&+ this.sessionToken === sessionToken &&+ this.me === sessionUser+ ) {+ try {+ await this.tokenStore.setSessionToken(sessionToken, nextEnvKey)+ await bindChatStoreForUser(sessionUser.id, nextEnvKey, {+ legacyEnvKeys: [previousEnvKey],+ teamId: this.chatStoreTeamId(),+ })+ await this.tokenStore.clearSessionToken(previousEnvKey, {+ clearLegacyGlobalSlot: false,+ })+ } catch (migrationError) {+ try {+ await saveDesktopRuntimeConfig(previousConfig)+ await this.tokenStore.setSessionToken(sessionToken, previousEnvKey)+ await this.tokenStore.clearSessionToken(nextEnvKey, {+ clearLegacyGlobalSlot: false,+ })+ await bindChatStoreForUser(sessionUser.id, previousEnvKey, {+ legacyEnvKeys: [nextEnvKey],+ teamId: this.chatStoreTeamId(),+ })+ } catch (rollbackError) {+ throw new AggregateError(+ [migrationError, rollbackError],+ 'RPC discovery session migration and rollback failed'+ )+ }+ throw migrationError+ }+ }+ if (nextEnvKey !== previousEnvKey) this.rpcTokenManager.clear()})}diff --git a/desktop-app/src/tokenStore.ts b/desktop-app/src/tokenStore.tsindex 8d728fa4a..001528cf4 100644--- a/desktop-app/src/tokenStore.ts+++ b/desktop-app/src/tokenStore.ts@@ -399,7 +399,7 @@ export class TokenStore {async clearSessionToken(envKey: string,- options: { legacyEnvKeys?: readonly string[] } = {}+ options: { legacyEnvKeys?: readonly string[]; clearLegacyGlobalSlot?: boolean } = {}): Promise<void> {assertEnvKey(envKey)if (this.isolatedUserDataPath !== undefined) await this.verifiedStorageBase()@@ -424,9 +424,11 @@ export class TokenStore {for (const scopedEnvKey of scopedEnvKeys) {await deleteKeychainPassword(accountFor(scopedEnvKey))}- // Best-effort cleanup of the legacy global slot so it can't be migrated- // into another environment later.- await deleteKeychainPassword(LEGACY_ACCOUNT)+ if (options.clearLegacyGlobalSlot !== false) {+ // Best-effort cleanup of the legacy global slot so it can't be migrated+ // into another environment later.+ await deleteKeychainPassword(LEGACY_ACCOUNT)+ }}// Always clean up file-based storage regardless of keychain result,// since prior versions may have written both stores.@@ -444,14 +446,17 @@ export class TokenStore {await Promise.all(scopedFileRemovals)return}- await Promise.all([- ...scopedFileRemovals,- legacyEncryptedFilePath()- .then(file => fs.unlink(file))- .catch(() => {}),- legacyFilePath()- .then(file => fs.unlink(file))- .catch(() => {}),- ])+ const legacyGlobalFileRemovals =+ options.clearLegacyGlobalSlot === false+ ? []+ : [+ legacyEncryptedFilePath()+ .then(file => fs.unlink(file))+ .catch(() => {}),+ legacyFilePath()+ .then(file => fs.unlink(file))+ .catch(() => {}),+ ]+ await Promise.all([...scopedFileRemovals, ...legacyGlobalFileRemovals])}}