Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): r19-l1 defer RPC discovery to auth boundary
Josuéfb8e1553a23d
diff --git a/desktop-app/src/__tests__/appService.runtimeConfigBoundary.integration.test.ts b/desktop-app/src/__tests__/appService.runtimeConfigBoundary.integration.test.tsnew file mode 100644index 000000000..21beea71f--- /dev/null+++ b/desktop-app/src/__tests__/appService.runtimeConfigBoundary.integration.test.ts@@ -0,0 +1,163 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import fs from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { testSessionMe } from '../../testSupport/authTestFixtures.js'++const originalConfigPath = process.env.CLERUM_DESKTOP_CONFIG_PATH+const originalAppData = process.env.APPDATA+let tempDir: string | null = null+let cleanupModules: (() => Promise<void>) | null = null++afterEach(async () => {+ await cleanupModules?.()+ cleanupModules = null+ vi.doUnmock('electron')+ vi.resetModules()+ if (originalConfigPath === undefined) delete process.env.CLERUM_DESKTOP_CONFIG_PATH+ else process.env.CLERUM_DESKTOP_CONFIG_PATH = originalConfigPath+ if (originalAppData === undefined) delete process.env.APPDATA+ else process.env.APPDATA = originalAppData+ if (tempDir) await fs.rm(tempDir, { recursive: true, force: true })+ tempDir = null+})++describe('AppService RPC discovery restore boundary', () => {+ it('migrates real token, chat, and GFS state at the next restore boundary', async () => {+ tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'evenfire-runtime-boundary-'))+ const userDataDir = path.join(tempDir, 'user-data')+ const chatBaseDir = path.join(tempDir, 'chats')+ const configPath = path.join(tempDir, 'runtime-config.json')+ await fs.mkdir(userDataDir, { recursive: true })+ process.env.CLERUM_DESKTOP_CONFIG_PATH = configPath+ delete process.env.APPDATA++ vi.resetModules()+ vi.doMock('electron', () => ({+ app: {+ getPath: vi.fn((name: string) =>+ name === 'appData' ? path.dirname(userDataDir) : userDataDir+ ),+ isPackaged: false,+ isReady: vi.fn(() => true),+ setName: vi.fn(),+ setPath: vi.fn(),+ },+ safeStorage: { isEncryptionAvailable: vi.fn(() => false) },+ }))++ const [{ AppService }, runtimeConfig, chatStoreBinding, { TokenStore }] = await Promise.all([+ import('../appService.js'),+ import('../config.js'),+ import('../chatStoreBinding.js'),+ import('../tokenStore.js'),+ ])+ cleanupModules = async () => {+ chatStoreBinding.unbindChatStore()+ }+ chatStoreBinding.__setChatStoreBaseDirForTests(chatBaseDir)++ const restBaseUrl = 'https://api-a.example.test'+ const rpcBaseUrl = 'https://rpc-discovered.example.test'+ await runtimeConfig.saveDesktopRuntimeConfig({+ externalRestApiBaseUrl: restBaseUrl,+ rpcProxyBaseUrl: '',+ appName: 'Environment A',+ })+ const restOnlyEnvKey = runtimeConfig.getActiveEnvKey()+ const me = testSessionMe()+ const tokenStore = new TokenStore({ isolatedUserDataPath: userDataDir })+ await tokenStore.setSessionToken('synthetic-saved-session-a', restOnlyEnvKey)+ await chatStoreBinding.bindChatStoreForUser(me.id, restOnlyEnvKey, {+ teamId: me.teamId,+ })+ await chatStoreBinding.requireChatStore().createChat('agent-a', 'chat-a')++ const gfsStatePath = path.join(userDataDir, 'gfs-upload-sessions.json')+ const now = new Date().toISOString()+ await fs.writeFile(+ gfsStatePath,+ JSON.stringify({+ version: 2,+ records: [+ {+ version: 2,+ uploadId: 'upload-a',+ filePath: '/payload.bin',+ fileName: 'payload.bin',+ fileSize: 4,+ target: { operation: 'create', parentRid: 'parent-a' },+ name: 'payload.bin',+ session: {+ uploadId: 'upload-a',+ drive: 'main',+ operation: 'create',+ expectedBytes: 4,+ partBytes: 4,+ partCount: 1,+ state: 'uploading',+ contiguousBytes: 0,+ committedBytes: 0,+ committedPartCount: 0,+ activePartCount: 0,+ expiresAt: now,+ },+ scope: {+ ownerId: me.id,+ teamId: me.teamId,+ environmentKey: restOnlyEnvKey,+ baseUrl: restBaseUrl,+ drive: 'main',+ authEpoch: 1,+ },+ status: 'active',+ updatedAt: now,+ },+ ],+ quarantined: [],+ }),+ { mode: 0o600 }+ )++ const service = new AppService() as unknown as {+ authClient: {+ getDesktopEnvironment: ReturnType<typeof vi.fn>+ getMe: ReturnType<typeof vi.fn>+ }+ tokenStore: TokenStore+ initialize: () => Promise<unknown>+ listGfsUploadSessions: (+ drive?: string+ ) => Promise<Array<{ uploadId: string; status: string }>>+ }+ service.tokenStore = tokenStore+ service.authClient = {+ getDesktopEnvironment: vi.fn().mockResolvedValue({+ externalRestApiBaseUrl: restBaseUrl,+ rpcProxyBaseUrl: rpcBaseUrl,+ appName: 'Environment A',+ }),+ getMe: vi.fn().mockResolvedValue(me),+ }++ await expect(service.initialize()).resolves.toMatchObject({ authenticated: true, me })++ const rpcEnvKey = runtimeConfig.getActiveEnvKey()+ expect(runtimeConfig.config.rpcProxyBaseUrl).toBe(rpcBaseUrl)+ expect(rpcEnvKey).not.toBe(restOnlyEnvKey)+ expect(await tokenStore.getSessionToken(rpcEnvKey)).toBe('synthetic-saved-session-a')+ expect(await tokenStore.getSessionToken(restOnlyEnvKey)).toBeNull()+ expect(+ (await chatStoreBinding.requireChatStore().listChats('agent-a')).map(chat => chat.id)+ ).toEqual(['chat-a'])+ await expect(fs.access(path.join(chatBaseDir, restOnlyEnvKey, me.id))).rejects.toMatchObject({+ code: 'ENOENT',+ })+ await expect(+ fs.access(path.join(chatBaseDir, rpcEnvKey, me.id, 'agent-a', 'index.json'))+ ).resolves.toBeUndefined()+ await expect(service.listGfsUploadSessions('main')).resolves.toEqual([+ expect.objectContaining({ uploadId: 'upload-a', status: 'suspended_auth' }),+ ])+ })+})diff --git a/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.ts b/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.tsindex 41f2ca27b..9897b9233 100644--- a/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.ts+++ b/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.ts@@ -15,7 +15,44 @@ type DesktopEnvironmentDiscovery = {}describe('AppService runtime config discovery ownership', () => {- it('rebinds the live session when a retry discovers RPC for its selected REST profile', async () => {+ it('uses RPC discovery completed before the signed-out login result is installed', 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 app = service as unknown as {+ authClient: {+ getDesktopEnvironment: ReturnType<typeof vi.fn>+ googleLogin: ReturnType<typeof vi.fn>+ }+ }+ app.authClient = {+ getDesktopEnvironment: vi.fn().mockResolvedValue({+ externalRestApiBaseUrl: restA,+ rpcProxyBaseUrl: 'https://rpc-discovered.example.test',+ appName: 'Environment A',+ }),+ googleLogin: vi.fn().mockResolvedValue(testLoginResult('session-token-a', me)),+ }++ await service.googleLogin('google-token-a')++ const rpcEnvKey = runtimeConfig.getDesktopRuntimeConfigState().envKey+ const { bindChatStoreForUser } = await import('../chatStoreBinding.js')+ expect(rpcEnvKey).not.toBe(restOnlyEnvKey)+ expect(service.tokenStore.setSessionToken).toHaveBeenCalledWith('session-token-a', rpcEnvKey)+ expect(bindChatStoreForUser).toHaveBeenLastCalledWith(+ me.id,+ rpcEnvKey,+ expect.objectContaining({ legacyEnvKeys: [restOnlyEnvKey] })+ )+ })++ it('defers late RPC discovery until logout and the next login boundary', async () => {const { service, runtimeConfig, restA } = await createNativeCommitTestHarness()await runtimeConfig.saveDesktopRuntimeConfig({externalRestApiBaseUrl: restA,@@ -44,16 +81,22 @@ describe('AppService runtime config discovery ownership', () => {authorityScope: { environmentKey: string }sessionGeneration: number}+ gfsScopeIdentity: { environmentKey: string } | null}app.authClient = {getDesktopEnvironment,- googleLogin: vi.fn().mockResolvedValue(testLoginResult('session-token-a', me)),+ googleLogin: vi+ .fn()+ .mockResolvedValueOnce(testLoginResult('session-token-a', me))+ .mockResolvedValueOnce(testLoginResult('session-token-b', 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()+ const { bindChatStoreForUser } = await import('../chatStoreBinding.js')+ const activeBindingCount = vi.mocked(bindChatStoreForUser).mock.calls.lengthexpect(service.tokenStore.setSessionToken).toHaveBeenCalledWith('session-token-a',restOnlyEnvKey@@ -61,11 +104,29 @@ describe('AppService runtime config discovery ownership', () => {await app.getDependenciesHealth()+ expect(runtimeConfig.getDesktopRuntimeConfigState().envKey).toBe(restOnlyEnvKey)+ expect(runtimeConfig.config.rpcProxyBaseUrl).toBe('')+ expect(service.tokenStore.setSessionToken).toHaveBeenCalledTimes(1)+ expect(vi.mocked(bindChatStoreForUser)).toHaveBeenCalledTimes(activeBindingCount)+ expect(app.getChatDeletionFenceAuthority().authorityScope.environmentKey).toBe(restOnlyEnvKey)+ expect(service.getSessionGeneration()).toBe(generation)+ expect(service.getCachedUserId()).toBe('user-a')+ expect(app.gfsScopeIdentity?.environmentKey).toBe(restOnlyEnvKey)++ await service.logout()+const rpcConfiguredEnvKey = runtimeConfig.getDesktopRuntimeConfigState().envKey- const { bindChatStoreForUser } = await import('../chatStoreBinding.js')expect(rpcConfiguredEnvKey).not.toBe(restOnlyEnvKey)+ expect(runtimeConfig.config.rpcProxyBaseUrl).toBe('https://rpc-discovered.example.test')+ expect(service.tokenStore.clearSessionToken).toHaveBeenCalledWith(+ restOnlyEnvKey,+ expect.any(Object)+ )+ expect(app.gfsScopeIdentity).toBeNull()++ await service.googleLogin('google-token-b')expect(service.tokenStore.setSessionToken).toHaveBeenLastCalledWith(- 'session-token-a',+ 'session-token-b',rpcConfiguredEnvKey)expect(bindChatStoreForUser).toHaveBeenLastCalledWith(@@ -73,14 +134,9 @@ describe('AppService runtime config discovery ownership', () => {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 () => {+ it('defers discovery completed during saved-session restore until logout', async () => {const { service, runtimeConfig, restA } = await createNativeCommitTestHarness()await runtimeConfig.saveDesktopRuntimeConfig({externalRestApiBaseUrl: restA,@@ -88,58 +144,70 @@ describe('AppService runtime config discovery ownership', () => {appName: 'Environment A',})const restOnlyEnvKey = runtimeConfig.getDesktopRuntimeConfigState().envKey- const me = testSessionMe()+ const discovery = deferred<DesktopEnvironmentDiscovery>()+ const discoveryStarted = deferred<void>()+ const restoredMe = deferred<ReturnType<typeof testSessionMe>>()const getDesktopEnvironment = vi.fn()- .mockRejectedValueOnce(new Error('temporary discovery failure'))- .mockResolvedValue({- externalRestApiBaseUrl: restA,- rpcProxyBaseUrl: 'https://rpc-discovered.example.test',- appName: 'Environment A',+ .mockRejectedValueOnce(new Error('startup discovery unavailable'))+ .mockImplementationOnce(() => {+ discoveryStarted.resolve()+ return discovery.promise})+ const getMeStarted = deferred<void>()+ const getMe = vi.fn(() => {+ getMeStarted.resolve()+ return restoredMe.promise+ })+ const me = testSessionMe()const app = service as unknown as {authClient: {getDesktopEnvironment: typeof getDesktopEnvironment- googleLogin: ReturnType<typeof vi.fn>+ getMe: typeof getMehealth: ReturnType<typeof vi.fn>}- rpcClient: { health: ReturnType<typeof vi.fn> }- getDependenciesHealth: () => Promise<unknown>- getChatDeletionFenceAuthority: () => {- authorityScope: { environmentKey: string }- }+ resolveRuntimeConfigIfNeeded: () => Promise<void>+ gfsScopeIdentity: { environmentKey: string } | null}app.authClient = {getDesktopEnvironment,- googleLogin: vi.fn().mockResolvedValue(testLoginResult('session-token-a', me)),+ getMe,health: vi.fn().mockResolvedValue({ status: 'ok' }),}- app.rpcClient = { health: vi.fn().mockResolvedValue({ status: 'ok' }) }+ service.tokenStore.getSessionToken.mockResolvedValue('synthetic-saved-session-a')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 restore = service.getSessionState()+ await getMeStarted.promise+ const discoveryRequest = app.resolveRuntimeConfigIfNeeded()+ await discoveryStarted.promise+ discovery.resolve({+ externalRestApiBaseUrl: restA,+ rpcProxyBaseUrl: 'https://rpc-discovered.example.test',+ appName: 'Environment A',+ })+ await discoveryRequest- const rpcConfiguredEnvKey = runtimeConfig.resolveEnvKey(- restA,- 'https://rpc-discovered.example.test'- )expect(runtimeConfig.getDesktopRuntimeConfigState().envKey).toBe(restOnlyEnvKey)- expect(app.getChatDeletionFenceAuthority().authorityScope.environmentKey).toBe(restOnlyEnvKey)+ expect(runtimeConfig.config.rpcProxyBaseUrl).toBe('')++ restoredMe.resolve(me)+ await expect(restore).resolves.toMatchObject({ authenticated: true, me })+ expect(service.tokenStore.getSessionToken).toHaveBeenCalledWith(restOnlyEnvKey, {+ legacyEnvKeys: [],+ })+ expect(service.tokenStore.setSessionToken).not.toHaveBeenCalled()expect(bindChatStoreForUser).toHaveBeenLastCalledWith('user-a',restOnlyEnvKey,- expect.objectContaining({ legacyEnvKeys: [rpcConfiguredEnvKey] })- )- expect(service.tokenStore.setSessionToken).toHaveBeenLastCalledWith(- 'session-token-a',- restOnlyEnvKey+ expect.objectContaining({ legacyEnvKeys: [] }))- expect(service.getSessionGeneration()).toBe(generation)+ expect(app.gfsScopeIdentity?.environmentKey).toBe(restOnlyEnvKey)expect(service.getCachedUserId()).toBe('user-a')++ await service.logout()+ expect(runtimeConfig.config.rpcProxyBaseUrl).toBe('https://rpc-discovered.example.test')+ expect(app.gfsScopeIdentity).toBeNull()})it('shares a pending discovery for the same profile and REST endpoint', async () => {diff --git a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.tsindex 4db384b73..add3935ca 100644--- a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts+++ b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts@@ -121,6 +121,19 @@ vi.mock('electron', () => ({vi.mock('../config.js', () => ({getActiveEnvKey: () => 'test-env',getActiveLegacyEnvKeys: () => [],+ getDesktopRuntimeConfigState: () => ({+ configured: true,+ isLocalhost: false,+ selectorVisible: false,+ activeOptionId: null,+ currentConfig: {+ externalRestApiBaseUrl: 'http://rest',+ rpcProxyBaseUrl: 'https://rpc.example',+ },+ envKey: 'test-env',+ storagePath: '/tmp/runtime-config.json',+ options: [],+ }),config: {rpcProxyBaseUrl: 'https://rpc.example',externalRestApiBaseUrl: 'http://rest',diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 07435ae67..961eefab0 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -892,7 +892,14 @@ export class AppService {private teamDirectoryCache: TeamDirectoryResult | null = nullprivate teamContextQueue: Promise<void> = Promise.resolve()private restoreSavedSessionInFlight: Promise<SessionState> | null = null+ private restoreSavedSessionReservationStarted = falseprivate runtimeConfigResolutionInFlight = new Map<string, { promise: Promise<void> }>()+ private pendingRuntimeConfigDiscovery: {+ profileId: string | null+ externalRestApiBaseUrl: string+ rpcProxyBaseUrl: string+ appName: string+ } | null = nullprivate savedSessionRestoreAttemptedEnvKey: string | null = nullprivate savedSessionRestoreAttemptedAtMs = 0private interactiveLoginAttempts = 0@@ -1643,6 +1650,7 @@ export class AppService {return await this.restoreSavedSessionInFlight}const restore = (async () => {+ this.restoreSavedSessionReservationStarted = falseawait this.resolveRuntimeConfigIfNeeded().catch(() => undefined)return this.restoreSavedSessionOnce(options)})()@@ -1653,11 +1661,18 @@ export class AppService {// No newer restore can start while this promise is installed, so the// single-flight slot can be cleared unconditionally after it settles.this.restoreSavedSessionInFlight = null+ this.restoreSavedSessionReservationStarted = false+ if (!this.sessionToken && !this.me && this.interactiveLoginAttempts === 0) {+ await this.withNativeAuthEnvironmentCommit(async () => {+ await this.commitPendingRuntimeConfigDiscoveryIfSafe().catch(() => undefined)+ })+ }}}private async restoreSavedSessionOnce(options: { runLaunchMaintenance?: boolean } = {}) {const reservation = await this.withNativeAuthEnvironmentCommit(async () => {+ this.restoreSavedSessionReservationStarted = trueif (this.interactiveLoginAttempts > 0) return nullhydrateDesktopRuntimeConfig()const environment = this.captureAuthEnvironmentBinding()@@ -1738,9 +1753,9 @@ export class AppService {const session = await this.withNativeAuthEnvironmentCommit(async () => {if (!ownsRestore()) return currentSession()this.sessionToken = token- const environmentKey = getActiveEnvKey()+ const environmentKey = reservation.environment.environmentKeyawait bindChatStoreForUser(restoredMe.id, environmentKey, {- legacyEnvKeys: getActiveLegacyEnvKeys(),+ legacyEnvKeys: reservation.legacyEnvKeys,teamId: restoredMe.teamId,})this.me = restoredMe@@ -1754,7 +1769,17 @@ export class AppService {// Persisted uploads are never auto-resumed. The active owner/team/env can// list only its own scoped records and must explicitly resume one, at// which point the record is rebound to this newly activated auth epoch.- this.activateGfsAuthScope()+ const restoredGfsIdentity: DesktopGfsUploadIdentity = {+ ownerId: restoredMe.id,+ teamId: restoredMe.teamId ? String(restoredMe.teamId).trim() : null,+ environmentKey,+ baseUrl: normalizeDesktopUploadBaseUrl(reservation.environment.restBaseUrl),+ }+ this.activateGfsAuthScope(restoredGfsIdentity)+ await this.migrateLegacyDesktopGfsUploadScopes(+ restoredGfsIdentity,+ reservation.legacyEnvKeys+ ).catch(() => undefined)// A successful restore publishes a new auth owner. Invalidate pending// setup and other work prepared against the signed-out generation only// after the restored session and its GFS scope are coherent.@@ -1854,6 +1879,12 @@ export class AppService {this.rpcTokenManager.clear()await this.tokenStore.setSessionToken(result.token, getActiveEnvKey())this.activateGfsAuthScope()+ if (this.gfsScopeIdentity) {+ await this.migrateLegacyDesktopGfsUploadScopes(+ this.gfsScopeIdentity,+ getActiveLegacyEnvKeys()+ ).catch(() => undefined)+ }return { authenticated: true, me: result.me }} finally {releasePrewarm()@@ -2128,6 +2159,9 @@ export class AppService {if (registered) {await this.withNativeAuthEnvironmentCommit(async () => {this.interactiveLoginAttempts = Math.max(0, this.interactiveLoginAttempts - 1)+ if (this.interactiveLoginAttempts === 0 && !this.sessionToken && !this.me) {+ await this.commitPendingRuntimeConfigDiscoveryIfSafe().catch(() => undefined)+ }})}}@@ -2320,6 +2354,9 @@ export class AppService {if (registered) {await this.withNativeAuthEnvironmentCommit(async () => {this.interactiveLoginAttempts = Math.max(0, this.interactiveLoginAttempts - 1)+ if (this.interactiveLoginAttempts === 0 && !this.sessionToken && !this.me) {+ await this.commitPendingRuntimeConfigDiscoveryIfSafe().catch(() => undefined)+ }})}}@@ -2466,62 +2503,65 @@ export class AppService {}await this.withNativeAuthEnvironmentCommit(async () => {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.me- await saveDesktopRuntimeConfig({- // Discovery is scoped to the configured REST endpoint; it may provide- // RPC details but must never switch or overwrite another REST profile.+ await this.applyRuntimeConfigDiscovery({+ profileId: request.environmentBinding.profileId,externalRestApiBaseUrl: request.externalRestApiBaseUrl,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- }+ })+ }++ /** Caller must hold the native auth/environment commit owner. */+ private async applyRuntimeConfigDiscovery(discovery: {+ profileId: string | null+ externalRestApiBaseUrl: string+ rpcProxyBaseUrl: string+ appName: string+ }): Promise<void> {+ this.pendingRuntimeConfigDiscovery = discovery+ hydrateDesktopRuntimeConfig()+ const currentBinding = this.captureAuthEnvironmentBinding()+ if (+ currentBinding.profileId !== discovery.profileId ||+ !sameDesktopRestEndpoint(currentBinding.restBaseUrl, discovery.externalRestApiBaseUrl)+ ) {+ if (this.pendingRuntimeConfigDiscovery === discovery) {+ this.pendingRuntimeConfigDiscovery = null+ }+ return+ }+ if (!isDesktopRuntimeConfigured() || config.rpcProxyBaseUrl?.trim()) {+ if (this.pendingRuntimeConfigDiscovery === discovery) {+ this.pendingRuntimeConfigDiscovery = null}- if (nextEnvKey !== previousEnvKey) this.rpcTokenManager.clear()+ return+ }++ const restoreHasReservedEnvironment =+ this.restoreSavedSessionInFlight !== null && this.restoreSavedSessionReservationStarted+ if (this.sessionToken || this.me || restoreHasReservedEnvironment) {+ return+ }++ const previousEnvKey = getActiveEnvKey()+ await saveDesktopRuntimeConfig({+ // Discovery only enriches the selected profile. Commit it while signed+ // out so the next auth boundary owns token and chat migration.+ externalRestApiBaseUrl: discovery.externalRestApiBaseUrl,+ rpcProxyBaseUrl: discovery.rpcProxyBaseUrl,+ appName: discovery.appName,})+ if (getActiveEnvKey() !== previousEnvKey) this.rpcTokenManager.clear()+ if (this.pendingRuntimeConfigDiscovery === discovery) {+ this.pendingRuntimeConfigDiscovery = null+ }+ }++ /** Caller must hold the native auth/environment commit owner. */+ private async commitPendingRuntimeConfigDiscoveryIfSafe(): Promise<void> {+ const pending = this.pendingRuntimeConfigDiscovery+ if (pending) await this.applyRuntimeConfigDiscovery(pending)}async getDesktopReleaseStatus(): Promise<DesktopReleaseStatus> {@@ -2581,6 +2621,7 @@ export class AppService {throw error}this.clearAuthenticatedSessionState()+ await this.commitPendingRuntimeConfigDiscoveryIfSafe().catch(() => undefined)// 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)@@ -2827,6 +2868,49 @@ export class AppService {})}+ private async migrateLegacyDesktopGfsUploadScopes(+ identity: DesktopGfsUploadIdentity,+ legacyEnvKeys: readonly string[]+ ): Promise<void> {+ const sourceEnvKeys = new Set(+ legacyEnvKeys+ .map(key => String(key || '').trim())+ .filter(key => key && key !== identity.environmentKey)+ )+ if (!sourceEnvKeys.size) return++ await this.enqueueDesktopGfsUploadState(async () => {+ const loaded = await this.loadDesktopGfsUploadState()+ const updatedAt = new Date().toISOString()+ let changed = false+ const records = loaded.state.records.map(record => {+ if (+ !sourceEnvKeys.has(record.scope.environmentKey) ||+ record.scope.ownerId !== identity.ownerId ||+ record.scope.teamId !== identity.teamId ||+ record.scope.baseUrl !== identity.baseUrl ||+ this.hasLiveDesktopGfsUpload(record)+ ) {+ return record+ }+ changed = true+ return {+ ...record,+ scope: {+ ...record.scope,+ environmentKey: identity.environmentKey,+ authEpoch: this.gfsAuthEpoch,+ },+ status: record.status === 'active' ? ('suspended_auth' as const) : record.status,+ updatedAt,+ }+ })+ if (changed || loaded.migrated) {+ await this.writeDesktopGfsUploadState({ ...loaded.state, records })+ }+ })+ }+private async persistDesktopGfsUpload(record: PersistedDesktopGfsUpload): Promise<void> {if (!isPersistedDesktopGfsUpload(record)) {throw new Error('Refusing to persist an invalid GFS upload record')