Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
refactor(desktop-app): retire the legacy embedded app view IPC
Diego Zacariasbba74d4c659a
diff --git a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts b/desktop-app/src/__tests__/appService.sandboxUiApps.test.tsindex 36ab4c4fd..8576cb1d4 100644--- a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts+++ b/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts@@ -608,58 +608,3 @@ describe('AppService profile UI link authority', () => {expect(service.memberRegistrationServiceClient.getInvitationProfile).not.toHaveBeenCalled()})})--// Round-trip of the renderer's route-persistence read (mini-spec 05 §1/§2). The-// driver output shapes fed to the mock are the ones the REAL producer emits:-// `{ recipeNs, recipeName, path }` where `path` is what `resolveSandboxUiSharePath`-// returns (see sandboxUiDriver.test.ts — a non-default route yields '/tickets/42',-// a default route yields undefined, an out-of-prefix URL throws).-describe('AppService.getSandboxUiLocation', () => {- it('reshapes a non-default route into { appRef, routePath }', async () => {- const service = makeService() as unknown as {- getSandboxUiLocation: () => Promise<{ appRef: string; routePath?: string } | null>- }- mockGetActiveSandboxUiLocation.mockReturnValue({- recipeNs: 'ns',- recipeName: 'app',- path: '/tickets/42',- })-- await expect(service.getSandboxUiLocation()).resolves.toEqual({- appRef: 'ns/app',- routePath: '/tickets/42',- })- })-- it('omits routePath when the active app is on its default route', async () => {- const service = makeService() as unknown as {- getSandboxUiLocation: () => Promise<{ appRef: string; routePath?: string } | null>- }- // Default route → the driver omits `path`.- mockGetActiveSandboxUiLocation.mockReturnValue({ recipeNs: 'ns', recipeName: 'app' })-- await expect(service.getSandboxUiLocation()).resolves.toEqual({ appRef: 'ns/app' })- })-- it('returns null when no embed is mounted or its webContents is destroyed', async () => {- const service = makeService() as unknown as {- getSandboxUiLocation: () => Promise<{ appRef: string; routePath?: string } | null>- }- mockGetActiveSandboxUiLocation.mockReturnValue(null)-- await expect(service.getSandboxUiLocation()).resolves.toBeNull()- })-- it('propagates the out-of-prefix throw so the renderer falls back to default', async () => {- const service = makeService() as unknown as {- getSandboxUiLocation: () => Promise<{ appRef: string; routePath?: string } | null>- }- mockGetActiveSandboxUiLocation.mockImplementation(() => {- throw new Error('Cannot read the current app route')- })-- await expect(service.getSandboxUiLocation()).rejects.toThrow(- 'Cannot read the current app route'- )- })-})diff --git a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.tsindex a9d8066cb..fa1525f89 100644--- a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts+++ b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts@@ -9,7 +9,11 @@ import { wireMainWindowRendererReadiness } from '../mainWindowReadiness.js'import { _resetPluginSdkRuntimeForTests, initPluginSdkRuntime } from '../pluginSdkRuntime.js'import { _resetPluginSurfacesForTests, resolvePluginSurface } from '../pluginSurfaceRegistry.js'import { SANDBOX_UI_MINT_TIMEOUT_MS } from '../rpcProxyClient.js'-import { getActiveSandboxUi, unmountSandboxUiView } from '../sandboxUiDriver.js'+import {+ getActiveSandboxUi,+ getActiveSandboxUiLocation,+ unmountSandboxUiView,+} from '../sandboxUiDriver.js'import {SANDBOX_UI_RATE_LIMIT_MS,SANDBOX_UI_REFRESH_INTERVAL_MS,@@ -149,7 +153,7 @@ type OpenArgs = Parameters<AppService['openSandboxUi']>[0]function openArgs(recipeName: string,parentWindow: FakeParentWindow,- onClosed: () => void = vi.fn(),+ onReleased: NonNullable<OpenArgs['onReleased']> = vi.fn(),overrides: Partial<Omit<OpenArgs, 'parentWindow'>> = {}): OpenArgs {return {@@ -160,7 +164,7 @@ function openArgs(bounds: { x: 0, y: 0, width: 400, height: 300 },parentWindow: parentWindow as unknown as OpenArgs['parentWindow'],launchId: crypto.randomUUID(),- onClosed,+ onReleased,...overrides,}}@@ -191,11 +195,11 @@ afterEach(async () => {await rm(userDataDir, { recursive: true, force: true })})-async function setupWithLiveFirstApp(onClosed: () => void = vi.fn()) {+async function setupWithLiveFirstApp(onReleased: NonNullable<OpenArgs['onReleased']> = vi.fn()) {const service = makeService()initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })const parentWindow = new FakeParentWindow()- await service.openSandboxUi(openArgs('first-app', parentWindow, onClosed))+ await service.openSandboxUi(openArgs('first-app', parentWindow, onReleased))const first = getActiveSandboxUi()expect(first?.appRef).toBe('sandbox-recipes/first-app')expect(resolvePluginSurface(first!.webContentsId)?.pluginId).toBe('sandbox-recipes/first-app')@@ -274,54 +278,20 @@ describe('AppService sandbox-ui open replaces the live view whatever its outcomeexpect(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')- })})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)+ it('leaves no view, no refresh loop and no pin, and reports the release once', async () => {+ const onReleased = vi.fn()+ const { parentWindow, firstWebContentsId, firstView } = await setupWithLiveFirstApp(onReleased)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()+ expect(onReleased).toHaveBeenCalledOnce()+ expect(onReleased).toHaveBeenCalledWith(expect.objectContaining({ reason: 'crashed' }))const mintsBefore = mintCallsFor('first-app')await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)expect(mintCallsFor('first-app')).toBe(mintsBefore)@@ -484,9 +454,7 @@ async function expectEmbedGoneWithoutRefresh(describe('AppService sandbox-ui embed whose trusted renderer is replaced', () => {it('a committed document navigation of the main window closes the embed', async () => {- const onClosed = vi.fn()- const { service, parentWindow, firstWebContentsId, firstView } =- await setupWithLiveFirstApp(onClosed)+ const { service, parentWindow, firstWebContentsId, firstView } = await setupWithLiveFirstApp()const mainWebContents = wireMainWindow(service)// A reload (Cmd+R / View > Reload with the renderer focused) or a new@@ -495,8 +463,6 @@ describe('AppService sandbox-ui embed whose trusted renderer is replaced', () =>mainWebContents.emit('did-navigate', {}, 'file:///ui-dist/index.html', 200, 'OK')await expectEmbedGoneWithoutRefresh(parentWindow, firstView, firstWebContentsId)- // The replacement renderer starts without state: nothing to notify.- expect(onClosed).not.toHaveBeenCalled()})it('in-page, subframe and cancelled navigations of the main window leave the embed', async () => {@@ -562,13 +528,13 @@ describe('AppService sandbox-ui embed across a session clear', () => {}it('an open whose mint lands after logout installs nothing and rejects', async () => {- const onClosed = vi.fn()+ const onReleased = vi.fn()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, onClosed))+ const open = service.openSandboxUi(openArgs('first-app', parentWindow, onReleased))const outcome = open.then(() => 'opened',(error: unknown) => error@@ -580,7 +546,8 @@ describe('AppService sandbox-ui embed across a session clear', () => {const settled = await outcomeawait expectNothingMountedFor(parentWindow, service)expect(settled).toMatchObject({ message: expect.stringMatching(/session changed/) })- expect(onClosed).not.toHaveBeenCalled()+ // No view was ever assigned to this launch, so it is never released.+ expect(onReleased).not.toHaveBeenCalled()})it('an open whose mint lands after another user logged in installs nothing and rejects', async () => {@@ -692,13 +659,13 @@ describe('AppService sandbox-ui embed across a session clear', () => {})it('an open whose mint fails after logout leaves nothing behind and rejects once', async () => {- const onClosed = vi.fn()+ const onReleased = vi.fn()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, onClosed))+ const open = service.openSandboxUi(openArgs('first-app', parentWindow, onReleased))const outcome = open.then(() => 'opened',(error: unknown) => error@@ -716,7 +683,8 @@ describe('AppService sandbox-ui embed across a session clear', () => {expect(getActiveSandboxUi()).toBeNull()expect(parentWindow.contentView.addChildView).not.toHaveBeenCalled()expect(parentWindow.contentView.removeChildView).not.toHaveBeenCalled()- expect(onClosed).not.toHaveBeenCalled()+ // No view was ever assigned to this launch, so it is never released.+ expect(onReleased).not.toHaveBeenCalled()await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)expect(mintCallsFor('first-app')).toBe(1)})@@ -775,12 +743,12 @@ describe('AppService sandbox-ui embed across a login that replaces a live sessio}it('an open whose mint lands after B logged in over A installs nothing and rejects', async () => {- const onClosed = vi.fn()+ const onReleased = vi.fn()const service = await serviceLoggedInAsA()const parentWindow = new FakeParentWindow()const answerMint = holdMint('first-app')- const outcome = service.openSandboxUi(openArgs('first-app', parentWindow, onClosed)).then(+ const outcome = service.openSandboxUi(openArgs('first-app', parentWindow, onReleased)).then(() => 'opened',(error: unknown) => error)@@ -795,7 +763,8 @@ describe('AppService sandbox-ui embed across a login that replaces a live sessioexpect(electronMocks.views).toHaveLength(0)expect(parentWindow.contentView.addChildView).not.toHaveBeenCalled()expect(getActiveSandboxUi()).toBeNull()- expect(onClosed).not.toHaveBeenCalled()+ // No view was ever assigned to this launch, so it is never released.+ expect(onReleased).not.toHaveBeenCalled()await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)expect(mintCallsFor('first-app')).toBe(1)})@@ -1014,7 +983,7 @@ describe('AppService sandbox-ui view release', () => {expect(released).toEqual([])expectNoOrphanView(parentWindow)- // The legacy close names no launch and still closes whatever is live.+ // Main's own close names no launch and closes whatever is live.await service.closeSandboxUi()expect(getActiveSandboxUi()).toBeNull()expect(released).toEqual([{ launchId: args.launchId, reason: 'closed', location: {} }])@@ -1123,9 +1092,10 @@ describe('AppService sandbox-ui represented location', () => {await service.openSandboxUi(first)const webContents = electronMocks.views[0]!.webContents- await expect(service.getSandboxUiLocation()).resolves.toEqual({- appRef: 'sandbox-recipes/first-app',- routePath: '/r/first',+ expect(getActiveSandboxUiLocation()).toEqual({+ recipeNs: 'sandbox-recipes',+ recipeName: 'first-app',+ path: '/r/first',})// The document commits and the driver hands the route to the app.@@ -1134,9 +1104,10 @@ describe('AppService sandbox-ui represented location', () => {timeout: 1_000,})webContents.navigateInPage(`${APP_VIEW_URL}/inbox`)- await expect(service.getSandboxUiLocation()).resolves.toEqual({- appRef: 'sandbox-recipes/first-app',- routePath: '/inbox',+ expect(getActiveSandboxUiLocation()).toEqual({+ recipeNs: 'sandbox-recipes',+ recipeName: 'first-app',+ path: '/inbox',})await service.closeSandboxUi({ launchId: first.launchId })@@ -1165,9 +1136,10 @@ describe('AppService sandbox-ui represented location', () => {// rpc-proxy answers with a "starting" interstitial: the handoff waits.webContents.commitLoad(503)- await expect(service.getSandboxUiLocation()).resolves.toEqual({- appRef: 'sandbox-recipes/first-app',- routePath: '/r/first',+ expect(getActiveSandboxUiLocation()).toEqual({+ recipeNs: 'sandbox-recipes',+ recipeName: 'first-app',+ path: '/r/first',})webContents.navigateInPage(`${APP_VIEW_URL}/elsewhere`)@@ -1183,8 +1155,9 @@ describe('AppService sandbox-ui represented location', () => {await service.openSandboxUi(first)const webContents = electronMocks.views[0]!.webContents- await expect(service.getSandboxUiLocation()).resolves.toEqual({- appRef: 'sandbox-recipes/first-app',+ expect(getActiveSandboxUiLocation()).toEqual({+ recipeNs: 'sandbox-recipes',+ recipeName: 'first-app',})webContents.commitLoad()webContents.navigateInPage(`${APP_VIEW_URL}/settings`)@@ -1414,10 +1387,8 @@ describe('AppService sandbox-ui teardown isolates every step', () => {const { service, parentWindow, released, args, view } = await openLive()view.webContents.commitLoad()view.webContents.navigateInPage('https://elsewhere.example/landing')- // The legacy reader keeps rejecting, so the renderer falls back.- await expect(service.getSandboxUiLocation()).rejects.toThrow(- 'Cannot read the current app route'- )+ // The deep link refuses it, and the release reports no location.+ expect(() => getActiveSandboxUiLocation()).toThrow('Cannot read the current app route')await expect(service.closeSandboxUi({ launchId: args.launchId })).resolves.toBeUndefined()@@ -1438,28 +1409,29 @@ describe('AppService sandbox-ui route settling', () => {}const location = (routePath?: string) => ({- appRef: 'sandbox-recipes/first-app',- ...(routePath ? { routePath } : {}),+ recipeNs: 'sandbox-recipes',+ recipeName: 'first-app',+ ...(routePath ? { path: routePath } : {}),})it('a view with no requested route reports where the server sent its first load', async () => {const { service, webContents } = await openLoading()webContents.commitLoad(200, `${APP_VIEW_URL}/welcome`)- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/welcome'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/welcome'))})it('an in-page navigation before the first load does not replace the requested route', async () => {const { service, webContents } = await openLoading('/r/first')webContents.navigateInPage(`${APP_VIEW_URL}/#boot`)webContents.commitLoad(503)- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/r/first'))})it('an in-page navigation of a subframe does not replace the requested route', async () => {const { service, webContents } = await openLoading('/r/first')webContents.commitLoad(503)webContents.emit('did-navigate-in-page', {}, `${APP_VIEW_URL}/frame`, false)- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/r/first'))})it('a handoff that finds the app already on the route settles it', async () => {@@ -1469,7 +1441,7 @@ describe('AppService sandbox-ui route settling', () => {timeout: 1_000,})await expect(webContents.executeJavaScript.mock.results[0]!.value).resolves.toBe(true)- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/r/first'))})it('a handoff the app does not take keeps the requested route', async () => {@@ -1480,7 +1452,7 @@ describe('AppService sandbox-ui route settling', () => {timeout: 1_000,})await expect(webContents.executeJavaScript.mock.results[0]!.value).resolves.toBe(false)- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/r/first'))})it('a new document the user opens after the handoff gave up is the live route', async () => {@@ -1490,10 +1462,10 @@ describe('AppService sandbox-ui route settling', () => {// A reload commits the same document: still the requested route.webContents.commitLoad()- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/r/first'))webContents.navigateTo(`${APP_VIEW_URL}/reports`)- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/reports'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/reports'))await service.closeSandboxUi()expect(released.map(event => event.location)).toEqual([{ routePath: '/reports' }])})@@ -1503,7 +1475,7 @@ describe('AppService sandbox-ui route settling', () => {const { service, webContents } = await openLoading('/r/first')await vi.advanceTimersByTimeAsync(30_000)webContents.commitLoad()- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/r/first'))})it('a document committed outside the app does not replace the requested route', async () => {@@ -1511,7 +1483,7 @@ describe('AppService sandbox-ui route settling', () => {webContents.commitLoad(503)await vi.advanceTimersByTimeAsync(30_000)webContents.navigateTo('https://elsewhere.example/landing')- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/r/first'))})it('a reload after the router moved the URL during boot keeps the requested route', async () => {@@ -1521,23 +1493,23 @@ describe('AppService sandbox-ui route settling', () => {webContents.navigateInPage(`${APP_VIEW_URL}/home`)await vi.advanceTimersByTimeAsync(30_000)webContents.emit('did-finish-load')- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/r/first'))// A reload commits the document the view is already showing.webContents.emit('did-navigate', {}, `${APP_VIEW_URL}/home`, 200, '')webContents.emit('did-finish-load')- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/r/first'))})it('a new document committed while the handoff still waits keeps the requested route', async () => {const { service, webContents } = await openLoading('/r/first')webContents.commitLoad(503)webContents.navigateTo(`${APP_VIEW_URL}/starting`, 503)- await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))+ expect(getActiveSandboxUiLocation()).toEqual(location('/r/first'))})})-describe('sandbox-ui IPC close ordering and legacy payloads', () => {+describe('sandbox-ui IPC close ordering and payloads', () => {type Sender = { id: number }async function setupIpc() {@@ -1570,17 +1542,42 @@ describe('sandbox-ui IPC close ordering and legacy payloads', () => {return { service, parentWindow, invoke, open, releasedSends }}- it('a null payload is the legacy close of whatever is live', async () => {- const { invoke, open, releasedSends, parentWindow } = await setupIpc()+ // The renderer always names its launch. A close without one used to close+ // whatever was live, which by the time the queue reached it could be a view+ // another launch owned.+ it.each([undefined, null, {}])(+ 'rejects a close with payload %j without closing the live view',+ async payload => {+ const { service, invoke, open, releasedSends, parentWindow } = await setupIpc()+ const launchId = crypto.randomUUID()+ await open(launchId)++ await expect(invoke('sandboxUi:close', payload)).rejects.toThrow(/launchId/)+ await drainLifecycleQueue(service)++ expect(getActiveSandboxUi()?.launchId).toBe(launchId)+ expect(parentWindow.contentView.children).toHaveLength(1)+ expect(releasedSends()).toEqual([])+ }+ )++ // A view main tears down on its own (crash, parent closed) reaches the+ // renderer only as its release; there is no second "closed" signal for the+ // renderer to reconcile against it.+ it('a view whose renderer dies is reported to its window only by its release', async () => {+ const { open, parentWindow } = await setupIpc()const launchId = crypto.randomUUID()await open(launchId)+ parentWindow.webContents.send.mockClear()- await invoke('sandboxUi:close', null)+ electronMocks.views[0]!.webContents.emit(+ 'render-process-gone',+ {},+ { reason: 'crashed', exitCode: 139 }+ )- expect(getActiveSandboxUi()).toBeNull()- expectNoOrphanView(parentWindow)- expect(releasedSends()).toEqual([- ['sandboxUi:released', { launchId, reason: 'closed', location: {} }],+ expect(parentWindow.webContents.send.mock.calls).toEqual([+ ['sandboxUi:released', { launchId, reason: 'crashed', location: null }],])})diff --git a/desktop-app/src/__tests__/ipc.sandboxUiLaunchId.test.ts b/desktop-app/src/__tests__/ipc.sandboxUiLaunchId.test.tsindex 857f10cc3..d9d1b2bab 100644--- a/desktop-app/src/__tests__/ipc.sandboxUiLaunchId.test.ts+++ b/desktop-app/src/__tests__/ipc.sandboxUiLaunchId.test.ts@@ -73,13 +73,11 @@ describe('sandboxUi:open launch id', () => {const [first, second] = opens// The replaced view reports after the relaunch of the same app.- first!.onClosed?.()first!.onRefreshError?.('refresh failed')first!.onTitleChanged?.('Old title')second!.onTitleChanged?.('New title')expect(electron.send.mock.calls).toEqual([- ['sandboxUi:closed', { appRef: 'sandbox-recipes/alpha', launchId: launch1 }],['sandboxUi:refreshError',{ appRef: 'sandbox-recipes/alpha', launchId: launch1, message: 'refresh failed' },@@ -115,10 +113,11 @@ describe('sandboxUi:open launch id', () => {it('accepts a renderer-minted UUID', async () => {const launchId = crypto.randomUUID()await open({ launchId })- opens[0]!.onClosed?.()- expect(electron.send).toHaveBeenCalledWith('sandboxUi:closed', {+ opens[0]!.onTitleChanged?.('Title')+ expect(electron.send).toHaveBeenCalledWith('sandboxUi:titleChanged', {appRef: 'sandbox-recipes/alpha',launchId,+ title: 'Title',})})})diff --git a/desktop-app/src/__tests__/sandboxUiDriver.test.ts b/desktop-app/src/__tests__/sandboxUiDriver.test.tsindex e9955c9f3..7d38a3427 100644--- a/desktop-app/src/__tests__/sandboxUiDriver.test.ts+++ b/desktop-app/src/__tests__/sandboxUiDriver.test.ts@@ -198,9 +198,8 @@ describe('sandbox UI route normalization', () => {})it('returns the in-prefix pathname for a non-default route (mini-spec 05 §2)', () => {- // The real producer of the route the renderer persists on deactivation:- // a nested view URL yields its pathname (leading-slash share form). This is- // the value `appService.getSandboxUiLocation` reshapes into `routePath`.+ // The real producer of the route a released view reports and a deep link+ // carries: a nested view URL yields its pathname (leading-slash share form).expect(resolveSandboxUiSharePath({currentUrl: 'https://rpc.example/api/v1/sandbox-ui/ns/app/view/tickets/42',diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 2a149afaa..1dc6d5672 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -5292,7 +5292,6 @@ export class AppService {routePath?: stringbounds: import('./sandboxUiDriver.js').SandboxUiBoundsparentWindow: import('electron').BrowserWindow- onClosed?: () => void/** Exactly once per view this open mounts, even if the open then rejects. */onReleased?: (event: import('./sandboxUiDriver.js').SandboxUiReleasedEvent) => voidonRefreshError?: (message: string) => void@@ -5317,10 +5316,7 @@ export class AppService {// 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.+ // told the open failed. Failure is reported only by the rejection.await this.teardownSandboxUiView('replaced')try {await this.mintAndMountSandboxUiView(args, recipeNs, recipeName, sessionEpoch)@@ -5360,6 +5356,8 @@ export class AppService {bounds: args.bounds,launchId: args.launchId,onReleased: args.onReleased,+ // A teardown main did not ask for (crash, parent window closed) skips+ // `teardownSandboxUiView`, so its cleanup runs here.onClosed: () => {// Cancel refresh first so the timer doesn't keep firing against a// partition we're about to evict on the next mount.@@ -5368,7 +5366,6 @@ export class AppService {// per-mount SDK state (session denials, prompt budget, rate budget)// dies with the mount.tryGetPluginSdkRuntime()?.unpinAllSandboxUiSurfaces()- args.onClosed?.()},onGfsOpen: uri => {const active = tryGetPluginSdkRuntime()@@ -5444,8 +5441,9 @@ export class AppService {/*** With a `launchId`, closes the view only if that launch still owns it: a* close that arrives after its view was replaced must not take down the- * replacement. Without one, closes whatever is live. Enqueued synchronously,- * like `openSandboxUi`.+ * replacement. Without one, closes whatever is live; only main's own callers+ * (session change, renderer replaced) do that, the renderer must always name+ * its launch. Enqueued synchronously, like `openSandboxUi`.*/closeSandboxUi(options: {@@ -5481,25 +5479,6 @@ export class AppService {await driver.unmountSandboxUiView(reason)}- // Read the active embed's current in-app route for the renderer's tab store- // (mini-spec 05 §1). Mirrors `createSandboxUiDeepLink`'s read: it wraps- // `driver.getActiveSandboxUiLocation()` and reshapes to the renderer contract.- // Returns null when no embed is mounted or its webContents is destroyed.- // While the view has not yet applied the route its open asked for, that route- // is returned without reading the URL. Once applied, an out-of-prefix current- // URL makes `getActiveSandboxUiLocation` THROW ('Cannot read the current app- // route'); that propagates so the renderer can fall back to the default route- // instead of persisting a stale one.- async getSandboxUiLocation(): Promise<{ appRef: string; routePath?: string } | null> {- const driver = await import('./sandboxUiDriver.js')- const location = driver.getActiveSandboxUiLocation()- if (!location) return null- return {- appRef: `${location.recipeNs}/${location.recipeName}`,- ...(location.path ? { routePath: location.path } : {}),- }- }-async createSandboxUiDeepLink(teamId?: string): Promise<{ url: string }> {const driver = await import('./sandboxUiDriver.js')const { buildSandboxUiWebLink } = await import('./sandboxUiDeepLinks.js')@@ -5516,15 +5495,6 @@ export class AppService {}}- // In-place hard-reload of the active embed (user-initiated "Refresh"). The- // session cookie is still valid, so this only reloads page content — it does- // NOT re-mint the session or cancel the refresh timer. No-op when nothing is- // mounted.- async reloadSandboxUi(): Promise<void> {- const driver = await import('./sandboxUiDriver.js')- driver.reloadActiveSandboxUiView()- }-async setSandboxUiBounds(bounds: import('./sandboxUiDriver.js').SandboxUiBounds): Promise<void> {const { setSandboxUiBounds } = await import('./sandboxUiDriver.js')setSandboxUiBounds(bounds)diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex 4d5ec8b8d..dcbbe36ae 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -2078,10 +2078,6 @@ export function registerIpcHandlers(service: AppService): void {routePath: typeof payload?.routePath === 'string' ? payload.routePath : undefined,bounds,parentWindow,- onClosed: () => {- if (parentWindow.isDestroyed()) return- parentWindow.webContents.send('sandboxUi:closed', { appRef, launchId })- },// Only the window the view was mounted in owns it.onReleased: released => {if (parentWindow.isDestroyed()) return@@ -2103,33 +2099,15 @@ export function registerIpcHandlers(service: AppService): void {})- // Without a payload this is the legacy close of whatever is live. With one,- // the launch id is mandatory: a malformed id must not degrade into closing- // another launch's view.+ // The launch id is mandatory: a close that names no launch, or a malformed+ // one, must not degrade into closing whatever view is live, which another+ // launch may own by the time the queue reaches it.ipcMain.handle('sandboxUi:close', async (event, payload?: { launchId?: unknown } | null) => {assertTrustedSender(event)- if (payload === undefined || payload === null) {- await service.closeSandboxUi()- return- }- const launchId = parseSandboxUiLaunchId(payload.launchId)+ const launchId = parseSandboxUiLaunchId(payload?.launchId)await service.closeSandboxUi({ launchId })})- ipcMain.handle('sandboxUi:reload', async event => {- assertTrustedSender(event)- await service.reloadSandboxUi()- })-- // Read the active embed's current in-app route so the renderer can persist it- // on the app tab before deactivation (mini-spec 05 §1). Returns null when no- // embed is mounted; rejects when the current URL is outside the recipe prefix- // (the renderer treats a rejection as "fall back to the default route").- ipcMain.handle('sandboxUi:getLocation', async event => {- assertTrustedSender(event)- return service.getSandboxUiLocation()- })-ipcMain.handle('sandboxUi:copyDeepLink', async (event, payload: { teamId?: unknown }) => {assertTrustedSender(event)const teamId = sanitizeString(payload?.teamId)diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex ab30961b7..78e4e8385 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -672,11 +672,8 @@ const clerum = Object.freeze({bounds: { x: number; y: number; width: number; height: number; dpr?: number }launchId: string}) => ipcRenderer.invoke('sandboxUi:open', args),- // Without args: legacy close of whatever is live. With a launch id: closes- // that launch's view only if it is still the live one.- close: (args?: { launchId: string }) => ipcRenderer.invoke('sandboxUi:close', args),- reload: () => ipcRenderer.invoke('sandboxUi:reload'),- getLocation: () => ipcRenderer.invoke('sandboxUi:getLocation'),+ // Closes that launch's view only if it is still the live one.+ close: (args: { launchId: string }) => ipcRenderer.invoke('sandboxUi:close', args),copyDeepLink: (teamId?: string) => ipcRenderer.invoke('sandboxUi:copyDeepLink', { teamId }),listPendingDeepLinks: () => ipcRenderer.invoke('sandboxUi:listPendingDeepLinks'),clearPendingDeepLinks: () => ipcRenderer.invoke('sandboxUi:clearPendingDeepLinks'),@@ -732,12 +729,6 @@ const clerum = Object.freeze({ipcRenderer.on('sandboxUi:deepLink', listener)return () => ipcRenderer.off('sandboxUi:deepLink', listener)},- onClosed: (callback: (args: { appRef: string; launchId: string }) => void) => {- const listener = (_event: unknown, args: { appRef: string; launchId: string }) =>- callback(args)- ipcRenderer.on('sandboxUi:closed', listener)- return () => ipcRenderer.off('sandboxUi:closed', listener)- },onReleased: (callback: (args: SandboxUiReleasedEvent) => void) => {const listener = (_event: unknown, args: SandboxUiReleasedEvent) => callback(args)ipcRenderer.on('sandboxUi:released', listener)diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex de744fdc5..f9c940aa0 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -763,15 +763,12 @@ declare global {defaultPath?: stringroutePath?: stringbounds: { x: number; y: number; width: number; height: number; dpr?: number }- // Echoed by main on `onClosed` / `onRefreshError` / `onTitleChanged`+ // Echoed by main on `onReleased` / `onRefreshError` / `onTitleChanged`// for the view this open mounts.launchId: string}) => Promise<void>- // Without args: closes whatever is live (legacy). With a launch id:- // closes that launch's view only if it is still the live one.- close: (args?: { launchId: string }) => Promise<void>- reload: () => Promise<void>- getLocation: () => Promise<{ appRef: string; routePath?: string } | null>+ // Closes that launch's view only if it is still the live one.+ close: (args: { launchId: string }) => Promise<void>copyDeepLink: (teamId?: string) => Promise<{ url: string }>listPendingDeepLinks: () => Promise<{ links: SandboxUiDeepLinkEnvelope[] }>clearPendingDeepLinks: () => Promise<void>@@ -810,7 +807,6 @@ declare global {}) => void) => () => voidonDeepLink: (callback: (args: SandboxUiDeepLinkEnvelope) => void) => () => void- onClosed: (callback: (args: { appRef: string; launchId: string }) => void) => () => void// Once per view main tears down, whatever the reason, with the route it// represented (`null`: unreadable, keep the last known one).onReleased: (callback: (args: SandboxUiReleasedEvent) => void) => () => voiddiff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.tsindex ddad83e30..c189da30c 100644--- a/desktop-app/src/sandboxUiDriver.ts+++ b/desktop-app/src/sandboxUiDriver.ts@@ -108,6 +108,7 @@ export type MountSandboxUiArgs = {parentWindow: BrowserWindowbounds: SandboxUiBoundsroutePath?: string+ /** Main-side cleanup for a teardown nobody asked for (crash, parent closed). */onClosed?: () => void/*** Fired exactly once when the view this mount created is torn down, for any@@ -566,8 +567,8 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void// `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.+ // a replacing mount) stay silent — the caller already ran its own cleanup.+ // The renderer learns of every teardown from `onReleased` instead.const onParentClosed = (): void => {teardownActive('parent_closed')onClosed?.()@@ -1093,10 +1094,10 @@ export function reloadSandboxUiWebContents(}/**- * Reload the active embed in place (user-initiated "Refresh"). No-op when- * nothing is mounted or the view was already torn down. This is the only- * in-place refresh path — without it, the embed's content stays as of its- * initial `loadURL` until the user navigates away and back (which remounts).+ * Reload the active embed in place once its session refresh has re-minted the+ * cookie after the document came back 401. No-op when nothing is mounted or the+ * view was already torn down. The user-facing Refresh relaunches the view+ * instead, so it never comes through here.*/export function reloadActiveSandboxUiView(): void {reloadSandboxUiWebContents(active?.view.webContents)