Skip to content

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

TypeScript

fix(desktop-app): r1-m1 tie sandbox-ui embed events to the launch that opened them

Diego Zacariasa4c167286f20
diff --git a/desktop-app/src/__tests__/ipc.sandboxUiLaunchId.test.ts b/desktop-app/src/__tests__/ipc.sandboxUiLaunchId.test.ts
new file mode 100644
index 000000000..208372648
--- /dev/null
+++ b/desktop-app/src/__tests__/ipc.sandboxUiLaunchId.test.ts
@@ -0,0 +1,113 @@
+/**
+ * Every per-view sandbox-ui event names the open request that mounted the view.
+ * A relaunch of the same app keeps the appRef, so the renderer can only tell a
+ * late event from the replaced view apart from the live one by this id. The
+ * events are produced by the real `sandboxUi:open` handler: the callbacks it
+ * hands to AppService are invoked the way AppService invokes them.
+ */
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import type { AppService } from '../appService.js'
+
+type Handler = (event: unknown, payload: unknown) => Promise<unknown>
+
+const electron = vi.hoisted(() => ({
+ handlers: new Map<string, Handler>(),
+ send: vi.fn(),
+}))
+
+vi.mock('electron', () => ({
+ BrowserWindow: {
+ fromWebContents: vi.fn(() => ({
+ isDestroyed: () => false,
+ webContents: { send: electron.send },
+ })),
+ getAllWindows: vi.fn(() => []),
+ },
+ Notification: vi.fn(),
+ app: { on: vi.fn(), getPath: vi.fn(), getVersion: vi.fn() },
+ clipboard: { writeText: vi.fn() },
+ dialog: { showSaveDialog: vi.fn() },
+ ipcMain: {
+ handle: vi.fn((channel: string, handler: Handler) => {
+ electron.handlers.set(channel, handler)
+ }),
+ on: vi.fn(),
+ removeHandler: vi.fn(),
+ },
+}))
+vi.mock('../appService.js', () => ({ AppService: class {} }))
+
+type OpenArgs = Parameters<AppService['openSandboxUi']>[0]
+const opens: OpenArgs[] = []
+const service = {
+ openSandboxUi: vi.fn(async (args: OpenArgs) => {
+ opens.push(args)
+ }),
+}
+const trusted = { senderFrame: { url: 'file:///app/index.html' }, sender: {} }
+const bounds = { x: 0, y: 0, width: 400, height: 300 }
+
+function open(payload: Record<string, unknown>) {
+ const handler = electron.handlers.get('sandboxUi:open')
+ if (!handler) throw new Error('no IPC handler registered for sandboxUi:open')
+ return handler(trusted, { recipeNs: 'sandbox-recipes', recipeName: 'alpha', bounds, ...payload })
+}
+
+beforeAll(async () => {
+ const { registerIpcHandlers } = await import('../ipc.js')
+ registerIpcHandlers(service as unknown as AppService)
+})
+
+afterEach(() => {
+ opens.length = 0
+ service.openSandboxUi.mockClear()
+ electron.send.mockClear()
+})
+
+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 [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: 'launch-1' }],
+ [
+ 'sandboxUi:refreshError',
+ { appRef: 'sandbox-recipes/alpha', launchId: 'launch-1', message: 'refresh failed' },
+ ],
+ [
+ 'sandboxUi:titleChanged',
+ { appRef: 'sandbox-recipes/alpha', launchId: 'launch-1', title: 'Old title' },
+ ],
+ [
+ 'sandboxUi:titleChanged',
+ { appRef: 'sandbox-recipes/alpha', launchId: 'launch-2', 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()
+ }
+ )
+
+ it('accepts a renderer-minted UUID', async () => {
+ const launchId = crypto.randomUUID()
+ await open({ launchId })
+ opens[0]!.onClosed?.()
+ expect(electron.send).toHaveBeenCalledWith('sandboxUi:closed', {
+ appRef: 'sandbox-recipes/alpha',
+ launchId,
+ })
+ })
+})
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index 340dcc39a..67038e6cd 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -43,6 +43,18 @@ function sanitizeString(input: unknown): string {
return String(input || '').trim()
}
+// 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}$/
+
+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-]')
+ }
+ return input
+}
+
function sanitizeChatAuthorityScope(input: unknown): ChatAuthorityScope {
if (!input || typeof input !== 'object' || Array.isArray(input)) {
throw new Error('Invalid chat deletion authority scope')
@@ -2031,6 +2043,7 @@ export function registerIpcHandlers(service: AppService): void {
defaultPath?: string
routePath?: string
bounds: unknown
+ launchId: unknown
}
) => {
assertTrustedSender(event)
@@ -2039,6 +2052,7 @@ export function registerIpcHandlers(service: AppService): void {
if (!recipeNs || !recipeName) {
throw new Error('recipeNs and recipeName are required')
}
+ const launchId = parseSandboxUiLaunchId(payload?.launchId)
const parentWindow = BrowserWindow.fromWebContents(event.sender)
if (!parentWindow) {
throw new Error('cannot resolve parent window from IPC sender')
@@ -2058,15 +2072,15 @@ export function registerIpcHandlers(service: AppService): void {
parentWindow,
onClosed: () => {
if (parentWindow.isDestroyed()) return
- parentWindow.webContents.send('sandboxUi:closed', { appRef })
+ parentWindow.webContents.send('sandboxUi:closed', { appRef, launchId })
},
onRefreshError: message => {
if (parentWindow.isDestroyed()) return
- parentWindow.webContents.send('sandboxUi:refreshError', { appRef, message })
+ parentWindow.webContents.send('sandboxUi:refreshError', { appRef, launchId, message })
},
onTitleChanged: title => {
if (parentWindow.isDestroyed()) return
- parentWindow.webContents.send('sandboxUi:titleChanged', { appRef, title })
+ parentWindow.webContents.send('sandboxUi:titleChanged', { appRef, launchId, title })
},
})
}
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 59abcb5b3..5c54f57c4 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -669,6 +669,7 @@ const clerum = Object.freeze({
defaultPath?: string
routePath?: string
bounds: { x: number; y: number; width: number; height: number; dpr?: number }
+ launchId: string
}) => ipcRenderer.invoke('sandboxUi:open', args),
close: () => ipcRenderer.invoke('sandboxUi:close'),
reload: () => ipcRenderer.invoke('sandboxUi:reload'),
@@ -728,19 +729,29 @@ const clerum = Object.freeze({
ipcRenderer.on('sandboxUi:deepLink', listener)
return () => ipcRenderer.off('sandboxUi:deepLink', listener)
},
- onClosed: (callback: (args: { appRef: string }) => void) => {
- const listener = (_event: unknown, args: { appRef: string }) => callback(args)
+ 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)
},
- onRefreshError: (callback: (args: { appRef: string; message: string }) => void) => {
- const listener = (_event: unknown, args: { appRef: string; message: string }) =>
- callback(args)
+ onRefreshError: (
+ callback: (args: { appRef: string; launchId: string; message: string }) => void
+ ) => {
+ const listener = (
+ _event: unknown,
+ args: { appRef: string; launchId: string; message: string }
+ ) => callback(args)
ipcRenderer.on('sandboxUi:refreshError', listener)
return () => ipcRenderer.off('sandboxUi:refreshError', listener)
},
- onTitleChanged: (callback: (args: { appRef: string; title: string }) => void) => {
- const listener = (_event: unknown, args: { appRef: string; title: string }) => callback(args)
+ onTitleChanged: (
+ callback: (args: { appRef: string; launchId: string; title: string }) => void
+ ) => {
+ const listener = (
+ _event: unknown,
+ args: { appRef: string; launchId: string; title: string }
+ ) => callback(args)
ipcRenderer.on('sandboxUi:titleChanged', listener)
return () => ipcRenderer.off('sandboxUi:titleChanged', listener)
},
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 338a01182..263188016 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -762,6 +762,9 @@ declare global {
defaultPath?: string
routePath?: string
bounds: { x: number; y: number; width: number; height: number; dpr?: number }
+ // Echoed by main on `onClosed` / `onRefreshError` / `onTitleChanged`
+ // for the view this open mounts.
+ launchId: string
}) => Promise<void>
close: () => Promise<void>
reload: () => Promise<void>
@@ -804,11 +807,13 @@ declare global {
}) => void
) => () => void
onDeepLink: (callback: (args: SandboxUiDeepLinkEnvelope) => void) => () => void
- onClosed: (callback: (args: { appRef: string }) => void) => () => void
+ onClosed: (callback: (args: { appRef: string; launchId: string }) => void) => () => void
onRefreshError: (
- callback: (args: { appRef: string; message: string }) => void
+ callback: (args: { appRef: string; launchId: string; message: string }) => void
+ ) => () => void
+ onTitleChanged: (
+ callback: (args: { appRef: string; launchId: string; title: string }) => void
) => () => void
- onTitleChanged: (callback: (args: { appRef: string; title: string }) => void) => () => void
}
pluginSdk: {
onConsentRequested: (callback: (request: PluginConsentRequest) => void) => () => void
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index cfa47c898..7f7022f33 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -410,6 +410,10 @@ export function App() {
// the tab keeps owning whatever main may still hold (see
// `handleSandboxUiOpenFailed`).
const liveSandboxUiTabIdRef = React.useRef<string | null>(null)
+ // Id of the most recent open request (minted by SandboxUiPage, echoed by main
+ // on per-view events). A relaunch of the same app keeps the appRef, so title
+ // events are matched on this id, not on the appRef.
+ const currentSandboxUiLaunchIdRef = React.useRef<string | null>(null)
// Monotonic generation bumped on EVERY transition of the active embed (the
// deactivation effect and the deep-link handoff are the only emitters). Each
// read-then-close continuation captures this at dispatch; anything reopened or
@@ -1299,7 +1303,8 @@ export function App() {
})
}, [vm.authenticatedPrincipalIdentity])
- const handleSandboxUiOpening = React.useCallback((app: ActiveSandboxUiApp) => {
+ const handleSandboxUiOpening = React.useCallback((app: ActiveSandboxUiApp, launchId: string) => {
+ currentSandboxUiLaunchIdRef.current = launchId
setSandboxUiMounted(false)
setActiveSandboxUiApp(app)
// Arm the store's embed-liveness ref on EVERY open, however it was launched
@@ -1727,11 +1732,14 @@ export function App() {
// Name the live app tab after the embed's `document.title` (mini-spec 06 §2).
// Only the tab whose embed is live (`liveSandboxUiTabIdRef`) is renamed, and
- // only when the reported `appRef` still matches it, so a late title event from
- // a torn-down embed can't relabel whichever app is live now. The store ignores
- // empty titles, so the tab keeps its `app.label` until a real title arrives.
+ // only when the event comes from the current launch and its `appRef` still
+ // matches the tab, so a late title event from a torn-down embed (even one of
+ // the same app being relaunched) can't relabel whichever view is live now.
+ // The store ignores empty titles, so the tab keeps its `app.label` until a
+ // real title arrives.
React.useEffect(() => {
- const off = window.clerum.sandboxUi.onTitleChanged?.(({ appRef, title }) => {
+ const off = window.clerum.sandboxUi.onTitleChanged?.(({ appRef, launchId, title }) => {
+ if (launchId !== currentSandboxUiLaunchIdRef.current) return
const tabId = liveSandboxUiTabIdRef.current
if (!tabId) return
setWorkspaceTabs(state => {
diff --git a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
index 02311b5b2..2a9fad2a8 100644
--- a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
@@ -1043,92 +1043,6 @@ describe('App chat drawer — reopen preserves the last-viewed chat', () => {
})
})
-// Mini-spec 06 §2 — an app tab is named after the embed's live `document.title`.
-// The main process forwards `page-title-updated` over `sandboxUi.onTitleChanged`;
-// App renames the LIVE app tab (never a background one), ignoring empty titles so
-// the tab keeps its `app.label`. Driven through the real store producer + the real
-// WorkspaceTabStrip so the assertion is on the rendered tab label (T4).
-describe('App app-tab title — live document.title (mini-spec 06 §2)', () => {
- let currentController: AppController
- let titleChangedCb: ((args: { appRef: string; title: string }) => void) | null
-
- beforeEach(() => {
- vi.clearAllMocks()
- sidebarHarness.props = null
- sandboxUiPageHarness.props = null
- appHeaderHarness.props = null
- appHeaderHarness.openNotification = null
- titleChangedCb = null
- currentController = makeController()
- vi.mocked(useAppController).mockImplementation(() => useReactiveController(currentController))
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: {
- shortcuts: { onCommand: vi.fn(() => vi.fn()) },
- app: { rendererReady: vi.fn().mockResolvedValue(undefined) },
- sandboxUi: {
- listApps: vi.fn().mockResolvedValue({ apps: [] }),
- listPendingDeepLinks: vi.fn().mockResolvedValue({ links: [] }),
- clearPendingDeepLinks: vi.fn().mockResolvedValue(undefined),
- onDeepLink: vi.fn(() => vi.fn()),
- onTitleChanged: vi.fn((cb: (args: { appRef: string; title: string }) => void) => {
- titleChangedCb = cb
- return vi.fn()
- }),
- setVisible: vi.fn().mockResolvedValue(undefined),
- setBounds: vi.fn().mockResolvedValue(undefined),
- focusActive: vi.fn().mockResolvedValue(true),
- close: vi.fn().mockResolvedValue(undefined),
- },
- } as unknown as Window['clerum'],
- })
- })
-
- afterEach(() => {
- cleanup()
- delete (window as { clerum?: unknown }).clerum
- })
-
- it('renames the live app tab to the embed document.title, and an empty title keeps the label', () => {
- render(<App />)
-
- // Launch an app: its tab starts named after the registry label ('App').
- act(() => {
- sidebarHarness.props?.onOpenSandboxUiApp?.({
- appRef: 'ns/app',
- label: 'App',
- defaultPath: '/',
- })
- })
- expect(screen.getByRole('button', { name: 'App' })).toBeTruthy()
-
- // The embed reports its live document.title → the tab renames to it.
- act(() => titleChangedCb?.({ appRef: 'ns/app', title: 'Ticket 42 — Acme' }))
- expect(screen.getByRole('button', { name: 'Ticket 42 — Acme' })).toBeTruthy()
- expect(screen.queryByRole('button', { name: 'App' })).toBeNull()
-
- // A subsequent EMPTY title (mid-navigation blank) must not blank the label —
- // the tab keeps the last real title.
- act(() => titleChangedCb?.({ appRef: 'ns/app', title: ' ' }))
- expect(screen.getByRole('button', { name: 'Ticket 42 — Acme' })).toBeTruthy()
- })
-
- it('ignores a title event whose appRef does not match the live tab', () => {
- render(<App />)
- act(() => {
- sidebarHarness.props?.onOpenSandboxUiApp?.({
- appRef: 'ns/app',
- label: 'App',
- defaultPath: '/',
- })
- })
- // A stale title from a different app must not relabel the live tab.
- act(() => titleChangedCb?.({ appRef: 'ns/other', title: 'Wrong' }))
- expect(screen.getByRole('button', { name: 'App' })).toBeTruthy()
- expect(screen.queryByRole('button', { name: 'Wrong' })).toBeNull()
- })
-})
-
// Mini-spec 06 §3 — files is multi-instance, deduped by path. A plugin deep-link
// (`pluginSdk.onOpenGfsResource`, folder / non-previewable) opens or focuses a
// files tab AT that gfsUri; two distinct gfsUris yield two tabs, re-opening the
diff --git a/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx b/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx
index 1bfcaba9d..4525d0f4c 100644
--- a/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx
@@ -435,23 +435,25 @@ describe('App sandbox-ui embed always has an owning app tab', () => {
await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
})
- // main tags `sandboxUi:closed` with the appRef it composed from the open
- // request (`${recipeNs}/${recipeName}` in the `sandboxUi:open` handler).
- // Derive it from the open() call the real page sent instead of restating it.
- function closedEventFor(openCall: number): { appRef: string } {
+ // main tags every per-view event with the appRef it composed from the open
+ // request (`${recipeNs}/${recipeName}` in the `sandboxUi:open` handler) and
+ // echoes that request's `launchId` (pinned main-side by
+ // ipc.sandboxUiLaunchId.test.ts). Derive both from the open() call the real
+ // page sent instead of restating them.
+ type ViewEventTag = { appRef: string; launchId: string }
+ function closedEventFor(openCall: number): ViewEventTag {
const request = sandboxUi.open.mock.calls[openCall]![0] as {
recipeNs: string
recipeName: string
+ launchId: string
}
- return { appRef: `${request.recipeNs}/${request.recipeName}` }
+ return { appRef: `${request.recipeNs}/${request.recipeName}`, launchId: request.launchId }
}
- function emitSandboxUiClosed(event: { appRef: string }) {
- const listeners = sandboxUi.onClosed.mock.calls as unknown as Array<
- [(args: { appRef: string }) => void]
- >
+ function emitToSubscribed<T>(subscribe: ReturnType<typeof vi.fn>, event: T) {
+ const listeners = subscribe.mock.calls as unknown as Array<[(args: T) => void]>
const unsubscribed = new Set(
- sandboxUi.onClosed.mock.results
+ subscribe.mock.results
.map((result, index) =>
(result.value as ReturnType<typeof vi.fn>).mock.calls.length > 0 ? index : -1
)
@@ -464,6 +466,63 @@ describe('App sandbox-ui embed always has an owning app tab', () => {
})
}
+ function emitSandboxUiClosed(event: ViewEventTag) {
+ emitToSubscribed(sandboxUi.onClosed, event)
+ }
+
+ function emitRefreshError(event: ViewEventTag & { message: string }) {
+ emitToSubscribed(sandboxUi.onRefreshError, event)
+ }
+
+ // Relaunches the live Alpha tab (open #2) and holds that open in flight, the
+ // window in which main is still tearing down the view of open #1.
+ function relaunchAlphaHeldOpen(): Promise<() => Promise<void>> {
+ return relaunchAlphaHeldOpenFrom('Alpha')
+ }
+
+ async function relaunchAlphaHeldOpenFrom(tabLabel: string): Promise<() => Promise<void>> {
+ let resolveOpen: () => void = () => {}
+ sandboxUi.open.mockImplementationOnce(
+ () => new Promise<undefined>(resolve => (resolveOpen = () => resolve(undefined)))
+ )
+ clickActiveStripTab(tabLabel)
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ expect(closedEventFor(1).appRef).toBe(ALPHA!.appRef)
+ return async () => {
+ await act(async () => {
+ resolveOpen()
+ await new Promise(resolve => window.setTimeout(resolve, 0))
+ })
+ expect(await screen.findByTestId('sandbox-ui-mounted')).toBeTruthy()
+ }
+ }
+
+ it('keeps a same-app relaunch owned when the replaced view reports closed while the relaunch is opening', async () => {
+ await renderWithLiveApp(ALPHA)
+ const finishRelaunch = await relaunchAlphaHeldOpen()
+
+ // The view of open #1 dies (crash / teardown) before open #2 resolves.
+ emitSandboxUiClosed(closedEventFor(0))
+ await finishRelaunch()
+
+ await handOffMarkdownFromPlugin()
+ await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ })
+
+ it("ignores a same-app relaunch's predecessor refresh failure but shows the live view's", async () => {
+ await renderWithLiveApp(ALPHA)
+ const finishRelaunch = await relaunchAlphaHeldOpen()
+
+ emitRefreshError({ ...closedEventFor(0), message: 'stale failure' })
+ await finishRelaunch()
+ expect(screen.queryByText(text => text.startsWith('Session refresh failed'))).toBeNull()
+
+ emitRefreshError({ ...closedEventFor(1), message: 'live failure' })
+ expect(
+ await screen.findByText(text => text.startsWith('Session refresh failed: live failure'))
+ ).toBeTruthy()
+ })
+
it('keeps the live embed owned when a late closed event belongs to the app it replaced', async () => {
await renderWithLiveApp(ALPHA)
act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))
@@ -559,13 +618,30 @@ describe('App sandbox-ui embed always has an owning app tab', () => {
})
}
- function emitTitleChanged(event: { appRef: string; title: string }) {
- const listeners = sandboxUi.onTitleChanged.mock.calls as unknown as Array<
- [(args: { appRef: string; title: string }) => void]
- >
- act(() => listeners.forEach(([listener]) => listener(event)))
+ function emitTitleChanged(event: ViewEventTag & { title: string }) {
+ emitToSubscribed(sandboxUi.onTitleChanged, event)
}
+ it('renames the live app tab after its document.title, ignoring empty titles and titles from the view a relaunch replaces', async () => {
+ await renderWithLiveApp(ALPHA)
+ emitTitleChanged({ ...closedEventFor(0), title: 'Alpha Inbox' })
+ expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: true })).toBeTruthy()
+ // A mid-navigation blank title keeps the last real one.
+ emitTitleChanged({ ...closedEventFor(0), title: ' ' })
+ expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: true })).toBeTruthy()
+
+ const finishRelaunch = await relaunchAlphaHeldOpenFrom('Alpha Inbox')
+ // main only forwards titles of its active view; until the relaunch replaces
+ // it, that is still the view of open #1.
+ emitTitleChanged({ ...closedEventFor(0), title: 'Alpha Stale' })
+ expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: true })).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Alpha Stale' })).toBeNull()
+
+ await finishRelaunch()
+ emitTitleChanged({ ...closedEventFor(1), title: 'Alpha Fresh' })
+ expect(screen.getByRole('button', { name: 'Alpha Fresh', pressed: true })).toBeTruthy()
+ })
+
function tabByAppRef(appRef: string) {
return currentController.workspaceTabs.tabs.find(tab => tab.app?.appRef === appRef)
}
@@ -599,7 +675,7 @@ describe('App sandbox-ui embed always has an owning app tab', () => {
expect(screen.queryByTestId('sandbox-ui-mounted')).toBeNull()
expect(await screen.findByRole('button', { name: 'Open Alpha' })).toBeTruthy()
// A late title from Alpha must not relabel B.
- emitTitleChanged({ appRef: ALPHA!.appRef, title: 'Alpha Inbox' })
+ emitTitleChanged({ ...closedEventFor(1), title: 'Alpha Inbox' })
const betaAfter = currentController.workspaceTabs.tabs.find(tab => tab.id === betaTab.id)
expect(betaAfter?.title).toBe('Beta')
expect(betaAfter?.app?.appRef).toBe(BETA!.appRef)
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsx
index 907e966ca..14a34daaf 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx
+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx
@@ -44,11 +44,15 @@ function phasePill(phase: string | null): { label: string; tone: PhasePillTone }
}
}
+// `launchId` names one open request end to end: main tags every per-view event
+// (`closed`, `refreshError`, `titleChanged`) with the id of the open that
+// mounted that view. Relaunching the SAME app keeps the appRef, so only the id
+// tells a late event from the replaced view apart from the live one.
type LaunchState =
| { kind: 'idle' }
- | { kind: 'minting'; appRef: string }
- | { kind: 'mounted'; appRef: string }
- | { kind: 'error'; appRef: string; message: string }
+ | { kind: 'minting'; appRef: string; launchId: string }
+ | { kind: 'mounted'; appRef: string; launchId: string }
+ | { kind: 'error'; appRef: string; launchId: string; message: string }
function statusFromError(err: unknown): { status: number | null; message: string } {
const message = err instanceof Error ? err.message : String(err)
@@ -237,7 +241,9 @@ export function SandboxUiPage({
launchRef.current = next
setLaunchState(next)
}, [])
- const [refreshError, setRefreshError] = useState<{ appRef: string; message: string } | null>(null)
+ const [refreshError, setRefreshError] = useState<{ launchId: string; message: string } | null>(
+ null
+ )
const [appsPage, setAppsPage] = useState(0)
const [embedPreviewDataUrl, setEmbedPreviewDataUrl] = useState<string | null>(null)
const [localSearchOpen, setLocalSearchOpen] = useState(false)
@@ -282,13 +288,14 @@ export function SandboxUiPage({
// Re-render the picker if the main process tears the view down (e.g. on
// app quit, parent window close, or the embed's renderer crashing).
useEffect(() => {
- return window.clerum.sandboxUi.onClosed(({ appRef }) => {
+ return window.clerum.sandboxUi.onClosed(({ launchId }) => {
// A closed event can land after the renderer has already launched
- // another app (it was in flight when the switch happened). Reconciling it
- // would drop the owner of the NEW embed, which then stays painted over
- // every later surface. Only the launch it names may be released.
+ // another app, or relaunched the same one (it was in flight when the
+ // switch happened). Reconciling it would drop the owner of the NEW embed,
+ // which then stays painted over every later surface. Only the launch it
+ // names may be released.
const current = launchRef.current
- if (current.kind === 'idle' || current.appRef !== appRef) return
+ if (current.kind === 'idle' || current.launchId !== launchId) return
if (current.kind === 'mounted' || current.kind === 'minting') {
setLaunch({ kind: 'idle' })
}
@@ -302,7 +309,11 @@ export function SandboxUiPage({
// here — this is informational, not actionable beyond the user closing
// and re-opening.
useEffect(() => {
- return window.clerum.sandboxUi.onRefreshError(args => setRefreshError(args))
+ return window.clerum.sandboxUi.onRefreshError(({ launchId, message }) => {
+ const current = launchRef.current
+ if (current.kind === 'idle' || current.launchId !== launchId) return
+ setRefreshError({ launchId, message })
+ })
}, [])
useEffect(() => {
@@ -421,14 +432,20 @@ export function SandboxUiPage({
// slot, and the fallback would mount the WebContentsView full-window —
// covering the close button until the next ResizeObserver tick).
const seq = ++launchSeqRef.current
- setLaunch({ kind: 'minting', appRef: app.appRef })
- onEmbeddedAppOpening?.({
- appRef: app.appRef,
- label: app.label,
- icon: app.icon,
- defaultPath: app.defaultPath,
- ...(app.routePath ? { routePath: app.routePath } : {}),
- })
+ // Unique across page remounts, unlike `seq`: main echoes it on events
+ // that can outlive this component instance.
+ const launchId = crypto.randomUUID()
+ setLaunch({ kind: 'minting', appRef: app.appRef, launchId })
+ onEmbeddedAppOpening?.(
+ {
+ appRef: app.appRef,
+ label: app.label,
+ icon: app.icon,
+ defaultPath: app.defaultPath,
+ ...(app.routePath ? { routePath: app.routePath } : {}),
+ },
+ launchId
+ )
try {
const rect = await waitForEmbedSlotRect(embedSlotRef)
if (!rect) {
@@ -444,9 +461,10 @@ export function SandboxUiPage({
defaultPath: app.defaultPath,
...(app.routePath ? { routePath: app.routePath } : {}),
bounds,
+ launchId,
})
if (seq === launchSeqRef.current) {
- setLaunch({ kind: 'mounted', appRef: app.appRef })
+ setLaunch({ kind: 'mounted', appRef: app.appRef, launchId })
onEmbeddedAppMounted?.()
}
return { status: 'mounted' }
@@ -461,7 +479,7 @@ export function SandboxUiPage({
? 'This app is starting up — try again in a moment.'
: message
if (seq === launchSeqRef.current) {
- setLaunch({ kind: 'error', appRef: app.appRef, message: userFacing })
+ setLaunch({ kind: 'error', appRef: app.appRef, launchId, message: userFacing })
onEmbeddedAppOpenFailed?.()
}
return { status: 'failed', message: userFacing }
@@ -598,7 +616,7 @@ export function SandboxUiPage({
if (launch.kind === 'mounted' || launch.kind === 'minting') {
const showRefreshBanner =
- refreshError && launch.kind === 'mounted' && refreshError.appRef === launch.appRef
+ refreshError && launch.kind === 'mounted' && refreshError.launchId === launch.launchId
// The refresh/copy pair only exists while 'mounted'. The chat-drawer toggle
// moved to the app header (mini-spec 04a §C), so the leading slot carries no
// drawer control any more. In the 'minting' state both are absent, so
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.types.ts b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
index 0d3858f09..e89d2711b 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.types.ts
+++ b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
@@ -34,7 +34,7 @@ export type SandboxUiPageProps = {
// itself, so every embed is opened against a workspace tab that owns it. The
// app comes back through `shortcutApp` / `shortcutOpenRequestId`.
onLaunchApp: (app: ActiveSandboxUiApp) => void
- onEmbeddedAppOpening?: (app: ActiveSandboxUiApp) => void
+ onEmbeddedAppOpening?: (app: ActiveSandboxUiApp, launchId: string) => void
onEmbeddedAppMounted?: () => void
onEmbeddedAppBack?: () => void
onEmbeddedAppOpenFailed?: () => void
diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
index 5e1b0d304..94055d234 100644
--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
@@ -236,6 +236,7 @@ describe('SandboxUiPage', () => {
height: 300,
dpr: expect.any(Number),
},
+ launchId: expect.any(String),
})
})
expect(await screen.findByTestId('sandbox-ui-mounted')).toBeTruthy()
@@ -571,14 +572,20 @@ describe('SandboxUiPage', () => {
height: 300,
dpr: expect.any(Number),
},
+ launchId: expect.any(String),
})
})
- expect(onEmbeddedAppOpening).toHaveBeenCalledWith({
- appRef: 'sandbox-recipes/task-board',
- label: 'Agentic Task Board',
- defaultPath: '/',
- routePath: '/tasks/task-42',
- })
+ // The owner learns the same launch id main will echo on this view's events.
+ const { launchId } = sandboxUi.open.mock.calls[0]![0] as { launchId: string }
+ expect(onEmbeddedAppOpening).toHaveBeenCalledWith(
+ {
+ appRef: 'sandbox-recipes/task-board',
+ label: 'Agentic Task Board',
+ defaultPath: '/',
+ routePath: '/tasks/task-42',
+ },
+ launchId
+ )
await waitFor(() => {
expect(onShortcutOpenResult).toHaveBeenCalledWith(1, { status: 'mounted' })
})