Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix: serialize sandbox UI lifecycle and recover renderer readiness

Josuéd7dab3322677
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 3da38e378..961298c21 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.332",
+ "version": "0.1.333",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.332",
+ "version": "0.1.333",
"license": "MPL-2.0",
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index 5a266fefc..f95c2947a 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.332",
+ "version": "0.1.333",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts b/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts
index 81644311c..b432b950a 100644
--- a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts
+++ b/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts
@@ -2,8 +2,22 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { AppService } from '../appService.js'
import { ApiError } from '../httpClient.js'
-const { mockGetActiveSandboxUiLocation } = vi.hoisted(() => ({
+const {
+ mockCancelSandboxUiRefresh,
+ mockGetActiveSandboxUi,
+ mockGetActiveSandboxUiLocation,
+ mockInstallSandboxUiCookie,
+ mockMountSandboxUiView,
+ mockStartSandboxUiRefresh,
+ mockUnmountSandboxUiView,
+} = vi.hoisted(() => ({
+ mockCancelSandboxUiRefresh: vi.fn(),
+ mockGetActiveSandboxUi: vi.fn(),
mockGetActiveSandboxUiLocation: vi.fn(),
+ mockInstallSandboxUiCookie: vi.fn(),
+ mockMountSandboxUiView: vi.fn(),
+ mockStartSandboxUiRefresh: vi.fn(),
+ mockUnmountSandboxUiView: vi.fn(),
}))
vi.mock('electron', () => ({
@@ -21,7 +35,16 @@ vi.mock('electron', () => ({
}))
vi.mock('../sandboxUiDriver.js', () => ({
+ getActiveSandboxUi: mockGetActiveSandboxUi,
getActiveSandboxUiLocation: mockGetActiveSandboxUiLocation,
+ installSandboxUiCookie: mockInstallSandboxUiCookie,
+ mountSandboxUiView: mockMountSandboxUiView,
+ unmountSandboxUiView: mockUnmountSandboxUiView,
+}))
+
+vi.mock('../sandboxUiSessionRefresh.js', () => ({
+ cancelSandboxUiRefresh: mockCancelSandboxUiRefresh,
+ startSandboxUiRefresh: mockStartSandboxUiRefresh,
}))
vi.mock('../config.js', () => ({
@@ -151,6 +174,121 @@ describe('AppService.listSandboxUiApps', () => {
})
})
+describe('AppService sandbox UI lifecycle serialization', () => {
+ const openArgs = (recipeName: string) => ({
+ recipeNs: 'sandbox-recipes',
+ recipeName,
+ bounds: { x: 0, y: 0, width: 400, height: 300 },
+ parentWindow: {} as never,
+ })
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockMountSandboxUiView.mockImplementation(
+ async ({ recipeNs, recipeName }: { recipeNs: string; recipeName: string }) => {
+ mockGetActiveSandboxUi.mockReturnValue({
+ recipeNs,
+ recipeName,
+ appRef: `${recipeNs}/${recipeName}`,
+ webContentsId: recipeName === 'first-app' ? 1 : 2,
+ })
+ }
+ )
+ mockInstallSandboxUiCookie.mockResolvedValue(undefined)
+ mockUnmountSandboxUiView.mockResolvedValue(undefined)
+ })
+
+ it('finishes one mint, mount, and refresh setup before starting the next open', async () => {
+ let resolveFirstMint!: (value: { setCookie: string }) => void
+ let resolveSecondMint!: (value: { setCookie: string }) => void
+ const firstMint = new Promise<{ setCookie: string }>(resolve => {
+ resolveFirstMint = resolve
+ })
+ const secondMint = new Promise<{ setCookie: string }>(resolve => {
+ resolveSecondMint = resolve
+ })
+ const service = makeService() as unknown as {
+ mintSandboxUiSession: ReturnType<typeof vi.fn>
+ openSandboxUi: AppService['openSandboxUi']
+ }
+ service.mintSandboxUiSession = vi
+ .fn()
+ .mockReturnValueOnce(firstMint)
+ .mockReturnValueOnce(secondMint)
+
+ const firstOpen = service.openSandboxUi(openArgs('first-app'))
+ const secondOpen = service.openSandboxUi(openArgs('second-app'))
+
+ await vi.waitFor(() => {
+ expect(service.mintSandboxUiSession).toHaveBeenCalledTimes(1)
+ })
+ expect(mockMountSandboxUiView).not.toHaveBeenCalled()
+
+ resolveFirstMint({
+ setCookie:
+ 'clerum_sandbox_ui_session=first;' + ' Path=/api/v1/sandbox-ui/sandbox-recipes/first-app/',
+ })
+ await firstOpen
+ expect(mockStartSandboxUiRefresh).toHaveBeenCalledTimes(1)
+ expect(mockStartSandboxUiRefresh.mock.calls[0]?.[0]).toMatchObject({
+ recipeNs: 'sandbox-recipes',
+ recipeName: 'first-app',
+ webContentsId: 1,
+ })
+
+ await vi.waitFor(() => {
+ expect(service.mintSandboxUiSession).toHaveBeenCalledTimes(2)
+ })
+ resolveSecondMint({
+ setCookie:
+ 'clerum_sandbox_ui_session=second;' +
+ ' Path=/api/v1/sandbox-ui/sandbox-recipes/second-app/',
+ })
+ await secondOpen
+
+ expect(mockMountSandboxUiView.mock.calls.map(call => call[0].recipeName)).toEqual([
+ 'first-app',
+ 'second-app',
+ ])
+ expect(mockStartSandboxUiRefresh.mock.calls[1]?.[0]).toMatchObject({
+ recipeNs: 'sandbox-recipes',
+ recipeName: 'second-app',
+ webContentsId: 2,
+ })
+ })
+
+ it('queues close behind an in-flight open so the final state stays closed', async () => {
+ let resolveMint!: (value: { setCookie: string }) => void
+ const mint = new Promise<{ setCookie: string }>(resolve => {
+ resolveMint = resolve
+ })
+ const service = makeService() as unknown as {
+ mintSandboxUiSession: ReturnType<typeof vi.fn>
+ openSandboxUi: AppService['openSandboxUi']
+ closeSandboxUi: AppService['closeSandboxUi']
+ }
+ service.mintSandboxUiSession = vi.fn().mockReturnValue(mint)
+
+ const open = service.openSandboxUi(openArgs('first-app'))
+ const close = service.closeSandboxUi()
+
+ await vi.waitFor(() => {
+ expect(service.mintSandboxUiSession).toHaveBeenCalledOnce()
+ })
+ expect(mockUnmountSandboxUiView).not.toHaveBeenCalled()
+
+ resolveMint({
+ setCookie:
+ 'clerum_sandbox_ui_session=first;' + ' Path=/api/v1/sandbox-ui/sandbox-recipes/first-app/',
+ })
+ await open
+ await close
+
+ expect(mockCancelSandboxUiRefresh).toHaveBeenCalledOnce()
+ expect(mockUnmountSandboxUiView).toHaveBeenCalledOnce()
+ })
+})
+
describe('AppService.openForgotPassword', () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/desktop-app/src/__tests__/mainWindowReadiness.test.ts b/desktop-app/src/__tests__/mainWindowReadiness.test.ts
index 821d9a0b3..7a8df826f 100644
--- a/desktop-app/src/__tests__/mainWindowReadiness.test.ts
+++ b/desktop-app/src/__tests__/mainWindowReadiness.test.ts
@@ -1,25 +1,74 @@
import { describe, expect, it } from 'vitest'
-import { shouldResetRendererReadinessForNavigation } from '../mainWindowReadiness.js'
+import { vi } from 'vitest'
+import { wireMainWindowRendererReadiness } from '../mainWindowReadiness.js'
describe('main window renderer readiness', () => {
- it('resets only for main-frame cross-document navigations', () => {
- expect(
- shouldResetRendererReadinessForNavigation({
- isMainFrame: true,
- isSameDocument: false,
- })
- ).toBe(true)
- expect(
- shouldResetRendererReadinessForNavigation({
- isMainFrame: false,
- isSameDocument: false,
- })
- ).toBe(false)
- expect(
- shouldResetRendererReadinessForNavigation({
- isMainFrame: true,
- isSameDocument: true,
- })
- ).toBe(false)
+ function makeWebContents() {
+ const listeners = new Map<string, (...args: unknown[]) => void>()
+ return {
+ listeners,
+ webContents: {
+ isDestroyed: vi.fn(() => false),
+ on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
+ listeners.set(event, listener)
+ }),
+ reload: vi.fn(),
+ },
+ }
+ }
+
+ it('marks the renderer not ready only after a navigation commits', () => {
+ const { listeners, webContents } = makeWebContents()
+ const markNotReady = vi.fn()
+
+ wireMainWindowRendererReadiness({
+ webContents: webContents as never,
+ isCurrentWindow: () => true,
+ markNotReady,
+ })
+
+ expect(listeners.has('did-start-navigation')).toBe(false)
+ expect(listeners.has('did-navigate')).toBe(true)
+
+ listeners.get('did-navigate')?.()
+ expect(markNotReady).toHaveBeenCalledOnce()
+ })
+
+ it('reloads a crashed renderer so it can perform a new ready handshake', () => {
+ const { listeners, webContents } = makeWebContents()
+ const markNotReady = vi.fn()
+
+ wireMainWindowRendererReadiness({
+ webContents: webContents as never,
+ isCurrentWindow: () => true,
+ markNotReady,
+ })
+
+ listeners.get('render-process-gone')?.({}, { reason: 'crashed' })
+
+ expect(markNotReady).toHaveBeenCalledOnce()
+ expect(webContents.reload).toHaveBeenCalledOnce()
+ })
+
+ it('does not reload a clean exit or react to an obsolete window', () => {
+ const clean = makeWebContents()
+ wireMainWindowRendererReadiness({
+ webContents: clean.webContents as never,
+ isCurrentWindow: () => true,
+ markNotReady: vi.fn(),
+ })
+ clean.listeners.get('render-process-gone')?.({}, { reason: 'clean-exit' })
+ expect(clean.webContents.reload).not.toHaveBeenCalled()
+
+ const obsolete = makeWebContents()
+ const markNotReady = vi.fn()
+ wireMainWindowRendererReadiness({
+ webContents: obsolete.webContents as never,
+ isCurrentWindow: () => false,
+ markNotReady,
+ })
+ obsolete.listeners.get('render-process-gone')?.({}, { reason: 'crashed' })
+ expect(markNotReady).not.toHaveBeenCalled()
+ expect(obsolete.webContents.reload).not.toHaveBeenCalled()
})
})
diff --git a/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts b/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts
index c8f50854f..ebe209d79 100644
--- a/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts
+++ b/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts
@@ -1,10 +1,15 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { mountSandboxUiView, unmountSandboxUiView } from '../sandboxUiDriver.js'
+import {
+ installSandboxUiCookie,
+ mountSandboxUiView,
+ unmountSandboxUiView,
+} from '../sandboxUiDriver.js'
type Listener = () => void
const electronMocks = vi.hoisted(() => {
let nextWebContentsId = 1
+ const views: FakeWebContentsView[] = []
class FakeWebContents {
id = nextWebContentsId++
@@ -45,10 +50,16 @@ const electronMocks = vi.hoisted(() => {
webContents = new FakeWebContents()
setBounds = vi.fn()
setVisible = vi.fn()
+
+ constructor() {
+ views.push(this)
+ }
}
const sessionObject = {
- cookies: { set: vi.fn(async () => undefined) },
+ cookies: {
+ set: vi.fn(async (_details?: { value: string }): Promise<void> => undefined),
+ },
setPermissionRequestHandler: vi.fn(),
setPermissionCheckHandler: vi.fn(),
removeAllListeners: vi.fn(),
@@ -62,6 +73,7 @@ const electronMocks = vi.hoisted(() => {
getDisplayMatching: vi.fn(() => ({ scaleFactor: 1 })),
touchSandboxUiPartition: vi.fn(async () => undefined),
sessionObject,
+ views,
}
})
@@ -140,6 +152,8 @@ function mountArgs(overrides: MountSandboxUiViewOverrides): MountSandboxUiViewAr
beforeEach(() => {
vi.clearAllMocks()
+ electronMocks.views.length = 0
+ electronMocks.sessionObject.cookies.set.mockResolvedValue(undefined)
})
afterEach(async () => {
@@ -178,4 +192,93 @@ describe('mountSandboxUiView lifecycle cleanup', () => {
parentWindow.emit('closed')
expect(onClosed).not.toHaveBeenCalled()
})
+
+ it('keeps only the newest view when cookie writes complete out of order', async () => {
+ const parentWindow = new FakeParentWindow()
+ let resolveFirstCookie!: () => void
+ let resolveSecondCookie!: () => void
+ electronMocks.sessionObject.cookies.set.mockImplementation(
+ (details?: { value: string }) =>
+ new Promise<void>(resolve => {
+ const value = details?.value
+ if (value === 'tok-first') resolveFirstCookie = resolve
+ if (value === 'tok-second') resolveSecondCookie = resolve
+ })
+ )
+
+ const firstMount = mountSandboxUiView(
+ mountArgs({
+ parentWindow,
+ recipeName: 'first-app',
+ setCookie:
+ 'clerum_sandbox_ui_session=tok-first;' +
+ ' Path=/api/v1/sandbox-ui/sandbox-recipes/first-app/; HttpOnly',
+ })
+ )
+ await vi.waitFor(() => {
+ expect(electronMocks.sessionObject.cookies.set).toHaveBeenCalledTimes(1)
+ })
+
+ const secondMount = mountSandboxUiView(
+ mountArgs({
+ parentWindow,
+ recipeName: 'second-app',
+ setCookie:
+ 'clerum_sandbox_ui_session=tok-second;' +
+ ' Path=/api/v1/sandbox-ui/sandbox-recipes/second-app/; HttpOnly',
+ })
+ )
+ await vi.waitFor(() => {
+ expect(electronMocks.sessionObject.cookies.set).toHaveBeenCalledTimes(2)
+ })
+
+ resolveSecondCookie()
+ await secondMount
+ resolveFirstCookie()
+ await firstMount
+
+ expect(electronMocks.views).toHaveLength(1)
+ expect(parentWindow.contentView.addChildView).toHaveBeenCalledOnce()
+ expect(parentWindow.contentView.removeChildView).not.toHaveBeenCalled()
+ expect(parentWindow.listenerCount('closed')).toBe(1)
+ expect(electronMocks.views[0]?.webContents.isDestroyed()).toBe(false)
+ })
+
+ it('does not attach a view when unmount invalidates an in-flight mount', async () => {
+ const parentWindow = new FakeParentWindow()
+ let resolveCookie!: () => void
+ electronMocks.sessionObject.cookies.set.mockImplementation(
+ () =>
+ new Promise<void>(resolve => {
+ resolveCookie = resolve
+ })
+ )
+
+ const mount = mountSandboxUiView(mountArgs({ parentWindow }))
+ await vi.waitFor(() => {
+ expect(electronMocks.sessionObject.cookies.set).toHaveBeenCalledOnce()
+ })
+
+ await unmountSandboxUiView()
+ resolveCookie()
+ await mount
+
+ expect(electronMocks.views).toHaveLength(0)
+ expect(parentWindow.contentView.addChildView).not.toHaveBeenCalled()
+ expect(parentWindow.listenerCount('closed')).toBe(0)
+ })
+
+ it('rejects a refresh cookie scoped to a different recipe', async () => {
+ const parentWindow = new FakeParentWindow()
+ await mountSandboxUiView(mountArgs({ parentWindow }))
+
+ await expect(
+ installSandboxUiCookie(
+ 'clerum_sandbox_ui_session=foreign;' +
+ ' Path=/api/v1/sandbox-ui/sandbox-recipes/other-app/; HttpOnly'
+ )
+ ).rejects.toThrow('does not match the active recipe')
+
+ expect(electronMocks.sessionObject.cookies.set).toHaveBeenCalledOnce()
+ })
})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index ac92e2930..6033b3a5d 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -267,6 +267,7 @@ export class AppService {
private accessCatalog: AccessCatalog | null = null
private teamDirectoryCache: TeamDirectoryResult | null = null
private teamContextQueue: Promise<void> = Promise.resolve()
+ private sandboxUiLifecycleQueue: Promise<void> = Promise.resolve()
private workflowApprovalTeamById = new Map<string, string>()
private workflowTeamByKey = new Map<string, string>()
private readonly prewarmAttemptAtByHostRef = new Map<string, number>()
@@ -499,6 +500,15 @@ export class AppService {
return matchingEntry?.team.id ?? this.accessCatalog?.teamId ?? null
}
+ private enqueueSandboxUiLifecycle<T>(operation: () => Promise<T>): Promise<T> {
+ const result = this.sandboxUiLifecycleQueue.then(operation)
+ this.sandboxUiLifecycleQueue = result.then(
+ () => undefined,
+ () => undefined
+ )
+ return result
+ }
+
private async issueRpcTokenForHostRefs(
scopes: RpcScope[],
hostRefs: string[],
@@ -2873,7 +2883,21 @@ export class AppService {
* this). This keeps memory + GPU usage bounded and avoids accidental
* cross-recipe focus / cookie-jar mixups.
*/
- async openSandboxUi(args: {
+ openSandboxUi(args: {
+ recipeNs: string
+ recipeName: string
+ defaultPath?: string
+ routePath?: string
+ bounds: import('./sandboxUiDriver.js').SandboxUiBounds
+ parentWindow: import('electron').BrowserWindow
+ onClosed?: () => void
+ onRefreshError?: (message: string) => void
+ onOauthError?: (message: string) => void
+ }): Promise<void> {
+ return this.enqueueSandboxUiLifecycle(() => this.openSandboxUiNow(args))
+ }
+
+ private async openSandboxUiNow(args: {
recipeNs: string
recipeName: string
defaultPath?: string
@@ -2919,10 +2943,10 @@ export class AppService {
},
})
const activeView = driver.getActiveSandboxUi()
- if (!activeView) {
- // The mount step already threw if it failed; if we still get null
- // here something racy happened (parent window closed during the
- // mint). Bail without arming refresh.
+ if (!activeView || activeView.appRef !== `${recipeNs}/${recipeName}`) {
+ // A queued close or newer mount can invalidate this operation while an
+ // async cookie write is in flight. Do not cross-wire its refresh loop
+ // to whichever recipe is active now.
return
}
refreshModule.startSandboxUiRefresh({
@@ -2938,11 +2962,13 @@ export class AppService {
})
}
- async closeSandboxUi(): Promise<void> {
- const driver = await import('./sandboxUiDriver.js')
- const refreshModule = await import('./sandboxUiSessionRefresh.js')
- refreshModule.cancelSandboxUiRefresh()
- await driver.unmountSandboxUiView()
+ closeSandboxUi(): Promise<void> {
+ return this.enqueueSandboxUiLifecycle(async () => {
+ const driver = await import('./sandboxUiDriver.js')
+ const refreshModule = await import('./sandboxUiSessionRefresh.js')
+ refreshModule.cancelSandboxUiRefresh()
+ await driver.unmountSandboxUiView()
+ })
}
async createSandboxUiDeepLink(teamId?: string): Promise<{ url: string }> {
diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.ts
index 6165852b9..63a067cc3 100644
--- a/desktop-app/src/main.ts
+++ b/desktop-app/src/main.ts
@@ -4,7 +4,7 @@ import { AppService } from './appService.js'
import { config } from './config.js'
import { assertTrustedSender, registerIpcHandlers } from './ipc.js'
import { createMainWindowCoordinator, createRetryableInitializer } from './mainWindowCoordinator.js'
-import { shouldResetRendererReadinessForNavigation } from './mainWindowReadiness.js'
+import { wireMainWindowRendererReadiness } from './mainWindowReadiness.js'
import { collectInitialProtocolUrls } from './protocolLaunchArgs.js'
import { SandboxUiDeepLinkQueue } from './sandboxUiDeepLinkQueue.js'
import {
@@ -343,15 +343,12 @@ async function createWindow(): Promise<void> {
mainWindowRendererReady = false
}
})
- window.webContents.on('did-start-navigation', details => {
- if (mainWindow === window && shouldResetRendererReadinessForNavigation(details)) {
+ wireMainWindowRendererReadiness({
+ webContents: window.webContents,
+ isCurrentWindow: () => mainWindow === window,
+ markNotReady: () => {
mainWindowRendererReady = false
- }
- })
- window.webContents.on('render-process-gone', () => {
- if (mainWindow === window) {
- mainWindowRendererReady = false
- }
+ },
})
wireWindowVisibility(window)
diff --git a/desktop-app/src/mainWindowReadiness.ts b/desktop-app/src/mainWindowReadiness.ts
index bd8deefe5..d72934f2b 100644
--- a/desktop-app/src/mainWindowReadiness.ts
+++ b/desktop-app/src/mainWindowReadiness.ts
@@ -1,10 +1,25 @@
-export type RendererNavigationReadinessEvent = {
- isMainFrame: boolean
- isSameDocument: boolean
-}
+import type { WebContents } from 'electron'
+
+export function wireMainWindowRendererReadiness(input: {
+ webContents: Pick<WebContents, 'isDestroyed' | 'on' | 'reload'>
+ isCurrentWindow: () => boolean
+ markNotReady: () => void
+}): void {
+ const { webContents, isCurrentWindow, markNotReady } = input
+
+ // did-navigate only fires after a main-frame, cross-document navigation
+ // commits. did-start-navigation also fires for attempts later cancelled by
+ // will-navigate, which would leave readiness false with no replacement
+ // renderer available to perform the ready handshake.
+ webContents.on('did-navigate', () => {
+ if (isCurrentWindow()) markNotReady()
+ })
-export function shouldResetRendererReadinessForNavigation(
- details: RendererNavigationReadinessEvent
-): boolean {
- return details.isMainFrame && !details.isSameDocument
+ webContents.on('render-process-gone', (_event, details) => {
+ if (!isCurrentWindow()) return
+ markNotReady()
+ if (details.reason !== 'clean-exit' && !webContents.isDestroyed()) {
+ webContents.reload()
+ }
+ })
}
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 864cc69b3..48ff35fab 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -1,6 +1,9 @@
import { contextBridge, ipcRenderer } from 'electron'
-import type { SandboxUiDeepLinkEnvelope } from './sandboxUiDeepLinks.js'
-import type { HostMessageRequest, ProfileSettingsOpenOptions } from './types.js'
+import type {
+ HostMessageRequest,
+ ProfileSettingsOpenOptions,
+ SandboxUiDeepLinkEnvelope,
+} from './types.js'
const clerum = Object.freeze({
auth: {
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 4127edb02..2301effcf 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -1,5 +1,3 @@
-import type { SandboxUiApp } from './rpcProxyClient.js'
-import type { SandboxUiDeepLinkEnvelope } from './sandboxUiDeepLinks.js'
import {
AccessCatalog,
AgentWithMcpServers,
@@ -27,6 +25,8 @@ import {
PrewarmHostResult,
ProfileSettingsOpenOptions,
RpcAllowedServersResult,
+ SandboxUiApp,
+ SandboxUiDeepLinkEnvelope,
SessionLifecycleState,
SessionState,
SessionTokensLite,
diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.ts
index 55ca3f544..2a3af6878 100644
--- a/desktop-app/src/rpcProxyClient.ts
+++ b/desktop-app/src/rpcProxyClient.ts
@@ -11,12 +11,15 @@ import {
HostRuntimeStatus,
PendingApprovalLite,
RpcAllowedServersResult,
+ SandboxUiApp,
SessionLifecycleState,
SessionMessagesResult,
SessionTokensLite,
SetHostModelResult,
} from './types.js'
+export type { SandboxUiApp } from './types.js'
+
/**
* The runtime rejected a model that is not in the operator allowlist (R2/R3).
* The `model_not_allowed` token is preserved in the message so the renderer can
@@ -53,17 +56,6 @@ function url(path: string): string {
return `${config.rpcProxyBaseUrl.replace(/\/+$/, '')}${path}`
}
-export type SandboxUiApp = {
- appRef: string
- title?: string
- description?: string
- icon?: string
- defaultPath: string
- ready: boolean
- phase: string | null
- updatedAt: string | null
-}
-
/**
* Status mapping used by the renderer:
* 401 / 403 → re-auth or lost ACL
diff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.ts
index 331657d96..729501806 100644
--- a/desktop-app/src/sandboxUiDriver.ts
+++ b/desktop-app/src/sandboxUiDriver.ts
@@ -102,6 +102,7 @@ type ActiveView = {
}
let active: ActiveView | null = null
+let mountGeneration = 0
export const isSandboxUiNavigationWithinPrefix = isNavigationWithinPrefix
@@ -246,6 +247,13 @@ async function writeSandboxUiCookie(args: {
*/
export async function installSandboxUiCookie(setCookie: string | string[]): Promise<void> {
if (!active) return
+ const expectedPath =
+ `/api/v1/sandbox-ui/${encodeURIComponent(active.recipeNs)}/` +
+ `${encodeURIComponent(active.recipeName)}/`
+ const cookiePath = extractSandboxUiPath(setCookie, active.recipeNs, active.recipeName)
+ if (cookiePath !== expectedPath) {
+ throw new Error(`sandbox-ui refresh cookie path ${cookiePath} does not match the active recipe`)
+ }
await writeSandboxUiCookie({
rpcProxyOrigin: active.rpcProxyOrigin,
recipeNs: active.recipeNs,
@@ -296,10 +304,16 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
throw new Error('recipeNs and recipeName are required')
}
+ // Publish intent before the first await. A newer mount or unmount invalidates
+ // this operation while cookie installation is in flight, preventing an older
+ // request from attaching a view after the user has moved on.
+ const generation = ++mountGeneration
+
// Tear down any existing view before mounting (one-at-a-time embed). The
// per-recipe partition is left in place so storage survives a re-mount
// within the ACL window.
await teardownActive('replaced')
+ if (generation !== mountGeneration) return
const partition = partitionFor(getActiveEnvKey(), recipeNs, recipeName)
const proxyOriginUrl = new URL(rpcProxyUrl).toString().replace(/\/+$/, '')
@@ -320,6 +334,10 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
setCookie,
partition,
})
+ if (generation !== mountGeneration) return
+ if (parentWindow.isDestroyed()) {
+ throw new Error('parent window is destroyed')
+ }
// Apply default-deny permission + download policy on the partition's
// Session before the view is constructed so the very first navigation
@@ -573,6 +591,7 @@ export function canApplySandboxUiClientRoute(input: {
* re-mount within the ACL window is fast.
*/
export async function unmountSandboxUiView(): Promise<void> {
+ mountGeneration += 1
await teardownActive('closed')
}
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index a46feca02..e34c2ca63 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -15,6 +15,19 @@ export type RpcScope =
| 'sandbox:ui:view'
export type RpcAccessScope = 'team' | 'user'
+export type SandboxUiApp = {
+ appRef: string
+ title?: string
+ description?: string
+ icon?: string
+ defaultPath: string
+ ready: boolean
+ phase: string | null
+ updatedAt: string | null
+}
+
+export type { SandboxUiDeepLinkEnvelope } from '@clerum/desktop-app-links'
+
export type SessionMe = {
id: string
email: string
diff --git a/desktop-app/ui/src/lib/sandboxUiAppSelection.types.ts b/desktop-app/ui/src/lib/sandboxUiAppSelection.types.ts
index 346799d8c..1bc5a1da8 100644
--- a/desktop-app/ui/src/lib/sandboxUiAppSelection.types.ts
+++ b/desktop-app/ui/src/lib/sandboxUiAppSelection.types.ts
@@ -1,5 +1,5 @@
import type { ActiveSandboxUiApp } from '@/uiTypes'
-import type { SandboxUiApp } from '../../../src/rpcProxyClient'
+import type { SandboxUiApp } from '../../../src/types'
export type SandboxUiAppListing = SandboxUiApp