Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): tear down a crashed sandbox-ui embed and ignore stale closes
Diego Zacariaseda03c38b41d
diff --git a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.tsindex fdd22afbf..c779ce66e 100644--- a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts+++ b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts@@ -47,6 +47,10 @@ const electronMocks = vi.hoisted(() => {return this}+ emit(event: string, ...args: unknown[]): void {+ this.listeners.get(event)?.forEach(handler => handler(...args))+ }+getURL(): string {return this.currentUrl}@@ -393,3 +397,20 @@ describe('AppService sandbox-ui open replaces the live view whatever its outcomeexpect(getActiveSandboxUi()?.appRef).toBe('sandbox-recipes/second-app')})})++describe('AppService sandbox-ui embed whose renderer dies', () => {+ it('leaves no view, no refresh loop and no pin, and reports the close once', async () => {+ const onClosed = vi.fn()+ const { parentWindow, firstWebContentsId, firstView } = await setupWithLiveFirstApp(onClosed)++ firstView!.webContents.emit('render-process-gone', {}, { reason: 'crashed', exitCode: 139 })++ expect(getActiveSandboxUi()).toBeNull()+ expect(parentWindow.contentView.removeChildView).toHaveBeenCalledWith(firstView)+ expect(resolvePluginSurface(firstWebContentsId)).toBeNull()+ expect(onClosed).toHaveBeenCalledOnce()+ const mintsBefore = mintCallsFor('first-app')+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)+ expect(mintCallsFor('first-app')).toBe(mintsBefore)+ })+})diff --git a/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts b/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.tsindex 3944971c4..e2a69aa1c 100644--- a/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts+++ b/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {findInActiveSandboxUi,focusActiveSandboxUi,+ getActiveSandboxUi,installSandboxUiCookie,mountSandboxUiView,unmountSandboxUiView,@@ -42,6 +43,10 @@ const electronMocks = vi.hoisted(() => {this.listeners.get(event)?.forEach(handler => handler(...args))}+ listenerCount(event: string): number {+ return this.listeners.get(event)?.size ?? 0+ }+getURL(): string {return this.currentUrl}@@ -205,6 +210,62 @@ describe('mountSandboxUiView lifecycle cleanup', () => {expect(onClosed).not.toHaveBeenCalled()})+ // Electron's payload for a dead renderer; any reason (crash, OOM, kill)+ // leaves the view painting its last frame.+ const RENDER_PROCESS_GONE: [unknown, Electron.RenderProcessGoneDetails] = [+ {},+ { reason: 'crashed', exitCode: 139 },+ ]++ it('tears the active view down and reports it closed once when its renderer dies', async () => {+ const parentWindow = new FakeParentWindow()+ const onClosed = vi.fn()+ await mountSandboxUiView(mountArgs({ parentWindow, onClosed }))+ const view = electronMocks.views[0]!++ view.webContents.emit('render-process-gone', ...RENDER_PROCESS_GONE)++ expect(getActiveSandboxUi()).toBeNull()+ expect(parentWindow.contentView.removeChildView).toHaveBeenCalledOnce()+ expect(parentWindow.contentView.removeChildView).toHaveBeenCalledWith(view)+ expect(onClosed).toHaveBeenCalledOnce()+ // The listener went with the view: a repeated signal reports nothing more.+ expect(view.webContents.listenerCount('render-process-gone')).toBe(0)+ view.webContents.emit('render-process-gone', ...RENDER_PROCESS_GONE)+ expect(onClosed).toHaveBeenCalledOnce()+ })++ it('the dead-renderer listener of a replaced view no longer fires', async () => {+ const parentWindow = new FakeParentWindow()+ const firstClosed = vi.fn()+ const secondClosed = vi.fn()+ await mountSandboxUiView(mountArgs({ parentWindow, onClosed: firstClosed }))+ await mountSandboxUiView(+ mountArgs({ parentWindow, recipeName: 'support-desk', onClosed: secondClosed })+ )+ const [first, second] = electronMocks.views++ first!.webContents.emit('render-process-gone', ...RENDER_PROCESS_GONE)++ expect(getActiveSandboxUi()?.webContentsId).toBe(second!.webContents.id)+ expect(parentWindow.contentView.removeChildView).toHaveBeenCalledTimes(1)+ expect(firstClosed).not.toHaveBeenCalled()+ expect(secondClosed).not.toHaveBeenCalled()+ })++ it('removes the dead-renderer listener when the active view is unmounted', async () => {+ const parentWindow = new FakeParentWindow()+ const onClosed = vi.fn()+ await mountSandboxUiView(mountArgs({ parentWindow, onClosed }))+ const view = electronMocks.views[0]!+ expect(view.webContents.listenerCount('render-process-gone')).toBe(1)++ await unmountSandboxUiView()++ expect(view.webContents.listenerCount('render-process-gone')).toBe(0)+ expect(onClosed).not.toHaveBeenCalled()+ })+it('focuses only the currently mounted native view', async () => {expect(focusActiveSandboxUi()).toBe(false)const parentWindow = new FakeParentWindow()diff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.tsindex d0ad53a9b..6e6cde56d 100644--- a/desktop-app/src/sandboxUiDriver.ts+++ b/desktop-app/src/sandboxUiDriver.ts@@ -137,6 +137,7 @@ type ActiveView = {rpcProxyOrigin: stringcleanupClientRouteHandoff?: () => voidcleanupParentClosed?: () => void+ cleanupRenderProcessGone?: () => voidcleanupShortcutRouting?: () => voidcleanupDocumentLifecycle?: () => voidcleanupFindResults?: () => void@@ -313,13 +314,16 @@ export async function installSandboxUiCookie(setCookie: string | string[]): Prom})}-async function teardownActive(reason: 'replaced' | 'closed' | 'parent_closed'): Promise<void> {+async function teardownActive(+ reason: 'replaced' | 'closed' | 'parent_closed' | 'crashed'+): Promise<void> {if (!active) returnconst current = activeactive = nulltry {current.cleanupClientRouteHandoff?.()current.cleanupParentClosed?.()+ current.cleanupRenderProcessGone?.()current.cleanupShortcutRouting?.()current.cleanupDocumentLifecycle?.()current.cleanupFindResults?.()@@ -436,11 +440,10 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void},})- // The closed callback fires when the renderer gives up the view (parent- // window closed, teardown via removeChildView, or the embed crashed).- // For now we only wire the parent-window-closed case so the renderer can- // re-render its picker; teardown via `unmountSandboxUiView` is a- // synchronous user action (no callback needed).+ // `onClosed` reports a teardown nobody asked for: the parent window closed+ // or the embed's renderer died. Solicited teardowns (`unmountSandboxUiView`,+ // a replacing mount) stay silent — the caller already knows, and the+ // renderer drops its owner of the embed on that signal.const onParentClosed = (): void => {void teardownActive('parent_closed')onClosed?.()@@ -449,6 +452,20 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<voidconst cleanupParentClosed = (): void => {parentWindow.removeListener('closed', onParentClosed)}+ // A dead renderer leaves its last frame painted over the app with nothing+ // behind it, whatever the reason. The identity check keeps a late signal+ // from a view that was already replaced from tearing down its successor.+ // `mountGeneration` is deliberately left alone: bumping it would abort an+ // unrelated mount that is in flight.+ const onRenderProcessGone = (): void => {+ if (active?.view !== view) return+ void teardownActive('crashed')+ onClosed?.()+ }+ view.webContents.on('render-process-gone', onRenderProcessGone)+ const cleanupRenderProcessGone = (): void => {+ view.webContents.removeListener('render-process-gone', onRenderProcessGone)+ }active = {view,@@ -459,6 +476,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<voidparentWindow,rpcProxyOrigin: proxyOriginUrl,cleanupParentClosed,+ cleanupRenderProcessGone,documentGeneration: 0,documentReady: false,}diff --git a/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx b/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsxindex 75b73f66e..d19dfd3c1 100644--- a/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx+++ b/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx@@ -435,6 +435,94 @@ describe('App sandbox-ui embed always has an owning app tab', () => {await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))})+ // main tags `sandboxUi:closed` with the appRef it composed from the open+ // request (`${recipeNs}/${recipeName}` in the `sandboxUi:open` handler).+ // Derive it from the open() call the real page sent instead of restating it.+ function closedEventFor(openCall: number): { appRef: string } {+ const request = sandboxUi.open.mock.calls[openCall]![0] as {+ recipeNs: string+ recipeName: string+ }+ return { appRef: `${request.recipeNs}/${request.recipeName}` }+ }++ function emitSandboxUiClosed(event: { appRef: string }) {+ const listeners = sandboxUi.onClosed.mock.calls as unknown as Array<+ [(args: { appRef: string }) => void]+ >+ const unsubscribed = new Set(+ sandboxUi.onClosed.mock.results+ .map((result, index) =>+ (result.value as ReturnType<typeof vi.fn>).mock.calls.length > 0 ? index : -1+ )+ .filter(index => index >= 0)+ )+ act(() => {+ listeners.forEach(([listener], index) => {+ if (!unsubscribed.has(index)) listener(event)+ })+ })+ }++ it('keeps the live embed owned when a late closed event belongs to the app it replaced', async () => {+ await renderWithLiveApp(ALPHA)+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))+ await act(async () => {+ await new Promise(resolve => window.setTimeout(resolve, 0))+ })++ emitSandboxUiClosed(closedEventFor(0))++ await handOffMarkdownFromPlugin()+ await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))+ })++ it('keeps the newer launch owned when a superseded open resolves late and its view then dies', async () => {+ render(<App />)+ await waitFor(() => expect(sandboxUi.listApps).toHaveBeenCalled())+ await act(async () => {+ await Promise.resolve()+ })+ let resolveAlphaOpen: () => void = () => {}+ sandboxUi.open.mockImplementationOnce(+ () => new Promise<undefined>(resolve => (resolveAlphaOpen = () => resolve(undefined)))+ )+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(ALPHA!))+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))++ // main serves the opens in order: Alpha mounts first, and its renderer dies+ // before Beta's open replaces it.+ await act(async () => {+ resolveAlphaOpen()+ await new Promise(resolve => window.setTimeout(resolve, 0))+ })+ emitSandboxUiClosed(closedEventFor(0))++ await handOffMarkdownFromPlugin()+ await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))+ })++ it('drops the owner when the closed event belongs to the live embed', async () => {+ await renderWithLiveApp(ALPHA)+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))+ await act(async () => {+ await new Promise(resolve => window.setTimeout(resolve, 0))+ })++ emitSandboxUiClosed(closedEventFor(1))++ await handOffMarkdownFromPlugin()+ await act(async () => {+ await new Promise(resolve => window.setTimeout(resolve, 0))+ })+ // main already tore the view down: nothing is left to close.+ expect(sandboxUi.close).not.toHaveBeenCalled()+ })+it('opens a grid pick shown inside an app tab after back-to-apps as its own tab, leaving that tab intact', async () => {await renderWithLiveApp(ALPHA)const alphaTab = activeWorkspaceTab(currentController.workspaceTabs)diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsxindex 19fe81fe0..e731fb480 100644--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx@@ -223,7 +223,20 @@ export function SandboxUiPage({}: SandboxUiPageProps) {const [apps, setApps] = useState<SandboxUiAppListing[] | null>(null)const [error, setError] = useState<string | null>(null)- const [launch, setLaunch] = useState<LaunchState>({ kind: 'idle' })+ const [launch, setLaunchState] = useState<LaunchState>({ kind: 'idle' })+ // Mirrors `launch` synchronously: the `sandboxUi:closed` listener must judge+ // the launch that is current when the event lands, not the last committed+ // render.+ const launchRef = useRef<LaunchState>({ kind: 'idle' })+ // Bumped by every launch and by back-to-apps. An open that resolves after a+ // newer one took over must not write its outcome: that would re-point+ // `launchRef` at the superseded app, so a later `closed` for it would release+ // the owner of the embed that is actually live.+ const launchSeqRef = useRef(0)+ const setLaunch = useCallback((next: LaunchState) => {+ launchRef.current = next+ setLaunchState(next)+ }, [])const [refreshError, setRefreshError] = useState<{ appRef: string; message: string } | null>(null)const [appsPage, setAppsPage] = useState(0)const [embedPreviewDataUrl, setEmbedPreviewDataUrl] = useState<string | null>(null)@@ -267,16 +280,22 @@ export function SandboxUiPage({}, [apps?.length])// Re-render the picker if the main process tears the view down (e.g. on- // app quit, parent window close, or partition GC).+ // app quit, parent window close, or the embed's renderer crashing).useEffect(() => {- return window.clerum.sandboxUi.onClosed(() => {- setLaunch(current =>- current.kind === 'mounted' || current.kind === 'minting' ? { kind: 'idle' } : current- )+ return window.clerum.sandboxUi.onClosed(({ appRef }) => {+ // A closed event can land after the renderer has already launched+ // another app (it was in flight when the switch happened). Reconciling it+ // would drop the owner of the NEW embed, which then stays painted over+ // every later surface. Only the launch it names may be released.+ const current = launchRef.current+ if (current.kind === 'idle' || current.appRef !== appRef) return+ if (current.kind === 'mounted' || current.kind === 'minting') {+ setLaunch({ kind: 'idle' })+ }setRefreshError(null)onEmbeddedAppBack?.()})- }, [onEmbeddedAppBack])+ }, [onEmbeddedAppBack, setLaunch])// Surface refresh failures (403 / 410 / network) as an in-chrome banner.// The main-process timer has already stopped firing by the time we get@@ -401,6 +420,7 @@ export function SandboxUiPage({// position (otherwise we'd be reading before React has rendered the// slot, and the fallback would mount the WebContentsView full-window —// covering the close button until the next ResizeObserver tick).+ const seq = ++launchSeqRef.currentsetLaunch({ kind: 'minting', appRef: app.appRef })onEmbeddedAppOpening?.({appRef: app.appRef,@@ -425,8 +445,10 @@ export function SandboxUiPage({...(app.routePath ? { routePath: app.routePath } : {}),bounds,})- setLaunch({ kind: 'mounted', appRef: app.appRef })- onEmbeddedAppMounted?.()+ if (seq === launchSeqRef.current) {+ setLaunch({ kind: 'mounted', appRef: app.appRef })+ onEmbeddedAppMounted?.()+ }return { status: 'mounted' }} catch (err) {const { status, message } = statusFromError(err)@@ -438,15 +460,18 @@ export function SandboxUiPage({: status === 409? 'This app is starting up — try again in a moment.': message- setLaunch({ kind: 'error', appRef: app.appRef, message: userFacing })- onEmbeddedAppOpenFailed?.()+ if (seq === launchSeqRef.current) {+ setLaunch({ kind: 'error', appRef: app.appRef, message: userFacing })+ onEmbeddedAppOpenFailed?.()+ }return { status: 'failed', message: userFacing }}},- [onEmbeddedAppMounted, onEmbeddedAppOpening, onEmbeddedAppOpenFailed]+ [onEmbeddedAppMounted, onEmbeddedAppOpening, onEmbeddedAppOpenFailed, setLaunch])const closeEmbed = useCallback(async () => {+ launchSeqRef.current += 1try {await window.clerum.sandboxUi.close()} catch {@@ -455,7 +480,7 @@ export function SandboxUiPage({}setLaunch({ kind: 'idle' })setRefreshError(null)- }, [])+ }, [setLaunch])const onBackToApps = useCallback(async () => {await closeEmbed()