Skip to content

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

TypeScript

feat(desktop-app): give each embedded app view a launch id and an exactly-once release event

Diego Zacarias0f827844efde
diff --git a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts b/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts
index d08cc61f3..36ab4c4fd 100644
--- a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts
+++ b/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts
@@ -178,6 +178,7 @@ describe('AppService.listSandboxUiApps', () => {
describe('AppService sandbox UI lifecycle serialization', () => {
const openArgs = (recipeName: string) => ({
+ launchId: crypto.randomUUID(),
recipeNs: 'sandbox-recipes',
recipeName,
bounds: { x: 0, y: 0, width: 400, height: 300 },
@@ -187,8 +188,17 @@ describe('AppService sandbox UI lifecycle serialization', () => {
beforeEach(() => {
vi.clearAllMocks()
mockMountSandboxUiView.mockImplementation(
- async ({ recipeNs, recipeName }: { recipeNs: string; recipeName: string }) => {
+ async ({
+ launchId,
+ recipeNs,
+ recipeName,
+ }: {
+ launchId: string
+ recipeNs: string
+ recipeName: string
+ }) => {
mockGetActiveSandboxUi.mockReturnValue({
+ launchId,
recipeNs,
recipeName,
appRef: `${recipeNs}/${recipeName}`,
diff --git a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts
index 4e801c75a..5f26f0860 100644
--- a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts
+++ b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts
@@ -28,15 +28,76 @@ const electronMocks = vi.hoisted(() => {
class FakeWebContents {
id = nextWebContentsId++
+ // Chromium reports the last committed URL: '' until the first document
+ // commits, whatever `loadURL` was asked for.
currentUrl = ''
+ pendingUrl = ''
destroyed = false
+ // A page whose router has taken over the history API: `replaceState` does
+ // not move the URL.
+ historyLocked = false
private readonly listeners = new Map<string, Set<(...args: unknown[]) => void>>()
- executeJavaScript = vi.fn()
+ // Runs the script the driver sends against a minimal page, so whatever the
+ // embed would observe comes from the driver's real script, not a canned
+ // answer.
+ executeJavaScript = vi.fn(async (code: string): Promise<unknown> => {
+ const vm = await import('node:vm')
+ const webContents = this
+ const history = {
+ state: null as unknown,
+ replaceState(state: unknown, _title: string, url: string) {
+ history.state = state
+ if (webContents.historyLocked) return
+ webContents.currentUrl = new URL(url, webContents.currentUrl).href
+ webContents.emit('did-navigate-in-page', {}, webContents.currentUrl, true)
+ },
+ }
+ class PopStateEvent {
+ constructor(
+ readonly type: string,
+ readonly init?: unknown
+ ) {}
+ }
+ const window = {
+ location: {
+ get href() {
+ return webContents.currentUrl
+ },
+ },
+ history,
+ dispatchEvent: () => true,
+ }
+ return vm.runInNewContext(code, { window, URL, PopStateEvent })
+ })
loadURL = vi.fn(async (url: string) => {
- this.currentUrl = url
+ this.pendingUrl = url
})
+
+ /**
+ * The requested document commits with `status` and finishes loading;
+ * `redirectedTo` is where the server sent it instead.
+ */
+ commitLoad(status = 200, redirectedTo?: string): void {
+ this.currentUrl = redirectedTo ?? this.pendingUrl
+ this.emit('did-navigate', {}, this.currentUrl, status, '')
+ this.emit('did-finish-load')
+ }
+
+ /** The app navigates inside its document (history API / hash). */
+ navigateInPage(url: string): void {
+ this.currentUrl = url
+ this.emit('did-navigate-in-page', {}, url, true)
+ }
+ /** The user follows a link to another document of the app. */
+ navigateTo(url: string, status = 200): void {
+ this.pendingUrl = url
+ this.commitLoad(status)
+ }
setWindowOpenHandler = vi.fn()
- stopFindInPage = vi.fn()
+ // Native methods of a destroyed webContents throw, like Electron's.
+ stopFindInPage = vi.fn(() => {
+ this.assertAlive()
+ })
findInPage = vi.fn(() => 41)
focus = vi.fn()
send = vi.fn()
@@ -58,6 +119,7 @@ const electronMocks = vi.hoisted(() => {
}
getURL(): string {
+ this.assertAlive()
return this.currentUrl
}
@@ -68,6 +130,10 @@ const electronMocks = vi.hoisted(() => {
close(): void {
this.destroyed = true
}
+
+ private assertAlive(): void {
+ if (this.destroyed) throw new Error('Object has been destroyed')
+ }
}
class FakeWebContentsView {
@@ -98,12 +164,26 @@ const electronMocks = vi.hoisted(() => {
touchSandboxUiPartition: vi.fn(async () => undefined),
sessionObject,
views,
+ ipcHandlers: new Map<string, (event: unknown, payload?: unknown) => Promise<unknown>>(),
+ windowsBySender: new Map<unknown, unknown>(),
}
})
vi.mock('electron', () => ({
WebContentsView: electronMocks.FakeWebContentsView,
- BrowserWindow: { getAllWindows: () => [] },
+ BrowserWindow: {
+ getAllWindows: () => [],
+ fromWebContents: (sender: unknown) => electronMocks.windowsBySender.get(sender) ?? null,
+ },
+ ipcMain: {
+ handle: (channel: string, handler: (event: unknown, payload?: unknown) => Promise<unknown>) => {
+ electronMocks.ipcHandlers.set(channel, handler)
+ },
+ on: vi.fn(),
+ removeHandler: vi.fn(),
+ },
+ clipboard: { writeText: vi.fn() },
+ dialog: { showSaveDialog: vi.fn(), showMessageBox: vi.fn() },
Notification: class {
static isSupported(): boolean {
return false
@@ -166,14 +246,48 @@ vi.mock('../tokenStore.js', () => ({
type Listener = (...args: unknown[]) => void
+// Electron throws from the native methods of a destroyed window instead of
+// ignoring the call; the contentView keeps its real child list.
class FakeParentWindow {
destroyed = false
- contentView = {
- addChildView: vi.fn(),
- removeChildView: vi.fn(),
+ readonly children: unknown[] = []
+ readonly webContents = { send: vi.fn(), isDestroyed: () => this.destroyed }
+ readonly contentView: {
+ addChildView: ReturnType<typeof vi.fn>
+ removeChildView: ReturnType<typeof vi.fn>
+ readonly children: unknown[]
}
private readonly listeners = new Map<string, Set<Listener>>()
+ constructor() {
+ const win = this
+ this.contentView = {
+ addChildView: vi.fn((view: unknown) => {
+ win.assertAlive()
+ win.children.push(view)
+ }),
+ removeChildView: vi.fn((view: unknown) => {
+ win.assertAlive()
+ const index = win.children.indexOf(view)
+ if (index !== -1) win.children.splice(index, 1)
+ }),
+ get children(): unknown[] {
+ win.assertAlive()
+ return [...win.children]
+ },
+ }
+ }
+
+ /** The window closes: Electron destroys it and the views it held. */
+ destroy(): void {
+ this.destroyed = true
+ this.children.length = 0
+ }
+
+ private assertAlive(): void {
+ if (this.destroyed) throw new Error('Object has been destroyed')
+ }
+
isDestroyed(): boolean {
return this.destroyed
}
@@ -200,6 +314,7 @@ class FakeParentWindow {
return this.on(event, handler)
}
+ // EventEmitter, not native: works on a destroyed window too.
removeListener(event: string, handler: Listener): this {
this.listeners.get(event)?.delete(handler)
return this
@@ -279,21 +394,24 @@ function makeService(): AppService {
return svc
}
+type OpenArgs = Parameters<AppService['openSandboxUi']>[0]
+
function openArgs(
recipeName: string,
parentWindow: FakeParentWindow,
- onClosed: () => void = vi.fn()
-): Parameters<AppService['openSandboxUi']>[0] {
+ onClosed: () => void = vi.fn(),
+ overrides: Partial<Omit<OpenArgs, 'parentWindow'>> = {}
+): OpenArgs {
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'],
+ parentWindow: parentWindow as unknown as OpenArgs['parentWindow'],
+ launchId: crypto.randomUUID(),
onClosed,
+ ...overrides,
}
}
@@ -595,7 +713,7 @@ function wireMainWindow(service: AppService): FakeMainWebContents {
webContents: mainWebContents as never,
isCurrentWindow: () => true,
markNotReady: vi.fn(),
- closeSandboxUi: () => service.closeSandboxUi(),
+ sandboxUi: service,
})
return mainWebContents
}
@@ -980,3 +1098,755 @@ describe('AppService sandbox-ui embed across a login that replaces a live sessio
expect(electronMocks.views).toHaveLength(2)
})
})
+
+// ─── View release contract ───────────────────────────────────────────────
+// Every view main assigns ends with exactly one `released` that names the open
+// that mounted it, why it died and the route it was showing, and no view is
+// left attached without an owner.
+
+type ReleasedEvent = {
+ launchId: string
+ reason: string
+ location: { routePath?: string } | null
+}
+
+const APP_VIEW_URL = 'https://rpc.example/api/v1/sandbox-ui/sandbox-recipes/first-app/view'
+
+async function drainLifecycleQueue(service: AppService): Promise<void> {
+ await (
+ service as unknown as { enqueueSandboxUiLifecycle(op: () => Promise<void>): Promise<void> }
+ ).enqueueSandboxUiLifecycle(async () => undefined)
+}
+
+// I-orphan: without an active view, the window holds no sandbox-ui view; with
+// one, it holds exactly that one.
+function expectNoOrphanView(parentWindow: FakeParentWindow): void {
+ if (parentWindow.destroyed) return
+ const active = getActiveSandboxUi()
+ const attached = parentWindow.contentView.children
+ if (!active) {
+ expect(attached).toEqual([])
+ return
+ }
+ expect(attached).toHaveLength(1)
+ expect(
+ (attached[0] as InstanceType<typeof electronMocks.FakeWebContentsView>).webContents.id
+ ).toBe(active.webContentsId)
+}
+
+async function setupReleaseRecorder(routePath?: string) {
+ const service = makeService()
+ const runtime = initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })
+ const parentWindow = new FakeParentWindow()
+ const released: ReleasedEvent[] = []
+ const onReleased = (event: ReleasedEvent) => {
+ released.push(event)
+ }
+ const launch = (
+ recipeName: string,
+ overrides: Partial<Omit<OpenArgs, 'parentWindow'>> = {}
+ ): OpenArgs =>
+ openArgs(recipeName, parentWindow, vi.fn(), {
+ onReleased,
+ ...(routePath ? { routePath } : {}),
+ ...overrides,
+ })
+ return { service, runtime, parentWindow, released, launch }
+}
+
+describe('AppService sandbox-ui teardown whose cleanup throws', () => {
+ it('still detaches the view, closes its webContents and releases it once', async () => {
+ const { service, parentWindow, released, launch } = await setupReleaseRecorder()
+ const args = launch('first-app')
+ await service.openSandboxUi(args)
+ const view = electronMocks.views[0]!
+ // A native call made while tearing down fails (the renderer went away
+ // between the liveness check and the call).
+ view.webContents.stopFindInPage.mockImplementationOnce(() => {
+ throw new Error('Object has been destroyed')
+ })
+
+ await service.closeSandboxUi({ launchId: args.launchId })
+
+ expect(parentWindow.contentView.children).toEqual([])
+ expect(view.webContents.isDestroyed()).toBe(true)
+ expect(getActiveSandboxUi()).toBeNull()
+ expect(released).toEqual([{ launchId: args.launchId, reason: 'closed', location: {} }])
+ expectNoOrphanView(parentWindow)
+ })
+
+ it('still releases the view when unhooking the session refresh from the parent throws', async () => {
+ // Electron's removeListener does not throw; the failure is injected to
+ // prove that nothing run ahead of the unmount (the refresh loop unhooks
+ // its own parent listeners first) can keep the view attached.
+ const { service, parentWindow, released, launch } = await setupReleaseRecorder()
+ const args = launch('first-app')
+ await service.openSandboxUi(args)
+ const view = electronMocks.views[0]!
+ vi.spyOn(parentWindow, 'removeListener').mockImplementation(() => {
+ throw new Error('Object has been destroyed')
+ })
+
+ await service.closeSandboxUi({ launchId: args.launchId })
+
+ expect(parentWindow.contentView.children).toEqual([])
+ expect(view.webContents.isDestroyed()).toBe(true)
+ expect(getActiveSandboxUi()).toBeNull()
+ expect(released).toEqual([{ launchId: args.launchId, reason: 'closed', location: {} }])
+ expect(resolvePluginSurface(view.webContents.id)).toBeNull()
+ })
+})
+
+describe('AppService sandbox-ui view release', () => {
+ it('releases each assigned view exactly once and never a launch that got no view', async () => {
+ const { service, parentWindow, released, launch } = await setupReleaseRecorder()
+ const first = launch('first-app')
+ await service.openSandboxUi(first)
+ expectNoOrphanView(parentWindow)
+
+ mintResponders.set('second-app', () => mintFails(409, 'app is starting'))
+ const failed = launch('second-app')
+ await expect(service.openSandboxUi(failed)).rejects.toThrow(/\(409\)/)
+ expectNoOrphanView(parentWindow)
+
+ const third = launch('first-app')
+ await service.openSandboxUi(third)
+ await service.closeSandboxUi({ launchId: third.launchId })
+ await service.logout()
+ await drainLifecycleQueue(service)
+
+ expect(released).toEqual([
+ { launchId: first.launchId, reason: 'replaced', location: {} },
+ { launchId: third.launchId, reason: 'closed', location: {} },
+ ])
+ expectNoOrphanView(parentWindow)
+ })
+
+ it('releases a view mounted under a session that ended before rejecting its open', async () => {
+ const { service, parentWindow, launch } = await setupReleaseRecorder()
+ const order: Array<[string, unknown]> = []
+ const args = launch('first-app', {
+ onReleased: event => {
+ order.push(['released', event])
+ },
+ })
+ // The session ends right as the view is attached: what logout does
+ // synchronously once its upload fence settles.
+ parentWindow.contentView.addChildView.mockImplementationOnce((view: unknown) => {
+ parentWindow.children.push(view)
+ ;(
+ service as unknown as { clearAuthenticatedSessionState(): void }
+ ).clearAuthenticatedSessionState()
+ })
+
+ await service.openSandboxUi(args).catch((error: Error) => {
+ order.push(['rejected', error.message])
+ })
+ await drainLifecycleQueue(service)
+
+ expect(order).toEqual([
+ ['released', { launchId: args.launchId, reason: 'session', location: {} }],
+ ['rejected', expect.stringMatching(/session changed/)],
+ ])
+ expect(getActiveSandboxUi()).toBeNull()
+ expectNoOrphanView(parentWindow)
+ })
+
+ it('a close naming another launch leaves the live view alone', async () => {
+ const { service, parentWindow, released, launch } = await setupReleaseRecorder()
+ const args = launch('first-app')
+ await service.openSandboxUi(args)
+ const live = getActiveSandboxUi()
+
+ await service.closeSandboxUi({ launchId: crypto.randomUUID() })
+
+ expect(getActiveSandboxUi()?.webContentsId).toBe(live!.webContentsId)
+ expect(released).toEqual([])
+ expectNoOrphanView(parentWindow)
+
+ // The legacy close names no launch and still closes whatever is live.
+ await service.closeSandboxUi()
+ expect(getActiveSandboxUi()).toBeNull()
+ expect(released).toEqual([{ launchId: args.launchId, reason: 'closed', location: {} }])
+ expectNoOrphanView(parentWindow)
+ })
+})
+
+describe('AppService sandbox-ui release reason per caller', () => {
+ it('crashed during the open: the release comes first, then the open rejects', async () => {
+ const { service, parentWindow, launch } = await setupReleaseRecorder()
+ const order: Array<[string, unknown]> = []
+ const args = launch('first-app', {
+ onReleased: event => {
+ order.push(['released', event])
+ },
+ })
+ // The embed renderer dies as soon as the view is attached.
+ parentWindow.contentView.addChildView.mockImplementationOnce((view: unknown) => {
+ parentWindow.children.push(view)
+ ;(view as InstanceType<typeof electronMocks.FakeWebContentsView>).webContents.emit(
+ 'render-process-gone',
+ {},
+ { reason: 'crashed' }
+ )
+ })
+
+ await service.openSandboxUi(args).catch((error: Error) => {
+ order.push(['rejected', error.message])
+ })
+
+ expect(order).toEqual([
+ ['released', { launchId: args.launchId, reason: 'crashed', location: null }],
+ ['rejected', expect.stringMatching(/closed before it finished opening/)],
+ ])
+ expect(getActiveSandboxUi()).toBeNull()
+ expectNoOrphanView(parentWindow)
+ })
+
+ it('replaced: an open over a live view', async () => {
+ const { service, released, launch } = await setupReleaseRecorder()
+ const first = launch('first-app')
+ await service.openSandboxUi(first)
+ await service.openSandboxUi(launch('second-app'))
+ expect(released).toEqual([{ launchId: first.launchId, reason: 'replaced', location: {} }])
+ })
+
+ it('crashed: the embed renderer dies, and the route is not reported', async () => {
+ // The route the view was asked for would otherwise be reported: a crash
+ // must not hand it back for a relaunch that would crash again.
+ const { service, parentWindow, released, launch } = await setupReleaseRecorder('/r/crash')
+ const args = launch('first-app')
+ await service.openSandboxUi(args)
+
+ electronMocks.views[0]!.webContents.emit('render-process-gone', {}, { reason: 'crashed' })
+
+ expect(released).toEqual([{ launchId: args.launchId, reason: 'crashed', location: null }])
+ expectNoOrphanView(parentWindow)
+ })
+
+ it('parent_closed: the window holding the view closes', async () => {
+ const { service, parentWindow, released, launch } = await setupReleaseRecorder()
+ const args = launch('first-app')
+ await service.openSandboxUi(args)
+ const view = electronMocks.views[0]!
+
+ parentWindow.destroy()
+ parentWindow.emit('closed')
+
+ expect(view.webContents.isDestroyed()).toBe(true)
+ expect(getActiveSandboxUi()).toBeNull()
+ expect(released).toEqual([{ launchId: args.launchId, reason: 'parent_closed', location: {} }])
+ })
+
+ it('session: logout', async () => {
+ const { service, parentWindow, released, launch } = await setupReleaseRecorder()
+ const args = launch('first-app')
+ await service.openSandboxUi(args)
+
+ await service.logout()
+ await drainLifecycleQueue(service)
+
+ expect(released).toEqual([{ launchId: args.launchId, reason: 'session', location: {} }])
+ expectNoOrphanView(parentWindow)
+ })
+
+ it('renderer_replaced: the trusted renderer commits a new document', async () => {
+ const { service, parentWindow, released, launch } = await setupReleaseRecorder()
+ const args = launch('first-app')
+ await service.openSandboxUi(args)
+ const mainWebContents = wireMainWindow(service)
+
+ mainWebContents.emit('did-navigate', {}, 'file:///ui-dist/index.html', 200, 'OK')
+ await drainLifecycleQueue(service)
+
+ expect(released).toEqual([
+ { launchId: args.launchId, reason: 'renderer_replaced', location: {} },
+ ])
+ expectNoOrphanView(parentWindow)
+ })
+})
+
+describe('AppService sandbox-ui represented location', () => {
+ it('is the requested route until the view applies it, then the live route', async () => {
+ const { service, released, launch } = await setupReleaseRecorder('/r/first')
+ const first = launch('first-app')
+ await service.openSandboxUi(first)
+ const webContents = electronMocks.views[0]!.webContents
+
+ await expect(service.getSandboxUiLocation()).resolves.toEqual({
+ appRef: 'sandbox-recipes/first-app',
+ routePath: '/r/first',
+ })
+
+ // The document commits and the driver hands the route to the app.
+ webContents.commitLoad()
+ await vi.waitFor(() => expect(webContents.getURL()).toBe(`${APP_VIEW_URL}/r/first`), {
+ timeout: 1_000,
+ })
+ webContents.navigateInPage(`${APP_VIEW_URL}/inbox`)
+ await expect(service.getSandboxUiLocation()).resolves.toEqual({
+ appRef: 'sandbox-recipes/first-app',
+ routePath: '/inbox',
+ })
+
+ await service.closeSandboxUi({ launchId: first.launchId })
+ expect(released).toEqual([
+ { launchId: first.launchId, reason: 'closed', location: { routePath: '/inbox' } },
+ ])
+ })
+
+ it('a view replaced while still loading reports the route it was asked for', async () => {
+ const { service, released, launch } = await setupReleaseRecorder('/r/first')
+ const first = launch('first-app')
+ await service.openSandboxUi(first)
+
+ await service.openSandboxUi(launch('second-app', { routePath: '/r/second' }))
+
+ expect(released).toEqual([
+ { launchId: first.launchId, reason: 'replaced', location: { routePath: '/r/first' } },
+ ])
+ })
+
+ it('keeps the requested route while the app is not ready for it, until the user navigates', async () => {
+ const { service, released, launch } = await setupReleaseRecorder('/r/first')
+ const first = launch('first-app')
+ await service.openSandboxUi(first)
+ const webContents = electronMocks.views[0]!.webContents
+
+ // 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',
+ })
+
+ webContents.navigateInPage(`${APP_VIEW_URL}/elsewhere`)
+ await service.closeSandboxUi({ launchId: first.launchId })
+ expect(released).toEqual([
+ { launchId: first.launchId, reason: 'closed', location: { routePath: '/elsewhere' } },
+ ])
+ })
+
+ it('a view without a requested route reports the default route until it navigates', async () => {
+ const { service, released, launch } = await setupReleaseRecorder()
+ const first = launch('first-app')
+ await service.openSandboxUi(first)
+ const webContents = electronMocks.views[0]!.webContents
+
+ await expect(service.getSandboxUiLocation()).resolves.toEqual({
+ appRef: 'sandbox-recipes/first-app',
+ })
+ webContents.commitLoad()
+ webContents.navigateInPage(`${APP_VIEW_URL}/settings`)
+
+ await service.closeSandboxUi({ launchId: first.launchId })
+ expect(released).toEqual([
+ { launchId: first.launchId, reason: 'closed', location: { routePath: '/settings' } },
+ ])
+ })
+
+ it('a deep link copied while the view loads points at the requested route', async () => {
+ const { buildSandboxUiWebLink } = await import('../sandboxUiDeepLinks.js')
+ const { config } = await import('../config.js')
+ vi.spyOn(config, 'desktopProfileUiBaseUrlExplicit', 'get').mockReturnValue(true)
+ const { service, launch } = await setupReleaseRecorder('/r/first')
+ await service.openSandboxUi(launch('first-app'))
+
+ await expect(service.createSandboxUiDeepLink()).resolves.toEqual({
+ url: buildSandboxUiWebLink('https://profile.example.com', {
+ recipeNs: 'sandbox-recipes',
+ recipeName: 'first-app',
+ path: '/r/first',
+ }),
+ })
+ })
+})
+
+describe('sandbox-ui IPC lifecycle handlers over the real AppService', () => {
+ type Sender = { id: number }
+
+ function registerHandlers(service: AppService) {
+ electronMocks.ipcHandlers.clear()
+ electronMocks.windowsBySender.clear()
+ return import('../ipc.js').then(({ registerIpcHandlers }) => registerIpcHandlers(service))
+ }
+
+ function invoke(channel: string, sender: Sender, payload?: unknown): Promise<unknown> {
+ const handler = electronMocks.ipcHandlers.get(channel)
+ if (!handler) throw new Error(`no IPC handler registered for ${channel}`)
+ return handler({ sender, senderFrame: { url: 'file:///app/index.html' } }, payload)
+ }
+
+ function windowFor(sender: Sender): FakeParentWindow {
+ const parentWindow = new FakeParentWindow()
+ electronMocks.windowsBySender.set(sender, parentWindow)
+ return parentWindow
+ }
+
+ const openPayload = (launchId: string) => ({
+ recipeNs: 'sandbox-recipes',
+ recipeName: 'first-app',
+ defaultPath: '/',
+ bounds: { x: 0, y: 0, width: 400, height: 300 },
+ launchId,
+ })
+
+ it('a close sent right after its open never reaches the queue first', async () => {
+ const service = makeService()
+ initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })
+ await registerHandlers(service)
+ const mainSender = { id: 1 }
+ const otherSender = { id: 2 }
+ const parentWindow = windowFor(mainSender)
+ const otherWindow = windowFor(otherSender)
+ const launchId = crypto.randomUUID()
+
+ // Both invokes are dispatched in the same tick, in send order.
+ const opened = invoke('sandboxUi:open', mainSender, openPayload(launchId))
+ const closed = invoke('sandboxUi:close', otherSender, { launchId })
+ await Promise.all([opened, closed])
+
+ expect(getActiveSandboxUi()).toBeNull()
+ expectNoOrphanView(parentWindow)
+ const releasedSends = parentWindow.webContents.send.mock.calls.filter(
+ ([channel]) => channel === 'sandboxUi:released'
+ )
+ expect(releasedSends).toEqual([
+ ['sandboxUi:released', { launchId, reason: 'closed', location: {} }],
+ ])
+ // Only the window that mounted the view hears about it.
+ expect(otherWindow.webContents.send).not.toHaveBeenCalled()
+ })
+
+ it('rejects a close with a malformed launch id without closing anything', async () => {
+ const service = makeService()
+ initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })
+ await registerHandlers(service)
+ const sender = { id: 1 }
+ const parentWindow = windowFor(sender)
+ await invoke('sandboxUi:open', sender, openPayload(crypto.randomUUID()))
+
+ await expect(invoke('sandboxUi:close', sender, { launchId: '../x' })).rejects.toThrow(
+ /launchId/
+ )
+ await drainLifecycleQueue(service)
+
+ expect(getActiveSandboxUi()).not.toBeNull()
+ expectNoOrphanView(parentWindow)
+ })
+})
+
+describe('AppService sandbox-ui teardown isolates every step', () => {
+ async function openLive(routePath?: string) {
+ const recorder = await setupReleaseRecorder(routePath)
+ const args = recorder.launch('first-app')
+ await recorder.service.openSandboxUi(args)
+ const view = electronMocks.views[0]!
+ return { ...recorder, args, view }
+ }
+
+ function expectReleasedAndGone(
+ view: InstanceType<typeof electronMocks.FakeWebContentsView>,
+ released: ReleasedEvent[],
+ expected: ReleasedEvent
+ ): void {
+ expect(view.webContents.isDestroyed()).toBe(true)
+ expect(getActiveSandboxUi()).toBeNull()
+ expect(released).toEqual([expected])
+ }
+
+ it('a view whose listener unhooks and find stop all throw is still released and gone', async () => {
+ // Every per-view cleanup is live: a route handoff still waiting (the app
+ // answered 503), a find session, shortcut routing, document listeners.
+ const { service, parentWindow, released, args, view } = await openLive('/r/first')
+ view.webContents.commitLoad(503)
+ await expect(service.findInActiveSandboxUi('invoice', 'start', 1, vi.fn())).resolves.toEqual({
+ status: 'started',
+ requestId: 41,
+ })
+ // Injected failures, one per cleanup step.
+ vi.spyOn(view.webContents, 'removeListener').mockImplementation(() => {
+ throw new Error('injected unhook failure')
+ })
+ view.webContents.stopFindInPage.mockImplementation(() => {
+ throw new Error('injected stop failure')
+ })
+
+ await expect(service.closeSandboxUi({ launchId: args.launchId })).resolves.toBeUndefined()
+
+ expect(parentWindow.contentView.children).toEqual([])
+ expectReleasedAndGone(view, released, {
+ launchId: args.launchId,
+ reason: 'closed',
+ location: { routePath: '/r/first' },
+ })
+ })
+
+ it('a failing detach still closes and releases the view', async () => {
+ const { service, parentWindow, released, args, view } = await openLive()
+ parentWindow.contentView.removeChildView.mockImplementationOnce(() => {
+ throw new Error('detach failed')
+ })
+
+ await expect(service.closeSandboxUi({ launchId: args.launchId })).resolves.toBeUndefined()
+
+ expectReleasedAndGone(view, released, {
+ launchId: args.launchId,
+ reason: 'closed',
+ location: {},
+ })
+ })
+
+ it('a failing webContents close still detaches and releases the view', async () => {
+ const { service, parentWindow, released, args, view } = await openLive()
+ vi.spyOn(view.webContents, 'close').mockImplementationOnce(() => {
+ throw new Error('close failed')
+ })
+
+ await expect(service.closeSandboxUi({ launchId: args.launchId })).resolves.toBeUndefined()
+
+ expect(parentWindow.contentView.children).toEqual([])
+ expect(getActiveSandboxUi()).toBeNull()
+ expect(released).toEqual([{ launchId: args.launchId, reason: 'closed', location: {} }])
+ })
+
+ it('a release listener that throws does not fail the close', async () => {
+ const recorder = await setupReleaseRecorder()
+ const args = recorder.launch('first-app', {
+ onReleased: () => {
+ throw new Error('listener failed')
+ },
+ })
+ await recorder.service.openSandboxUi(args)
+
+ await expect(
+ recorder.service.closeSandboxUi({ launchId: args.launchId })
+ ).resolves.toBeUndefined()
+
+ expect(getActiveSandboxUi()).toBeNull()
+ expectNoOrphanView(recorder.parentWindow)
+ })
+
+ it('a failing surface unpin still unmounts and releases the view', async () => {
+ const { service, runtime, parentWindow, released, args, view } = await openLive()
+ vi.spyOn(runtime, 'unpinAllSandboxUiSurfaces').mockImplementation(() => {
+ throw new Error('unpin failed')
+ })
+
+ await expect(service.closeSandboxUi({ launchId: args.launchId })).resolves.toBeUndefined()
+
+ expect(parentWindow.contentView.children).toEqual([])
+ expectReleasedAndGone(view, released, {
+ launchId: args.launchId,
+ reason: 'closed',
+ location: {},
+ })
+ })
+
+ it('a view whose URL cannot be read is released with no location', async () => {
+ const { service, parentWindow, released, args, view } = await openLive()
+ view.webContents.commitLoad()
+ vi.spyOn(view.webContents, 'getURL').mockImplementation(() => {
+ throw new Error('Object has been destroyed')
+ })
+
+ await expect(service.closeSandboxUi({ launchId: args.launchId })).resolves.toBeUndefined()
+
+ expect(parentWindow.contentView.children).toEqual([])
+ expectReleasedAndGone(view, released, {
+ launchId: args.launchId,
+ reason: 'closed',
+ location: null,
+ })
+ })
+
+ it('a view showing a URL outside the app is released with no location', async () => {
+ 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'
+ )
+
+ await expect(service.closeSandboxUi({ launchId: args.launchId })).resolves.toBeUndefined()
+
+ expect(parentWindow.contentView.children).toEqual([])
+ expectReleasedAndGone(view, released, {
+ launchId: args.launchId,
+ reason: 'closed',
+ location: null,
+ })
+ })
+})
+
+describe('AppService sandbox-ui route settling', () => {
+ async function openLoading(routePath?: string) {
+ const recorder = await setupReleaseRecorder(routePath)
+ await recorder.service.openSandboxUi(recorder.launch('first-app'))
+ return { ...recorder, webContents: electronMocks.views[0]!.webContents }
+ }
+
+ const location = (routePath?: string) => ({
+ appRef: 'sandbox-recipes/first-app',
+ ...(routePath ? { 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'))
+ })
+
+ 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'))
+ })
+
+ 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'))
+ })
+
+ it('a handoff that finds the app already on the route settles it', async () => {
+ const { service, webContents } = await openLoading('/r/first')
+ webContents.commitLoad(200, `${APP_VIEW_URL}/r/first`)
+ await vi.waitFor(() => expect(webContents.executeJavaScript).toHaveBeenCalledOnce(), {
+ timeout: 1_000,
+ })
+ await expect(webContents.executeJavaScript.mock.results[0]!.value).resolves.toBe(true)
+ await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))
+ })
+
+ it('a handoff the app does not take keeps the requested route', async () => {
+ const { service, webContents } = await openLoading('/r/first')
+ webContents.historyLocked = true
+ webContents.commitLoad()
+ await vi.waitFor(() => expect(webContents.executeJavaScript).toHaveBeenCalledOnce(), {
+ timeout: 1_000,
+ })
+ await expect(webContents.executeJavaScript.mock.results[0]!.value).resolves.toBe(false)
+ await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))
+ })
+
+ it('a new document the user opens after the handoff gave up is the live route', async () => {
+ const { service, released, webContents } = await openLoading('/r/first')
+ webContents.commitLoad(503)
+ await vi.advanceTimersByTimeAsync(30_000)
+
+ // A reload commits the same document: still the requested route.
+ webContents.commitLoad()
+ await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))
+
+ webContents.navigateTo(`${APP_VIEW_URL}/reports`)
+ await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/reports'))
+ await service.closeSandboxUi()
+ expect(released.map(event => event.location)).toEqual([{ routePath: '/reports' }])
+ })
+
+ it('a handoff that gives up before the first load does not settle on that first load', async () => {
+ // The app takes longer than the handoff waits to answer at all.
+ const { service, webContents } = await openLoading('/r/first')
+ await vi.advanceTimersByTimeAsync(30_000)
+ webContents.commitLoad()
+ await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))
+ })
+
+ it('a document committed outside the app does not replace the requested route', async () => {
+ const { service, webContents } = await openLoading('/r/first')
+ webContents.commitLoad(503)
+ await vi.advanceTimersByTimeAsync(30_000)
+ webContents.navigateTo('https://elsewhere.example/landing')
+ await expect(service.getSandboxUiLocation()).resolves.toEqual(location('/r/first'))
+ })
+
+ it('a reload after the router moved the URL during boot keeps the requested route', async () => {
+ const { service, webContents } = await openLoading('/r/first')
+ // The app's router rewrites the URL before the document finishes loading.
+ webContents.emit('did-navigate', {}, `${APP_VIEW_URL}/`, 200, '')
+ 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'))
+
+ // 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'))
+ })
+
+ 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'))
+ })
+})
+
+describe('sandbox-ui IPC close ordering and legacy payloads', () => {
+ type Sender = { id: number }
+
+ async function setupIpc() {
+ const service = makeService()
+ initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })
+ electronMocks.ipcHandlers.clear()
+ electronMocks.windowsBySender.clear()
+ const { registerIpcHandlers } = await import('../ipc.js')
+ registerIpcHandlers(service)
+ const sender: Sender = { id: 1 }
+ const parentWindow = new FakeParentWindow()
+ electronMocks.windowsBySender.set(sender, parentWindow)
+ const invoke = (channel: string, payload?: unknown): Promise<unknown> => {
+ const handler = electronMocks.ipcHandlers.get(channel)
+ if (!handler) throw new Error(`no IPC handler registered for ${channel}`)
+ return handler({ sender, senderFrame: { url: 'file:///app/index.html' } }, payload)
+ }
+ const open = (launchId: string) =>
+ invoke('sandboxUi:open', {
+ recipeNs: 'sandbox-recipes',
+ recipeName: 'first-app',
+ defaultPath: '/',
+ bounds: { x: 0, y: 0, width: 400, height: 300 },
+ launchId,
+ })
+ const releasedSends = () =>
+ parentWindow.webContents.send.mock.calls.filter(
+ ([channel]) => channel === 'sandboxUi:released'
+ )
+ 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()
+ const launchId = crypto.randomUUID()
+ await open(launchId)
+
+ await invoke('sandboxUi:close', null)
+
+ expect(getActiveSandboxUi()).toBeNull()
+ expectNoOrphanView(parentWindow)
+ expect(releasedSends()).toEqual([
+ ['sandboxUi:released', { launchId, reason: 'closed', location: {} }],
+ ])
+ })
+
+ it('a close sent right before the next open closes its own view first', async () => {
+ const { invoke, open, releasedSends } = await setupIpc()
+ const first = crypto.randomUUID()
+ const second = crypto.randomUUID()
+ await open(first)
+
+ const closed = invoke('sandboxUi:close', { launchId: first })
+ const opened = open(second)
+ await Promise.all([closed, opened])
+
+ expect(getActiveSandboxUi()?.launchId).toBe(second)
+ expect(releasedSends()).toEqual([
+ ['sandboxUi:released', { launchId: first, reason: 'closed', location: {} }],
+ ])
+ })
+})
diff --git a/desktop-app/src/__tests__/ipc.sandboxUiLaunchId.test.ts b/desktop-app/src/__tests__/ipc.sandboxUiLaunchId.test.ts
index 208372648..857f10cc3 100644
--- a/desktop-app/src/__tests__/ipc.sandboxUiLaunchId.test.ts
+++ b/desktop-app/src/__tests__/ipc.sandboxUiLaunchId.test.ts
@@ -66,8 +66,10 @@ afterEach(() => {
describe('sandboxUi:open launch id', () => {
it("tags each view's events with the launch id of the open that mounted it", async () => {
- await open({ launchId: 'launch-1' })
- await open({ launchId: 'launch-2' })
+ const launch1 = crypto.randomUUID()
+ const launch2 = crypto.randomUUID()
+ await open({ launchId: launch1 })
+ await open({ launchId: launch2 })
const [first, second] = opens
// The replaced view reports after the relaunch of the same app.
@@ -77,29 +79,38 @@ describe('sandboxUi:open launch id', () => {
second!.onTitleChanged?.('New title')
expect(electron.send.mock.calls).toEqual([
- ['sandboxUi:closed', { appRef: 'sandbox-recipes/alpha', launchId: 'launch-1' }],
+ ['sandboxUi:closed', { appRef: 'sandbox-recipes/alpha', launchId: launch1 }],
[
'sandboxUi:refreshError',
- { appRef: 'sandbox-recipes/alpha', launchId: 'launch-1', message: 'refresh failed' },
+ { appRef: 'sandbox-recipes/alpha', launchId: launch1, message: 'refresh failed' },
],
[
'sandboxUi:titleChanged',
- { appRef: 'sandbox-recipes/alpha', launchId: 'launch-1', title: 'Old title' },
+ { appRef: 'sandbox-recipes/alpha', launchId: launch1, title: 'Old title' },
],
[
'sandboxUi:titleChanged',
- { appRef: 'sandbox-recipes/alpha', launchId: 'launch-2', title: 'New title' },
+ { appRef: 'sandbox-recipes/alpha', launchId: launch2, title: 'New title' },
],
])
})
- it.each([undefined, '', 42, 'a'.repeat(65), 'has space', '../x', { id: 'x' }])(
- 'rejects launch id %j before opening anything',
- async launchId => {
- await expect(open({ launchId })).rejects.toThrow(/launchId/)
- expect(service.openSandboxUi).not.toHaveBeenCalled()
- }
- )
+ // A counter or any non-UUID id could repeat across renderer reloads, which
+ // main outlives.
+ it.each([
+ undefined,
+ '',
+ 42,
+ 'launch-1',
+ 'a'.repeat(65),
+ 'has space',
+ '../x',
+ { id: 'x' },
+ `${crypto.randomUUID()}-extra`,
+ ])('rejects launch id %j before opening anything', async launchId => {
+ await expect(open({ launchId })).rejects.toThrow(/launchId/)
+ expect(service.openSandboxUi).not.toHaveBeenCalled()
+ })
it('accepts a renderer-minted UUID', async () => {
const launchId = crypto.randomUUID()
diff --git a/desktop-app/src/__tests__/mainWindowReadiness.test.ts b/desktop-app/src/__tests__/mainWindowReadiness.test.ts
index 0326997cf..dfc801c3a 100644
--- a/desktop-app/src/__tests__/mainWindowReadiness.test.ts
+++ b/desktop-app/src/__tests__/mainWindowReadiness.test.ts
@@ -25,7 +25,7 @@ describe('main window renderer readiness', () => {
webContents: webContents as never,
isCurrentWindow: () => true,
markNotReady,
- closeSandboxUi: vi.fn(async () => undefined),
+ sandboxUi: { closeSandboxUi: vi.fn(async () => undefined) },
})
expect(listeners.has('did-start-navigation')).toBe(false)
@@ -43,7 +43,7 @@ describe('main window renderer readiness', () => {
webContents: webContents as never,
isCurrentWindow: () => true,
markNotReady,
- closeSandboxUi: vi.fn(async () => undefined),
+ sandboxUi: { closeSandboxUi: vi.fn(async () => undefined) },
})
listeners.get('render-process-gone')?.({}, { reason: 'crashed' })
@@ -58,7 +58,7 @@ describe('main window renderer readiness', () => {
webContents: clean.webContents as never,
isCurrentWindow: () => true,
markNotReady: vi.fn(),
- closeSandboxUi: vi.fn(async () => undefined),
+ sandboxUi: { closeSandboxUi: vi.fn(async () => undefined) },
})
clean.listeners.get('render-process-gone')?.({}, { reason: 'clean-exit' })
expect(clean.webContents.reload).not.toHaveBeenCalled()
@@ -69,7 +69,7 @@ describe('main window renderer readiness', () => {
webContents: obsolete.webContents as never,
isCurrentWindow: () => false,
markNotReady,
- closeSandboxUi: vi.fn(async () => undefined),
+ sandboxUi: { closeSandboxUi: vi.fn(async () => undefined) },
})
obsolete.listeners.get('render-process-gone')?.({}, { reason: 'crashed' })
expect(markNotReady).not.toHaveBeenCalled()
@@ -83,10 +83,11 @@ describe('main window renderer readiness', () => {
webContents: navigated.webContents as never,
isCurrentWindow: () => true,
markNotReady: vi.fn(),
- closeSandboxUi: closeOnNavigate,
+ sandboxUi: { closeSandboxUi: closeOnNavigate },
})
navigated.listeners.get('did-navigate')?.()
expect(closeOnNavigate).toHaveBeenCalledOnce()
+ expect(closeOnNavigate).toHaveBeenCalledWith({ reason: 'renderer_replaced' })
// A clean exit is not reloaded, but the renderer that owned the embed is gone.
const exited = makeWebContents()
@@ -95,10 +96,11 @@ describe('main window renderer readiness', () => {
webContents: exited.webContents as never,
isCurrentWindow: () => true,
markNotReady: vi.fn(),
- closeSandboxUi: closeOnExit,
+ sandboxUi: { closeSandboxUi: closeOnExit },
})
exited.listeners.get('render-process-gone')?.({}, { reason: 'clean-exit' })
expect(closeOnExit).toHaveBeenCalledOnce()
+ expect(closeOnExit).toHaveBeenCalledWith({ reason: 'renderer_replaced' })
})
it('never closes the sandbox-ui embed for an obsolete window', () => {
@@ -108,7 +110,7 @@ describe('main window renderer readiness', () => {
webContents: obsolete.webContents as never,
isCurrentWindow: () => false,
markNotReady: vi.fn(),
- closeSandboxUi,
+ sandboxUi: { closeSandboxUi },
})
obsolete.listeners.get('did-navigate')?.()
diff --git a/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts b/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts
index 982ed9a24..eedd151a5 100644
--- a/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts
+++ b/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts
@@ -160,6 +160,7 @@ type MountSandboxUiViewOverrides = Omit<Partial<MountSandboxUiViewArgs>, 'parent
function mountArgs(overrides: MountSandboxUiViewOverrides): MountSandboxUiViewArgs {
return {
+ launchId: crypto.randomUUID(),
recipeNs: 'sandbox-recipes',
recipeName: 'task-board',
setCookie:
@@ -397,6 +398,22 @@ describe('mountSandboxUiView lifecycle cleanup', () => {
expect(findInActiveSandboxUi('invoice', 'start', 2, onResult).status).toBe('started')
})
+ it('a mount over a live view releases that view as replaced', async () => {
+ const parentWindow = new FakeParentWindow()
+ const onReleased = vi.fn()
+ const first = mountArgs({ parentWindow, onReleased })
+ await mountSandboxUiView(first)
+
+ await mountSandboxUiView(mountArgs({ parentWindow, recipeName: 'second-app' }))
+
+ expect(onReleased).toHaveBeenCalledOnce()
+ expect(onReleased).toHaveBeenCalledWith({
+ launchId: first.launchId,
+ reason: 'replaced',
+ location: {},
+ })
+ })
+
it('keeps only the newest view when cookie writes complete out of order', async () => {
const parentWindow = new FakeParentWindow()
let resolveFirstCookie!: () => void
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index bee13e1c2..2a149afaa 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -1403,7 +1403,7 @@ export class AppService {
// The embed and its refresh loop run on the outgoing session. Queued rather
// than awaited: callers must not wait on a pending open's mint; the serial
// queue still tears down whatever that open mounts.
- void this.closeSandboxUi().catch(error => {
+ void this.closeSandboxUi({ reason: 'session' }).catch(error => {
console.error('[SandboxUI] Could not close the embed on session change:', error)
})
}
@@ -5283,6 +5283,8 @@ export class AppService {
* mixups.
*/
openSandboxUi(args: {
+ /** Names the view this open mounts in every event about it. */
+ launchId: string
recipeNs: string
recipeName: string
title?: string
@@ -5291,12 +5293,15 @@ export class AppService {
bounds: import('./sandboxUiDriver.js').SandboxUiBounds
parentWindow: import('electron').BrowserWindow
onClosed?: () => void
+ /** Exactly once per view this open mounts, even if the open then rejects. */
+ onReleased?: (event: import('./sandboxUiDriver.js').SandboxUiReleasedEvent) => void
onRefreshError?: (message: string) => void
onOauthError?: (message: string) => void
onTitleChanged?: (title: string) => void
}): Promise<void> {
// Captured at request time, not when the queue reaches it: an open asked for
- // under one session must not run under the next one.
+ // under one session must not run under the next one. Enqueued synchronously:
+ // a close for this launch sent right after it must find it ahead in the queue.
const sessionEpoch = this.sandboxUiSessionEpoch
return this.enqueueSandboxUiLifecycle(() => this.openSandboxUiNow(args, sessionEpoch))
}
@@ -5316,11 +5321,14 @@ export class AppService {
// 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()
+ await this.teardownSandboxUiView('replaced')
try {
await this.mintAndMountSandboxUiView(args, recipeNs, recipeName, sessionEpoch)
} catch (error) {
- await this.teardownSandboxUiView()
+ // Only this open's own view, never one another launch owns; its release
+ // goes out before the rejection.
+ const reason = this.sandboxUiSessionEpoch === sessionEpoch ? 'closed' : 'session'
+ await this.teardownSandboxUiView(reason, args.launchId)
throw error
}
}
@@ -5350,6 +5358,8 @@ export class AppService {
routePath: args.routePath,
parentWindow: args.parentWindow,
bounds: args.bounds,
+ launchId: args.launchId,
+ onReleased: args.onReleased,
onClosed: () => {
// Cancel refresh first so the timer doesn't keep firing against a
// partition we're about to evict on the next mount.
@@ -5386,11 +5396,11 @@ export class AppService {
})
this.assertSandboxUiSessionEpoch(sessionEpoch)
const activeView = driver.getActiveSandboxUi()
- if (!activeView || activeView.appRef !== `${recipeNs}/${recipeName}`) {
- // A queued close or newer mount can invalidate this operation while an
- // async cookie write is in flight. Do not cross-wire its refresh loop
- // to whichever recipe is active now.
- return
+ if (!activeView || activeView.launchId !== args.launchId) {
+ // The view died before the open finished (its renderer crashed, its
+ // window closed). An open resolves only when it leaves its view mounted,
+ // and its refresh loop must not attach to whatever is active now.
+ throw new Error('The app view closed before it finished opening')
}
// Pin the surface so the SDK broker can derive this plugin's identity from
// `webContents.id` — the plugin never asserts who it is.
@@ -5431,25 +5441,55 @@ export class AppService {
})
}
- closeSandboxUi(): Promise<void> {
- return this.enqueueSandboxUiLifecycle(() => this.teardownSandboxUiView())
+ /**
+ * 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`.
+ */
+ closeSandboxUi(
+ options: {
+ launchId?: string
+ reason?: import('./sandboxUiDriver.js').SandboxUiReleaseReason
+ } = {}
+ ): Promise<void> {
+ return this.enqueueSandboxUiLifecycle(() =>
+ this.teardownSandboxUiView(options.reason ?? 'closed', options.launchId)
+ )
}
- private async teardownSandboxUiView(): Promise<void> {
+ private async teardownSandboxUiView(
+ reason: import('./sandboxUiDriver.js').SandboxUiReleaseReason,
+ onlyLaunchId?: string
+ ): Promise<void> {
const driver = await import('./sandboxUiDriver.js')
const refreshModule = await import('./sandboxUiSessionRefresh.js')
- refreshModule.cancelSandboxUiRefresh()
- tryGetPluginSdkRuntime()?.unpinAllSandboxUiSurfaces()
- await driver.unmountSandboxUiView()
+ if (onlyLaunchId !== undefined && driver.getActiveSandboxUi()?.launchId !== onlyLaunchId) {
+ return
+ }
+ // Neither must keep the view from being unmounted and released.
+ try {
+ refreshModule.cancelSandboxUiRefresh()
+ } catch (error) {
+ console.error('[SandboxUI] Could not cancel the session refresh of a closing view:', error)
+ }
+ try {
+ tryGetPluginSdkRuntime()?.unpinAllSandboxUiSurfaces()
+ } catch (error) {
+ console.error('[SandboxUI] Could not unpin the surfaces of a closing view:', error)
+ }
+ 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.
- // 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.
+ // 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()
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index 67038e6cd..4d5ec8b8d 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -45,12 +45,15 @@ function sanitizeString(input: unknown): string {
// The renderer names each sandbox-ui open so it can tell events of the view
// that open mounted from those of a view it replaced (same appRef on a
-// relaunch). The id is echoed verbatim on IPC events, so bound it here.
-const SANDBOX_UI_LAUNCH_ID_PATTERN = /^[A-Za-z0-9-]{1,64}$/
+// relaunch). Main outlives renderer reloads and keeps reporting views opened by
+// an earlier renderer, so the id must be unique across renderer lifetimes: a
+// random UUID, never a counter. It is echoed verbatim on IPC events.
+const SANDBOX_UI_LAUNCH_ID_PATTERN =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
function parseSandboxUiLaunchId(input: unknown): string {
if (typeof input !== 'string' || !SANDBOX_UI_LAUNCH_ID_PATTERN.test(input)) {
- throw new Error('launchId must be 1-64 characters of [A-Za-z0-9-]')
+ throw new Error('launchId must be a UUID')
}
return input
}
@@ -2033,6 +2036,10 @@ export function registerIpcHandlers(service: AppService): void {
return { x, y, width, height, dpr }
}
+ // `sandboxUi:open` and `sandboxUi:close` must reach the AppService queue with
+ // no `await` before it, in both handlers: a close the renderer sends right
+ // after an open for the same launch would otherwise be enqueued first and
+ // miss the view the open then mounts.
ipcMain.handle(
'sandboxUi:open',
async (
@@ -2060,6 +2067,7 @@ export function registerIpcHandlers(service: AppService): void {
const bounds = parseBounds(payload?.bounds)
const appRef = `${recipeNs}/${recipeName}`
await service.openSandboxUi({
+ launchId,
recipeNs,
recipeName,
// Human title from the installed recipe, used verbatim in consent
@@ -2074,6 +2082,15 @@ export function registerIpcHandlers(service: AppService): void {
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
+ parentWindow.webContents.send('sandboxUi:released', {
+ launchId: released.launchId,
+ reason: released.reason,
+ location: released.location,
+ })
+ },
onRefreshError: message => {
if (parentWindow.isDestroyed()) return
parentWindow.webContents.send('sandboxUi:refreshError', { appRef, launchId, message })
@@ -2086,9 +2103,17 @@ export function registerIpcHandlers(service: AppService): void {
}
)
- ipcMain.handle('sandboxUi:close', async event => {
+ // 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.
+ ipcMain.handle('sandboxUi:close', async (event, payload?: { launchId?: unknown } | null) => {
assertTrustedSender(event)
- await service.closeSandboxUi()
+ if (payload === undefined || payload === null) {
+ await service.closeSandboxUi()
+ return
+ }
+ const launchId = parseSandboxUiLaunchId(payload.launchId)
+ await service.closeSandboxUi({ launchId })
})
ipcMain.handle('sandboxUi:reload', async event => {
diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.ts
index f0b52dc2d..4c3273617 100644
--- a/desktop-app/src/main.ts
+++ b/desktop-app/src/main.ts
@@ -511,7 +511,7 @@ async function createWindow(): Promise<void> {
markNotReady: () => {
mainWindowRendererReady = false
},
- closeSandboxUi: () => appService.closeSandboxUi(),
+ sandboxUi: appService,
})
wireWindowVisibility(window)
diff --git a/desktop-app/src/mainWindowReadiness.ts b/desktop-app/src/mainWindowReadiness.ts
index aea977a4a..caa6aaa56 100644
--- a/desktop-app/src/mainWindowReadiness.ts
+++ b/desktop-app/src/mainWindowReadiness.ts
@@ -4,15 +4,19 @@ export function wireMainWindowRendererReadiness(input: {
webContents: Pick<WebContents, 'isDestroyed' | 'on' | 'reload'>
isCurrentWindow: () => boolean
markNotReady: () => void
- closeSandboxUi: () => Promise<void>
+ // The service itself rather than a closure, so the release reason chosen here
+ // cannot be dropped on the way.
+ sandboxUi: { closeSandboxUi(options: { reason: 'renderer_replaced' }): Promise<void> }
}): void {
- const { webContents, isCurrentWindow, markNotReady, closeSandboxUi } = input
+ const { webContents, isCurrentWindow, markNotReady, sandboxUi } = input
// The sandbox-ui embed is a native view painted over this renderer and owned
// by renderer state. A replacement renderer starts with no owner for it, so
- // main drops the embed itself; the new renderer needs no notice.
+ // main drops the embed itself. Its release is still sent to this window's
+ // webContents, which may by then belong to the replacement renderer: that
+ // renderer did not open the launch and ignores it.
const discardSandboxUi = () => {
- void closeSandboxUi().catch(error => {
+ void sandboxUi.closeSandboxUi({ reason: 'renderer_replaced' }).catch(error => {
console.error('[Desktop] Could not close the sandbox-ui embed of a replaced renderer:', error)
})
}
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 5c54f57c4..ab30961b7 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -6,6 +6,7 @@ import type {
HostMessageRequest,
ProfileSettingsOpenOptions,
SandboxUiDeepLinkEnvelope,
+ SandboxUiReleasedEvent,
} from './types.js'
// Sandboxed Electron preloads cannot load relative runtime modules. Keep this
@@ -671,7 +672,9 @@ const clerum = Object.freeze({
bounds: { x: number; y: number; width: number; height: number; dpr?: number }
launchId: string
}) => ipcRenderer.invoke('sandboxUi:open', args),
- close: () => ipcRenderer.invoke('sandboxUi:close'),
+ // 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'),
copyDeepLink: (teamId?: string) => ipcRenderer.invoke('sandboxUi:copyDeepLink', { teamId }),
@@ -735,6 +738,11 @@ const clerum = Object.freeze({
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)
+ return () => ipcRenderer.off('sandboxUi:released', listener)
+ },
onRefreshError: (
callback: (args: { appRef: string; launchId: string; message: string }) => void
) => {
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 263188016..de744fdc5 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -39,6 +39,7 @@ import {
RpcConnectorsResult,
SandboxUiApp,
SandboxUiDeepLinkEnvelope,
+ SandboxUiReleasedEvent,
SessionLifecycleState,
SessionMessagesQuery,
SessionMessagesResult,
@@ -766,7 +767,9 @@ declare global {
// for the view this open mounts.
launchId: string
}) => Promise<void>
- close: () => 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>
copyDeepLink: (teamId?: string) => Promise<{ url: string }>
@@ -808,6 +811,9 @@ declare global {
) => () => void
onDeepLink: (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) => () => void
onRefreshError: (
callback: (args: { appRef: string; launchId: string; message: string }) => void
) => () => void
diff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.ts
index b878af8c8..ddad83e30 100644
--- a/desktop-app/src/sandboxUiDriver.ts
+++ b/desktop-app/src/sandboxUiDriver.ts
@@ -10,6 +10,9 @@ import {
isSandboxUiNavigationWithinPrefix as isNavigationWithinPrefix,
} from './sandboxUiPartitionPolicies.js'
import { wireDesktopShortcutRouting } from './shortcutRouter.js'
+import type { SandboxUiReleaseReason, SandboxUiReleasedEvent, SandboxUiRoute } from './types.js'
+
+export type { SandboxUiReleaseReason, SandboxUiReleasedEvent, SandboxUiRoute }
/**
* Sandbox UI embed driver. Owns the lifecycle of the single active
@@ -95,6 +98,8 @@ function toViewBounds(
}
export type MountSandboxUiArgs = {
+ /** Names this mount in every event about the view it creates. */
+ launchId: string
recipeNs: string
recipeName: string
setCookie: string
@@ -104,6 +109,12 @@ export type MountSandboxUiArgs = {
bounds: SandboxUiBounds
routePath?: string
onClosed?: () => void
+ /**
+ * Fired exactly once when the view this mount created is torn down, for any
+ * reason, including a teardown that fails half-way. Never fired when the
+ * mount did not get as far as creating a view.
+ */
+ onReleased?: (event: SandboxUiReleasedEvent) => void
/**
* Fired when the embedded document's `<title>` changes (`page-title-updated`).
* The driver only forwards the plugin-controlled title; the renderer decides
@@ -141,7 +152,9 @@ export type MountSandboxUiArgs = {
}
type ActiveView = {
+ launchId: string
view: WebContentsView
+ onReleased?: (event: SandboxUiReleasedEvent) => void
recipeNs: string
recipeName: string
defaultPath: string
@@ -154,6 +167,14 @@ type ActiveView = {
cleanupShortcutRouting?: () => void
cleanupDocumentLifecycle?: () => void
cleanupFindResults?: () => void
+ /** The route the open asked for, as `representedSandboxUiLocation` reports it. */
+ requestedRoute: SandboxUiRoute
+ /**
+ * False while the document cannot yet stand for the requested route: it has
+ * not loaded, or the route handoff is pending or failed with no navigation
+ * since. Once true it stays true: a reload keeps the committed URL.
+ */
+ routeSettled: boolean
documentGeneration: number
documentReady: boolean
findSession?: {
@@ -171,6 +192,7 @@ let mountGeneration = 0
export const isSandboxUiNavigationWithinPrefix = isNavigationWithinPrefix
export function getActiveSandboxUi(): {
+ launchId: string
recipeNs: string
recipeName: string
appRef: string
@@ -178,6 +200,7 @@ export function getActiveSandboxUi(): {
} | null {
if (!active) return null
return {
+ launchId: active.launchId,
recipeNs: active.recipeNs,
recipeName: active.recipeName,
appRef: `${active.recipeNs}/${active.recipeName}`,
@@ -192,20 +215,33 @@ export function getActiveSandboxUiLocation(): {
} | null {
if (!active) return null
if (active.view.webContents.isDestroyed()) return null
- const path = resolveSandboxUiSharePath({
- currentUrl: active.view.webContents.getURL(),
- rpcProxyOrigin: active.rpcProxyOrigin,
- recipeNs: active.recipeNs,
- recipeName: active.recipeName,
- defaultPath: active.defaultPath,
- })
+ const { routePath } = representedSandboxUiLocation(active)
return {
recipeNs: active.recipeNs,
recipeName: active.recipeName,
- ...(path ? { path } : {}),
+ ...(routePath ? { path: routePath } : {}),
}
}
+/**
+ * The single reader of the route a view stands for. Until the document can
+ * represent the requested route, the live URL is empty or the default route,
+ * and reporting it would overwrite the route the user is on with a wrong one.
+ * Throws when the live URL is outside the app; each caller decides what that
+ * means for it.
+ */
+function representedSandboxUiLocation(view: ActiveView): SandboxUiRoute {
+ if (!view.routeSettled) return { ...view.requestedRoute }
+ const routePath = resolveSandboxUiSharePath({
+ currentUrl: view.view.webContents.getURL(),
+ rpcProxyOrigin: view.rpcProxyOrigin,
+ recipeNs: view.recipeNs,
+ recipeName: view.recipeName,
+ defaultPath: view.defaultPath,
+ })
+ return routePath ? { routePath } : {}
+}
+
export function resolveSandboxUiSharePath(input: {
currentUrl: string
rpcProxyOrigin: string
@@ -346,38 +382,82 @@ export async function installSandboxUiCookie(setCookie: string | string[]): Prom
})
}
-async function teardownActive(
- reason: 'replaced' | 'closed' | 'parent_closed' | 'crashed'
-): Promise<void> {
+function readReleasedLocation(
+ view: ActiveView,
+ reason: SandboxUiReleaseReason
+): SandboxUiRoute | null {
+ if (reason === 'crashed') return null
+ try {
+ return representedSandboxUiLocation(view)
+ } catch (err) {
+ console.warn('[SandboxUI] could not read the route of a view being torn down:', err)
+ return null
+ }
+}
+
+function runTeardownStep(step: string, reason: SandboxUiReleaseReason, run: () => void): void {
+ try {
+ run()
+ } catch (err) {
+ console.error(`[SandboxUI] teardown step ${step} failed:`, err, 'reason:', reason)
+ }
+}
+
+/**
+ * Synchronous on purpose: the release event must leave before anything else
+ * can run, so a caller that rejects after a teardown always reports the release
+ * first. Every step is isolated; a failing listener unhook must not leave the
+ * view attached, alive or unreported.
+ */
+function teardownActive(reason: SandboxUiReleaseReason): void {
if (!active) return
const current = active
active = null
+ const location = readReleasedLocation(current, reason)
+ const webContents = current.view.webContents
try {
- current.cleanupClientRouteHandoff?.()
- current.cleanupParentClosed?.()
- current.cleanupRenderProcessGone?.()
- current.cleanupShortcutRouting?.()
- current.cleanupDocumentLifecycle?.()
- current.cleanupFindResults?.()
- if (!current.view.webContents.isDestroyed()) {
- current.view.webContents.stopFindInPage('clearSelection')
- }
- // contentView.removeChildView is the documented teardown step; it both
- // detaches the view from layout AND severs the parent's ownership ref.
- if (!current.parentWindow.isDestroyed()) {
- current.parentWindow.contentView.removeChildView(current.view)
- }
- // Closing the webContents stops loading + frees the renderer process.
- if (!current.view.webContents.isDestroyed()) {
- current.view.webContents.close()
- }
- } catch (err) {
- console.error('[SandboxUI] teardown error:', err, 'reason:', reason)
+ runTeardownStep('cleanupClientRouteHandoff', reason, () =>
+ current.cleanupClientRouteHandoff?.()
+ )
+ runTeardownStep('cleanupParentClosed', reason, () => current.cleanupParentClosed?.())
+ runTeardownStep('cleanupRenderProcessGone', reason, () => current.cleanupRenderProcessGone?.())
+ runTeardownStep('cleanupShortcutRouting', reason, () => current.cleanupShortcutRouting?.())
+ runTeardownStep('cleanupDocumentLifecycle', reason, () => current.cleanupDocumentLifecycle?.())
+ runTeardownStep('cleanupFindResults', reason, () => current.cleanupFindResults?.())
+ runTeardownStep('stopFindInPage', reason, () => {
+ if (!webContents.isDestroyed()) webContents.stopFindInPage('clearSelection')
+ })
+ } finally {
+ // Every step above is guarded today; the finally keeps detach, close and
+ // release unconditional if a step is ever added without its guard.
+ // removeChildView both detaches the view from layout and severs the
+ // parent's ownership ref.
+ runTeardownStep('removeChildView', reason, () => {
+ if (!current.parentWindow.isDestroyed()) {
+ current.parentWindow.contentView.removeChildView(current.view)
+ }
+ })
+ // Closing the webContents stops loading and frees the renderer process.
+ runTeardownStep('closeWebContents', reason, () => {
+ if (!webContents.isDestroyed()) webContents.close()
+ })
+ runTeardownStep('onReleased', reason, () =>
+ current.onReleased?.({ launchId: current.launchId, reason, location })
+ )
+ runTeardownStep('verifyDetached', reason, () => {
+ if (
+ !current.parentWindow.isDestroyed() &&
+ current.parentWindow.contentView.children.includes(current.view)
+ ) {
+ console.error('[SandboxUI] a torn-down view is still attached to its window')
+ }
+ })
}
}
export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void> {
const {
+ launchId,
recipeNs,
recipeName,
setCookie,
@@ -387,6 +467,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
bounds,
routePath,
onClosed,
+ onReleased,
onTitleChanged,
isCurrent = () => true,
} = args
@@ -406,7 +487,9 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
// 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')
+ // AppService already tore down before minting; this covers callers that
+ // mount through the driver without that queue.
+ teardownActive('replaced')
if (generation !== mountGeneration || !isCurrent()) return
const partition = partitionFor(getActiveEnvKey(), recipeNs, recipeName)
@@ -414,6 +497,9 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
const viewPath = resolveSandboxUiDefaultPath(defaultPath)
const clientRoutePath = normalizeSandboxUiRoute(routePath || '')
const sharedViewPath = sharedPathForDefaultPath(viewPath)
+ const needsClientRouteHandoff = Boolean(clientRoutePath && clientRoutePath !== sharedViewPath)
+ const requestedRoute: SandboxUiRoute =
+ needsClientRouteHandoff && clientRoutePath ? { routePath: clientRoutePath } : {}
const allowedNavigationPrefix =
`${proxyOriginUrl}/api/v1/sandbox-ui/` +
`${encodeURIComponent(recipeNs)}/${encodeURIComponent(recipeName)}/view`
@@ -483,7 +569,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
// 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')
+ teardownActive('parent_closed')
onClosed?.()
}
parentWindow.once('closed', onParentClosed)
@@ -497,7 +583,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
// unrelated mount that is in flight.
const onRenderProcessGone = (): void => {
if (active?.view !== view) return
- void teardownActive('crashed')
+ teardownActive('crashed')
onClosed?.()
}
view.webContents.on('render-process-gone', onRenderProcessGone)
@@ -506,7 +592,9 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
}
active = {
+ launchId,
view,
+ onReleased,
recipeNs,
recipeName,
defaultPath: viewPath,
@@ -515,6 +603,8 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
rpcProxyOrigin: proxyOriginUrl,
cleanupParentClosed,
cleanupRenderProcessGone,
+ requestedRoute,
+ routeSettled: false,
documentGeneration: 0,
documentReady: false,
}
@@ -533,8 +623,25 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
): void => {
if (isMainFrame) invalidateFindForNavigation(!isInPlace)
}
+ let documentLoaded = false
+ // Cleared by the handoff when it applies the route, fails, times out or is
+ // abandoned.
+ let clientRouteHandoffPending = needsClientRouteHandoff
+ let lastMainFrameUrl = ''
const onDocumentReady = (): void => {
- if (active?.view === view) active.documentReady = true
+ if (active?.view !== view) return
+ documentLoaded = true
+ active.documentReady = true
+ if (!needsClientRouteHandoff) active.routeSettled = true
+ }
+ // A navigation inside the loaded document is the user's (or the app's) own:
+ // from then on the live URL is the route, whatever became of the handoff.
+ const onDidNavigateInPage = (_event: Electron.Event, url: string, isMainFrame: boolean): void => {
+ if (active?.view !== view || !isMainFrame) return
+ // A router can move the URL before the first load; a later reload commits
+ // that URL and must still read as a reload.
+ lastMainFrameUrl = url
+ if (documentLoaded) active.routeSettled = true
}
// Forward the embed's live `document.title` so the renderer can name its app
// tab after it (mirrors the URL-report pattern). The title is plugin content,
@@ -548,17 +655,29 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
navigatedUrl: string,
httpResponseCode: number
): void => {
- if (active?.view !== view || httpResponseCode !== 401) return
- if (!isSandboxUiNavigationWithinPrefix(navigatedUrl, allowedNavigationPrefix)) return
+ if (active?.view !== view) return
+ const previousUrl = lastMainFrameUrl
+ lastMainFrameUrl = navigatedUrl
+ const withinApp = isSandboxUiNavigationWithinPrefix(navigatedUrl, allowedNavigationPrefix)
+ // A new document the user reached after the handoff gave up (a multi-page
+ // app) is the live route. A reload commits the same URL and the commits a
+ // pending handoff is still waiting through are not the user's: neither may
+ // replace the requested route.
+ if (withinApp && documentLoaded && !clientRouteHandoffPending && navigatedUrl !== previousUrl) {
+ active.routeSettled = true
+ }
+ if (httpResponseCode !== 401 || !withinApp) return
args.onUnauthorizedNavigation?.(view.webContents.id)
}
view.webContents.on('did-start-navigation', onDidStartNavigation)
view.webContents.on('did-finish-load', onDocumentReady)
+ view.webContents.on('did-navigate-in-page', onDidNavigateInPage)
view.webContents.on('page-title-updated', onPageTitleUpdated)
view.webContents.on('did-navigate', onDocumentNavigated)
active.cleanupDocumentLifecycle = () => {
view.webContents.removeListener('did-start-navigation', onDidStartNavigation)
view.webContents.removeListener('did-finish-load', onDocumentReady)
+ view.webContents.removeListener('did-navigate-in-page', onDidNavigateInPage)
view.webContents.removeListener('page-title-updated', onPageTitleUpdated)
view.webContents.removeListener('did-navigate', onDocumentNavigated)
}
@@ -589,7 +708,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
`${encodeURIComponent(recipeNs)}/${encodeURIComponent(recipeName)}/view${encodeSandboxUiDefaultPath(
viewPath
)}`
- if (clientRoutePath && clientRoutePath !== sharedViewPath) {
+ if (needsClientRouteHandoff && clientRoutePath) {
const encodedClientRoutePath = encodeSandboxUiRoutePath(clientRoutePath)
const clientRouteUrl =
`${proxyOriginUrl}/api/v1/sandbox-ui/` +
@@ -600,6 +719,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
const cleanupClientRouteHandoff = () => {
if (handoffFinished) return
handoffFinished = true
+ clientRouteHandoffPending = false
if (handoffTimeout) clearTimeout(handoffTimeout)
view.webContents.removeListener('did-navigate', onDidNavigate)
view.webContents.removeListener('did-finish-load', onDidFinishLoad)
@@ -639,6 +759,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
}
void applySandboxUiClientRoute(view.webContents, clientRouteUrl)
.then(applied => {
+ if (applied && active?.view === view) active.routeSettled = true
if (!applied) {
console.warn('[SandboxUI] client route handoff did not update the app URL')
}
@@ -802,9 +923,11 @@ export function canApplySandboxUiClientRoute(input: {
* "Close" / navigate-away. Leaves the per-recipe partition intact so a
* re-mount within the ACL window is fast.
*/
-export async function unmountSandboxUiView(): Promise<void> {
+export async function unmountSandboxUiView(
+ reason: SandboxUiReleaseReason = 'closed'
+): Promise<void> {
mountGeneration += 1
- await teardownActive('closed')
+ teardownActive(reason)
}
/**
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 86dc5f892..37cb45684 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -32,6 +32,32 @@ export type SandboxUiApp = {
export type { SandboxUiDeepLinkEnvelope } from '@clerum/desktop-app-links'
+/**
+ * Why a sandbox-ui view died. `crashed` never carries a location: handing the
+ * route back would relaunch straight into whatever crashed it.
+ */
+export type SandboxUiReleaseReason =
+ | 'replaced'
+ | 'closed'
+ | 'crashed'
+ | 'parent_closed'
+ | 'session'
+ | 'renderer_replaced'
+
+/** `{}` is the app's default route, `{ routePath }` a specific one. */
+export type SandboxUiRoute = { routePath?: string }
+
+/**
+ * Sent once per sandbox-ui view main tears down, to the window it was mounted
+ * in. `location: null` means the route could not be read: keep the last known
+ * one.
+ */
+export type SandboxUiReleasedEvent = {
+ launchId: string
+ reason: SandboxUiReleaseReason
+ location: SandboxUiRoute | null
+}
+
export type SessionMe = {
id: string
email: string