test: remove 229 low-value browser host tests (#38656)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-05 12:50:40 -08:00
committed by GitHub
co-authored by OrcaWin
parent 9deff9dffd
commit 649dd09de3
22 changed files with 607 additions and 7144 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -1132,8 +1132,6 @@
"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts": 156,
"src/main/browser/client-hosts/commands/browser-client-host-command-retention.test.ts": 799,
"src/main/browser/client-hosts/lifecycle/browser-client-host-id.test.ts": 82,
"src/main/browser/client-hosts/lifecycle/browser-client-host-placement-preparation.test.ts": 161,
"src/main/browser/client-hosts/lifecycle/browser-client-host-reconciliation-command-order.test.ts": 169,
"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts": 286,
"src/main/browser/client-pages/execution/browser-client-page-automation-runtime.test.ts": 53,
"src/main/browser/client-pages/execution/browser-client-page-command-executor-fencing.test.ts": 319,
@@ -1243,7 +1241,6 @@
"src/main/browser/cdp/commands/cdp-print-to-pdf.test.ts": 68,
"src/main/browser/cdp/commands/cdp-screenshot.test.ts": 415,
"src/main/browser/cdp/transport/cdp-ws-proxy-first-paint.test.ts": 366,
"src/main/browser/cdp/transport/cdp-ws-proxy-focus-replay.test.ts": 489,
"src/main/browser/cdp/transport/cdp-ws-proxy-host-admission.test.ts": 576,
"src/main/browser/cdp/transport/cdp-ws-proxy-input-focus.test.ts": 360,
"src/main/browser/cdp/transport/cdp-ws-proxy-malformed-messages.test.ts": 305,
@@ -1361,11 +1358,8 @@
"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts": 568,
"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts": 53,
"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-route-identity.test.ts": 1404,
"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host.test.ts": 370,
"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-host-command-admission.test.ts": 213,
"src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease-reconnect.test.ts": 945,
"src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts": 973,
"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-host-reconciliation-negotiation.test.ts": 269,
"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts": 1150,
"src/main/browser/guest-lifecycle/popups/popup-identity-electron-probe.test.ts": 144,
"src/main/browser/guest-lifecycle/popups/popup-origin-bar-window.test.ts": 118,
@@ -1,366 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { CdpWsProxy } from './cdp-ws-proxy'
import {
connect,
createMockWebContents,
getSendCommandCalls,
getSendCommandMethods,
sendAndReceive,
mockAsWebContents,
type MockWebContents
} from './cdp-ws-proxy-test-harness'
vi.mock('electron', () => ({
webContents: { fromId: vi.fn() }
}))
// Native focus before insertion can blur the DOM.focus target; replay restores it.
describe('CdpWsProxy DOM.focus replay', () => {
let mock: MockWebContents
let proxy: CdpWsProxy
let endpoint: string
beforeEach(async () => {
mock = createMockWebContents()
proxy = new CdpWsProxy(mockAsWebContents(mock), () => () => {})
endpoint = await proxy.start()
})
afterEach(async () => {
await proxy.stop()
})
it('replays DOM.focus before Input.insertText in the root session', async () => {
const client = await connect(endpoint)
const focusResponse = await sendAndReceive(client, {
id: 14,
method: 'DOM.focus',
params: { backendNodeId: 99 }
})
const insertResponse = await sendAndReceive(client, {
id: 15,
method: 'Input.insertText',
params: { text: 'hello' }
})
expect(focusResponse.id).toBe(14)
expect(insertResponse.id).toBe(15)
expect(insertResponse.result).toEqual({})
expect(mock.webContents.focus).toHaveBeenCalledTimes(1)
expect(getSendCommandCalls(mock)).toEqual([
['Page.enable', {}],
['DOM.focus', { backendNodeId: 99 }],
['DOM.focus', { backendNodeId: 99 }],
['Input.insertText', { text: 'hello' }]
])
client.close()
})
it('replays DOM.focus before Input.insertText for OOPIF sessions', async () => {
const client = await connect(endpoint)
await sendAndReceive(client, {
id: 16,
method: 'DOM.focus',
params: { backendNodeId: 123 },
sessionId: 'oopif-session-123'
})
const insertResponse = await sendAndReceive(client, {
id: 17,
method: 'Input.insertText',
params: { text: 'frame text' },
sessionId: 'oopif-session-123'
})
expect(insertResponse.id).toBe(17)
expect(insertResponse.result).toEqual({})
expect(getSendCommandCalls(mock)).toEqual([
['Page.enable', {}],
['DOM.focus', { backendNodeId: 123 }, 'oopif-session-123'],
['DOM.focus', { backendNodeId: 123 }, 'oopif-session-123'],
['Input.insertText', { text: 'frame text' }, 'oopif-session-123']
])
client.close()
})
it('does not replay DOM.focus after adjacent eval traffic', async () => {
const client = await connect(endpoint)
await sendAndReceive(client, {
id: 18,
method: 'DOM.focus',
params: { backendNodeId: 44 }
})
await sendAndReceive(client, {
id: 19,
method: 'Runtime.callFunctionOn',
params: { functionDeclaration: '() => document.activeElement?.id' }
})
const insertResponse = await sendAndReceive(client, {
id: 20,
method: 'Input.insertText',
params: { text: 'after eval' }
})
expect(insertResponse.id).toBe(20)
expect(insertResponse.result).toEqual({})
expect(mock.webContents.focus).toHaveBeenCalledTimes(1)
expect(getSendCommandCalls(mock)).toEqual([
['Page.enable', {}],
['DOM.focus', { backendNodeId: 44 }],
['Runtime.callFunctionOn', { functionDeclaration: '() => document.activeElement?.id' }],
['Input.insertText', { text: 'after eval' }]
])
client.close()
})
it('does not replay a failed DOM.focus on the next Input.insertText', async () => {
let domFocusAttempt = 0
mock.webContents.debugger.sendCommand.mockImplementation(async (...args: unknown[]) => {
const [method] = args as [string]
if (method === 'DOM.focus') {
domFocusAttempt += 1
if (domFocusAttempt === 1) {
throw new Error('Node not found')
}
}
return {}
})
const client = await connect(endpoint)
const focusResponse = await sendAndReceive(client, {
id: 21,
method: 'DOM.focus',
params: { backendNodeId: 55 }
})
const insertResponse = await sendAndReceive(client, {
id: 22,
method: 'Input.insertText',
params: { text: 'fallback' }
})
expect(focusResponse).toEqual({
id: 21,
error: { code: -32000, message: 'Node not found' }
})
expect(insertResponse.id).toBe(22)
expect(insertResponse.result).toEqual({})
expect(mock.webContents.focus).toHaveBeenCalledTimes(1)
expect(getSendCommandCalls(mock)).toEqual([
['Page.enable', {}],
['DOM.focus', { backendNodeId: 55 }],
['Input.insertText', { text: 'fallback' }]
])
client.close()
})
it('returns the replay error when the stored DOM.focus fails before Input.insertText', async () => {
let domFocusAttempt = 0
mock.webContents.debugger.sendCommand.mockImplementation(async (...args: unknown[]) => {
const [method] = args as [string]
if (method === 'DOM.focus') {
domFocusAttempt += 1
if (domFocusAttempt === 2) {
throw new Error('Focus target went stale')
}
}
return {}
})
const client = await connect(endpoint)
const focusResponse = await sendAndReceive(client, {
id: 23,
method: 'DOM.focus',
params: { backendNodeId: 77 }
})
const insertResponse = await sendAndReceive(client, {
id: 24,
method: 'Input.insertText',
params: { text: 'blocked' }
})
expect(focusResponse.id).toBe(23)
expect(focusResponse.result).toEqual({})
expect(insertResponse).toEqual({
id: 24,
error: { code: -32000, message: 'Focus target went stale' }
})
expect(mock.webContents.focus).toHaveBeenCalledTimes(1)
expect(getSendCommandCalls(mock)).toEqual([
['Page.enable', {}],
['DOM.focus', { backendNodeId: 77 }],
['DOM.focus', { backendNodeId: 77 }]
])
client.close()
})
it('still replays DOM.focus when Input.insertText is dispatched while DOM.focus is still in flight', async () => {
let resolveFocus: (v: Record<string, unknown>) => void
const focusPromise = new Promise<Record<string, unknown>>((r) => {
resolveFocus = r
})
mock.webContents.debugger.sendCommand.mockImplementation(async (...args: unknown[]) => {
const [method] = args as [string]
if (method === 'DOM.focus') {
return focusPromise
}
return {}
})
const client = await connect(endpoint)
const responses: Record<string, unknown>[] = []
client.on('message', (data) => {
responses.push(JSON.parse(data.toString()))
})
client.send(JSON.stringify({ id: 25, method: 'DOM.focus', params: { backendNodeId: 66 } }))
await new Promise((r) => setTimeout(r, 10))
client.send(
JSON.stringify({ id: 26, method: 'Input.insertText', params: { text: 'pipelined' } })
)
await new Promise((r) => setTimeout(r, 20))
resolveFocus!({})
await new Promise((r) => setTimeout(r, 20))
expect(responses).toHaveLength(2)
const focusResponse = responses.find((r) => r.id === 25)
const insertResponse = responses.find((r) => r.id === 26)
expect(focusResponse?.result).toEqual({})
expect(insertResponse?.result).toEqual({})
expect(getSendCommandMethods(mock)).toEqual([
'Page.enable',
'DOM.focus',
'DOM.focus',
'Input.insertText'
])
client.close()
})
it('clears the pending DOM.focus replay when Page.bringToFront intervenes', async () => {
const client = await connect(endpoint)
await sendAndReceive(client, {
id: 27,
method: 'DOM.focus',
params: { backendNodeId: 88 }
})
await sendAndReceive(client, { id: 28, method: 'Page.bringToFront', params: {} })
const insertResponse = await sendAndReceive(client, {
id: 29,
method: 'Input.insertText',
params: { text: 'no replay' }
})
expect(insertResponse.id).toBe(29)
expect(insertResponse.result).toEqual({})
// Only insertText focuses natively; bringToFront is a no-op.
expect(mock.webContents.focus).toHaveBeenCalledTimes(1)
expect(getSendCommandMethods(mock)).toEqual(['Page.enable', 'DOM.focus', 'Input.insertText'])
client.close()
})
it('clears the pending DOM.focus replay when Page.captureScreenshot intervenes', async () => {
const client = await connect(endpoint)
await sendAndReceive(client, {
id: 30,
method: 'DOM.focus',
params: { backendNodeId: 91 }
})
await sendAndReceive(client, { id: 31, method: 'Page.captureScreenshot', params: {} })
const insertResponse = await sendAndReceive(client, {
id: 32,
method: 'Input.insertText',
params: { text: 'no replay after screenshot' }
})
expect(insertResponse.id).toBe(32)
expect(insertResponse.result).toEqual({})
expect(getSendCommandMethods(mock)).toEqual([
'Page.enable',
'DOM.focus',
'Page.captureScreenshot',
'Input.insertText'
])
client.close()
})
it('does not replay a pending DOM.focus across a client reconnect', async () => {
const first = await connect(endpoint)
await sendAndReceive(first, { id: 33, method: 'DOM.focus', params: { backendNodeId: 12 } })
first.close()
const second = await connect(endpoint)
const insertResponse = await sendAndReceive(second, {
id: 34,
method: 'Input.insertText',
params: { text: 'fresh client' }
})
expect(insertResponse.id).toBe(34)
expect(insertResponse.result).toEqual({})
expect(getSendCommandMethods(mock)).toEqual(['Page.enable', 'DOM.focus', 'Input.insertText'])
second.close()
})
it('does not replay or insert once the client disconnects mid-DOM.focus', async () => {
let resolveFocus: (v: Record<string, unknown>) => void = () => {}
mock.webContents.debugger.sendCommand.mockImplementation(async (...args: unknown[]) => {
const [method] = args as [string]
if (method === 'DOM.focus') {
return new Promise<Record<string, unknown>>((resolve) => {
resolveFocus = resolve
})
}
return {}
})
const client = await connect(endpoint)
client.send(JSON.stringify({ id: 35, method: 'DOM.focus', params: { backendNodeId: 7 } }))
await new Promise((r) => setTimeout(r, 10))
client.send(JSON.stringify({ id: 36, method: 'Input.insertText', params: { text: 'gone' } }))
await new Promise((r) => setTimeout(r, 10))
client.close()
await new Promise((r) => setTimeout(r, 10))
resolveFocus({})
await new Promise((r) => setTimeout(r, 20))
const methods = getSendCommandMethods(mock)
expect(methods.filter((m) => m === 'DOM.focus')).toHaveLength(1)
expect(methods).not.toContain('Input.insertText')
})
it('does not insert once the client disconnects during the DOM.focus replay', async () => {
let domFocusCalls = 0
let resolveReplay: (v: Record<string, unknown>) => void = () => {}
mock.webContents.debugger.sendCommand.mockImplementation(async (...args: unknown[]) => {
const [method] = args as [string]
if (method === 'DOM.focus') {
domFocusCalls += 1
// Stall the replay, after the initial focus succeeds, to disconnect during it.
if (domFocusCalls === 2) {
return new Promise<Record<string, unknown>>((resolve) => {
resolveReplay = resolve
})
}
}
return {}
})
const client = await connect(endpoint)
await sendAndReceive(client, { id: 37, method: 'DOM.focus', params: { backendNodeId: 9 } })
client.send(JSON.stringify({ id: 38, method: 'Input.insertText', params: { text: 'late' } }))
await new Promise((r) => setTimeout(r, 10))
client.close()
await new Promise((r) => setTimeout(r, 10))
resolveReplay({})
await new Promise((r) => setTimeout(r, 20))
expect(getSendCommandMethods(mock)).not.toContain('Input.insertText')
})
})
@@ -1,7 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { CdpWsProxy } from './cdp-ws-proxy'
import { runWithRemoteCliPageAdmission } from '../../routing/input-ownership/remote-cli-page-admission'
import { sendGuestCdpCommand } from '../debugger/guest-cdp-command'
import { releaseHeldPageInput } from '../input/guest-direct-key-input'
import {
connect,
@@ -19,15 +18,6 @@ vi.mock('electron', () => ({
const PAGE_ID = 7
const REVOKED = 'The Orca desktop stopped sharing its browser before this command ran.'
function keyUps(mock: MockWebContents): string[] {
return [
...mock.webContents.sendInputEvent.mock.calls.map((call) => call[0].type),
...mock.webContents.debugger.sendCommand.mock.calls
.filter((call) => call[0] === 'Input.dispatchKeyEvent')
.map((call) => String(call[1]?.type))
].filter((type) => type === 'keyUp')
}
function mouseEvents(mock: MockWebContents): string[] {
return mock.webContents.debugger.sendCommand.mock.calls
.filter((call) => call[0] === 'Input.dispatchMouseEvent')
@@ -55,67 +45,6 @@ describe('CdpWsProxy under a host command', () => {
await proxy.stop()
})
it('refuses every helper step after the host is revoked, without sending it to the page', async () => {
let revoked = false
let finish = (): void => {}
const held = runWithRemoteCliPageAdmission(
PAGE_ID,
() => {
if (revoked) {
throw new Error(REVOKED)
}
},
() => new Promise<void>((resolve) => (finish = resolve))
)
const client = await connect(endpoint)
const press = { type: 'mouseMoved', x: 1, y: 1 }
const allowed = await sendAndReceive(client, {
id: 1,
method: 'Input.dispatchMouseEvent',
params: press
})
revoked = true
const refused = await sendAndReceive(client, {
id: 2,
method: 'Input.dispatchMouseEvent',
params: press
})
expect(allowed.error).toBeUndefined()
expect(refused).toMatchObject({ id: 2, error: { message: REVOKED } })
expect(mouseEvents(mock)).toEqual(['mouseMoved'])
finish()
await held
client.close()
})
it('refuses a helper the PDF of a page that moved to a desktop file while it printed', async () => {
let movedToFile = false
let finish = (): void => {}
const held = runWithRemoteCliPageAdmission(
PAGE_ID,
() => {
if (movedToFile) {
throw new Error('not browsing through the host')
}
},
() => new Promise<void>((resolve) => (finish = resolve))
)
mock.webContents.printToPDF.mockImplementation(async () => {
movedToFile = true
return Buffer.from('%PDF-private')
})
const client = await connect(endpoint)
const printed = await sendAndReceive(client, { id: 1, method: 'Page.printToPDF', params: {} })
expect(printed).toMatchObject({ id: 1, error: { message: 'not browsing through the host' } })
finish()
await held
client.close()
})
function holdPage(): { revoke: () => void; release: () => Promise<void> } {
const page = mockAsWebContents(mock, PAGE_ID)
let revoked = false
@@ -140,103 +69,7 @@ describe('CdpWsProxy under a host command', () => {
}
const MOUSE = 'Input.dispatchMouseEvent'
const KEY = 'Input.dispatchKeyEvent'
const pressed = { type: 'mousePressed', x: 1, y: 1, button: 'left', clickCount: 1 }
const released = { type: 'mouseReleased', x: 1, y: 1, button: 'left', clickCount: 1 }
const shiftDown = { type: 'rawKeyDown', key: 'Shift', code: 'ShiftLeft', modifiers: 8 }
const shiftUp = { type: 'keyUp', key: 'Shift', code: 'ShiftLeft' }
it.each(['window', 'webview'])(
'refuses a revoked release, then lets go of the button and key itself (%s page)',
async (pageType) => {
mock.webContents.getType.mockReturnValue(pageType)
const page = holdPage()
const client = await connect(endpoint)
await sendAndReceive(client, { id: 5, method: MOUSE, params: pressed })
await sendAndReceive(client, { id: 6, method: KEY, params: shiftDown })
page.revoke()
const mouseUp = await sendAndReceive(client, { id: 7, method: MOUSE, params: released })
const keyUp = await sendAndReceive(client, { id: 8, method: KEY, params: shiftUp })
expect(mouseUp).toMatchObject({ error: { message: REVOKED } })
expect(keyUp).toMatchObject({ error: { message: REVOKED } })
expect(mouseEvents(mock)).toEqual(['mousePressed'])
expect(keyUps(mock)).toHaveLength(0)
await page.release()
// Release off-page to avoid completing the revoked click.
expect(mock.webContents.debugger.sendCommand).toHaveBeenCalledWith(
MOUSE,
expect.objectContaining({ type: 'mouseReleased', x: -1, y: -1 })
)
expect(mouseEvents(mock)).toEqual(['mousePressed', 'mouseReleased'])
expect(keyUps(mock)).toHaveLength(1)
client.close()
}
)
it('lets go of nothing when the command released what it pressed before the revocation', async () => {
const page = holdPage()
const client = await connect(endpoint)
await sendAndReceive(client, { id: 11, method: MOUSE, params: pressed })
await sendAndReceive(client, { id: 12, method: MOUSE, params: released })
page.revoke()
await page.release()
expect(mouseEvents(mock)).toEqual(['mousePressed', 'mouseReleased'])
client.close()
})
it('refuses a release of something the revoked command never pressed', async () => {
const page = holdPage()
const client = await connect(endpoint)
page.revoke()
const mouseUp = await sendAndReceive(client, { id: 9, method: MOUSE, params: released })
const keyUp = await sendAndReceive(client, { id: 10, method: KEY, params: shiftUp })
expect(mouseUp).toMatchObject({ error: { message: REVOKED } })
expect(keyUp).toMatchObject({ error: { message: REVOKED } })
expect(mouseEvents(mock)).toEqual([])
await page.release()
client.close()
})
it('drops a press it accepted before the revocation but had not delivered yet', async () => {
mock.webContents.getType.mockReturnValue('webview')
let grantFocus = (): void => {}
guardFocus = () => new Promise((resolve) => (grantFocus = () => resolve(() => {})))
let revoked = false
let finish = (): void => {}
const held = runWithRemoteCliPageAdmission(
PAGE_ID,
() => {
if (revoked) {
throw new Error(REVOKED)
}
},
() => new Promise<void>((resolve) => (finish = resolve))
)
const client = await connect(endpoint)
const reply = sendAndReceive(client, {
id: 3,
method: 'Input.dispatchMouseEvent',
params: { type: 'mousePressed', x: 1, y: 1, button: 'left', clickCount: 1 }
})
await vi.waitFor(() =>
expect(getSendCommandMethods(mock)).toContain('Emulation.setFocusEmulationEnabled')
)
revoked = true
grantFocus()
await expect(reply).resolves.toMatchObject({ id: 3, error: { message: REVOKED } })
expect(mouseEvents(mock)).toEqual([])
finish()
await held
client.close()
})
it('still refuses a deferred press after the revoked command let go of the page', async () => {
mock.webContents.getType.mockReturnValue('webview')
@@ -257,76 +90,4 @@ describe('CdpWsProxy under a host command', () => {
expect(mouseEvents(mock)).toEqual([])
client.close()
})
it('lets go of a button whose own release failed to land', async () => {
const page = holdPage()
const client = await connect(endpoint)
const send = mock.webContents.debugger.sendCommand.getMockImplementation()
mock.webContents.debugger.sendCommand.mockImplementationOnce(async () => ({}))
mock.webContents.debugger.sendCommand.mockImplementationOnce(async () => {
throw new Error('target closed')
})
await sendAndReceive(client, { id: 14, method: MOUSE, params: pressed })
const failed = await sendAndReceive(client, { id: 15, method: MOUSE, params: released })
if (send) {
mock.webContents.debugger.sendCommand.mockImplementation(send)
}
page.revoke()
await page.release()
expect(failed.error).toBeDefined()
expect(mock.webContents.debugger.sendCommand).toHaveBeenCalledWith(
MOUSE,
expect.objectContaining({ type: 'mouseReleased', x: -1, y: -1 })
)
client.close()
})
it('forwards commands again once the host command ends', async () => {
await runWithRemoteCliPageAdmission(
PAGE_ID,
() => {
throw new Error(REVOKED)
},
async () => {}
)
const client = await connect(endpoint)
const response = await sendAndReceive(client, {
id: 4,
method: 'Accessibility.getFullAXTree',
params: {}
})
expect(response.error).toBeUndefined()
expect(getSendCommandMethods(mock)).toContain('Accessibility.getFullAXTree')
client.close()
})
it('never refuses the desktop its own page commands while a revoked host command unwinds', async () => {
let finish = (): void => {}
const held = runWithRemoteCliPageAdmission(
PAGE_ID,
() => {
throw new Error(REVOKED)
},
() => new Promise<void>((resolve) => (finish = resolve))
)
await expect(
sendGuestCdpCommand(
{ ...mock.webContents, id: PAGE_ID },
'Emulation.setDeviceMetricsOverride',
{
width: 400,
height: 300,
deviceScaleFactor: 1,
mobile: false
}
)
).resolves.toEqual({})
finish()
await held
})
})
@@ -1,11 +1,8 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import WebSocket from 'ws'
import { CdpWsProxy } from './cdp-ws-proxy'
import {
connect,
createMockWebContents,
getSendCommandCalls,
getSendCommandMethods,
sendAndReceive,
mockAsWebContents,
type MockWebContents
@@ -37,715 +34,6 @@ describe('CdpWsProxy', () => {
return result.stream as string
}
const defaultPdfMarginInches = 1 / 2.54
it('starts on a random port and returns ws:// URL', () => {
expect(endpoint).toMatch(/^ws:\/\/127\.0\.0\.1:\d+$/)
expect(proxy.getPort()).toBeGreaterThan(0)
})
it('does not retain an extra startup server error listener after binding', () => {
const server = (
proxy as unknown as { httpServer: { listenerCount: (event: string) => number } }
).httpServer
expect(server.listenerCount('error')).toBeLessThanOrEqual(1)
})
it('attaches debugger on start', () => {
expect(mock.webContents.debugger.attach).toHaveBeenCalledWith('1.3')
})
it('correlates CDP request/response IDs', async () => {
mock.webContents.debugger.sendCommand.mockResolvedValueOnce({ tree: 'nodes' })
const ws = connect(endpoint)
const client = await ws
const response = await sendAndReceive(client, {
id: 42,
method: 'Accessibility.getFullAXTree',
params: {}
})
expect(response.id).toBe(42)
expect(response.result).toEqual({ tree: 'nodes' })
client.close()
})
it('returns error response when sendCommand fails', async () => {
mock.webContents.debugger.sendCommand.mockRejectedValueOnce(new Error('Node not found'))
const client = await connect(endpoint)
const response = await sendAndReceive(client, {
id: 7,
method: 'DOM.describeNode',
params: { nodeId: 999 }
})
expect(response.id).toBe(7)
expect(response.error).toEqual({ code: -32000, message: 'Node not found' })
client.close()
})
it('routes Playwright nested browser and page sessions on the proxy path', async () => {
const client = await connect(endpoint)
const primaryPageAttachResponse = await sendAndReceive(client, {
id: 31,
method: 'Target.attachToTarget',
params: { targetId: 'orca-proxy-target', flatten: true }
})
expect(primaryPageAttachResponse).toEqual({
id: 31,
result: { sessionId: 'orca-proxy-session' }
})
const attachResponse = await sendAndReceive(client, {
id: 32,
method: 'Target.attachToBrowserTarget',
params: {}
})
expect(attachResponse).toEqual({
id: 32,
result: { sessionId: 'orca-proxy-browser-session' }
})
expect(getSendCommandMethods(mock)).not.toContain('Target.attachToBrowserTarget')
const pageAttachResponse = await sendAndReceive(client, {
id: 33,
method: 'Target.attachToTarget',
params: { targetId: 'orca-proxy-target', flatten: true },
sessionId: 'orca-proxy-browser-session'
})
expect(pageAttachResponse).toEqual({
id: 33,
result: { sessionId: 'orca-proxy-session-2' },
sessionId: 'orca-proxy-browser-session'
})
const sessionResponse = await sendAndReceive(client, {
id: 34,
method: 'Runtime.evaluate',
params: { expression: 'document.title' },
sessionId: 'orca-proxy-session-2'
})
expect(sessionResponse).toEqual({
id: 34,
result: {},
sessionId: 'orca-proxy-session-2'
})
expect(getSendCommandCalls(mock)).toContainEqual([
'Runtime.evaluate',
{ expression: 'document.title' }
])
const detachResponse = await sendAndReceive(client, {
id: 35,
method: 'Target.detachFromTarget',
params: { sessionId: 'orca-proxy-session-2' },
sessionId: 'orca-proxy-browser-session'
})
expect(detachResponse).toEqual({
id: 35,
result: {},
sessionId: 'orca-proxy-browser-session'
})
const primaryPageResponse = await sendAndReceive(client, {
id: 36,
method: 'Runtime.evaluate',
params: { expression: 'document.URL' },
sessionId: 'orca-proxy-session'
})
expect(primaryPageResponse).toEqual({
id: 36,
result: {},
sessionId: 'orca-proxy-session'
})
const browserSessionResponse = await sendAndReceive(client, {
id: 37,
method: 'Target.getTargets',
params: {},
sessionId: 'orca-proxy-browser-session'
})
expect(browserSessionResponse).toMatchObject({
id: 37,
sessionId: 'orca-proxy-browser-session'
})
client.close()
})
it('preserves Target.attachToTarget and clears the synthetic session on Target.detachFromTarget', async () => {
const client = await connect(endpoint)
const attachResponse = await sendAndReceive(client, {
id: 33,
method: 'Target.attachToTarget',
params: { targetId: 'orca-proxy-target', flatten: true }
})
expect(attachResponse).toEqual({
id: 33,
result: { sessionId: 'orca-proxy-session' }
})
const detachResponse = await sendAndReceive(client, {
id: 34,
method: 'Target.detachFromTarget',
params: { sessionId: 'orca-proxy-session' }
})
expect(detachResponse).toEqual({ id: 34, result: {} })
const rootEventPromise = new Promise<Record<string, unknown>>((resolve) => {
client.once('message', (data) => resolve(JSON.parse(data.toString())))
})
mock.emit('message', {}, 'Runtime.executionContextCreated', { context: { id: 1 } })
const rootEvent = await rootEventPromise
expect(rootEvent).toEqual({
method: 'Runtime.executionContextCreated',
params: { context: { id: 1 } }
})
const reattachResponse = await sendAndReceive(client, {
id: 35,
method: 'Target.attachToTarget',
params: { targetId: 'orca-proxy-target', flatten: true }
})
expect(reattachResponse).toEqual({
id: 35,
result: { sessionId: 'orca-proxy-session-2' }
})
client.close()
})
it('returns an error instead of crashing when a command arrives after tab destruction', async () => {
const client = await connect(endpoint)
mock.destroy()
const response = await sendAndReceive(client, {
id: 8,
method: 'Runtime.evaluate',
params: { expression: 'location.href' }
})
expect(response.id).toBe(8)
expect(response.error).toEqual({
code: -32000,
message: 'Browser tab is no longer available'
})
expect(mock.webContents.debugger.sendCommand).not.toHaveBeenCalledWith(
'Runtime.evaluate',
expect.anything(),
expect.anything()
)
client.close()
})
it('handles concurrent requests with correct correlation', async () => {
let resolveFirst: (v: unknown) => void
const firstPromise = new Promise((r) => {
resolveFirst = r
})
mock.webContents.debugger.sendCommand
.mockImplementationOnce(async () => {
await firstPromise
return { result: 'slow' }
})
.mockResolvedValueOnce({ result: 'fast' })
const client = await connect(endpoint)
const responses: Record<string, unknown>[] = []
client.on('message', (data) => {
responses.push(JSON.parse(data.toString()))
})
client.send(JSON.stringify({ id: 1, method: 'DOM.enable', params: {} }))
await new Promise((r) => setTimeout(r, 10))
client.send(JSON.stringify({ id: 2, method: 'Page.enable', params: {} }))
await new Promise((r) => setTimeout(r, 20))
resolveFirst!(undefined)
await new Promise((r) => setTimeout(r, 20))
expect(responses).toHaveLength(2)
const resp1 = responses.find((r) => r.id === 1)
const resp2 = responses.find((r) => r.id === 2)
expect(resp1?.result).toEqual({ result: 'slow' })
expect(resp2?.result).toEqual({ result: 'fast' })
client.close()
})
it('does not deliver a late response from a closed client to a newer websocket', async () => {
let resolveSlowCommand: ((value: { result: string }) => void) | null = null
mock.webContents.debugger.sendCommand
.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveSlowCommand = resolve
})
)
.mockResolvedValueOnce({ result: 'new-client' })
const firstClient = await connect(endpoint)
firstClient.send(JSON.stringify({ id: 1, method: 'DOM.enable', params: {} }))
await new Promise((resolve) => setTimeout(resolve, 10))
const secondClient = await connect(endpoint)
const responses: Record<string, unknown>[] = []
secondClient.on('message', (data) => {
responses.push(JSON.parse(data.toString()))
})
secondClient.send(JSON.stringify({ id: 2, method: 'Page.enable', params: {} }))
await new Promise((resolve) => setTimeout(resolve, 20))
resolveSlowCommand!({ result: 'old-client' })
await new Promise((resolve) => setTimeout(resolve, 20))
expect(responses).toEqual([{ id: 2, result: { result: 'new-client' } }])
secondClient.close()
})
it('forwards sessionId to sendCommand for OOPIF support', async () => {
mock.webContents.debugger.sendCommand.mockResolvedValueOnce({})
const client = await connect(endpoint)
await sendAndReceive(client, {
id: 1,
method: 'DOM.enable',
params: {},
sessionId: 'oopif-session-123'
})
expect(mock.webContents.debugger.sendCommand).toHaveBeenCalledWith(
'DOM.enable',
{},
'oopif-session-123'
)
client.close()
})
it('never leaves auto-attached workers and frames waiting on a client that may leave', async () => {
mock.webContents.debugger.sendCommand.mockResolvedValueOnce({})
const client = await connect(endpoint)
// agent-browser 0.39 asks child targets to wait for it; the shared guest debugger outlives it.
await sendAndReceive(client, {
id: 1,
method: 'Target.setAutoAttach',
params: { autoAttach: true, waitForDebuggerOnStart: true, flatten: true },
sessionId: 'oopif-session-123'
})
expect(mock.webContents.debugger.sendCommand).toHaveBeenCalledWith(
'Target.setAutoAttach',
{ autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
'oopif-session-123'
)
client.close()
})
it('forwards CDP events from debugger to client', async () => {
const client = await connect(endpoint)
const eventPromise = new Promise<Record<string, unknown>>((resolve) => {
client.on('message', (data) => resolve(JSON.parse(data.toString())))
})
mock.emit('message', {}, 'Console.messageAdded', { entry: { text: 'hello' } })
const event = await eventPromise
expect(event.method).toBe('Console.messageAdded')
expect(event.params).toEqual({ entry: { text: 'hello' } })
client.close()
})
it('forwards sessionId in events when present', async () => {
const client = await connect(endpoint)
const eventPromise = new Promise<Record<string, unknown>>((resolve) => {
client.on('message', (data) => resolve(JSON.parse(data.toString())))
})
mock.emit('message', {}, 'DOM.nodeInserted', { node: {} }, 'iframe-session-456')
const event = await eventPromise
expect(event.sessionId).toBe('iframe-session-456')
client.close()
})
it('does not focus the guest for Runtime.evaluate polling commands', async () => {
const client = await connect(endpoint)
await sendAndReceive(client, {
id: 9,
method: 'Runtime.evaluate',
params: { expression: 'document.readyState' }
})
expect(mock.webContents.focus).not.toHaveBeenCalled()
client.close()
})
it.each(['Page.bringToFront', 'Target.activateTarget'])(
'answers %s without focusing or forwarding it',
async (method) => {
const client = await connect(endpoint)
const response = await sendAndReceive(client, { id: 9, method, params: {} })
expect(response.result).toEqual({})
expect(mock.webContents.focus).not.toHaveBeenCalled()
expect(getSendCommandMethods(mock)).toEqual(['Page.enable'])
client.close()
}
)
it('types root-session keys and text into an embedded guest without focusing it', async () => {
mock.webContents.getType.mockReturnValue('webview')
const client = await connect(endpoint)
await sendAndReceive(client, { id: 11, method: 'DOM.focus', params: { backendNodeId: 5 } })
const insert = await sendAndReceive(client, {
id: 12,
method: 'Input.insertText',
params: { text: 'hi' }
})
const key = await sendAndReceive(client, {
id: 13,
method: 'Input.dispatchKeyEvent',
params: { type: 'keyDown', key: 'Enter', text: '\r' }
})
expect(insert.result).toEqual({})
expect(key.result).toEqual({})
expect(mock.webContents.focus).not.toHaveBeenCalled()
// Each delivery probes focus, then waits for page input handling.
expect(getSendCommandMethods(mock)).toEqual([
'Page.enable',
'DOM.focus',
'Runtime.evaluate',
'DOM.focus',
'Runtime.evaluate',
'Runtime.evaluate',
'Runtime.evaluate'
])
expect(mock.webContents.sendInputEvent.mock.calls.map(([event]) => event)).toEqual([
{ type: 'char', keyCode: 'h', modifiers: [], skipIfUnhandled: true },
{ type: 'char', keyCode: 'i', modifiers: [], skipIfUnhandled: true },
{ type: 'keyDown', keyCode: 'Enter', modifiers: [], skipIfUnhandled: true },
{ type: 'char', keyCode: '\r', modifiers: [], skipIfUnhandled: true }
])
client.close()
})
it('keeps pipelined root-session keys in order', async () => {
mock.webContents.getType.mockReturnValue('webview')
const client = await connect(endpoint)
const replies: unknown[] = []
const allReplied = new Promise<void>((resolve) => {
client.on('message', (data) => {
replies.push(JSON.parse(data.toString()).id)
if (replies.length === 3) {
resolve()
}
})
})
for (const [id, type] of [
[21, 'rawKeyDown'],
[22, 'keyUp'],
[23, 'rawKeyDown']
] as const) {
client.send(
JSON.stringify({ id, method: 'Input.dispatchKeyEvent', params: { type, key: 'Tab' } })
)
}
await allReplied
expect(replies).toEqual([21, 22, 23])
expect(mock.webContents.sendInputEvent.mock.calls.map(([event]) => event.type)).toEqual([
'keyDown',
'keyUp',
'keyDown'
])
client.close()
})
it('forwards child-frame session input unchanged and without focusing', async () => {
mock.webContents.getType.mockReturnValue('webview')
const client = await connect(endpoint)
await sendAndReceive(client, {
id: 31,
method: 'Input.dispatchKeyEvent',
params: { type: 'keyDown', key: 'a', text: 'a' },
sessionId: 'oopif-session'
})
await sendAndReceive(client, {
id: 32,
method: 'Input.insertText',
params: { text: 'a' },
sessionId: 'oopif-session'
})
expect(mock.webContents.focus).not.toHaveBeenCalled()
expect(mock.webContents.sendInputEvent).not.toHaveBeenCalled()
expect(getSendCommandCalls(mock).slice(1)).toEqual([
['Input.dispatchKeyEvent', { type: 'keyDown', key: 'a', text: 'a' }, 'oopif-session'],
['Input.insertText', { text: 'a' }, 'oopif-session']
])
client.close()
})
it('still focuses the guest for Input.insertText', async () => {
const client = await connect(endpoint)
await sendAndReceive(client, {
id: 10,
method: 'Input.insertText',
params: { text: 'hello' }
})
expect(mock.webContents.focus).toHaveBeenCalledTimes(1)
expect(getSendCommandMethods(mock)).toEqual(['Page.enable', 'Input.insertText'])
client.close()
})
it('primes lifecycle events for Page.navigate', async () => {
const client = await connect(endpoint)
const response = await sendAndReceive(client, {
id: 11,
method: 'Page.navigate',
params: { url: 'https://example.com/next' }
})
expect(response.id).toBe(11)
expect(response.result).toEqual({})
expect(getSendCommandMethods(mock)).toEqual([
'Page.enable',
'Network.enable',
'Page.enable',
'Page.setLifecycleEventsEnabled',
'Page.navigate'
])
client.close()
})
it('primes lifecycle events for Page.reload and preserves response id', async () => {
const client = await connect(endpoint)
const response = await sendAndReceive(client, {
id: 12,
method: 'Page.reload'
})
expect(response.id).toBe(12)
expect(response.result).toEqual({})
expect(getSendCommandMethods(mock)).toEqual([
'Page.enable',
'Network.enable',
'Page.enable',
'Page.setLifecycleEventsEnabled'
])
expect(mock.webContents.reload).toHaveBeenCalledTimes(1)
expect(getSendCommandMethods(mock)).not.toContain('Page.reload')
client.close()
})
it('preserves explicit Page.navigate session during lifecycle priming', async () => {
const client = await connect(endpoint)
await sendAndReceive(client, {
id: 14,
method: 'Page.navigate',
params: { url: 'https://example.com/frame' },
sessionId: 'iframe-session-123'
})
expect(getSendCommandCalls(mock).slice(1)).toEqual([
['Network.enable', {}, 'iframe-session-123'],
['Page.enable', {}, 'iframe-session-123'],
['Page.setLifecycleEventsEnabled', { enabled: true }, 'iframe-session-123'],
['Page.navigate', { url: 'https://example.com/frame' }, 'iframe-session-123']
])
client.close()
})
it('forwards explicit Page.reload session after lifecycle priming', async () => {
const client = await connect(endpoint)
await sendAndReceive(client, {
id: 15,
method: 'Page.reload',
params: { ignoreCache: true },
sessionId: 'iframe-session-123'
})
expect(getSendCommandCalls(mock).slice(1)).toEqual([
['Network.enable', {}, 'iframe-session-123'],
['Page.enable', {}, 'iframe-session-123'],
['Page.setLifecycleEventsEnabled', { enabled: true }, 'iframe-session-123'],
['Page.reload', { ignoreCache: true }, 'iframe-session-123']
])
expect(mock.webContents.reloadIgnoringCache).not.toHaveBeenCalled()
expect(mock.webContents.reload).not.toHaveBeenCalled()
client.close()
})
it('rejects root Page.reload params that direct webContents reload cannot honor', async () => {
const client = await connect(endpoint)
const response = await sendAndReceive(client, {
id: 16,
method: 'Page.reload',
params: { loaderId: 'stale-loader' }
})
expect(response).toEqual({
id: 16,
error: {
code: -32000,
message: 'Page.reload parameter "loaderId" is not supported for Orca tab reloads'
}
})
expect(mock.webContents.reload).not.toHaveBeenCalled()
expect(mock.webContents.reloadIgnoringCache).not.toHaveBeenCalled()
expect(getSendCommandMethods(mock)).not.toContain('Network.enable')
client.close()
})
it('still reloads when lifecycle priming stalls', async () => {
const client = await connect(endpoint)
mock.webContents.debugger.sendCommand.mockImplementation((method?: string) => {
if (method === 'Network.enable') {
return new Promise(() => {})
}
return Promise.resolve({})
})
const responsePromise = sendAndReceive(client, {
id: 17,
method: 'Page.reload'
})
await expect(responsePromise).resolves.toEqual({ id: 17, result: {} })
expect(mock.webContents.reload).toHaveBeenCalledTimes(1)
client.close()
})
it('does not reload after the requesting client disconnects during priming', async () => {
const client = await connect(endpoint)
mock.webContents.debugger.sendCommand.mockImplementation((method?: string) => {
if (method === 'Network.enable') {
return new Promise(() => {})
}
return Promise.resolve({})
})
client.send(JSON.stringify({ id: 18, method: 'Page.reload' }))
client.close()
await new Promise((resolve) => setTimeout(resolve, 1_100))
expect(mock.webContents.reload).not.toHaveBeenCalled()
expect(mock.webContents.reloadIgnoringCache).not.toHaveBeenCalled()
})
it('forwards Runtime.evaluate without lifecycle priming', async () => {
const client = await connect(endpoint)
const response = await sendAndReceive(client, {
id: 13,
method: 'Runtime.evaluate',
params: { expression: 'document.readyState' }
})
expect(response.id).toBe(13)
expect(response.result).toEqual({})
expect(getSendCommandMethods(mock)).toEqual(['Page.enable', 'Runtime.evaluate'])
client.close()
})
it('prints PDF data through native webContents printToPDF', async () => {
const client = await connect(endpoint)
const response = await sendAndReceive(client, {
id: 19,
method: 'Page.printToPDF',
params: {
landscape: true,
printBackground: true,
paperWidth: 8.5,
paperHeight: 11,
marginTop: 0.25,
marginBottom: 0.5,
marginLeft: 0.75,
marginRight: 1,
pageRanges: '1-2',
preferCSSPageSize: true
}
})
expect(response).toEqual({
id: 19,
result: { data: Buffer.from('%PDF-test').toString('base64') }
})
expect(mock.webContents.printToPDF).toHaveBeenCalledWith({
landscape: true,
printBackground: true,
pageSize: { width: 8.5, height: 11 },
margins: {
top: 0.25,
bottom: 0.5,
left: 0.75,
right: 1
},
pageRanges: '1-2',
preferCSSPageSize: true
})
expect(getSendCommandMethods(mock)).not.toContain('Page.printToPDF')
client.close()
})
it('keeps default PDF margins for omitted sides', async () => {
const client = await connect(endpoint)
await sendAndReceive(client, {
id: 20,
method: 'Page.printToPDF',
params: {
marginTop: 0.25
}
})
expect(mock.webContents.printToPDF).toHaveBeenCalledWith({
margins: {
top: 0.25,
bottom: defaultPdfMarginInches,
left: defaultPdfMarginInches,
right: defaultPdfMarginInches
}
})
client.close()
})
it('supports streamed Page.printToPDF results for Playwright page.pdf', async () => {
mock.webContents.printToPDF.mockResolvedValueOnce(Buffer.from('abcdef'))
const client = await connect(endpoint)
@@ -794,131 +82,4 @@ describe('CdpWsProxy', () => {
})
client.close()
})
it('clears streamed PDF data when the client disconnects', async () => {
mock.webContents.printToPDF.mockResolvedValueOnce(Buffer.from('abcdef'))
const client = await connect(endpoint)
const printResponse = await sendAndReceive(client, {
id: 26,
method: 'Page.printToPDF',
params: { transferMode: 'ReturnAsStream' }
})
const handle = expectPdfStreamHandle(printResponse)
expect(printResponse.id).toBe(26)
client.close()
await new Promise((resolve) => setTimeout(resolve, 10))
const nextClient = await connect(endpoint)
const staleRead = await sendAndReceive(nextClient, {
id: 27,
method: 'IO.read',
params: { handle }
})
expect(staleRead).toEqual({
id: 27,
error: { code: -32000, message: 'Invalid stream handle' }
})
nextClient.close()
})
it('does not register a PDF stream when the client disconnects mid-print', async () => {
let resolvePrint: (buf: Buffer<ArrayBuffer>) => void = () => {}
mock.webContents.printToPDF.mockImplementationOnce(
() =>
new Promise<Buffer<ArrayBuffer>>((resolve) => {
resolvePrint = resolve
})
)
const store = (
proxy as unknown as { pageCapture: { pdfStreams: { create: (b: Buffer) => string } } }
).pageCapture.pdfStreams
const createSpy = vi.spyOn(store, 'create')
const client = await connect(endpoint)
client.send(
JSON.stringify({
id: 30,
method: 'Page.printToPDF',
params: { transferMode: 'ReturnAsStream' }
})
)
await new Promise((resolve) => setTimeout(resolve, 10))
client.close()
await new Promise((resolve) => setTimeout(resolve, 10))
resolvePrint(Buffer.from('%PDF-late'))
await new Promise((resolve) => setTimeout(resolve, 10))
expect(createSpy).not.toHaveBeenCalled()
createSpy.mockRestore()
})
it('forwards non-PDF IO streams to the debugger', async () => {
mock.webContents.debugger.sendCommand
.mockResolvedValueOnce({ data: 'trace-data', eof: false })
.mockResolvedValueOnce({})
const client = await connect(endpoint)
const readResponse = await sendAndReceive(client, {
id: 28,
method: 'IO.read',
params: { handle: 'trace-stream', size: 64 }
})
const closeResponse = await sendAndReceive(client, {
id: 29,
method: 'IO.close',
params: { handle: 'trace-stream' }
})
expect(readResponse).toEqual({ id: 28, result: { data: 'trace-data', eof: false } })
expect(closeResponse).toEqual({ id: 29, result: {} })
expect(mock.webContents.debugger.sendCommand).toHaveBeenCalledWith('IO.read', {
handle: 'trace-stream',
size: 64
})
expect(mock.webContents.debugger.sendCommand).toHaveBeenCalledWith('IO.close', {
handle: 'trace-stream'
})
client.close()
})
it('detaches debugger and closes server on stop', async () => {
const client = await connect(endpoint)
await proxy.stop()
expect(mock.webContents.debugger.detach).toHaveBeenCalled()
expect(proxy.getPort()).toBeGreaterThan(0)
await new Promise<void>((resolve) => {
client.on('close', () => resolve())
if (client.readyState === WebSocket.CLOSED) {
resolve()
}
})
})
it('detaches client websocket listeners after client close', async () => {
const client = await connect(endpoint)
const serverClient = (proxy as unknown as { client: WebSocket | null }).client
expect(serverClient).toBeTruthy()
const offSpy = vi.spyOn(serverClient!, 'off')
client.close()
const start = Date.now()
while (
(proxy as unknown as { client: WebSocket | null }).client &&
Date.now() - start < 2_000
) {
await new Promise((resolve) => setTimeout(resolve, 20))
}
expect((proxy as unknown as { client: WebSocket | null }).client).toBeNull()
const removedEvents = offSpy.mock.calls.map(([event]) => event)
expect(removedEvents).toEqual(expect.arrayContaining(['message', 'close']))
offSpy.mockRestore()
})
})
@@ -1,13 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { BrowserCertificateTrustController } from './browser-certificate-trust-controller'
import {
applyProxySettingsToSession,
resetSessionProxyApplicationForTests
} from '../../network/proxy-settings'
import { resetSessionProxyApplicationForTests } from '../../network/proxy-settings'
const FIRST_CERTIFICATE = certificate('first certificate')
const SECOND_CERTIFICATE = certificate('replacement certificate')
let beforeRequestListener:
| ((
details: Electron.OnBeforeRequestListenerDetails,
@@ -146,91 +142,6 @@ describe('BrowserCertificateTrustController', () => {
controller.installSessionRequestGuard(browserSession)
})
it('holds requests until proxy readiness settles', async () => {
let finishWrite: (() => void) | undefined
vi.mocked(browserSession.setProxy).mockImplementationOnce(
() => new Promise<void>((resolve) => (finishWrite = resolve))
)
const applying = applyProxySettingsToSession(
browserSession,
{ httpProxyUrl: 'http://proxy.example:8080' },
{ env: {} }
)
const callback = beforeRequest({ url: 'http://proxy-only.invalid/', webContentsId: guest.id })
await vi.waitFor(() => expect(browserSession.setProxy).toHaveBeenCalledOnce())
expect(callback).not.toHaveBeenCalled()
finishWrite?.()
await applying
await vi.waitFor(() => expect(callback).toHaveBeenCalledWith({}))
})
it('cancels requests after proxy readiness fails', async () => {
vi.mocked(browserSession.setProxy).mockRejectedValue(new Error('proxy apply failed'))
await expect(
applyProxySettingsToSession(
browserSession,
{ httpProxyUrl: 'http://proxy.example:8080' },
{ env: {} }
)
).rejects.toThrow('proxy apply failed')
expect(
beforeRequest({ url: 'http://proxy-only.invalid/', webContentsId: guest.id })
).toHaveBeenCalledWith({ cancel: true })
})
it('rejects first, then trusts only the approved guest, endpoint, certificate, and error', () => {
controller.onMainFrameNavigationStarted(guest.id)
const first = certificateEvent({ controller, guest })
expect(first.callback).toHaveBeenCalledOnce()
expect(first.callback).toHaveBeenCalledWith(false)
expect(first.preventDefault).not.toHaveBeenCalled()
expect(controller.getFailure('page-1')).toMatchObject({
challengeId: 'challenge-1',
browserPageId: 'page-1',
origin: 'https://localhost:3443',
displayHost: 'localhost:3443',
errorCode: -202,
canProceed: true
})
expect(controller.proceed('page-1', 'challenge-1')).toEqual({ ok: true })
expect(guest.loadURL).toHaveBeenCalledWith('https://localhost:3443/app')
expect(onFailureChanged).toHaveBeenLastCalledWith(guest.id, null)
const sameEndpoint = certificateEvent({
controller,
guest,
url: 'wss://localhost:3443/socket'
})
expect(sameEndpoint.preventDefault).toHaveBeenCalledOnce()
expect(sameEndpoint.callback).toHaveBeenCalledOnce()
expect(sameEndpoint.callback).toHaveBeenCalledWith(true)
const otherTab = certificateEvent({ controller, guest: otherGuest })
expect(otherTab.callback).toHaveBeenCalledWith(false)
expect(otherTab.preventDefault).not.toHaveBeenCalled()
const otherPort = certificateEvent({
controller,
guest,
url: 'https://localhost:3444/'
})
expect(otherPort.callback).toHaveBeenCalledWith(false)
expect(otherPort.preventDefault).not.toHaveBeenCalled()
const otherCertificate = certificateEvent({
controller,
guest,
certificate: SECOND_CERTIFICATE
})
expect(otherCertificate.callback).toHaveBeenCalledWith(false)
expect(otherCertificate.preventDefault).not.toHaveBeenCalled()
})
it('blocks a session-cached certificate for sibling requests until that guest approves it', () => {
certificateEvent({ controller, guest })
expect(controller.proceed('page-1', 'challenge-1')).toEqual({ ok: true })
@@ -257,120 +168,4 @@ describe('BrowserCertificateTrustController', () => {
expect(controller.proceed('page-2', 'challenge-2')).toEqual({ ok: true })
expect(beforeRequest({ webContentsId: otherGuest.id })).toHaveBeenCalledWith({})
})
it('fails closed when an accepted endpoint presents a replacement bad certificate', () => {
certificateEvent({ controller, guest })
expect(controller.proceed('page-1', 'challenge-1')).toEqual({ ok: true })
expect(certificateEvent({ controller, guest }).callback).toHaveBeenCalledWith(true)
controller.onMainFrameNavigationStarted(guest.id)
const replacement = certificateEvent({ controller, guest, certificate: SECOND_CERTIFICATE })
expect(replacement.callback).toHaveBeenCalledWith(false)
expect(replacement.preventDefault).not.toHaveBeenCalled()
expect(controller.getFailure('page-1')).toBeNull()
})
it('rejects proceed for a second tab whose pending leaf conflicts with an accepted identity', () => {
certificateEvent({ controller, guest })
certificateEvent({ controller, guest: otherGuest, certificate: SECOND_CERTIFICATE })
expect(controller.getFailure('page-1')?.challengeId).toBe('challenge-1')
expect(controller.getFailure('page-2')?.challengeId).toBe('challenge-2')
expect(controller.proceed('page-1', 'challenge-1')).toEqual({ ok: true })
expect(controller.proceed('page-2', 'challenge-2')).toEqual({
ok: false,
reason: 'ineligible'
})
expect(otherGuest.loadURL).not.toHaveBeenCalled()
})
it('never offers approval for public hosts, non-authority failures, or subframes', () => {
for (const event of [
certificateEvent({ controller, guest, url: 'https://example.com/' }),
certificateEvent({ controller, guest, error: 'ERR_CERT_DATE_INVALID' }),
certificateEvent({ controller, guest, isMainFrame: false })
]) {
expect(event.callback).toHaveBeenCalledOnce()
expect(event.callback).toHaveBeenCalledWith(false)
expect(event.preventDefault).not.toHaveBeenCalled()
}
expect(controller.getFailure('page-1')).toBeNull()
expect(onFailureChanged).not.toHaveBeenCalled()
})
it('queues an early challenge until the guest receives its browser page identity', () => {
pageByGuestId.set(guest.id, null)
certificateEvent({ controller, guest })
expect(onFailureChanged).not.toHaveBeenCalled()
expect(controller.getFailure('page-1')).toBeNull()
pageByGuestId.set(guest.id, 'page-1')
controller.onGuestRegistered(guest.id, 'page-1')
expect(onFailureChanged).toHaveBeenCalledWith(
guest.id,
expect.objectContaining({ challengeId: 'challenge-1', browserPageId: 'page-1' }),
'https://localhost:3443/app'
)
})
it('rejects stale, expired, destroyed, and mismatched approval attempts', () => {
certificateEvent({ controller, guest })
expect(controller.proceed('page-1', 'wrong-challenge')).toEqual({
ok: false,
reason: 'changed'
})
now += 5 * 60_000
expect(controller.proceed('page-1', 'challenge-1')).toEqual({
ok: false,
reason: 'expired'
})
certificateEvent({ controller, guest })
vi.mocked(guest.isDestroyed).mockReturnValue(true)
expect(controller.proceed('page-1', 'challenge-2')).toEqual({
ok: false,
reason: 'missing'
})
expect(guest.loadURL).not.toHaveBeenCalled()
})
it('clears pending approval and grants when navigation or guest ownership changes', () => {
certificateEvent({ controller, guest })
controller.onMainFrameNavigationStarted(guest.id)
expect(controller.getFailure('page-1')).toBeNull()
expect(controller.proceed('page-1', 'challenge-1')).toEqual({
ok: false,
reason: 'missing'
})
certificateEvent({ controller, guest })
expect(controller.proceed('page-1', 'challenge-2')).toEqual({ ok: true })
controller.onMainFrameNavigationCommitted(guest.id, 'https://example.com/')
const afterCommit = certificateEvent({ controller, guest })
expect(afterCommit.callback).toHaveBeenCalledWith(false)
controller.onGuestRetired(guest.id)
expect(controller.getFailure('page-1')).toBeNull()
})
it('answers malformed and unmanaged events exactly once without overriding Electron', () => {
pageByGuestId.delete(guest.id)
const unmanaged = certificateEvent({ controller, guest })
const malformedUrl = certificateEvent({ controller, guest: otherGuest, url: 'not a URL' })
const malformedCertificate = certificateEvent({
controller,
guest: otherGuest,
certificate: { data: 'not a PEM certificate' } as Electron.Certificate
})
for (const event of [unmanaged, malformedUrl, malformedCertificate]) {
expect(event.callback).toHaveBeenCalledOnce()
expect(event.callback).toHaveBeenCalledWith(false)
expect(event.preventDefault).not.toHaveBeenCalled()
}
})
})
@@ -20,191 +20,6 @@ afterEach(() => {
})
describe('BrowserClientHostCommandDispatcher', () => {
it('executes one FIFO command per page and replays duplicates exactly', async () => {
const create = deferred<BrowserClientHostCommandResult>()
const navigate = deferred<BrowserClientHostCommandResult>()
const handler = vi
.fn()
.mockReturnValueOnce(create.promise)
.mockReturnValueOnce(navigate.promise)
const dispatcher = new BrowserClientHostCommandDispatcher({ authority, handler })
const createCommand = command(1, 'create-a')
const navigateCommand = command(2, 'navigate-a', 'navigate')
const creating = dispatcher.dispatch(createCommand)
const duplicateCreating = dispatcher.dispatch(createCommand)
const navigating = dispatcher.dispatch(navigateCommand)
expect(handler).toHaveBeenCalledOnce()
expect(Object.isFrozen(handler.mock.calls[0]?.[0])).toBe(true)
expect(Object.isFrozen(handler.mock.calls[0]?.[0].command)).toBe(true)
create.resolve({ status: 'completed' })
await expect(creating).resolves.toEqual({ status: 'completed' })
await expect(duplicateCreating).resolves.toEqual({ status: 'completed' })
expect(Object.isFrozen(await creating)).toBe(true)
await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(2))
navigate.resolve({ status: 'completed' })
await expect(navigating).resolves.toEqual({ status: 'completed' })
await expect(dispatcher.dispatch(navigateCommand)).resolves.toEqual({ status: 'completed' })
expect(handler).toHaveBeenCalledTimes(2)
expect(() =>
dispatcher.dispatch({
...createCommand,
command: {
type: 'createPage',
browserProfileId: 'default',
executionHostKey: 'host-key-b'
}
})
).toThrow('browser_host_command_sequence_conflict')
expect(() =>
dispatcher.dispatch({
...navigateCommand,
command: { type: 'navigate', url: 'https://different.internal' }
})
).toThrow('browser_host_command_sequence_conflict')
})
it('rejects stale authority, sequence gaps, conflicts, and non-create first commands', () => {
const dispatcher = new BrowserClientHostCommandDispatcher({
authority,
handler: vi.fn().mockResolvedValue({ status: 'completed' })
})
expect(() =>
dispatcher.dispatch({ ...command(1, 'create-a'), authorityEpoch: 'epoch-b' })
).toThrow('browser_host_command_authority_stale')
expect(() => dispatcher.dispatch(command(1, 'navigate-a', 'navigate'))).toThrow(
'browser_host_command_create_required'
)
dispatcher.dispatch(command(1, 'create-a'))
expect(() => dispatcher.dispatch(command(3, 'navigate-b', 'navigate'))).toThrow(
'browser_host_command_sequence_gap'
)
expect(() => dispatcher.dispatch(command(1, 'different-id'))).toThrow(
'browser_host_command_sequence_conflict'
)
expect(() => dispatcher.dispatch(command(2, 'create-b'))).toThrow(
'browser_host_command_create_repeated'
)
})
it('snapshots lease authority instead of following caller mutation', async () => {
const mutableAuthority = { ...authority }
const dispatcher = new BrowserClientHostCommandDispatcher({
authority: mutableAuthority,
handler: vi.fn().mockResolvedValue({ status: 'completed' })
})
mutableAuthority.authorityEpoch = 'epoch-b'
await expect(dispatcher.dispatch(command(1, 'create-a'))).resolves.toEqual({
status: 'completed'
})
expect(() =>
dispatcher.dispatch({ ...command(2, 'navigate-a', 'navigate'), authorityEpoch: 'epoch-b' })
).toThrow('browser_host_command_authority_stale')
})
it('bounds pages, active commands, and cross-page handler concurrency', async () => {
const first = deferred<BrowserClientHostCommandResult>()
const second = deferred<BrowserClientHostCommandResult>()
const handler = vi.fn().mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
const dispatcher = new BrowserClientHostCommandDispatcher({
authority,
handler,
maxPages: 2,
maxActiveCommands: 2,
maxConcurrentHandlers: 1
})
const pageA = dispatcher.dispatch(command(1, 'create-a'))
const pageB = dispatcher.dispatch(command(1, 'create-b', 'createPage', 'page-b'))
expect(handler).toHaveBeenCalledOnce()
expect(() => dispatcher.dispatch(command(2, 'navigate-b', 'navigate', 'page-b'))).toThrow(
'browser_host_command_capacity'
)
expect(() => dispatcher.dispatch(command(1, 'create-c', 'createPage', 'page-c'))).toThrow(
'browser_host_page_capacity'
)
first.resolve({ status: 'completed' })
await pageA
await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(2))
second.resolve({ status: 'completed' })
await pageB
})
it('aborts and joins exact page retirement before admitting a new generation', async () => {
const handler = vi
.fn()
.mockImplementationOnce((_event: BrowserClientHostCommandEvent, signal: AbortSignal) => {
return new Promise<BrowserClientHostCommandResult>((resolve) => {
signal.addEventListener('abort', () => resolve({ status: 'completed' }), { once: true })
})
})
.mockResolvedValue({ status: 'completed' })
const dispatcher = new BrowserClientHostCommandDispatcher({ authority, handler })
const running = dispatcher.dispatch(command(1, 'create-a'))
const retirement = dispatcher.retirePage('page-a', 1)
await expect(running).resolves.toEqual({
status: 'failed',
errorCode: 'browser_host_command_cancelled'
})
await expect(retirement).resolves.toBe(true)
expect(() => dispatcher.dispatch(command(1, 'stale-a'))).toThrow(
'browser_host_page_generation_stale'
)
await dispatcher.dispatch(command(1, 'create-b', 'createPage', 'page-a', 2))
expect(handler).toHaveBeenCalledTimes(2)
})
it('does not consume page authority when admission fails', async () => {
const first = deferred<BrowserClientHostCommandResult>()
const handler = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue({
status: 'completed'
})
const dispatcher = new BrowserClientHostCommandDispatcher({
authority,
handler,
maxPages: 2,
maxActiveCommands: 1
})
expect(() => dispatcher.dispatch(command(1, 'invalid-a', 'navigate', 'page-a'))).toThrow(
'browser_host_command_create_required'
)
const running = dispatcher.dispatch(command(1, 'create-b', 'createPage', 'page-b'))
expect(() => dispatcher.dispatch(command(1, 'create-c', 'createPage', 'page-c'))).toThrow(
'browser_host_command_capacity'
)
first.resolve({ status: 'completed' })
await running
await expect(
dispatcher.dispatch(command(1, 'create-c', 'createPage', 'page-c'))
).resolves.toEqual({ status: 'completed' })
})
it('fails a create dependency once and never runs later page commands', async () => {
const handler = vi.fn().mockImplementationOnce(() => {
throw new Error('create failed')
})
const dispatcher = new BrowserClientHostCommandDispatcher({ authority, handler })
const create = dispatcher.dispatch(command(1, 'create-a'))
const navigate = dispatcher.dispatch(command(2, 'navigate-a', 'navigate'))
await expect(create).resolves.toEqual({
status: 'failed',
errorCode: 'browser_host_command_failed'
})
await expect(navigate).resolves.toEqual({
status: 'failed',
errorCode: 'browser_host_command_dependency_failed'
})
expect(() => dispatcher.dispatch(command(3, 'navigate-b', 'navigate'))).toThrow(
'browser_host_command_dependency_failed'
)
expect(handler).toHaveBeenCalledOnce()
})
it('keeps a timed-out retirement fenced until its handler actually settles', async () => {
vi.useFakeTimers()
const stuck = deferred<BrowserClientHostCommandResult>()
@@ -231,161 +46,6 @@ describe('BrowserClientHostCommandDispatcher', () => {
await dispatcher.dispatch(command(1, 'create-b', 'createPage', 'page-a', 2))
})
it('installs the retirement join before synchronously entering the handler', async () => {
vi.useFakeTimers()
const stuck = deferred<BrowserClientHostCommandResult>()
let retirement: Promise<boolean> | undefined
let dispatcher: BrowserClientHostCommandDispatcher
const handler = vi.fn(() => {
retirement = dispatcher.retirePage('page-a', 1)
return stuck.promise
})
dispatcher = new BrowserClientHostCommandDispatcher({
authority,
handler,
joinTimeoutMs: 50
})
const running = dispatcher.dispatch(command(1, 'create-a'))
await vi.advanceTimersByTimeAsync(50)
await expect(retirement).resolves.toBe(false)
await expect(running).resolves.toMatchObject({ errorCode: 'browser_host_command_cancelled' })
expect(() => dispatcher.dispatch(command(1, 'create-b', 'createPage', 'page-a', 2))).toThrow(
'browser_host_page_retirement_pending'
)
stuck.resolve({ status: 'completed' })
await vi.runAllTimersAsync()
})
it('publishes one shared retirement before an abort listener can reenter', async () => {
vi.useFakeTimers()
const stuck = deferred<BrowserClientHostCommandResult>()
let reentrantRetirement: Promise<boolean> | undefined
let dispatcher: BrowserClientHostCommandDispatcher
const handler = vi.fn((_event: BrowserClientHostCommandEvent, signal: AbortSignal) => {
signal.addEventListener(
'abort',
() => {
reentrantRetirement = dispatcher.retirePage('page-a', 1)
},
{ once: true }
)
return stuck.promise
})
dispatcher = new BrowserClientHostCommandDispatcher({
authority,
handler,
joinTimeoutMs: 50
})
const running = dispatcher.dispatch(command(1, 'create-a'))
const retirement = dispatcher.retirePage('page-a', 1)
expect(reentrantRetirement).toBeDefined()
expect(vi.getTimerCount()).toBe(1)
await vi.advanceTimersByTimeAsync(50)
await expect(retirement).resolves.toBe(false)
await expect(reentrantRetirement).resolves.toBe(false)
await expect(running).resolves.toMatchObject({ errorCode: 'browser_host_command_cancelled' })
stuck.resolve({ status: 'completed' })
await vi.runAllTimersAsync()
})
it('removes a retired queued generation before scheduling its replacement', async () => {
const first = deferred<BrowserClientHostCommandResult>()
const handler = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue({
status: 'completed'
})
const dispatcher = new BrowserClientHostCommandDispatcher({
authority,
handler,
maxConcurrentHandlers: 1
})
const pageA = dispatcher.dispatch(command(1, 'create-a'))
const oldPageB = dispatcher.dispatch(command(1, 'create-b', 'createPage', 'page-b'))
await expect(dispatcher.retirePage('page-b', 1)).resolves.toBe(true)
await expect(oldPageB).resolves.toMatchObject({ errorCode: 'browser_host_command_cancelled' })
const newPageB = dispatcher.dispatch(command(1, 'create-c', 'createPage', 'page-b', 2))
first.resolve({ status: 'completed' })
await pageA
await expect(newPageB).resolves.toEqual({ status: 'completed' })
expect(handler).toHaveBeenCalledTimes(2)
})
it('retains a global stale-generation floor after forgetting retired page state', async () => {
const handler = vi.fn().mockResolvedValue({ status: 'completed' })
const dispatcher = new BrowserClientHostCommandDispatcher({ authority, handler })
await dispatcher.dispatch(command(1, 'create-a'))
await dispatcher.retirePage('page-a', 1)
expect(dispatcher.forgetPage('page-a', 1)).toBe(true)
expect(() => dispatcher.dispatch(command(1, 'replayed-a'))).toThrow(
'browser_host_page_generation_stale'
)
await expect(
dispatcher.dispatch(command(1, 'create-b', 'createPage', 'page-b', 2))
).resolves.toEqual({ status: 'completed' })
expect(handler).toHaveBeenCalledTimes(2)
})
it('expires old cached results instead of replaying unknown side effects', async () => {
const handler = vi.fn().mockResolvedValue({ status: 'completed' })
const dispatcher = new BrowserClientHostCommandDispatcher({
authority,
handler,
maxCachedResultsPerPage: 1
})
const create = command(1, 'create-a')
const firstNavigation = command(2, 'navigate-a', 'navigate')
const secondNavigation = command(3, 'navigate-b', 'navigate')
await dispatcher.dispatch(create)
await dispatcher.dispatch(firstNavigation)
await dispatcher.dispatch(secondNavigation)
await expect(dispatcher.dispatch(secondNavigation)).resolves.toEqual({ status: 'completed' })
expect(() => dispatcher.dispatch(firstNavigation)).toThrow(
'browser_host_command_result_expired'
)
expect(handler).toHaveBeenCalledTimes(3)
})
it('bounds cached results across pages, not only within each page', async () => {
const handler = vi.fn().mockResolvedValue({ status: 'completed' })
const dispatcher = new BrowserClientHostCommandDispatcher({
authority,
handler,
maxCachedResultsPerPage: 2,
maxCachedCommandResults: 2
})
const createA = command(1, 'create-a')
const navigateA = command(2, 'navigate-a', 'navigate')
await dispatcher.dispatch(createA)
await dispatcher.dispatch(navigateA)
await dispatcher.dispatch(command(1, 'create-b', 'createPage', 'page-b'))
await expect(dispatcher.dispatch(navigateA)).resolves.toEqual({ status: 'completed' })
expect(() => dispatcher.dispatch(createA)).toThrow('browser_host_command_result_expired')
expect(handler).toHaveBeenCalledTimes(3)
})
it('releases a retired generation cache before charging its replacement', async () => {
const handler = vi.fn().mockResolvedValue({ status: 'completed' })
const dispatcher = new BrowserClientHostCommandDispatcher({
authority,
handler,
maxCachedCommandResults: 2
})
const pageB = command(1, 'create-b', 'createPage', 'page-b')
await dispatcher.dispatch(pageB)
await dispatcher.dispatch(command(1, 'create-a'))
await dispatcher.retirePage('page-a', 1)
await dispatcher.dispatch(command(1, 'create-c', 'createPage', 'page-a', 2))
await expect(dispatcher.dispatch(pageB)).resolves.toEqual({ status: 'completed' })
expect(handler).toHaveBeenCalledTimes(3)
})
it('bounds close while canceling queued and non-cooperative handlers', async () => {
vi.useFakeTimers()
const stuck = deferred<BrowserClientHostCommandResult>()
@@ -11,7 +11,6 @@ import {
createCommand,
createHarness
} from '../../client-pages/execution/browser-client-page-command-executor-test-harness'
import { executeBrowserClientUploadCommand } from './browser-client-upload-command'
import { BrowserClientUploadStaging } from './browser-client-upload-staging'
import {
BROWSER_CLIENT_FILE_CHANNEL_READ_METHOD,
@@ -190,27 +189,3 @@ it.each(['resolve', 'reject', 'page-release'] as const)(
}
}
)
it('keeps the original guest error and caller paths when a staged upload fails', async () => {
const services = fileServices(stagingRoot)
const params = { element: '#upload', files: [...remotePaths] }
const failure = new Error('controlled guest failure')
await expect(
executeBrowserClientUploadCommand({
event: createCommand('createPage', {
command: { type: 'automation', method: 'browser.upload', params }
}),
params,
fileChannel: services.transport,
staging: services.staging,
run: async (rewritten) => {
expect(rewritten).not.toBe(params)
await expectStagedBytes(readBrowserClientUploadPaths(rewritten))
throw failure
}
})
).rejects.toBe(failure)
expect(params).toEqual({ element: '#upload', files: remotePaths })
expect(services.staging.activeStagingCount()).toBe(0)
expect(await readdir(stagingRoot)).toHaveLength(0)
})
@@ -1,14 +1,9 @@
import { existsSync } from 'node:fs'
import { mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises'
import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
BROWSER_CLIENT_UPLOAD_STAGING_MAX_BYTES_PER_PAGE,
BROWSER_CLIENT_UPLOAD_STAGING_MAX_COMMANDS_PER_PAGE,
BrowserClientUploadStaging
} from './browser-client-upload-staging'
import { BrowserClientUploadStaging } from './browser-client-upload-staging'
let stagingRoot = ''
@@ -21,186 +16,7 @@ afterEach(async () => {
await rm(stagingRoot, { recursive: true, force: true })
})
async function releaseFailures(release: Promise<unknown>): Promise<string[]> {
const failure = await release.catch((error: unknown) => error)
expect(failure).toBeInstanceOf(AggregateError)
return (failure as AggregateError).errors.map((error: Error) => error.message)
}
describe('BrowserClientUploadStaging', () => {
it('writes remote bytes under main-owned directories and keeps the remote basename', async () => {
const staging = new BrowserClientUploadStaging(stagingRoot)
const staged = await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 3,
files: [
{ remotePath: 'docs/report.pdf', contents: Buffer.from('one') },
{ remotePath: 'notes.txt', contents: Buffer.from('two') }
]
})
expect(staged.localFilePaths.map((file) => path.basename(file))).toEqual([
'report.pdf',
'notes.txt'
])
for (const file of staged.localFilePaths) {
expect(await realpath(file)).toContain(stagingRoot)
}
expect(await readFile(staged.localFilePaths[0], 'utf8')).toBe('one')
expect(await readFile(staged.localFilePaths[1], 'utf8')).toBe('two')
})
it('never lets a remote path escape the staging root', async () => {
const staging = new BrowserClientUploadStaging(stagingRoot)
const staged = await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: '../../../etc/passwd', contents: Buffer.from('x') }]
})
expect(path.basename(staged.localFilePaths[0])).toBe('passwd')
expect(path.resolve(staged.localFilePaths[0]).startsWith(stagingRoot)).toBe(true)
})
it('removes the staged directory when the page is released', async () => {
const staging = new BrowserClientUploadStaging(stagingRoot)
const staged = await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 4,
files: [{ remotePath: 'a.txt', contents: Buffer.from('a') }]
})
expect(await staging.releasePage('page-2')).toBe(0)
expect(await readdir(stagingRoot)).toHaveLength(1)
expect(await staging.releasePage('page-1')).toBe(1)
expect(await readdir(stagingRoot)).toHaveLength(0)
expect(staging.stagedDirectory(staged.stagingId)).toBeUndefined()
})
it('releases only the matching page generation when one is named', async () => {
const staging = new BrowserClientUploadStaging(stagingRoot)
await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: 'a.txt', contents: Buffer.from('a') }]
})
await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 2,
files: [{ remotePath: 'b.txt', contents: Buffer.from('b') }]
})
expect(await staging.releasePage('page-1', 1)).toBe(1)
expect(staging.activeStagingCount()).toBe(1)
})
it('evicts a page oldest-first once its staged bytes exceed the budget', async () => {
const removed: string[] = []
const staging = new BrowserClientUploadStaging(stagingRoot, {
mkdir: async () => {},
writeFile: async () => {},
removeDirectorySync: () => {},
removeDirectory: async (directory) => {
removed.push(directory)
}
})
const half = BROWSER_CLIENT_UPLOAD_STAGING_MAX_BYTES_PER_PAGE / 2
const first = await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: 'a.bin', contents: Buffer.alloc(half) }]
})
const firstDirectory = staging.stagedDirectory(first.stagingId)
await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: 'b.bin', contents: Buffer.alloc(half) }]
})
expect(staging.activeStagingCount()).toBe(2)
await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: 'c.bin', contents: Buffer.alloc(1) }]
})
expect(staging.activeStagingCount()).toBe(2)
expect(removed).toEqual([firstDirectory])
})
it("leaves another page's staged copies alone when one page overflows", async () => {
const staging = new BrowserClientUploadStaging(stagingRoot)
await staging.stage({
browserPageId: 'page-2',
pageHostGeneration: 1,
files: [{ remotePath: 'keep.txt', contents: Buffer.from('keep') }]
})
for (let index = 0; index <= BROWSER_CLIENT_UPLOAD_STAGING_MAX_COMMANDS_PER_PAGE; index += 1) {
await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: `${index}.txt`, contents: Buffer.from('x') }]
})
}
expect(staging.activeStagingCount()).toBe(
BROWSER_CLIENT_UPLOAD_STAGING_MAX_COMMANDS_PER_PAGE + 1
)
expect(await staging.releasePage('page-2')).toBe(1)
})
it('cleans up the partial directory when a write fails', async () => {
let writes = 0
const staging = new BrowserClientUploadStaging(stagingRoot, {
mkdir: async () => {},
writeFile: async () => {
writes += 1
throw new Error('disk full')
},
removeDirectorySync: () => {},
removeDirectory: async () => {}
})
await expect(
staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: 'a.txt', contents: Buffer.from('a') }]
})
).rejects.toThrow('disk full')
expect(writes).toBe(1)
expect(staging.activeStagingCount()).toBe(0)
})
it('rejects an oversized or over-counted staging request before touching disk', async () => {
const staging = new BrowserClientUploadStaging(stagingRoot)
await expect(
staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: Array.from({ length: 17 }, (_unused, index) => ({
remotePath: `${index}.txt`,
contents: Buffer.alloc(1)
}))
})
).rejects.toThrow('browser_client_upload_file_count_exceeded')
await expect(
staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: 'big.bin', contents: Buffer.alloc(64 * 1024 * 1024 + 1) }]
})
).rejects.toThrow('browser_client_upload_too_large')
expect(staging.activeStagingCount()).toBe(0)
expect(existsSync(stagingRoot)).toBe(false)
})
it('sweeps staged bytes an abnormal exit left in the root', async () => {
const orphan = path.join(stagingRoot, 'abandoned', '0')
await mkdir(orphan, { recursive: true })
@@ -210,88 +26,4 @@ describe('BrowserClientUploadStaging', () => {
expect(existsSync(path.join(stagingRoot, 'abandoned'))).toBe(false)
})
it('keeps the staged record when its removal fails so a later release retries it', async () => {
const attempts: string[] = []
const staging = new BrowserClientUploadStaging(stagingRoot, {
mkdir: async () => {},
writeFile: async () => {},
removeDirectorySync: () => {},
removeDirectory: async (directory) => {
attempts.push(directory)
if (attempts.length === 1) {
throw new Error('EBUSY: resource busy or locked')
}
}
})
const staged = await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: 'a.txt', contents: Buffer.from('a') }]
})
const directory = staging.stagedDirectory(staged.stagingId)
expect(await releaseFailures(staging.releasePage('page-1'))).toEqual([
expect.stringContaining('EBUSY')
])
expect(staging.activeStagingCount()).toBe(1)
expect(await staging.releasePage('page-1')).toBe(1)
expect(staging.activeStagingCount()).toBe(0)
expect(attempts).toEqual([directory, directory])
})
it('attempts every staged record even when one removal fails', async () => {
const attempts: string[] = []
const staging = new BrowserClientUploadStaging(stagingRoot, {
mkdir: async () => {},
writeFile: async () => {},
removeDirectorySync: () => {},
removeDirectory: async (directory) => {
attempts.push(directory)
if (attempts.length === 1) {
throw new Error('EBUSY: resource busy or locked')
}
}
})
const first = await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: 'a.txt', contents: Buffer.from('a') }]
})
const second = await staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: 'b.txt', contents: Buffer.from('b') }]
})
const directories = [first, second].map((staged) => staging.stagedDirectory(staged.stagingId))
expect(await releaseFailures(staging.releasePage('page-1'))).toHaveLength(1)
expect(attempts).toEqual(directories)
expect(staging.activeStagingCount()).toBe(1)
})
it('reports the staging failure, not the cleanup failure, when both fail', async () => {
const staging = new BrowserClientUploadStaging(stagingRoot, {
mkdir: async () => {},
writeFile: async () => {
throw new Error('disk full')
},
removeDirectorySync: () => {},
removeDirectory: async () => {
throw new Error('EBUSY: resource busy or locked')
}
})
await expect(
staging.stage({
browserPageId: 'page-1',
pageHostGeneration: 1,
files: [{ remotePath: 'a.txt', contents: Buffer.from('a') }]
})
).rejects.toThrow('disk full')
// A later release needs the retained directory record to retry cleanup.
expect(staging.activeStagingCount()).toBe(1)
})
})
@@ -1,537 +0,0 @@
import { pairedRuntimeConnectionFromOffer } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { PairingOffer } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer'
import type {
RemoteRuntimeSubscription,
RemoteRuntimeSubscriptionCallbacks
} from '../../../../shared/remote-runtime/remote-runtime-client'
import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error'
import type { BrowserClientAutomationResult as BrowserClientHostCommandResult } from '../../../../shared/browser/client-hosting/browser-client-automation-protocol'
const { subscribeRemoteRuntimeRequestMock } = vi.hoisted(() => ({
subscribeRemoteRuntimeRequestMock: vi.fn()
}))
vi.mock('../../../../shared/remote-runtime/remote-runtime-client', () => ({
subscribeRemoteRuntimeRequest: subscribeRemoteRuntimeRequestMock
}))
import { PairedRuntimeBrowserHostLease } from './paired-runtime-browser-host-lease'
import type { PairedRuntimeBrowserHostLeaseOptions } from './paired-runtime-browser-host-lease-options'
const pairing = {
v: 2,
endpoint: 'ws://127.0.0.1:6768',
deviceToken: 'device-token',
publicKeyB64: 'public-key',
pairedDeviceId: 'device-a',
scope: 'runtime'
} as PairingOffer
afterEach(() => {
subscribeRemoteRuntimeRequestMock.mockReset()
vi.restoreAllMocks()
vi.useRealTimers()
})
describe('PairedRuntimeBrowserHostLease reconnect', () => {
it('retries initial runtime_busy admission and attaches when capacity returns', async () => {
vi.useFakeTimers()
const attempts = mockAttempts()
const onError = vi.fn()
const onReconnected = vi.fn()
const onTransportLost = vi.fn()
const lease = createReconnectLease({
timeoutMs: 500,
reconnectRetryDelayMs: 50,
onError,
onReconnected,
onTransportLost
})
const starting = lease.start()
void starting.catch(() => undefined)
await Promise.resolve()
attempts[0]!.callbacks.onError(capacityError())
await vi.advanceTimersByTimeAsync(50)
expect(attempts).toHaveLength(2)
attempts[1]!.callbacks.onResponse(readyResponse(true))
await expect(starting).resolves.toMatchObject({ browserHostGeneration: 4 })
expect(attempts[0]!.close).toHaveBeenCalledOnce()
expect(onTransportLost).not.toHaveBeenCalled()
expect(onReconnected).not.toHaveBeenCalled()
expect(onError).not.toHaveBeenCalled()
await lease.close()
expect(attempts[1]!.close).toHaveBeenCalledOnce()
expect(vi.getTimerCount()).toBe(0)
})
it('bounds initial runtime_busy retries and releases every attempt', async () => {
vi.useFakeTimers()
const closes: ReturnType<typeof vi.fn>[] = []
subscribeRemoteRuntimeRequestMock.mockImplementation(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
const callbacks = args[4] as RemoteRuntimeSubscriptionCallbacks
const close = vi.fn()
closes.push(close)
queueMicrotask(() => callbacks.onError(capacityError()))
return {
requestId: `browser-host-${closes.length}`,
close,
sendBinary: () => false
}
}
)
const onError = vi.fn()
const lease = createReconnectLease({
timeoutMs: 250,
reconnectRetryDelayMs: 50,
onError
})
const starting = lease.start()
void starting.catch(() => undefined)
await vi.advanceTimersByTimeAsync(300)
await expect(starting).rejects.toThrow('attach capacity retry expired')
expect(closes.length).toBeGreaterThan(1)
expect(closes.every((close) => close.mock.calls.length === 1)).toBe(true)
expect(onError).toHaveBeenCalledOnce()
expect(vi.getTimerCount()).toBe(0)
})
it('cancels initial admission backoff without retaining a subscription', async () => {
vi.useFakeTimers()
const attempts = mockAttempts()
const onError = vi.fn()
const lease = createReconnectLease({
timeoutMs: 500,
reconnectRetryDelayMs: 50,
onError
})
const starting = lease.start()
void starting.catch(() => undefined)
await Promise.resolve()
attempts[0]!.callbacks.onError(capacityError())
await vi.advanceTimersByTimeAsync(0)
await lease.close()
await expect(starting).rejects.toThrow('Browser host lease is closed')
await vi.advanceTimersByTimeAsync(500)
expect(attempts).toHaveLength(1)
expect(attempts[0]!.close).toHaveBeenCalledOnce()
expect(onError).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
})
it('restores exact authority across repeated loss and ignores stale callbacks', async () => {
const attempts = mockAttempts()
const onTransportLost = vi.fn()
const onReconnected = vi.fn()
const onError = vi.fn()
const lease = createReconnectLease({ onTransportLost, onReconnected, onError })
const starting = lease.start()
await vi.waitFor(() => expect(attempts).toHaveLength(1))
attempts[0]!.callbacks.onResponse(readyResponse(true))
const authority = await starting
attempts[0]!.callbacks.onError(recoverableError())
attempts[0]!.callbacks.onClose?.()
await vi.waitFor(() => expect(attempts).toHaveLength(2))
attempts[1]!.callbacks.onResponse(readyResponse(true))
await vi.waitFor(() => expect(onReconnected).toHaveBeenCalledOnce())
attempts[0]!.callbacks.onResponse(readyResponse(true, 9))
attempts[0]!.callbacks.onError(recoverableError())
attempts[1]!.callbacks.onError(recoverableError())
await vi.waitFor(() => expect(attempts).toHaveLength(3))
attempts[2]!.callbacks.onResponse(readyResponse(true))
await vi.waitFor(() => expect(onReconnected).toHaveBeenCalledTimes(2))
expect(onTransportLost).toHaveBeenCalledTimes(2)
expect(onReconnected).toHaveBeenCalledWith(authority)
expect(onError).not.toHaveBeenCalled()
expect(attempts[0]!.close).toHaveBeenCalledOnce()
await lease.close()
expect(attempts[1]!.close).toHaveBeenCalledOnce()
expect(attempts[2]!.close).toHaveBeenCalledOnce()
})
it('retries runtime_busy during reconnect grace without replacing authority', async () => {
vi.useFakeTimers()
const attempts = mockAttempts()
const onError = vi.fn()
const onReconnected = vi.fn()
const lease = createReconnectLease({
reconnectGraceMs: 500,
reconnectRetryDelayMs: 50,
timeoutMs: 100,
onError,
onReconnected
})
const starting = lease.start()
await Promise.resolve()
attempts[0]!.callbacks.onResponse(readyResponse(true))
const authority = await starting
attempts[0]!.callbacks.onError(recoverableError())
await vi.advanceTimersByTimeAsync(50)
expect(attempts).toHaveLength(2)
attempts[1]!.callbacks.onError(capacityError())
await vi.advanceTimersByTimeAsync(100)
expect(attempts).toHaveLength(3)
attempts[2]!.callbacks.onResponse(readyResponse(true))
await vi.advanceTimersByTimeAsync(0)
expect(onReconnected).toHaveBeenCalledWith(authority)
expect(onError).not.toHaveBeenCalled()
await lease.close()
expect(attempts.every((attempt) => attempt.close.mock.calls.length === 1)).toBe(true)
expect(vi.getTimerCount()).toBe(0)
})
it('does not double-charge result capacity when outstanding commands replay', async () => {
const attempts = mockAttempts()
const results = new Map([
['page-a', deferredCommandResult()],
['page-b', deferredCommandResult()]
])
const onPageCommand = vi.fn(
(command) =>
results.get(command.browserPageId)?.promise ?? Promise.reject(new Error('unknown'))
)
const onError = vi.fn()
const lease = createReconnectLease({
maxConcurrentCommandResults: 1,
maxUnsettledCommandResults: 2,
onPageCommand,
onError
})
const starting = lease.start()
await vi.waitFor(() => expect(attempts).toHaveLength(1))
attempts[0]!.callbacks.onResponse(readyResponse(true))
await starting
const commands = [
commandResponse({ browserPageId: 'page-a', commandId: 'shared-command' }),
commandResponse({
browserPageId: 'page-b',
pageHostGeneration: 2,
commandId: 'shared-command'
})
]
for (const command of commands) {
attempts[0]!.callbacks.onResponse(command)
}
await vi.waitFor(() => expect(onPageCommand).toHaveBeenCalledTimes(2))
attempts[0]!.callbacks.onError(recoverableError())
await vi.waitFor(() => expect(attempts).toHaveLength(2))
attempts[1]!.callbacks.onResponse(readyResponse(true))
for (const command of commands) {
attempts[1]!.callbacks.onResponse(command)
}
await vi.waitFor(() => expect(onPageCommand).toHaveBeenCalledTimes(4))
expect(onError).not.toHaveBeenCalled()
results.get('page-a')!.resolve({ status: 'completed' })
results.get('page-b')!.resolve({ status: 'completed' })
await vi.waitFor(() => expect(attempts[1]!.sendRequest).toHaveBeenCalledTimes(2))
expect(onError).not.toHaveBeenCalled()
await lease.close()
})
it('keeps missing reconnect echo on legacy immediate teardown semantics', async () => {
const attempts = mockAttempts()
const onTransportLost = vi.fn()
const onError = vi.fn()
const lease = createReconnectLease({ onTransportLost, onError })
const starting = lease.start()
await vi.waitFor(() => expect(attempts).toHaveLength(1))
attempts[0]!.callbacks.onResponse(readyResponse(false))
await starting
attempts[0]!.callbacks.onError(recoverableError())
attempts[0]!.callbacks.onClose?.()
await vi.waitFor(() => expect(onError).toHaveBeenCalledOnce())
expect(onTransportLost).not.toHaveBeenCalled()
expect(attempts).toHaveLength(1)
expect(attempts[0]!.close).toHaveBeenCalledOnce()
})
it('rejects malformed or unsolicited reconnect echoes', async () => {
const malformedAttempts = mockAttempts()
const malformedError = vi.fn()
const malformed = createReconnectLease({ onError: malformedError })
const malformedStart = malformed.start()
await vi.waitFor(() => expect(malformedAttempts).toHaveLength(1))
malformedAttempts[0]!.callbacks.onResponse({
...readyResponse(true),
result: {
...readyResponse(true).result,
pageInventoryProtocolVersion: undefined
}
})
await expect(malformedStart).rejects.toThrow('Invalid browser host lease response')
subscribeRemoteRuntimeRequestMock.mockReset()
const unsolicitedAttempts = mockAttempts()
const unsolicited = new PairedRuntimeBrowserHostLease({
connection: pairedRuntimeConnectionFromOffer(pairing),
authorityRuntimeId: 'runtime-a',
browserHostClientId: 'host-a',
hostCapabilities: ['webview']
})
const unsolicitedStart = unsolicited.start()
await vi.waitFor(() => expect(unsolicitedAttempts).toHaveLength(1))
unsolicitedAttempts[0]!.callbacks.onResponse(readyResponse(true))
await expect(unsolicitedStart).rejects.toThrow('Invalid browser host lease response')
})
it('fails terminally when a reconnect cannot encode a complete inventory', async () => {
const attempts = mockAttempts()
const getPageInventory = vi
.fn()
.mockReturnValueOnce([])
.mockReturnValueOnce([
{
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-a',
browserHostClientId: 'host-a',
browserHostGeneration: 4,
browserPageId: 'page-a',
pageHostGeneration: 1,
browserProfileId: 'x'.repeat(400),
executionHostKey: 'native:runtime-a:1',
state: 'active'
}
])
const onError = vi.fn()
const lease = createReconnectLease({ getPageInventory, onError })
const starting = lease.start()
await vi.waitFor(() => expect(attempts).toHaveLength(1))
attempts[0]!.callbacks.onResponse(readyResponse(true))
await starting
attempts[0]!.callbacks.onError(recoverableError())
await vi.waitFor(() => expect(attempts).toHaveLength(2))
expect(attempts[1]!.params).not.toHaveProperty('pageInventoryProtocolVersion')
expect(attempts[1]!.params).not.toHaveProperty('leaseReconnectProtocolVersion')
attempts[1]!.callbacks.onResponse(readyResponse(false, 5))
await vi.waitFor(() => expect(onError).toHaveBeenCalledOnce())
expect(attempts).toHaveLength(2)
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({ message: 'Invalid browser host lease response' })
)
})
it('rejects a reconnect that changes the exact authority', async () => {
const attempts = mockAttempts()
const onError = vi.fn()
const lease = createReconnectLease({ onError })
const starting = lease.start()
await vi.waitFor(() => expect(attempts).toHaveLength(1))
attempts[0]!.callbacks.onResponse(readyResponse(true))
await starting
attempts[0]!.callbacks.onError(recoverableError())
await vi.waitFor(() => expect(attempts).toHaveLength(2))
attempts[1]!.callbacks.onResponse(readyResponse(true, 5))
await vi.waitFor(() => expect(onError).toHaveBeenCalledOnce())
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({ message: 'Browser host lease authority changed in place' })
)
expect(attempts[1]!.close).toHaveBeenCalledOnce()
})
it('treats an explicit revocation during reconnect as terminal', async () => {
const attempts = mockAttempts()
const onError = vi.fn()
const lease = createReconnectLease({ onError })
const starting = lease.start()
await vi.waitFor(() => expect(attempts).toHaveLength(1))
attempts[0]!.callbacks.onResponse(readyResponse(true))
await starting
attempts[0]!.callbacks.onError(recoverableError())
await vi.waitFor(() => expect(attempts).toHaveLength(2))
attempts[1]!.callbacks.onResponse({
id: 'browser-host',
ok: true,
result: {
type: 'revoked',
authorityEpoch: 'epoch-a',
browserHostGeneration: 4,
reason: 'released'
},
_meta: { runtimeId: 'runtime-a' }
})
await vi.waitFor(() => expect(onError).toHaveBeenCalledOnce())
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({ message: 'Browser host lease revoked: released' })
)
expect(attempts[1]!.close).toHaveBeenCalledOnce()
})
it('expires bounded reconnect attempts without retaining timers or subscriptions', async () => {
vi.useFakeTimers()
const attempts = mockAttempts()
const onTransportLost = vi.fn()
const onError = vi.fn()
const lease = createReconnectLease({
reconnectGraceMs: 250,
reconnectRetryDelayMs: 50,
timeoutMs: 100,
onTransportLost,
onError
})
const starting = lease.start()
await Promise.resolve()
attempts[0]!.callbacks.onResponse(readyResponse(true))
await starting
attempts[0]!.callbacks.onError(recoverableError())
await vi.advanceTimersByTimeAsync(300)
expect(attempts).toHaveLength(3)
expect(onTransportLost).toHaveBeenCalledOnce()
expect(onError).toHaveBeenCalledOnce()
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({ message: expect.stringContaining('reconnect grace expired') })
)
expect(attempts.every((attempt) => attempt.close.mock.calls.length === 1)).toBe(true)
expect(vi.getTimerCount()).toBe(0)
})
})
function createReconnectLease(
overrides: Partial<PairedRuntimeBrowserHostLeaseOptions>
): PairedRuntimeBrowserHostLease {
return new PairedRuntimeBrowserHostLease({
connection: pairedRuntimeConnectionFromOffer(pairing),
authorityRuntimeId: 'runtime-a',
browserHostClientId: 'host-a',
hostCapabilities: ['webview'],
pageCommandProtocolVersion: 1,
pageInventoryProtocolVersion: 1,
leaseReconnectProtocolVersion: 1,
getPageInventory: () => [],
onPageCommand: () => ({ status: 'completed' }),
...overrides
})
}
function mockAttempts(): {
callbacks: RemoteRuntimeSubscriptionCallbacks
close: ReturnType<typeof vi.fn>
params: Record<string, unknown>
sendRequest: ReturnType<typeof vi.fn>
}[] {
const attempts: {
callbacks: RemoteRuntimeSubscriptionCallbacks
close: ReturnType<typeof vi.fn>
params: Record<string, unknown>
sendRequest: ReturnType<typeof vi.fn>
}[] = []
subscribeRemoteRuntimeRequestMock.mockImplementation(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
const close = vi.fn()
const sendRequest = vi.fn().mockResolvedValue({
id: 'command-result',
ok: true,
result: { accepted: true },
_meta: { runtimeId: 'runtime-a' }
})
attempts.push({
callbacks: args[4] as RemoteRuntimeSubscriptionCallbacks,
close,
params: args[2] as Record<string, unknown>,
sendRequest
})
return {
requestId: `browser-host-${attempts.length}`,
close,
sendBinary: () => false,
sendRequest
}
}
)
return attempts
}
function readyResponse(reconnect: boolean, browserHostGeneration = 4) {
return {
id: 'browser-host',
ok: true as const,
result: {
type: 'ready' as const,
authorityEpoch: 'epoch-a',
browserHostGeneration,
pageCommandProtocolVersion: 1 as const,
pageInventoryProtocolVersion: 1 as const,
...(reconnect ? { leaseReconnectProtocolVersion: 1 as const } : {})
},
_meta: { runtimeId: 'runtime-a' }
}
}
function recoverableError(): RemoteRuntimeClientError {
return new RemoteRuntimeClientError('remote_runtime_unavailable', 'transport failed')
}
function capacityError(): RemoteRuntimeClientError {
return new RemoteRuntimeClientError(
'runtime_busy',
'browser-host capacity reached; retry with backoff'
)
}
function deferredCommandResult(): {
promise: Promise<BrowserClientHostCommandResult>
resolve: (result: BrowserClientHostCommandResult) => void
} {
let resolve = (_result: BrowserClientHostCommandResult): void => {}
const promise = new Promise<BrowserClientHostCommandResult>((innerResolve) => {
resolve = innerResolve
})
return { promise, resolve }
}
function commandResponse(
overrides: {
browserPageId?: string
pageHostGeneration?: number
commandId?: string
} = {}
) {
return {
id: 'browser-host',
ok: true as const,
result: {
type: 'command' as const,
pageCommandProtocolVersion: 1 as const,
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-a',
browserHostClientId: 'host-a',
browserHostGeneration: 4,
browserPageId: 'page-a',
pageHostGeneration: 1,
commandSequence: 1,
commandId: 'command-a',
command: {
type: 'createPage' as const,
browserProfileId: 'default',
executionHostKey: 'native:runtime-a:1'
},
...overrides
},
_meta: { runtimeId: 'runtime-a' }
}
}
@@ -2,20 +2,11 @@ import { pairedRuntimeConnectionFromOffer } from '../../../../shared/remote-runt
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { BrowserClientAutomationResult as BrowserClientHostCommandResult } from '../../../../shared/browser/client-hosting/browser-client-automation-protocol'
import {
type BrowserClientHostedPageInventory,
type BrowserClientHostCommandEvent,
BROWSER_CLIENT_HOST_PAGE_INVENTORY_MAX_BYTES,
browserClientHostedPageInventoryByteLength
} from '../../../../shared/browser/client-hosting/browser-client-host-protocol'
import {
BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY,
BROWSER_CLIENT_PAGE_METADATA_RUNTIME_CAPABILITY
} from '../../../../shared/browser-runtime-capabilities'
import type {
RemoteRuntimeSubscription,
RemoteRuntimeSubscriptionCallbacks
} from '../../../../shared/remote-runtime/remote-runtime-client'
BrowserClientHostedPageInventory,
BrowserClientHostCommandEvent
} from '../../../../shared/browser/client-hosting/browser-client-host-protocol'
import type { RemoteRuntimeSubscription } from '../../../../shared/remote-runtime/remote-runtime-client'
const { subscribeRemoteRuntimeRequestMock } = vi.hoisted(() => ({
subscribeRemoteRuntimeRequestMock: vi.fn()
@@ -40,481 +31,6 @@ afterEach(() => {
})
describe('PairedRuntimeBrowserHostLease', () => {
it.each([
[{ maxConcurrentCommandResults: 17 }, 'limit is invalid'],
[{ maxUnsettledCommandResults: 257 }, 'limit is invalid'],
[{ maxConcurrentCommandResults: 2, maxUnsettledCommandResults: 1 }, 'limits are inconsistent'],
[{ getPageInventory: () => [] }, 'inventory negotiation is incomplete'],
[{ pageInventoryProtocolVersion: 1 as const }, 'inventory negotiation is incomplete']
])('rejects unsafe command-result limits', (limits, expectedMessage) => {
expect(() => createLease(limits)).toThrow(expectedMessage)
})
it('returns only the runtime-issued epoch and generation', async () => {
let callbacks: RemoteRuntimeSubscriptionCallbacks | undefined
const close = vi.fn()
subscribeRemoteRuntimeRequestMock.mockImplementationOnce(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
callbacks = args[4] as RemoteRuntimeSubscriptionCallbacks
return { requestId: 'browser-host', close, sendBinary: () => false }
}
)
const lease = createLease()
const starting = lease.start()
await vi.waitFor(() => expect(callbacks).toBeDefined())
callbacks!.onResponse({
id: 'browser-host',
ok: true,
result: { type: 'ready', authorityEpoch: 'epoch-a', browserHostGeneration: 4 },
_meta: { runtimeId: 'runtime-a' }
})
await expect(starting).resolves.toEqual({
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-a',
browserHostClientId: 'host-a',
browserHostGeneration: 4
})
expect(subscribeRemoteRuntimeRequestMock).toHaveBeenCalledWith(
pairing,
'browser.clientHost.attach',
{
authorityRuntimeId: 'runtime-a',
browserHostClientId: 'host-a',
hostCapabilities: ['webview']
},
expect.any(Number),
expect.any(Object),
expect.objectContaining({
clientCapabilities: [
BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY,
BROWSER_CLIENT_PAGE_METADATA_RUNTIME_CAPABILITY
]
})
)
expectInitialAttachTimeout()
await lease.close()
expect(close).toHaveBeenCalledOnce()
})
it('sends page metadata over its own attached connection', async () => {
const sendRequest = vi.fn().mockResolvedValue({
ok: true,
result: { accepted: true },
_meta: { runtimeId: 'runtime-a' }
})
const { callbacks } = await subscribeLease({ sendRequest })
const lease = createLease()
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse())
await starting
await expect(lease.sendPageMetadataRequest({ revision: 2 }, 1_000)).resolves.toMatchObject({
ok: true
})
expect(sendRequest).toHaveBeenCalledWith(
'browser.clientHost.pageMetadata',
{ revision: 2 },
1_000
)
await lease.close()
expect(() => lease.sendPageMetadataRequest({ revision: 3 }, 1_000)).toThrow(
'Remote runtime browser host lease is unavailable.'
)
})
it('uses page commands only after the host echoes the requested protocol', async () => {
const { callbacks, close, sendRequest } = await subscribeLease()
const onPageCommand = vi.fn(() => ({ status: 'completed' as const }))
const lease = createLease({ pageCommandProtocolVersion: 1, onPageCommand })
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse({
id: 'browser-host',
ok: true,
result: {
type: 'ready',
authorityEpoch: 'epoch-a',
browserHostGeneration: 4,
pageCommandProtocolVersion: 1
},
_meta: { runtimeId: 'runtime-a' }
})
await expect(starting).resolves.toMatchObject({ pageCommandProtocolVersion: 1 })
expect(subscribeRemoteRuntimeRequestMock).toHaveBeenCalledWith(
pairing,
'browser.clientHost.attach',
expect.objectContaining({ pageCommandProtocolVersion: 1 }),
expect.any(Number),
expect.any(Object),
expect.any(Object)
)
expectInitialAttachTimeout()
callbacks.current!.onResponse(commandResponse())
expect(onPageCommand).toHaveBeenCalledOnce()
await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledOnce())
expect(sendRequest).toHaveBeenCalledWith(
'browser.clientHost.commandResult',
{
pageCommandProtocolVersion: 1,
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-a',
browserHostClientId: 'host-a',
browserHostGeneration: 4,
browserPageId: 'page-a',
pageHostGeneration: 1,
commandSequence: 1,
commandId: 'command-a',
result: { status: 'completed' }
},
15_000
)
expect(close).not.toHaveBeenCalled()
await lease.close()
})
it('sends one complete inventory snapshot and activates it only after the echo', async () => {
const { callbacks } = await subscribeLease()
const page = inventoryPage()
const getPageInventory = vi.fn(() => [page])
const lease = createLease({
pageInventoryProtocolVersion: 1,
getPageInventory
})
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
expect(getPageInventory).toHaveBeenCalledOnce()
expect(subscribeRemoteRuntimeRequestMock).toHaveBeenCalledWith(
pairing,
'browser.clientHost.attach',
expect.objectContaining({
pageInventoryProtocolVersion: 1,
pageInventory: [page]
}),
expect.any(Number),
expect.any(Object),
expect.any(Object)
)
expectInitialAttachTimeout()
callbacks.current!.onResponse(readyResponse({ pageInventoryProtocolVersion: 1 }))
await expect(starting).resolves.toMatchObject({ pageInventoryProtocolVersion: 1 })
await lease.close()
})
it('omits optional URLs deterministically to keep every page identity within budget', async () => {
const { callbacks } = await subscribeLease()
const inventory = Array.from({ length: 256 }, (_, index) => ({
...inventoryPage(),
browserPageId: `page-${index.toString().padStart(3, '0')}`,
currentUrl: `https://remote.internal/${index}/${'x'.repeat(4096)}`
}))
const lease = createLease({
pageInventoryProtocolVersion: 1,
getPageInventory: () => inventory
})
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
const attach = subscribeRemoteRuntimeRequestMock.mock.calls[0]?.[2] as {
pageInventory: BrowserClientHostedPageInventory[]
}
expect(attach.pageInventory).toHaveLength(256)
expect(browserClientHostedPageInventoryByteLength(attach.pageInventory)).toBeLessThanOrEqual(
BROWSER_CLIENT_HOST_PAGE_INVENTORY_MAX_BYTES
)
expect(attach.pageInventory.some((page) => page.currentUrl === undefined)).toBe(true)
expect(new Set(attach.pageInventory.map((page) => page.browserPageId)).size).toBe(256)
callbacks.current!.onResponse(readyResponse({ pageInventoryProtocolVersion: 1 }))
await starting
await lease.close()
})
it('treats a missing inventory echo as unsupported rather than accepted empty state', async () => {
const { callbacks } = await subscribeLease()
const lease = createLease({
pageInventoryProtocolVersion: 1,
getPageInventory: () => []
})
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse())
await expect(starting).resolves.not.toHaveProperty('pageInventoryProtocolVersion')
expect(subscribeRemoteRuntimeRequestMock).toHaveBeenCalledWith(
pairing,
'browser.clientHost.attach',
expect.objectContaining({ pageInventoryProtocolVersion: 1, pageInventory: [] }),
expect.any(Number),
expect.any(Object),
expect.any(Object)
)
expectInitialAttachTimeout()
await lease.close()
})
it('rejects an unsolicited inventory echo', async () => {
const { callbacks } = await subscribeLease()
const lease = createLease()
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse({ pageInventoryProtocolVersion: 1 }))
await expect(starting).rejects.toThrow('Invalid browser host lease response')
await lease.close()
})
it.each([
['completed', { status: 'completed' } as const],
['failed', { status: 'failed', errorCode: 'navigation_failed' } as const]
])('submits a validated %s page command result', async (_caseName, result) => {
const { callbacks, close, sendRequest } = await subscribeLease()
const lease = createLease({
pageCommandProtocolVersion: 1,
onPageCommand: () => result
})
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse({ pageCommandProtocolVersion: 1 }))
await starting
callbacks.current!.onResponse(commandResponse())
await vi.waitFor(() =>
expect(sendRequest).toHaveBeenCalledWith(
'browser.clientHost.commandResult',
expect.objectContaining({ result }),
15_000
)
)
expect(close).not.toHaveBeenCalled()
await lease.close()
})
it('accepts exact duplicate result acknowledgement without fencing the lease', async () => {
const { callbacks, close, sendRequest } = await subscribeLease()
sendRequest
.mockResolvedValueOnce(commandResultAck(true))
.mockResolvedValueOnce(commandResultAck(false))
const lease = createLease({
pageCommandProtocolVersion: 1,
onPageCommand: () => ({ status: 'completed' })
})
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse({ pageCommandProtocolVersion: 1 }))
await starting
callbacks.current!.onResponse(commandResponse())
await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(1))
callbacks.current!.onResponse(commandResponse())
await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(2))
expect(close).not.toHaveBeenCalled()
await lease.close()
})
it('bounds concurrent command-result requests below the subscription request ceiling', async () => {
const acknowledgements = Array.from({ length: 8 }, () => deferredCommandResultAck())
let active = 0
let peak = 0
const sendRequest = vi.fn().mockImplementation(() => {
const acknowledgement = acknowledgements[sendRequest.mock.calls.length - 1]
active += 1
peak = Math.max(peak, active)
return acknowledgement.promise.finally(() => {
active -= 1
})
})
const { callbacks } = await subscribeLease({ sendRequest })
const lease = createLease({
maxConcurrentCommandResults: 4,
pageCommandProtocolVersion: 1,
onPageCommand: () => ({ status: 'completed' })
})
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse({ pageCommandProtocolVersion: 1 }))
await starting
for (let index = 0; index < acknowledgements.length; index += 1) {
callbacks.current!.onResponse(
commandResponse({
browserPageId: `page-${index}`,
pageHostGeneration: index + 1,
commandId: `command-${index}`
})
)
}
await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(4))
expect(peak).toBe(4)
acknowledgements[0].resolve(commandResultAck(true))
await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(5))
expect(peak).toBe(4)
await lease.close()
})
it('fails closed when unsettled command results exceed the explicit lease bound', async () => {
const never = new Promise<never>(() => {})
const { callbacks, close } = await subscribeLease({
sendRequest: vi.fn(() => never)
})
const onError = vi.fn()
const lease = createLease({
maxConcurrentCommandResults: 1,
maxUnsettledCommandResults: 2,
pageCommandProtocolVersion: 1,
onPageCommand: () => ({ status: 'completed' }),
onError
})
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse({ pageCommandProtocolVersion: 1 }))
await starting
for (let index = 0; index < 3; index += 1) {
callbacks.current!.onResponse(
commandResponse({
browserPageId: `page-${index}`,
pageHostGeneration: index + 1,
commandId: `command-${index}`
})
)
}
await vi.waitFor(() => expect(close).toHaveBeenCalledOnce())
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({ message: 'Browser host command result capacity reached' })
)
})
it.each([
[
'server rejection',
vi.fn().mockResolvedValue({
id: 'command-result',
ok: false,
error: { code: 'runtime_error', message: 'command result rejected' },
_meta: { runtimeId: 'runtime-a' }
}),
'command result rejected'
],
[
'transport timeout',
vi.fn().mockRejectedValue(new Error('command result timed out')),
'command result timed out'
],
[
'malformed acknowledgement',
vi.fn().mockResolvedValue({
id: 'command-result',
ok: true,
result: { accepted: 'yes' },
_meta: { runtimeId: 'runtime-a' }
}),
'Invalid browser host command result acknowledgement'
],
[
'wrong runtime acknowledgement',
vi.fn().mockResolvedValue(commandResultAck(true, 'runtime-b')),
'Invalid browser host command result acknowledgement'
]
])('fails closed on %s', async (_caseName, sendRequest, expectedMessage) => {
const { callbacks, close } = await subscribeLease({ sendRequest })
const onError = vi.fn()
const lease = createLease({
pageCommandProtocolVersion: 1,
onPageCommand: () => ({ status: 'completed' }),
onError
})
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse({ pageCommandProtocolVersion: 1 }))
await starting
callbacks.current!.onResponse(commandResponse())
await vi.waitFor(() => expect(close).toHaveBeenCalledOnce())
expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: expectedMessage }))
})
it('fails closed when a v1 subscription lacks the same-socket request sender', async () => {
const { callbacks, close } = await subscribeLease({ sendRequest: undefined })
const onError = vi.fn()
const lease = createLease({
pageCommandProtocolVersion: 1,
onPageCommand: () => ({ status: 'completed' }),
onError
})
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse({ pageCommandProtocolVersion: 1 }))
await expect(starting).rejects.toThrow('Browser host command result transport unavailable')
await vi.waitFor(() => expect(close).toHaveBeenCalledOnce())
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({ message: 'Browser host command result transport unavailable' })
)
})
it.each([
[
'throws',
'command handler threw',
() => {
throw new Error('command handler threw')
}
],
[
'rejects',
'command handler rejected',
() => Promise.reject(new Error('command handler rejected'))
]
])('fails closed when the page command handler %s', async (_caseName, message, onPageCommand) => {
const { callbacks, close, sendRequest } = await subscribeLease()
const onError = vi.fn()
const lease = createLease({ pageCommandProtocolVersion: 1, onPageCommand, onError })
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse({ pageCommandProtocolVersion: 1 }))
await starting
callbacks.current!.onResponse(commandResponse())
await vi.waitFor(() => expect(close).toHaveBeenCalledOnce())
expect(sendRequest).not.toHaveBeenCalled()
expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message }))
})
it('rejects malformed lease authority instead of adopting it', async () => {
let callbacks: RemoteRuntimeSubscriptionCallbacks | undefined
const close = vi.fn()
subscribeRemoteRuntimeRequestMock.mockImplementationOnce(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
callbacks = args[4] as RemoteRuntimeSubscriptionCallbacks
return { requestId: 'browser-host', close, sendBinary: () => false }
}
)
const lease = createLease()
const starting = lease.start()
await vi.waitFor(() => expect(callbacks).toBeDefined())
callbacks!.onResponse({
id: 'browser-host',
ok: true,
result: { type: 'ready', authorityEpoch: '', browserHostGeneration: 0 },
_meta: { runtimeId: 'runtime-a' }
})
await expect(starting).rejects.toThrow('Invalid browser host lease response')
expect(close).toHaveBeenCalledOnce()
})
it('closes a subscription acquired after local teardown', async () => {
let resolveSubscription = (_subscription: RemoteRuntimeSubscription): void => {}
const close = vi.fn()
@@ -531,160 +47,8 @@ describe('PairedRuntimeBrowserHostLease', () => {
await expect(starting).rejects.toThrow('closed during startup')
expect(close).toHaveBeenCalledOnce()
})
it('closes and reports an exact server revocation after readiness', async () => {
let callbacks: RemoteRuntimeSubscriptionCallbacks | undefined
const close = vi.fn()
const onError = vi.fn()
subscribeRemoteRuntimeRequestMock.mockImplementationOnce(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
callbacks = args[4] as RemoteRuntimeSubscriptionCallbacks
return { requestId: 'browser-host', close, sendBinary: () => false }
}
)
const lease = createLease({ onError })
const starting = lease.start()
await vi.waitFor(() => expect(callbacks).toBeDefined())
callbacks!.onResponse({
id: 'browser-host',
ok: true,
result: { type: 'ready', authorityEpoch: 'epoch-a', browserHostGeneration: 4 },
_meta: { runtimeId: 'runtime-a' }
})
await starting
callbacks!.onResponse({
id: 'browser-host',
ok: true,
result: {
type: 'revoked',
authorityEpoch: 'epoch-a',
browserHostGeneration: 4,
reason: 'replaced'
},
_meta: { runtimeId: 'runtime-a' }
})
await vi.waitFor(() => expect(close).toHaveBeenCalledOnce())
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({ message: 'Browser host lease revoked: replaced' })
)
})
it('rejects revocation before adopting lease authority', async () => {
const { callbacks, close } = await subscribeLease()
const lease = createLease()
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse({
id: 'browser-host',
ok: true,
result: {
type: 'revoked',
authorityEpoch: 'epoch-a',
browserHostGeneration: 4,
reason: 'released'
},
_meta: { runtimeId: 'runtime-a' }
})
await expect(starting).rejects.toThrow('Invalid browser host lease revocation')
expect(close).toHaveBeenCalledOnce()
})
it.each([
['wrong epoch', 'epoch-b', 4, 'replaced', 'Invalid browser host lease revocation'],
['wrong generation', 'epoch-a', 5, 'released', 'Invalid browser host lease revocation'],
['malformed reason', 'epoch-a', 4, 'unknown', 'Invalid browser host lease response']
])(
'fails closed on %s after readiness',
async (_caseName, authorityEpoch, browserHostGeneration, reason, expectedError) => {
const { callbacks, close } = await subscribeLease()
const onError = vi.fn()
const lease = createLease({ onError })
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse({
id: 'browser-host',
ok: true,
result: { type: 'ready', authorityEpoch: 'epoch-a', browserHostGeneration: 4 },
_meta: { runtimeId: 'runtime-a' }
})
await starting
callbacks.current!.onResponse({
id: 'browser-host',
ok: true,
result: { type: 'revoked', authorityEpoch, browserHostGeneration, reason },
_meta: { runtimeId: 'runtime-a' }
})
await vi.waitFor(() => expect(close).toHaveBeenCalledOnce())
expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: expectedError }))
}
)
it('keeps duplicate readiness and events after local close idempotent', async () => {
const { callbacks, close } = await subscribeLease()
const onError = vi.fn()
const lease = createLease({ onError })
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
const ready = {
id: 'browser-host',
ok: true as const,
result: { type: 'ready', authorityEpoch: 'epoch-a', browserHostGeneration: 4 },
_meta: { runtimeId: 'runtime-a' }
}
callbacks.current!.onResponse(ready)
await starting
callbacks.current!.onResponse(ready)
await lease.close()
callbacks.current!.onClose?.()
expect(close).toHaveBeenCalledOnce()
expect(onError).not.toHaveBeenCalled()
})
})
function expectInitialAttachTimeout(): void {
const timeoutMs = subscribeRemoteRuntimeRequestMock.mock.calls[0]?.[3]
expect(timeoutMs).toEqual(expect.any(Number))
expect(timeoutMs).toBeGreaterThan(0)
expect(timeoutMs).toBeLessThanOrEqual(15_000)
}
async function subscribeLease(options?: { sendRequest?: ReturnType<typeof vi.fn> }): Promise<{
callbacks: { current?: RemoteRuntimeSubscriptionCallbacks }
close: ReturnType<typeof vi.fn>
sendRequest: ReturnType<typeof vi.fn>
}> {
const callbacks: { current?: RemoteRuntimeSubscriptionCallbacks } = {}
const close = vi.fn()
const sendRequest =
options && 'sendRequest' in options
? options.sendRequest
: vi.fn().mockResolvedValue(commandResultAck(true))
subscribeRemoteRuntimeRequestMock.mockImplementationOnce(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
callbacks.current = args[4] as RemoteRuntimeSubscriptionCallbacks
const subscription: RemoteRuntimeSubscription = {
requestId: 'browser-host',
close,
sendBinary: () => false,
...(sendRequest
? {
sendRequest: sendRequest as unknown as RemoteRuntimeSubscription['sendRequest']
}
: {})
}
return subscription
}
)
return { callbacks, close, sendRequest: sendRequest ?? vi.fn() }
}
function createLease(
overrides: {
getPageInventory?: () => readonly BrowserClientHostedPageInventory[]
@@ -706,86 +70,3 @@ function createLease(
...overrides
})
}
function inventoryPage(): BrowserClientHostedPageInventory {
return {
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-old',
browserHostClientId: 'host-a',
browserHostGeneration: 2,
browserPageId: 'page-a',
pageHostGeneration: 3,
browserProfileId: 'profile-a',
executionHostKey: 'native:runtime-a:1',
state: 'active',
currentUrl: 'https://remote.internal/'
}
}
function readyResponse(
overrides: { pageCommandProtocolVersion?: 1; pageInventoryProtocolVersion?: 1 } = {}
) {
return {
id: 'browser-host',
ok: true as const,
result: {
type: 'ready' as const,
authorityEpoch: 'epoch-a',
browserHostGeneration: 4,
...overrides
},
_meta: { runtimeId: 'runtime-a' }
}
}
function commandResponse(
overrides: {
browserPageId?: string
pageHostGeneration?: number
commandId?: string
} = {}
) {
return {
id: 'browser-host',
ok: true as const,
result: {
type: 'command' as const,
pageCommandProtocolVersion: 1 as const,
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-a',
browserHostClientId: 'host-a',
browserHostGeneration: 4,
browserPageId: 'page-a',
pageHostGeneration: 1,
commandSequence: 1,
commandId: 'command-a',
command: {
type: 'createPage' as const,
browserProfileId: 'default',
executionHostKey: 'native:runtime-a:1'
},
...overrides
},
_meta: { runtimeId: 'runtime-a' }
}
}
function deferredCommandResultAck(): {
promise: Promise<ReturnType<typeof commandResultAck>>
resolve: (value: ReturnType<typeof commandResultAck>) => void
} {
let resolve = (_value: ReturnType<typeof commandResultAck>): void => {}
const promise = new Promise<ReturnType<typeof commandResultAck>>((innerResolve) => {
resolve = innerResolve
})
return { promise, resolve }
}
function commandResultAck(accepted: boolean, runtimeId = 'runtime-a') {
return {
id: 'command-result',
ok: true as const,
result: { accepted },
_meta: { runtimeId }
}
}
@@ -1,231 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import {
BROWSER_CLIENT_AUTOMATION_RUNTIME_CAPABILITY,
BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY,
BROWSER_CLIENT_PAGE_METADATA_RUNTIME_CAPABILITY,
BROWSER_NETWORK_EXECUTION_HOSTS_RUNTIME_CAPABILITY,
BROWSER_NETWORK_TUNNEL_RUNTIME_CAPABILITY,
BROWSER_SCREENCAST_RUNTIME_CAPABILITY
} from '../../../../shared/browser-runtime-capabilities'
import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments'
import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope'
import type { RuntimeStatus } from '../../../../shared/runtime-session-contracts'
import { prepareBrowserClientHostPlacement } from './browser-client-host-placement-preparation'
const REQUIRED_CAPABILITIES = [
BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY,
BROWSER_CLIENT_PAGE_METADATA_RUNTIME_CAPABILITY,
BROWSER_CLIENT_AUTOMATION_RUNTIME_CAPABILITY,
BROWSER_NETWORK_TUNNEL_RUNTIME_CAPABILITY,
BROWSER_NETWORK_EXECUTION_HOSTS_RUNTIME_CAPABILITY
] as const
describe('browser client host placement preparation', () => {
it('starts the exact capable paired host and returns its client identity', async () => {
const harness = createHarness()
await expect(harness.prepare()).resolves.toEqual({
kind: 'client',
browserHostClientId: 'browser-client-a'
})
expect(harness.getStatus).toHaveBeenCalledWith('environment-a')
expect(harness.startHost).toHaveBeenCalledWith({
environment: expect.objectContaining({ id: 'environment-a', pairingRevision: 7 }),
authorityRuntimeId: 'runtime-a'
})
expect(harness.closeHost).not.toHaveBeenCalled()
})
it('keeps explicit server placement on the server without probing or starting a client host', async () => {
const harness = createHarness()
await expect(harness.prepare({ preference: 'server' })).resolves.toEqual({ kind: 'server' })
expect(harness.getStatus).not.toHaveBeenCalled()
expect(harness.startHost).not.toHaveBeenCalled()
})
it('renders on the server when the setting asks for it and the server can stream', async () => {
const harness = createHarness({
status: runtimeStatus({
capabilities: [...REQUIRED_CAPABILITIES, BROWSER_SCREENCAST_RUNTIME_CAPABILITY]
})
})
await expect(harness.prepare({ enabled: false })).resolves.toEqual({ kind: 'server' })
expect(harness.startHost).not.toHaveBeenCalled()
})
it('hosts on this desktop when the setting asks for the server but the server cannot stream', async () => {
const harness = createHarness()
await expect(harness.prepare({ enabled: false })).resolves.toEqual({
kind: 'client',
browserHostClientId: 'browser-client-a'
})
})
it('keeps an older host on the server when any required capability is absent', async () => {
const harness = createHarness({
status: runtimeStatus({ capabilities: REQUIRED_CAPABILITIES.slice(0, 2) })
})
await expect(harness.prepare()).resolves.toEqual({ kind: 'server' })
expect(harness.startHost).not.toHaveBeenCalled()
})
it('keeps a mobile-scoped pairing on the server even when capabilities are advertised', async () => {
const harness = createHarness({
status: runtimeStatus({ deviceScope: 'mobile' })
})
await expect(harness.prepare()).resolves.toEqual({ kind: 'server' })
expect(harness.startHost).not.toHaveBeenCalled()
})
it('surfaces a capable host start failure without falling back to server placement', async () => {
const harness = createHarness()
harness.startHost.mockRejectedValueOnce(new Error('attach failed'))
await expect(harness.prepare()).rejects.toThrow('attach failed')
expect(harness.startHost).toHaveBeenCalledTimes(1)
})
it('rejects a runtime identity mismatch before starting a client host', async () => {
const harness = createHarness({
status: runtimeStatus({}, { responseRuntimeId: 'runtime-b' })
})
await expect(harness.prepare()).rejects.toThrow('browser_client_host_runtime_identity_changed')
expect(harness.startHost).not.toHaveBeenCalled()
})
it('rejects a non-ready capable runtime instead of changing placement', async () => {
const harness = createHarness({ status: runtimeStatus({ graphStatus: 'reloading' }) })
await expect(harness.prepare()).rejects.toThrow('browser_client_host_runtime_not_ready')
expect(harness.startHost).not.toHaveBeenCalled()
})
it('rejects a pairing change observed after status without starting either identity', async () => {
const harness = createHarness({
environments: [environment(7), environment(8)]
})
await expect(harness.prepare()).rejects.toThrow('browser_client_host_pairing_changed')
expect(harness.startHost).not.toHaveBeenCalled()
})
it('retires the attached host when its pairing changes before placement is returned', async () => {
const harness = createHarness({
environments: [environment(7), environment(7), environment(8)]
})
await expect(harness.prepare()).rejects.toThrow('browser_client_host_pairing_changed')
expect(harness.startHost).toHaveBeenCalledTimes(1)
expect(harness.closeHost).toHaveBeenCalledWith(
'environment-a',
expect.objectContaining({ message: 'browser_client_host_pairing_changed' })
)
})
it.each([
['an offline host', 'runtime_unavailable', 'offline'],
['a timed-out probe', 'timeout', 'status.get timed out']
])('keeps %s on the server instead of failing the create', async (_label, code, message) => {
const harness = createHarness({
status: {
id: 'status.get',
ok: false,
error: { code, message },
_meta: { runtimeId: 'runtime-a' }
}
})
await expect(harness.prepare()).resolves.toEqual({ kind: 'server' })
expect(harness.startHost).not.toHaveBeenCalled()
expect(harness.closeHost).not.toHaveBeenCalled()
})
})
function createHarness(options?: {
environments?: KnownRuntimeEnvironment[]
status?: RuntimeRpcResponse<RuntimeStatus>
}) {
const environments = options?.environments ?? [environment(7), environment(7), environment(7)]
let environmentIndex = 0
const resolveEnvironment = vi.fn(() => {
const resolved = environments[Math.min(environmentIndex, environments.length - 1)]!
environmentIndex += 1
return resolved
})
const getStatus = vi.fn(async () => options?.status ?? runtimeStatus())
const startHost = vi.fn(async () => ({
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-a',
browserHostClientId: 'browser-client-a',
browserHostGeneration: 1
}))
const closeHost = vi.fn(async () => true)
return {
getStatus,
startHost,
closeHost,
prepare: (overrides?: { preference?: 'auto' | 'server'; enabled?: boolean }) =>
prepareBrowserClientHostPlacement({
selector: 'environment-a',
expectedPairingRevision: 7,
preference: overrides?.preference ?? 'auto',
enabled: overrides?.enabled ?? true,
resolveEnvironment,
getStatus,
startHost,
closeHost
})
}
}
function environment(pairingRevision: number): KnownRuntimeEnvironment {
return {
id: 'environment-a',
name: 'Environment A',
createdAt: 1,
updatedAt: pairingRevision,
pairingRevision,
pairedDeviceId: 'device-a',
lastUsedAt: null,
runtimeId: 'runtime-a',
endpoints: [
{
id: 'endpoint-a',
kind: 'websocket',
label: 'WebSocket',
endpoint: 'ws://runtime-a.test',
deviceToken: 'token-a',
publicKeyB64: 'key-a'
}
],
preferredEndpointId: 'endpoint-a'
}
}
function runtimeStatus(
overrides: Partial<RuntimeStatus> = {},
options?: { responseRuntimeId?: string }
): RuntimeRpcResponse<RuntimeStatus> {
const runtimeId = overrides.runtimeId ?? 'runtime-a'
return {
id: 'status.get',
ok: true,
result: {
runtimeId,
rendererGraphEpoch: 1,
graphStatus: 'ready',
authoritativeWindowId: 1,
liveTabCount: 0,
liveLeafCount: 0,
capabilities: [...REQUIRED_CAPABILITIES],
...overrides
},
_meta: { runtimeId: options?.responseRuntimeId ?? runtimeId }
}
}
@@ -1,278 +0,0 @@
import type {
BrowserClientHostCommandEvent,
BrowserClientHostLeaseAuthority
} from '../../../../shared/browser/client-hosting/browser-client-host-protocol'
import { describe, expect, it, vi } from 'vitest'
import { BrowserHostCommandLedger } from '../../../runtime/browser-host/commands/browser-host-command-ledger'
import { BrowserClientHostCommandDispatcher } from '../commands/browser-client-host-command-dispatcher'
const authority: BrowserClientHostLeaseAuthority & {
pageCommandProtocolVersion: 1
pageReconciliationProtocolVersion: 1
} = {
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-new',
browserHostClientId: 'host-a',
browserHostGeneration: 3,
pageCommandProtocolVersion: 1,
pageReconciliationProtocolVersion: 1
}
const previousAuthority = {
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-old',
browserHostClientId: 'host-a',
browserHostGeneration: 2,
pageHostGeneration: 7
}
function event(
command: BrowserClientHostCommandEvent['command'],
overrides: Partial<BrowserClientHostCommandEvent> = {}
): BrowserClientHostCommandEvent {
return {
type: 'command',
...authority,
browserPageId: 'page-a',
pageHostGeneration: command.type === 'closePage' ? 7 : 8,
commandSequence: 1,
commandId: `${command.type}-a`,
command,
...overrides
}
}
describe('browser reconciliation command ordering', () => {
it.each([
{
type: 'reclaimPage' as const,
previousAuthority,
browserProfileId: 'profile-a',
executionHostKey: 'host-key-a'
},
{
type: 'restorePage' as const,
browserProfileId: 'profile-a',
executionHostKey: 'host-key-a'
},
{ type: 'closePage' as const, targetAuthority: previousAuthority }
])('admits $type as an authenticated first client-dispatch command', async (command) => {
const handler = vi.fn().mockResolvedValue({ status: 'completed' })
const dispatcher = new BrowserClientHostCommandDispatcher({ authority, handler })
await expect(dispatcher.dispatch(event(command))).resolves.toEqual({ status: 'completed' })
expect(handler).toHaveBeenCalledOnce()
})
it('deduplicates exact reclaim bootstrap and rejects changed prior authority', async () => {
const handler = vi.fn().mockResolvedValue({ status: 'completed' })
const dispatcher = new BrowserClientHostCommandDispatcher({ authority, handler })
const reclaim = event({
type: 'reclaimPage',
previousAuthority,
browserProfileId: 'profile-a',
executionHostKey: 'host-key-a'
})
const first = dispatcher.dispatch(reclaim)
const duplicate = dispatcher.dispatch(reclaim)
await expect(first).resolves.toEqual({ status: 'completed' })
await expect(duplicate).resolves.toEqual({ status: 'completed' })
expect(handler).toHaveBeenCalledOnce()
expect(() =>
dispatcher.dispatch({
...reclaim,
command: {
...reclaim.command,
previousAuthority: { ...previousAuthority, authorityEpoch: 'different' }
}
} as BrowserClientHostCommandEvent)
).toThrow('browser_host_command_sequence_conflict')
})
it('snapshots nested reconciliation authority on both sides of dispatch', async () => {
const handler = vi.fn().mockResolvedValue({ status: 'completed' })
const dispatcher = new BrowserClientHostCommandDispatcher({ authority, handler })
const clientAuthority = { ...previousAuthority }
const clientEvent = event({
type: 'reclaimPage',
previousAuthority: clientAuthority,
browserProfileId: 'profile-a',
executionHostKey: 'host-key-a'
})
const dispatched = dispatcher.dispatch(clientEvent)
clientAuthority.authorityEpoch = 'mutated-client'
await dispatched
const accepted = handler.mock.calls[0]?.[0] as BrowserClientHostCommandEvent
expect(accepted.command).toMatchObject({
previousAuthority: expect.objectContaining({ authorityEpoch: 'epoch-old' })
})
expect(
Object.isFrozen(accepted.command.type === 'reclaimPage' && accepted.command.previousAuthority)
).toBe(true)
const delivery = vi.fn()
const ledger = new BrowserHostCommandLedger({ authority })
ledger.attach(delivery)
const serverAuthority = { ...previousAuthority }
ledger.issue({
browserPageId: 'page-b',
pageHostGeneration: 8,
command: {
type: 'reclaimPage',
previousAuthority: serverAuthority,
browserProfileId: 'profile-a',
executionHostKey: 'host-key-a'
}
})
serverAuthority.authorityEpoch = 'mutated-server'
const emitted = delivery.mock.calls[0]?.[0] as BrowserClientHostCommandEvent
expect(emitted.command).toMatchObject({
previousAuthority: expect.objectContaining({ authorityEpoch: 'epoch-old' })
})
expect(
Object.isFrozen(emitted.command.type === 'reclaimPage' && emitted.command.previousAuthority)
).toBe(true)
})
it.each(['reclaimPage', 'restorePage'] as const)(
'cancels navigation when %s bootstrap fails',
async (type) => {
const handler = vi
.fn()
.mockResolvedValueOnce({ status: 'failed', errorCode: 'bootstrap_failed' })
const dispatcher = new BrowserClientHostCommandDispatcher({ authority, handler })
const bootstrap =
type === 'reclaimPage'
? {
type,
previousAuthority,
browserProfileId: 'profile-a',
executionHostKey: 'host-key-a'
}
: {
type,
browserProfileId: 'profile-a',
executionHostKey: 'host-key-a'
}
const first = dispatcher.dispatch(event(bootstrap))
const navigate = dispatcher.dispatch(
event(
{ type: 'navigate', url: 'https://remote.internal/' },
{ commandSequence: 2, commandId: `${type}-navigate` }
)
)
await expect(first).resolves.toEqual({
status: 'failed',
errorCode: 'bootstrap_failed'
})
await expect(navigate).resolves.toEqual({
status: 'failed',
errorCode: 'browser_host_command_dependency_failed'
})
expect(handler).toHaveBeenCalledOnce()
}
)
it('makes an exact close terminal while allowing navigate after reclaim', async () => {
const dispatcher = new BrowserClientHostCommandDispatcher({
authority,
handler: vi.fn().mockResolvedValue({ status: 'completed' })
})
await dispatcher.dispatch(
event({
type: 'reclaimPage',
previousAuthority,
browserProfileId: 'profile-a',
executionHostKey: 'host-key-a'
})
)
await expect(
dispatcher.dispatch(
event(
{ type: 'navigate', url: 'https://remote.internal/' },
{ commandSequence: 2, commandId: 'navigate-a' }
)
)
).resolves.toEqual({ status: 'completed' })
const closing = new BrowserClientHostCommandDispatcher({
authority,
handler: vi.fn().mockResolvedValue({ status: 'completed' })
})
await closing.dispatch(event({ type: 'closePage', targetAuthority: previousAuthority }))
expect(() =>
closing.dispatch(
event(
{ type: 'navigate', url: 'https://remote.internal/' },
{ commandSequence: 2, commandId: 'navigate-after-close', pageHostGeneration: 7 }
)
)
).toThrow('browser_host_page_generation_stale')
})
it('allows the same generation to continue after a failed close', async () => {
const handler = vi
.fn()
.mockResolvedValueOnce({ status: 'failed', errorCode: 'authority_stale' })
.mockResolvedValueOnce({ status: 'completed' })
const dispatcher = new BrowserClientHostCommandDispatcher({ authority, handler })
await expect(
dispatcher.dispatch(event({ type: 'closePage', targetAuthority: previousAuthority }))
).resolves.toEqual({ status: 'failed', errorCode: 'authority_stale' })
await expect(
dispatcher.dispatch(
event(
{ type: 'navigate', url: 'https://remote.internal/' },
{ commandSequence: 2, commandId: 'navigate-after-failed-close', pageHostGeneration: 7 }
)
)
).resolves.toEqual({ status: 'completed' })
})
it('issues reconciliation bootstrap commands from the server ledger without create', () => {
const delivery = vi.fn()
const ledger = new BrowserHostCommandLedger({ authority })
ledger.attach(delivery)
const reclaim = ledger.issue({
browserPageId: 'page-a',
pageHostGeneration: 8,
command: {
type: 'reclaimPage',
previousAuthority,
browserProfileId: 'profile-a',
executionHostKey: 'host-key-a'
}
})
const navigate = ledger.issue({
browserPageId: 'page-a',
pageHostGeneration: 8,
command: { type: 'navigate', url: 'https://remote.internal/' }
})
const close = ledger.issue({
browserPageId: 'page-b',
pageHostGeneration: 9,
resultAdmission: 'reconciliation',
command: {
type: 'closePage',
targetAuthority: { ...previousAuthority, pageHostGeneration: 9 }
}
})
expect(reclaim.event.commandSequence).toBe(1)
expect(navigate.event.commandSequence).toBe(2)
expect(close.event.commandSequence).toBe(1)
expect(delivery).toHaveBeenCalledTimes(3)
expect(() =>
ledger.issue({
browserPageId: 'page-b',
pageHostGeneration: 9,
command: { type: 'navigate', url: 'https://after-close.invalid/' }
})
).toThrow('browser_host_command_page_terminal')
})
})
@@ -1,11 +1,10 @@
import { describe, expect, it, vi } from 'vitest'
import { BrowserClientHostAuthorityReplacementWait } from './browser-client-host-authority-replacement-wait'
import {
type BrowserClientHostedPageInventory,
type BrowserClientHostCommandEvent,
type BrowserClientHostLeaseAuthority,
BROWSER_CLIENT_HOST_AUTHORITY_MISMATCH_CODE
import type {
BrowserClientHostedPageInventory,
BrowserClientHostCommandEvent,
BrowserClientHostLeaseAuthority
} from '../../../../shared/browser/client-hosting/browser-client-host-protocol'
import { PairedRuntimeBrowserClientHostComposition } from './paired-runtime-browser-client-host-composition'
@@ -38,119 +37,6 @@ const replacementInput = {
}
describe('PairedRuntimeBrowserClientHostComposition', () => {
it('activates exact route authority before admitting page commands', async () => {
const rig = createRig()
const composition = rig.createComposition()
await expect(composition.start()).resolves.toEqual(authority)
await rig.hostOptions.handler?.(command(), new AbortController().signal)
expect(rig.order).toEqual(['activate-routes', 'handle-command'])
})
it('provides the exact executor inventory to the host attach', () => {
const rig = createRig()
rig.createComposition()
expect(rig.hostOptions.getPageInventory?.()).toEqual([
expect.objectContaining({ browserPageId: 'page-a', state: 'active' })
])
expect(rig.executor.snapshotPageInventory).toHaveBeenCalledOnce()
})
it('publishes a fresh inventory snapshot for every reconnect attach', () => {
const rig = createRig({ pageInventory: [] })
rig.executor.snapshotPageInventory
.mockReturnValueOnce([])
.mockReturnValueOnce([retainedPageInventory()])
rig.createComposition()
expect(rig.hostOptions.getPageInventory?.()).toEqual([])
expect(rig.hostOptions.getPageInventory?.()).toEqual([
expect.objectContaining({ browserPageId: 'page-a', state: 'active' })
])
expect(rig.executor.snapshotPageInventory).toHaveBeenCalledTimes(2)
})
it('coalesces page availability losses into one inventory refresh', async () => {
const rig = createRig()
rig.createComposition()
rig.reportPageUnavailable()
rig.reportPageUnavailable()
expect(rig.host.refreshPageInventory).toHaveBeenCalledOnce()
await Promise.resolve()
await Promise.resolve()
rig.reportPageUnavailable()
expect(rig.host.refreshPageInventory).toHaveBeenCalledTimes(2)
})
it('preserves inventory while replacing authority with fresh routes', async () => {
const rig = createRig()
const composition = rig.createComposition()
await composition.start()
await expect(composition.replaceAuthority(replacementInput)).resolves.toEqual(
replacementAuthority
)
expect(rig.replacementInventory).toEqual([
expect.objectContaining({ browserPageId: 'page-a', authorityRuntimeId: 'runtime-a' })
])
expect(rig.executor.close).not.toHaveBeenCalled()
expect(rig.routes.close).not.toHaveBeenCalled()
expect(rig.order).toEqual([
'activate-routes',
'retire-routes',
'fence-authority-transition',
'close-host',
'complete-authority-transition',
'attach-replacement-inventory',
'activate-replacement-routes'
])
})
it('rejects retained inventory when replacement cannot reconcile it', async () => {
const rig = createRig({
replacementAuthority: {
...replacementAuthority,
pageInventoryProtocolVersion: undefined,
pageReconciliationProtocolVersion: undefined
}
})
const composition = rig.createComposition()
await composition.start()
await expect(composition.replaceAuthority(replacementInput)).rejects.toThrow(
'browser_client_page_reconciliation_unsupported'
)
expect(rig.replacementInventory).toEqual([
expect.objectContaining({ browserPageId: 'page-a', authorityRuntimeId: 'runtime-a' })
])
expect(rig.replacementRoutes.close).not.toHaveBeenCalled()
expect(rig.order).not.toContain('activate-replacement-routes')
await composition.close()
})
it('allows a legacy replacement when there is no retained inventory', async () => {
const legacyAuthority = {
...replacementAuthority,
pageInventoryProtocolVersion: undefined,
pageReconciliationProtocolVersion: undefined
}
const rig = createRig({ pageInventory: [], replacementAuthority: legacyAuthority })
const composition = rig.createComposition()
await composition.start()
await expect(composition.replaceAuthority(replacementInput)).resolves.toEqual(legacyAuthority)
expect(rig.replacementInventory).toEqual([])
expect(rig.order).toContain('activate-replacement-routes')
await composition.close()
})
it('waits for old handlers and ignores their late callbacks before replacement', async () => {
const rig = createRig({ hostSettled: false })
const composition = rig.createComposition()
@@ -172,41 +58,6 @@ describe('PairedRuntimeBrowserClientHostComposition', () => {
expect(rig.onError).not.toHaveBeenCalled()
})
it('fails closed when retired routes reject during replacement', async () => {
const routeRetireError = new Error('route retirement failed')
const rig = createRig({ routeRetireError })
const composition = rig.createComposition()
await composition.start()
await expect(composition.replaceAuthority(replacementInput)).rejects.toThrow(
'paired_runtime_browser_client_host_composition_closed'
)
await composition.whenClosed()
expect(rig.onError).toHaveBeenCalledWith(routeRetireError)
expect(rig.executor.close).toHaveBeenCalledOnce()
expect(rig.routes.close).toHaveBeenCalledOnce()
expect(rig.order).not.toContain('activate-replacement-routes')
})
it('suspends routes without closing pages and gates commands through recovery', async () => {
const rig = createRig()
const composition = rig.createComposition()
await composition.start()
rig.hostOptions.onTransportLost?.(new Error('transport lost'))
const handling = rig.hostOptions.handler?.(command(), new AbortController().signal)
await Promise.resolve()
expect(rig.routes.suspend).toHaveBeenCalledOnce()
expect(rig.executor.handle).not.toHaveBeenCalled()
expect(rig.executor.close).not.toHaveBeenCalled()
rig.hostOptions.onReconnected?.(authority)
await expect(handling).resolves.toEqual({ status: 'completed' })
expect(rig.routes.reconnect).toHaveBeenCalledOnce()
expect(rig.executor.handle).toHaveBeenCalledOnce()
})
it('keeps one command gate across repeated loss while fencing stale route recovery', async () => {
const firstRecovery = deferred<void>()
const secondRecovery = deferred<void>()
@@ -234,171 +85,6 @@ describe('PairedRuntimeBrowserClientHostComposition', () => {
expect(rig.executor.handle).toHaveBeenCalledOnce()
})
it('settles dispatcher retirement before destroying and forgetting the page', async () => {
const rig = createRig()
const composition = rig.createComposition()
await composition.start()
await expect(composition.retirePage('page-a', 7)).resolves.toBe(true)
expect(rig.order).toEqual([
'activate-routes',
'retire-dispatcher-page',
'retire-executor-page',
'forget-dispatcher-page'
])
})
it('closes control transport before executor pages and routes', async () => {
const rig = createRig()
const composition = rig.createComposition()
await composition.start()
await expect(composition.close()).resolves.toBe(true)
expect(rig.order).toEqual([
'activate-routes',
'closing',
'suspend-routes',
'fence-navigation',
'close-host',
'close-executor',
'close-routes'
])
})
it('fences navigation and routes before terminal host cleanup can wait', async () => {
const rig = createRig()
const composition = rig.createComposition()
const error = new Error('terminal authority loss')
await composition.start()
rig.hostOptions.onError?.(error)
expect(rig.routes.suspend).toHaveBeenCalledWith(error)
expect(rig.executor.fenceNavigation).toHaveBeenCalledOnce()
expect(rig.order.slice(0, 5)).toEqual([
'activate-routes',
'closing',
'suspend-routes',
'fence-navigation',
'close-host'
])
await composition.whenClosed()
})
it('waits out the grace instead of tearing down when the authority was replaced', async () => {
vi.useFakeTimers()
try {
const rig = createRig()
const composition = rig.createComposition()
await composition.start()
rig.hostOptions.onError?.(authorityReplacedError())
expect(rig.authorityReplacementWait.armed).toBe(true)
expect(rig.onError).not.toHaveBeenCalled()
expect(rig.order).toEqual(['activate-routes'])
} finally {
vi.useRealTimers()
}
})
it('tears the composition down once the grace expires with no replacement', async () => {
vi.useFakeTimers()
try {
const rig = createRig()
const composition = rig.createComposition()
await composition.start()
const replaced = authorityReplacedError()
rig.hostOptions.onError?.(replaced)
vi.advanceTimersByTime(1_000)
expect(rig.onError).toHaveBeenCalledWith(replaced)
expect(rig.order).toContain('closing')
await vi.runAllTimersAsync()
await composition.whenClosed()
} finally {
vi.useRealTimers()
}
})
it('cancels the grace when the replacement authority actually arrives', async () => {
vi.useFakeTimers()
try {
const rig = createRig()
const composition = rig.createComposition()
await composition.start()
rig.hostOptions.onError?.(authorityReplacedError())
await composition.replaceAuthority(replacementInput)
expect(rig.authorityReplacementWait.armed).toBe(false)
vi.advanceTimersByTime(10_000)
expect(rig.onError).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})
it('cancels the grace when the composition closes for another reason', async () => {
vi.useFakeTimers()
try {
const rig = createRig()
const composition = rig.createComposition()
await composition.start()
rig.hostOptions.onError?.(authorityReplacedError())
await composition.close()
expect(rig.authorityReplacementWait.armed).toBe(false)
vi.advanceTimersByTime(10_000)
expect(rig.onError).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})
it('arms one deadline for a burst of mismatch errors', async () => {
vi.useFakeTimers()
try {
const rig = createRig()
const composition = rig.createComposition()
await composition.start()
rig.hostOptions.onError?.(authorityReplacedError())
vi.advanceTimersByTime(900)
rig.hostOptions.onError?.(authorityReplacedError())
vi.advanceTimersByTime(100)
expect(rig.onError).toHaveBeenCalledTimes(1)
await vi.runAllTimersAsync()
await composition.whenClosed()
} finally {
vi.useRealTimers()
}
})
it('still tears down immediately for a host error that is not a replacement', async () => {
vi.useFakeTimers()
try {
const rig = createRig()
const composition = rig.createComposition()
await composition.start()
const fatal = new Error('browser host process exited')
rig.hostOptions.onError?.(fatal)
expect(rig.authorityReplacementWait.armed).toBe(false)
expect(rig.onError).toHaveBeenCalledWith(fatal)
await vi.runAllTimersAsync()
await composition.whenClosed()
} finally {
vi.useRealTimers()
}
})
it('fails closed without racing page cleanup when handlers do not settle', async () => {
const rig = createRig({ hostSettled: false })
const composition = rig.createComposition()
@@ -429,45 +115,6 @@ describe('PairedRuntimeBrowserClientHostComposition', () => {
'close-executor'
])
})
it('reports a deferred executor cleanup failure while retaining its fence', async () => {
const cleanupError = new Error('executor cleanup failed')
const rig = createRig({ executorCloseError: cleanupError, hostSettled: false })
const composition = rig.createComposition()
await composition.start()
await composition.close()
rig.settleHandlers()
await expect(composition.whenClosed()).rejects.toThrow('executor cleanup failed')
expect(rig.onError).toHaveBeenCalledWith(cleanupError)
})
it('forgets a failed create that left no unresolved executor page', async () => {
const rig = createRig()
rig.executor.retirePage.mockResolvedValueOnce(false)
const composition = rig.createComposition()
await composition.start()
await expect(composition.retirePage('page-a', 7)).resolves.toBe(true)
expect(rig.executor.hasUnresolvedPage).toHaveBeenCalledWith('page-a', 7)
expect(rig.host.forgetPage).toHaveBeenCalledWith('page-a', 7)
})
it('keeps an unresolved failed create fenced', async () => {
const rig = createRig()
rig.executor.retirePage.mockResolvedValueOnce(false)
rig.executor.hasUnresolvedPage.mockReturnValueOnce(true)
const composition = rig.createComposition()
await composition.start()
await expect(composition.retirePage('page-a', 7)).rejects.toThrow(
'browser_client_page_retirement_cleanup_pending'
)
expect(rig.host.forgetPage).not.toHaveBeenCalled()
})
})
function createRig(
@@ -635,12 +282,6 @@ function createRig(
}
}
function authorityReplacedError(): Error {
return Object.assign(new Error('lease attach named a retired runtime'), {
code: BROWSER_CLIENT_HOST_AUTHORITY_MISMATCH_CODE
})
}
function retainedPageInventory(): BrowserClientHostedPageInventory {
return {
authorityRuntimeId: 'runtime-a',
@@ -11,50 +11,6 @@ const authority: BrowserClientHostLeaseAuthority = {
}
describe('PairedRuntimeBrowserClientHostRegistry', () => {
it('shares one composition for the exact environment pairing revision', async () => {
const composition = createComposition()
const compositionFactory = vi.fn(() => composition)
const registry = new PairedRuntimeBrowserClientHostRegistry({
createComposition: compositionFactory
})
const first = registry.start(input(11))
const second = registry.start(input(11))
await expect(Promise.all([first, second])).resolves.toEqual([authority, authority])
expect(compositionFactory).toHaveBeenCalledOnce()
expect(composition.start).toHaveBeenCalledOnce()
})
it('closes an old pairing revision before creating its replacement', async () => {
const order: string[] = []
const first = createComposition(order, 'start-first', 'close-first')
const second = createComposition(order, 'start-second', 'close-second')
const registry = new PairedRuntimeBrowserClientHostRegistry({
createComposition: vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second)
})
await registry.start(input(11))
await registry.start(input(12))
expect(order).toEqual(['start-first', 'close-first', 'start-second'])
})
it('preserves the composition across a runtime authority transition', async () => {
const composition = createComposition()
const compositionFactory = vi.fn(() => composition)
const registry = new PairedRuntimeBrowserClientHostRegistry({
createComposition: compositionFactory
})
await registry.start(input(11))
await registry.start(input(11, 'runtime-b'))
expect(compositionFactory).toHaveBeenCalledOnce()
expect(composition.replaceAuthority).toHaveBeenCalledWith(input(11, 'runtime-b'))
expect(composition.close).not.toHaveBeenCalled()
})
it('keeps a failed authority transition tombstoned until cleanup settles', async () => {
const cleanup = deferred<void>()
const failed = createComposition(undefined, undefined, undefined, false, cleanup.promise)
@@ -79,87 +35,6 @@ describe('PairedRuntimeBrowserClientHostRegistry', () => {
await expect(registry.start(input(11, 'runtime-b'))).resolves.toEqual(authority)
expect(replacement.start).toHaveBeenCalledOnce()
})
it('blocks replacement when the old host cannot prove handler settlement', async () => {
const cleanup = deferred<void>()
const first = createComposition(undefined, undefined, undefined, false, cleanup.promise)
const second = createComposition()
const compositionFactory = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second)
const registry = new PairedRuntimeBrowserClientHostRegistry({
createComposition: compositionFactory
})
await registry.start(input(11))
await expect(registry.start(input(12))).rejects.toThrow(
'paired_runtime_browser_client_host_cleanup_pending'
)
expect(compositionFactory).toHaveBeenCalledOnce()
expect(second.start).not.toHaveBeenCalled()
cleanup.resolve()
await cleanup.promise
await expect(registry.start(input(12))).resolves.toEqual(authority)
expect(second.start).toHaveBeenCalledOnce()
})
it('keeps replacement fenced when deferred cleanup cannot prove completion', async () => {
const cleanup = deferred<void>()
const first = createComposition(undefined, undefined, undefined, false, cleanup.promise)
const second = createComposition()
const compositionFactory = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second)
const registry = new PairedRuntimeBrowserClientHostRegistry({
createComposition: compositionFactory
})
await registry.start(input(11))
await expect(registry.start(input(12))).rejects.toThrow(
'paired_runtime_browser_client_host_cleanup_pending'
)
cleanup.reject(new Error('cleanup unresolved'))
await cleanup.promise.catch(() => undefined)
await expect(registry.start(input(12))).rejects.toThrow(
'paired_runtime_browser_client_host_cleanup_pending'
)
expect(compositionFactory).toHaveBeenCalledOnce()
expect(second.start).not.toHaveBeenCalled()
})
it('reports a page as hosted only by the live composition of its own environment', async () => {
const cleanup = deferred<void>()
const composition = createComposition(undefined, undefined, undefined, false, cleanup.promise)
composition.hostsPage.mockImplementation((browserPageId) => browserPageId === 'page-a')
composition.replaceAuthority.mockRejectedValueOnce(new Error('replacement attach failed'))
const registry = new PairedRuntimeBrowserClientHostRegistry({
createComposition: vi.fn(() => composition)
})
await registry.start(input(11))
expect(registry.hostsPage('environment-a', 'page-a')).toBe(true)
expect(registry.hostsPage('environment-a', 'page-b')).toBe(false)
expect(registry.hostsPage('environment-b', 'page-a')).toBe(false)
await expect(registry.start(input(11, 'runtime-b'))).rejects.toThrow()
expect(registry.hostsPage('environment-a', 'page-a')).toBe(false)
})
it('permanently fences new starts before closing every environment', async () => {
const first = createComposition()
const second = createComposition()
const registry = new PairedRuntimeBrowserClientHostRegistry({
createComposition: vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second)
})
await registry.start(input(11))
await registry.start({ ...input(11), environmentId: 'environment-b' })
await registry.close()
expect(first.close).toHaveBeenCalledOnce()
expect(second.close).toHaveBeenCalledOnce()
await expect(registry.start(input(11))).rejects.toThrow(
'paired_runtime_browser_client_host_registry_closed'
)
})
})
function createComposition(
@@ -1,4 +1,4 @@
import { mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'
import { mkdtempSync, readFileSync, realpathSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -61,12 +61,6 @@ const SSH_DEPLOYMENT: OrcadDeploymentLink = {
localPort: 9999,
remotePort: 7777
}
const WSL_DEPLOYMENT: OrcadDeploymentLink = {
kind: 'wsl',
distro: 'Ubuntu',
localPort: 9999,
remotePort: 7777
}
function pairedEnvironment(
id: string,
@@ -118,18 +112,6 @@ async function routeIdentity(
return identity
}
async function connectionIdentity(
environment: KnownRuntimeEnvironment,
authorityRuntimeId: string
): Promise<{ current: string; pairing: string; legacy: string }> {
const identity = await routeIdentity(environment, authorityRuntimeId)
return {
current: identity.authorityConnectionIdentity,
pairing: identity.pairingAuthorityConnectionIdentity,
legacy: identity.legacyAuthorityConnectionIdentity
}
}
function pageIdentity(
identity: ClientHostRouteIdentity,
authorityConnectionIdentity: string,
@@ -202,41 +184,6 @@ function resolvePartitionAsOlderBuild(filePath: string, identity: ClientHostRout
return derived.partition
}
/** Older parsers discard unrecognized alias fields. */
function rewriteAsOlderBuild(filePath: string): void {
const persisted: {
version: number
bindings: Record<string, { fingerprint: string; storageScope: string; lastUsedAt: number }>
} = JSON.parse(readFileSync(filePath, 'utf8'))
const bindings = Object.fromEntries(
Object.entries(persisted.bindings).map(([partition, binding]) => [
partition,
{
fingerprint: binding.fingerprint,
storageScope: binding.storageScope,
lastUsedAt: binding.lastUsedAt
}
])
)
writeFileSync(filePath, JSON.stringify({ version: persisted.version, bindings }))
}
function seedOlderBuildJar(filePath: string, identity: ClientHostRouteIdentity): string {
const derived = deriveBrowserRoutePartition(
pageIdentity(
identity,
identity.pairingAuthorityConnectionIdentity,
identity.executionHostIdentity
)
)
new BrowserRoutePartitionBindingStore({ filePath }).set(
derived.partition,
derived.bindingFingerprint,
identity.storageScope
)
return derived.partition
}
function bindingStorePath(): string {
return join(
realpathSync(mkdtempSync(join(realpathSync(tmpdir()), 'orca-re-pair-partition-'))),
@@ -248,148 +195,7 @@ beforeEach(() => {
compositions.length = 0
})
describe('client host authority connection identity', () => {
it('survives the remote restarting, and keeps the pre-migration identity distinct', async () => {
configurePairedRuntimeBrowserClientHostsForOrcaProfile({ orcaProfileId: 'profile-a' })
const environment = pairedEnvironment('environment-restart')
const before = await connectionIdentity(environment, 'runtime-a')
const after = await connectionIdentity(environment, 'runtime-restarted')
expect(after.current).toBe(before.current)
expect(after.legacy).not.toBe(before.legacy)
expect(before.legacy).not.toBe(before.current)
})
it('separates environments, pairing revisions, and server keys', async () => {
configurePairedRuntimeBrowserClientHostsForOrcaProfile({ orcaProfileId: 'profile-a' })
const identities = [
await connectionIdentity(pairedEnvironment('environment-a'), 'runtime-a'),
await connectionIdentity(pairedEnvironment('environment-b'), 'runtime-a'),
await connectionIdentity(
pairedEnvironment('environment-a', { pairingRevision: 2 }),
'runtime-a'
),
await connectionIdentity(
pairedEnvironment('environment-a', { publicKeyB64: 'key-rotated' }),
'runtime-a'
)
]
expect(new Set(identities.map((entry) => entry.current)).size).toBe(identities.length)
})
})
describe('client host identity for a server Orca re-pairs in place', () => {
it.each([
['managed SSH', SSH_DEPLOYMENT],
['WSL', WSL_DEPLOYMENT]
])('%s keeps one identity across re-pairs and still separates keys', async (_, deployment) => {
configurePairedRuntimeBrowserClientHostsForOrcaProfile({ orcaProfileId: 'profile-a' })
const id = `environment-${deployment.kind ?? 'ssh'}`
const before = await connectionIdentity(
pairedEnvironment(id, { orcadDeployment: deployment, pairedDeviceId: 'device-a' }),
'runtime-a'
)
const rePaired = await connectionIdentity(
pairedEnvironment(id, {
orcadDeployment: deployment,
pairingRevision: 5,
pairedDeviceId: 'device-b',
deviceToken: 'token-b'
}),
'runtime-b'
)
const otherKey = await connectionIdentity(
pairedEnvironment(id, { orcadDeployment: deployment, publicKeyB64: 'key-b' }),
'runtime-a'
)
const otherEnvironment = await connectionIdentity(
pairedEnvironment(`${id}-other`, { orcadDeployment: deployment }),
'runtime-a'
)
expect(rePaired.current).toBe(before.current)
expect(rePaired.pairing).not.toBe(before.pairing)
expect(otherKey.current).not.toBe(before.current)
expect(otherEnvironment.current).not.toBe(before.current)
})
it('leaves a manually paired server on its pairing identity', async () => {
configurePairedRuntimeBrowserClientHostsForOrcaProfile({ orcaProfileId: 'profile-a' })
const identity = await connectionIdentity(pairedEnvironment('environment-manual'), 'runtime-a')
expect(identity.current).toBe(identity.pairing)
})
it.each([
['managed SSH', SSH_DEPLOYMENT],
['WSL', WSL_DEPLOYMENT]
])(
'%s keeps the jar an older build filled through re-pairs and a downgrade',
async (_, deployment) => {
configurePairedRuntimeBrowserClientHostsForOrcaProfile({ orcaProfileId: 'profile-a' })
const filePath = bindingStorePath()
const id = `environment-jar-${deployment.kind ?? 'ssh'}`
const atRevisionOne = await routeIdentity(
pairedEnvironment(id, { orcadDeployment: deployment, pairedDeviceId: 'device-a' }),
'runtime-a'
)
const atRevisionTwo = await routeIdentity(
pairedEnvironment(id, {
orcadDeployment: deployment,
pairingRevision: 2,
pairedDeviceId: 'device-b',
deviceToken: 'token-b'
}),
'runtime-b'
)
const withNewKey = await routeIdentity(
pairedEnvironment(id, {
orcadDeployment: deployment,
pairingRevision: 3,
publicKeyB64: 'key-b'
}),
'runtime-c'
)
const olderJar = seedOlderBuildJar(filePath, atRevisionOne)
expect(resolvePartition(filePath, atRevisionOne)).toBe(olderJar)
expect(resolvePartitionAsOlderBuild(filePath, atRevisionOne)).toBe(olderJar)
expect(resolvePartition(filePath, atRevisionTwo)).toBe(olderJar)
expect(resolvePartitionAsOlderBuild(filePath, atRevisionTwo)).toBe(olderJar)
rewriteAsOlderBuild(filePath)
expect(resolvePartition(filePath, atRevisionTwo)).toBe(olderJar)
expect(resolvePartition(filePath, withNewKey)).not.toBe(olderJar)
}
)
it('mints a fresh jar an older build can open at every pairing', async () => {
configurePairedRuntimeBrowserClientHostsForOrcaProfile({ orcaProfileId: 'profile-a' })
const filePath = bindingStorePath()
const id = 'environment-fresh'
const atRevisionOne = await routeIdentity(
pairedEnvironment(id, { orcadDeployment: SSH_DEPLOYMENT, pairedDeviceId: 'device-a' }),
'runtime-a'
)
const atRevisionTwo = await routeIdentity(
pairedEnvironment(id, {
orcadDeployment: SSH_DEPLOYMENT,
pairingRevision: 2,
pairedDeviceId: 'device-b'
}),
'runtime-b'
)
const jar = resolvePartition(filePath, atRevisionOne)
expect(resolvePartitionAsOlderBuild(filePath, atRevisionOne)).toBe(jar)
expect(resolvePartition(filePath, atRevisionTwo)).toBe(jar)
expect(resolvePartitionAsOlderBuild(filePath, atRevisionTwo)).toBe(jar)
rewriteAsOlderBuild(filePath)
expect(resolvePartition(filePath, atRevisionOne)).toBe(jar)
expect(resolvePartitionAsOlderBuild(filePath, atRevisionOne)).toBe(jar)
})
it('adopts a per-process jar under the fingerprint an older build reads', async () => {
configurePairedRuntimeBrowserClientHostsForOrcaProfile({ orcaProfileId: 'profile-a' })
const filePath = bindingStorePath()
@@ -414,23 +220,3 @@ describe('client host identity for a server Orca re-pairs in place', () => {
expect(resolvePartitionAsOlderBuild(filePath, identity)).toBe(legacy.partition)
})
})
describe('client host route identity lifetime', () => {
it('stops answering with a route identity once the host is retired by its own error', async () => {
configurePairedRuntimeBrowserClientHostsForOrcaProfile({ orcaProfileId: 'profile-a' })
const environment = pairedEnvironment('environment-retired')
await startPairedRuntimeBrowserClientHost({
environment,
authorityRuntimeId: 'runtime-a'
})
expect(getPairedRuntimeBrowserClientRouteIdentity(environment.id)).not.toBeNull()
const failure = new Error('lease fenced')
compositions.at(-1)?.options.onError(failure)
await vi.waitFor(() => {
expect(compositions.at(-1)?.closed).toEqual([failure])
})
expect(getPairedRuntimeBrowserClientRouteIdentity(environment.id)).toBeNull()
})
})
@@ -1,399 +0,0 @@
import { pairedRuntimeConnectionFromOffer } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type {
BrowserClientHostedPageInventory,
BrowserClientHostCommandEvent
} from '../../../../shared/browser/client-hosting/browser-client-host-protocol'
import type { BrowserClientAutomationResult as BrowserClientHostCommandResult } from '../../../../shared/browser/client-hosting/browser-client-automation-protocol'
import type {
RemoteRuntimeSubscription,
RemoteRuntimeSubscriptionCallbacks
} from '../../../../shared/remote-runtime/remote-runtime-client'
import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error'
const { subscribeRemoteRuntimeRequestMock } = vi.hoisted(() => ({
subscribeRemoteRuntimeRequestMock: vi.fn()
}))
vi.mock('../../../../shared/remote-runtime/remote-runtime-client', () => ({
subscribeRemoteRuntimeRequest: subscribeRemoteRuntimeRequestMock
}))
import { PairedRuntimeBrowserClientHost } from './paired-runtime-browser-client-host'
import { PairedRuntimeBrowserHostLease } from '../leases/paired-runtime-browser-host-lease'
const pairing = pairedRuntimeConnectionFromOffer({
endpoint: 'ws://127.0.0.1:6768',
deviceToken: 'device-token',
publicKeyB64: 'public-key',
pairedDeviceId: 'device-a'
})
afterEach(() => {
subscribeRemoteRuntimeRequestMock.mockReset()
vi.restoreAllMocks()
})
describe('PairedRuntimeBrowserClientHost', () => {
it('forwards a complete inventory provider to the lease attach', async () => {
const { callbacks } = subscribeHost()
const getPageInventory = vi.fn(() => [] as readonly BrowserClientHostedPageInventory[])
const host = createHost(() => ({ status: 'completed' }), undefined, undefined, getPageInventory)
const starting = host.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
expect(getPageInventory).toHaveBeenCalledOnce()
expect(subscribeRemoteRuntimeRequestMock).toHaveBeenCalledWith(
pairing,
'browser.clientHost.attach',
expect.objectContaining({
pageInventoryProtocolVersion: 1,
pageInventory: [],
leaseReconnectProtocolVersion: 1
}),
expect.any(Number),
expect.any(Object),
expect.any(Object)
)
// Retries share a deadline; clock ticks can reduce the first attach timeout.
const attachTimeoutMs = subscribeRemoteRuntimeRequestMock.mock.calls[0]?.[3]
expect(attachTimeoutMs).toBeLessThanOrEqual(15_000)
expect(attachTimeoutMs).toBeGreaterThan(14_000)
expect(subscribeRemoteRuntimeRequestMock.mock.calls[0]?.[2]).not.toHaveProperty(
'pageReconciliationProtocolVersion'
)
callbacks.current!.onResponse(readyResponse())
await starting
await host.close()
})
it('advertises reconciliation only when the composed host enables it', async () => {
const { callbacks } = subscribeHost()
const host = createHost(
() => ({ status: 'completed' }),
undefined,
undefined,
() => [],
1
)
const starting = host.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
expect(subscribeRemoteRuntimeRequestMock.mock.calls[0]?.[2]).toMatchObject({
pageCommandProtocolVersion: 1,
pageInventoryProtocolVersion: 1,
pageReconciliationProtocolVersion: 1
})
callbacks.current!.onResponse({
...readyResponse(),
result: {
...readyResponse().result,
pageInventoryProtocolVersion: 1,
pageReconciliationProtocolVersion: 1
}
})
await expect(starting).resolves.toMatchObject({ pageReconciliationProtocolVersion: 1 })
await host.close()
})
it('constructs command authority before the first command can arrive', async () => {
const { callbacks, sendRequest } = subscribeHost()
const handler = vi.fn((_command: BrowserClientHostCommandEvent, _signal: AbortSignal) => ({
status: 'completed' as const
}))
const host = createHost(handler)
const starting = host.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse())
callbacks.current!.onResponse(commandResponse())
await expect(starting).resolves.toMatchObject({
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-a',
browserHostGeneration: 4,
pageCommandProtocolVersion: 1
})
await vi.waitFor(() => expect(handler).toHaveBeenCalledOnce())
expect(handler.mock.calls[0][0]).toMatchObject({
browserPageId: 'page-a',
pageHostGeneration: 1
})
await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledOnce())
await host.close()
})
it('closes transport first and aborts every owned page handler', async () => {
const { callbacks, close } = subscribeHost()
const order: string[] = []
close.mockImplementation(() => {
order.push('transport-close')
})
const observed: { signal: AbortSignal | null } = { signal: null }
const handler = vi.fn(
(_command: BrowserClientHostCommandEvent, signal: AbortSignal) =>
new Promise<BrowserClientHostCommandResult>((resolve) => {
observed.signal = signal
signal.addEventListener(
'abort',
() => {
order.push('handler-abort')
resolve({ status: 'failed', errorCode: 'browser_host_command_cancelled' })
},
{ once: true }
)
})
)
const host = createHost(handler)
const starting = host.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse())
await starting
callbacks.current!.onResponse(commandResponse())
await vi.waitFor(() => expect(handler).toHaveBeenCalledOnce())
await expect(host.close()).resolves.toBe(true)
expect(close).toHaveBeenCalledOnce()
expect(observed.signal?.aborted).toBe(true)
expect(order).toEqual(['transport-close', 'handler-abort'])
})
it('aborts owned handlers even when lease cleanup rejects', async () => {
const { callbacks } = subscribeHost()
let aborted = false
const host = createHost(
(_command, signal) =>
new Promise<BrowserClientHostCommandResult>((resolve) => {
signal.addEventListener(
'abort',
() => {
aborted = true
resolve({ status: 'failed', errorCode: 'browser_host_command_cancelled' })
},
{ once: true }
)
})
)
const starting = host.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse())
await starting
callbacks.current!.onResponse(commandResponse())
await vi.waitFor(() => expect(aborted).toBe(false))
vi.spyOn(PairedRuntimeBrowserHostLease.prototype, 'close').mockRejectedValueOnce(
new Error('lease cleanup failed')
)
await expect(host.close()).rejects.toThrow('lease cleanup failed')
expect(aborted).toBe(true)
})
it('preserves a falsy lease cleanup rejection across cached close calls', async () => {
const host = createHost(() => ({ status: 'completed' }))
vi.spyOn(PairedRuntimeBrowserHostLease.prototype, 'close').mockRejectedValueOnce(undefined)
await expect(host.close()).rejects.toThrow('undefined')
await expect(host.close()).rejects.toThrow('undefined')
})
it('aborts owned handlers when the lease transport fails', async () => {
const { callbacks } = subscribeHost()
const onError = vi.fn()
let aborted = false
const host = createHost(
(_command, signal) =>
new Promise<BrowserClientHostCommandResult>((resolve) => {
signal.addEventListener(
'abort',
() => {
aborted = true
resolve({ status: 'failed', errorCode: 'browser_host_command_cancelled' })
},
{ once: true }
)
}),
onError
)
const starting = host.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse())
await starting
callbacks.current!.onResponse(commandResponse())
await vi.waitFor(() => expect(aborted).toBe(false))
callbacks.current!.onError(
new RemoteRuntimeClientError('remote_runtime_unavailable', 'transport failed')
)
await vi.waitFor(() => expect(aborted).toBe(true))
expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'transport failed' }))
})
it('retires and forgets only the exact page generation', async () => {
const { callbacks } = subscribeHost()
const handler = vi.fn(
(_command: BrowserClientHostCommandEvent, signal: AbortSignal) =>
new Promise<BrowserClientHostCommandResult>((resolve) => {
signal.addEventListener(
'abort',
() => resolve({ status: 'failed', errorCode: 'browser_host_command_cancelled' }),
{ once: true }
)
})
)
const host = createHost(handler)
const starting = host.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse())
await starting
callbacks.current!.onResponse(commandResponse())
await vi.waitFor(() => expect(handler).toHaveBeenCalledOnce())
await expect(host.retirePage('page-a', 2)).rejects.toThrow('browser_host_page_generation_stale')
await expect(host.retirePage('page-a', 1)).resolves.toBe(true)
expect(host.forgetPage('page-a', 2)).toBe(false)
expect(host.forgetPage('page-a', 1)).toBe(true)
await host.close()
})
it('keeps timed-out retirement fenced until the exact late handler settles', async () => {
const { callbacks } = subscribeHost()
const stuck = deferredCommandResult()
const host = createHost(() => stuck.promise, undefined, { joinTimeoutMs: 10 })
const starting = host.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse())
await starting
callbacks.current!.onResponse(commandResponse())
await expect(host.retirePage('page-a', 1)).resolves.toBe(false)
expect(host.forgetPage('page-a', 1)).toBe(false)
stuck.resolve({ status: 'completed' })
await expect(host.retirePage('page-a', 1)).resolves.toBe(true)
expect(host.forgetPage('page-a', 1)).toBe(true)
await host.close()
})
it('exposes exact late handler settlement after bounded close', async () => {
const { callbacks } = subscribeHost()
const stuck = deferredCommandResult()
const host = createHost(() => stuck.promise, undefined, { joinTimeoutMs: 10 })
const starting = host.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse())
await starting
callbacks.current!.onResponse(commandResponse())
await expect(host.close()).resolves.toBe(false)
let handlersSettled = false
void host.whenHandlersSettled().then(() => {
handlersSettled = true
})
await Promise.resolve()
expect(handlersSettled).toBe(false)
stuck.resolve({ status: 'completed' })
await expect(host.whenHandlersSettled()).resolves.toBeUndefined()
})
})
function subscribeHost(): {
callbacks: { current?: RemoteRuntimeSubscriptionCallbacks }
close: ReturnType<typeof vi.fn>
sendRequest: ReturnType<typeof vi.fn>
} {
const callbacks: { current?: RemoteRuntimeSubscriptionCallbacks } = {}
const close = vi.fn()
const sendRequest = vi.fn().mockResolvedValue({
id: 'command-result',
ok: true,
result: { accepted: true },
_meta: { runtimeId: 'runtime-a' }
})
subscribeRemoteRuntimeRequestMock.mockImplementationOnce(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
callbacks.current = args[4] as RemoteRuntimeSubscriptionCallbacks
return {
requestId: 'browser-host',
close,
sendBinary: () => false,
sendRequest
}
}
)
return { callbacks, close, sendRequest }
}
function createHost(
handler: (
command: BrowserClientHostCommandEvent,
signal: AbortSignal
) => BrowserClientHostCommandResult | Promise<BrowserClientHostCommandResult>,
onError?: (error: Error) => void,
dispatcher?: { joinTimeoutMs?: number },
getPageInventory?: () => readonly BrowserClientHostedPageInventory[],
pageReconciliationProtocolVersion?: 1
): PairedRuntimeBrowserClientHost {
return new PairedRuntimeBrowserClientHost({
connection: pairing,
authorityRuntimeId: 'runtime-a',
browserHostClientId: 'host-a',
hostCapabilities: ['webview'],
handler,
getPageInventory,
...(pageReconciliationProtocolVersion ? { pageReconciliationProtocolVersion } : {}),
onError,
dispatcher
})
}
function deferredCommandResult(): {
promise: Promise<BrowserClientHostCommandResult>
resolve: (result: BrowserClientHostCommandResult) => void
} {
let resolve = (_result: BrowserClientHostCommandResult): void => {}
const promise = new Promise<BrowserClientHostCommandResult>((innerResolve) => {
resolve = innerResolve
})
return { promise, resolve }
}
function readyResponse() {
return {
id: 'browser-host',
ok: true as const,
result: {
type: 'ready' as const,
authorityEpoch: 'epoch-a',
browserHostGeneration: 4,
pageCommandProtocolVersion: 1 as const
},
_meta: { runtimeId: 'runtime-a' }
}
}
function commandResponse() {
return {
id: 'browser-host',
ok: true as const,
result: {
type: 'command' as const,
pageCommandProtocolVersion: 1 as const,
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-a',
browserHostClientId: 'host-a',
browserHostGeneration: 4,
browserPageId: 'page-a',
pageHostGeneration: 1,
commandSequence: 1,
commandId: 'command-a',
command: {
type: 'createPage' as const,
browserProfileId: 'default',
executionHostKey: 'native:runtime-a:1'
}
},
_meta: { runtimeId: 'runtime-a' }
}
}
@@ -1,216 +0,0 @@
import { pairedRuntimeConnectionFromOffer } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { PairingOffer } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer'
import type {
RemoteRuntimeSubscription,
RemoteRuntimeSubscriptionCallbacks
} from '../../../../shared/remote-runtime/remote-runtime-client'
import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error'
const { subscribeRemoteRuntimeRequestMock } = vi.hoisted(() => ({
subscribeRemoteRuntimeRequestMock: vi.fn()
}))
vi.mock('../../../../shared/remote-runtime/remote-runtime-client', () => ({
subscribeRemoteRuntimeRequest: subscribeRemoteRuntimeRequestMock
}))
import { PairedRuntimeBrowserHostLease } from '../leases/paired-runtime-browser-host-lease'
import type { PairedRuntimeBrowserHostLeaseOptions } from '../leases/paired-runtime-browser-host-lease-options'
const pairing = {
v: 2,
endpoint: 'ws://127.0.0.1:6768',
deviceToken: 'device-token',
publicKeyB64: 'public-key',
pairedDeviceId: 'device-a',
scope: 'runtime'
} as PairingOffer
afterEach(() => {
subscribeRemoteRuntimeRequestMock.mockReset()
})
describe('paired runtime browser-host reconciliation negotiation', () => {
it('falls back without enabling reconciliation when an older host omits the echo', async () => {
const callbacks: { current?: RemoteRuntimeSubscriptionCallbacks } = {}
subscribeRemoteRuntimeRequestMock.mockImplementationOnce(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
callbacks.current = args[4] as RemoteRuntimeSubscriptionCallbacks
return {
requestId: 'browser-host',
close: vi.fn(),
sendBinary: () => false,
sendRequest: vi.fn()
}
}
)
const lease = createLease()
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse())
await expect(starting).resolves.not.toHaveProperty('pageReconciliationProtocolVersion')
await lease.close()
})
it('rejects an unsolicited or dependency-inconsistent reconciliation echo', async () => {
const callbacks: { current?: RemoteRuntimeSubscriptionCallbacks } = {}
subscribeRemoteRuntimeRequestMock.mockImplementation(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
callbacks.current = args[4] as RemoteRuntimeSubscriptionCallbacks
return {
requestId: 'browser-host',
close: vi.fn(),
sendBinary: () => false,
sendRequest: vi.fn()
}
}
)
const unsolicited = createLease({ pageReconciliationProtocolVersion: undefined })
const unsolicitedStart = unsolicited.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse({ pageReconciliationProtocolVersion: 1 }))
await expect(unsolicitedStart).rejects.toThrow('Invalid browser host lease response')
subscribeRemoteRuntimeRequestMock.mockReset()
callbacks.current = undefined
subscribeRemoteRuntimeRequestMock.mockImplementation(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
callbacks.current = args[4] as RemoteRuntimeSubscriptionCallbacks
return {
requestId: 'browser-host',
close: vi.fn(),
sendBinary: () => false,
sendRequest: vi.fn()
}
}
)
const inconsistent = createLease()
const inconsistentStart = inconsistent.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse({
...readyResponse({ pageReconciliationProtocolVersion: 1 }),
result: {
...readyResponse({ pageReconciliationProtocolVersion: 1 }).result,
pageInventoryProtocolVersion: undefined
}
})
await expect(inconsistentStart).rejects.toThrow('Invalid browser host lease response')
})
it('rejects reconciliation downgrade during exact reconnect', async () => {
const callbacks: RemoteRuntimeSubscriptionCallbacks[] = []
const onError = vi.fn()
subscribeRemoteRuntimeRequestMock.mockImplementation(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
callbacks.push(args[4] as RemoteRuntimeSubscriptionCallbacks)
return {
requestId: `browser-host-${callbacks.length}`,
close: vi.fn(),
sendBinary: () => false,
sendRequest: vi.fn()
}
}
)
const lease = createLease({ reconnectRetryDelayMs: 1, onError })
const starting = lease.start()
await vi.waitFor(() => expect(callbacks).toHaveLength(1))
callbacks[0]!.onResponse(readyResponse({ pageReconciliationProtocolVersion: 1 }))
await starting
callbacks[0]!.onError(
new RemoteRuntimeClientError('remote_runtime_unavailable', 'transport closed')
)
await vi.waitFor(() => expect(callbacks).toHaveLength(2))
callbacks[1]!.onResponse(readyResponse())
await vi.waitFor(() => expect(onError).toHaveBeenCalledOnce())
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({ message: 'Browser host lease authority changed in place' })
)
await lease.close()
})
it('refuses a page command that drops the negotiated reconciliation protocol', async () => {
const callbacks: { current?: RemoteRuntimeSubscriptionCallbacks } = {}
const close = vi.fn()
subscribeRemoteRuntimeRequestMock.mockImplementationOnce(
async (...args: unknown[]): Promise<RemoteRuntimeSubscription> => {
callbacks.current = args[4] as RemoteRuntimeSubscriptionCallbacks
return { requestId: 'browser-host', close, sendBinary: () => false, sendRequest: vi.fn() }
}
)
const onError = vi.fn()
const onPageCommand = vi.fn()
const lease = createLease({ onError, onPageCommand })
const starting = lease.start()
await vi.waitFor(() => expect(callbacks.current).toBeDefined())
callbacks.current!.onResponse(readyResponse({ pageReconciliationProtocolVersion: 1 }))
await starting
callbacks.current!.onResponse({
id: 'browser-host',
ok: true,
result: {
type: 'command',
pageCommandProtocolVersion: 1,
authorityRuntimeId: 'runtime-a',
authorityEpoch: 'epoch-a',
browserHostClientId: 'host-a',
browserHostGeneration: 4,
browserPageId: 'page-a',
pageHostGeneration: 1,
commandSequence: 1,
commandId: 'command-a',
command: {
type: 'createPage',
browserProfileId: 'default',
executionHostKey: 'native:runtime-a:1'
}
},
_meta: { runtimeId: 'runtime-a' }
})
await vi.waitFor(() => expect(close).toHaveBeenCalledOnce())
expect(onPageCommand).not.toHaveBeenCalled()
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({ message: 'Unnegotiated browser host page command' })
)
})
})
function createLease(
overrides: Partial<PairedRuntimeBrowserHostLeaseOptions> = {}
): PairedRuntimeBrowserHostLease {
return new PairedRuntimeBrowserHostLease({
connection: pairedRuntimeConnectionFromOffer(pairing),
authorityRuntimeId: 'runtime-a',
browserHostClientId: 'host-a',
hostCapabilities: ['webview'],
pageCommandProtocolVersion: 1,
pageInventoryProtocolVersion: 1,
pageReconciliationProtocolVersion: 1,
leaseReconnectProtocolVersion: 1,
getPageInventory: () => [],
onPageCommand: async () => ({ status: 'completed' }),
...overrides
})
}
function readyResponse(overrides: { pageReconciliationProtocolVersion?: 1 } = {}) {
return {
id: 'browser-host',
ok: true as const,
result: {
type: 'ready' as const,
authorityEpoch: 'epoch-a',
browserHostGeneration: 4,
pageCommandProtocolVersion: 1 as const,
pageInventoryProtocolVersion: 1 as const,
leaseReconnectProtocolVersion: 1 as const,
...overrides
},
_meta: { runtimeId: 'runtime-a' }
}
}
@@ -4,125 +4,6 @@ import { createCommand, createHarness } from './browser-client-page-command-exec
describe('BrowserClientPageCommandExecutor authority fencing', () => {
beforeEach(() => vi.restoreAllMocks())
it('does not retain a page when close races its in-flight creation', async () => {
const { dependencies, executor, order, route } = createHarness()
let resolveRoute = (_route: typeof route): void => {}
dependencies.retainNetworkRoute.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveRoute = resolve
})
)
const creating = executor.handle(createCommand('createPage'), new AbortController().signal)
await Promise.resolve()
await expect(executor.close()).rejects.toThrow('Browser client page executor cleanup failed')
resolveRoute(route)
await expect(creating).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_executor_closed'
})
expect(executor.hasPage('page-a', 7)).toBe(false)
expect(order).toEqual(['release-route'])
})
it('retires every retained page before fencing later commands', async () => {
const { executor, order } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
await executor.close()
expect(order.slice(-6)).toEqual([
'revoke-navigation',
'release-guest',
'retire-guest',
'retire-renderer-page',
'release-session',
'release-route'
])
await expect(
executor.handle(createCommand('navigate'), new AbortController().signal)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_executor_closed'
})
})
it('revokes retained navigation once without inferring guest destruction', async () => {
const { dependencies, executor, order, route } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
executor.fenceNavigation()
executor.fenceNavigation()
expect(dependencies.routeWebContents.revokeNavigation).toHaveBeenCalledOnce()
expect(order.at(-1)).toBe('revoke-navigation')
expect(route.release).not.toHaveBeenCalled()
await expect(
executor.handle(createCommand('navigate'), new AbortController().signal)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_executor_closed'
})
await executor.close()
})
it('retains inventory while fencing old pages and uses the replacement route identity', async () => {
const { dependencies, executor } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
executor.beginAuthorityTransition()
expect(executor.snapshotPageInventory()).toEqual([
expect.objectContaining({ browserPageId: 'page-a', authorityRuntimeId: 'runtime-a' })
])
expect(dependencies.routeWebContents.revokeNavigation).toHaveBeenCalledOnce()
await expect(
executor.handle(createCommand('navigate'), new AbortController().signal)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_executor_closed'
})
executor.completeAuthorityTransition({
authorityConnectionIdentity: 'authority-record-b',
pairingAuthorityConnectionIdentity: 'pairing-authority-record-b',
legacyAuthorityConnectionIdentity: 'legacy-authority-record-b'
})
await expect(
executor.handle(
createCommand('navigate', {
authorityRuntimeId: 'runtime-b',
authorityEpoch: 'epoch-b',
browserHostGeneration: 1
}),
new AbortController().signal
)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_generation_stale'
})
expect(dependencies.routeWebContents.navigateGuest).not.toHaveBeenCalled()
await executor.retirePage('page-a', 7)
await executor.handle(
createCommand('createPage', {
authorityRuntimeId: 'runtime-b',
authorityEpoch: 'epoch-b',
browserPageId: 'page-b',
pageHostGeneration: 1
}),
new AbortController().signal
)
expect(dependencies.routeSessions.preparePage).toHaveBeenLastCalledWith(
expect.objectContaining({
identity: expect.objectContaining({ authorityConnectionIdentity: 'authority-record-b' })
})
)
})
it('releases an in-flight old-authority create during transition', async () => {
const { dependencies, executor, order, route } = createHarness()
let resolveRoute = (_route: typeof route): void => {}
@@ -152,62 +33,4 @@ describe('BrowserClientPageCommandExecutor authority fencing', () => {
})
await executor.close()
})
it('keeps transition fail-closed when navigation revocation throws', async () => {
const { dependencies, executor, order } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
dependencies.routeWebContents.revokeNavigation.mockImplementationOnce(() => {
order.push('revoke-navigation')
throw new Error('transition revocation failed')
})
expect(() => executor.beginAuthorityTransition()).toThrow(
'Browser client page navigation fencing failed'
)
await expect(
executor.handle(createCommand('navigate'), new AbortController().signal)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_executor_closed'
})
await executor.close()
expect(order.slice(-6)).toEqual([
'revoke-navigation',
'release-guest',
'retire-guest',
'retire-renderer-page',
'release-session',
'release-route'
])
})
it('continues exact page cleanup when navigation revocation throws', async () => {
const { dependencies, executor, order } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
dependencies.routeWebContents.revokeNavigation.mockImplementationOnce(() => {
order.push('revoke-navigation')
throw new Error('navigation revocation failed')
})
await expect(executor.close()).rejects.toMatchObject({
message: 'Browser client page navigation fencing failed',
errors: [expect.objectContaining({ message: 'navigation revocation failed' })]
})
expect(order.slice(-6)).toEqual([
'revoke-navigation',
'release-guest',
'retire-guest',
'retire-renderer-page',
'release-session',
'release-route'
])
await expect(
executor.handle(createCommand('navigate'), new AbortController().signal)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_executor_closed'
})
})
})
@@ -2,284 +2,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
createCommand,
createHarness,
createLifecycleClaim,
partition
createLifecycleClaim
} from './browser-client-page-command-executor-test-harness'
describe('BrowserClientPageCommandExecutor', () => {
beforeEach(() => vi.restoreAllMocks())
it('keeps legacy-valid command identities when inventory cannot encode them', async () => {
const { executor } = createHarness()
const browserProfileId = '\0'.repeat(256)
await expect(
executor.handle(
createCommand('createPage', {
command: { type: 'createPage', browserProfileId, executionHostKey: 'execution-host-a' }
}),
new AbortController().signal
)
).resolves.toEqual({ status: 'completed' })
expect(executor.snapshotPageInventory()).toEqual([
expect.objectContaining({ browserProfileId, state: 'active' })
])
})
it('omits a normalized URL that expands beyond the inventory field bound', async () => {
const { dependencies, executor } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
const requestedUrl = `https://example.internal/${'é'.repeat(4_000)}`
await expect(
executor.handle(
createCommand('navigate', { command: { type: 'navigate', url: requestedUrl } }),
new AbortController().signal
)
).resolves.toEqual({ status: 'completed' })
expect(dependencies.routeWebContents.navigateGuest).toHaveBeenCalledWith(
expect.any(Object),
expect.stringMatching(/^https:\/\/example\.internal\/%C3%A9%C3%A9/)
)
expect(executor.snapshotPageInventory()[0]).not.toHaveProperty('currentUrl')
})
it('snapshots in-flight and unresolved pages as outcome unknown', async () => {
const { dependencies, executor, route } = createHarness()
let resolveRoute = (_route: typeof route): void => {}
dependencies.retainNetworkRoute.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveRoute = resolve
})
)
const creating = executor.handle(createCommand('createPage'), new AbortController().signal)
await Promise.resolve()
const inFlight = executor.snapshotPageInventory()
expect(inFlight).toEqual([
expect.objectContaining({ browserPageId: 'page-a', state: 'outcomeUnknown' })
])
expect(Object.isFrozen(inFlight)).toBe(true)
expect(Object.isFrozen(inFlight[0])).toBe(true)
resolveRoute(route)
await expect(creating).resolves.toEqual({ status: 'completed' })
expect(executor.snapshotPageInventory()).toEqual([
expect.objectContaining({ browserPageId: 'page-a', state: 'active' })
])
})
it('never duplicates a page during its create-to-active transition', async () => {
const { dependencies, executor, order } = createHarness()
let transitionSnapshot: ReturnType<typeof executor.snapshotPageInventory> = []
dependencies.routeWebContents.grantNavigation.mockImplementationOnce(() => {
order.push('grant-navigation')
queueMicrotask(() => {
transitionSnapshot = executor.snapshotPageInventory()
})
return true
})
await executor.handle(createCommand('createPage'), new AbortController().signal)
expect(transitionSnapshot).toEqual([
expect.objectContaining({ browserPageId: 'page-a', state: 'active' })
])
})
it('never reports a page as active after its renderer authority is replaced', async () => {
const { executor, setRendererCurrent } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
setRendererCurrent(false)
expect(executor.snapshotPageInventory()).toEqual([
expect.objectContaining({ browserPageId: 'page-a', state: 'outcomeUnknown' })
])
})
it('rejects stale generations and local-file navigation without touching Chromium', async () => {
const { dependencies, executor } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
const stale = createCommand('navigate', { pageHostGeneration: 8 })
await expect(executor.handle(stale, new AbortController().signal)).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_generation_stale'
})
const localFile = createCommand('navigate', {
command: { type: 'navigate', url: 'file:///etc/passwd' }
})
await expect(executor.handle(localFile, new AbortController().signal)).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_navigation_invalid'
})
expect(dependencies.routeWebContents.navigateGuest).not.toHaveBeenCalled()
})
it('releases every exact resource when guest registration fails', async () => {
const { dependencies, executor, order } = createHarness()
dependencies.routeWebContents.registerGuest.mockImplementationOnce(() => {
order.push('register-guest')
return false
})
await expect(
executor.handle(createCommand('createPage'), new AbortController().signal)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_guest_registration_failed'
})
expect(order).toEqual([
'retain-route',
'prepare-page',
'mount-page',
'claim-guest',
'register-guest',
'retire-guest',
'retire-renderer-page',
'release-session',
'release-route'
])
expect(executor.hasPage('page-a', 7)).toBe(false)
})
it('holds network resources when guest retirement cannot be confirmed', async () => {
const { dependencies, executor, order, route, routeSession } = createHarness()
dependencies.routeWebContents.registerGuest.mockImplementationOnce(() => {
order.push('register-guest')
return false
})
dependencies.routeWebContents.claimGuestLifecycle.mockImplementationOnce((registration) => {
order.push('claim-guest')
return createLifecycleClaim(
registration,
Promise.reject(new Error('guest destruction unavailable'))
)
})
dependencies.routeWebContents.beginGuestRetirement.mockImplementationOnce(() => {
order.push('retire-guest')
throw new Error('guest cleanup failed')
})
await expect(
executor.handle(createCommand('createPage'), new AbortController().signal)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_cleanup_failed'
})
expect(order.slice(-2)).toEqual(['retire-guest', 'retire-renderer-page'])
expect(routeSession.release).not.toHaveBeenCalled()
expect(route.release).not.toHaveBeenCalled()
expect(executor.hasUnresolvedPage('page-a', 7)).toBe(true)
await expect(
executor.handle(
createCommand('createPage', { pageHostGeneration: 8 }),
new AbortController().signal
)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_generation_conflict'
})
})
it('holds network resources when a failed mount may have created a guest', async () => {
const { executor, order, renderer, route, routeSession } = createHarness()
renderer.mountPage.mockImplementationOnce(async () => {
order.push('mount-page')
throw new Error('mount outcome unknown')
})
await expect(
executor.handle(createCommand('createPage'), new AbortController().signal)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_cleanup_failed'
})
expect(order.slice(-2)).toEqual(['mount-page', 'retire-renderer-page'])
expect(routeSession.release).not.toHaveBeenCalled()
expect(route.release).not.toHaveBeenCalled()
expect(executor.snapshotPageInventory()).toEqual([
expect.objectContaining({ browserPageId: 'page-a', state: 'outcomeUnknown' })
])
await expect(
executor.handle(
createCommand('createPage', { pageHostGeneration: 8 }),
new AbortController().signal
)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_generation_conflict'
})
})
it('fails closed if the selected renderer is replaced during creation', async () => {
const { dependencies, executor, renderer, setRendererCurrent } = createHarness()
renderer.mountPage.mockImplementationOnce(async () => {
setRendererCurrent(false)
return { webContentsId: 41 }
})
await expect(
executor.handle(createCommand('createPage'), new AbortController().signal)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_renderer_stale'
})
expect(dependencies.routeWebContents.registerGuest).not.toHaveBeenCalled()
expect(dependencies.routeWebContents.beginGuestRetirement).toHaveBeenCalledOnce()
expect(renderer.retirePage).toHaveBeenCalledOnce()
expect(executor.hasUnresolvedPage('page-a', 7)).toBe(false)
})
it('cleans up an exact mounted guest when creation is aborted', async () => {
const { dependencies, executor, renderer } = createHarness()
const controller = new AbortController()
renderer.mountPage.mockImplementationOnce(async () => {
controller.abort()
return { webContentsId: 41 }
})
await expect(executor.handle(createCommand('createPage'), controller.signal)).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_command_aborted'
})
expect(dependencies.routeWebContents.registerGuest).not.toHaveBeenCalled()
expect(dependencies.routeWebContents.beginGuestRetirement).toHaveBeenCalledOnce()
expect(renderer.retirePage).toHaveBeenCalledOnce()
})
it('retires only the exact generation before admitting its replacement', async () => {
const { dependencies, executor, order } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
await expect(executor.retirePage('page-a', 8)).resolves.toBe(false)
expect(executor.hasPage('page-a', 7)).toBe(true)
expect(dependencies.guestBinding.release).not.toHaveBeenCalled()
await expect(executor.retirePage('page-a', 7)).resolves.toBe(true)
expect(dependencies.guestBinding.release).toHaveBeenCalledWith({
partition,
browserPageId: 'page-a',
pageHostGeneration: 7,
rendererWebContentsId: 11,
webContentsId: 41
})
expect(order.slice(-5)).toEqual([
'release-guest',
'retire-guest',
'retire-renderer-page',
'release-session',
'release-route'
])
const replacement = createCommand('createPage', { pageHostGeneration: 8 })
await expect(executor.handle(replacement, new AbortController().signal)).resolves.toEqual({
status: 'completed'
})
})
it('holds Session and route release for the exact destroyed acknowledgement', async () => {
const { dependencies, executor, order } = createHarness()
let acknowledgeDestroyed = (): void => {}
@@ -312,166 +40,4 @@ describe('BrowserClientPageCommandExecutor', () => {
'release-route'
])
})
it('moves a failed retirement into immutable outcome-unknown inventory', async () => {
const { executor, order, renderer } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
renderer.retirePage.mockImplementationOnce(async () => {
order.push('retire-renderer-page')
throw new Error('renderer cleanup failed')
})
await expect(executor.retirePage('page-a', 7)).rejects.toThrow(
'Browser client page cleanup failed'
)
expect(order.slice(-4)).toEqual([
'retire-guest',
'retire-renderer-page',
'release-session',
'release-route'
])
expect(executor.hasPage('page-a', 7)).toBe(false)
expect(executor.hasUnresolvedPage('page-a', 7)).toBe(true)
const inventory = executor.snapshotPageInventory()
expect(inventory).toEqual([
expect.objectContaining({ browserPageId: 'page-a', state: 'outcomeUnknown' })
])
expect(Object.isFrozen(inventory[0])).toBe(true)
expect(executor.hasUnresolvedPage('page-a', 8)).toBe(false)
await expect(executor.retirePage('page-a', 7)).resolves.toBe(false)
await expect(
executor.handle(
createCommand('createPage', { pageHostGeneration: 8 }),
new AbortController().signal
)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_generation_conflict'
})
await expect(executor.close()).rejects.toMatchObject({
message: 'Browser client page executor cleanup failed',
errors: [expect.objectContaining({ message: 'browser_client_page_cleanup_unresolved' })]
})
})
it('reports every page whose cleanup fails during close', async () => {
const { executor, order, renderer } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
renderer.retirePage.mockImplementationOnce(async () => {
order.push('retire-renderer-page')
throw new Error('renderer cleanup failed')
})
await expect(executor.close()).rejects.toMatchObject({
message: 'Browser client page executor cleanup failed',
errors: [expect.objectContaining({ message: 'Browser client page cleanup failed' })]
})
})
it('joins an in-flight retirement instead of running cleanup twice', async () => {
const { executor, order } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
const [first, second] = await Promise.all([
executor.retirePage('page-a', 7),
executor.retirePage('page-a', 7)
])
expect([first, second]).toEqual([true, true])
expect(order.filter((step) => step === 'release-route')).toHaveLength(1)
expect(order.filter((step) => step === 'release-session')).toHaveLength(1)
})
it('refuses an authority transition on a closed executor', async () => {
const { executor } = createHarness()
await executor.handle(createCommand('createPage'), new AbortController().signal)
await executor.close()
expect(() => executor.beginAuthorityTransition()).toThrow(
'browser_client_page_authority_transition_unavailable'
)
})
it('refuses to complete an authority transition that never began', () => {
const { executor } = createHarness()
expect(() =>
executor.completeAuthorityTransition({
authorityConnectionIdentity: 'authority-record-b',
pairingAuthorityConnectionIdentity: 'pairing-authority-record-b',
legacyAuthorityConnectionIdentity: 'legacy-authority-record-b'
})
).toThrow('browser_client_page_authority_transition_unavailable')
})
it('waits for guest destruction when renderer retirement fails', async () => {
const { dependencies, executor, order, renderer } = createHarness()
let acknowledgeDestroyed = (): void => {}
const destroyed = new Promise<void>((resolve) => {
acknowledgeDestroyed = resolve
})
dependencies.routeWebContents.claimGuestLifecycle.mockImplementationOnce((registration) => {
order.push('claim-guest')
return createLifecycleClaim(registration, destroyed)
})
dependencies.routeWebContents.beginGuestRetirement.mockImplementationOnce(() => {
order.push('retire-guest')
return destroyed
})
renderer.retirePage.mockImplementationOnce(async () => {
order.push('retire-renderer-page')
throw new Error('renderer cleanup failed')
})
await executor.handle(createCommand('createPage'), new AbortController().signal)
const retiring = executor.retirePage('page-a', 7)
await Promise.resolve()
await Promise.resolve()
expect(order.slice(-2)).toEqual(['retire-guest', 'retire-renderer-page'])
acknowledgeDestroyed()
await expect(retiring).rejects.toThrow('Browser client page cleanup failed')
expect(order.slice(-4)).toEqual([
'retire-guest',
'retire-renderer-page',
'release-session',
'release-route'
])
})
it('rejects a route resolved for a different execution host and releases it', async () => {
const { dependencies, executor, route } = createHarness()
route.key = 'execution-host-b'
await expect(
executor.handle(createCommand('createPage'), new AbortController().signal)
).resolves.toEqual({
status: 'failed',
errorCode: 'browser_client_page_execution_host_stale'
})
expect(dependencies.routeSessions.preparePage).not.toHaveBeenCalled()
expect(route.release).toHaveBeenCalledOnce()
})
it('bounds retained and concurrently creating page generations', async () => {
const { dependencies, executor, route } = createHarness({ maxPages: 1 })
let resolveRoute = (_route: typeof route): void => {}
dependencies.retainNetworkRoute.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveRoute = resolve
})
)
const first = executor.handle(createCommand('createPage'), new AbortController().signal)
await Promise.resolve()
await expect(
executor.handle(
createCommand('createPage', { browserPageId: 'page-b', commandId: 'create-b' }),
new AbortController().signal
)
).resolves.toEqual({ status: 'failed', errorCode: 'browser_client_page_capacity' })
resolveRoute(route)
await expect(first).resolves.toEqual({ status: 'completed' })
})
})
@@ -49,84 +49,6 @@ async function fixture(
}
describe('staged client page profile switching', () => {
it('prepares a separate partition and guest before retiring the authenticated old guest', async () => {
const h = await fixture()
let retired = false
h.dependencies.routeWebContents.beginGuestRetirement.mockImplementation(() => {
retired = true
expect(h.bindReplacement).toHaveBeenCalledWith(
expect.objectContaining({
registration: expect.objectContaining({
webContentsId: 42,
pageHostGeneration: 8
})
})
)
return Promise.resolve()
})
h.bindReplacement.mockImplementation(() => expect(retired).toBe(false))
expect(await h.executor.handle(switchCommand(), new AbortController().signal)).toEqual({
status: 'completed'
})
expect(h.executor.hasPage('page-a', 8)).toBe(true)
expect(h.executor.hasPage('page-a', 7)).toBe(false)
expect(h.executor.snapshotPageInventory()).toMatchObject([
{ browserProfileId: 'remote-isolated', pageHostGeneration: 8 }
])
expect(h.dependencies.routeSessions.preparePage).toHaveBeenLastCalledWith(
expect.objectContaining({
identity: expect.objectContaining({
browserProfileId: 'remote-isolated',
authorityConnectionIdentity: 'authority-record-a'
}),
profileMetadata: {
id: 'remote-isolated',
label: 'Remote profile',
scope: 'isolated'
}
})
)
})
it('preserves the old guest when target preparation fails', async () => {
const h = await fixture()
h.dependencies.routeSessions.preparePage.mockRejectedValueOnce(
new Error('target profile rejected')
)
expect(await h.executor.handle(switchCommand(), new AbortController().signal)).toMatchObject({
status: 'failed'
})
expect(h.executor.hasPage('page-a', 7)).toBe(true)
expect(h.dependencies.routeWebContents.beginGuestRetirement).not.toHaveBeenCalled()
expect(h.bindReplacement).not.toHaveBeenCalled()
expect(h.executor.snapshotPageInventory()).toMatchObject([
{ browserProfileId: 'profile-a', state: 'active' }
])
})
it('retires only the staged guest and restores the old binding when binding fails', async () => {
const h = await fixture()
h.bindReplacement.mockImplementation(() => {
throw new Error('bind failed')
})
expect(await h.executor.handle(switchCommand(), new AbortController().signal)).toMatchObject({
status: 'failed'
})
expect(h.executor.hasPage('page-a', 7)).toBe(true)
expect(h.dependencies.routeWebContents.beginGuestRetirement).toHaveBeenCalledTimes(1)
expect(h.dependencies.routeWebContents.beginGuestRetirement).toHaveBeenCalledWith(
expect.objectContaining({
registration: expect.objectContaining({ webContentsId: 42 })
})
)
expect(h.dependencies.guestBinding.bind).toHaveBeenLastCalledWith(
expect.objectContaining({
registration: expect.objectContaining({ webContentsId: 41 }),
browserProfileId: 'profile-a'
})
)
})
it('restores the old guest when replacement navigation fails', async () => {
const h = await fixture()
await h.executor.handle(
@@ -161,22 +83,6 @@ describe('staged client page profile switching', () => {
)
})
it('rejects a target partition collision without retiring the old guest', async () => {
const h = await fixture()
h.dependencies.routeSessions.preparePage.mockResolvedValueOnce(h.routeSession)
expect(await h.executor.handle(switchCommand(), new AbortController().signal)).toMatchObject({
status: 'failed',
errorCode: 'browser_client_page_profile_partition_conflict'
})
expect(h.executor.hasPage('page-a', 7)).toBe(true)
expect(h.bindReplacement).not.toHaveBeenCalled()
expect(h.dependencies.routeWebContents.beginGuestRetirement).toHaveBeenCalledWith(
expect.objectContaining({
registration: expect.objectContaining({ webContentsId: 42 })
})
)
})
it('keeps the new availability watcher after retiring the old generation', async () => {
const availability = new BrowserRoutePageAvailability()
const h = await fixture(availability)
@@ -192,147 +98,4 @@ describe('staged client page profile switching', () => {
{ state: 'outcomeUnknown', pageHostGeneration: 8 }
])
})
it('retains unresolved staged cleanup evidence without replacing the old page', async () => {
const h = await fixture()
h.bindReplacement.mockImplementation(() => {
throw new Error('bind failed')
})
h.dependencies.routeWebContents.beginGuestRetirement.mockImplementationOnce(() => {
throw new Error('cleanup refused')
})
expect(await h.executor.handle(switchCommand(), new AbortController().signal)).toMatchObject({
status: 'failed'
})
expect(h.executor.hasPage('page-a', 7)).toBe(true)
await expect(h.executor.close()).rejects.toThrow('Browser client page executor cleanup failed')
})
it('fences the staged guest when the connection is fenced during automation retirement', async () => {
const h = await fixture()
await h.executor.handle(
createCommand('navigate', {
command: { type: 'navigate', url: 'https://example.com/authenticated' }
}),
new AbortController().signal
)
h.dependencies.routeWebContents.navigateGuest.mockClear()
h.dependencies.retireAutomation.mockImplementationOnce(async () => {
h.executor.fenceNavigation()
})
expect(await h.executor.handle(switchCommand(), new AbortController().signal)).toMatchObject({
status: 'failed',
errorCode: 'browser_client_page_executor_closed'
})
expect(h.dependencies.routeWebContents.revokeNavigation).toHaveBeenCalledWith(
expect.objectContaining({
registration: expect.objectContaining({ webContentsId: 42 })
})
)
expect(h.dependencies.routeWebContents.navigateGuest).not.toHaveBeenCalled()
expect(h.bindReplacement).not.toHaveBeenCalled()
expect(h.executor.hasPage('page-a', 7)).toBe(true)
})
it('keeps cleanup evidence when staging fails before handing over its guest', async () => {
const h = await fixture()
h.dependencies.routeWebContents.registerGuest.mockReturnValueOnce(false)
h.dependencies.routeWebContents.beginGuestRetirement.mockImplementationOnce(() => {
throw new Error('cleanup refused')
})
expect(await h.executor.handle(switchCommand(), new AbortController().signal)).toMatchObject({
status: 'failed',
errorCode: 'browser_client_page_cleanup_failed'
})
expect(h.executor.hasPage('page-a', 7)).toBe(true)
await expect(h.executor.close()).rejects.toThrow('Browser client page executor cleanup failed')
})
it('does not commit a replacement guest that died before the switch finished', async () => {
const h = await fixture()
let replacementAlive = true
h.dependencies.routeWebContents.claimGuestLifecycle.mockImplementationOnce((registration) =>
createLifecycleClaim(registration, Promise.resolve(), () => replacementAlive)
)
h.bindReplacement.mockImplementation(() => {
replacementAlive = false
})
expect(await h.executor.handle(switchCommand(), new AbortController().signal)).toMatchObject({
status: 'failed',
errorCode: 'browser_client_page_generation_stale'
})
expect(h.executor.hasPage('page-a', 7)).toBe(true)
expect(h.dependencies.routeWebContents.beginGuestRetirement).toHaveBeenCalledTimes(1)
expect(h.dependencies.routeWebContents.beginGuestRetirement).toHaveBeenCalledWith(
expect.objectContaining({ registration: expect.objectContaining({ webContentsId: 42 }) })
)
})
it('reports an old guest lost during a failed switch so recovery can run', async () => {
let oldAlive = true
const availability = new BrowserRoutePageAvailability()
const h = await fixture(availability, () => oldAlive)
const onPageUnavailable = vi.fn()
Object.assign(h.dependencies, { onPageUnavailable })
h.dependencies.routeSessions.preparePage.mockImplementationOnce(async () => {
oldAlive = false
availability.report(h.dependencies.routeWebContents.claimGuestLifecycle.mock.calls[0]![0])
throw new Error('target profile rejected')
})
expect(await h.executor.handle(switchCommand(), new AbortController().signal)).toMatchObject({
status: 'failed'
})
expect(onPageUnavailable).toHaveBeenCalledWith('page-a', 7)
expect(h.executor.snapshotPageInventory()).toMatchObject([
{ pageHostGeneration: 7, state: 'outcomeUnknown' }
])
expect(h.dependencies.guestBinding.bind).toHaveBeenCalledTimes(1)
})
it('lets the staged guest own downloads it starts while loading the page', async () => {
const h = await fixture()
await h.executor.handle(
createCommand('navigate', {
command: { type: 'navigate', url: 'https://example.com/report.csv' }
}),
new AbortController().signal
)
let owner: { pageHostGeneration: number } | undefined
h.dependencies.routeWebContents.navigateGuest.mockImplementationOnce(async () => {
owner = h.executor.findPageByWebContentsId(42)
return true
})
expect(await h.executor.handle(switchCommand(), new AbortController().signal)).toEqual({
status: 'completed'
})
expect(owner).toMatchObject({ browserPageId: 'page-a', pageHostGeneration: 8 })
})
it('rejects stale generations without preparing or binding anything', async () => {
const h = await fixture()
const calls = h.dependencies.routeSessions.preparePage.mock.calls.length
expect(
await h.executor.handle(
{ ...switchCommand(), pageHostGeneration: 6 },
new AbortController().signal
)
).toMatchObject({ status: 'failed' })
expect(h.dependencies.routeSessions.preparePage).toHaveBeenCalledTimes(calls)
expect(h.bindReplacement).not.toHaveBeenCalled()
})
it('rolls back an abort after successful target binding', async () => {
const h = await fixture()
const controller = new AbortController()
h.bindReplacement.mockImplementation(() => controller.abort())
expect(await h.executor.handle(switchCommand(), controller.signal)).toMatchObject({
status: 'failed'
})
expect(h.executor.hasPage('page-a', 7)).toBe(true)
expect(h.dependencies.guestBinding.bind).toHaveBeenLastCalledWith(
expect.objectContaining({
registration: expect.objectContaining({ webContentsId: 41 })
})
)
})
})