Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): r6-h5 bind stream to committed session
Josuéa05bee22e0b6
diff --git a/desktop-app/src/__tests__/appService.entityChanges.test.ts b/desktop-app/src/__tests__/appService.entityChanges.test.tsindex 487979a6e..2f0b91ec1 100644--- a/desktop-app/src/__tests__/appService.entityChanges.test.ts+++ b/desktop-app/src/__tests__/appService.entityChanges.test.ts@@ -24,6 +24,7 @@ function setSyntheticSessionToken(service: object, value: string): void {if (!Reflect.set(service, ['session', 'Token'].join(''), value)) {throw new Error('Unable to set synthetic session fixture')}+ Reflect.set(service, 'entityChangeSessionToken', value)}describe('AppService entity-change fan-out', () => {@@ -141,7 +142,7 @@ describe('AppService.startEntityChangeStream session expiry', () => {service.stopEntityChangeStream('stream-1', 7)})- it('does not reconnect after the server announces session expiry', async () => {+ it('removes dead subscribers after the server announces session expiry', async () => {const service = new AppService() as anysetSyntheticSessionToken(service, 'session-token')service.authClient = {@@ -164,6 +165,141 @@ describe('AppService.startEntityChangeStream session expiry', () => {expect(events.map(event => event.type)).toEqual(['open', 'stream.closing'])expect(service.authClient.openEntityChangeStream).toHaveBeenCalledOnce()+ expect(service.entityChangeSubscribers.size).toBe(0)service.stopEntityChangeStream('stream-1', 7)})++ it('rebinds a stale expired connection once to the newer committed session', async () => {+ const service = new AppService() as any+ setSyntheticSessionToken(service, 'old-session-token')+ const opens: Array<{+ token: string+ cursor: string | null+ onEvent: (event: EntityChangeStreamEvent) => void+ signal: AbortSignal+ }> = []+ service.authClient = {+ openEntityChangeStream: vi.fn((token, cursor, onEvent, signal) => {+ opens.push({ token, cursor, onEvent, signal })+ return new Promise<void>(resolve => {+ signal.addEventListener('abort', () => resolve(), { once: true })+ })+ }),+ }+ service.startEntityChangeStream('stream-1', 7, vi.fn())+ await flushAsyncWork()+ Reflect.set(service, 'entityChangeSessionToken', 'new-committed-session-token')+ Reflect.set(service, 'entityChangeSessionGeneration', 1)++ opens[0]?.onEvent({+ type: 'stream.closing',+ schemaVersion: 1,+ cursor: '00000000-0000-0000-0000-000000000002',+ reason: 'session_expired',+ })+ await flushAsyncWork()++ expect(opens.map(entry => entry.token)).toEqual([+ 'old-session-token',+ 'new-committed-session-token',+ ])+ expect(opens[1]?.cursor).toBeNull()+ expect(service.entityChangeSubscribers.size).toBe(1)+ service.stopEntityChangeStream('stream-1', 7)+ })++ it('does not strand subscribers when expiry is deferred through a transient hop', async () => {+ const service = new AppService() as any+ setSyntheticSessionToken(service, 'committed-session-token')+ let publish!: (event: EntityChangeStreamEvent) => void+ service.authClient = {+ openEntityChangeStream: vi.fn((_token, _cursor, onEvent, signal) => {+ publish = onEvent+ return new Promise<void>(resolve => {+ signal.addEventListener('abort', () => resolve(), { once: true })+ })+ }),+ }+ const events: EntityChangeStreamEvent[] = []+ const releaseTransientHop = service.enterGfsTransientTeamHop()+ service.startEntityChangeStream('stream-1', 7, (event: EntityChangeStreamEvent) => {+ events.push(event)+ })+ await flushAsyncWork()++ publish({+ type: 'stream.closing',+ schemaVersion: 1,+ cursor: '00000000-0000-0000-0000-000000000003',+ reason: 'session_expired',+ })+ await flushAsyncWork()++ expect(events).toEqual([])+ expect(service.entityChangeSubscribers.size).toBe(1)+ releaseTransientHop()+ expect(events.map(event => event.type)).toEqual(['stream.closing'])+ expect(service.entityChangeSubscribers.size).toBe(0)+ })+})++describe('AppService entity-change stream team-context lifecycle', () => {+ it('never reconnects with a transient team token and rebinds after the hop', async () => {+ vi.useFakeTimers()+ vi.spyOn(Math, 'random').mockReturnValue(0)+ const service = new AppService() as any+ setSyntheticSessionToken(service, 'committed-session-token')+ service.me = { id: 'user-1', teamId: 'team-a' }+ service.gfsScopeIdentity = {}+ service.bindCurrentChatStore = vi.fn()+ service.tokenStore = { setSessionToken: vi.fn() }++ const opened: Array<{ token: string; signal: AbortSignal }> = []+ let finishFirstStream!: () => void+ service.authClient = {+ openEntityChangeStream: vi.fn((token, _cursor, _onEvent, signal) => {+ opened.push({ token, signal })+ return new Promise<void>(resolve => {+ if (opened.length === 1) finishFirstStream = resolve+ signal.addEventListener('abort', () => resolve(), { once: true })+ })+ }),+ switchTeam: vi.fn(async (_token, teamId) => ({+ token: teamId === 'team-b' ? 'transient-team-context-token' : 'restored-session-token',+ })),+ getMe: vi.fn(async token => ({+ id: 'user-1',+ teamId: token === 'transient-team-context-token' ? 'team-b' : 'team-a',+ })),+ }++ let finishOperation!: () => void+ const operationGate = new Promise<void>(resolve => {+ finishOperation = resolve+ })+ try {+ service.startEntityChangeStream('stream-1', 7, vi.fn())+ await flushAsyncWork()+ expect(opened[0]?.token).toBe('committed-session-token')++ const teamOperation = service.runWithTeamContext('team-b', async () => operationGate)+ await flushAsyncWork()+ expect(service.sessionToken).toBe('transient-team-context-token')++ finishFirstStream()+ await flushAsyncWork()+ await vi.advanceTimersByTimeAsync(1000)++ expect(opened.map(entry => entry.token)).not.toContain('transient-team-context-token')++ finishOperation()+ await teamOperation+ await flushAsyncWork()+ expect(opened.map(entry => entry.token)).toContain('restored-session-token')+ } finally {+ service.stopEntityChangeStream('stream-1', 7)+ vi.useRealTimers()+ vi.restoreAllMocks()+ }+ })})diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 8f99bf79c..cc55ba96a 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -931,6 +931,9 @@ export class AppService {{ ownerId: number; onEvent: (event: EntityChangeStreamEvent) => void }>()private entityChangeConnectionStop: ((opts?: { silent?: boolean }) => void) | null = null+ private entityChangeSessionToken: string | null = null+ private entityChangeSessionGeneration = 0+ private entityChangeSessionExpiryDeferred = falseprivate entityChangeCursor: string | null = nullprivate progressStreams = new Map<string,@@ -1030,6 +1033,10 @@ export class AppService {this.profileUiBaseUrlCache = nullthis.accessCatalog = nullawait this.tokenStore.setSessionToken(token, getActiveEnvKey())+ if (this.gfsTransientTeamHopDepth === 0) {+ this.updateEntityChangeSessionToken(token)+ this.restartEntityChangeStreamForSessionReplacement()+ }}if (options.refreshMe) {try {@@ -1117,6 +1124,10 @@ export class AppService {if (released) returnreleased = truethis.gfsTransientTeamHopDepth = Math.max(0, this.gfsTransientTeamHopDepth - 1)+ if (this.gfsTransientTeamHopDepth === 0 && this.entityChangeSessionExpiryDeferred) {+ this.entityChangeSessionExpiryDeferred = false+ this.emitEntityChangeSessionExpired()+ }}}@@ -1156,6 +1167,7 @@ export class AppService {let activeToken = originalTokenconst shouldSwitch = originalTeamId !== targetTeamIdconst shouldRestore = Boolean(originalTeamId && shouldSwitch)+ let restoredOriginalTeam = falseconst releaseTransientHop = shouldSwitch ? this.enterGfsTransientTeamHop() : undefinedtry {@@ -1172,6 +1184,7 @@ export class AppService {if (shouldRestore) {try {await this.switchSessionToTeam(originalTeamId, this.requireSessionToken())+ restoredOriginalTeam = true} catch (restoreError) {if (!operationError) throw restoreErrorconsole.warn(@@ -1180,6 +1193,10 @@ export class AppService {)}}+ if (restoredOriginalTeam && this.sessionToken) {+ this.updateEntityChangeSessionToken(this.sessionToken)+ this.restartEntityChangeStreamForSessionReplacement()+ }}} finally {releaseTransientHop?.()@@ -1250,6 +1267,7 @@ export class AppService {private clearAuthenticatedSessionState(): void {this.sessionGeneration += 1+ this.updateEntityChangeSessionToken(null)this.gfsAuthEpoch += 1this.gfsDispatchBlocked = truethis.gfsScopeIdentity = null@@ -1410,6 +1428,8 @@ export class AppService {return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }}this.me = restoredMe+ this.updateEntityChangeSessionToken(token)+ this.restartEntityChangeStreamForSessionReplacement()this.accessCatalog = nullthis.teamDirectoryCache = nullthis.workflowApprovalTeamById.clear()@@ -1496,6 +1516,7 @@ export class AppService {this.sessionGeneration += 1this.sessionToken = result.tokenthis.me = result.me+ this.updateEntityChangeSessionToken(result.token)this.restartEntityChangeStreamForSessionReplacement()await this.bindCurrentChatStore(result.me.id)this.accessCatalog = null@@ -2777,8 +2798,50 @@ export class AppService {}}+ private updateEntityChangeSessionToken(token: string | null): void {+ if (this.entityChangeSessionToken === token) return+ this.entityChangeSessionToken = token+ this.entityChangeSessionGeneration += 1+ }++ private handleEntityChangeSessionExpiry(connectionGeneration: number): void {+ const hasNewerCommittedSession =+ this.entityChangeSessionGeneration > connectionGeneration &&+ Boolean(this.entityChangeSessionToken)+ if (hasNewerCommittedSession) {+ this.restartEntityChangeStreamForSessionReplacement()+ return+ }++ this.entityChangeConnectionStop?.({ silent: true })+ if (this.gfsTransientTeamHopDepth > 0) {+ this.entityChangeSessionExpiryDeferred = true+ return+ }++ this.emitEntityChangeSessionExpired()+ }++ private emitEntityChangeSessionExpired(): void {+ this.emitEntityChangeEvent({+ type: 'stream.closing',+ schemaVersion: 1,+ cursor: this.entityChangeCursor ?? '00000000-0000-0000-0000-000000000000',+ reason: 'session_expired',+ })+ this.entityChangeSubscribers.clear()+ }+private ensureEntityChangeConnection(): void {if (this.entityChangeConnectionStop || this.entityChangeSubscribers.size === 0) return+ if (+ !this.entityChangeSessionToken &&+ this.sessionToken &&+ this.gfsTransientTeamHopDepth === 0+ ) {+ this.updateEntityChangeSessionToken(this.sessionToken)+ }+ if (!this.entityChangeSessionToken) returnlet closed = falselet abortController: AbortController | null = nulllet retryTimer: NodeJS.Timeout | null = null@@ -2795,36 +2858,33 @@ export class AppService {if (this.entityChangeConnectionStop === stop) this.entityChangeConnectionStop = nullif (!opts?.silent) this.emitEntityChangeEvent({ type: 'closed' })}- const stopForSessionExpiry = () => stop({ silent: true })this.entityChangeConnectionStop = stopconst connect = async () => {if (closed) return+ const connectionToken = this.entityChangeSessionToken+ const connectionGeneration = this.entityChangeSessionGeneration+ if (!connectionToken) returnabortController = new AbortController()try {await this.authClient.openEntityChangeStream(- this.requireSessionToken(),+ connectionToken,this.entityChangeCursor,event => {if (closed) returnif (event.type === 'open') backoffMs = 1000- this.emitEntityChangeEvent(event)if (event.type === 'stream.closing' && event.reason === 'session_expired') {- stopForSessionExpiry()+ this.handleEntityChangeSessionExpiry(connectionGeneration)+ return}+ this.emitEntityChangeEvent(event)},abortController.signal)} catch (error) {if (!closed) {if (error instanceof ApiError && error.status === 401) {- this.emitEntityChangeEvent({- type: 'stream.closing',- schemaVersion: 1,- cursor: this.entityChangeCursor ?? '00000000-0000-0000-0000-000000000000',- reason: 'session_expired',- })- stopForSessionExpiry()+ this.handleEntityChangeSessionExpiry(connectionGeneration)} else {this.emitEntityChangeEvent({type: 'error',@@ -2845,6 +2905,7 @@ export class AppService {}private restartEntityChangeStreamForSessionReplacement(): void {+ this.entityChangeSessionExpiryDeferred = falsethis.entityChangeCursor = nullthis.entityChangeConnectionStop?.({ silent: true })this.ensureEntityChangeConnection()@@ -3015,6 +3076,7 @@ export class AppService {for (const entry of Array.from(this.hostStatusStreams.values())) entry.stop({ silent: true })for (const entry of Array.from(this.notificationStreams.values())) entry.stop({ silent: true })this.entityChangeSubscribers.clear()+ this.entityChangeSessionExpiryDeferred = falsethis.entityChangeConnectionStop?.({ silent: true })this.entityChangeCursor = null}@@ -3223,6 +3285,7 @@ export class AppService {throw error}this.activateGfsAuthScope()+ this.updateEntityChangeSessionToken(this.sessionToken)this.stopAllStreams()// Grants are keyed by userId, not by team, so they carry over — but every// cached org/agents/contexts answer is now about the wrong team. Drop the