Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(desktop-app): interpret embed ownership effects and check them against the real main process
Diego Zacarias467d912a34d4
diff --git a/desktop-app/src/__tests__/__fixtures__/sandboxUiElectronFakes.ts b/desktop-app/src/__tests__/__fixtures__/sandboxUiElectronFakes.tsnew file mode 100644index 000000000..4e2e579d7--- /dev/null+++ b/desktop-app/src/__tests__/__fixtures__/sandboxUiElectronFakes.ts@@ -0,0 +1,273 @@+import { vi } from 'vitest'+import { tmpdir } from 'node:os'++// Electron runtime fakes for suites that drive the REAL AppService, sandbox-ui+// driver and IPC handlers. Consumed through+// vi.mock('electron', async () =>+// (await import('./__fixtures__/sandboxUiElectronFakes')).electronModule)+// and imported directly by the suite for the handles below; both resolve to+// this one module instance, so the suite and the code under test share state.+// This module must never import `electron` itself.++type Listener = (...args: unknown[]) => void++let nextWebContentsId = 1+const views: FakeWebContentsView[] = []++export 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<Listener>>()+ // 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.pendingUrl = url+ electronMocks.onLoadURL?.(this, 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()+ // 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()+ reloadIgnoringCache = vi.fn()++ on(event: string, handler: Listener): this {+ if (!this.listeners.has(event)) this.listeners.set(event, new Set())+ this.listeners.get(event)!.add(handler)+ return this+ }++ removeListener(event: string, handler: Listener): this {+ this.listeners.get(event)?.delete(handler)+ return this+ }++ emit(event: string, ...args: unknown[]): void {+ this.listeners.get(event)?.forEach(handler => handler(...args))+ }++ getURL(): string {+ this.assertAlive()+ return this.currentUrl+ }++ isDestroyed(): boolean {+ return this.destroyed+ }++ close(): void {+ this.destroyed = true+ }++ private assertAlive(): void {+ if (this.destroyed) throw new Error('Object has been destroyed')+ }+}++export class FakeWebContentsView {+ webContents = new FakeWebContents()+ setBounds = vi.fn()+ setVisible = vi.fn()++ constructor() {+ views.push(this)+ }+}++const sessionObject = {+ cookies: {+ set: vi.fn(async (_details?: { value: string }): Promise<void> => undefined),+ },+ setPermissionRequestHandler: vi.fn(),+ setPermissionCheckHandler: vi.fn(),+ removeAllListeners: vi.fn(),+ on: vi.fn(),+ clearCache: vi.fn(async () => undefined),+}++export const electronMocks = {+ FakeWebContentsView,+ fromPartition: vi.fn(() => sessionObject),+ getDisplayMatching: vi.fn(() => ({ scaleFactor: 1 })),+ touchSandboxUiPartition: vi.fn(async () => undefined),+ sessionObject,+ views,+ ipcHandlers: new Map<string, (event: unknown, payload?: unknown) => Promise<unknown>>(),+ windowsBySender: new Map<unknown, unknown>(),+ /**+ * Observes every document load the driver starts, so a suite can decide when+ * that load commits. Unset, a load never commits on its own.+ */+ onLoadURL: null as ((webContents: FakeWebContents, url: string) => void) | null,+}++export const electronModule = {+ WebContentsView: FakeWebContentsView,+ 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+ }+ },+ app: { getPath: vi.fn(() => tmpdir()) },+ safeStorage: {+ isEncryptionAvailable: vi.fn(() => false),+ encryptString: vi.fn(),+ decryptString: vi.fn(),+ },+ screen: { getDisplayMatching: electronMocks.getDisplayMatching },+ session: { fromPartition: electronMocks.fromPartition },+ shell: { openExternal: vi.fn() },+}++// Electron throws from the native methods of a destroyed window instead of+// ignoring the call; the contentView keeps its real child list.+export class FakeParentWindow {+ destroyed = false+ 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+ }++ isVisible(): boolean {+ return true+ }++ isMinimized(): boolean {+ return false+ }++ getBounds(): { x: number; y: number; width: number; height: number } {+ return { x: 0, y: 0, width: 800, height: 600 }+ }++ on(event: string, handler: Listener): this {+ if (!this.listeners.has(event)) this.listeners.set(event, new Set())+ this.listeners.get(event)!.add(handler)+ return this+ }++ once(event: string, handler: Listener): this {+ 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+ }++ emit(event: string): void {+ this.listeners.get(event)?.forEach(handler => handler())+ }+}diff --git a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.tsindex 5f26f0860..a9d8066cb 100644--- a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts+++ b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts@@ -15,6 +15,7 @@ import {SANDBOX_UI_REFRESH_INTERVAL_MS,_resetSandboxUiRefreshForTests,} from '../sandboxUiSessionRefresh.js'+import { FakeParentWindow, electronMocks } from './__fixtures__/sandboxUiElectronFakes.js'// The open/close lifecycle is exercised end to end through the REAL AppService,// the REAL sandbox-ui driver, the REAL session-refresh loop, the REAL plugin@@ -22,183 +23,10 @@ import {// (views, sessions, windows) and the RPC-token issuer are faked; mint outcomes// come from rpc-proxy HTTP responses fed to the real client through `fetch`.-const electronMocks = vi.hoisted(() => {- let nextWebContentsId = 1- const views: FakeWebContentsView[] = []-- 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>>()- // 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.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()- // 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()- reloadIgnoringCache = 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- }-- removeListener(event: string, handler: (...args: unknown[]) => void): this {- this.listeners.get(event)?.delete(handler)- return this- }-- emit(event: string, ...args: unknown[]): void {- this.listeners.get(event)?.forEach(handler => handler(...args))- }-- getURL(): string {- this.assertAlive()- return this.currentUrl- }-- isDestroyed(): boolean {- return this.destroyed- }-- close(): void {- this.destroyed = true- }-- private assertAlive(): void {- if (this.destroyed) throw new Error('Object has been destroyed')- }- }-- class FakeWebContentsView {- webContents = new FakeWebContents()- setBounds = vi.fn()- setVisible = vi.fn()-- constructor() {- views.push(this)- }- }-- const sessionObject = {- cookies: {- set: vi.fn(async (_details?: { value: string }): Promise<void> => undefined),- },- setPermissionRequestHandler: vi.fn(),- setPermissionCheckHandler: vi.fn(),- removeAllListeners: vi.fn(),- on: vi.fn(),- clearCache: vi.fn(async () => undefined),- }-- return {- FakeWebContentsView,- fromPartition: vi.fn(() => sessionObject),- getDisplayMatching: vi.fn(() => ({ scaleFactor: 1 })),- 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: () => [],- 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- }- },- app: { getPath: vi.fn(() => tmpdir()) },- safeStorage: {- isEncryptionAvailable: vi.fn(() => false),- encryptString: vi.fn(),- decryptString: vi.fn(),- },- screen: { getDisplayMatching: electronMocks.getDisplayMatching },- session: { fromPartition: electronMocks.fromPartition },- shell: { openExternal: vi.fn() },-}))+vi.mock(+ 'electron',+ async () => (await import('./__fixtures__/sandboxUiElectronFakes.js')).electronModule+)vi.mock('../config.js', () => ({getActiveEnvKey: () => 'test-env',@@ -214,8 +42,9 @@ vi.mock('../config.js', () => ({},}))-vi.mock('../sandboxUiPartitionGc.js', () => ({- touchSandboxUiPartition: electronMocks.touchSandboxUiPartition,+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@@ -246,85 +75,6 @@ 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- 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- }-- isVisible(): boolean {- return true- }-- isMinimized(): boolean {- return false- }-- getBounds(): { x: number; y: number; width: number; height: number } {- return { x: 0, y: 0, width: 800, height: 600 }- }-- on(event: string, handler: Listener): this {- if (!this.listeners.has(event)) this.listeners.set(event, new Set())- this.listeners.get(event)!.add(handler)- return this- }-- once(event: string, handler: Listener): this {- 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- }-- emit(event: string): void {- this.listeners.get(event)?.forEach(handler => handler())- }-}-// 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 {diff --git a/desktop-app/src/__tests__/embedOwnership.property.test.ts b/desktop-app/src/__tests__/embedOwnership.property.test.tsnew file mode 100644index 000000000..9b265089d--- /dev/null+++ b/desktop-app/src/__tests__/embedOwnership.property.test.ts@@ -0,0 +1,1804 @@+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import fc from 'fast-check'+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { reduceEmbedOwnership } from '../../ui/src/lib/embedOwnership'+import type {+ Bounds,+ EmbedEffect,+ EmbedEvent,+ EmbedOwnershipState,+ Launch,+ LaunchId,+ LaunchOutcome,+} from '../../ui/src/lib/embedOwnership.types'+import { createEmbedOwnershipMachine } from '../../ui/src/lib/embedOwnershipMachine'+import type {+ EmbedOwnershipMachine,+ EmbedRefreshErrorEvent,+} from '../../ui/src/lib/embedOwnershipMachine.types'+import {+ activeWorkspaceTab,+ closeWorkspaceTab,+ createWorkspaceTabsState,+ openAppTab,+ 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 { SandboxUiReleasedEvent } from '../types.js'+import {+ FakeParentWindow,+ type FakeWebContents,+ type FakeWebContentsView,+ electronMocks,+} from './__fixtures__/sandboxUiElectronFakes.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+// ipc.ts, and behind them the REAL AppService lifecycle queue and sandbox-ui+// driver. Only the Electron runtime, rpc-proxy's HTTP answers and the RPC-token+// issuer are fake. Nothing here models main: every `released`, every open+// outcome and every location comes from the code that produces it in the app.+//+// The IPC wire is two FIFO lanes (renderer → main, main → renderer) whose+// deliveries, like slot measurements, mints, document commits/loads and the+// route-handoff script, are tasks of a fast-check scheduler, so each run tries a+// different interleaving of them with the user's gestures and with the+// accidents of the real world (crashes, renderer reloads, session changes, a+// throwing cleanup).++vi.mock(+ 'electron',+ 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('../authClient.js', () => ({+ AuthClient: class {+ health = vi.fn().mockResolvedValue({ status: 'ok' })+ getMe = vi.fn()+ },+}))++vi.mock('../tokenStore.js', () => ({+ TokenStore: class {+ getSessionToken = vi.fn().mockResolvedValue(null)+ setSessionToken = vi.fn()+ clearSessionToken = vi.fn()+ },+}))++const RUNS = Number(process.env.EMBED_PROP_RUNS ?? 4000)+const SEED = process.env.EMBED_PROP_SEED ? Number(process.env.EMBED_PROP_SEED) : undefined+const P8_RUNS = Math.max(1, Math.round(RUNS / 2))+// About 60% of P8 runs compare two different interleavings; from 50 runs on, a+// share under 40% is far outside chance and means the two schedulers collapsed.+// Fewer runs (a small EMBED_PROP_RUNS) are too noisy to judge and skip the check.+const P8_GUARD_MIN_RUNS = 50++const BOUNDS: Bounds = { x: 0, y: 40, width: 800, height: 600 }+const RPC_ORIGIN = 'https://rpc.example'+const APPS = {+ alpha: 'sandbox-recipes/alpha',+ beta: 'sandbox-recipes/beta',+ // rpc-proxy refuses every mint for this one.+ gamma: 'sandbox-recipes/gamma',+} as const+type AppName = keyof typeof APPS++const viewBase = (appRef: string) => `${RPC_ORIGIN}/api/v1/sandbox-ui/${appRef}/view`++// ─── Scheduling ────────────────────────────────────────────────────────────++type TaskSink = { schedule<T>(task: Promise<T>, label: string): Promise<T> }++const macrotask = () => new Promise<void>(resolve => setImmediate(resolve))++async function settleAsyncWork(): Promise<void> {+ for (let i = 0; i < 3; i++) await macrotask()+}++async function microtasks(): Promise<void> {+ for (let i = 0; i < 10; i++) await Promise.resolve()+}++/** Holds every task until a named case releases it, for exact orderings. */+class ManualSink implements TaskSink {+ private tasks: Array<{ label: string; release: () => void }> = []++ schedule<T>(task: Promise<T>, label: string): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ this.tasks.push({ label, release: () => void task.then(resolve, reject) })+ })+ }++ labels(): string[] {+ return this.tasks.map(task => task.label)+ }++ /** Releases tasks oldest first until only held ones (if any) remain. */+ async runAll(hold: (label: string) => boolean = () => false): Promise<void> {+ for (let step = 0; step < 10_000; step++) {+ await settleAsyncWork()+ const index = this.tasks.findIndex(task => !hold(task.label))+ if (index === -1) {+ await settleAsyncWork()+ if (this.tasks.findIndex(task => !hold(task.label)) === -1) return+ continue+ }+ const [task] = this.tasks.splice(index, 1)+ task!.release()+ }+ throw new Error(`ManualSink did not settle: ${this.labels().join(', ')}`)+ }+}++async function drainScheduler(+ s: fc.Scheduler,+ finished: () => boolean = () => true+): Promise<void> {+ for (let round = 0; round < 1_000; round++) {+ await s.waitIdle()+ await settleAsyncWork()+ if (s.count() === 0 && finished()) return+ }+ throw new Error('the scheduler never went idle')+}++// ─── 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 = null+let 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+ launchId: LaunchId+ resolve: (value: unknown) => void+ reject: (error: unknown) => void+}++type ToRenderer =+ | { kind: 'reply'; label: string; settle: () => void }+ | { kind: 'event'; label: string; channel: string; payload: unknown }++type Gesture =+ | { type: 'select'; tab: number }+ | { type: 'reclick' }+ | { type: 'relaunch' }+ | { type: 'backToApps' }+ /** Hands the embed off (a deep link to another team); the link then opens `tab`. */+ | { type: 'handoff'; tab: number }+ | { type: 'closeTab'; tab: number }+ | { type: 'openTab'; app: AppName }+ /** The commit that should have activated this tab did not (K23). */+ | { type: 'staleIntent'; tab: number }++type Reality =+ /** The next view dies (crash, session change) inside its mount, before its open settles. */+ | 'crashDuringMount'+ | 'sessionDuringMount'+ | 'crash'+ | 'title'+ | 'navigate'+ | 'reload'+ | 'session'+ | 'cleanupThrows'+ | 'lateMeasurer'+ /** The window holding the embed closes; its renderer goes with it. */+ | 'parentClosed'++type WorldOptions = {+ sink: TaskSink+ launchIds?: readonly string[]+ /** Deliver every queued renderer → main message in one go, as one IPC burst. */+ batch?: boolean+ /** Launches, by the order they are issued, whose slot never becomes measurable. */+ slotFailures?: readonly boolean[]+ lateMeasurer?: boolean+}++function short(id: string): string {+ return id.slice(0, 8)+}++function describeEvent(event: EmbedEvent): string {+ switch (event.type) {+ case 'projected':+ return `projected(${event.activeAppTabId})`+ case 'intent':+ case 'relaunch':+ return `${event.type}(${short(event.launch.launchId)}@${event.launch.tabId})`+ case 'backToApps':+ return 'backToApps'+ case 'handoff':+ return `handoff(${event.requestId})`+ case 'slotMeasured':+ return `slotMeasured(${short(event.launchId)}, ${event.bounds ? 'bounds' : 'null'})`+ case 'openSettled':+ return `openSettled(${short(event.launchId)}, ${JSON.stringify(event.outcome)})`+ case 'closeFailed':+ return `closeFailed(${short(event.launchId)})`+ case 'released':+ return `released(${short(event.launchId)}, ${event.reason}, ${JSON.stringify(event.location)})`+ case 'titleChanged':+ return `titleChanged(${short(event.launchId)})`+ }+}++const UNSOLICITED_REASONS = new Set<SandboxUiReleasedEvent['reason']>([+ 'crashed',+ 'session',+ 'renderer_replaced',+ 'parent_closed',+])++const IDEMPOTENT_EVENTS = new Set<EmbedEvent['type']>([+ 'projected',+ 'slotMeasured',+ 'openSettled',+ 'closeFailed',+ 'released',+])++/**+ * One renderer (machine + tab store) wired to one real main process through the+ * fake IPC wire. Gestures go through the same seam the app uses: commit the tab+ * store, project it, then dispatch the launch.+ */+class World {+ readonly sink: TaskSink+ readonly parent = new FakeParentWindow()+ readonly sender = { id: 1 }+ readonly mainWebContents = new FakeMainWebContents()+ readonly service: AppService+ readonly failingRecipes = new Set<string>(['gamma'])+ immediateMints = false+ /** The next view's renderer dies the moment its document starts loading. */+ crashNextLoad = false+ /** The session changes the moment the next view starts loading. */+ sessionChangeNextLoad = false+ dead = false+ tabs: WorkspaceTabsState+ machine: EmbedOwnershipMachine+ generation = 0+ measurerRegistered = false++ /** Main-side arrival order of lifecycle IPC. */+ readonly ipcTrace: Array<{ op: 'open' | 'close'; launchId: LaunchId; routePath?: string }> = []+ readonly launches = new Map<LaunchId, { tabId: string; generation: number }>()+ readonly settledCount = new Map<LaunchId, number>()+ readonly outcomes = new Map<LaunchId, LaunchOutcome>()+ readonly viewOf = new Map<LaunchId, FakeWebContentsView>()+ /** Every route a launch's view was asked to show or navigated to. */+ readonly shownRoutes = new Map<LaunchId, Set<string | undefined>>()+ readonly navigated = new Set<LaunchId>()+ readonly releases: SandboxUiReleasedEvent[] = []+ readonly handoffsReady: number[] = []+ readonly refreshErrors: EmbedRefreshErrorEvent[] = []+ readonly violations: string[] = []+ readonly log: string[] = []++ /** The last gesture asked for an owner on the tab still active. */+ expectOwner = false+ /** The owner that gesture left behind: the new launch, or the live one it kept. */+ gestureOwner: LaunchId | null = null+ /**+ * Since that gesture, main reported the death of the owner for a reason the+ * user did not ask for (crash, session, renderer reload).+ */+ killedSinceLaunch = false++ private readonly launchIds: string[]+ private readonly slotFailures: readonly boolean[]+ private readonly batch: boolean+ private readonly failedSlots = new Set<LaunchId>()+ private launchesIssued = 0+ private nextTab = 5+ private nextRequest = 1+ private navigation = 0+ private opensInMain = 0+ private readonly clearedTabs = new Set<string>()+ private readonly settlePromises = new Map<LaunchId, Promise<LaunchOutcome>>()+ private readonly continuations = new Map<+ number,+ { targetTabId: string | undefined; resolve: (value: unknown) => void }+ >()+ private lastLaunch: LaunchId | null = null+ /** The window closed: the renderer is gone and only main is left to check. */+ windowClosed = false+ private toMain: ToMain[] = []+ private toRenderer: ToRenderer[] = []+ private rendererLane: Promise<void> = Promise.resolve()+ private crashWatch: {+ launchId: LaunchId+ activeAppTabId: string | null+ owner: LaunchId | null+ } | null = null++ private constructor(options: WorldOptions) {+ this.sink = options.sink+ this.launchIds = [...(options.launchIds ?? [])]+ this.slotFailures = options.slotFailures ?? []+ this.batch = options.batch ?? false+ let tabs = createWorkspaceTabsState('chat-tab-1')+ tabs = openAppTab(tabs, { id: 'ws-tab-2', appRef: APPS.alpha, title: 'Alpha' })+ 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 = service+ this.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)+ })+ wireMainWindowRendererReadiness({+ webContents: world.mainWebContents as never,+ isCurrentWindow: () => true,+ markNotReady: () => {},+ sandboxUi: world.service,+ })+ currentWorld = world+ electronMocks.onLoadURL = (webContents, url) => currentWorld?.onLoad(webContents, url)+ if (!options.lateMeasurer) world.registerMeasurer()+ world.machine.projected(world.activeAppTabId())+ return world+ }++ // ── renderer ──++ private createMachine(): EmbedOwnershipMachine {+ const generation = ++this.generation+ return createEmbedOwnershipMachine({+ bridge: {+ open: request => this.sendToMain('sandboxUi:open', request, request.launchId),+ close: request => this.sendToMain('sandboxUi:close', request, request.launchId),+ },+ updateTabs: updater => {+ this.tabs = updater(this.tabs)+ },+ onHandoffReady: requestId => this.continueHandoff(requestId),+ onOwnerRefreshError: event => this.refreshErrors.push(event),+ onTransition: transition => this.checkTransition(transition, generation),+ })+ }++ registerMeasurer(): void {+ this.measurerRegistered = true+ this.machine.registerMeasurer(launchId =>+ this.sink.schedule(+ Promise.resolve(this.failedSlots.has(launchId) ? null : BOUNDS),+ `measure ${short(launchId)}`+ )+ )+ }++ activeAppTabId(): string | null {+ const tab = activeWorkspaceTab(this.tabs)+ return tab?.kind === 'app' ? tab.id : null+ }++ private tabAt(index: number): string | undefined {+ if (this.tabs.tabs.length === 0) return undefined+ return this.tabs.tabs[index % this.tabs.tabs.length]!.id+ }++ private commit(next: WorkspaceTabsState): void {+ this.tabs = next+ this.machine.projected(this.activeAppTabId())+ }++ private takeLaunchId(): string {+ return this.launchIds.shift() ?? crypto.randomUUID()+ }++ /** Builds a launch for `tabId` as the seam would; `dispatch` decides how it is sent. */+ private newLaunch(tabId: string, kind: 'tab' | 'explicit'): Launch {+ const tab = this.tabs.tabs.find(candidate => candidate.id === tabId)!+ const launchId = this.takeLaunchId()+ if (this.slotFailures[this.launchesIssued]) this.failedSlots.add(launchId)+ this.launchesIssued += 1+ this.launches.set(launchId, { tabId, generation: this.generation })+ const settled = this.machine.registerWhenSettled(launchId)+ this.settlePromises.set(launchId, settled)+ void settled.then(outcome => {+ this.outcomes.set(launchId, outcome)+ })+ // Like the seam, a tab launch asks for the route its tab was left at: after+ // a renderer reload that is all a fresh machine has to go on. A tab never+ // left anywhere asks for a route of its own, so routes name their launch.+ const routePath =+ kind === 'tab' && tab.app?.savedRoutePath !== undefined+ ? tab.app.savedRoutePath+ : `/r/${launchId}`+ return {+ launchId,+ tabId,+ appRef: tab.app!.appRef,+ route: { kind, routePath },+ app: { label: tab.title, defaultPath: '/' },+ }+ }++ launch(tabId: string, kind: 'tab' | 'explicit', replace = false): LaunchId {+ const launch = this.newLaunch(tabId, kind)+ // The owner it leaves is read when the machine reduces this launch: from+ // inside an effect the dispatch is only queued and the snapshot lags.+ this.lastLaunch = launch.launchId+ this.gestureOwner = null+ this.killedSinceLaunch = false+ if (replace) this.machine.relaunch(launch)+ else this.machine.intent(launch)+ this.expectOwner = this.activeAppTabId() === tabId+ return launch.launchId+ }++ selectTab(tabId: string): LaunchId | undefined {+ this.commit(selectWorkspaceTab(this.tabs, tabId))+ if (this.activeAppTabId() === tabId) return this.launch(tabId, 'tab')+ this.expectOwner = false+ return undefined+ }++ /** The tab activates but its app cannot be resolved: no launch follows (K6). */+ commitOnly(tabId: string): void {+ this.commit(selectWorkspaceTab(this.tabs, tabId))+ this.expectOwner = false+ }++ reclick(): LaunchId | undefined {+ const tabId = this.activeAppTabId()+ return tabId ? this.launch(tabId, 'tab') : undefined+ }++ relaunch(): LaunchId | undefined {+ const tabId = this.activeAppTabId()+ return tabId ? this.launch(tabId, 'tab', true) : undefined+ }++ backToApps(): void {+ this.machine.backToApps()+ this.expectOwner = false+ }++ handoff(targetTabId?: string): Promise<unknown> {+ const requestId = this.nextRequest+++ const done = new Promise<unknown>(resolve =>+ this.continuations.set(requestId, { targetTabId, resolve })+ )+ this.machine.handoff(requestId)+ this.expectOwner = false+ return done+ }++ /**+ * The deep link's continuation once the embed is handed off: it activates its+ * target tab and launches it, synchronously, from inside the machine's effect+ * — what the seam does when the continuation runs.+ */+ private continueHandoff(requestId: number): void {+ this.handoffsReady.push(requestId)+ const continuation = this.continuations.get(requestId)+ this.continuations.delete(requestId)+ if (!continuation) return+ const target = continuation.targetTabId+ const exists = target && this.tabs.tabs.some(tab => tab.id === target && tab.kind === 'app')+ if (!exists) return continuation.resolve(undefined)+ this.log.push(`continuation of handoff ${requestId} opens ${target}`)+ const launchId = this.selectTab(target)+ continuation.resolve(launchId ? this.settled(launchId) : undefined)+ }++ /** The single outcome of a launch, whenever it settles. */+ settled(launchId: LaunchId): Promise<LaunchOutcome> {+ return this.settlePromises.get(launchId)!+ }++ openTab(app: AppName): LaunchId {+ const id = `ws-tab-${this.nextTab++}`+ const title = app[0]!.toUpperCase() + app.slice(1)+ this.commit(openAppTab(this.tabs, { id, appRef: APPS[app], title }))+ return this.launch(id, 'explicit')+ }++ /** Closing a tab activates a neighbour; an app neighbour is relaunched by the seam. */+ closeTab(tabId: string): LaunchId | undefined {+ this.commit(closeWorkspaceTab(this.tabs, tabId))+ const active = this.activeAppTabId()+ if (active) return this.launch(active, 'tab')+ this.expectOwner = false+ return undefined+ }++ /** Activates `tabId` with the launch dispatched BEFORE its commit is projected. */+ selectBreakingCommitOrder(tabId: string): LaunchId {+ const launch = this.newLaunch(tabId, 'tab')+ this.machine.intent(launch)+ this.commit(selectWorkspaceTab(this.tabs, tabId))+ return launch.launchId+ }++ staleIntent(tabId: string): LaunchId | undefined {+ if (tabId === this.activeAppTabId()) return undefined+ const tab = this.tabs.tabs.find(candidate => candidate.id === tabId)+ if (tab?.kind !== 'app') return undefined+ const launch = this.newLaunch(tabId, 'tab')+ this.machine.intent(launch)+ return launch.launchId+ }++ gesture(gesture: Gesture): LaunchId | Promise<unknown> | undefined {+ if (this.windowClosed) return undefined+ this.log.push(`gesture ${JSON.stringify(gesture)}`)+ switch (gesture.type) {+ case 'select': {+ const tabId = this.tabAt(gesture.tab)+ return tabId ? this.selectTab(tabId) : undefined+ }+ case 'reclick':+ return this.reclick()+ case 'relaunch':+ return this.relaunch()+ case 'backToApps':+ this.backToApps()+ return undefined+ case 'handoff':+ return this.handoff(this.tabAt(gesture.tab))+ case 'closeTab': {+ const tabId = this.tabAt(gesture.tab)+ return tabId ? this.closeTab(tabId) : undefined+ }+ case 'openTab':+ return this.openTab(gesture.app)+ case 'staleIntent': {+ const tabId = this.tabAt(gesture.tab)+ return tabId ? this.staleIntent(tabId) : undefined+ }+ }+ }++ /**+ * The trusted renderer reloads: main drops the embed it owned, the new+ * document starts with an empty machine, projects the restored store and+ * relaunches the active app tab.+ */+ reloadRenderer(): void {+ if (this.windowClosed) return+ this.log.push('reality reload')+ // What the old document already sent reaches main before its replacement commits.+ while (this.toMain.length > 0) this.invokeMain(this.toMain.shift()!)+ this.machine.dispose()+ this.mainWebContents.emit('did-navigate', {}, 'file:///ui-dist/index.html', 200, 'OK')+ this.machine = this.createMachine()+ this.crashWatch = null+ this.clearedTabs.clear()+ if (this.measurerRegistered) this.registerMeasurer()+ this.machine.projected(this.activeAppTabId())+ const active = this.activeAppTabId()+ if (active) this.launch(active, 'tab')+ else this.expectOwner = false+ }++ /** Returns false when there was nothing for it to act on yet. */+ reality(kind: Reality): boolean {+ if (kind === 'reload') {+ this.reloadRenderer()+ return true+ }+ if (kind === 'parentClosed') {+ if (this.windowClosed) return true+ if (!getActiveSandboxUi() && this.opensInMain === 0) return false+ this.log.push('reality parent window closed')+ this.windowClosed = true+ this.machine.dispose()+ this.parent.destroy()+ this.parent.emit('closed')+ return true+ }+ if (kind === 'lateMeasurer') {+ if (!this.measurerRegistered) this.registerMeasurer()+ return true+ }+ if (kind === 'session') {+ if (!getActiveSandboxUi() && this.opensInMain === 0) return false+ this.log.push('reality session')+ this.invalidateSession()+ return true+ }+ if (kind === 'crashDuringMount') {+ this.crashNextLoad = true+ return true+ }+ if (kind === 'sessionDuringMount') {+ this.sessionChangeNextLoad = true+ return true+ }+ const active = getActiveSandboxUi()+ const view = active ? this.viewOf.get(active.launchId) : undefined+ if (!active || !view || view.webContents.destroyed) return false+ switch (kind) {+ case 'crash':+ this.log.push(`reality crash on ${short(active.launchId)}`)+ view.webContents.emit('render-process-gone', {}, { reason: 'crashed', exitCode: 139 })+ return true+ case 'title':+ this.log.push(`reality title on ${short(active.launchId)}`)+ view.webContents.emit('page-title-updated', {}, `title ${active.launchId}`)+ return true+ case 'navigate': {+ if (!view.webContents.currentUrl) return false+ this.log.push(`reality navigate on ${short(active.launchId)}`)+ const route = `/r/nav-${++this.navigation}`+ this.navigated.add(active.launchId)+ this.shownRoutes.get(active.launchId)?.add(route)+ view.webContents.navigateInPage(`${viewBase(active.appRef)}${route}`)+ return true+ }+ case 'cleanupThrows':+ this.log.push(`reality cleanupThrows on ${short(active.launchId)}`)+ vi.spyOn(view.webContents, 'removeListener').mockImplementation(() => {+ throw new Error('injected unhook failure')+ })+ return true+ }+ }++ /** 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()+ }++ /** Schedules an accident; one with no view to hit yet tries again later, a few times. */+ scheduleReality(kind: Reality, attempts = 4): void {+ void this.sink.schedule(Promise.resolve(), `reality ${kind}`).then(() => {+ if (this.dead) return+ if (!this.reality(kind) && attempts > 1) this.scheduleReality(kind, attempts - 1)+ })+ }++ // ── wire ──++ private sendToMain(channel: ToMain['channel'], payload: unknown, launchId: LaunchId) {+ return new Promise<unknown>((resolve, reject) => {+ this.toMain.push({ channel, payload, launchId, resolve, reject })+ void this.sink+ .schedule(Promise.resolve(), `ipc→main ${channel} ${short(launchId)}`)+ .then(() => this.deliverToMain())+ })+ }++ private deliverToMain(): void {+ const count = this.batch ? this.toMain.length : 1+ for (let i = 0; i < count; i++) {+ const message = this.toMain.shift()+ if (!message) return+ this.invokeMain(message)+ }+ }++ private invokeMain(message: ToMain): void {+ const op = message.channel === 'sandboxUi:open' ? 'open' : 'close'+ const routePath = (message.payload as { routePath?: string }).routePath+ this.ipcTrace.push({ op, launchId: message.launchId, ...(op === 'open' ? { routePath } : {}) })+ if (op === 'open') {+ 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 label = `reply ${message.channel} ${short(message.launchId)}`+ if (op === 'open') {+ void result.then(+ () => (this.opensInMain -= 1),+ () => (this.opensInMain -= 1)+ )+ }+ result.then(+ value => this.queueToRenderer({ kind: 'reply', label, settle: () => message.resolve(value) }),+ error => this.queueToRenderer({ kind: 'reply', label, settle: () => message.reject(error) })+ )+ }++ fromMain(channel: string, payload: unknown): void {+ if (channel === 'sandboxUi:released')+ this.checkReleasedLocation(payload as SandboxUiReleasedEvent)+ const launchId = (payload as { launchId?: string } | undefined)?.launchId ?? ''+ this.queueToRenderer({+ kind: 'event',+ label: `${channel} ${short(launchId)}`,+ channel,+ payload,+ })+ }++ // Replies and events share one ordered lane, as they share the IPC pipe; a+ // message is handled, microtasks included, before the next one arrives.+ private queueToRenderer(message: ToRenderer): void {+ this.toRenderer.push(message)+ const released = this.sink.schedule(Promise.resolve(), `ipc→renderer ${message.label}`)+ this.rendererLane = this.rendererLane+ .then(() => released)+ .then(() => this.deliverToRenderer())+ .then(microtasks)+ .catch(error => {+ this.violations.push(`renderer delivery threw: ${String(error)}`)+ })+ }++ private deliverToRenderer(): void {+ const message = this.toRenderer.shift()+ if (!message) return+ if (message.kind === 'reply') {+ message.settle()+ return+ }+ switch (message.channel) {+ case 'sandboxUi:released': {+ const released = message.payload as SandboxUiReleasedEvent+ this.releases.push(released)+ if (+ UNSOLICITED_REASONS.has(released.reason) &&+ this.machine.getSnapshot().owner === released.launchId+ ) {+ this.killedSinceLaunch = true+ }+ this.machine.onReleased(released)+ return+ }+ case 'sandboxUi:titleChanged':+ this.machine.onTitleChanged(message.payload as { launchId: string; title: string })+ return+ case 'sandboxUi:refreshError':+ this.machine.onRefreshError(message.payload as EmbedRefreshErrorEvent)+ return+ }+ }++ onLoad(webContents: FakeWebContents, _url: string): void {+ const active = getActiveSandboxUi()+ const view = electronMocks.views.find(candidate => candidate.webContents === webContents)+ if (!active || !view) return+ const launchId = active.launchId+ this.viewOf.set(launchId, view)+ // Inside the mount: nothing else can run between this and the open's own+ // checks, so these reach the window between mounting and settling.+ if (this.sessionChangeNextLoad) {+ this.sessionChangeNextLoad = false+ this.log.push(`reality session inside the mount of ${short(launchId)}`)+ this.invalidateSession()+ }+ if (this.crashNextLoad) {+ this.crashNextLoad = false+ this.log.push(`reality crash inside the mount of ${short(launchId)}`)+ webContents.emit('render-process-gone', {}, { reason: 'crashed', exitCode: 139 })+ return+ }+ const runScript = webContents.executeJavaScript.getMockImplementation()!+ // The page runs the handoff script when the scheduler says so, and runs it+ // for real: whatever it reads or changes comes from the script itself.+ webContents.executeJavaScript.mockImplementation((code: string) =>+ this.sink.schedule(Promise.resolve(), `exec ${short(launchId)}`).then(() => runScript(code))+ )+ void this.sink.schedule(Promise.resolve(), `commit ${short(launchId)}`).then(() => {+ if (webContents.destroyed || this.dead) return+ webContents.currentUrl = webContents.pendingUrl+ webContents.emit('did-navigate', {}, webContents.currentUrl, 200, '')+ void this.sink.schedule(Promise.resolve(), `loaded ${short(launchId)}`).then(() => {+ if (webContents.destroyed || this.dead) return+ webContents.emit('did-finish-load')+ })+ })+ }++ // ── properties checked on every transition ──++ private violation(property: string, detail: string): void {+ this.violations.push(`${property}: ${detail}`)+ }++ private checkTransition(+ transition: {+ event: EmbedEvent+ previous: EmbedOwnershipState+ next: EmbedOwnershipState+ effects: readonly EmbedEffect[]+ },+ generation: number+ ): void {+ const { event, previous, next, effects } = transition+ const where = `[r${generation}] ${describeEvent(event)}`+ this.log.push(+ `${where} → owner ${next.owner ? short(next.owner) : null}; ` ++ effects.map(e => e.type + ('launchId' in e ? ` ${short(e.launchId)}` : '')).join(', ')+ )+ if (+ (event.type === 'intent' || event.type === 'relaunch') &&+ event.launch.launchId === this.lastLaunch+ ) {+ this.gestureOwner = next.owner+ }++ if (next.owner !== null) {+ const owner = next.views.get(next.owner)+ if (!owner || owner.tabId !== next.activeAppTabId) {+ this.violation('P1', `${where}: owner ${short(next.owner)} is not a view of the active tab`)+ }+ }++ for (const effect of effects) {+ if (effect.type === 'close' && effect.launchId === next.owner) {+ this.violation('P3', `${where}: closes the owner ${short(effect.launchId)}`)+ }+ if (effect.type === 'persistRoute') {+ const record = event.type === 'released' ? previous.views.get(event.launchId) : undefined+ if (!record || record.tabId !== effect.tabId) {+ this.violation('P4', `${where}: persists ${effect.tabId} without a release of its view`)+ } else {+ const route = effect.route.action === 'set' ? effect.route.routePath : undefined+ if (!this.shownRoutes.get(record.launchId)?.has(route)) {+ this.violation(+ 'P4',+ `${where}: persists ${route} that ${short(record.launchId)} never showed`+ )+ }+ }+ }+ if (effect.type === 'persistRoute' && effect.route.action === 'clear') {+ this.clearedTabs.add(effect.tabId)+ }+ if (effect.type === 'sendOpen' && effect.launch.route.kind === 'tab') {+ // K19: a tab reopens where the store says it was left, even though the+ // seam built the launch before that route reached the store.+ const tab = this.tabs.tabs.find(candidate => candidate.id === effect.launch.tabId)+ const saved = tab?.app?.savedRoutePath+ const expected =+ saved !== undefined || this.clearedTabs.has(effect.launch.tabId)+ ? saved+ : effect.launch.route.routePath+ if (tab && effect.routePath !== expected) {+ this.violation(+ 'K19',+ `${where}: opens ${short(effect.launch.launchId)} at ${effect.routePath}, its tab was left at ${expected}`+ )+ }+ }+ if (effect.type === 'setTitle') {+ const owner = previous.owner === null ? undefined : previous.views.get(previous.owner)+ if (+ event.type !== 'titleChanged' ||+ event.launchId !== previous.owner ||+ owner?.tabId !== effect.tabId ||+ event.title !== effect.title+ ) {+ this.violation('P5', `${where}: setTitle(${effect.tabId}) not from the owner's title`)+ }+ }+ if (effect.type === 'launchSettled') {+ const count = (this.settledCount.get(effect.launchId) ?? 0) + 1+ this.settledCount.set(effect.launchId, count)+ if (count > 1) this.violation('P12', `${where}: ${short(effect.launchId)} settled twice`)+ }+ }++ // P13, renderer side: the route main reports for a dying view reaches its tab.+ if (event.type === 'released' && event.location !== null) {+ const record = previous.views.get(event.launchId)+ if (record) {+ const routePath = event.location.routePath+ const persisted = effects.some(+ effect =>+ effect.type === 'persistRoute' &&+ effect.tabId === record.tabId &&+ (routePath === undefined+ ? effect.route.action === 'clear'+ : effect.route.action === 'set' && effect.route.routePath === routePath)+ )+ if (!persisted) {+ this.violation('P13', `${where}: the released route never reaches ${record.tabId}`)+ }+ }+ }++ if (IDEMPOTENT_EVENTS.has(event.type)) {+ const again = reduceEmbedOwnership(next, event)+ if (again.state !== next || again.effects.length > 0) {+ this.violation('P6', `${where}: repeating it is not a no-op`)+ }+ }++ const mainPhaseByTab = new Map<string, number>()+ for (const view of next.views.values()) {+ if (view.phase === 'opening' || view.phase === 'mounted' || view.phase === 'closeRequested') {+ mainPhaseByTab.set(view.tabId, (mainPhaseByTab.get(view.tabId) ?? 0) + 1)+ }+ }+ for (const [tabId, count] of mainPhaseByTab) {+ if (count > 1) this.violation('P10', `${where}: ${count} records of ${tabId} in main`)+ }++ if (next.owner !== null && next.views.get(next.owner)?.phase === 'mounted') {+ const active = getActiveSandboxUi()+ if (active && active.launchId !== next.owner) {+ this.violation('P14', `${where}: owner mounted but main shows ${short(active.launchId)}`)+ }+ }++ if (+ event.type === 'released' &&+ event.reason === 'crashed' &&+ previous.owner === event.launchId &&+ previous.views.get(event.launchId)?.phase === 'mounted'+ ) {+ if (next.failure?.launchId !== event.launchId || next.failure.kind !== 'crashed') {+ this.violation('P17', `${where}: the owner's crash left no crash failure`)+ }+ this.crashWatch = {+ launchId: event.launchId,+ activeAppTabId: next.activeAppTabId,+ owner: next.owner,+ }+ } else if (this.crashWatch) {+ if (+ next.activeAppTabId === this.crashWatch.activeAppTabId &&+ next.owner === this.crashWatch.owner+ ) {+ if (next.failure?.launchId !== this.crashWatch.launchId) {+ this.violation('P17', `${where}: the crash failure vanished with nothing changed`)+ }+ } else {+ this.crashWatch = null+ }+ }+ }++ /** P13 (and K17): what main reports for a view that dies is the route it stood for. */+ private checkReleasedLocation(event: SandboxUiReleasedEvent): void {+ const where = `released(${short(event.launchId)}, ${event.reason})`+ if (event.reason === 'crashed') {+ if (event.location !== null) this.violation('P13', `${where}: a crash reports a route`)+ return+ }+ const shown = this.shownRoutes.get(event.launchId)+ const location = event.location+ if (location === null) {+ this.violation('P13', `${where}: no route for a view that did not crash`)+ return+ }+ if (!this.navigated.has(event.launchId)) {+ const requested = this.ipcTrace.find(+ entry => entry.op === 'open' && entry.launchId === event.launchId+ )?.routePath+ if (location.routePath !== requested) {+ this.violation(+ 'P13',+ `${where}: reports ${JSON.stringify(location)} instead of the requested ${requested}`+ )+ }+ } else if (!shown?.has(location.routePath)) {+ this.violation('P13', `${where}: reports ${location.routePath}, a route it never showed`)+ }+ }++ // ── properties checked once everything has drained ──++ checkDrained(): void {+ if (this.windowClosed) {+ // Only main is left: no view may outlive the window, alive or registered.+ const active = getActiveSandboxUi()+ if (active) this.violation('I-orphan', `${short(active.launchId)} outlived its window`)+ for (const view of electronMocks.views) {+ if (!view.webContents.destroyed) {+ this.violation('I-orphan', `webContents ${view.webContents.id} outlived its window`)+ }+ }+ // What the renderer sent before the window closed still reached main in order.+ this.checkIpcOrder()+ return+ }+ const state = this.machine.getSnapshot()+ const active = getActiveSandboxUi()+ const activeTab = this.activeAppTabId()+ const ownerId = state.owner++ if (state.activeAppTabId !== activeTab) {+ this.violation(+ 'projection',+ `machine projects ${state.activeAppTabId}, store has ${activeTab}`+ )+ }+ if (activeTab === null || ownerId === null) {+ if (active !== null)+ this.violation('P2', `main shows ${short(active.launchId)} with no owner`)+ } else if (active?.launchId !== ownerId) {+ this.violation(+ 'P2',+ `owner ${short(ownerId)} but main shows ${active ? short(active.launchId) : null}`+ )+ }++ for (const [launchId, view] of state.views) {+ if (launchId !== ownerId)+ this.violation('P7', `${short(launchId)} (${view.phase}) left in views`)+ else if (view.phase !== 'mounted') {+ this.violation('P11', `owner ${short(launchId)} stuck in ${view.phase}`)+ }+ }+ if (state.handoffs.length > 0)+ this.violation('P7/P11', `${state.handoffs.length} handoffs left`)++ for (const [launchId, record] of this.launches) {+ const count = this.settledCount.get(launchId) ?? 0+ if (record.generation === this.generation && count !== 1) {+ this.violation('P12', `${short(launchId)} settled ${count} times`)+ }+ }+ if (this.machine.pendingWhenSettled() !== 0) {+ this.violation('P12', `${this.machine.pendingWhenSettled()} whenSettled still pending`)+ }++ if (this.expectOwner && !this.killedSinceLaunch && activeTab !== null) {+ // Only the failure of the launch the gesture asked for explains a missing+ // owner; an older failure on the same tab would hide a dropped launch.+ if (ownerId === null && state.failure?.launchId !== this.gestureOwner) {+ this.violation('P15', `active app tab ${activeTab} has neither an owner nor its failure`)+ }+ }++ const children = this.parent.contentView.children as FakeWebContentsView[]+ if (!active) {+ if (children.length > 0)+ this.violation('P16', `${children.length} views attached, none active`)+ } else if (children.length !== 1 || children[0]!.webContents.id !== active.webContentsId) {+ this.violation('P16', `attached views are not exactly the active one (${children.length})`)+ }++ this.checkIpcOrder()+ }++ /** P9: main never receives a close before the open of the same launch. */+ private checkIpcOrder(): void {+ const opened = new Set<LaunchId>()+ for (const entry of this.ipcTrace) {+ if (entry.op === 'open') opened.add(entry.launchId)+ else if (!opened.has(entry.launchId)) {+ this.violation('P9', `close(${short(entry.launchId)}) reached main before its open`)+ }+ }+ }++ /** What the user ends up with; must not depend on how the world interleaved. */+ outcome() {+ const state = this.machine.getSnapshot()+ const active = getActiveSandboxUi()+ return {+ activeAppTabId: state.activeAppTabId,+ hasOwner: state.owner !== null,+ savedRoutes: this.tabs.tabs.map(tab => [tab.id, tab.app?.savedRoutePath] as const),+ liveView: active?.launchId ?? null,+ liveViewOpenedAt: active+ ? this.ipcTrace.find(entry => entry.op === 'open' && entry.launchId === active.launchId)+ ?.routePath+ : null,+ attached: this.parent.contentView.children.length,+ }+ }++ report(): string {+ return [...this.violations, '--- log ---', ...this.log.slice(-60)].join('\n')+ }+}++// ─── Arbitraries ───────────────────────────────────────────────────────────++const tabIndex = fc.nat({ max: 7 })++const gestureArb: fc.Arbitrary<Gesture> = fc.oneof(+ { weight: 5, arbitrary: tabIndex.map(tab => ({ type: 'select', tab }) as const) },+ { weight: 1, arbitrary: fc.constant({ type: 'reclick' } as const) },+ { weight: 2, arbitrary: fc.constant({ type: 'relaunch' } as const) },+ { weight: 1, arbitrary: fc.constant({ type: 'backToApps' } as const) },+ { weight: 1, arbitrary: tabIndex.map(tab => ({ type: 'handoff', tab }) as const) },+ { weight: 1, arbitrary: tabIndex.map(tab => ({ type: 'closeTab', tab }) as const) },+ {+ weight: 2,+ arbitrary: fc+ .constantFrom<AppName>('alpha', 'beta', 'gamma')+ .map(app => ({ type: 'openTab', app }) as const),+ },+ { weight: 1, arbitrary: tabIndex.map(tab => ({ type: 'staleIntent', tab }) as const) }+)++const realityArb = fc.array(+ fc.constantFrom<Reality>(+ 'crashDuringMount',+ 'sessionDuringMount',+ 'crash',+ 'title',+ 'navigate',+ 'reload',+ 'session',+ 'cleanupThrows',+ 'lateMeasurer',+ 'parentClosed'+ ),+ { maxLength: 6 }+)++const LAUNCH_POOL = 32+const launchIdsArb = fc.uniqueArray(fc.uuid(), { minLength: LAUNCH_POOL, maxLength: LAUNCH_POOL })+const slotFailuresArb = fc.array(+ fc.nat({ max: 9 }).map(n => n === 0),+ { minLength: LAUNCH_POOL, maxLength: LAUNCH_POOL }+)++// ─── Suite ─────────────────────────────────────────────────────────────────++beforeAll(async () => {+ userDataDir = await mkdtemp(path.join(tmpdir(), 'clerum-embed-ownership-'))+})++afterAll(async () => {+ await rm(userDataDir, { recursive: true, force: true })+})++beforeEach(() => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ vi.stubGlobal('fetch', fetchMock)+ // 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+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ vi.useRealTimers()+})++function assertClean(world: World): void {+ if (world.violations.length > 0) throw new Error(world.report())+}++describe('embed ownership against the real main process (properties)', () => {+ it('P1–P7, P9–P17 hold for any gestures under any interleaving with the real world', async () => {+ await fc.assert(+ fc.asyncProperty(+ fc.scheduler(),+ fc.array(gestureArb, { minLength: 1, maxLength: 10 }),+ realityArb,+ launchIdsArb,+ slotFailuresArb,+ fc.boolean(),+ async (s, gestures, realities, launchIds, slotFailures, batch) => {+ const world = await World.create({+ sink: s,+ launchIds,+ slotFailures,+ batch,+ lateMeasurer: realities.includes('lateMeasurer'),+ })+ for (const reality of realities) world.scheduleReality(reality)+ s.scheduleSequence(+ gestures.map(gesture => ({+ label: `gesture ${gesture.type}`,+ builder: async () => {+ world.gesture(gesture)+ },+ }))+ )+ await drainScheduler(s)+ world.checkDrained()+ assertClean(world)+ }+ ),+ { numRuns: RUNS, ...(SEED === undefined ? {} : { seed: SEED }) }+ )+ })++ it('P8: the same intentions end in the same place under any interleaving', async () => {+ const runIntentions = async (+ s: fc.Scheduler,+ gestures: Gesture[],+ launchIds: string[],+ slotFailures: boolean[]+ ) => {+ const world = await World.create({ sink: s, launchIds, slotFailures })+ // Not `scheduleSequence`: it holds every other task while a step's builder+ // runs, and a step that waits for its launch would wait forever.+ let done = false+ const user = (async () => {+ for (const gesture of gestures) {+ await s.schedule(Promise.resolve(), `gesture ${gesture.type}`)+ const asked = world.gesture(gesture)+ // The user moves on once what they asked for has settled, a deep+ // link once its continuation has.+ if (typeof asked === 'string') await world.settled(asked)+ else if (asked) await asked+ }+ })().finally(() => {+ done = true+ })+ await drainScheduler(s, () => done)+ await user+ world.checkDrained()+ assertClean(world)+ return { outcome: world.outcome(), order: s.report().map(task => task.label) }+ }+ let runs = 0+ let reordered = 0+ await fc.assert(+ // The two schedulers must not sit next to each other: fast-check 4.9 gives+ // adjacent ones the same task order, and P8 then compares a run with itself.+ fc.asyncProperty(+ fc.scheduler(),+ fc.array(gestureArb, { minLength: 1, maxLength: 8 }),+ launchIdsArb,+ slotFailuresArb,+ fc.scheduler(),+ async (first, gestures, launchIds, slotFailures, second) => {+ const a = await runIntentions(first, gestures, launchIds, slotFailures)+ const b = await runIntentions(second, gestures, launchIds, slotFailures)+ runs += 1+ if (a.order.join('\n') !== b.order.join('\n')) reordered += 1+ expect(b.outcome).toEqual(a.outcome)+ }+ ),+ { numRuns: P8_RUNS, ...(SEED === undefined ? {} : { seed: SEED }) }+ )+ // Guards against P8 going vacuous again: most runs must really compare two+ // different interleavings.+ if (runs >= P8_GUARD_MIN_RUNS) expect(reordered / runs).toBeGreaterThan(0.4)+ })+})++// ─── Named cases ───────────────────────────────────────────────────────────+// Exact orderings, through the same real main process. Ported from the+// ownership cases the App suite pinned with a hand-written bridge. Where those+// relaunched the app by re-clicking its live tab, these use `relaunch`: a+// re-click with a live view now changes nothing (K15).++async function manualWorld(options: Partial<WorldOptions> = {}) {+ const sink = new ManualSink()+ const world = await World.create({ sink, ...options })+ return { sink, world }+}++const TAB_ALPHA = 'ws-tab-2'+const TAB_BETA = 'ws-tab-3'++async function liveOn(world: World, sink: ManualSink, tabId: string): Promise<LaunchId> {+ const launchId = world.selectTab(tabId)!+ await sink.runAll()+ expect(getActiveSandboxUi()?.launchId).toBe(launchId)+ return launchId+}++function closesSent(world: World): LaunchId[] {+ return world.ipcTrace.filter(entry => entry.op === 'close').map(entry => entry.launchId)+}++function expectNoView(world: World): void {+ expect(getActiveSandboxUi()).toBeNull()+ expect(world.parent.contentView.children).toEqual([])+}++const isLabel =+ (...parts: string[]) =>+ (label: string) =>+ parts.every(part => label.includes(part))++describe('embed ownership named cases (real main process)', () => {+ it('K5: a relaunch whose open main rejects leaves no view, and leaving has nothing to close', async () => {+ const { sink, world } = await manualWorld()+ const first = await liveOn(world, sink, TAB_ALPHA)++ world.failingRecipes.add('alpha')+ const relaunched = world.relaunch()!+ await sink.runAll()++ expect(world.outcomes.get(relaunched)).toBe('failed')+ expect(world.machine.getSnapshot().failure).toMatchObject({+ launchId: relaunched,+ kind: 'open',+ })+ expectNoView(world)++ world.selectTab('chat-tab-1')+ await sink.runAll()+ expect(closesSent(world)).toEqual([first])+ expectNoView(world)+ world.checkDrained()+ assertClean(world)+ })++ it('K5: a relaunch whose slot never measures closes the old view and sends no open', async () => {+ const { sink, world } = await manualWorld({ slotFailures: [false, true] })+ const first = await liveOn(world, sink, TAB_ALPHA)++ const relaunched = world.relaunch()!+ await sink.runAll()++ expect(world.outcomes.get(relaunched)).toBe('failed')+ expect(world.machine.getSnapshot().failure).toMatchObject({+ launchId: relaunched,+ kind: 'slot',+ })+ expect(world.ipcTrace.some(e => e.op === 'open' && e.launchId === relaunched)).toBe(false)+ expect(closesSent(world)).toEqual([first])+ expectNoView(world)+ world.checkDrained()+ assertClean(world)+ })++ it('K5: an app-to-app switch whose open fails leaves no view behind', async () => {+ const { sink, world } = await manualWorld()+ const first = await liveOn(world, sink, TAB_ALPHA)++ const failing = world.openTab('gamma')+ await sink.runAll()+ expect(world.outcomes.get(failing)).toBe('failed')+ expectNoView(world)++ world.selectTab('chat-tab-1')+ await sink.runAll()+ expect(closesSent(world)).toEqual([first])+ expectNoView(world)+ world.checkDrained()+ assertClean(world)+ })++ it('an app opened from the picker as its own tab owns the view and closes it on leave', async () => {+ const { sink, world } = await manualWorld()+ const opened = world.openTab('alpha')+ await sink.runAll()+ const tab = activeWorkspaceTab(world.tabs)+ expect(tab?.app?.appRef).toBe(APPS.alpha)+ expect(world.machine.getSnapshot().owner).toBe(opened)+ expect(getActiveSandboxUi()?.launchId).toBe(opened)++ world.selectTab('chat-tab-1')+ await sink.runAll()+ expect(closesSent(world)).toEqual([opened])+ expectNoView(world)+ world.checkDrained()+ assertClean(world)+ })++ it('K3: the replaced view crashing while a relaunch waits for it does not cost the relaunch its ownership', async () => {+ const { sink, world } = await manualWorld()+ const first = await liveOn(world, sink, TAB_ALPHA)++ const relaunched = world.relaunch()!+ // The close of the old view is still on its way to main when its renderer dies.+ world.reality('crash')+ await sink.runAll()++ expect(world.releases.map(r => [r.launchId, r.reason])).toEqual([[first, 'crashed']])+ expect(world.machine.getSnapshot().owner).toBe(relaunched)+ expect(world.machine.getSnapshot().failure).toBeNull()+ expect(getActiveSandboxUi()?.launchId).toBe(relaunched)++ world.selectTab('chat-tab-1')+ await sink.runAll()+ expect(closesSent(world)).toEqual([first, relaunched])+ expectNoView(world)+ world.checkDrained()+ assertClean(world)+ })++ it("K3: a refresh failure of the view a relaunch replaced never reaches the page; the live view's does", async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })+ const { sink, world } = await manualWorld()+ const first = await liveOn(world, sink, TAB_ALPHA)++ // rpc-proxy starts refusing: the first view's session loop gives up and reports it.+ world.failingRecipes.add('alpha')+ world.immediateMints = true+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)+ await vi.advanceTimersByTimeAsync(120_000)+ expect(sink.labels().some(isLabel('sandboxUi:refreshError', short(first)))).toBe(true)++ // The report is still on the wire when the user relaunches.+ world.failingRecipes.delete('alpha')+ world.immediateMints = false+ const relaunched = world.relaunch()!+ await sink.runAll()+ expect(world.machine.getSnapshot().owner).toBe(relaunched)+ expect(world.refreshErrors).toEqual([])++ world.failingRecipes.add('alpha')+ world.immediateMints = true+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)+ await vi.advanceTimersByTimeAsync(120_000)+ await sink.runAll()+ expect(world.refreshErrors).toHaveLength(1)+ expect(world.refreshErrors[0]!.launchId).toBe(relaunched)+ expect(world.refreshErrors[0]!.message).toContain('503')+ })++ it('K4: the late release of the app an app-to-app switch replaced keeps the new owner', async () => {+ const { sink, world } = await manualWorld()+ const first = await liveOn(world, sink, TAB_ALPHA)++ const second = world.selectTab(TAB_BETA)!+ // Everything but the release of the first view, which arrives last.+ await sink.runAll(isLabel('sandboxUi:released', short(first)))+ expect(world.machine.getSnapshot().owner).toBe(second)+ await sink.runAll()++ expect(world.machine.getSnapshot().owner).toBe(second)+ expect(getActiveSandboxUi()?.launchId).toBe(second)+ expect(world.tabs.tabs.find(t => t.id === TAB_ALPHA)?.app?.savedRoutePath).toBe(`/r/${first}`)++ world.selectTab('chat-tab-1')+ await sink.runAll()+ expect(closesSent(world)).toEqual([first, second])+ expectNoView(world)+ world.checkDrained()+ assertClean(world)+ })++ it('K4: a superseded open that mounts and then crashes does not take the newer launch its ownership', async () => {+ const { sink, world } = await manualWorld()+ const first = world.selectTab(TAB_ALPHA)!+ // Alpha's open reaches main; its mint is held.+ await sink.runAll(isLabel('mint alpha'))+ expect(world.ipcTrace.map(e => [e.op, e.launchId])).toEqual([['open', first]])++ const second = world.selectTab(TAB_BETA)!+ // Alpha mounts while its close and Beta's open are still on the wire, and dies.+ await sink.runAll(isLabel('ipc→main'))+ expect(getActiveSandboxUi()?.launchId).toBe(first)+ world.reality('crash')+ await sink.runAll()++ expect(world.machine.getSnapshot().owner).toBe(second)+ expect(world.machine.getSnapshot().failure).toBeNull()+ expect(getActiveSandboxUi()?.launchId).toBe(second)+ world.checkDrained()+ assertClean(world)+ })++ it('K7: the owner crashing drops its ownership, shows the crash and leaves nothing to close', async () => {+ const { sink, world } = await manualWorld()+ const live = await liveOn(world, sink, TAB_BETA)++ world.reality('crash')+ await sink.runAll()+ expect(world.machine.getSnapshot().owner).toBeNull()+ expect(world.machine.getSnapshot().failure).toEqual({+ tabId: TAB_BETA,+ launchId: live,+ kind: 'crashed',+ })+ // A crash never hands its route back.+ expect(world.tabs.tabs.find(t => t.id === TAB_BETA)?.app?.savedRoutePath).toBeUndefined()++ world.selectTab('chat-tab-1')+ await sink.runAll()+ expect(closesSent(world)).toEqual([])+ expectNoView(world)+ world.checkDrained()+ assertClean(world)+ })++ it('K15: re-clicking the active tab while its view is alive changes nothing', async () => {+ const { sink, world } = await manualWorld()+ const live = await liveOn(world, sink, TAB_ALPHA)+ const trace = world.ipcTrace.length++ const reclicked = world.reclick()!+ await sink.runAll()++ expect(world.outcomes.get(reclicked)).toBe('abandoned')+ expect(world.ipcTrace).toHaveLength(trace)+ expect(world.machine.getSnapshot().owner).toBe(live)+ expect(getActiveSandboxUi()?.launchId).toBe(live)+ world.checkDrained()+ assertClean(world)+ })++ it('K20: a view whose renderer dies before its open resolves settles abandoned, not crashed', async () => {+ const { sink, world } = await manualWorld()+ world.crashNextLoad = true++ const launchId = world.selectTab(TAB_ALPHA)!+ await sink.runAll()++ // main reports the release first, then rejects the open.+ expect(world.releases).toEqual([{ launchId, reason: 'crashed', location: null }])+ expect(world.outcomes.get(launchId)).toBe('abandoned')+ expect(world.machine.getSnapshot().failure).toBeNull()+ expect(world.machine.getSnapshot().owner).toBeNull()+ expectNoView(world)+ })++ it('K20: a view mounted under a session that ends before its open settles is abandoned', async () => {+ const { sink, world } = await manualWorld()+ world.sessionChangeNextLoad = true++ const launchId = world.selectTab(TAB_ALPHA)!+ await sink.runAll()++ expect(world.releases).toEqual([+ { launchId, reason: 'session', location: { routePath: `/r/${launchId}` } },+ ])+ expect(world.outcomes.get(launchId)).toBe('abandoned')+ expect(world.machine.getSnapshot().failure).toBeNull()+ expectNoView(world)+ world.checkDrained()+ assertClean(world)+ })++ it('K6: back to apps closes the view but keeps its tab; a pick from the grid opens its own tab', async () => {+ const { sink, world } = await manualWorld()+ const first = await liveOn(world, sink, TAB_ALPHA)++ world.backToApps()+ await sink.runAll()+ expect(closesSent(world)).toEqual([first])+ expect(world.tabs.activeTabId).toBe(TAB_ALPHA)+ expectNoView(world)++ const picked = world.openTab('beta')+ await sink.runAll()+ expect(world.tabs.activeTabId).not.toBe(TAB_ALPHA)+ expect(world.tabs.tabs.find(t => t.id === TAB_ALPHA)).toMatchObject({+ title: 'Alpha',+ app: { appRef: APPS.alpha, savedRoutePath: `/r/${first}` },+ })+ expect(getActiveSandboxUi()?.launchId).toBe(picked)+ world.checkDrained()+ assertClean(world)+ })++ it("K3: only the owner's titles rename its tab; a relaunch's predecessor cannot", async () => {+ const { sink, world } = await manualWorld()+ const first = await liveOn(world, sink, TAB_ALPHA)+ const alphaTitle = () => world.tabs.tabs.find(t => t.id === TAB_ALPHA)?.title++ world.reality('title')+ await sink.runAll()+ expect(alphaTitle()).toBe(`title ${first}`)++ const relaunched = world.relaunch()!+ // main only forwards titles of its active view, still the first one.+ world.reality('title')+ await sink.runAll()+ expect(alphaTitle()).toBe(`title ${first}`)++ world.reality('title')+ await sink.runAll()+ expect(getActiveSandboxUi()?.launchId).toBe(relaunched)+ expect(alphaTitle()).toBe(`title ${relaunched}`)+ world.checkDrained()+ assertClean(world)+ })++ it('K6: activating an app tab with no launch closes the live view and keeps its route on its own tab', async () => {+ const { sink, world } = await manualWorld()+ const first = await liveOn(world, sink, TAB_BETA)++ // Alpha's app cannot be resolved right now: its tab activates without a launch.+ world.commitOnly(TAB_ALPHA)+ await sink.runAll()+ expect(closesSent(world)).toEqual([first])+ expectNoView(world)+ expect(world.tabs.tabs.find(t => t.id === TAB_BETA)?.app?.savedRoutePath).toBe(`/r/${first}`)+ expect(world.tabs.tabs.find(t => t.id === TAB_ALPHA)?.app?.savedRoutePath).toBeUndefined()+ expect(world.tabs.tabs.find(t => t.id === TAB_ALPHA)?.title).toBe('Alpha')++ // Once the app is back, re-clicking its tab launches it.+ const launched = world.reclick()!+ await sink.runAll()+ expect(getActiveSandboxUi()?.launchId).toBe(launched)+ world.checkDrained()+ assertClean(world)+ })++ it('K6: moving to an app tab with no launch drops the failure of the tab left behind', async () => {+ const { sink, world } = await manualWorld()+ await liveOn(world, sink, TAB_ALPHA)+ world.failingRecipes.add('alpha')+ world.relaunch()+ await sink.runAll()+ expect(world.machine.getSnapshot().failure?.tabId).toBe(TAB_ALPHA)++ world.commitOnly(TAB_BETA)+ await sink.runAll()++ expect(world.machine.getSnapshot().failure).toBeNull()+ expectNoView(world)+ })++ it('K8: closing a tab while its view opens or measures leaves only the neighbour it activates', async () => {+ const { sink, world } = await manualWorld()+ const opening = world.selectTab(TAB_ALPHA)!+ // The open is in main, its mint not answered yet. Closing Alpha activates+ // Beta, its neighbour, which the seam launches.+ await sink.runAll(isLabel('mint alpha'))+ const neighbour = world.closeTab(TAB_ALPHA)!+ await sink.runAll()+ expect(world.outcomes.get(opening)).toBe('abandoned')+ expect(closesSent(world)).toEqual([opening])+ expect(getActiveSandboxUi()?.launchId).toBe(neighbour)++ // Gamma is closed before its slot is measured: main never hears of it.+ const measuring = world.selectTab('ws-tab-4')!+ const next = world.closeTab('ws-tab-4')!+ await sink.runAll()+ expect(world.outcomes.get(measuring)).toBe('abandoned')+ expect(world.ipcTrace.some(e => e.launchId === measuring)).toBe(false)+ expect(getActiveSandboxUi()?.launchId).toBe(next)+ world.checkDrained()+ assertClean(world)+ })++ it('K17: leaving an app while its document loads keeps the route it was asked for', async () => {+ const { sink, world } = await manualWorld()+ const first = await liveOn(world, sink, TAB_ALPHA)+ world.backToApps()+ await sink.runAll()+ const relaunched = world.reclick()!+ // Opened at the first view's route; the document has not committed yet.+ await sink.runAll(isLabel('commit'))+ expect(getActiveSandboxUi()?.launchId).toBe(relaunched)+ expect(world.ipcTrace.at(-1)).toMatchObject({ op: 'open', routePath: `/r/${first}` })++ world.selectTab('chat-tab-1')+ await sink.runAll()++ expect(world.releases.at(-1)).toEqual({+ launchId: relaunched,+ reason: 'closed',+ location: { routePath: `/r/${first}` },+ })+ expect(world.tabs.tabs.find(t => t.id === TAB_ALPHA)?.app?.savedRoutePath).toBe(`/r/${first}`)+ world.checkDrained()+ assertClean(world)+ })++ it('K24: a teardown whose cleanups throw still releases the view and detaches it', async () => {+ const { sink, world } = await manualWorld()+ const first = await liveOn(world, sink, TAB_ALPHA)+ world.reality('cleanupThrows')++ world.selectTab('chat-tab-1')+ await sink.runAll()++ expect(world.releases.map(r => r.launchId)).toEqual([first])+ expect(world.machine.getSnapshot().views.size).toBe(0)+ expectNoView(world)+ world.checkDrained()+ assertClean(world)+ })++ it('I-commit broken on purpose: a launch dispatched before its commit is abandoned and the tab has no owner', async () => {+ const { sink, world } = await manualWorld()+ const launchId = world.selectBreakingCommitOrder(TAB_ALPHA)+ await sink.runAll()++ expect(world.tabs.activeTabId).toBe(TAB_ALPHA)+ expect(world.outcomes.get(launchId)).toBe('abandoned')+ expect(world.machine.getSnapshot().owner).toBeNull()+ expect(world.ipcTrace).toEqual([])+ expectNoView(world)+ })+})diff --git a/desktop-app/ui/src/lib/__tests__/embedOwnershipMachine.test.ts b/desktop-app/ui/src/lib/__tests__/embedOwnershipMachine.test.tsnew file mode 100644index 000000000..a6c06caf5--- /dev/null+++ b/desktop-app/ui/src/lib/__tests__/embedOwnershipMachine.test.ts@@ -0,0 +1,549 @@+import { describe, expect, it, vi } from 'vitest'+import type { Bounds, Launch, LaunchId, TabId } from '../embedOwnership.types'+import { createEmbedOwnershipMachine } from '../embedOwnershipMachine'+import type {+ EmbedOpenRequest,+ EmbedOwnershipMachineDeps,+ EmbedSlotMeasurer,+} from '../embedOwnershipMachine.types'+import { createWorkspaceTabsState, openAppTab } from '../workspaceTabs'+import type { WorkspaceTabsState } from '../workspaceTabs.types'++// Interpreter only: the reducer is the real one and the bridge stands at the+// IPC boundary. Main's side of the contract (what `released` carries, when an+// open resolves) is certified against the real AppService in+// src/__tests__/embedOwnership.property.test.ts.++const BOUNDS: Bounds = { x: 0, y: 40, width: 800, height: 600 }+const TAB_A: TabId = 'ws-tab-2'+const TAB_B: TabId = 'ws-tab-3'++type Deferred = { promise: Promise<unknown>; resolve(): void; reject(error: Error): void }++function deferred(): Deferred {+ let resolve: () => void = () => {}+ let reject: (error: Error) => void = () => {}+ const promise = new Promise<unknown>((res, rej) => {+ resolve = () => res(undefined)+ reject = rej+ })+ return { promise, resolve, reject }+}++function launch(launchId: LaunchId, tabId: TabId = TAB_A, overrides: Partial<Launch> = {}): Launch {+ return {+ launchId,+ tabId,+ appRef: 'sandbox-recipes/alpha',+ route: { kind: 'explicit', routePath: `/r/${launchId}` },+ app: { label: 'Alpha', defaultPath: '/home' },+ ...overrides,+ }+}++function harness(overrides: Partial<EmbedOwnershipMachineDeps> = {}) {+ const log: string[] = []+ const opens = new Map<LaunchId, Deferred>()+ const closes = new Map<LaunchId, Deferred>()+ let tabs: WorkspaceTabsState = openAppTab(+ openAppTab(createWorkspaceTabsState('chat-tab-1'), {+ id: TAB_A,+ appRef: 'sandbox-recipes/alpha',+ title: 'Alpha',+ }),+ { id: TAB_B, appRef: 'sandbox-recipes/beta', title: 'Beta' }+ )+ const bridge = {+ open: vi.fn((request: EmbedOpenRequest) => {+ log.push(`open:${request.launchId}`)+ const d = deferred()+ opens.set(request.launchId, d)+ return d.promise+ }),+ close: vi.fn(({ launchId }: { launchId: LaunchId }) => {+ log.push(`close:${launchId}`)+ const d = deferred()+ closes.set(launchId, d)+ return d.promise+ }),+ }+ const updateTabs = vi.fn((updater: (state: WorkspaceTabsState) => WorkspaceTabsState) => {+ tabs = updater(tabs)+ })+ const machine = createEmbedOwnershipMachine({ bridge, updateTabs, ...overrides })+ return {+ machine,+ bridge,+ log,+ opens,+ closes,+ updateTabs,+ tabs: () => tabs,+ }+}++const flush = () => new Promise<void>(resolve => setTimeout(resolve, 0))++/** A measurer that answers immediately. */+const measured: EmbedSlotMeasurer = async () => BOUNDS++async function mountedOwner(h: ReturnType<typeof harness>, l: Launch) {+ h.machine.registerMeasurer(measured)+ h.machine.projected(l.tabId)+ h.machine.intent(l)+ await flush()+ h.opens.get(l.launchId)!.resolve()+ await flush()+ expect(h.machine.getSnapshot().views.get(l.launchId)?.phase).toBe('mounted')+}++describe('embed ownership machine — external store', () => {+ it('keeps the same snapshot and notifies nobody when a transition changes nothing', () => {+ const h = harness()+ const listener = vi.fn()+ h.machine.subscribe(listener)+ h.machine.projected(TAB_A)+ const snapshot = h.machine.getSnapshot()+ expect(listener).toHaveBeenCalledTimes(1)++ h.machine.projected(TAB_A)++ expect(h.machine.getSnapshot()).toBe(snapshot)+ expect(listener).toHaveBeenCalledTimes(1)+ })++ it('stops notifying a listener once it unsubscribes', () => {+ const h = harness()+ const listener = vi.fn()+ const unsubscribe = h.machine.subscribe(listener)+ unsubscribe()+ h.machine.projected(TAB_A)+ expect(listener).not.toHaveBeenCalled()+ })+})++describe('embed ownership machine — IPC ordering', () => {+ it('invokes the close of a launch in the same tick as its open when both come out back to back', () => {+ const h = harness()+ const l = launch('l-1')+ h.machine.projected(TAB_A)+ h.machine.intent(l)+ expect(h.machine.getSnapshot().views.get('l-1')?.phase).toBe('measuring')++ // The slot answers and, before any await, the user leaves the tab.+ h.machine.dispatch({ type: 'slotMeasured', launchId: 'l-1', bounds: BOUNDS })+ h.machine.projected(TAB_B)++ expect(h.log).toEqual(['open:l-1', 'close:l-1'])+ })++ it('sends a close while the open it undoes is still in flight', () => {+ const h = harness()+ h.machine.projected(TAB_A)+ h.machine.intent(launch('l-1'))+ h.machine.dispatch({ type: 'slotMeasured', launchId: 'l-1', bounds: BOUNDS })+ expect(h.bridge.open).toHaveBeenCalledTimes(1)++ h.machine.backToApps()++ expect(h.bridge.close).toHaveBeenCalledWith({ launchId: 'l-1' })+ expect(h.log).toEqual(['open:l-1', 'close:l-1'])+ })+})++describe('embed ownership machine — open request', () => {+ it('settles an open the bridge throws on at once, so no close follows it to main', () => {+ const h = harness()+ h.bridge.open.mockImplementationOnce((request: EmbedOpenRequest) => {+ h.log.push(`open-threw:${request.launchId}`)+ throw new Error('bridge unavailable')+ })+ h.machine.projected(TAB_A)+ const settled = h.machine.registerWhenSettled('l-0')+ h.machine.intent(launch('l-0'))++ // The slot answers and, in the same tick, the user leaves the tab.+ h.machine.dispatch({ type: 'slotMeasured', launchId: 'l-0', bounds: BOUNDS })+ h.machine.projected(TAB_B)++ expect(h.log).toEqual(['open-threw:l-0'])+ expect(h.machine.pendingWhenSettled()).toBe(0)+ return expect(settled).resolves.toBe('failed')+ })++ it('builds the open from the launch, the measured bounds and the route the reducer chose', async () => {+ const h = harness()+ h.machine.registerMeasurer(measured)+ h.machine.projected(TAB_A)+ h.machine.intent(launch('l-1'))+ await flush()++ expect(h.bridge.open).toHaveBeenCalledWith({+ launchId: 'l-1',+ recipeNs: 'sandbox-recipes',+ recipeName: 'alpha',+ title: 'Alpha',+ defaultPath: '/home',+ routePath: '/r/l-1',+ bounds: BOUNDS,+ })+ })++ it('never sends an empty route: the default route is sent as no route', async () => {+ const h = harness()+ h.machine.registerMeasurer(measured)+ h.machine.projected(TAB_A)+ h.machine.intent(launch('l-1', TAB_A, { route: { kind: 'explicit', routePath: '' } }))+ await flush()++ expect(h.bridge.open).toHaveBeenCalledTimes(1)+ expect(h.bridge.open.mock.calls[0]![0]).not.toHaveProperty('routePath')+ })++ it('fails a launch whose app reference names no recipe without calling main', async () => {+ const h = harness()+ h.machine.registerMeasurer(measured)+ h.machine.projected(TAB_A)+ const l = launch('l-1', TAB_A, { appRef: 'sandbox-recipes/a/b' })+ const settled = h.machine.registerWhenSettled('l-1')+ h.machine.intent(l)+ await flush()++ expect(h.bridge.open).not.toHaveBeenCalled()+ await expect(settled).resolves.toBe('failed')+ expect(h.machine.getSnapshot().failure).toMatchObject({ launchId: 'l-1', kind: 'open' })+ })++ it('settles mounted when main resolves the open, failed with its message when it rejects', async () => {+ const h = harness()+ h.machine.registerMeasurer(measured)+ h.machine.projected(TAB_A)+ const first = h.machine.registerWhenSettled('l-1')+ h.machine.intent(launch('l-1'))+ await flush()+ h.opens.get('l-1')!.resolve()+ await expect(first).resolves.toBe('mounted')++ const second = h.machine.registerWhenSettled('l-2')+ h.machine.relaunch(launch('l-2'))+ h.machine.onReleased({ launchId: 'l-1', reason: 'closed', location: { routePath: '/r/l-1' } })+ await flush()+ h.opens.get('l-2')!.reject(new Error('mint refused'))+ await expect(second).resolves.toBe('failed')+ expect(h.machine.getSnapshot().failure).toEqual({+ tabId: TAB_A,+ launchId: 'l-2',+ kind: 'open',+ message: 'mint refused',+ })+ })++ it('forgets a view whose close main rejected', async () => {+ const h = harness()+ await mountedOwner(h, launch('l-1'))+ h.machine.backToApps()+ expect(h.machine.getSnapshot().views.get('l-1')?.phase).toBe('closeRequested')++ h.closes.get('l-1')!.reject(new Error('ipc down'))+ await flush()++ expect(h.machine.getSnapshot().views.size).toBe(0)+ })+})++describe('embed ownership machine — slot measurement', () => {+ it('waits for a registered measurer before measuring', async () => {+ const h = harness()+ h.machine.projected(TAB_A)+ h.machine.intent(launch('l-1'))+ await flush()+ expect(h.bridge.open).not.toHaveBeenCalled()++ const measurer = vi.fn(measured)+ h.machine.registerMeasurer(measurer)+ await flush()++ expect(measurer).toHaveBeenCalledWith('l-1')+ expect(h.bridge.open).toHaveBeenCalledTimes(1)+ })++ it('fails the launch on the slot when the measurer rejects', async () => {+ const h = harness()+ h.machine.registerMeasurer(async () => {+ throw new Error('no frame')+ })+ h.machine.projected(TAB_A)+ h.machine.intent(launch('l-1'))+ await flush()++ expect(h.bridge.open).not.toHaveBeenCalled()+ expect(h.machine.getSnapshot().failure).toMatchObject({ launchId: 'l-1', kind: 'slot' })+ })++ it('stops using a measurer once it unregisters', async () => {+ const h = harness()+ const measurer = vi.fn(measured)+ h.machine.registerMeasurer(measurer)()+ h.machine.projected(TAB_A)+ h.machine.intent(launch('l-1'))+ await flush()+ expect(measurer).not.toHaveBeenCalled()+ })+})++describe('embed ownership machine — tab store writes', () => {+ it('persists the route a released view reports on its own tab', async () => {+ const h = harness()+ await mountedOwner(h, launch('l-1'))+ h.machine.backToApps()++ h.machine.onReleased({ launchId: 'l-1', reason: 'closed', location: { routePath: '/inbox' } })++ expect(h.tabs().tabs.find(tab => tab.id === TAB_A)?.app?.savedRoutePath).toBe('/inbox')+ })++ it('clears the saved route when the view reports the default route', async () => {+ const h = harness()+ await mountedOwner(h, launch('l-1'))+ h.machine.onReleased({ launchId: 'l-1', reason: 'closed', location: { routePath: '/x' } })+ h.machine.relaunch(launch('l-2'))+ await flush()+ h.opens.get('l-2')!.resolve()+ await flush()+ h.machine.backToApps()++ h.machine.onReleased({ launchId: 'l-2', reason: 'closed', location: {} })++ const tab = h.tabs().tabs.find(t => t.id === TAB_A)+ expect(tab?.app).toEqual({ appRef: 'sandbox-recipes/alpha' })+ })++ it('leaves the store untouched when the tab is gone', async () => {+ const h = harness()+ await mountedOwner(h, launch('l-1', 'ws-tab-gone'))+ const before = h.tabs()+ h.machine.backToApps()++ h.machine.onReleased({ launchId: 'l-1', reason: 'closed', location: { routePath: '/inbox' } })++ expect(h.updateTabs).toHaveBeenCalled()+ expect(h.tabs()).toBe(before)+ })++ it("renames the owner's tab after its title and ignores titles of other launches", async () => {+ const h = harness()+ await mountedOwner(h, launch('l-1'))++ h.machine.onTitleChanged({ launchId: 'l-1', title: 'Alpha Inbox' })+ h.machine.onTitleChanged({ launchId: 'l-stale', title: 'Stale' })++ expect(h.tabs().tabs.find(tab => tab.id === TAB_A)?.title).toBe('Alpha Inbox')+ })++ it('keeps running the IPC effects of a transition when a store write throws', async () => {+ const h = harness()+ await mountedOwner(h, launch('l-1'))+ h.machine.relaunch(launch('l-2'))+ h.machine.onReleased({ launchId: 'l-1', reason: 'closed', location: { routePath: '/x' } })+ await flush()+ h.opens.get('l-2')!.resolve()+ await flush()+ h.updateTabs.mockImplementation(() => {+ throw new Error('store gone')+ })+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})++ // l-3 replaces l-2: the sweep closes l-2 in the same transition.+ h.machine.relaunch(launch('l-3'))+ h.machine.onReleased({ launchId: 'l-2', reason: 'closed', location: { routePath: '/y' } })++ expect(h.bridge.close).toHaveBeenCalledWith({ launchId: 'l-2' })+ expect(h.machine.getSnapshot().views.get('l-3')?.phase).toBe('measuring')+ error.mockRestore()+ })+})++describe('embed ownership machine — notifications', () => {+ it("reports only the owner's refresh failures", async () => {+ const onOwnerRefreshError = vi.fn()+ const h = harness({ onOwnerRefreshError })+ await mountedOwner(h, launch('l-1'))++ h.machine.onRefreshError({ launchId: 'l-old', message: 'stale' })+ h.machine.onRefreshError({ launchId: 'l-1', message: 'live' })++ expect(onOwnerRefreshError).toHaveBeenCalledTimes(1)+ expect(onOwnerRefreshError).toHaveBeenCalledWith({ launchId: 'l-1', message: 'live' })+ })++ it('announces a handoff once the views it waits for are gone', async () => {+ const onHandoffReady = vi.fn()+ const h = harness({ onHandoffReady })+ await mountedOwner(h, launch('l-1'))++ h.machine.handoff(7)+ expect(onHandoffReady).not.toHaveBeenCalled()+ h.machine.onReleased({ launchId: 'l-1', reason: 'closed', location: null })++ expect(onHandoffReady).toHaveBeenCalledWith(7)+ })++ it('resolves a launch that never got its tab as abandoned, in the same dispatch', async () => {+ const h = harness()+ h.machine.projected(TAB_B)+ const settled = h.machine.registerWhenSettled('l-1')++ h.machine.intent(launch('l-1', TAB_A))++ expect(h.machine.pendingWhenSettled()).toBe(0)+ await expect(settled).resolves.toBe('abandoned')+ })++ // The seam registers, dispatches, and only then reads `whenSettled`: a launch+ // that settles inside that dispatch must still hand out its outcome.+ it('hands out the outcome of a launch abandoned in its own dispatch for an inactive tab', async () => {+ const h = harness()+ h.machine.projected(TAB_B)+ h.machine.registerWhenSettled('l-1')+ h.machine.intent(launch('l-1', TAB_A))++ await expect(h.machine.whenSettled('l-1')).resolves.toBe('abandoned')+ })++ it('hands out the outcome of a re-click abandoned in its own dispatch', async () => {+ const h = harness()+ await mountedOwner(h, launch('l-1'))+ h.machine.registerWhenSettled('l-2')+ h.machine.intent(launch('l-2'))++ await expect(h.machine.whenSettled('l-2')).resolves.toBe('abandoned')+ expect(h.machine.getSnapshot().owner).toBe('l-1')+ })++ it('returns the same settled promise when a launch is registered again', async () => {+ const h = harness()+ h.machine.projected(TAB_B)+ const first = h.machine.registerWhenSettled('l-1')+ h.machine.intent(launch('l-1', TAB_A))++ expect(h.machine.registerWhenSettled('l-1')).toBe(first)+ await expect(h.machine.registerWhenSettled('l-1')).resolves.toBe('abandoned')+ expect(h.machine.pendingWhenSettled()).toBe(0)+ })++ it('hands out the pending promise of a registered launch until it settles, and after', async () => {+ const h = harness()+ h.machine.registerMeasurer(measured)+ h.machine.projected(TAB_A)+ const registered = h.machine.registerWhenSettled('l-1')+ h.machine.intent(launch('l-1'))++ expect(h.machine.whenSettled('l-1')).toBe(registered)+ expect(h.machine.pendingWhenSettled()).toBe(1)+ await flush()+ h.opens.get('l-1')!.resolve()+ await expect(registered).resolves.toBe('mounted')+ expect(h.machine.whenSettled('l-1')).toBe(registered)+ expect(h.machine.pendingWhenSettled()).toBe(0)+ })+})++describe('embed ownership machine — re-entrant dispatch', () => {+ it('finishes the effects of a transition before reducing what its callbacks dispatch', () => {+ const seenAtNestedIntent: number[] = []+ let machine: ReturnType<typeof harness>['machine'] | null = null+ const h = harness({+ // A deep-link continuation: once the handoff is ready it activates its+ // target tab and launches it, synchronously, from inside the effect.+ onHandoffReady: () => {+ machine!.projected(TAB_B)+ machine!.intent(launch('l-2', TAB_B))+ },+ onTransition: ({ event }) => {+ if (event.type === 'intent' && event.launch.launchId === 'l-2') {+ seenAtNestedIntent.push(machine!.pendingWhenSettled())+ }+ },+ })+ machine = h.machine+ h.machine.projected(TAB_A)+ h.machine.registerWhenSettled('l-1')+ // No measurer yet: l-1 stays in the slot measurement.+ h.machine.intent(launch('l-1'))++ // The handoff drops l-1 (never sent to main), is ready at once, and settles+ // l-1 as abandoned after announcing the handoff.+ h.machine.handoff(7)++ expect(seenAtNestedIntent).toEqual([0])+ expect(h.machine.getSnapshot().owner).toBe('l-2')+ expect(h.log).toEqual([])+ })++ it('settles an open it refuses ahead of events already queued, so no close goes out for it', async () => {+ let machine: ReturnType<typeof harness>['machine'] | null = null+ let reenter = false+ const h = harness({+ // A store write that synchronously commits and dispatches, as a layout+ // effect could: the slot answers and the user leaves the tab.+ updateTabs: () => {+ if (!reenter) return+ reenter = false+ machine!.dispatch({ type: 'slotMeasured', launchId: 'l-bad', bounds: BOUNDS })+ machine!.projected(TAB_B)+ },+ })+ machine = h.machine+ await mountedOwner(h, launch('l-0'))+ h.machine.relaunch(launch('l-bad', TAB_A, { appRef: 'not-a-recipe' }))+ reenter = true++ h.machine.onReleased({ launchId: 'l-0', reason: 'closed', location: { routePath: '/x' } })++ expect(h.bridge.close.mock.calls.map(([request]) => request.launchId)).toEqual(['l-0'])+ expect(h.bridge.open.mock.calls.map(([request]) => request.launchId)).toEqual(['l-0'])+ expect(h.machine.getSnapshot().views.size).toBe(0)+ })+})++describe('embed ownership machine — dispose', () => {+ it('ignores events, measurements and IPC outcomes that arrive after dispose', async () => {+ const h = harness()+ let answerSlot: (bounds: Bounds) => void = () => {}+ h.machine.registerMeasurer(() => new Promise<Bounds>(resolve => (answerSlot = resolve)))+ h.machine.projected(TAB_A)+ h.machine.intent(launch('l-1'))+ h.machine.dispatch({ type: 'slotMeasured', launchId: 'l-1', bounds: BOUNDS })+ const listener = vi.fn()+ h.machine.subscribe(listener)+ const snapshot = h.machine.getSnapshot()+ const tabs = h.tabs()++ h.machine.dispose()+ answerSlot(BOUNDS)+ h.opens.get('l-1')!.resolve()+ h.machine.onReleased({ launchId: 'l-1', reason: 'closed', location: { routePath: '/x' } })+ h.machine.onTitleChanged({ launchId: 'l-1', title: 'Late' })+ h.machine.onRefreshError({ launchId: 'l-1', message: 'late' })+ h.machine.projected(TAB_B)+ await flush()++ expect(h.machine.getSnapshot()).toBe(snapshot)+ expect(listener).not.toHaveBeenCalled()+ expect(h.updateTabs).not.toHaveBeenCalled()+ expect(h.tabs()).toBe(tabs)+ expect(h.bridge.close).not.toHaveBeenCalled()+ })++ it('tolerates a rejected open and close after dispose', async () => {+ const h = harness()+ await mountedOwner(h, launch('l-1'))+ h.machine.relaunch(launch('l-2'))+ h.machine.dispose()++ h.closes.get('l-1')!.reject(new Error('late'))+ await flush()++ expect(h.machine.getSnapshot().views.get('l-1')?.phase).toBe('closeRequested')+ })+})diff --git a/desktop-app/ui/src/lib/embedOwnershipMachine.ts b/desktop-app/ui/src/lib/embedOwnershipMachine.tsnew file mode 100644index 000000000..3349e25bc--- /dev/null+++ b/desktop-app/ui/src/lib/embedOwnershipMachine.ts@@ -0,0 +1,271 @@+import { createEmbedOwnershipState, reduceEmbedOwnership } from './embedOwnership'+import type {+ EmbedEffect,+ EmbedEvent,+ EmbedOwnershipState,+ Launch,+ LaunchId,+ LaunchOutcome,+} from './embedOwnership.types'+import type {+ EmbedOpenRequest,+ EmbedOwnershipMachine,+ EmbedOwnershipMachineDeps,+ EmbedSlotMeasurer,+} from './embedOwnershipMachine.types'+import { setAppTabSavedRoutePath, setAppTabTitle } from './workspaceTabs'++/**+ * Runs `reduceEmbedOwnership` against the outside world. It owns no decision:+ * every choice is the reducer's; this only turns effects into calls and call+ * outcomes back into events.+ *+ * `sendOpen` and `close` are invoked synchronously while walking a transition's+ * effects, in their order, and only the promises they return are awaited. Main+ * serves opens and closes in arrival order, so deferring one of the two calls+ * would let a close overtake the open it is meant to undo and leave a view+ * nobody owns.+ */+export function createEmbedOwnershipMachine(+ deps: EmbedOwnershipMachineDeps+): EmbedOwnershipMachine {+ let state: EmbedOwnershipState = createEmbedOwnershipState()+ let disposed = false+ const listeners = new Set<() => void>()+ // Events raised while a transition's effects are still running wait here, so+ // each transition's effects all run before the next event is reduced.+ const queue: EmbedEvent[] = []+ let draining = false+ let measurer: EmbedSlotMeasurer | null = null+ const awaitingMeasurer: LaunchId[] = []+ // Kept after settling: the seam registers a launch, dispatches it and only+ // then asks for its promise, and a launch can settle inside that dispatch.+ const settleWaiters = new Map<+ LaunchId,+ { promise: Promise<LaunchOutcome>; resolve: (outcome: LaunchOutcome) => void }+ >()+ const unsettled = new Set<LaunchId>()++ function dispatch(event: EmbedEvent): void {+ if (disposed) return+ queue.push(event)+ if (draining) return+ draining = true+ const before = state+ try {+ while (queue.length > 0 && !disposed) {+ const next = queue.shift()!+ const previous = state+ const transition = reduceEmbedOwnership(previous, next)+ state = transition.state+ deps.onTransition?.({+ event: next,+ previous,+ next: transition.state,+ effects: transition.effects,+ })+ for (const effect of transition.effects) runEffect(effect)+ }+ } finally {+ draining = false+ if (disposed) queue.length = 0+ }+ if (state !== before && !disposed) {+ for (const listener of [...listeners]) listener()+ }+ }++ function runEffect(effect: EmbedEffect): void {+ if (disposed) return+ // One failing effect must not keep the IPC effects after it from running.+ try {+ switch (effect.type) {+ case 'measure':+ requestMeasure(effect.launchId)+ return+ case 'sendOpen':+ sendOpen(effect.launch, effect.bounds, effect.routePath)+ return+ case 'close':+ sendClose(effect.launchId)+ return+ case 'persistRoute': {+ const routePath = effect.route.action === 'set' ? effect.route.routePath : undefined+ deps.updateTabs(tabs => setAppTabSavedRoutePath(tabs, effect.tabId, routePath))+ return+ }+ case 'setTitle':+ deps.updateTabs(tabs => setAppTabTitle(tabs, effect.tabId, effect.title))+ return+ case 'handoffReady':+ deps.onHandoffReady?.(effect.requestId)+ return+ case 'launchSettled':+ settle(effect.launchId, effect.outcome)+ return+ }+ } catch (error) {+ console.error('[embedOwnership] effect failed:', effect.type, error)+ }+ }++ function requestMeasure(launchId: LaunchId): void {+ if (measurer) startMeasure(launchId, measurer)+ else awaitingMeasurer.push(launchId)+ }++ function startMeasure(launchId: LaunchId, measure: EmbedSlotMeasurer): void {+ let pending: Promise<EmbedOpenRequest['bounds'] | null>+ try {+ pending = measure(launchId)+ } catch {+ pending = Promise.resolve(null)+ }+ pending.then(+ bounds => dispatch({ type: 'slotMeasured', launchId, bounds: bounds ?? null }),+ () => dispatch({ type: 'slotMeasured', launchId, bounds: null })+ )+ }++ function sendOpen(launch: Launch, bounds: EmbedOpenRequest['bounds'], routePath?: string): void {+ const recipe = parseAppRef(launch.appRef)+ if (!recipe) {+ // Main would refuse it anyway. Settled ahead of anything already queued:+ // an earlier queued event could otherwise sweep this launch and send main+ // a close for an open it never received.+ queue.unshift({+ type: 'openSettled',+ launchId: launch.launchId,+ outcome: { failed: `Invalid app reference: ${launch.appRef}` },+ })+ return+ }+ const request: EmbedOpenRequest = {+ launchId: launch.launchId,+ ...recipe,+ // From the trusted renderer's app list, never from the plugin: main shows it+ // in consent prompts and notification attribution as the app's name.+ ...(launch.app.label ? { title: launch.app.label } : {}),+ ...(launch.app.defaultPath ? { defaultPath: launch.app.defaultPath } : {}),+ // '' is the default route, which main expresses as no route at all.+ ...(routePath ? { routePath } : {}),+ bounds,+ }+ let pending: Promise<unknown>+ try {+ pending = deps.bridge.open(request)+ } catch (error) {+ // The open never left the renderer: settled like a refused app reference,+ // ahead of anything queued, so no close can follow it to main.+ queue.unshift({+ type: 'openSettled',+ launchId: launch.launchId,+ outcome: { failed: error instanceof Error ? error.message : String(error) },+ })+ return+ }+ pending.then(+ () => dispatch({ type: 'openSettled', launchId: launch.launchId, outcome: 'mounted' }),+ error =>+ dispatch({+ type: 'openSettled',+ launchId: launch.launchId,+ outcome: { failed: error instanceof Error ? error.message : String(error) },+ })+ )+ }++ function sendClose(launchId: LaunchId): void {+ let pending: Promise<unknown>+ try {+ pending = deps.bridge.close({ launchId })+ } catch (error) {+ pending = Promise.reject(error)+ }+ pending.then(undefined, () => dispatch({ type: 'closeFailed', launchId }))+ }++ function waiterFor(launchId: LaunchId) {+ const existing = settleWaiters.get(launchId)+ if (existing) return existing+ let resolve: (outcome: LaunchOutcome) => void = () => {}+ const promise = new Promise<LaunchOutcome>(r => (resolve = r))+ const waiter = { promise, resolve }+ settleWaiters.set(launchId, waiter)+ unsettled.add(launchId)+ return waiter+ }++ /** Only the first outcome counts; a launch settles once. */+ function settle(launchId: LaunchId, outcome: LaunchOutcome): void {+ const known = settleWaiters.has(launchId)+ if (known && !unsettled.has(launchId)) return+ waiterFor(launchId).resolve(outcome)+ unsettled.delete(launchId)+ }++ function registerWhenSettled(launchId: LaunchId): Promise<LaunchOutcome> {+ return waiterFor(launchId).promise+ }++ return {+ subscribe(listener) {+ if (disposed) return () => {}+ listeners.add(listener)+ return () => {+ listeners.delete(listener)+ }+ },+ getSnapshot: () => state,+ dispatch,+ projected: activeAppTabId => dispatch({ type: 'projected', activeAppTabId }),+ intent: launch => dispatch({ type: 'intent', launch }),+ relaunch: launch => dispatch({ type: 'relaunch', launch }),+ backToApps: () => dispatch({ type: 'backToApps' }),+ handoff: requestId => dispatch({ type: 'handoff', requestId }),+ onReleased: event =>+ dispatch({+ type: 'released',+ launchId: event.launchId,+ reason: event.reason,+ location: event.location,+ }),+ onTitleChanged: event =>+ dispatch({ type: 'titleChanged', launchId: event.launchId, title: event.title }),+ // Read at arrival: a failure of a view the user already left must not+ // surface on the launch that replaced it.+ onRefreshError: event => {+ if (disposed || event.launchId !== state.owner) return+ deps.onOwnerRefreshError?.(event)+ },+ registerMeasurer(next) {+ if (disposed) return () => {}+ measurer = next+ for (const launchId of awaitingMeasurer.splice(0)) startMeasure(launchId, next)+ return () => {+ if (measurer === next) measurer = null+ }+ },+ registerWhenSettled,+ whenSettled: launchId => settleWaiters.get(launchId)?.promise,+ pendingWhenSettled: () => unsettled.size,+ // Pending `whenSettled` promises are left unresolved: whoever awaits them+ // belongs to the renderer being torn down and must not act afterwards.+ dispose() {+ disposed = true+ listeners.clear()+ measurer = null+ awaitingMeasurer.length = 0+ queue.length = 0+ },+ }+}++function parseAppRef(appRef: string): { recipeNs: string; recipeName: string } | null {+ const slash = appRef.indexOf('/')+ if (slash <= 0) return null+ const recipeNs = appRef.slice(0, slash)+ const recipeName = appRef.slice(slash + 1)+ if (!recipeName || recipeName.includes('/')) return null+ return { recipeNs, recipeName }+}diff --git a/desktop-app/ui/src/lib/embedOwnershipMachine.types.ts b/desktop-app/ui/src/lib/embedOwnershipMachine.types.tsnew file mode 100644index 000000000..07e9f40d4--- /dev/null+++ b/desktop-app/ui/src/lib/embedOwnershipMachine.types.ts@@ -0,0 +1,85 @@+import type { SandboxUiReleasedEvent } from '../../../src/types'+import type {+ Bounds,+ EmbedEffect,+ EmbedEvent,+ EmbedOwnershipState,+ Launch,+ LaunchId,+ LaunchOutcome,+} from './embedOwnership.types'+import type { WorkspaceTabsState } from './workspaceTabs.types'++/** The `sandboxUi.open` request, as the preload bridge takes it. */+export type EmbedOpenRequest = {+ launchId: LaunchId+ recipeNs: string+ recipeName: string+ title?: string+ defaultPath?: string+ routePath?: string+ bounds: Bounds+}++/**+ * The two lifecycle calls into main. Each must be invoked by the caller in the+ * order the machine asks for them and without deferring the call itself; only+ * the returned promise is awaited.+ */+export type EmbedOwnershipBridge = {+ open(request: EmbedOpenRequest): Promise<unknown>+ close(request: { launchId: LaunchId }): Promise<unknown>+}++/** Measures the embed slot for a launch; `null` when it never became measurable. */+export type EmbedSlotMeasurer = (launchId: LaunchId) => Promise<Bounds | null>++export type EmbedTabsUpdater = (state: WorkspaceTabsState) => WorkspaceTabsState++export type EmbedRefreshErrorEvent = { launchId: LaunchId; message: string }++export type EmbedTitleChangedEvent = { launchId: LaunchId; title: string }++export type EmbedOwnershipMachineDeps = {+ bridge: EmbedOwnershipBridge+ /** Writes into the tab store; the updater is a no-op for a tab that no longer exists. */+ updateTabs: (updater: EmbedTabsUpdater) => void+ onHandoffReady?: (requestId: number) => void+ /** Only refresh failures of the launch that owns the embed when they arrive. */+ onOwnerRefreshError?: (event: EmbedRefreshErrorEvent) => void+ /** Observability for tests: every reduced event with the state around it and its effects. */+ onTransition?: (transition: {+ event: EmbedEvent+ previous: EmbedOwnershipState+ next: EmbedOwnershipState+ effects: readonly EmbedEffect[]+ }) => void+}++export type EmbedOwnershipMachine = {+ subscribe(listener: () => void): () => void+ /** The reducer state; the same reference until a transition changes it. */+ getSnapshot(): EmbedOwnershipState+ dispatch(event: EmbedEvent): void+ projected(activeAppTabId: string | null): void+ intent(launch: Launch): void+ relaunch(launch: Launch): void+ backToApps(): void+ handoff(requestId: number): void+ /** Inlets for main's per-view events. */+ onReleased(event: SandboxUiReleasedEvent): void+ onTitleChanged(event: EmbedTitleChangedEvent): void+ onRefreshError(event: EmbedRefreshErrorEvent): void+ /** The page registers while its slot exists; measures wait until one is registered. */+ registerMeasurer(measurer: EmbedSlotMeasurer): () => void+ /**+ * Called before the launch is dispatched; resolves with its single outcome.+ * Registering again, even after it settled, returns the same promise.+ */+ registerWhenSettled(launchId: LaunchId): Promise<LaunchOutcome>+ /** The promise of a registered launch, settled or not. */+ whenSettled(launchId: LaunchId): Promise<LaunchOutcome> | undefined+ /** Registered launches that have not settled yet. */+ pendingWhenSettled(): number+ dispose(): void+}