Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): r1-h1 drop sandbox-ui effects that land after the session was cleared
Diego Zacarias45207086b16e
diff --git a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.tsindex 3ca9c99d1..72bf951a5 100644--- a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts+++ b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts@@ -1,8 +1,10 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { shell } from 'electron'import { mkdtemp, rm } from 'node:fs/promises'import { tmpdir } from 'node:os'import path from 'node:path'import { AppService } from '../appService.js'+import { __setChatStoreBaseDirForTests, unbindChatStore } from '../chatStoreBinding.js'import { wireMainWindowRendererReadiness } from '../mainWindowReadiness.js'import { _resetPluginSdkRuntimeForTests, initPluginSdkRuntime } from '../pluginSdkRuntime.js'import { _resetPluginSurfacesForTests, resolvePluginSurface } from '../pluginSurfaceRegistry.js'@@ -239,9 +241,18 @@ function shrinkMintBound(toMs = 25) {}const mintResponders = new Map<string, (init?: RequestInit) => Response | Promise<Response>>()+const authorizeUrlResponders = new Map<string, () => Response | Promise<Response>>()const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {const url = String(input instanceof Request ? input.url : input)+ const authorize = /\/api\/v1\/sandbox-ui\/sandbox-recipes\/([^/]+)\/oauth\/authorize-url$/.exec(+ url+ )+ if (authorize) {+ const respond = authorizeUrlResponders.get(decodeURIComponent(authorize[1]!))+ if (!respond) throw new Error(`unexpected authorize-url fetch ${url}`)+ return respond()+ }const match = /\/api\/v1\/sandbox-ui\/sandbox-recipes\/([^/]+)\/session$/.exec(url)if (!match) throw new Error(`unexpected fetch ${url}`)const recipeName = decodeURIComponent(match[1]!)@@ -288,12 +299,15 @@ beforeEach(async () => {electronMocks.views.length = 0electronMocks.sessionObject.cookies.set.mockResolvedValue(undefined)mintResponders.clear()+ authorizeUrlResponders.clear()vi.stubGlobal('fetch', fetchMock)userDataDir = await mkdtemp(path.join(tmpdir(), 'clerum-sandbox-lifecycle-'))})afterEach(async () => {vi.restoreAllMocks()+ unbindChatStore()+ __setChatStoreBaseDirForTests(null)await unmountSandboxUiView()_resetSandboxUiRefreshForTests()_resetPluginSurfacesForTests()@@ -587,7 +601,25 @@ describe('AppService sandbox-ui embed across a session clear', () => {return (response: Response) => answer(response)}- it('an open whose mint lands after logout is torn down with no refresh loop', async () => {+ // Effects observable outside main: a cookie written to a partition, a view+ // created, attached or navigated, a pinned SDK surface, a refresh mint.+ async function expectNothingMountedFor(+ parentWindow: FakeParentWindow,+ service: AppService+ ): Promise<void> {+ // Drain the serial queue so the close queued by the session clear has run.+ await (+ service as unknown as { enqueueSandboxUiLifecycle(op: () => Promise<void>): Promise<void> }+ ).enqueueSandboxUiLifecycle(async () => undefined)+ expect(electronMocks.sessionObject.cookies.set).not.toHaveBeenCalled()+ expect(electronMocks.views).toHaveLength(0)+ expect(parentWindow.contentView.addChildView).not.toHaveBeenCalled()+ expect(getActiveSandboxUi()).toBeNull()+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)+ expect(mintCallsFor('first-app')).toBe(1)+ }++ it('an open whose mint lands after logout installs nothing and rejects', async () => {const onClosed = vi.fn()const service = makeService()initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })@@ -595,22 +627,128 @@ describe('AppService sandbox-ui embed across a session clear', () => {const answerMint = holdMint('first-app')const open = service.openSandboxUi(openArgs('first-app', parentWindow, onClosed))+ const outcome = open.then(+ () => 'opened',+ (error: unknown) => error+ )await vi.waitFor(() => expect(mintCallsFor('first-app')).toBe(1), { timeout: 1_000 })await service.logout()answerMint(mintOk('first-app'))- await open- const mountedView = electronMocks.views[0]- expect(mountedView).toBeDefined()- await vi.waitFor(() => expect(getActiveSandboxUi()).toBeNull(), { timeout: 1_000 })- expect(parentWindow.contentView.removeChildView).toHaveBeenCalledWith(mountedView)- expect(mountedView?.webContents.isDestroyed()).toBe(true)- expect(resolvePluginSurface(mountedView!.webContents.id)).toBeNull()+ const settled = await outcome+ await expectNothingMountedFor(parentWindow, service)+ expect(settled).toMatchObject({ message: expect.stringMatching(/session changed/) })expect(onClosed).not.toHaveBeenCalled()+ })++ it('an open whose mint lands after another user logged in installs nothing and rejects', async () => {+ const service = makeService()+ initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })+ const parentWindow = new FakeParentWindow()+ const answerMint = holdMint('first-app')++ const open = service.openSandboxUi(openArgs('first-app', parentWindow))+ const outcome = open.then(+ () => 'opened',+ (error: unknown) => error+ )+ await vi.waitFor(() => expect(mintCallsFor('first-app')).toBe(1), { timeout: 1_000 })+ await service.logout()+ __setChatStoreBaseDirForTests(userDataDir)+ const authClient = (service as unknown as { authClient: Record<string, unknown> }).authClient+ authClient.googleLogin = vi.fn().mockResolvedValue({+ token: 'session-token-b',+ me: { id: 'user-b', teamId: 'team-b' },+ })+ await service.googleLogin('id-token-b')+ answerMint(mintOk('first-app'))++ const settled = await outcome+ await expectNothingMountedFor(parentWindow, service)+ expect(settled).toMatchObject({ message: expect.stringMatching(/session changed/) })+ })++ it('an open whose cookie write is in flight at logout creates no view and rejects', async () => {+ const service = makeService()+ initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })+ const parentWindow = new FakeParentWindow()+ let finishCookieWrite: () => void = () => undefined+ electronMocks.sessionObject.cookies.set.mockImplementationOnce(+ () =>+ new Promise<void>(resolve => {+ finishCookieWrite = resolve+ })+ )++ const outcome = service.openSandboxUi(openArgs('first-app', parentWindow)).then(+ () => 'opened',+ (error: unknown) => error+ )+ await vi.waitFor(() => expect(electronMocks.sessionObject.cookies.set).toHaveBeenCalledOnce(), {+ timeout: 1_000,+ })+ await service.logout()+ finishCookieWrite()++ const settled = await outcome+ expect(electronMocks.views).toHaveLength(0)+ expect(parentWindow.contentView.addChildView).not.toHaveBeenCalled()+ expect(getActiveSandboxUi()).toBeNull()+ expect(settled).toMatchObject({ message: expect.stringMatching(/session changed/) })await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)expect(mintCallsFor('first-app')).toBe(1)})+ it('a refresh whose mint lands after logout writes no cookie and reports nothing', async () => {+ const onRefreshError = vi.fn()+ const service = makeService()+ initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })+ const parentWindow = new FakeParentWindow()+ await service.openSandboxUi({ ...openArgs('first-app', parentWindow), onRefreshError })+ const answerMint = holdMint('first-app')+ electronMocks.sessionObject.cookies.set.mockClear()++ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)+ await vi.waitFor(() => expect(mintCallsFor('first-app')).toBe(2), { timeout: 1_000 })+ await service.logout()+ answerMint(mintOk('first-app'))+ await vi.waitFor(() => expect(getActiveSandboxUi()).toBeNull(), { timeout: 1_000 })+ await (+ service as unknown as { enqueueSandboxUiLifecycle(op: () => Promise<void>): Promise<void> }+ ).enqueueSandboxUiLifecycle(async () => undefined)++ expect(electronMocks.sessionObject.cookies.set).not.toHaveBeenCalled()+ expect(onRefreshError).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)+ expect(mintCallsFor('first-app')).toBe(2)+ })++ it('an OAuth connect whose authorize URL lands after logout opens no browser', async () => {+ const service = makeService()+ let answer: (response: Response) => void = () => undefined+ authorizeUrlResponders.set(+ 'first-app',+ () =>+ new Promise<Response>(resolve => {+ answer = resolve+ })+ )++ const connect = service+ .requestSandboxUiOauthAuthorize('sandbox-recipes', 'first-app', 'client-1')+ .then(+ () => 'opened',+ (error: unknown) => error+ )+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce(), { timeout: 1_000 })+ await service.logout()+ answer(Response.json({ authorizeUrl: 'https://provider.example/authorize?state=a' }))++ const settled = await connect+ expect(shell.openExternal).not.toHaveBeenCalled()+ expect(settled).toMatchObject({ message: expect.stringMatching(/session changed/) })+ })+it('an open whose mint fails after logout leaves nothing behind and rejects once', async () => {const onClosed = vi.fn()const service = makeService()diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex f72e964a4..c4ec8c3d0 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -1340,6 +1340,21 @@ export class AppService {*/private sandboxUiGeneration = 0+ /**+ * Advanced only when the authenticated session is cleared. Sandbox-ui work+ * that awaits the network (open mint, OAuth authorize-url fetch) captures it+ * first and drops its effects if it moved. `sessionGeneration` cannot serve:+ * every token commit bumps it, including the two of each transient team hop+ * that unrelated concurrent work performs while a mint is in flight.+ */+ private sandboxUiSessionEpoch = 0++ private assertSandboxUiSessionEpoch(epoch: number): void {+ if (this.sandboxUiSessionEpoch !== epoch) {+ throw new Error('The session changed while this app request was in flight')+ }+ }+private enqueueSandboxUiLifecycle<T>(operation: () => Promise<T>): Promise<T> {const result = this.sandboxUiLifecycleQueue.then(operation)this.sandboxUiLifecycleQueue = result.then(@@ -1378,6 +1393,7 @@ export class AppService {this.workflowTeamByKey.clear()this.rpcTokenManager.clear()unbindChatStore()+ this.sandboxUiSessionEpoch += 1// The embed and its refresh loop run on the session being cleared. Queued// rather than awaited: callers are synchronous and must not wait on a// pending open's mint; the serial queue still tears down whatever that@@ -5020,6 +5036,7 @@ export class AppService {const clientId = String(oauthClientId || '').trim()if (!ns || !name) throw new Error('recipeNs and recipeName are required')if (!clientId) throw new Error('oauthClientId is required')+ const sessionEpoch = this.sandboxUiSessionEpochconst token = this.requireSessionToken()const issueRpc = () =>this.rpcTokenManager.getOrIssue(token, SANDBOX_UI_VIEW_SCOPES, [SANDBOX_UI_HOST_REF_SENTINEL])@@ -5048,6 +5065,9 @@ export class AppService {throw error}}+ // The authorize URL binds the grant to the session that fetched it; never+ // hand it to the browser once that session is gone.+ this.assertSandboxUiSessionEpoch(sessionEpoch)if (background) {const { dialog, BrowserWindow } = await import('electron')const win = BrowserWindow.getFocusedWindow() ?? undefined@@ -5064,6 +5084,7 @@ export class AppService {? await dialog.showMessageBox(win, opts): await dialog.showMessageBox(opts)if (result.response !== 1) return+ this.assertSandboxUiSessionEpoch(sessionEpoch)}await openExternalDataUrl(result.authorizeUrl, { requireHttps: true })}@@ -5266,22 +5287,16 @@ export class AppService {onOauthError?: (message: string) => voidonTitleChanged?: (title: string) => void}): Promise<void> {- return this.enqueueSandboxUiLifecycle(() => this.openSandboxUiNow(args))+ // Captured at request time, not when the queue reaches it: an open asked for+ // under one session must not run under the next one.+ const sessionEpoch = this.sandboxUiSessionEpoch+ return this.enqueueSandboxUiLifecycle(() => this.openSandboxUiNow(args, sessionEpoch))}- private async openSandboxUiNow(args: {- recipeNs: string- recipeName: string- title?: string- defaultPath?: string- routePath?: string- bounds: import('./sandboxUiDriver.js').SandboxUiBounds- parentWindow: import('electron').BrowserWindow- onClosed?: () => void- onRefreshError?: (message: string) => void- onOauthError?: (message: string) => void- onTitleChanged?: (title: string) => void- }): Promise<void> {+ private async openSandboxUiNow(+ args: Parameters<AppService['openSandboxUi']>[0],+ sessionEpoch: number+ ): Promise<void> {const recipeNs = String(args.recipeNs || '').trim()const recipeName = String(args.recipeName || '').trim()if (!recipeNs || !recipeName) throw new Error('recipeNs and recipeName are required')@@ -5295,7 +5310,7 @@ export class AppService {// the rejection.await this.teardownSandboxUiView()try {- await this.mintAndMountSandboxUiView(args, recipeNs, recipeName)+ await this.mintAndMountSandboxUiView(args, recipeNs, recipeName, sessionEpoch)} catch (error) {await this.teardownSandboxUiView()throw error@@ -5305,11 +5320,18 @@ export class AppService {private async mintAndMountSandboxUiView(args: Parameters<AppService['openSandboxUi']>[0],recipeNs: string,- recipeName: string+ recipeName: string,+ sessionEpoch: number): Promise<void> {+ // The close queued by a session clear only runs after this open settles, so+ // the open itself must refuse to install the cleared session's cookie or+ // attach a view for it.+ this.assertSandboxUiSessionEpoch(sessionEpoch)const { setCookie } = await this.mintSandboxUiSession(recipeNs, recipeName)+ this.assertSandboxUiSessionEpoch(sessionEpoch)const driver = await import('./sandboxUiDriver.js')const refreshModule = await import('./sandboxUiSessionRefresh.js')+ this.assertSandboxUiSessionEpoch(sessionEpoch)await driver.mountSandboxUiView({recipeNs,recipeName,@@ -5348,7 +5370,9 @@ export class AppService {args.onOauthError?.(message)})},+ isCurrent: () => this.sandboxUiSessionEpoch === sessionEpoch,})+ this.assertSandboxUiSessionEpoch(sessionEpoch)const activeView = driver.getActiveSandboxUi()if (!activeView || activeView.appRef !== `${recipeNs}/${recipeName}`) {// A queued close or newer mount can invalidate this operation while an@@ -5370,8 +5394,16 @@ export class AppService {webContentsId: activeView.webContentsId,parentWindow: args.parentWindow,refresh: (ns, name) => this.mintSandboxUiSession(ns, name),- installCookie: setCookieValue => driver.installSandboxUiCookie(setCookieValue),+ // A refresh minted before a session clear can land before the queued+ // close cancels this loop. Rejecting stops the loop without writing the+ // cleared session's cookie; the user has nothing to act on, so it is not+ // reported.+ installCookie: async setCookieValue => {+ this.assertSandboxUiSessionEpoch(sessionEpoch)+ await driver.installSandboxUiCookie(setCookieValue)+ },onError: err => {+ if (this.sandboxUiSessionEpoch !== sessionEpoch) returnargs.onRefreshError?.(err instanceof Error ? err.message : String(err))},})diff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.tsindex 6e6cde56d..64793b71d 100644--- a/desktop-app/src/sandboxUiDriver.ts+++ b/desktop-app/src/sandboxUiDriver.ts@@ -125,6 +125,12 @@ export type MountSandboxUiArgs = {* viewer, so a click reveals nothing to the plugin.*/onGfsOpen?: (uri: string) => void+ /**+ * Re-checked at every await before a session effect (cookie write, view+ * creation). False means the caller's authenticated session ended while this+ * mount was in flight, so it must not attach anything for it.+ */+ isCurrent?: () => boolean}type ActiveView = {@@ -356,6 +362,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<voidroutePath,onClosed,onTitleChanged,+ isCurrent = () => true,} = argsif (parentWindow.isDestroyed()) {@@ -374,7 +381,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void// per-recipe partition is left in place so storage survives a re-mount// within the ACL window.await teardownActive('replaced')- if (generation !== mountGeneration) return+ if (generation !== mountGeneration || !isCurrent()) returnconst partition = partitionFor(getActiveEnvKey(), recipeNs, recipeName)const proxyOriginUrl = new URL(rpcProxyUrl).toString().replace(/\/+$/, '')@@ -396,7 +403,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<voidsetCookie,partition,})- if (generation !== mountGeneration) return+ if (generation !== mountGeneration || !isCurrent()) returnif (parentWindow.isDestroyed()) {throw new Error('parent window is destroyed')}