Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): fence stateless prewarm across auth changes
Alfredo Lopezfb834fcfb699
diff --git a/desktop-app/src/__tests__/appService.prewarm.test.ts b/desktop-app/src/__tests__/appService.prewarm.test.tsindex 4c124a8c0..91d4d4584 100644--- a/desktop-app/src/__tests__/appService.prewarm.test.ts+++ b/desktop-app/src/__tests__/appService.prewarm.test.ts@@ -7,6 +7,8 @@ import { ApiError } from '../httpClient.js'// ── mock dependencies before AppService is imported ──────────────────────────vi.mock('../config.js', () => ({+ getActiveEnvKey: () => 'test-env',+ getActiveLegacyEnvKeys: () => [],config: {rpcProxyBaseUrl: 'http://proxy',externalRestApiBaseUrl: 'http://rest',@@ -258,6 +260,155 @@ describe('AppService.prewarmHost — bounded wake re-emission', () => {infoSpy.mockRestore()})+ it('logout cancels pending re-emissions and does not leak cooldown to the next session', async () => {+ mockPrewarmHost+ .mockResolvedValueOnce({ status: 'wake-requested' })+ .mockResolvedValueOnce({ status: 'active' })+ const svc = makeService()+ vi.spyOn(+ svc as unknown as { suspendDesktopGfsUploadsForAuthBoundary: () => Promise<void> },+ 'suspendDesktopGfsUploadsForAuthBoundary'+ ).mockResolvedValue()++ await expect(svc.prewarmHost('chatllm')).resolves.toEqual({+ requested: true,+ status: 'wake-requested',+ })+ expect(vi.getTimerCount()).toBe(1)++ await svc.logout()++ expect(vi.getTimerCount()).toBe(0)+ await vi.advanceTimersByTimeAsync(30_000)+ expect(mockPrewarmHost).toHaveBeenCalledTimes(1)+ ;(svc as unknown as { sessionToken: string }).sessionToken = 'next-session'+ ;(svc as unknown as { me: unknown }).me = { id: 2, teamId: 'team-2' }+ await expect(svc.prewarmHost('chatllm')).resolves.toEqual({+ requested: true,+ status: 'active',+ })+ expect(mockPrewarmHost).toHaveBeenCalledTimes(2)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('a late prewarm result cannot erase the next session cooldown', async () => {+ const grant = await mockGetOrIssue()+ mockGetOrIssue.mockClear()+ let complete!: (value: typeof grant) => void+ const pending = new Promise<typeof grant>(resolve => {+ complete = resolve+ })+ mockGetOrIssue.mockReturnValueOnce(pending)+ mockPrewarmHost.mockResolvedValue({ status: 'active' })+ const svc = makeService()+ vi.spyOn(+ svc as unknown as { suspendDesktopGfsUploadsForAuthBoundary: () => Promise<void> },+ 'suspendDesktopGfsUploadsForAuthBoundary'+ ).mockResolvedValue()++ const oldAttempt = svc.prewarmHost('chatllm')+ for (let i = 0; i < 10 && mockGetOrIssue.mock.calls.length === 0; i++) await Promise.resolve()+ expect(mockGetOrIssue).toHaveBeenCalledTimes(1)+ await svc.logout()+ ;(svc as unknown as { sessionToken: string }).sessionToken = 'next-session'+ ;(svc as unknown as { me: unknown }).me = { id: 2, teamId: 'team-2' }++ await expect(svc.prewarmHost('chatllm')).resolves.toEqual({+ requested: true,+ status: 'active',+ })+ complete(grant)+ await expect(oldAttempt).resolves.toEqual({ requested: false, skipped: 'auth-changed' })+ await expect(svc.prewarmHost('chatllm')).resolves.toEqual({+ requested: false,+ skipped: 'cooldown',+ })+ expect(mockPrewarmHost).toHaveBeenCalledTimes(1)+ })++ it('a pending explicit team switch blocks prewarm and a failed switch releases the guard', async () => {+ let rejectSwitch!: (error: Error) => void+ const pendingSwitch = new Promise<string>((_resolve, reject) => {+ rejectSwitch = reject+ })+ const svc = makeService()+ vi.spyOn(+ svc as unknown as { switchSessionToTeam: () => Promise<string> },+ 'switchSessionToTeam'+ ).mockReturnValue(pendingSwitch)+ mockPrewarmHost.mockResolvedValue({ status: 'active' })++ const switching = svc.switchTeam('team-2')+ await expect(svc.prewarmHost('chatllm')).resolves.toEqual({+ requested: false,+ skipped: 'auth-changed',+ })+ expect(mockPrewarmHost).not.toHaveBeenCalled()++ rejectSwitch(new Error('switch canceled'))+ await expect(switching).rejects.toThrow('switch canceled')+ await expect(svc.prewarmHost('chatllm')).resolves.toEqual({+ requested: true,+ status: 'active',+ })+ })++ it('a transient session revision does not cancel the bounded wake loop', async () => {+ mockPrewarmHost+ .mockResolvedValueOnce({ status: 'wake-requested' })+ .mockResolvedValueOnce({ status: 'active' })+ const svc = makeService()++ await svc.prewarmHost('chatllm')+ ;(svc as unknown as { sessionGeneration: number }).sessionGeneration += 1+ await vi.advanceTimersByTimeAsync(10_000)++ expect(mockPrewarmHost).toHaveBeenCalledTimes(2)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('a late prior response cannot clear the new session wake loop', async () => {+ let completeOld!: (value: { status: string }) => void+ const pendingOld = new Promise<{ status: string }>(resolve => {+ completeOld = resolve+ })+ mockPrewarmHost+ .mockResolvedValueOnce({ status: 'wake-requested' })+ .mockReturnValueOnce(pendingOld)+ .mockResolvedValueOnce({ status: 'wake-requested' })+ .mockResolvedValueOnce({ status: 'active' })+ const svc = makeService()+ vi.spyOn(+ svc as unknown as { suspendDesktopGfsUploadsForAuthBoundary: () => Promise<void> },+ 'suspendDesktopGfsUploadsForAuthBoundary'+ ).mockResolvedValue()++ await svc.prewarmHost('chatllm')+ await vi.advanceTimersByTimeAsync(10_000)+ expect(mockPrewarmHost).toHaveBeenCalledTimes(2)+ await svc.logout()+ ;(svc as unknown as { sessionToken: string }).sessionToken = 'next-session'+ ;(svc as unknown as { me: unknown }).me = { id: 2, teamId: 'team-2' }+ await svc.prewarmHost('chatllm')++ completeOld({ status: 'active' })+ await Promise.resolve()+ await Promise.resolve()+ const loops = (svc as unknown as { prewarmReemitLoopHostRefs: Set<string> })+ .prewarmReemitLoopHostRefs+ expect(loops.has('chatllm')).toBe(true)+ ;(+ svc as unknown as { prewarmAttemptAtByHostRef: Map<string, number> }+ ).prewarmAttemptAtByHostRef.delete('chatllm')+ await expect(svc.prewarmHost('chatllm')).resolves.toEqual({+ requested: false,+ skipped: 'in-flight',+ })+ await vi.advanceTimersByTimeAsync(10_000)+ expect(mockPrewarmHost).toHaveBeenCalledTimes(4)+ expect(loops.has('chatllm')).toBe(false)+ })+it('immediate 200 or 409 schedules no re-emission at all', async () => {mockPrewarmHost.mockResolvedValueOnce({ status: 'active' })const svc = makeService()diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex f4a64765e..c8f045452 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -900,6 +900,9 @@ export class AppService {private workflowTeamByKey = new Map<string, string>()private readonly prewarmAttemptAtByHostRef = new Map<string, number>()private readonly prewarmReemitLoopHostRefs = new Set<string>()+ private readonly prewarmReemitAbortControllers = new Map<string, AbortController>()+ private prewarmAuthEpoch = 0+ private prewarmAuthTransitionCount = 0private hostStatusStreams = new Map<string,{@@ -1264,6 +1267,7 @@ export class AppService {this.gfsAuthEpoch += 1this.gfsDispatchBlocked = truethis.gfsScopeIdentity = null+ this.cancelPrewarmReemissions()this.stopAllStreams()this.sessionToken = nullthis.me = null@@ -1282,6 +1286,26 @@ export class AppService {this.gfsScopeIdentity = identityOverride ?? (this.me ? desktopGfsUploadIdentity(this.me) : null)}+ private cancelPrewarmReemissions(): void {+ this.prewarmAuthEpoch += 1+ this.prewarmAttemptAtByHostRef.clear()+ this.prewarmReemitLoopHostRefs.clear()+ for (const controller of this.prewarmReemitAbortControllers.values()) controller.abort()+ this.prewarmReemitAbortControllers.clear()+ }++ private beginPrewarmAuthTransition(): () => void {+ this.prewarmAuthTransitionCount += 1+ this.cancelPrewarmReemissions()+ let released = false+ return () => {+ if (released) return+ released = true+ this.cancelPrewarmReemissions()+ this.prewarmAuthTransitionCount -= 1+ }+ }+private currentDesktopGfsUploadScope(driveValue: string | undefined,options: { allowTransientTeamHop?: boolean } = {}@@ -1481,44 +1505,49 @@ export class AppService {token: stringme: SessionMe}): Promise<SessionState> {- const previousToken = this.sessionToken- const previousMe = this.me- const previousGeneration = this.sessionGeneration- const hadAuthenticatedScope = Boolean(previousToken && previousMe)- if (hadAuthenticatedScope) {- try {- await this.suspendDesktopGfsUploadsForAuthBoundary()- } catch (error) {+ const releasePrewarm = this.beginPrewarmAuthTransition()+ try {+ const previousToken = this.sessionToken+ const previousMe = this.me+ const previousGeneration = this.sessionGeneration+ const hadAuthenticatedScope = Boolean(previousToken && previousMe)+ if (hadAuthenticatedScope) {+ try {+ await this.suspendDesktopGfsUploadsForAuthBoundary()+ } catch (error) {+ if (+ this.sessionGeneration === previousGeneration &&+ this.sessionToken === previousToken &&+ this.me === previousMe+ ) {+ this.activateGfsAuthScope()+ }+ throw error+ }if (- this.sessionGeneration === previousGeneration &&- this.sessionToken === previousToken &&- this.me === previousMe+ this.sessionGeneration !== previousGeneration ||+ this.sessionToken !== previousToken ||+ this.me !== previousMe) {- this.activateGfsAuthScope()+ throw new Error('stale_auth_epoch: authenticated scope changed during login replacement')}- throw error- }- if (- this.sessionGeneration !== previousGeneration ||- this.sessionToken !== previousToken ||- this.me !== previousMe- ) {- throw new Error('stale_auth_epoch: authenticated scope changed during login replacement')}+ this.logoutInProgress = false+ this.sessionGeneration += 1+ this.sessionToken = result.token+ this.me = result.me+ await this.bindCurrentChatStore(result.me.id)+ this.accessCatalog = null+ this.teamDirectoryCache = null+ this.workflowApprovalTeamById.clear()+ this.workflowTeamByKey.clear()+ this.rpcTokenManager.clear()+ await this.tokenStore.setSessionToken(result.token, getActiveEnvKey())+ this.activateGfsAuthScope()+ return { authenticated: true, me: result.me }+ } finally {+ releasePrewarm()}- this.logoutInProgress = false- this.sessionGeneration += 1- this.sessionToken = result.token- this.me = result.me- await this.bindCurrentChatStore(result.me.id)- this.accessCatalog = null- this.teamDirectoryCache = null- this.workflowApprovalTeamById.clear()- this.workflowTeamByKey.clear()- this.rpcTokenManager.clear()- await this.tokenStore.setSessionToken(result.token, getActiveEnvKey())- this.activateGfsAuthScope()- return { authenticated: true, me: result.me }}private async completePasswordLogin(email: string, password: string): Promise<SessionState> {@@ -1561,28 +1590,33 @@ export class AppService {}private async applyRuntimeEnvironmentChange(operation: () => Promise<void>): Promise<void> {- const oldEnvKey = getActiveEnvKey()- const oldBaseUrl = normalizeDesktopUploadBaseUrl(config.externalRestApiBaseUrl)- const oldLegacyEnvKeys = getActiveLegacyEnvKeys()- const hadAuthenticatedScope = Boolean(this.sessionToken && this.me)- // 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- if (hadAuthenticatedScope) await this.suspendDesktopGfsUploadsForAuthBoundary()+ const releasePrewarm = this.beginPrewarmAuthTransition()try {- await operation()- } catch (error) {- if (hadAuthenticatedScope && this.sessionToken && this.me) this.activateGfsAuthScope()- throw error- }- const boundaryChanged =- getActiveEnvKey() !== oldEnvKey ||- normalizeDesktopUploadBaseUrl(config.externalRestApiBaseUrl) !== oldBaseUrl- if (boundaryChanged) {- this.clearAuthenticatedSessionState()- await this.tokenStore.clearSessionToken(oldEnvKey, { legacyEnvKeys: oldLegacyEnvKeys })- } else if (hadAuthenticatedScope && this.sessionToken && this.me) {- this.activateGfsAuthScope()+ const oldEnvKey = getActiveEnvKey()+ const oldBaseUrl = normalizeDesktopUploadBaseUrl(config.externalRestApiBaseUrl)+ const oldLegacyEnvKeys = getActiveLegacyEnvKeys()+ const hadAuthenticatedScope = Boolean(this.sessionToken && this.me)+ // 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+ if (hadAuthenticatedScope) await this.suspendDesktopGfsUploadsForAuthBoundary()+ try {+ await operation()+ } catch (error) {+ if (hadAuthenticatedScope && this.sessionToken && this.me) this.activateGfsAuthScope()+ throw error+ }+ const boundaryChanged =+ getActiveEnvKey() !== oldEnvKey ||+ normalizeDesktopUploadBaseUrl(config.externalRestApiBaseUrl) !== oldBaseUrl+ if (boundaryChanged) {+ this.clearAuthenticatedSessionState()+ await this.tokenStore.clearSessionToken(oldEnvKey, { legacyEnvKeys: oldLegacyEnvKeys })+ } else if (hadAuthenticatedScope && this.sessionToken && this.me) {+ this.activateGfsAuthScope()+ }+ } finally {+ releasePrewarm()}}@@ -1924,6 +1958,7 @@ export class AppService {async logout(): Promise<void> {this.logoutInProgress = true+ const releasePrewarm = this.beginPrewarmAuthTransition()try {const envKey = getActiveEnvKey()const legacyEnvKeys = getActiveLegacyEnvKeys()@@ -1934,6 +1969,7 @@ export class AppService {// result must not: the next user of this machine gets nothing of this one's.tryGetPluginSdkRuntime()?.notifySessionChanged(false)} finally {+ releasePrewarm()this.logoutInProgress = false}}@@ -3080,6 +3116,9 @@ export class AppService {async switchTeam(teamId: string): Promise<SessionState> {const targetTeamId = String(teamId || '').trim()if (!targetTeamId) throw new Error('teamId is required')+ // Explicit team changes fence opportunistic wake immediately. A failed+ // switch can safely leave prewarm canceled; the message path remains live.+ const releasePrewarm = this.beginPrewarmAuthTransition()const previousIdentity =this.gfsScopeIdentity ?? (this.me ? desktopGfsUploadIdentity(this.me) : undefined)// Keep the new team token fenced until the old GFS jobs have been@@ -3131,6 +3170,7 @@ export class AppService {tryGetPluginSdkRuntime()?.notifySessionChanged(true)return { authenticated: true, me: this.me }} finally {+ releasePrewarm()releaseTransientHop()}}@@ -3492,6 +3532,10 @@ export class AppService {if (!targetHostRef) {throw new Error('hostRef is required')}+ if (this.prewarmAuthTransitionCount > 0) {+ return { requested: false, skipped: 'auth-changed' }+ }+ const authEpoch = this.prewarmAuthEpochconst now = Date.now()const lastAttemptAt = this.prewarmAttemptAtByHostRef.get(targetHostRef)if (lastAttemptAt !== undefined && now - lastAttemptAt < PREWARM_COOLDOWN_MS) {@@ -3517,14 +3561,23 @@ export class AppService {HOST_WAKEABLE_OPERATION_SCOPES,effectiveHostRefs)+ if (this.prewarmAuthEpoch !== authEpoch || this.prewarmAuthTransitionCount > 0) {+ return { requested: false, skipped: 'auth-changed' }+ }const result = await this.rpcClient.prewarmHost(rpc.token, targetHostRef)- if (result.status === 'wake-requested') {+ if (+ result.status === 'wake-requested' &&+ this.prewarmAuthEpoch === authEpoch &&+ this.prewarmAuthTransitionCount === 0+ ) {// HCC has not acted yet and its watch may have lost the event. Run// the bounded background re-emission tied to THIS catalog-driven// invocation — the renderer never awaits it, and the cooldown gate// (checked above, not refreshed by re-emits) keeps it single-flight.this.prewarmReemitLoopHostRefs.add(targetHostRef)- void this.runPrewarmReemissionLoop(targetHostRef, rpc.token)+ const controller = new AbortController()+ this.prewarmReemitAbortControllers.set(targetHostRef, controller)+ void this.runPrewarmReemissionLoop(targetHostRef, rpc.token, authEpoch, controller.signal)}return { requested: true, status: result.status }} catch (error) {@@ -3535,8 +3588,23 @@ export class AppService {}/** Injectable so tests stay deterministic; fake timers advance it. */- private prewarmReemitDelay = (ms: number): Promise<void> =>- new Promise(resolve => setTimeout(resolve, ms))+ private prewarmReemitDelay = (ms: number, signal?: AbortSignal): Promise<void> =>+ new Promise(resolve => {+ if (signal?.aborted) {+ resolve()+ return+ }+ const timer = setTimeout(() => {+ signal?.removeEventListener('abort', abort)+ resolve()+ }, ms)+ const abort = () => {+ clearTimeout(timer)+ signal?.removeEventListener('abort', abort)+ resolve()+ }+ signal?.addEventListener('abort', abort, { once: true })+ })/*** Bounded background wake re-emission (see PREWARM_REEMIT_* constants).@@ -3548,10 +3616,16 @@ export class AppService {* the cooldown window. Deliberately NOT reachable from the host status* stream lifecycle — the anti-flap invariant is unchanged.*/- private async runPrewarmReemissionLoop(hostRef: string, rpcToken: string): Promise<void> {+ private async runPrewarmReemissionLoop(+ hostRef: string,+ rpcToken: string,+ authEpoch: number,+ signal: AbortSignal+ ): Promise<void> {try {for (let attempt = 1; attempt <= PREWARM_REEMIT_MAX_ATTEMPTS; attempt++) {- await this.prewarmReemitDelay(PREWARM_REEMIT_INTERVAL_MS)+ await this.prewarmReemitDelay(PREWARM_REEMIT_INTERVAL_MS, signal)+ if (signal.aborted || this.prewarmAuthEpoch !== authEpoch) returnconst result = await this.rpcClient.prewarmHost(rpcToken, hostRef)console.info(`[AppService] prewarmHost re-emit host=${hostRef} attempt=${attempt} status=${result.status}`@@ -3567,7 +3641,10 @@ export class AppService {const message = error instanceof Error ? error.message : String(error)console.warn(`[AppService] prewarmHost re-emit failed host=${hostRef}: ${message}`)} finally {- this.prewarmReemitLoopHostRefs.delete(hostRef)+ if (this.prewarmReemitAbortControllers.get(hostRef)?.signal === signal) {+ this.prewarmReemitLoopHostRefs.delete(hostRef)+ this.prewarmReemitAbortControllers.delete(hostRef)+ }}}diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.tsindex 263e0d3fc..4e37addbb 100644--- a/desktop-app/src/types.ts+++ b/desktop-app/src/types.ts@@ -755,15 +755,16 @@ export type HostRuntimeHealth = {* 409 `not-stateless`). `skipped: 'cooldown'` means a recent attempt for the* same hostRef suppressed the HTTP call entirely; `skipped: 'in-flight'`* means that attempt's bounded re-emission loop is still running (structural- * single-loop-per-host guarantee). `error` carries the failure- * message for any other outcome — the caller treats prewarm as+ * single-loop-per-host guarantee). `skipped: 'auth-changed'` means the+ * authenticated owner changed or is changing before a wake can be issued.+ * `error` carries the failure message for any other outcome — the caller treats prewarm as* fire-and-forget, so failures surface here (and in main-process logs), never* as a thrown error.*/export type PrewarmHostResult = {requested: booleanstatus?: string- skipped?: 'cooldown' | 'in-flight'+ skipped?: 'cooldown' | 'in-flight' | 'auth-changed'error?: string}