Skip to content

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

TypeScript

fix(desktop-app): keep a sandbox-ui view owned when a reopen fails

Diego Zacarias6ed61a4a6310
diff --git a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts b/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts
index 588c7ec46..d08cc61f3 100644
--- a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts
+++ b/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts
@@ -277,7 +277,11 @@ describe('AppService sandbox UI lifecycle serialization', () => {
await vi.waitFor(() => {
expect(service.mintSandboxUiSession).toHaveBeenCalledOnce()
})
- expect(mockUnmountSandboxUiView).not.toHaveBeenCalled()
+ // The open tears down whatever view was live BEFORE its mint (so a failed
+ // mint never leaves the previous view behind); that is the only teardown so
+ // far — the queued close has not run while the open is still in flight.
+ expect(mockUnmountSandboxUiView).toHaveBeenCalledOnce()
+ expect(mockMountSandboxUiView).not.toHaveBeenCalled()
resolveMint({
setCookie:
@@ -286,8 +290,16 @@ describe('AppService sandbox UI lifecycle serialization', () => {
await open
await close
- expect(mockCancelSandboxUiRefresh).toHaveBeenCalledOnce()
- expect(mockUnmountSandboxUiView).toHaveBeenCalledOnce()
+ // The queued close runs strictly after the mount and refresh setup, so the
+ // final state is closed: its unmount is the last driver call.
+ expect(mockCancelSandboxUiRefresh).toHaveBeenCalledTimes(2)
+ expect(mockUnmountSandboxUiView).toHaveBeenCalledTimes(2)
+ const mountOrder = mockMountSandboxUiView.mock.invocationCallOrder[0]!
+ const refreshStartOrder = mockStartSandboxUiRefresh.mock.invocationCallOrder[0]!
+ const finalUnmountOrder = mockUnmountSandboxUiView.mock.invocationCallOrder[1]!
+ const finalCancelOrder = mockCancelSandboxUiRefresh.mock.invocationCallOrder[1]!
+ expect(finalUnmountOrder).toBeGreaterThan(mountOrder)
+ expect(finalCancelOrder).toBeGreaterThan(refreshStartOrder)
})
})
diff --git a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts
new file mode 100644
index 000000000..fdd22afbf
--- /dev/null
+++ b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts
@@ -0,0 +1,395 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtemp, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { AppService } from '../appService.js'
+import { _resetPluginSdkRuntimeForTests, initPluginSdkRuntime } from '../pluginSdkRuntime.js'
+import { _resetPluginSurfacesForTests, resolvePluginSurface } from '../pluginSurfaceRegistry.js'
+import { getActiveSandboxUi, unmountSandboxUiView } from '../sandboxUiDriver.js'
+import {
+ SANDBOX_UI_REFRESH_INTERVAL_MS,
+ _resetSandboxUiRefreshForTests,
+} from '../sandboxUiSessionRefresh.js'
+
+// The open/close lifecycle is exercised end to end through the REAL AppService,
+// the REAL sandbox-ui driver, the REAL session-refresh loop, the REAL plugin
+// surface pin registry and the REAL RpcProxyClient. Only the Electron runtime
+// (views, sessions, windows) and the RPC-token issuer are faked; mint outcomes
+// come from rpc-proxy HTTP responses fed to the real client through `fetch`.
+
+const electronMocks = vi.hoisted(() => {
+ let nextWebContentsId = 1
+ const views: FakeWebContentsView[] = []
+
+ class FakeWebContents {
+ id = nextWebContentsId++
+ currentUrl = ''
+ destroyed = false
+ private readonly listeners = new Map<string, Set<(...args: unknown[]) => void>>()
+ executeJavaScript = vi.fn()
+ loadURL = vi.fn(async (url: string) => {
+ this.currentUrl = url
+ })
+ setWindowOpenHandler = vi.fn()
+ stopFindInPage = vi.fn()
+ findInPage = vi.fn(() => 41)
+ focus = vi.fn()
+ send = vi.fn()
+
+ on(event: string, handler: (...args: unknown[]) => void): this {
+ if (!this.listeners.has(event)) this.listeners.set(event, new Set())
+ this.listeners.get(event)!.add(handler)
+ return this
+ }
+
+ removeListener(event: string, handler: (...args: unknown[]) => void): this {
+ this.listeners.get(event)?.delete(handler)
+ return this
+ }
+
+ getURL(): string {
+ return this.currentUrl
+ }
+
+ isDestroyed(): boolean {
+ return this.destroyed
+ }
+
+ close(): void {
+ this.destroyed = true
+ }
+ }
+
+ class FakeWebContentsView {
+ webContents = new FakeWebContents()
+ setBounds = vi.fn()
+ setVisible = vi.fn()
+
+ constructor() {
+ views.push(this)
+ }
+ }
+
+ const sessionObject = {
+ cookies: {
+ set: vi.fn(async (_details?: { value: string }): Promise<void> => undefined),
+ },
+ setPermissionRequestHandler: vi.fn(),
+ setPermissionCheckHandler: vi.fn(),
+ removeAllListeners: vi.fn(),
+ on: vi.fn(),
+ clearCache: vi.fn(async () => undefined),
+ }
+
+ return {
+ FakeWebContentsView,
+ fromPartition: vi.fn(() => sessionObject),
+ getDisplayMatching: vi.fn(() => ({ scaleFactor: 1 })),
+ touchSandboxUiPartition: vi.fn(async () => undefined),
+ sessionObject,
+ views,
+ }
+})
+
+vi.mock('electron', () => ({
+ WebContentsView: electronMocks.FakeWebContentsView,
+ BrowserWindow: { getAllWindows: () => [] },
+ Notification: class {
+ static isSupported(): boolean {
+ return false
+ }
+ },
+ app: { getPath: vi.fn(() => tmpdir()) },
+ safeStorage: {
+ isEncryptionAvailable: vi.fn(() => false),
+ encryptString: vi.fn(),
+ decryptString: vi.fn(),
+ },
+ screen: { getDisplayMatching: electronMocks.getDisplayMatching },
+ session: { fromPartition: electronMocks.fromPartition },
+ shell: { openExternal: vi.fn() },
+}))
+
+vi.mock('../config.js', () => ({
+ getActiveEnvKey: () => 'test-env',
+ config: {
+ rpcProxyBaseUrl: 'https://rpc.example',
+ externalRestApiBaseUrl: 'http://rest',
+ desktopProfileUiBaseUrl: 'https://profile.example.com',
+ desktopProfileUiBaseUrlExplicit: false,
+ enableDevLoginUi: false,
+ requestTimeoutMs: 60000,
+ appName: 'test',
+ },
+}))
+
+vi.mock('../sandboxUiPartitionGc.js', () => ({
+ touchSandboxUiPartition: electronMocks.touchSandboxUiPartition,
+}))
+
+// The RPC token is issued by control-api through external-rest-api — a layer
+// this suite does not stand up. The mint itself (rpc-proxy) runs through the
+// real RpcProxyClient below.
+vi.mock('../rpcTokenManager.js', () => ({
+ RpcTokenManager: class {
+ getOrIssue = vi.fn(async () => ({ token: 'rpc-token' }))
+ clear = vi.fn()
+ getMetadata = vi.fn(() => ({ expiresAtMs: null, scopes: [], hostRefs: [] }))
+ },
+}))
+
+vi.mock('../authClient.js', () => ({
+ AuthClient: class {
+ health = vi.fn().mockResolvedValue({ status: 'ok' })
+ getMe = vi.fn()
+ },
+}))
+
+vi.mock('../tokenStore.js', () => ({
+ TokenStore: class {
+ getSessionToken = vi.fn().mockResolvedValue(null)
+ setSessionToken = vi.fn()
+ clearSessionToken = vi.fn()
+ },
+}))
+
+type Listener = (...args: unknown[]) => void
+
+class FakeParentWindow {
+ destroyed = false
+ contentView = {
+ addChildView: vi.fn(),
+ removeChildView: vi.fn(),
+ }
+ private readonly listeners = new Map<string, Set<Listener>>()
+
+ isDestroyed(): boolean {
+ return this.destroyed
+ }
+
+ isVisible(): boolean {
+ return true
+ }
+
+ isMinimized(): boolean {
+ return false
+ }
+
+ getBounds(): { x: number; y: number; width: number; height: number } {
+ return { x: 0, y: 0, width: 800, height: 600 }
+ }
+
+ on(event: string, handler: Listener): this {
+ if (!this.listeners.has(event)) this.listeners.set(event, new Set())
+ this.listeners.get(event)!.add(handler)
+ return this
+ }
+
+ once(event: string, handler: Listener): this {
+ return this.on(event, handler)
+ }
+
+ removeListener(event: string, handler: Listener): this {
+ this.listeners.get(event)?.delete(handler)
+ return this
+ }
+}
+
+// rpc-proxy's mint contract: 204 + a Path-scoped Set-Cookie on success, any
+// other status with a text body on failure.
+function mintOk(recipeName: string): Response {
+ return new Response(null, {
+ status: 204,
+ headers: {
+ 'set-cookie':
+ `clerum_sandbox_ui_session=tok-${recipeName}; ` +
+ `Path=/api/v1/sandbox-ui/sandbox-recipes/${recipeName}/; HttpOnly`,
+ },
+ })
+}
+
+function mintFails(status: number, body: string): Response {
+ return new Response(body, { status })
+}
+
+const mintResponders = new Map<string, () => Response>()
+const fetchMock = vi.fn(async (input: string | URL | Request): Promise<Response> => {
+ const url = String(input instanceof Request ? input.url : input)
+ const match = /\/api\/v1\/sandbox-ui\/sandbox-recipes\/([^/]+)\/session$/.exec(url)
+ if (!match) throw new Error(`unexpected fetch ${url}`)
+ const recipeName = decodeURIComponent(match[1]!)
+ const respond = mintResponders.get(recipeName)
+ return respond ? respond() : mintOk(recipeName)
+})
+
+function mintCallsFor(recipeName: string): number {
+ return fetchMock.mock.calls.filter(([input]) =>
+ String(input).includes(`/sandbox-recipes/${recipeName}/session`)
+ ).length
+}
+
+function makeService(): AppService {
+ const svc = new AppService()
+ ;(svc as unknown as { sessionToken: string }).sessionToken = 'session-token'
+ return svc
+}
+
+function openArgs(
+ recipeName: string,
+ parentWindow: FakeParentWindow,
+ onClosed: () => void = vi.fn()
+): Parameters<AppService['openSandboxUi']>[0] {
+ return {
+ recipeNs: 'sandbox-recipes',
+ recipeName,
+ title: recipeName,
+ defaultPath: '/',
+ bounds: { x: 0, y: 0, width: 400, height: 300 },
+ parentWindow: parentWindow as unknown as Parameters<
+ AppService['openSandboxUi']
+ >[0]['parentWindow'],
+ onClosed,
+ }
+}
+
+let userDataDir = ''
+
+beforeEach(async () => {
+ vi.clearAllMocks()
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ electronMocks.views.length = 0
+ electronMocks.sessionObject.cookies.set.mockResolvedValue(undefined)
+ mintResponders.clear()
+ vi.stubGlobal('fetch', fetchMock)
+ userDataDir = await mkdtemp(path.join(tmpdir(), 'clerum-sandbox-lifecycle-'))
+})
+
+afterEach(async () => {
+ await unmountSandboxUiView()
+ _resetSandboxUiRefreshForTests()
+ _resetPluginSurfacesForTests()
+ _resetPluginSdkRuntimeForTests()
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+ await rm(userDataDir, { recursive: true, force: true })
+})
+
+async function setupWithLiveFirstApp(onClosed: () => void = vi.fn()) {
+ const service = makeService()
+ initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })
+ const parentWindow = new FakeParentWindow()
+ await service.openSandboxUi(openArgs('first-app', parentWindow, onClosed))
+ const first = getActiveSandboxUi()
+ expect(first?.appRef).toBe('sandbox-recipes/first-app')
+ expect(resolvePluginSurface(first!.webContentsId)?.pluginId).toBe('sandbox-recipes/first-app')
+ const firstView = electronMocks.views[0]
+ return { service, parentWindow, firstWebContentsId: first!.webContentsId, firstView }
+}
+
+describe('AppService sandbox-ui open replaces the live view whatever its outcome', () => {
+ it('a reopen whose mint rejects leaves no view, no refresh loop and no pin behind', async () => {
+ const { service, parentWindow, firstWebContentsId, firstView } = await setupWithLiveFirstApp()
+ mintResponders.set('second-app', () => mintFails(409, 'app is starting'))
+
+ await expect(service.openSandboxUi(openArgs('second-app', parentWindow))).rejects.toThrow(
+ /\(409\)/
+ )
+
+ expect(getActiveSandboxUi()).toBeNull()
+ expect(parentWindow.contentView.removeChildView).toHaveBeenCalledTimes(1)
+ expect(parentWindow.contentView.removeChildView).toHaveBeenCalledWith(firstView)
+ expect(firstView?.webContents.isDestroyed()).toBe(true)
+ expect(resolvePluginSurface(firstWebContentsId)).toBeNull()
+ // The old view's refresh loop is gone: a full refresh interval mints nothing.
+ const mintsBefore = mintCallsFor('first-app')
+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)
+ expect(mintCallsFor('first-app')).toBe(mintsBefore)
+ })
+
+ it('a reopen whose mount fails after the teardown leaves no view and no refresh loop', async () => {
+ const { service, parentWindow, firstWebContentsId } = await setupWithLiveFirstApp()
+ electronMocks.sessionObject.cookies.set.mockRejectedValueOnce(new Error('cookie store down'))
+
+ await expect(service.openSandboxUi(openArgs('second-app', parentWindow))).rejects.toThrow(
+ 'cookie store down'
+ )
+
+ expect(getActiveSandboxUi()).toBeNull()
+ expect(resolvePluginSurface(firstWebContentsId)).toBeNull()
+ const mintsBefore = mintCallsFor('first-app') + mintCallsFor('second-app')
+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)
+ expect(mintCallsFor('first-app') + mintCallsFor('second-app')).toBe(mintsBefore)
+ })
+
+ it('a reopen that fails once the new view is already active tears that new view down', async () => {
+ const { service, parentWindow } = await setupWithLiveFirstApp()
+ // The driver registers the new view as active before attaching it, so an
+ // attach failure leaves B active unless the open cleans up after itself.
+ parentWindow.contentView.addChildView.mockImplementationOnce(() => {
+ throw new Error('attach failed')
+ })
+
+ await expect(service.openSandboxUi(openArgs('second-app', parentWindow))).rejects.toThrow(
+ 'attach failed'
+ )
+
+ const secondView = electronMocks.views[1]
+ expect(secondView).toBeDefined()
+ expect(getActiveSandboxUi()).toBeNull()
+ expect(parentWindow.contentView.removeChildView).toHaveBeenCalledWith(secondView)
+ expect(secondView?.webContents.isDestroyed()).toBe(true)
+ const mintsBefore = mintCallsFor('first-app') + mintCallsFor('second-app')
+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)
+ expect(mintCallsFor('first-app') + mintCallsFor('second-app')).toBe(mintsBefore)
+ })
+
+ it('a successful reopen swaps to the new view with only its own refresh loop', async () => {
+ const { service, parentWindow, firstWebContentsId } = await setupWithLiveFirstApp()
+
+ await service.openSandboxUi(openArgs('second-app', parentWindow))
+
+ const second = getActiveSandboxUi()
+ expect(second?.appRef).toBe('sandbox-recipes/second-app')
+ expect(resolvePluginSurface(firstWebContentsId)).toBeNull()
+ expect(resolvePluginSurface(second!.webContentsId)?.pluginId).toBe('sandbox-recipes/second-app')
+ fetchMock.mockClear()
+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)
+ expect(mintCallsFor('first-app')).toBe(0)
+ expect(mintCallsFor('second-app')).toBe(1)
+ })
+
+ // The renderer's `sandboxUi:closed` listener drops ownership of the live
+ // embed. If the solicited teardown inside an open signalled it, the renderer
+ // would lose the owner of the view main is about to mount — the very orphan
+ // this teardown prevents. An open reports failure only through its rejection.
+ it('never signals onClosed from a reopen, whether it succeeds or fails', async () => {
+ const onClosed = vi.fn()
+ const { service, parentWindow } = await setupWithLiveFirstApp(onClosed)
+
+ await service.openSandboxUi(openArgs('first-app', parentWindow, onClosed))
+ expect(getActiveSandboxUi()?.appRef).toBe('sandbox-recipes/first-app')
+
+ mintResponders.set('first-app', () => mintFails(409, 'app is starting'))
+ await expect(
+ service.openSandboxUi(openArgs('first-app', parentWindow, onClosed))
+ ).rejects.toThrow(/\(409\)/)
+ expect(getActiveSandboxUi()).toBeNull()
+
+ expect(onClosed).not.toHaveBeenCalled()
+ })
+
+ // On an app→app switch the renderer reads the outgoing view's route and then
+ // asks main to open the incoming app, in that order and in the same tick. The
+ // open's teardown must not overtake that read, or the outgoing tab's route is
+ // read from nothing.
+ it('a location read issued before an open in the same tick still sees the outgoing view', async () => {
+ const { service, parentWindow } = await setupWithLiveFirstApp()
+
+ const location = service.getSandboxUiLocation()
+ const reopen = service.openSandboxUi(openArgs('second-app', parentWindow))
+
+ await expect(location).resolves.toMatchObject({ appRef: 'sandbox-recipes/first-app' })
+ await reopen
+ expect(getActiveSandboxUi()?.appRef).toBe('sandbox-recipes/second-app')
+ })
+})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 3c6bd1c98..ef49e403c 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -5241,9 +5241,10 @@ export class AppService {
* view at the bounds the renderer reserved.
*
* Only one sandbox-ui view exists at a time across the desktop app —
- * re-opening recipe B while A is up tears down A first (the driver enforces
- * this). This keeps memory + GPU usage bounded and avoids accidental
- * cross-recipe focus / cookie-jar mixups.
+ * re-opening recipe B while A is up tears down A first, before B's session
+ * is minted, so a failed open leaves no view at all. This keeps memory + GPU
+ * usage bounded and avoids accidental cross-recipe focus / cookie-jar
+ * mixups.
*/
openSandboxUi(args: {
recipeNs: string
@@ -5278,6 +5279,27 @@ export class AppService {
const recipeName = String(args.recipeName || '').trim()
if (!recipeNs || !recipeName) throw new Error('recipeNs and recipeName are required')
this.sandboxUiGeneration += 1
+ // An open replaces the current view whatever its outcome, so the outgoing
+ // view goes BEFORE the network mint: a failed mint must not leave it
+ // painted (with its refresh loop still minting) after the renderer has been
+ // told the open failed. Deliberately silent — no `onClosed`: the renderer
+ // drops its owner of the embed on `sandboxUi:closed`, which here would
+ // orphan the view this open is about to mount. Failure is reported only by
+ // the rejection.
+ await this.teardownSandboxUiView()
+ try {
+ await this.mintAndMountSandboxUiView(args, recipeNs, recipeName)
+ } catch (error) {
+ await this.teardownSandboxUiView()
+ throw error
+ }
+ }
+
+ private async mintAndMountSandboxUiView(
+ args: Parameters<AppService['openSandboxUi']>[0],
+ recipeNs: string,
+ recipeName: string
+ ): Promise<void> {
const { setCookie } = await this.mintSandboxUiSession(recipeNs, recipeName)
const driver = await import('./sandboxUiDriver.js')
const refreshModule = await import('./sandboxUiSessionRefresh.js')
@@ -5349,13 +5371,15 @@ export class AppService {
}
closeSandboxUi(): Promise<void> {
- return this.enqueueSandboxUiLifecycle(async () => {
- const driver = await import('./sandboxUiDriver.js')
- const refreshModule = await import('./sandboxUiSessionRefresh.js')
- refreshModule.cancelSandboxUiRefresh()
- tryGetPluginSdkRuntime()?.unpinAllSandboxUiSurfaces()
- await driver.unmountSandboxUiView()
- })
+ return this.enqueueSandboxUiLifecycle(() => this.teardownSandboxUiView())
+ }
+
+ private async teardownSandboxUiView(): Promise<void> {
+ const driver = await import('./sandboxUiDriver.js')
+ const refreshModule = await import('./sandboxUiSessionRefresh.js')
+ refreshModule.cancelSandboxUiRefresh()
+ tryGetPluginSdkRuntime()?.unpinAllSandboxUiSurfaces()
+ await driver.unmountSandboxUiView()
}
// Read the active embed's current in-app route for the renderer's tab store
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index f2b8960f3..fa43a017e 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -405,7 +405,9 @@ export function App() {
// app tab changes, this ref tells the deactivation effect which OUTGOING tab
// to persist the route onto. `null` = no embed is live (also the reconciled
// state after an UNsolicited close — crash/quit/GC — so a later tab switch
- // does not persist or re-close a dead embed).
+ // does not persist or re-close a dead embed). A FAILED open does not reset it:
+ // the tab keeps owning whatever main may still hold (see
+ // `handleSandboxUiRemoved`).
const liveSandboxUiTabIdRef = React.useRef<string | null>(null)
// Monotonic generation bumped on EVERY transition of the active embed (the
// deactivation effect and the deep-link handoff are the only emitters). Each
@@ -1327,8 +1329,12 @@ export function App() {
setSidebarSettingsMenuOpen(false)
}, [])
+ // A failed open (rejected by main, or failed before reaching it) clears only
+ // the React state. The active tab stays the embed's owner: a failure before
+ // the open IPC leaves the previous view live in main, and only an owner makes
+ // the deactivation effect `close()` it when the user leaves the tab. When main
+ // already tore the view down, that `close()` is a harmless no-op.
const handleSandboxUiRemoved = React.useCallback(() => {
- liveSandboxUiTabIdRef.current = null
setActiveSandboxUiApp(null)
setSandboxUiMounted(false)
setSandboxUiConversationOrigin(null)
diff --git a/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx b/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx
new file mode 100644
index 000000000..4c0a269a8
--- /dev/null
+++ b/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx
@@ -0,0 +1,395 @@
+// @vitest-environment jsdom
+import { useReducer } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { DESKTOP_ROUTES } from '@constants/navigation'
+import { useAppController } from '@hooks/useAppController'
+import type { GfsPreviewResource } from '@lib/gfsPreview'
+import { toActiveSandboxUiApps } from '@lib/sandboxUiAppSelection'
+import type { SandboxUiAppListing } from '@lib/sandboxUiAppSelection.types'
+import {
+ activeWorkspaceTab,
+ createWorkspaceTabsState,
+ openFilesTab,
+ openPreviewTab,
+} from '@lib/workspaceTabs'
+import { mapKindToRoute } from '@lib/workspaceTabsRoute'
+import { App } from '@/App'
+import { openGfsResourcePayload, resolvedFile } from '@/gfs/__fixtures__/gfsProducerFixtures'
+
+// Ownership of the native sandbox-ui embed across a FAILED relaunch. The
+// WebContentsView paints above the renderer DOM, so whichever app tab owns it
+// must emit `sandboxUi.close()` when the user leaves it — even after an open on
+// that tab failed, because main may still hold a view (a failure before the
+// open IPC never reaches main at all). These cases drive the REAL SandboxUiPage
+// (its open/catch path is the producer under test) and the REAL tab strip; the
+// App harness in App.chatDrawer.test.tsx stubs SandboxUiPage and so cannot.
+
+let forceControllerRender: () => void = () => {}
+
+function useReactiveController(controller: AppController): AppController {
+ const [, force] = useReducer((count: number) => count + 1, 0)
+ forceControllerRender = force
+ const activeTab = activeWorkspaceTab(controller.workspaceTabs)
+ ;(controller as { activeWorkspaceTab: unknown }).activeWorkspaceTab = activeTab
+ ;(controller as { navItem: unknown }).navItem = controller.appsPickerActive
+ ? DESKTOP_ROUTES.apps
+ : mapKindToRoute(activeTab)
+ return controller
+}
+
+type WorkspaceState = ReturnType<typeof useAppController>['workspaceTabs']
+
+const sidebarHarness = vi.hoisted(() => ({
+ props: null as null | {
+ onOpenSandboxUiApp?: (app: {
+ appRef: string
+ label: string
+ defaultPath: string
+ icon?: string
+ }) => void
+ },
+}))
+
+vi.mock('@hooks/useAppController', () => ({ useAppController: vi.fn() }))
+vi.mock('@hooks/useAgentChatActionsValue', () => ({ useAgentChatActionsValue: () => ({}) }))
+vi.mock('@components/AppHeader', () => ({ AppHeader: () => null }))
+vi.mock('@components/ChatLocalSearch', () => ({ ChatLocalSearch: () => null }))
+vi.mock('@components/CommandPalette', () => ({ CommandPalette: () => null }))
+vi.mock('@components/BootSplash', () => ({ BootSplash: () => null }))
+vi.mock('@components/ConfirmDialog', () => ({ ConfirmDialog: () => null }))
+vi.mock('@components/GfsImagePreview', () => ({ GfsImagePreview: () => null }))
+vi.mock('@components/PluginConsentModal', () => ({ PluginConsentModal: () => null }))
+vi.mock('@components/SidebarNav', () => ({
+ SidebarNav: (props: NonNullable<typeof sidebarHarness.props>) => {
+ sidebarHarness.props = props
+ return null
+ },
+}))
+vi.mock('@pages/AgentsPage', () => ({ AgentsPage: () => null }))
+vi.mock('@pages/AuthPage', () => ({ AuthPage: () => null }))
+vi.mock('@pages/ChatPage', () => ({ ChatPage: () => null }))
+vi.mock('@pages/ContextDetailsPage', () => ({ ContextDetailsPage: () => null }))
+vi.mock('@pages/ContextsPage', () => ({ ContextsPage: () => null }))
+vi.mock('@pages/FilesPage', () => ({ FilesPage: () => null }))
+vi.mock('@pages/FilePreviewPage', () => ({ FilePreviewPage: () => null }))
+vi.mock('@pages/McpServersPage', () => ({ McpServersPage: () => null }))
+vi.mock('@pages/SettingsPage', () => ({ SettingsPage: () => null }))
+vi.mock('@pages/TeamDetailsPage', () => ({ TeamDetailsPage: () => null }))
+vi.mock('@pages/TeamsPage', () => ({ TeamsPage: () => null }))
+vi.mock('@pages/UnavailablePage', () => ({ UnavailablePage: () => null }))
+vi.mock('@pages/WorkflowsPage', () => ({ WorkflowsPage: () => null }))
+
+type AppController = ReturnType<typeof useAppController>
+
+// Store-faithful controller (same contract as App.chatDrawer.test.tsx): `navItem`
+// derives from the active tab, and every navigation drives the real store
+// producers.
+function makeController(): AppController {
+ const noop = vi.fn()
+ let controller: AppController
+ let tabSequence = 2
+ const nextWorkspaceTabId = vi.fn(() => `ws-tab-${tabSequence++}`)
+ const setWorkspaceTabs = vi.fn((updater: unknown) => {
+ const next =
+ typeof updater === 'function'
+ ? (updater as (state: WorkspaceState) => WorkspaceState)(controller.workspaceTabs)
+ : (updater as WorkspaceState)
+ if (next === controller.workspaceTabs) return
+ controller.workspaceTabs = next
+ forceControllerRender()
+ })
+ const clearAppsPicker = vi.fn(() => {
+ if (!controller.appsPickerActive) return
+ controller.appsPickerActive = false
+ forceControllerRender()
+ })
+ const openFilesSection = vi.fn((path: string | null = null) => {
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) =>
+ openFilesTab(state, { id: nextWorkspaceTabId(), path })
+ )
+ forceControllerRender()
+ })
+ const openPreviewSection = vi.fn((preview: GfsPreviewResource) => {
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) =>
+ openPreviewTab(state, {
+ id: nextWorkspaceTabId(),
+ title: preview.name,
+ gfsUri: preview.gfsUri,
+ fileKind: preview.kind,
+ byteLength: preview.bytes,
+ ...(preview.version !== undefined ? { resourceVersion: preview.version } : {}),
+ ...('mimeType' in preview ? { mimeType: preview.mimeType } : {}),
+ })
+ )
+ forceControllerRender()
+ })
+ const showAppsPicker = vi.fn(() => {
+ if (controller.appsPickerActive) return
+ if (activeWorkspaceTab(controller.workspaceTabs)?.kind === 'app') return
+ controller.appsPickerActive = true
+ forceControllerRender()
+ })
+ const handleSelectChatAgent = vi.fn(() => forceControllerRender())
+ controller = {
+ booting: false,
+ initialExperienceLoading: false,
+ busy: false,
+ statusText: '',
+ statusTone: 'info',
+ isAuthenticated: true,
+ authenticatedPrincipalIdentity: 'user-a:[email protected]',
+ me: { id: 'user-a', email: '[email protected]', name: 'User A', teamId: 'team-a' },
+ currentTeamId: 'team-a',
+ navItem: DESKTOP_ROUTES.chat,
+ selectedAgent: null,
+ selectedAgentRoute: null,
+ selectedContext: null,
+ selectedTeam: null,
+ workspaceTabs: createWorkspaceTabsState('chat-tab-1'),
+ setWorkspaceTabs,
+ activeWorkspaceTab: undefined,
+ nextWorkspaceTabId,
+ appsPickerActive: false,
+ showAppsPicker,
+ clearAppsPicker,
+ activateWorkspaceChatTab: noop,
+ openFilesSection,
+ openPreviewSection,
+ lastActiveChatTabId: null,
+ activeChatId: null,
+ chatList: [],
+ latestChatSessions: [],
+ notifications: [],
+ toasts: [],
+ pendingApprovals: [],
+ composerImageAttachments: [],
+ composerReferenceAttachments: [],
+ groupedMessages: [],
+ activeMessages: [],
+ notificationActionById: {},
+ sessionStateByChatId: {},
+ sessionStateByChatKey: {},
+ activityByMessageId: {},
+ progressByMessageId: {},
+ agentLastActiveByAgent: {},
+ dependencyHealth: null,
+ hasDependencyOutage: false,
+ desktopEnvironmentSetupComplete: false,
+ pendingDesktopEnvironmentSetup: null,
+ desktopReleaseStatus: null,
+ showRuntimeConfigSelector: false,
+ runtimeConfigMissing: false,
+ authTransitioning: false,
+ handleEnsureTeamContext: vi.fn(async () => false),
+ getCurrentTeamId: vi.fn(() => 'team-a'),
+ isHostAccessBlocked: vi.fn(() => false),
+ handleSelectChatAgent,
+ handleOpenNotification: vi.fn(async () => undefined),
+ handleNavSelect: vi.fn(),
+ handleLogout: vi.fn(),
+ pushToast: vi.fn(),
+ setStatus: noop,
+ setBooting: noop,
+ } as unknown as AppController
+ return controller
+}
+
+const APP_LISTING: SandboxUiAppListing[] = [
+ {
+ appRef: 'sandbox-recipes/alpha',
+ title: 'Alpha',
+ defaultPath: '/',
+ ready: true,
+ phase: 'active',
+ updatedAt: null,
+ },
+ {
+ appRef: 'sandbox-recipes/beta',
+ title: 'Beta',
+ defaultPath: '/',
+ ready: true,
+ phase: 'active',
+ updatedAt: null,
+ },
+]
+// What the real sidebar hands to `onOpenSandboxUiApp`: App's own mapping of the
+// listing it loaded.
+const [ALPHA, BETA] = toActiveSandboxUiApps(APP_LISTING)
+
+// Any rejection of the open IPC takes the same failure path; its text only
+// picks the banner copy, which these tests deliberately do not assert.
+const OPEN_REJECTED = new Error('open rejected')
+
+// The failure banner is prefixed with the appRef of the failed launch. Waiting
+// on that prefix (not on the copy) pins the moment the page has handled the
+// failure, before the test leaves the tab.
+async function waitForLaunchFailure(appRef: string) {
+ const prefix = `${appRef}: `
+ expect(await screen.findByText(text => text.startsWith(prefix))).toBeTruthy()
+}
+
+const MEASURED_SLOT = {
+ x: 0,
+ y: 0,
+ top: 12,
+ left: 16,
+ right: 416,
+ bottom: 312,
+ width: 400,
+ height: 300,
+ toJSON: () => ({}),
+} as DOMRect
+const UNMEASURED_SLOT = { ...MEASURED_SLOT, width: 0, height: 0, right: 16, bottom: 12 } as DOMRect
+
+function makeSandboxUiBridge() {
+ return {
+ listApps: vi.fn().mockResolvedValue({ apps: APP_LISTING }),
+ listPendingDeepLinks: vi.fn().mockResolvedValue({ links: [] }),
+ clearPendingDeepLinks: vi.fn().mockResolvedValue(undefined),
+ onDeepLink: vi.fn(() => vi.fn()),
+ onTitleChanged: vi.fn(() => vi.fn()),
+ onClosed: vi.fn(() => vi.fn()),
+ onRefreshError: vi.fn(() => vi.fn()),
+ onFindResult: vi.fn(() => vi.fn()),
+ open: vi.fn().mockResolvedValue(undefined),
+ close: vi.fn().mockResolvedValue(undefined),
+ getLocation: vi.fn().mockResolvedValue(null),
+ setVisible: vi.fn().mockResolvedValue(undefined),
+ setBounds: vi.fn().mockResolvedValue(undefined),
+ capturePreview: vi.fn().mockResolvedValue(null),
+ stopFindInPage: vi.fn().mockResolvedValue(undefined),
+ focusActive: vi.fn().mockResolvedValue(true),
+ reload: vi.fn().mockResolvedValue(undefined),
+ }
+}
+
+type OpenGfsPayload = Awaited<ReturnType<typeof openGfsResourcePayload>>
+
+describe('App sandbox-ui ownership survives a failed relaunch', () => {
+ let currentController: AppController
+ let openGfsResourceCb: ((resource: OpenGfsPayload) => void) | null
+ let sandboxUi: ReturnType<typeof makeSandboxUiBridge>
+ let slotRect: ReturnType<typeof vi.spyOn>
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ sidebarHarness.props = null
+ openGfsResourceCb = null
+ currentController = makeController()
+ vi.mocked(useAppController).mockImplementation(() => useReactiveController(currentController))
+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
+ cb(0)
+ return 1
+ })
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe = vi.fn()
+ unobserve = vi.fn()
+ disconnect = vi.fn()
+ }
+ )
+ slotRect = vi
+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')
+ .mockReturnValue(MEASURED_SLOT)
+ sandboxUi = makeSandboxUiBridge()
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ shortcuts: { onCommand: vi.fn(() => vi.fn()) },
+ app: { rendererReady: vi.fn().mockResolvedValue(undefined) },
+ sandboxUi,
+ pluginSdk: {
+ onOpenGfsResource: vi.fn((cb: (resource: OpenGfsPayload) => void) => {
+ openGfsResourceCb = cb
+ return vi.fn()
+ }),
+ },
+ } as unknown as Window['clerum'],
+ })
+ })
+
+ afterEach(async () => {
+ cleanup()
+ await new Promise(resolve => window.setTimeout(resolve, 0))
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ delete (window as { clerum?: unknown }).clerum
+ })
+
+ async function renderWithLiveApp(app: typeof ALPHA) {
+ render(<App />)
+ // The strip relaunch resolves the tab's app against the loaded listing.
+ await waitFor(() => expect(sandboxUi.listApps).toHaveBeenCalled())
+ await act(async () => {
+ await Promise.resolve()
+ })
+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(app!))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
+ await waitFor(() => expect(currentController.navItem).toBe(DESKTOP_ROUTES.apps))
+ }
+
+ function clickActiveStripTab(label: string) {
+ const activeTab = currentController.workspaceTabs.tabs.find(
+ tab => tab.id === currentController.workspaceTabs.activeTabId
+ )
+ expect(activeTab?.kind).toBe('app')
+ // The strip marks the active tab with aria-pressed.
+ fireEvent.click(screen.getByRole('button', { name: label, pressed: true }))
+ }
+
+ async function handOffMarkdownFromPlugin() {
+ const payload = await openGfsResourcePayload(
+ resolvedFile('md1', 'README.md', { gfsUri: 'gfs://main/md1' })
+ )
+ act(() => openGfsResourceCb?.(payload))
+ expect(currentController.navItem).toBe(DESKTOP_ROUTES.preview)
+ }
+
+ it('closes the embed when a plugin handoff leaves the app tab after a relaunch rejected by main', async () => {
+ await renderWithLiveApp(ALPHA)
+ expect(sandboxUi.close).not.toHaveBeenCalled()
+
+ sandboxUi.open.mockRejectedValueOnce(OPEN_REJECTED)
+ clickActiveStripTab('Alpha')
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ await waitForLaunchFailure(ALPHA!.appRef)
+
+ await handOffMarkdownFromPlugin()
+
+ await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ })
+
+ it('closes the embed when a relaunch fails before reaching main (slot never measured)', async () => {
+ await renderWithLiveApp(ALPHA)
+
+ slotRect.mockReturnValue(UNMEASURED_SLOT)
+ clickActiveStripTab('Alpha')
+ await waitForLaunchFailure(ALPHA!.appRef)
+ // The failure happened before the open IPC: main still holds the old view.
+ expect(sandboxUi.open).toHaveBeenCalledTimes(1)
+
+ slotRect.mockReturnValue(MEASURED_SLOT)
+ await handOffMarkdownFromPlugin()
+
+ await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ })
+
+ it('closes the embed when leaving an app tab whose open failed after an app-to-app switch', async () => {
+ await renderWithLiveApp(ALPHA)
+
+ sandboxUi.open.mockRejectedValueOnce(OPEN_REJECTED)
+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ await waitForLaunchFailure(BETA!.appRef)
+ // app→app hands the embed over; it is never closed on the way in.
+ expect(sandboxUi.close).not.toHaveBeenCalled()
+
+ await handOffMarkdownFromPlugin()
+
+ await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ })
+})
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsx
index 847606dae..68015e5ce 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx
+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx
@@ -507,11 +507,6 @@ export function SandboxUiPage({
}
}, [currentTeamId, onNotify])
- const onRemoveApp = useCallback(async () => {
- await closeEmbed()
- onEmbeddedAppRemoved?.()
- }, [closeEmbed, onEmbeddedAppRemoved])
-
useEffect(() => {
if (shortcutOpenRequestId === lastShortcutOpenRequestIdRef.current) return
lastShortcutOpenRequestIdRef.current = shortcutOpenRequestId