test: retire synthetic browser and document host suites

This commit is contained in:
OrcaWin
2026-11-12 10:44:36 -08:00
parent 9a9cefa192
commit fd15e03ef0
3 changed files with 4 additions and 394 deletions
File diff suppressed because one or more lines are too long
@@ -1,167 +0,0 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it } from 'vitest'
import { createTerminalDocument } from './create-terminal-document'
import { terminalDocumentDouble } from './document-terminal-double.test-support'
import { TERMINAL_DOCUMENT_MARKUP } from '../terminal-webview-html'
function plantHost(id: string) {
const host = document.createElement('div')
host.id = id
host.innerHTML = TERMINAL_DOCUMENT_MARKUP
document.body.appendChild(host)
return host
}
function startDocumentIn(host: HTMLElement) {
const engine = terminalDocumentDouble()
const posted: Array<Record<string, unknown>> = []
const started = createTerminalDocument({
root: host,
postToHost: (message) => {
posted.push(message)
},
hasEngine: () => true,
installHostTransport: () => () => {},
installErrorReporter: () => () => {},
paintDocumentBackground: () => {},
createTerminal: () => engine.terminal,
createUnicode11Addon: () => null,
createWebglAddon: () => null
})
started.send({ type: 'init', cols: 80, rows: 24, initialData: '', preserveScroll: false })
return { started, openedOn: engine.openedOn, posted }
}
type PlantedFinger = { surface: HTMLElement; identifier: number; x?: number; y?: number }
// Dispatch on document with page-wide touches so both terminal scopes receive the event and must filter ownership.
function fireTouch(type: string, fingers: PlantedFinger[], target: HTMLElement) {
const event = new Event(type, { bubbles: true, cancelable: true })
Object.defineProperty(event, 'touches', {
value: fingers.map((finger) => ({
identifier: finger.identifier,
clientX: finger.x ?? 10,
clientY: finger.y ?? 10,
target: finger.surface
}))
})
Object.defineProperty(event, 'target', { value: target })
document.dispatchEvent(event)
}
function fireTwoFingerTouchStart(surface: HTMLElement) {
fireTouch(
'touchstart',
[
{ surface, identifier: 0, x: 10 },
{ surface, identifier: 1, x: 30 }
],
surface
)
}
function elementOf(host: HTMLElement, id: string) {
const element = host.querySelector<HTMLElement>(`#${id}`)
if (element === null) {
throw new Error(`${host.id} carries no #${id}`)
}
return element
}
const surfaceOf = (host: HTMLElement) => elementOf(host, 'terminal-surface')
function selectAllInBoth(...documents: Array<ReturnType<typeof startDocumentIn>>) {
for (const started of documents) {
started.started.send({ type: 'do-select-all' })
expect(started.posted.map((message) => message.type)).toContain('set-select-mode')
started.posted.length = 0
}
}
const pinchCancels = (posted: Array<Record<string, unknown>>) =>
posted.filter((message) => message.type === 'mobile-clip-cancel-by-pinch')
// Stack transitions overlap terminal mounts with duplicate markup ids; assert each engine opens its own host surface.
describe('two terminal documents on one page', () => {
beforeEach(() => {
document.body.innerHTML = ''
})
it('opens each engine on the surface inside its own host', () => {
const first = plantHost('first-host')
const second = plantHost('second-host')
expect(first.querySelector('#terminal-surface')).not.toBe(null)
expect(second.querySelector('#terminal-surface')).not.toBe(null)
const one = startDocumentIn(first)
const two = startDocumentIn(second)
expect(first.contains(one.openedOn() ?? null)).toBe(true)
expect(second.contains(two.openedOn() ?? null)).toBe(true)
one.started.stop()
two.started.stop()
})
// A pinch in another host must not clear this terminal’s selection before target filtering.
it('leaves the other document alone when two fingers land in that other host', () => {
const first = plantHost('first-host')
const second = plantHost('second-host')
const one = startDocumentIn(first)
const two = startDocumentIn(second)
selectAllInBoth(one, two)
fireTwoFingerTouchStart(surfaceOf(second))
expect(pinchCancels(one.posted)).toHaveLength(0)
expect(one.posted).toEqual([])
expect(pinchCancels(two.posted)).toHaveLength(1)
one.started.stop()
two.started.stop()
})
// Event ownership is not enough: page-wide touches must also exclude fingers in the other terminal.
it("does not read another host's finger as its own second one", () => {
const first = plantHost('first-host')
const second = plantHost('second-host')
const one = startDocumentIn(first)
const two = startDocumentIn(second)
selectAllInBoth(two)
const held = { surface: surfaceOf(first), identifier: 0 }
// Use B’s menu pill so a local tap preserves selection; surface taps dismiss it by design.
const pill = elementOf(second, 'selection-overlay')
fireTouch('touchstart', [held], held.surface)
one.posted.length = 0
two.posted.length = 0
fireTouch('touchstart', [held, { surface: pill, identifier: 1 }], pill)
expect(pinchCancels(two.posted)).toHaveLength(0)
expect(two.posted).toEqual([])
one.started.stop()
two.started.stop()
})
// A finger in A must not prevent B’s last-finger touchend from firing its tap.
it('fires its own surface tap while the other host still has a finger down', () => {
const first = plantHost('first-host')
const second = plantHost('second-host')
const one = startDocumentIn(first)
const two = startDocumentIn(second)
const held = { surface: surfaceOf(first), identifier: 0 }
const tapping = { surface: surfaceOf(second), identifier: 1, x: 20, y: 5 }
fireTouch('touchstart', [held], held.surface)
fireTouch('touchstart', [held, tapping], tapping.surface)
two.posted.length = 0
fireTouch('touchend', [held], tapping.surface)
expect(two.posted.map((message) => message.type)).toContain('terminal-tap')
one.started.stop()
two.started.stop()
})
})
@@ -1,217 +0,0 @@
import type { Session, WebContents } from 'electron'
import { describe, expect, it, vi } from 'vitest'
import type { BrowserClientHostCommandEvent } from '../../../../shared/browser/client-hosting/browser-client-host-protocol'
import { BrowserClientHostCommandDispatcher } from '../../client-hosts/commands/browser-client-host-command-dispatcher'
import { BrowserClientPageCommandExecutor } from './browser-client-page-command-executor'
import { createBrowserRoutePartitionBindingStoreFake } from '../../routing/partitions/browser-route-partition-binding-store-fake'
import { BrowserRouteSessionRegistry } from '../../routing/sessions/browser-route-session-registry'
import { BrowserRouteWebContentsRegistry } from '../../routing/guest-authority/browser-route-webcontents-registry'
const partition = `persist:orca-browser-v1-${'b'.repeat(64)}`
describe('BrowserClientPageCommandExecutor integration', () => {
it('composes exact route, Session, navigation, and spontaneous destroyed cleanup', async () => {
const routeSession = {
setProxy: vi.fn(async () => {}),
closeAllConnections: vi.fn(async () => {}),
resolveProxy: vi.fn(async () => 'SOCKS5 127.0.0.1:43123')
}
const clearPolicies = vi.fn()
let webContentsRegistry: BrowserRouteWebContentsRegistry | null = null
const sessionRegistry = new BrowserRouteSessionRegistry({
derivePartition: () => ({ partition, bindingFingerprint: 'binding-a' }),
validateProfile: vi.fn(),
getSession: () => routeSession,
setupPolicies: vi.fn(),
clearPolicies,
retirePageAuthority: (retirement) =>
webContentsRegistry?.retirePageAuthority(retirement) ?? false,
bindingStore: createBrowserRoutePartitionBindingStoreFake()
})
webContentsRegistry = new BrowserRouteWebContentsRegistry({
getPartitionForSession: (session) => sessionRegistry.getPartitionForSession(session),
getPreparedPageAuthority: (page) => sessionRegistry.getPreparedPageAuthority(page),
rekeyPreparedPage: (previous, next) => sessionRegistry.rekeyPreparedPage(previous, next),
retirePreparedPage: (page) => sessionRegistry.retirePreparedPage(page),
retirePreparedPagesOwnedByRenderer: (rendererWebContentsId) =>
sessionRegistry.retirePreparedPagesOwnedByRenderer(rendererWebContentsId)
})
const rekeyGuestLifecycle = vi.spyOn(webContentsRegistry, 'rekeyGuestLifecycle')
const grantReconciledNavigation = vi.spyOn(webContentsRegistry, 'grantReconciledNavigation')
const guest = createGuest(routeSession as unknown as Session)
const routeRelease = vi.fn()
const rendererRetire = vi.fn(async () => {
guest.destroy()
})
const rendererRekey = vi.fn(async () => {})
const executor = new BrowserClientPageCommandExecutor({
orcaProfileId: 'orca-profile-a',
authorityConnectionIdentity: 'authority-record-a',
pairingAuthorityConnectionIdentity: 'pairing-authority-record-a',
legacyAuthorityConnectionIdentity: 'legacy-authority-record-a',
storageScope: 'a'.repeat(64),
retainNetworkRoute: vi.fn(async () => ({
key: 'execution-host-a',
executionHostIdentity: 'execution-host-record-a',
legacyExecutionHostIdentity: 'legacy-execution-host-record-a',
proxyEndpoint: { host: '127.0.0.1' as const, port: 43123 },
release: routeRelease
})),
selectRenderer: () => ({
rendererWebContentsId: 11,
isCurrent: () => true,
mountPage: async () => {
expect(webContentsRegistry?.attachGuest(guest.webContents)).toBe(true)
return { webContentsId: 41 }
},
rekeyPage: rendererRekey,
retirePage: rendererRetire
}),
routeSessions: sessionRegistry,
executeAutomation: vi.fn(async () => undefined),
retireAutomation: vi.fn(async () => {}),
guestBinding: { bind: vi.fn(), release: vi.fn() },
routeWebContents: webContentsRegistry
})
await expect(executor.handle(createCommand('createPage'), signal())).resolves.toEqual({
status: 'completed'
})
expect(guest.webContents.setWebRTCIPHandlingPolicy).toHaveBeenCalledWith(
'disable_non_proxied_udp'
)
expect(sessionRegistry.isAllowedPartition(partition)).toBe(true)
expect(guest.url()).toBe('about:blank')
await expect(executor.handle(createCommand('navigate'), signal())).resolves.toEqual({
status: 'completed'
})
expect(guest.url()).toBe('https://example.internal/path')
const reclaim = createCommand('reclaimPage')
const dispatcher = new BrowserClientHostCommandDispatcher({
authority: reclaim,
handler: (event, commandSignal) => executor.handle(event, commandSignal)
})
const reclaimed = await dispatcher.dispatch(reclaim)
expect(rekeyGuestLifecycle).toHaveReturnedWith(expect.any(Object))
expect(grantReconciledNavigation).toHaveReturnedWith(true)
expect(reclaimed).toEqual({ status: 'completed' })
expect(rendererRekey).toHaveBeenCalledOnce()
expect(executor.hasPage('page-a', 7)).toBe(false)
expect(executor.hasPage('page-a', 8)).toBe(true)
expect(executor.snapshotPageInventory()).toEqual([
expect.objectContaining({
authorityEpoch: 'epoch-new',
pageHostGeneration: 8,
currentUrl: 'https://example.internal/path',
state: 'active'
})
])
guest.destroy()
expect(executor.snapshotPageInventory()).toEqual([
expect.objectContaining({ browserPageId: 'page-a', state: 'outcomeUnknown' })
])
await expect(executor.retirePage('page-a', 8)).resolves.toBe(true)
expect(guest.webContents.close).not.toHaveBeenCalled()
expect(rendererRetire).toHaveBeenCalledOnce()
expect(routeRelease).toHaveBeenCalledOnce()
expect(clearPolicies).toHaveBeenCalledOnce()
expect(sessionRegistry.isAllowedPartition(partition)).toBe(false)
})
})
function createCommand(
type: 'createPage' | 'navigate' | 'reclaimPage'
): BrowserClientHostCommandEvent {
const previousAuthority = {
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-a',
browserHostClientId: 'client-a',
browserHostGeneration: 3,
pageHostGeneration: 7
}
return {
type: 'command',
authorityRuntimeId: 'runtime-a',
authorityEpoch: type === 'reclaimPage' ? 'epoch-new' : 'epoch-a',
browserHostClientId: 'client-a',
browserHostGeneration: type === 'reclaimPage' ? 4 : 3,
pageCommandProtocolVersion: 1,
pageReconciliationProtocolVersion: 1,
browserPageId: 'page-a',
pageHostGeneration: type === 'reclaimPage' ? 8 : 7,
commandSequence: type === 'createPage' || type === 'reclaimPage' ? 1 : 2,
commandId: `${type}-a`,
command:
type === 'createPage'
? {
type: 'createPage',
browserProfileId: 'profile-a',
executionHostKey: 'execution-host-a'
}
: type === 'navigate'
? { type: 'navigate', url: 'example.internal/path' }
: {
type: 'reclaimPage',
previousAuthority,
browserProfileId: 'profile-a',
executionHostKey: 'execution-host-a'
}
}
}
function createGuest(routeSession: Session) {
const listeners = new Map<string, Set<(...args: unknown[]) => void>>()
let destroyed = false
let url = 'about:blank'
const emit = (event: string, ...args: unknown[]): void => {
for (const listener of listeners.get(event) ?? []) {
listener(...args)
}
}
const webContents = {
id: 41,
session: routeSession,
hostWebContents: { id: 11 },
getType: () => 'webview',
getURL: () => url,
isDestroyed: () => destroyed,
close: vi.fn(() => {
destroyed = true
emit('destroyed')
}),
loadURL: vi.fn(async (nextUrl: string) => {
const event = { preventDefault: vi.fn() }
emit('will-navigate', event, nextUrl)
if (event.preventDefault.mock.calls.length > 0) {
throw new Error('navigation denied')
}
url = nextUrl
}),
setWebRTCIPHandlingPolicy: vi.fn(),
setWindowOpenHandler: vi.fn(),
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
const eventListeners = listeners.get(event) ?? new Set()
eventListeners.add(listener)
listeners.set(event, eventListeners)
}),
off: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.get(event)?.delete(listener)
})
} as unknown as WebContents
return {
webContents,
url: () => url,
destroy: () => {
if (!destroyed) {
destroyed = true
emit('destroyed')
}
}
}
}
function signal(): AbortSignal {
return new AbortController().signal
}