Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): derive the App tests' main fake from the real producer (R1-M6)
Diego Zacarias59a72a621c23
diff --git a/desktop-app/src/__tests__/__fixtures__/sandboxUiMainModuleMocks.ts b/desktop-app/src/__tests__/__fixtures__/sandboxUiMainModuleMocks.tsnew file mode 100644index 000000000..7bbe4f554--- /dev/null+++ b/desktop-app/src/__tests__/__fixtures__/sandboxUiMainModuleMocks.ts@@ -0,0 +1,55 @@+import { vi } from 'vitest'+import { electronMocks } from './sandboxUiElectronFakes.js'++// Stand-ins for the modules a suite running the REAL sandbox-ui main process+// (`sandboxUiRealMain.ts`) does not stand up. `vi.mock` is hoisted per test+// file, so each suite still declares the mocks itself and takes the module+// from here:+// vi.mock('<src>/config.js', async () =>+// (await import('<fixtures>/sandboxUiMainModuleMocks')).configModule)+// This module must not import the AppService (or anything that imports one of+// the modules it stands for): a mock factory that does would wait on itself.++export const configModule = {+ getActiveEnvKey: () => 'test-env',+ getActiveLegacyEnvKeys: () => [],+ config: {+ rpcProxyBaseUrl: 'https://rpc.example',+ externalRestApiBaseUrl: 'http://rest',+ desktopProfileUiBaseUrl: 'https://profile.example.com',+ desktopProfileUiBaseUrlExplicit: false,+ enableDevLoginUi: false,+ requestTimeoutMs: 60000,+ appName: 'test',+ },+}++export const partitionGcModule = {+ touchSandboxUiPartition: electronMocks.touchSandboxUiPartition,+}++// The RPC token is issued by control-api through external-rest-api, a layer+// these suites do not stand up; the mint itself runs through the real+// RpcProxyClient.+export const rpcTokenManagerModule = {+ RpcTokenManager: class {+ getOrIssue = vi.fn(async () => ({ token: 'fake-rpc-token' }))+ clear = vi.fn()+ getMetadata = vi.fn(() => ({ expiresAtMs: null, scopes: [], hostRefs: [] }))+ },+}++export const authClientModule = {+ AuthClient: class {+ health = vi.fn().mockResolvedValue({ status: 'ok' })+ getMe = vi.fn()+ },+}++export const tokenStoreModule = {+ TokenStore: class {+ getSessionToken = vi.fn().mockResolvedValue(null)+ setSessionToken = vi.fn()+ clearSessionToken = vi.fn()+ },+}diff --git a/desktop-app/src/__tests__/__fixtures__/sandboxUiRealMain.ts b/desktop-app/src/__tests__/__fixtures__/sandboxUiRealMain.tsnew file mode 100644index 000000000..9c8268023--- /dev/null+++ b/desktop-app/src/__tests__/__fixtures__/sandboxUiRealMain.ts@@ -0,0 +1,151 @@+import { vi } from 'vitest'+import { AppService } from '../../appService.js'+import { registerIpcHandlers } from '../../ipc.js'+import { wireMainWindowRendererReadiness } from '../../mainWindowReadiness.js'+import { _resetPluginSdkRuntimeForTests, initPluginSdkRuntime } from '../../pluginSdkRuntime.js'+import { _resetPluginSurfacesForTests } from '../../pluginSurfaceRegistry.js'+import { unmountSandboxUiView } from '../../sandboxUiDriver.js'+import { _resetSandboxUiRefreshForTests } from '../../sandboxUiSessionRefresh.js'+import { FakeParentWindow, type FakeWebContents, electronMocks } from './sandboxUiElectronFakes.js'++// The REAL sandbox-ui main process — AppService lifecycle queue, sandbox-ui+// driver, session refresh and the `sandboxUi:*` IPC handlers of ipc.ts —+// standing on the Electron fakes. Only the Electron runtime, rpc-proxy's HTTP+// answers and the RPC-token issuer are fake, so every `released`, open outcome+// and location a suite sees is the one the app produces.+//+// A suite that uses it must mock, in its own file, `electron` with+// `sandboxUiElectronFakes` and config / sandboxUiPartitionGc / rpcTokenManager /+// authClient / tokenStore with `sandboxUiMainModuleMocks`, and stub the global+// `fetch` with `sandboxUiMintFetch`.++export type RealMainOptions = {+ /** Plugin SDK state directory; the suite owns it. */+ userDataDir: string+ /** rpc-proxy's answer to a session mint for `recipeNs/recipeName`. */+ mint(recipeName: string, recipeNs: string): Response | Promise<Response>+ /** Everything main sends to the window the embed lives in. */+ onSend(channel: string, payload: unknown): void+ /** Every document load the driver starts; unset, a load never commits. */+ onLoad?(webContents: FakeWebContents, url: string): void+}++export type RealMain = {+ readonly service: AppService+ readonly parent: FakeParentWindow+ readonly sender: { id: number }+ readonly mainWebContents: FakeMainWebContents+ /** True once the main process was reset; nothing it does reaches the suite any more. */+ readonly dead: boolean+ /** Calls the real IPC handler of `channel` as the trusted renderer would. */+ invoke(channel: string, payload: unknown): Promise<unknown>+ /** What a logout or a login over the live session does to the embed. */+ invalidateSession(): void+}++// rpc-proxy's mint contract: 204 + a Path-scoped Set-Cookie on success, any+// other status with a text body on failure.+export function mintOk(recipeName: string, recipeNs = 'sandbox-recipes'): Response {+ return new Response(null, {+ status: 204,+ headers: {+ 'set-cookie':+ `clerum_sandbox_ui_session=tok-${recipeName}; ` ++ `Path=/api/v1/sandbox-ui/${recipeNs}/${recipeName}/; HttpOnly`,+ },+ })+}++export class FakeMainWebContents {+ private readonly listeners = new Map<string, Set<(...args: unknown[]) => void>>()+ reload = vi.fn()++ on(event: string, handler: (...args: unknown[]) => void): this {+ if (!this.listeners.has(event)) this.listeners.set(event, new Set())+ this.listeners.get(event)!.add(handler)+ return this+ }++ emit(event: string, ...args: unknown[]): void {+ this.listeners.get(event)?.forEach(handler => handler(...args))+ }++ isDestroyed(): boolean {+ return false+ }+}++type LiveMain = RealMain & { dead: boolean; options: RealMainOptions }++let current: LiveMain | null = null++export const sandboxUiMintFetch = vi.fn(+ async (input: string | URL | Request): Promise<Response> => {+ const url = String(input instanceof Request ? input.url : input)+ const match = /\/api\/v1\/sandbox-ui\/([^/]+)\/([^/]+)\/session$/.exec(url)+ if (!match) throw new Error(`unexpected fetch ${url}`)+ if (!current) throw new Error('mint with no main process running')+ return current.options.mint(decodeURIComponent(match[2]!), decodeURIComponent(match[1]!))+ }+)++/** Tears the running main process down; await it before starting the next one. */+export async function resetRealMain(): Promise<void> {+ if (current) current.dead = true+ current = null+ electronMocks.onLoadURL = null+ await unmountSandboxUiView()+ _resetSandboxUiRefreshForTests()+ _resetPluginSurfacesForTests()+ _resetPluginSdkRuntimeForTests()+ electronMocks.views.length = 0+}++/** Starts a main process with one trusted window. The previous one must have been reset. */+export function startRealMain(options: RealMainOptions): RealMain {+ if (current) throw new Error('a main process is already running: await resetRealMain() first')+ const service = new AppService()+ ;(service as unknown as { sessionToken: string }).sessionToken = 'fake-session-token'+ const parent = new FakeParentWindow()+ const sender = { id: 1 }+ const mainWebContents = new FakeMainWebContents()+ const main: LiveMain = {+ service,+ parent,+ sender,+ mainWebContents,+ dead: false,+ options,+ invoke(channel, payload) {+ const handler = electronMocks.ipcHandlers.get(channel)+ if (!handler) return Promise.reject(new Error(`no IPC handler for ${channel}`))+ try {+ return handler({ sender, senderFrame: { url: 'file:///app/index.html' } }, payload)+ } catch (error) {+ return Promise.reject(error)+ }+ },+ invalidateSession() {+ ;(service as unknown as { invalidateSandboxUiSession(): void }).invalidateSandboxUiSession()+ },+ }+ initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir: options.userDataDir })+ electronMocks.ipcHandlers.clear()+ electronMocks.windowsBySender.clear()+ registerIpcHandlers(service)+ electronMocks.windowsBySender.set(sender, parent)+ parent.webContents.send.mockImplementation((channel: string, payload: unknown) => {+ if (!main.dead) options.onSend(channel, payload)+ })+ wireMainWindowRendererReadiness({+ webContents: mainWebContents as never,+ isCurrentWindow: () => true,+ markNotReady: () => {},+ sandboxUi: service,+ })+ electronMocks.onLoadURL = (webContents, url) => {+ if (!main.dead) options.onLoad?.(webContents, url)+ }+ current = main+ return main+}diff --git a/desktop-app/src/__tests__/embedOwnership.property.test.ts b/desktop-app/src/__tests__/embedOwnership.property.test.tsindex 988d42801..b352d4dc7 100644--- a/desktop-app/src/__tests__/embedOwnership.property.test.ts+++ b/desktop-app/src/__tests__/embedOwnership.property.test.ts@@ -26,22 +26,24 @@ import {selectWorkspaceTab,} from '../../ui/src/lib/workspaceTabs'import type { WorkspaceTabsState } from '../../ui/src/lib/workspaceTabs.types'-import { AppService } from '../appService.js'-import { wireMainWindowRendererReadiness } from '../mainWindowReadiness.js'-import { _resetPluginSdkRuntimeForTests, initPluginSdkRuntime } from '../pluginSdkRuntime.js'-import { _resetPluginSurfacesForTests } from '../pluginSurfaceRegistry.js'-import { getActiveSandboxUi, unmountSandboxUiView } from '../sandboxUiDriver.js'-import {- SANDBOX_UI_REFRESH_INTERVAL_MS,- _resetSandboxUiRefreshForTests,-} from '../sandboxUiSessionRefresh.js'+import type { AppService } from '../appService.js'+import { getActiveSandboxUi } from '../sandboxUiDriver.js'+import { SANDBOX_UI_REFRESH_INTERVAL_MS } from '../sandboxUiSessionRefresh.js'import type { SandboxUiReleasedEvent } from '../types.js'import {- FakeParentWindow,+ type FakeParentWindow,type FakeWebContents,type FakeWebContentsView,electronMocks,} from './__fixtures__/sandboxUiElectronFakes.js'+import {+ type FakeMainWebContents,+ type RealMain,+ mintOk,+ resetRealMain,+ sandboxUiMintFetch,+ startRealMain,+} from './__fixtures__/sandboxUiRealMain.js'// Ownership of the native embed, end to end: the REAL reducer and interpreter// in the renderer, the REAL `sandboxUi:open`/`sandboxUi:close` IPC handlers of@@ -62,49 +64,30 @@ vi.mock(async () => (await import('./__fixtures__/sandboxUiElectronFakes.js')).electronModule)-vi.mock('../config.js', () => ({- getActiveEnvKey: () => 'test-env',- getActiveLegacyEnvKeys: () => [],- config: {- rpcProxyBaseUrl: 'https://rpc.example',- externalRestApiBaseUrl: 'http://rest',- desktopProfileUiBaseUrl: 'https://profile.example.com',- desktopProfileUiBaseUrlExplicit: false,- enableDevLoginUi: false,- requestTimeoutMs: 60000,- appName: 'test',- },-}))--vi.mock('../sandboxUiPartitionGc.js', async () => ({- touchSandboxUiPartition: (await import('./__fixtures__/sandboxUiElectronFakes.js')).electronMocks- .touchSandboxUiPartition,-}))--// The RPC token is issued by control-api through external-rest-api, a layer this-// suite does not stand up; the mint itself runs through the real RpcProxyClient.-vi.mock('../rpcTokenManager.js', () => ({- RpcTokenManager: class {- getOrIssue = vi.fn(async () => ({ token: 'fake-rpc-token' }))- clear = vi.fn()- getMetadata = vi.fn(() => ({ expiresAtMs: null, scopes: [], hostRefs: [] }))- },-}))+vi.mock(+ '../config.js',+ async () => (await import('./__fixtures__/sandboxUiMainModuleMocks.js')).configModule+)-vi.mock('../authClient.js', () => ({- AuthClient: class {- health = vi.fn().mockResolvedValue({ status: 'ok' })- getMe = vi.fn()- },-}))+vi.mock(+ '../sandboxUiPartitionGc.js',+ async () => (await import('./__fixtures__/sandboxUiMainModuleMocks.js')).partitionGcModule+)-vi.mock('../tokenStore.js', () => ({- TokenStore: class {- getSessionToken = vi.fn().mockResolvedValue(null)- setSessionToken = vi.fn()- clearSessionToken = vi.fn()- },-}))+vi.mock(+ '../rpcTokenManager.js',+ async () => (await import('./__fixtures__/sandboxUiMainModuleMocks.js')).rpcTokenManagerModule+)++vi.mock(+ '../authClient.js',+ async () => (await import('./__fixtures__/sandboxUiMainModuleMocks.js')).authClientModule+)++vi.mock(+ '../tokenStore.js',+ async () => (await import('./__fixtures__/sandboxUiMainModuleMocks.js')).tokenStoreModule+)const RUNS = Number(process.env.EMBED_PROP_RUNS ?? 4000)const SEED = process.env.EMBED_PROP_SEED ? Number(process.env.EMBED_PROP_SEED) : undefined@@ -185,65 +168,8 @@ async function drainScheduler(// ─── The real main process behind a fake wire ──────────────────────────────-// rpc-proxy's mint contract: 204 + a Path-scoped Set-Cookie on success, any-// other status with a text body on failure.-function mintOk(recipeName: string): Response {- return new Response(null, {- status: 204,- headers: {- 'set-cookie':- `clerum_sandbox_ui_session=tok-${recipeName}; ` +- `Path=/api/v1/sandbox-ui/sandbox-recipes/${recipeName}/; HttpOnly`,- },- })-}--let currentWorld: World | null = nulllet userDataDir = ''-const fetchMock = vi.fn(async (input: string | URL | Request): Promise<Response> => {- const url = String(input instanceof Request ? input.url : input)- const match = /\/api\/v1\/sandbox-ui\/sandbox-recipes\/([^/]+)\/session$/.exec(url)- if (!match) throw new Error(`unexpected fetch ${url}`)- const recipeName = decodeURIComponent(match[1]!)- const world = currentWorld- if (!world) throw new Error('mint outside a world')- const response = world.failingRecipes.has(recipeName)- ? new Response('upstream unavailable', { status: 503 })- : mintOk(recipeName)- if (world.immediateMints) return response- return world.sink.schedule(Promise.resolve(response), `mint ${recipeName}`)-})--class FakeMainWebContents {- private readonly listeners = new Map<string, Set<(...args: unknown[]) => void>>()- reload = vi.fn()-- on(event: string, handler: (...args: unknown[]) => void): this {- if (!this.listeners.has(event)) this.listeners.set(event, new Set())- this.listeners.get(event)!.add(handler)- return this- }-- emit(event: string, ...args: unknown[]): void {- this.listeners.get(event)?.forEach(handler => handler(...args))- }-- isDestroyed(): boolean {- return false- }-}--async function resetMain(): Promise<void> {- if (currentWorld) currentWorld.dead = true- currentWorld = null- await unmountSandboxUiView()- _resetSandboxUiRefreshForTests()- _resetPluginSurfacesForTests()- _resetPluginSdkRuntimeForTests()- electronMocks.views.length = 0-}-type ToMain = {channel: 'sandboxUi:open' | 'sandboxUi:close'payload: unknown@@ -342,9 +268,9 @@ const IDEMPOTENT_EVENTS = new Set<EmbedEvent['type']>([*/class World {readonly sink: TaskSink- readonly parent = new FakeParentWindow()- readonly sender = { id: 1 }- readonly mainWebContents = new FakeMainWebContents()+ readonly main: RealMain+ readonly parent: FakeParentWindow+ readonly mainWebContents: FakeMainWebContentsreadonly service: AppServicereadonly failingRecipes = new Set<string>(['gamma'])immediateMints = false@@ -352,7 +278,6 @@ class World {crashNextLoad = false/** The session changes the moment the next view starts loading. */sessionChangeNextLoad = false- dead = falsetabs: WorkspaceTabsStatemachine: EmbedOwnershipMachinegeneration = 0@@ -410,8 +335,12 @@ class World {owner: LaunchId | null} | null = null- private constructor(options: WorldOptions) {+ private constructor(options: WorldOptions, main: RealMain) {this.sink = options.sink+ this.main = main+ this.parent = main.parent+ this.mainWebContents = main.mainWebContents+ this.service = main.servicethis.launchIds = [...(options.launchIds ?? [])]this.slotFailures = options.slotFailures ?? []this.batch = options.batch ?? false@@ -420,37 +349,31 @@ class World {tabs = openAppTab(tabs, { id: 'ws-tab-3', appRef: APPS.beta, title: 'Beta' })tabs = openAppTab(tabs, { id: 'ws-tab-4', appRef: APPS.gamma, title: 'Gamma' })this.tabs = selectWorkspaceTab(tabs, 'chat-tab-1')- const service = new AppService()- ;(service as unknown as { sessionToken: string }).sessionToken = 'fake-session-token'- this.service = servicethis.machine = this.createMachine()}static async create(options: WorldOptions): Promise<World> {- await resetMain()- const world = new World(options)- initPluginSdkRuntime({ service: world.service, getMainWindow: () => null, userDataDir })- electronMocks.ipcHandlers.clear()- electronMocks.windowsBySender.clear()- const { registerIpcHandlers } = await import('../ipc.js')- registerIpcHandlers(world.service)- electronMocks.windowsBySender.set(world.sender, world.parent)- world.parent.webContents.send.mockImplementation((channel: string, payload: unknown) => {- if (!world.dead) world.fromMain(channel, payload)+ await resetRealMain()+ // The callbacks only run once the world exists: nothing reaches main before+ // the first gesture.+ let world!: World+ const main = startRealMain({+ userDataDir,+ mint: recipeName => world.mint(recipeName),+ onSend: (channel, payload) => world.fromMain(channel, payload),+ onLoad: (webContents, url) => world.onLoad(webContents, url),})- wireMainWindowRendererReadiness({- webContents: world.mainWebContents as never,- isCurrentWindow: () => true,- markNotReady: () => {},- sandboxUi: world.service,- })- currentWorld = world- electronMocks.onLoadURL = (webContents, url) => currentWorld?.onLoad(webContents, url)+ world = new World(options, main)if (!options.lateMeasurer) world.registerMeasurer()world.machine.projected(world.activeAppTabId())return world}+ /** Main is gone (the world was reset); nothing may act on it any more. */+ get dead(): boolean {+ return this.main.dead+ }+// ── renderer ──private createMachine(): EmbedOwnershipMachine {@@ -751,8 +674,16 @@ class World {/** What a logout or a login over the live session does to the embed. */private invalidateSession(): void {- const service = this.service as unknown as { invalidateSandboxUiSession(): void }- service.invalidateSandboxUiSession()+ this.main.invalidateSession()+ }++ /** rpc-proxy's answer to a session mint, delivered when the scheduler says so. */+ mint(recipeName: string): Promise<Response> | Response {+ const response = this.failingRecipes.has(recipeName)+ ? new Response('upstream unavailable', { status: 503 })+ : mintOk(recipeName)+ if (this.immediateMints) return response+ return this.sink.schedule(Promise.resolve(response), `mint ${recipeName}`)}/** Schedules an accident; one with no view to hit yet tries again later, a few times. */@@ -791,16 +722,7 @@ class World {this.shownRoutes.set(message.launchId, new Set([routePath]))this.opensInMain += 1}- const handler = electronMocks.ipcHandlers.get(message.channel)!- let result: Promise<unknown>- try {- result = handler(- { sender: this.sender, senderFrame: { url: 'file:///app/index.html' } },- message.payload- )- } catch (error) {- result = Promise.reject(error)- }+ const result = this.main.invoke(message.channel, message.payload)const label = `reply ${message.channel} ${short(message.launchId)}`if (op === 'open') {void result.then(@@ -1259,15 +1181,14 @@ afterAll(async () => {beforeEach(() => {vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })- vi.stubGlobal('fetch', fetchMock)+ vi.stubGlobal('fetch', sandboxUiMintFetch)// The driver logs every injected failure; the properties judge them.vi.spyOn(console, 'warn').mockImplementation(() => {})vi.spyOn(console, 'error').mockImplementation(() => {})})afterEach(async () => {- await resetMain()- electronMocks.onLoadURL = null+ await resetRealMain()vi.restoreAllMocks()vi.unstubAllGlobals()vi.useRealTimers()diff --git a/desktop-app/ui/src/__tests__/App.activationSeam.test.tsx b/desktop-app/ui/src/__tests__/App.activationSeam.test.tsxindex 09cda3538..a40d6fd56 100644--- a/desktop-app/ui/src/__tests__/App.activationSeam.test.tsx+++ b/desktop-app/ui/src/__tests__/App.activationSeam.test.tsx@@ -22,6 +22,40 @@ import type { SandboxUiDeepLinkEnvelope } from '@/App.types'import { openGfsResourcePayload, resolvedFile } from '@/gfs/__fixtures__/gfsProducerFixtures'import { type SandboxUiMainFake, createSandboxUiMainFake } from './__fixtures__/sandboxUiMainFake'+// The sandbox-ui main fake runs the real main process; these are the+// layers under it that the suite does not stand up.+vi.mock(+ 'electron',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiElectronFakes')).electronModule+)+vi.mock(+ '../../../src/config',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).configModule+)+vi.mock(+ '../../../src/sandboxUiPartitionGc',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).partitionGcModule+)+vi.mock(+ '../../../src/rpcTokenManager',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks'))+ .rpcTokenManagerModule+)+vi.mock(+ '../../../src/authClient',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).authClientModule+)+vi.mock(+ '../../../src/tokenStore',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).tokenStoreModule+)+// Every gesture that activates an app tab must do it through App's single// activation seam, which commits the store and the launch together under// `flushSync`. A store write that activates an app tab from anywhere else (an@@ -369,6 +403,7 @@ describe('App activates app tabs only through its activation seam', () => {afterEach(async () => {cleanup()await new Promise(resolve => window.setTimeout(resolve, 0))+ await main.dispose()vi.restoreAllMocks()vi.unstubAllGlobals()delete (window as { clerum?: unknown }).clerum@@ -501,7 +536,7 @@ describe('App activates app tabs only through its activation seam', () => {await openFromSidebar(ALPHA, 1)// A title from the live embed renames its tab.- act(() => main.retitle('Alpha Inbox'))+ await act(() => main.retitle('Alpha Inbox'))// Leaving the app persists its route, and a plugin handoff opens a preview.main.navigate('/inbox')const payload = await openGfsResourcePayload(@@ -534,8 +569,9 @@ describe('App activates app tabs only through its activation seam', () => {async function renderWithRetitledLiveAlpha(gesture: () => void) {await renderApp()await openFromSidebar(ALPHA, 1)- act(() => {- main.retitle('Alpha Inbox')+ // The title is in, but App has not rendered it, when the gesture runs.+ await act(async () => {+ await main.retitle('Alpha Inbox')gesture()})await flushMacrotask()diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsxindex 43bb4bff6..3199825f7 100644--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx@@ -20,6 +20,40 @@ import type { SandboxUiDeepLinkEnvelope } from '@/App.types'import type { DesktopCommandId } from '../../../src/desktopCommands'import { type SandboxUiMainFake, createSandboxUiMainFake } from './__fixtures__/sandboxUiMainFake'+// The sandbox-ui main fake runs the real main process; these are the+// layers under it that the suite does not stand up.+vi.mock(+ 'electron',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiElectronFakes')).electronModule+)+vi.mock(+ '../../../src/config',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).configModule+)+vi.mock(+ '../../../src/sandboxUiPartitionGc',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).partitionGcModule+)+vi.mock(+ '../../../src/rpcTokenManager',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks'))+ .rpcTokenManagerModule+)+vi.mock(+ '../../../src/authClient',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).authClientModule+)+vi.mock(+ '../../../src/tokenStore',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).tokenStoreModule+)+// The universal tab store lives inside the controller; the mock reproduces that// contract — `navItem` is DERIVED from the store, the store is reactive, and nav// drives it through the real producers (T1). See App.chatDrawer.test for the@@ -577,7 +611,7 @@ describe('App deep-link orchestration', () => {act(() => appHeaderHarness.props?.onShellOverlayOpenChange?.(true))expect(sandboxUiPageHarness.props?.headerShellOverlayOpen).toBe(true)- act(() => main.crash())+ await act(() => main.crash())await waitFor(() => expect(embedState().failure?.kind).toBe('crashed'))expect(sandboxUiPageHarness.props?.headerShellOverlayOpen).toBe(false)@@ -801,8 +835,9 @@ describe('App deep-link orchestration', () => {})})- afterEach(() => {+ afterEach(async () => {vi.useRealTimers()+ await main.dispose()})// The deep link's launch reached main (`times` opens so far). Main mounts it@@ -1886,7 +1921,7 @@ describe('App deep-link orchestration', () => {render(<App />)await launchAppFromSidebar()- act(() => main.crash())+ await act(() => main.crash())await waitFor(() => expect(embedState().failure?.kind).toBe('crashed'))await selectTab(0)diff --git a/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx b/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsxindex 75c34fd0e..44c48e225 100644--- a/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx+++ b/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx@@ -26,6 +26,40 @@ import type { SandboxUiDeepLinkEnvelope } from '@/App.types'import { openGfsResourcePayload, resolvedFile } from '@/gfs/__fixtures__/gfsProducerFixtures'import { type SandboxUiMainFake, createSandboxUiMainFake } from './__fixtures__/sandboxUiMainFake'+// The sandbox-ui main fake runs the real main process; these are the+// layers under it that the suite does not stand up.+vi.mock(+ 'electron',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiElectronFakes')).electronModule+)+vi.mock(+ '../../../src/config',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).configModule+)+vi.mock(+ '../../../src/sandboxUiPartitionGc',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).partitionGcModule+)+vi.mock(+ '../../../src/rpcTokenManager',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks'))+ .rpcTokenManagerModule+)+vi.mock(+ '../../../src/authClient',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).authClientModule+)+vi.mock(+ '../../../src/tokenStore',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).tokenStoreModule+)+// Wiring of App to the embed ownership machine: which event each gesture// dispatches, in which commit, and that the real SandboxUiPage paints what the// machine holds. Who owns the embed under every interleaving is not decided@@ -388,6 +422,7 @@ describe('App wires gestures and main events to the embed ownership machine', ()afterEach(async () => {cleanup()await new Promise(resolve => window.setTimeout(resolve, 0))+ await main.dispose()expect(flushSyncErrors).toEqual([])vi.restoreAllMocks()vi.unstubAllGlobals()@@ -540,7 +575,7 @@ describe('App wires gestures and main events to the embed ownership machine', ()await renderApp()await openFromSidebar(ALPHA, 1)- act(() => main.crash())+ await act(() => main.crash())expect(await screen.findByText('The app closed unexpectedly.')).toBeTruthy()expect(sidebarHarness.props?.activeSandboxUiApp ?? null).toBeNull()@@ -556,13 +591,14 @@ describe('App wires gestures and main events to the embed ownership machine', ()it('shows a crash while the app is still opening with Reopen (DEC-10)', async () => {await renderApp()- main.holdNextOpen()+ const held = main.holdNextOpen()+ main.crashNextMount()act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(ALPHA!))await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))expect(screen.getByText('Loading app')).toBeTruthy()- act(() => main.crash())-+ // The view mounts and its renderer dies before the open settles.+ held().resolve()expect(await screen.findByText('The app closed unexpectedly.')).toBeTruthy()fireEvent.click(screen.getByRole('button', { name: 'Reopen' }))await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))@@ -572,7 +608,7 @@ describe('App wires gestures and main events to the embed ownership machine', ()it('relaunches a dead view when its tab is clicked again', async () => {await renderApp()await openFromSidebar(ALPHA, 1)- act(() => main.crash())+ await act(() => main.crash())await screen.findByText('The app closed unexpectedly.')fireEvent.click(screen.getByRole('button', { name: 'Alpha', pressed: true }))@@ -615,9 +651,7 @@ describe('App wires gestures and main events to the embed ownership machine', ()await openFromSidebar(ALPHA, 1)const first = main.openCall(0).launchId- act(() => main.refreshFailed('stale failure', crypto.randomUUID()))- expect(screen.queryByText(/Session refresh failed/)).toBeNull()- act(() => main.refreshFailed('mint failed'))+ await act(() => main.refreshFailed(new Error('mint failed')))expect(await screen.findByText('Session refresh failed: mint failed.')).toBeTruthy()fireEvent.click(screen.getByRole('button', { name: 'Retry' }))@@ -628,6 +662,23 @@ describe('App wires gestures and main events to the embed ownership machine', ()await waitFor(() => expect(screen.queryByText(/Session refresh failed/)).toBeNull())})+ it('ignores the session failure of a view it already replaced', async () => {+ await renderApp()+ await openFromSidebar(ALPHA, 1)+ const first = main.openCall(0).launchId++ // The replaced view's loop gives up before the close for it reaches main.+ fireEvent.click(screen.getByRole('button', { name: 'Refresh app content' }))+ await act(() => main.refreshFailed(new Error('stale failure')))+ await act(() => main.settle())++ expect(main.reported('sandboxUi:refreshError')).toEqual([+ expect.objectContaining({ launchId: first, message: 'stale failure' }),+ ])+ expect(screen.queryByText(/Session refresh failed/)).toBeNull()+ expect(main.live()?.launchId).toBe(main.openCall(1).launchId)+ })+it('goes back to apps on the app.backToApps command, keeping the tab', async () => {await renderApp()await openFromSidebar(ALPHA, 1)@@ -645,9 +696,19 @@ describe('App wires gestures and main events to the embed ownership machine', ()await renderApp()await openFromSidebar(ALPHA, 1)- act(() => main.retitle('Alpha Inbox'))+ await act(() => main.retitle('Alpha Inbox'))+ expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: true })).toBeTruthy()++ // The view a relaunch replaces retitles itself before its close reaches main.+ const first = main.openCall(0).launchId+ fireEvent.click(screen.getByRole('button', { name: 'Refresh app content' }))+ await act(() => main.retitle('Stale'))+ await act(() => main.settle())++ expect(main.reported('sandboxUi:titleChanged')).toContainEqual(+ expect.objectContaining({ launchId: first, title: 'Stale' })+ )expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: true })).toBeTruthy()- act(() => main.retitle('Stale', crypto.randomUUID()))expect(screen.queryByRole('button', { name: 'Stale' })).toBeNull()})@@ -727,7 +788,7 @@ describe('App wires gestures and main events to the embed ownership machine', ()await renderApp()await openFromSidebar(BETA, 1)// The app renames its own tab; that title must never name it to main.- act(() => main.retitle('Beta Inbox'))+ await act(() => main.retitle('Beta Inbox'))await openFromSidebar(ALPHA, 2)const alpha = main.openCall(1).launchIdconst betaTab = tabOf(BETA!.appRef)!@@ -737,7 +798,9 @@ describe('App wires gestures and main events to the embed ownership machine', ()await refreshCatalogOnFocus()main.navigate('/inbox')fireEvent.click(screen.getByRole('button', { name: 'Beta Inbox', pressed: false }))- await flushMacrotask()+ // Alpha retitles itself before the close the click sent reaches main.+ await act(() => main.retitle('Alpha Late'))+ await act(() => main.settle())expect(sandboxUi.close).toHaveBeenCalledWith({ launchId: alpha })expect(sandboxUi.open).toHaveBeenCalledTimes(2)@@ -745,8 +808,10 @@ describe('App wires gestures and main events to the embed ownership machine', ()expect(owner()).toBeUndefined()expect(screen.queryByTestId('sandbox-ui-mounted')).toBeNull()expect(await screen.findByRole('button', { name: 'Open Alpha' })).toBeTruthy()- // A late title from Alpha does not relabel Beta, and Alpha keeps its route.- act(() => main.retitle('Alpha Late', alpha))+ // Alpha's late title does not relabel Beta, and Alpha keeps its route.+ expect(main.reported('sandboxUi:titleChanged')).toContainEqual(+ expect.objectContaining({ launchId: alpha, title: 'Alpha Late' })+ )expect(controller.workspaceTabs.tabs.find(tab => tab.id === betaTab.id)?.title).toBe('Beta Inbox')diff --git a/desktop-app/ui/src/__tests__/__fixtures__/sandboxUiMainFake.ts b/desktop-app/ui/src/__tests__/__fixtures__/sandboxUiMainFake.tsindex b1374f5e7..8ef14810c 100644--- a/desktop-app/ui/src/__tests__/__fixtures__/sandboxUiMainFake.ts+++ b/desktop-app/ui/src/__tests__/__fixtures__/sandboxUiMainFake.ts@@ -1,17 +1,41 @@import { vi } from 'vitest'-import type { SandboxUiReleaseReason, SandboxUiReleasedEvent } from '../../../../src/types'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import path from 'node:path'+import {+ type FakeWebContents,+ electronMocks,+} from '../../../../src/__tests__/__fixtures__/sandboxUiElectronFakes'+import {+ type RealMain,+ mintOk,+ resetRealMain,+ sandboxUiMintFetch,+ startRealMain,+} from '../../../../src/__tests__/__fixtures__/sandboxUiRealMain'+import { getActiveSandboxUi, getActiveSandboxUiLocation } from '../../../../src/sandboxUiDriver'+import {+ SANDBOX_UI_COOKIE_TTL_MS,+ SANDBOX_UI_REFRESH_INTERVAL_MS,+ SANDBOX_UI_RETRY_GRACE_MS,+} from '../../../../src/sandboxUiSessionRefresh'+import type { SandboxUiReleasedEvent } from '../../../../src/types'/**- * The lifecycle half of main's sandbox-ui contract, reduced to what App's- * wiring tests need: one live view at a time, `open` resolves once it mounted,- * `close({ launchId })` only closes that launch's view, and every view that- * dies reports `released` once, with the route it stood for (the requested one- * until the test navigates it, none for a crash) before the call that killed it- * resolves.+ * The trusted renderer's `window.clerum.sandboxUi` lifecycle bridge, backed by+ * the REAL main process: AppService's lifecycle queue, the sandbox-ui driver,+ * the session refresh loop and the `sandboxUi:open` / `sandboxUi:close`+ * handlers of ipc.ts, on the Electron fakes. Nothing here decides what main+ * reports: every `released`, every open outcome and every location comes from+ * that code. The helpers only act on the world (rpc-proxy's answer to a mint,+ * the embed's renderer crashing, the user navigating the app, time passing).*- * The ownership properties themselves are checked against the real main process- * (`src/__tests__/embedOwnership.property.test.ts`); this only has to deliver- * the events, so App-level suites can run in jsdom.+ * The wire is two FIFO lanes, as IPC is: a call reaches main one macrotask+ * after the renderer sent it, and main's replies and events reach the renderer+ * in the order main produced them, each one macrotask after the previous.+ *+ * A suite that uses it must mock the main-process modules it stands on (see+ * `sandboxUiRealMain.ts`) and await `dispose()` after each test.*/export type SandboxUiOpenCall = {launchId: string@@ -20,10 +44,26 @@ export type SandboxUiOpenCall = {title?: stringdefaultPath?: stringroutePath?: string+ bounds: { x: number; y: number; width: number; height: number; dpr?: number }}type HeldOpen = { resolve: () => void; reject: (error: Error) => void }+type MintDecision = { kind: 'fail'; error: Error } | { kind: 'hold'; handle: HeldMint }++type HeldMint = {+ decided: 'ok' | Error | null+ answer: ((response: Response) => void) | null+ fail: ((error: Error) => void) | null+ recipe: { name: string; ns: string } | null+}++// Captured before any test fakes timers: the wire runs on real macrotasks, so a+// suite that fakes timers for its own clock does not freeze IPC.+const realSetImmediate = globalThis.setImmediate.bind(globalThis)+const macrotask = () => new Promise<void>(resolve => realSetImmediate(resolve))+const realDateNow = Date.now.bind(Date)+export function createSandboxUiMainFake() {const releasedListeners = new Set<(event: SandboxUiReleasedEvent) => void>()const titleListeners = new Set<@@ -32,46 +72,146 @@ export function createSandboxUiMainFake() {const refreshErrorListeners = new Set<(event: { appRef: string; launchId: string; message: string }) => void>()- let live: { launchId: string; appRef: string; routePath?: string } | null = null- const held: HeldOpen[] = []- let holdNext = 0- const failures: Error[] = []-- function release(reason: SandboxUiReleaseReason, crashed = false): void {- if (!live) return- const view = live- live = null- const event: SandboxUiReleasedEvent = {- launchId: view.launchId,- reason,- location: crashed ? null : view.routePath ? { routePath: view.routePath } : {},- }- for (const listener of [...releasedListeners]) listener(event)+ const userDataDir = mkdtempSync(path.join(tmpdir(), 'clerum-sandbox-ui-main-'))+ const openMints: MintDecision[] = []+ let failNextMount: Error | null = null+ let crashNextMount = false+ let refreshFailure: Error | null = null+ let toMainLane: Promise<void> = Promise.resolve()+ let toRendererLane: Promise<void> = Promise.resolve()+ // A listener that throws must fail the test, not stall the lane behind it.+ const deliveryErrors: unknown[] = []+ let inFlight = 0+ let held = 0+ let clockOffsetMs = 0+ // The refresh loop reads its clock at mount; shifting it is how the fake+ // lets time pass for main without faking the suite's timers.+ vi.spyOn(Date, 'now').mockImplementation(() => realDateNow() + clockOffsetMs)++ function toRenderer(deliver: () => void): void {+ inFlight += 1+ toRendererLane = toRendererLane+ .then(macrotask)+ .then(deliver)+ .catch(error => {+ deliveryErrors.push(error)+ })+ .finally(() => {+ inFlight -= 1+ })+ }++ const sent: Array<{ channel: string; payload: unknown }> = []+ function reported(channel: string): unknown[] {+ return sent.filter(message => message.channel === channel).map(message => message.payload)}- const open = vi.fn(async (request: SandboxUiOpenCall) => {- const appRef = `${request.recipeNs}/${request.recipeName}`- if (live) release('replaced')- const failure = failures.shift()- if (failure) throw failure- live = {- launchId: request.launchId,- appRef,- ...(request.routePath ? { routePath: request.routePath } : {}),+ function fromMain(channel: string, payload: unknown): void {+ sent.push({ channel, payload })+ toRenderer(() => {+ switch (channel) {+ case 'sandboxUi:released':+ for (const listener of [...releasedListeners]) {+ listener(payload as SandboxUiReleasedEvent)+ }+ return+ case 'sandboxUi:titleChanged':+ for (const listener of [...titleListeners]) {+ listener(payload as { appRef: string; launchId: string; title: string })+ }+ return+ case 'sandboxUi:refreshError':+ for (const listener of [...refreshErrorListeners]) {+ listener(payload as { appRef: string; launchId: string; message: string })+ }+ }+ })+ }++ function mint(recipeName: string, recipeNs: string): Response | Promise<Response> {+ if (refreshFailure) return Promise.reject(refreshFailure)+ const decision = openMints.shift()+ if (!decision) return mintOk(recipeName, recipeNs)+ if (decision.kind === 'fail') return Promise.reject(decision.error)+ const handle = decision.handle+ handle.recipe = { name: recipeName, ns: recipeNs }+ if (handle.decided === 'ok') return mintOk(recipeName, recipeNs)+ if (handle.decided) return Promise.reject(handle.decided)+ held += 1+ return new Promise<Response>((resolve, reject) => {+ handle.answer = response => {+ held -= 1+ resolve(response)+ }+ handle.fail = error => {+ held -= 1+ reject(error)+ }+ })+ }++ // The document a view asked for commits and loads a task later, as a real+ // page does; until then the view stands for the route it was asked to show.+ function onLoad(webContents: FakeWebContents): void {+ if (crashNextMount) {+ crashNextMount = false+ webContents.emit('render-process-gone', {}, { reason: 'crashed', exitCode: 139 })+ return}- if (holdNext > 0) {- holdNext -= 1- await new Promise<void>((resolve, reject) => held.push({ resolve, reject }))+ inFlight += 1+ void macrotask()+ .then(() => {+ if (webContents.destroyed || main.dead) return+ webContents.commitLoad()+ })+ .finally(() => {+ inFlight -= 1+ })+ }++ const main: RealMain = startRealMain({ userDataDir, mint, onSend: fromMain, onLoad })+ vi.stubGlobal('fetch', sandboxUiMintFetch)+ const attach = main.parent.contentView.addChildView.getMockImplementation() as (+ view: unknown+ ) => void+ main.parent.contentView.addChildView.mockImplementation((view: unknown) => {+ if (failNextMount) {+ const error = failNextMount+ failNextMount = null+ throw error}+ attach(view)})- // Main's events reach the renderer in a later task than the call that- // caused them.- const close = vi.fn(async (request?: { launchId: string }) => {- await new Promise(resolve => setTimeout(resolve, 0))- if (!live || (request && request.launchId !== live.launchId)) return- release('closed')- })+ function send(channel: string, payload: unknown): Promise<unknown> {+ return new Promise<unknown>((resolve, reject) => {+ inFlight += 1+ toMainLane = toMainLane.then(macrotask).then(() => {+ const result = main.invoke(channel, payload)+ result.then(+ value => toRenderer(() => resolve(value)),+ error => toRenderer(() => reject(error))+ )+ void result+ .catch(() => {})+ .finally(() => {+ inFlight -= 1+ })+ })+ })+ }++ const open = vi.fn((request: SandboxUiOpenCall) => send('sandboxUi:open', request))+ const close = vi.fn((request: { launchId: string }) => send('sandboxUi:close', request))++ function liveView() {+ const active = getActiveSandboxUi()+ if (!active) return null+ const view = electronMocks.views.find(+ candidate => candidate.webContents.id === active.webContentsId+ )+ return view && !view.webContents.destroyed ? { active, view } : null+ }return {bridge: {@@ -100,41 +240,146 @@ export function createSandboxUiMainFake() {if (!call) throw new Error(`no open call #${index}`)return call[0]},- live: () => live,- /** The next open stays in flight until the returned handle settles it. */+ /** The view main has mounted right now, and the route it stands for. */+ live(): { launchId: string; appRef: string; routePath?: string } | null {+ const active = getActiveSandboxUi()+ if (!active) return null+ const routePath = getActiveSandboxUiLocation()?.path+ return {+ launchId: active.launchId,+ appRef: active.appRef,+ ...(routePath ? { routePath } : {}),+ }+ },+ /**+ * rpc-proxy holds the session mint of the next open that reaches main until+ * the returned handle settles it: resolved, the open mounts; rejected, the+ * mint fails with that error.+ */holdNextOpen(): () => HeldOpen {- holdNext += 1- const index = held.length- return () => {- const handle = held[index]- if (!handle) throw new Error('the held open has not been sent yet')- return handle+ const handle: HeldMint = { decided: null, answer: null, fail: null, recipe: null }+ openMints.push({ kind: 'hold', handle })+ const settle: HeldOpen = {+ resolve: () => {+ if (handle.answer && handle.recipe) {+ handle.answer(mintOk(handle.recipe.name, handle.recipe.ns))+ } else handle.decided = 'ok'+ },+ reject: error => {+ if (handle.fail) handle.fail(error)+ else handle.decided = error+ },}+ return () => settle},+ /** The session mint of the next open that reaches main fails with `error`. */failNextOpen(error: Error): void {- failures.push(error)+ openMints.push({ kind: 'fail', error })},- /** The user navigated the live view. */+ /**+ * The next open mints its session and mounts its view, then attaching the+ * view to the window throws `error`.+ */+ failNextOpenAfterMount(error: Error): void {+ failNextMount = error+ },+ /**+ * The next view's renderer dies as its document starts loading, inside the+ * mount: main reports the release before the open settles, as the+ * ownership property suite drives it.+ */+ crashNextMount(): void {+ crashNextMount = true+ },+ /** The user navigates the live app to `routePath` inside its document. */navigate(routePath: string): void {- if (live) live = { ...live, routePath }+ const live = liveView()+ if (!live) throw new Error('no live view to navigate')+ const { active, view } = live+ if (!view.webContents.currentUrl) {+ throw new Error('the live view has not loaded its document yet: settle() first')+ }+ const base = new URL(view.webContents.currentUrl)+ const prefix = `/api/v1/sandbox-ui/${active.appRef}/view`+ view.webContents.navigateInPage(`${base.origin}${prefix}${routePath}`)},- crash(): void {- release('crashed', true)+ /**+ * The live view's renderer process dies. Resolves once what main reported+ * about it so far has reached the renderer.+ */+ crash(): Promise<void> {+ const live = liveView()+ if (!live) throw new Error('no live view to crash')+ live.view.webContents.emit('render-process-gone', {}, { reason: 'crashed', exitCode: 139 })+ return toRendererLane},+ /** The user signs out or signs in over the live session. */endSession(): void {- release('session')+ main.invalidateSession()+ },+ /**+ * The live app changes its document title. Resolves once main's report of+ * it has reached the renderer.+ */+ retitle(title: string): Promise<void> {+ const live = liveView()+ if (!live) throw new Error('no live view to retitle')+ live.view.webContents.emit('page-title-updated', {}, title)+ return toRendererLane},- retitle(title: string, launchId = live?.launchId): void {- if (!launchId) return- for (const listener of [...titleListeners]) {- listener({ appRef: live?.appRef ?? '', launchId, title })+ /**+ * Time passes until the live view's session is due for refresh, and+ * rpc-proxy refuses every refresh with `error` until main gives up on it+ * and reports it. A failing mint settles in microtasks, so all of it+ * happens before anything already on the wire reaches main: a close the+ * renderer just sent still finds this view live.+ */+ async refreshFailed(error: Error): Promise<void> {+ const live = liveView()+ if (!live) throw new Error('no live view whose session could fail to refresh')+ const reportsBefore = reported('sandboxUi:refreshError').length+ refreshFailure = error+ try {+ // First when the refresh is due, then at the end of the retry window+ // the failure opened (the cookie's expiry plus the grace period): that+ // retry is the last one the loop makes.+ const lastRetryAt = SANDBOX_UI_COOKIE_TTL_MS + SANDBOX_UI_RETRY_GRACE_MS+ for (const step of [+ SANDBOX_UI_REFRESH_INTERVAL_MS,+ lastRetryAt - SANDBOX_UI_REFRESH_INTERVAL_MS,+ ]) {+ clockOffsetMs += step+ main.parent.emit('focus')+ for (let i = 0; i < 100; i++) await Promise.resolve()+ }+ } finally {+ refreshFailure = null+ }+ if (reported('sandboxUi:refreshError').length === reportsBefore) {+ throw new Error('main did not report the refresh failure')}+ return toRendererLane},- refreshFailed(message: string, launchId = live?.launchId): void {- if (!launchId) return- for (const listener of [...refreshErrorListeners]) {- listener({ appRef: live?.appRef ?? '', launchId, message })+ /** What main has sent the renderer so far on `channel`, oldest first. */+ reported,+ /**+ * Waits until main and both lanes are idle: nothing in flight but the opens+ * whose mint is held.+ */+ async settle(): Promise<void> {+ for (let round = 0; round < 200; round++) {+ await macrotask()+ if (deliveryErrors.length > 0) throw deliveryErrors[0]+ if (inFlight === held) {+ await macrotask()+ if (inFlight === held) return+ }}+ throw new Error('main never went idle')+ },+ async dispose(): Promise<void> {+ await resetRealMain()+ rmSync(userDataDir, { recursive: true, force: true })},}}diff --git a/desktop-app/ui/src/__tests__/sandboxUiMainFake.contract.test.ts b/desktop-app/ui/src/__tests__/sandboxUiMainFake.contract.test.tsnew file mode 100644index 000000000..4e840897b--- /dev/null+++ b/desktop-app/ui/src/__tests__/sandboxUiMainFake.contract.test.ts@@ -0,0 +1,204 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { type SandboxUiMainFake, createSandboxUiMainFake } from './__fixtures__/sandboxUiMainFake'++vi.mock(+ 'electron',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiElectronFakes')).electronModule+)+vi.mock(+ '../../../src/config',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).configModule+)+vi.mock(+ '../../../src/sandboxUiPartitionGc',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).partitionGcModule+)+vi.mock(+ '../../../src/rpcTokenManager',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks'))+ .rpcTokenManagerModule+)+vi.mock(+ '../../../src/authClient',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).authClientModule+)+vi.mock(+ '../../../src/tokenStore',+ async () =>+ (await import('../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).tokenStoreModule+)++// What the App suites' sandbox-ui bridge shows the renderer, in the order the+// renderer sees it. The bridge is the real main process; these pin the parts+// of its contract the App suites lean on, so a bridge that drifted from main+// (events ahead of the replies main sent first, an open that fails after+// mounting without releasing its view, a close that names no launch) fails+// here instead of quietly passing App tests.++const A = '00000000-0000-4000-8000-00000000000a'+const B = '00000000-0000-4000-8000-00000000000b'+const BOUNDS = { x: 0, y: 40, width: 800, height: 600 }++function openRequest(launchId: string, recipeName = 'alpha') {+ return { launchId, recipeNs: 'sandbox-recipes', recipeName, bounds: BOUNDS }+}++describe('the App suites’ sandbox-ui bridge delivers what main produces, in order', () => {+ let main: SandboxUiMainFake+ /** Everything the renderer observed, in arrival order. */+ let seen: string[]++ beforeEach(() => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.spyOn(console, 'error').mockImplementation(() => {})+ main = createSandboxUiMainFake()+ seen = []+ main.bridge.onReleased(event => {+ seen.push(`released ${event.launchId} ${event.reason} ${JSON.stringify(event.location)}`)+ })+ })++ afterEach(async () => {+ await main.dispose()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ })++ function open(launchId: string, recipeName?: string): Promise<void> {+ return main.bridge.open(openRequest(launchId, recipeName)).then(+ () => {+ seen.push(`open ${launchId} ok`)+ },+ (error: Error) => {+ seen.push(`open ${launchId} failed: ${error.message}`)+ }+ )+ }++ function close(launchId: string): Promise<void> {+ return main.bridge.close({ launchId }).then(+ () => {+ seen.push(`close ${launchId} ok`)+ },+ (error: Error) => {+ seen.push(`close ${launchId} failed: ${error.message}`)+ }+ )+ }++ it('handles a close and an open sent in one tick in the order they were sent', async () => {+ await open(A)+ await main.settle()+ seen = []++ void close(A)+ void open(B, 'beta')+ await main.settle()++ expect(seen).toEqual(['released ' + A + ' closed {}', `close ${A} ok`, `open ${B} ok`])+ expect(main.live()?.launchId).toBe(B)+ })++ it('reports the view an open replaces before that open settles', async () => {+ await open(A)+ await main.settle()+ seen = []++ await open(B, 'beta')+ await main.settle()++ expect(seen).toEqual([`released ${A} replaced {}`, `open ${B} ok`])+ })++ it('rejects an open whose mint fails without reporting a view for it', async () => {+ await open(A)+ await main.settle()+ seen = []+ main.failNextOpen(new Error('upstream unavailable'))++ await open(B, 'beta')+ await main.settle()++ expect(seen).toEqual([`released ${A} replaced {}`, `open ${B} failed: upstream unavailable`])+ expect(main.live()).toBeNull()+ })++ it('reports the release of a view that mounted before the open that mounted it rejects', async () => {+ main.failNextOpenAfterMount(new Error('attach failed'))++ await open(A)+ await main.settle()++ expect(seen).toEqual([`released ${A} closed {}`, `open ${A} failed: attach failed`])+ expect(main.live()).toBeNull()+ })++ it('reports a view whose renderer dies inside its mount as crashed, before the open rejects', async () => {+ main.crashNextMount()++ await open(A)+ await main.settle()++ expect(seen).toEqual([+ `released ${A} crashed null`,+ `open ${A} failed: The app view closed before it finished opening`,+ ])+ })++ it('refuses a close that names no launch and leaves the live view alone', async () => {+ await open(A)+ await main.settle()+ seen = []++ await main.bridge.close({} as { launchId: string }).then(+ () => seen.push('close ok'),+ (error: Error) => seen.push(`close failed: ${error.message}`)+ )+ await main.settle()++ expect(seen).toEqual(['close failed: launchId must be a UUID'])+ expect(main.live()?.launchId).toBe(A)+ })++ it('ignores a close for a launch that no longer owns the view', async () => {+ await open(A)+ await open(B, 'beta')+ await main.settle()+ seen = []++ await close(A)+ await main.settle()++ expect(seen).toEqual([`close ${A} ok`])+ expect(main.live()?.launchId).toBe(B)+ })++ it('reports the route the user navigated to when the view is closed', async () => {+ await open(A)+ await main.settle()+ main.navigate('/inbox')+ seen = []++ await close(A)+ await main.settle()++ expect(seen).toEqual([`released ${A} closed {"routePath":"/inbox"}`, `close ${A} ok`])+ })++ it('releases the live view when the session changes', async () => {+ await open(A)+ await main.settle()+ seen = []++ main.endSession()+ await main.settle()++ expect(seen).toEqual([`released ${A} session {}`])+ expect(main.live()).toBeNull()+ })+})diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsxindex a0814ef8d..4bea03413 100644--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx@@ -3,13 +3,53 @@ import React from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import type { EmbedOwnershipMachine } from '@lib/embedOwnershipMachine.types'-import { createSandboxUiMainFake } from '../../__tests__/__fixtures__/sandboxUiMainFake'+import {+ type SandboxUiMainFake,+ createSandboxUiMainFake,+} from '../../__tests__/__fixtures__/sandboxUiMainFake'import { SandboxUiPage as SandboxUiPageBase } from '../SandboxUiPage'import {LaunchingSandboxUiPage as SandboxUiPage,createPageEmbed,} from './__fixtures__/launchingSandboxUiPage'+// The sandbox-ui main fake runs the real main process; these are the+// layers under it that the suite does not stand up.+vi.mock(+ 'electron',+ async () =>+ (await import('../../../../src/__tests__/__fixtures__/sandboxUiElectronFakes')).electronModule+)+vi.mock(+ '../../../../src/config',+ async () =>+ (await import('../../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks')).configModule+)+vi.mock(+ '../../../../src/sandboxUiPartitionGc',+ async () =>+ (await import('../../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks'))+ .partitionGcModule+)+vi.mock(+ '../../../../src/rpcTokenManager',+ async () =>+ (await import('../../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks'))+ .rpcTokenManagerModule+)+vi.mock(+ '../../../../src/authClient',+ async () =>+ (await import('../../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks'))+ .authClientModule+)+vi.mock(+ '../../../../src/tokenStore',+ async () =>+ (await import('../../../../src/__tests__/__fixtures__/sandboxUiMainModuleMocks'))+ .tokenStoreModule+)+const sandboxUi = {listApps: vi.fn(),open: vi.fn(),@@ -37,6 +77,7 @@ function installClerumApi(): void {}describe('SandboxUiPage', () => {+ let mainFake: SandboxUiMainFake | null = nullbeforeEach(() => {vi.clearAllMocks()sandboxUi.setBounds.mockResolvedValue(undefined)@@ -77,6 +118,8 @@ describe('SandboxUiPage', () => {afterEach(async () => {cleanup()await new Promise(resolve => window.setTimeout(resolve, 0))+ await mainFake?.dispose()+ mainFake = nullvi.restoreAllMocks()vi.unstubAllGlobals()delete (window as { clerum?: unknown }).clerum@@ -1073,6 +1116,7 @@ describe('SandboxUiPage', () => {// events are needed here; they come from the shared fake, wired the way App// wires them.const main = createSandboxUiMainFake()+ mainFake = mainsandboxUi.open.mockImplementation(main.bridge.open)sandboxUi.close.mockImplementation(main.bridge.close)const embed = createPageEmbed()