test: remove low-value bridge and native checks (#42105)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-13 11:15:10 -08:00
committed by GitHub
co-authored by OrcaWin
parent 12787ce772
commit a36d1ddafd
32 changed files with 57 additions and 916 deletions
@@ -38,6 +38,8 @@ jobs:
mac-native-owner-smoke:
if: github.event_name != 'pull_request' || github.event.pull_request.draft != true
runs-on: macos-15
env:
ORCA_BACKGROUND_LAUNCH: '1'
timeout-minutes: 180
permissions:
contents: read
@@ -29,7 +29,9 @@ import Foundation
// Shared with the Kotlin tests and the JS tests, which pin fflate's answer to the same inputs.
let url = URL(fileURLWithPath: "tests/gunzip-vectors.json")
let vectors = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as! [[String: Any]]
for vector in vectors {
for vector in vectors where [
"one member", "reaches the limit", "bomb", "bad CRC", "trailing data", "truncated body"
].contains(vector["name"] as? String ?? "") {
let name = vector["name"] as! String
let expected = (vector["native"] as? String).map { bytes(hex: $0) }
let actual = try? gunzipBounded(
@@ -41,9 +41,6 @@ import Foundation
// Only / may serve document bytes with CSP; no entrypoint alias.
precondition(built.entries["/index.html"] == nil)
precondition(generation(manifest(schemaVersion: 2)) == nil)
precondition(generation(manifest(entrypoint: "start.html")) == nil)
precondition(generation(manifest(assets: [])) == nil)
// The entrypoint must be one of the assets, or "/" would map to a file nobody declared.
precondition(generation(manifest(assets: [
["path": "assets/aa.js", "contentType": "text/javascript; charset=utf-8"]
@@ -56,46 +53,13 @@ import Foundation
["path": "index.html", "contentType": "text/html; charset=utf-8"],
["path": "assets/aa.js", "contentType": "text/javascript\r\nX-Injected: 1"]
])) == nil)
precondition(generation(manifest(assets: [
["path": "index.html", "contentType": "text/html; charset=utf-8"],
["path": 7, "contentType": "text/javascript; charset=utf-8"]
])) == nil)
let tooMany = (0..<257).map { index in
["path": "assets/a\(index).js", "contentType": "text/javascript; charset=utf-8"]
}
precondition(generation(manifest(assets: tooMany)) == nil)
// NSNumber bridges JSON true and 1.0 to Int; neither satisfies the integer-1 contract.
precondition(generation(Data(#"{"schemaVersion":true,"entrypoint":"index.html","assets":[{"path":"index.html","contentType":"text/html"}]}"#.utf8)) == nil)
precondition(generation(Data(#"{"schemaVersion":1.0,"entrypoint":"index.html","assets":[{"path":"index.html","contentType":"text/html"}]}"#.utf8)) == nil)
precondition(generation(Data(#"{"schemaVersion":"1","entrypoint":"index.html","assets":[{"path":"index.html","contentType":"text/html"}]}"#.utf8)) == nil)
precondition(generation(Data("not json".utf8)) == nil)
precondition(generation(Data("[]".utf8)) == nil)
}
static func checkLoadStateMachine() {
// Only the view’s own load raises the flag; commit, failure, renderer death and failed prop application clear it.
let ownLoad = MobileWebShellLoadStateMachine()
precondition(!ownLoad.isShellLoad)
ownLoad.shellLoadStarted()
precondition(ownLoad.isShellLoad)
ownLoad.committed()
precondition(!ownLoad.isShellLoad)
ownLoad.shellLoadStarted()
_ = ownLoad.failed(.documentLoadFailed)
precondition(!ownLoad.isShellLoad)
ownLoad.reset()
ownLoad.shellLoadStarted()
ownLoad.documentEnded()
precondition(!ownLoad.isShellLoad)
let progress = MobileWebShellLoadStateMachine()
precondition(progress.started()?.state == "loading")
precondition(progress.started() == nil)
progress.committed()
precondition(progress.finished()?.state == "ready")
precondition(progress.finished() == nil)
// replaceState rewrites the URL before finish; readiness must depend on commit state.
let unseated = MobileWebShellLoadStateMachine()
_ = unseated.started()
@@ -103,12 +67,6 @@ import Foundation
unseated.committed()
precondition(unseated.finished()?.state == "ready")
// A document replaced mid-load: the finish belongs to the one that is already gone.
let replaced = MobileWebShellLoadStateMachine()
replaced.committed()
replaced.documentEnded()
precondition(replaced.finished() == nil)
// A rule list compiles asynchronously, so it can fail after the generation was already refused.
let refused = MobileWebShellLoadStateMachine()
precondition(refused.failed(.generationUnreadable)?.reason == "generation-unreadable")
@@ -122,7 +80,6 @@ import Foundation
// A document is heard only between its own commit and the end of that load.
let arming = MobileWebShellLoadStateMachine()
precondition(!arming.hasCommittedDocument)
_ = arming.started()
// The previous document is alive and same-origin until the next one commits.
precondition(!arming.hasCommittedDocument)
@@ -12,15 +12,11 @@ import Foundation
}
let ledger = PushDismissalLedger(defaults: defaults)
ledger.remember(identity(2), now: 100)
ledger.remember(identity(1), now: 101)
let restored = PushDismissalLedger(defaults: defaults)
precondition(restored.contains(identity(1), now: 102))
precondition(restored.contains(identity(2), now: 102))
precondition(!restored.contains(identity(3), now: 102))
precondition(!restored.contains(identity(1, "other"), now: 102))
precondition(!restored.contains(identity(1, "qa-host", "other"), now: 102))
precondition(!restored.contains(identity(1, "qa-host", "qa-epoch", "other"), now: 102))
precondition(!restored.contains(identity(1), now: 86501))
precondition(PushDismissalIdentity(["hostFingerprint":"h", "notificationId":"n", "notificationEpoch":"e", "notificationSeq":true]) == nil)
for hosts in [1, 3] {
for index in 0..<520 {
@@ -36,7 +32,6 @@ import Foundation
let batch = PushDismissalLedger(defaults: defaults)
batch.remember(identity(5, "batch"), now: 300)
batch.remember([identity(4, "batch"), identity(7, "batch", "qa-epoch", "b"), identity(6, "batch", "qa-epoch", "b"), identity(1, "batch", "qa-epoch", "c")], now: 300)
batch.remember([PushDismissalIdentity](), now: 301)
let batchReopened = PushDismissalLedger(defaults: defaults)
precondition(batchReopened.contains(identity(5, "batch"), now: 301))
precondition(!batchReopened.contains(identity(6, "batch"), now: 301))
@@ -69,25 +69,4 @@ describe('a native method the page asks for', () => {
})
expect(JSON.stringify(bridge.posted)).not.toContain(secret)
})
it('settles a cancelled native request the way a forwarded one settles, with no late reply', async () => {
const settle: { resolve: ((value: unknown) => void) | null } = { resolve: null }
const bridge = harness({
serveNativeVerb: () =>
new Promise((resolve) => {
settle.resolve = resolve
})
})
bridge.host.receive(clientFrame({ type: 'ready' }))
bridge.host.receive(request('native.clipboard.read', { mime: 'text' }))
bridge.host.receive(clientFrame({ type: 'cancel', id: ID, target: 'request' }))
const afterCancel = bridge.frames().length
expect(settle.resolve).not.toBeNull()
if (settle.resolve === null) {
throw new Error('native handler never entered')
}
settle.resolve({ value: 'too late' })
await flushBridge()
expect(bridge.frames()).toHaveLength(afterCancel)
expect(reachedTheDesktop(bridge)).toEqual([])
})
})
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { ID, harness } from './bridge-host-test-harness'
import { harness } from './bridge-host-test-harness'
import { clientFrame, createFakeRpcClient } from './bridge-host-test-fakes'
import { BRIDGE_EXTERNAL_LINK_GRANT, BRIDGE_FAULT_GRANT } from './bridge/bridge-envelope'
@@ -32,20 +32,6 @@ describe('notifications, refusals and the fence', () => {
])
})
it('drops a page fault that arrives after the document said goodbye', () => {
const bridge = harness()
bridge.host.receive(clientFrame({ type: 'close' }))
bridge.host.receive(
clientFrame({
type: 'notify',
name: BRIDGE_FAULT_GRANT,
error: { category: 'Error', message: 'late', isRpcDeliveryUnknown: false }
})
)
expect(bridge.pageFaults).toEqual([])
expect(bridge.diagnostics).toEqual([{ kind: 'frame-after-close' }])
})
it('reports a listener that throws on a page fault once, and keeps reading', () => {
const failure = new Error('the session is gone')
const bridge = harness({
@@ -67,31 +53,6 @@ describe('notifications, refusals and the fence', () => {
expect(bridge.last().type).toBe('init')
})
it('reports a client that throws on a notify once per session, and keeps reading', () => {
const client = createFakeRpcClient()
const failure = new Error('no client')
const bridge = harness({
client: {
...client,
notifyForeground: () => {
throw failure
},
updateTerminalSubscriptionViewport: () => {
throw failure
}
}
})
bridge.host.receive(clientFrame({ type: 'ready' }))
// Never let a throw escape the native event handler delivering this frame.
bridge.host.receive(clientFrame({ type: 'notify', name: 'foreground' }))
bridge.host.receive(
clientFrame({ type: 'notify', name: 'terminalViewport', terminal: 't1', cols: 80, rows: 24 })
)
expect(bridge.diagnostics).toEqual([{ kind: 'notify-failed', error: failure }])
bridge.host.receive(clientFrame({ type: 'ready' }))
expect(bridge.last().type).toBe('init')
})
it('reports a post that throws instead of rejecting, and does not take the sender down', () => {
const failure = new Error('the bridge module is gone')
const client = createFakeRpcClient()
@@ -105,18 +66,6 @@ describe('notifications, refusals and the fence', () => {
expect(() => client.pushState('reconnecting')).not.toThrow()
expect(bridge.diagnostics).toEqual([{ kind: 'post-failed', error: failure }])
})
it('forwards to the client it was built with, whatever the frame names', () => {
const mine = createFakeRpcClient()
const theirs = createFakeRpcClient()
const bridge = harness({ ready: true, client: mine })
harness({ client: theirs })
bridge.host.receive(
clientFrame({ type: 'request', id: ID, method: 'status.get', hostId: 'other-host' })
)
expect(mine.requests.map((request) => request.method)).toEqual(['status.get'])
expect(theirs.requests).toHaveLength(0)
})
})
// Validate external-link schemes at the envelope too; a page bypassing its own guard must not reach the device handler with arbitrary URLs.
@@ -65,27 +65,6 @@ function observeBacklogs(): BridgeTerminalOutputBacklog[] {
afterEach(() => vi.restoreAllMocks())
describe('bridge subscription start cleanup', () => {
it('rethrows the original immediate failure without keeping a slot or timer', () => {
const failure = new Error('subscribe failed')
const timers = manualTimers()
const subscriptions = new BridgeHostSubscriptions({
client: {
...createFakeRpcClient(),
subscribe: () => {
throw failure
}
},
post: vi.fn(),
onBinaryFrameDropped: vi.fn(),
terminalTimers: timers
})
expect(() => subscriptions.start(ID, 'terminal.subscribe', {})).toThrow(failure)
expect(subscriptions.size).toBe(0)
expect(timers.pending()).toBe(0)
expect(timers.delays).toEqual([])
})
it('releases held output and its silence timer when subscribe emits and then throws', () => {
const failure = new Error('subscribe failed after output')
const timers = manualTimers()
@@ -12,8 +12,7 @@ import {
import {
BRIDGE_MAX_MESSAGE_BYTES,
BRIDGE_MAX_PENDING_DESKTOP_REQUESTS,
BRIDGE_MAX_REPLY_BYTES,
BRIDGE_MAX_SUBSCRIPTIONS
BRIDGE_MAX_REPLY_BYTES
} from './bridge/bridge-caps'
import type { BridgeHostMessage } from './bridge/bridge-envelope'
import { BridgeReplyAssembler } from './bridge/bridge-reply-chunking'
@@ -135,16 +134,6 @@ describe('replies too big for one frame', () => {
})
describe('subscriptions', () => {
it('reopens a slot when a stream is cancelled', () => {
const bridge = harness({ ready: true })
for (let index = 0; index < BRIDGE_MAX_SUBSCRIPTIONS; index += 1) {
bridge.host.receive(subscribeFrame(bridgeId(index)))
}
bridge.host.receive(clientFrame({ type: 'cancel', id: bridgeId(0), target: 'subscription' }))
bridge.host.receive(subscribeFrame(bridgeId(BRIDGE_MAX_SUBSCRIPTIONS)))
expect(bridge.client.streams).toHaveLength(BRIDGE_MAX_SUBSCRIPTIONS + 1)
})
it('unsubscribes on cancel, says so, and delivers nothing after', () => {
const bridge = harness({ ready: true })
bridge.host.receive(subscribeFrame(ID))
@@ -156,33 +145,6 @@ describe('subscriptions', () => {
expect(bridge.frames().filter((frame) => frame.type === 'event')).toHaveLength(1)
})
it('answers a client whose subscribe throws and holds no slot', () => {
const client = createFakeRpcClient()
let attempts = 0
const bridge = harness({
ready: true,
client: {
...client,
subscribe: () => {
attempts += 1
throw new Error('no socket')
}
}
})
bridge.host.receive(subscribeFrame(ID))
expect(bridge.last().type).toBe('error')
bridge.host.receive(subscribeFrame(ID))
expect(attempts).toBe(2)
expect(bridge.frames().filter((frame) => frame.type === 'error')).toEqual(
[1, 2].map(() =>
expect.objectContaining({
type: 'error',
error: expect.objectContaining({ message: 'no socket' })
})
)
)
})
it('unsubscribes a stream that overflowed inside subscribe, exactly once', () => {
const client = createFakeRpcClient()
let unsubscribes = 0
@@ -343,15 +305,6 @@ describe('teardown', () => {
)
})
it('is idempotent', () => {
const bridge = harness({ ready: true })
bridge.host.receive(subscribeFrame(ID))
bridge.host.dispose()
bridge.host.dispose()
expect(bridge.frames()).toHaveLength(2)
expect(bridge.client.streams[0]?.unsubscribes).toBe(1)
})
it('settles what the page owned on close without answering a page that said goodbye', async () => {
const bridge = harness({ ready: true })
bridge.host.receive(clientFrame({ type: 'request', id: ID, method: 'status.get' }))
@@ -1,71 +1,20 @@
import { describe, expect, it } from 'vitest'
import { BRIDGE_MAX_MESSAGE_BYTES } from './bridge/bridge-caps'
import { clientFrame } from './bridge-host-test-fakes'
import { harness, ID, OTHER } from './bridge-host-test-harness'
import type { TerminalBacklogTimers } from './bridge-terminal-output-backlog'
// Rebuild measured terminal timing: host JSON at 70.3 MiB/s, xterm at 2.2 MiB/s, batcher 64 KiB/5 ms and chunker 48 KiB; a 5 MB cat exhausts the ordinary window before paint.
// Measure JSON expansion for ASCII and SGR output; simulate the timeline because the original design capture files are not in this lane.
function manualTimers(): TerminalBacklogTimers & { fire: () => void; armed: () => boolean } {
let handler: (() => void) | null = null
return {
set: (next) => {
handler = next
return 1
},
clear: () => {
handler = null
},
armed: () => handler !== null,
fire: () => {
const pending = handler
handler = null
pending?.()
}
}
}
// Simulate emit → limited page drain → interval acknowledgement at measured rates; this ordering determines whether backpressure kills the stream.
describe('the two ends a held terminal stream has', () => {
function held(): ReturnType<typeof harness> & { timers: ReturnType<typeof manualTimers> } {
const timers = manualTimers()
const bridge = harness({ ready: true, terminalTimers: timers })
bridge.host.receive(
clientFrame({ type: 'subscribe', id: ID, method: 'terminal.subscribe', params: {} })
)
return Object.assign(bridge, { timers })
}
it('still ends on one event over the frame cap, which is C0.3 and is not slowness', () => {
// Holding cannot rescue an event the page refuses for size; the frame cap still ends it visibly.
const bridge = held()
bridge.client.streams[0].emit({
type: 'data',
streamId: 1,
chunk: 'z'.repeat(BRIDGE_MAX_MESSAGE_BYTES + 1)
})
const ends = bridge.frames().filter((frame) => frame.type === 'end')
expect(ends).toHaveLength(1)
expect(ends[0]).toMatchObject({ reason: 'overflow' })
})
})
import { harness, ID } from './bridge-host-test-harness'
describe('the cases the rulings name', () => {
function subscribed(
ids: readonly string[]
): ReturnType<typeof harness> & { timers: ReturnType<typeof manualTimers> } {
const timers = manualTimers()
const bridge = harness({ ready: true, terminalTimers: timers })
function subscribed(ids: readonly string[]): ReturnType<typeof harness> {
const bridge = harness({
ready: true,
terminalTimers: { set: () => 1, clear: () => undefined }
})
for (const id of ids) {
bridge.host.receive(
clientFrame({ type: 'subscribe', id, method: 'terminal.subscribe', params: {} })
)
}
return Object.assign(bridge, { timers })
return bridge
}
// Close the frame-count window cheaply; 256 small frames exercise the same held state without allocating a 4 MiB byte-window fixture.
@@ -87,17 +36,6 @@ describe('the cases the rulings name', () => {
}
}
it('keeps one backlog per subscription, so a busy terminal cannot end a quiet one', () => {
const bridge = subscribed([ID, OTHER])
for (let index = 0; index < OVER_FRAME_WINDOW; index += 1) {
bridge.client.streams[0].emit({ type: 'data', streamId: 1, chunk: SMALL_CHUNK })
}
bridge.client.streams[1].emit({ type: 'data', streamId: 2, chunk: 'quiet' })
const other = bridge.frames().filter((frame) => frame.type === 'event' && frame.id === OTHER)
expect(other).toHaveLength(1)
expect(bridge.frames().some((frame) => frame.type === 'end' && frame.id === OTHER)).toBe(false)
})
it('breaks a merge run on a payload that is not output, and keeps the order', () => {
// Merge only consecutive output; resize/metadata must retain their position between byte runs.
const bridge = subscribed([ID])
@@ -44,45 +44,11 @@ function drain(payloads: readonly Payload[], cap: number, windowEmpty: boolean):
}
}
// The wire serializer is the oracle for both escaping and the exact accepted prefix.
function serializedFrames(
payloads: readonly Payload[],
cap: number,
windowEmpty: boolean
): Payload[] {
const pending = [...payloads]
const frames: Payload[] = []
while (pending.length > 0) {
const head = pending[0]
if (wireBytes(head) > cap && !windowEmpty) {
break
}
pending.shift()
if (head.type !== 'data') {
frames.push(head)
continue
}
let frame = head
while (pending[0]?.type === 'data') {
const next = pending[0]
const combined = output(frame.chunk + next.chunk, head.streamId)
if (wireBytes(combined) > cap) {
break
}
pending.shift()
frame = combined
}
frames.push(frame)
}
return frames
}
describe('terminal backlog merge framing', () => {
it('merges split surrogate pairs across empty chunks at the exact byte cap', () => {
const payloads = [output('prefix\ud83d'), output(''), output(''), output('\ude00suffix')]
const combined = output('prefix😀suffix')
const cap = wireBytes(combined)
expect(drain(payloads, cap, true)).toEqual([combined])
expect(drain(payloads, cap - 1, true)).toEqual(serializedFrames(payloads, cap - 1, true))
})
})
@@ -100,19 +100,4 @@ describe('a Back press crossing from the shell to the page', () => {
})
})
describe('the Back lane with no negotiation', () => {
it('hands a press to any page it serves, whose ready declares nothing', async () => {
const pair = await opened()
pair.host.receive(JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready' }))
await pair.flush()
const before = pair.toPage.length
expect(pair.host.sendBack()).toBe(true)
await pair.flush()
expect(pair.toPage.length).toBe(before + 1)
expect(pair.readToPage().at(-1)).toEqual({ v: 1, type: 'back' })
expect(pair.backPops).toEqual(['popped'])
expect(pair.diagnostics).toContainEqual({ kind: 'back-unclaimed' })
})
})
afterEach(closeResources)
@@ -1,77 +0,0 @@
import { afterEach, describe, expect, it } from 'vitest'
import { BRIDGE_MAX_MESSAGE_BYTES, parseBridgeMessage } from './bridge-caps'
import { createFakeBridgePortPair as createPair } from './bridge-port-pair-test-harness'
const resources = new Set<ReturnType<typeof createPair>>()
function createFakeBridgePortPair(
...args: Parameters<typeof createPair>
): ReturnType<typeof createPair> {
const resource = createPair(...args)
resources.add(resource)
return resource
}
function closeResources(): void {
for (const resource of resources) {
resource.client.close()
resource.host.dispose()
}
resources.clear()
}
// Compare sender/reader at cap and cap+1 to catch off-by-one hangs; also require the shared predicate so a copied bound cannot drift later.
// Measure serialized request overhead rather than counting envelope characters by hand.
const envelope = (params: unknown) =>
JSON.stringify({ v: 1, type: 'request', id: '0'.repeat(22), method: METHOD, params })
const METHOD = 'git.status'
function framePayload(bytes: number): { pad: string } {
const pad = bytes - new TextEncoder().encode(envelope({ pad: '' })).byteLength
if (pad < 1) {
throw new Error(`a ${bytes}-byte frame cannot hold this envelope`)
}
return { pad: 'x'.repeat(pad) }
}
async function sendOfSize(bytes: number) {
const pair = createFakeBridgePortPair()
await pair.flush()
const before = pair.toShell.length
let rejection: string | null = null
void pair.client.sendRequest(METHOD, framePayload(bytes)).catch((error: Error) => {
rejection = error.name
})
await pair.flush()
const posted = pair.toShell.slice(before).filter((raw) => raw.includes(`"method":"${METHOD}"`))
return {
rejection,
posted,
expected: envelope(framePayload(bytes)),
diagnostics: pair.diagnostics.map((entry) => entry.kind)
}
}
describe('the page frame cap at its boundary', () => {
it('sends a frame of exactly the cap, which the reader accepts', async () => {
const sent = await sendOfSize(BRIDGE_MAX_MESSAGE_BYTES)
expect(sent.rejection).toBeNull()
expect(sent.posted).toHaveLength(1)
expect(new TextEncoder().encode(sent.posted[0]).byteLength).toBe(BRIDGE_MAX_MESSAGE_BYTES)
expect(parseBridgeMessage(sent.posted[0], 'page-to-shell').ok).toBe(true)
expect(sent.diagnostics).toEqual([])
})
it('refuses a frame one byte over it, which the reader would have dropped', async () => {
const overCap = BRIDGE_MAX_MESSAGE_BYTES + 1
const sent = await sendOfSize(overCap)
expect(sent.rejection).toBe('BridgeRequestOversizedError')
expect(sent.posted).toEqual([])
expect(sent.diagnostics).toEqual(['send-oversized'])
expect(new TextEncoder().encode(sent.expected).byteLength).toBe(overCap)
const read = parseBridgeMessage(sent.expected, 'page-to-shell')
expect(read.ok).toBe(false)
expect(read.ok ? null : read.refusal).toBe('oversized')
})
})
afterEach(closeResources)
@@ -18,7 +18,7 @@ function closeResources(): void {
resources.clear()
}
// Keep serialization inside sendFrame’s catch: cyclic params, BigInt or throwing toJSON must abandon the opened request id and report send failure, never leak one of 64 slots.
// Failed serialization must release the request slot.
function cyclicParams(): Record<string, unknown> {
const params: Record<string, unknown> = { worktree: 'id:wt-1' }
@@ -41,18 +41,7 @@ async function acceptedRequestCount(client: {
return attempts - refusals.filter((name) => name === 'BridgeClientCapExceededError').length
}
const unserializable = [
{ name: 'cycle', params: cyclicParams },
{ name: 'BigInt', params: () => ({ count: 1n }) },
{
name: 'throwing toJSON',
params: () => ({
toJSON() {
throw new Error('cannot serialize')
}
})
}
]
const unserializable = [{ name: 'cycle', params: cyclicParams }]
describe('a request frame the page cannot serialize', () => {
it.each(unserializable)('rejects $name as a send failure and reports it', async ({ params }) => {
@@ -1,29 +0,0 @@
import { afterEach, expect, it } from 'vitest'
import { createFakeBridgePortPair } from './bridge-port-pair-test-harness'
let pair: ReturnType<typeof createFakeBridgePortPair> | null = null
afterEach(() => {
pair?.client.close()
pair?.host.dispose()
pair = null
})
it('reads an init without colorScheme as dark, then repaints once per scheme change in place', async () => {
pair = createFakeBridgePortPair()
await pair.flush()
const init = pair.readToPage().find((frame) => frame.type === 'init')
expect(init !== undefined && 'colorScheme' in init).toBe(false)
const session = pair.client.getShellSession()
expect(session?.colorScheme).toBe('dark')
const seen: string[] = []
pair.client.onColorSchemeUpdate((scheme) => seen.push(scheme))
for (const scheme of ['light', 'light', 'dark'] as const) {
pair.host.publishColorScheme(scheme)
await pair.flush()
expect(pair.client.getShellSession()?.colorScheme).toBe(scheme)
}
expect(seen).toEqual(['light', 'dark'])
expect(pair.client.getShellSession()?.sessionId).toBe(session?.sessionId)
})
@@ -1,81 +0,0 @@
import { describe, expect, it } from 'vitest'
import { createFakeBridgePortPair } from './bridge-port-pair-test-harness'
import { readBridgeHostMessage } from './bridge-envelope'
import { createBridgeInitFrame } from './bridge-init-frame'
import { readShellSession } from './bridge-client-session'
import type { BridgeFoldDivision } from './bridge-fold-division'
// iPhone Duo, inner display, half folded: the fold band with UIKit's 20pt margins either side.
const BOOK: BridgeFoldDivision = { axis: 'vertical', start: 455.5, end: 495.5 }
const TABLETOP: BridgeFoldDivision = { axis: 'horizontal', start: 455.5, end: 495.5 }
function initFrame(foldDivision?: BridgeFoldDivision | null) {
return createBridgeInitFrame({
sessionId: 'session-a',
buildId: 'build-a',
connection: {
state: 'connected',
reconnectAttempt: 0,
lastConnectedAt: null,
lastInboundAt: null,
generation: null
},
route: { pathname: '/h/host-a' },
pageRoutes: ['/h/[hostId]'],
granted: [],
host: { id: 'host-a', name: 'Host A', endpoint: 'ws://host-a', lastConnected: 0 },
storage: {},
...(foldDivision === undefined ? {} : { foldDivision })
})
}
function readInit(json: string) {
const read = readBridgeHostMessage(json)
if (!read.ok || read.message.type !== 'init') {
throw new Error(
`not an init the page would read: ${read.ok ? read.message.type : read.refusal}`
)
}
return read.message
}
describe('foldDivision on init', () => {
it('drops a fold the page cannot read without refusing the init around it', () => {
for (const bad of [
{ ...BOOK, end: 400 },
{ ...BOOK, axis: 'diagonal' },
{ ...BOOK, start: -1 }
]) {
const init = readInit(JSON.stringify({ ...initFrame(), foldDivision: bad }))
expect(readShellSession(init).foldDivision, JSON.stringify(bad)).toBeNull()
}
})
})
describe('a fold that moves under a live page', () => {
it('re-sends init as the device folds, turns and opens, and the page reads each in place', async () => {
const pair = createFakeBridgePortPair()
await pair.flush()
const sessionId = pair.client.getShellSession()?.sessionId
const seen: (BridgeFoldDivision | null)[] = []
pair.client.onFoldDivisionUpdate((division) => seen.push(division))
for (const division of [BOOK, TABLETOP, null]) {
pair.host.publishFoldDivision(division)
await pair.flush()
expect(pair.client.getShellSession()?.foldDivision).toEqual(division)
}
expect(seen).toEqual([BOOK, TABLETOP, null])
expect(pair.client.getShellSession()?.sessionId).toBe(sessionId)
})
it('sends nothing for a fold that did not move', async () => {
const pair = createFakeBridgePortPair({ foldDivision: BOOK })
await pair.flush()
const inits = () => pair.readToPage().filter((frame) => frame.type === 'init').length
const before = inits()
pair.host.publishFoldDivision({ ...BOOK })
await pair.flush()
expect(inits()).toBe(before)
})
})
@@ -58,17 +58,6 @@ describe('keyboardInset on init', () => {
expect(readShellSession(init).keyboardInset).toBe(0)
}
})
it('passes the keyboard height through to the session the page holds', () => {
expect(readShellSession(readInit(JSON.stringify(initFrame(312)))).keyboardInset).toBe(312)
})
it('refuses negative, oversized, null and string keyboard heights', () => {
for (const bad of [-1, 1e9, null, '312']) {
const frame = { ...initFrame(), keyboardInset: bad }
expect(readBridgeHostMessage(JSON.stringify(frame)).ok, String(bad)).toBe(false)
}
})
})
describe('a keyboard that moves under a live page', () => {
@@ -91,17 +80,6 @@ describe('a keyboard that moves under a live page', () => {
expect(pair.client.getShellSession()?.sessionId).toBe(session?.sessionId)
expect(pair.client.getShellSession()?.route).toEqual(session?.route)
})
it('sends nothing for a height that did not move', async () => {
const pair = createFakeBridgePortPair({ keyboardInset: 312 })
await pair.flush()
const inits = () => pair.readToPage().filter((frame) => frame.type === 'init').length
const before = inits()
pair.host.publishKeyboardInset(312)
await pair.flush()
expect(inits()).toBe(before)
expect(pair.client.getShellSession()?.keyboardInset).toBe(312)
})
})
afterEach(closeResources)
@@ -42,19 +42,6 @@ describe('a route update over a re-sent init', () => {
expect(seen).toEqual(['pane-1', '', 'pane-1'])
})
it('reaches the page for a different pane without opening a second session', async () => {
const pair = await openedOnTheSession()
const before = pair.client.getShellSession()
const seen = recordRouteUpdates(pair)
pair.host.publishRoute(sessionRoute('pane-1'))
await pair.flush()
pair.host.publishRoute(sessionRoute('pane-2'))
await pair.flush()
expect(seen).toEqual(['pane-1', 'pane-2'])
expect(pair.pageReadyCount()).toBe(1)
expect(pair.client.getShellSession()?.sessionId).toBe(before?.sessionId)
})
// Repeated ready repairs state but is not another pane request; notify listeners only when route params move.
it('publishes nothing for a re-asked ready that carries the route the page holds', async () => {
const pair = await openedOnTheSession()
@@ -80,22 +67,4 @@ describe('a route update over a re-sent init', () => {
await pair.flush()
await expect(pending).resolves.toMatchObject({ ok: true })
})
it('leaves the storage snapshot the same object the page already held', async () => {
const pair = await openedOnTheSession()
const before = pair.client.getShellSession()?.storage
pair.host.publishRoute(sessionRoute('pane-1'))
await pair.flush()
expect(pair.client.getShellSession()?.storage).toBe(before)
})
it('sends the second init to a page whose ready declares nothing', async () => {
const pair = await openedOnTheSession()
pair.host.receive(JSON.stringify({ v: 1, type: 'ready' }))
await pair.flush()
const framesBefore = pair.toPage.length
pair.host.publishRoute(sessionRoute('pane-1'))
await pair.flush()
expect(pair.toPage.length).toBe(framesBefore + 1)
})
})
@@ -4,7 +4,7 @@ import { isRpcDeliveryUnknown } from '../../transport/rpc/rpc-delivery-ambiguity
import './bridge-caps'
import './bridge-port-pair-test-harness'
import './bridge-client-subscriptions'
import { BRIDGE_PROTOCOL_VERSION, type BridgeHostMessage } from './bridge-envelope'
import { BRIDGE_PROTOCOL_VERSION } from './bridge-envelope'
import './bridge-client-init-handshake'
import {
INIT,
@@ -132,33 +132,3 @@ describe('bridge client acks', () => {
expect(page.frames().filter((frame) => frame.type === 'cancel')).toEqual([])
})
})
describe('bridge client binary frames', () => {
const image = Uint8Array.from([137, 80, 78, 71, 13, 10, 26, 10])
const b64 = btoa(String.fromCharCode(...image))
function binaryFrame(id: string, b64Image: string): BridgeHostMessage {
return {
v: BRIDGE_PROTOCOL_VERSION,
type: 'event',
id,
seq: 1,
binary: { b64: b64Image, format: 'png', frameSeq: 41, metadata: { imageWidth: 8 } }
}
}
it('drops a frame with no listener and one it cannot decode', () => {
const page = createPageClient()
page.start()
page.client.subscribe('browser.screencast', {}, vi.fn())
page.deliver(binaryFrame(idOf(page, 0), b64))
const onBinaryFrame = vi.fn()
page.client.subscribe('browser.screencast', {}, vi.fn(), { onBinaryFrame })
page.deliver(binaryFrame(idOf(page, 1), '!!not base64!!'))
expect(onBinaryFrame).not.toHaveBeenCalled()
expect(page.diagnostics).toEqual([
{ kind: 'binary-frame-dropped' },
{ kind: 'binary-frame-dropped' }
])
})
})
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { BRIDGE_RPC_ENVELOPE_GRANT, readBridgeClientMessage } from './bridge-envelope'
import { BRIDGE_RPC_ENVELOPE_GRANT } from './bridge-envelope'
import {
BridgeRpcEnvelopeInvalidError,
BridgeRpcEnvelopeUngrantedError
@@ -65,31 +65,11 @@ describe('bridge rpc envelope: page side', () => {
.catch(readError)
expect(refusal).toBeInstanceOf(BridgeRpcEnvelopeInvalidError)
expect(refusal).toMatchObject({ code: 'bridge_rpc_envelope_invalid' })
expect(() =>
page.client.subscribe('terminal.subscribe', {}, () => undefined, { envelope: notJson })
).toThrow(BridgeRpcEnvelopeInvalidError)
expect(page.sent).toHaveLength(posted)
})
it.each([
['null', null],
['an array', []],
['a Date', new Date(0)]
])(
'refuses %s as an envelope with a rejection, never a throw or a silent drop',
async (_, value) => {
const page = grantedPage()
const posted = page.sent.length
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a caller that widened the type, which the check exists for.
const envelope = value as unknown as Record<string, null>
let answer: Promise<unknown> | undefined
expect(() => {
answer = page.client.sendRequest('worktree.ps', {}, { envelope })
}).not.toThrow()
expect(await answer?.catch(readError)).toBeInstanceOf(BridgeRpcEnvelopeInvalidError)
expect(() =>
page.client.subscribe('terminal.subscribe', {}, () => undefined, { envelope })
).toThrow(BridgeRpcEnvelopeInvalidError)
expect(page.sent).toHaveLength(posted)
}
)
})
describe('bridge rpc envelope: shell side', () => {
@@ -125,14 +105,4 @@ describe('bridge rpc envelope: shell side', () => {
])
expect(pair.rpc.streams.map((stream) => stream.envelope)).toEqual([undefined])
})
it('refuses a frame whose envelope is not a plain JSON object', () => {
for (const envelope of [[1], 'x', null, 3]) {
const frame = { v: 1, type: 'request', id: 'a'.repeat(22), method: 'm', envelope }
expect(readBridgeClientMessage(JSON.stringify(frame))).toEqual({
ok: false,
refusal: 'unrecognised-message'
})
}
})
})
@@ -43,22 +43,6 @@ describe('safeAreaInsets on init', () => {
expect('safeAreaInsets' in init).toBe(false)
expect(readShellSession(init).safeAreaInsets).toEqual(ZERO_SAFE_AREA_INSETS)
})
it('passes the shell insets through to the session the page holds', () => {
const init = readInit(JSON.stringify(initFrame(PHONE)))
expect(readShellSession(init).safeAreaInsets).toEqual(PHONE)
})
it('omits all-zero insets, since absent and zero are the same answer', () => {
expect('safeAreaInsets' in initFrame(ZERO_SAFE_AREA_INSETS)).toBe(false)
})
it('refuses an init whose insets no device produces, rather than padding by them', () => {
for (const bad of [{ ...PHONE, top: -1 }, { ...PHONE, bottom: 1e9 }, { top: 1 }]) {
const frame = { ...initFrame(), safeAreaInsets: bad }
expect(readBridgeHostMessage(JSON.stringify(frame)).ok, JSON.stringify(bad)).toBe(false)
}
})
})
describe('insets that move under a live page', () => {
@@ -78,14 +62,4 @@ describe('insets that move under a live page', () => {
expect(pair.client.getShellSession()?.sessionId).toBe(session?.sessionId)
expect(pair.client.getShellSession()?.route).toEqual(session?.route)
})
it('sends nothing for insets that did not move', async () => {
const pair = createFakeBridgePortPair({ safeAreaInsets: PHONE })
await pair.flush()
const inits = () => pair.readToPage().filter((frame) => frame.type === 'init').length
const before = inits()
pair.host.publishSafeAreaInsets({ ...PHONE })
await pair.flush()
expect(inits()).toBe(before)
})
})
@@ -51,16 +51,6 @@ describe('what init primed', () => {
await expect(pageAsyncStorage.getItem('orca:pins:host-2')).resolves.toBeNull()
})
it('reads several keys at once, which is how the list asks', async () => {
publish({ 'orca:pins:host-1': '["wt-1"]' })
await expect(
pageAsyncStorage.multiGet(['orca:pins:host-1', 'orca:last-visited-worktree'])
).resolves.toEqual([
['orca:pins:host-1', '["wt-1"]'],
['orca:last-visited-worktree', null]
])
})
it('replaces what the last page held rather than adding to it', async () => {
publish({ 'orca:pins:host-1': '["wt-1"]' })
publish({ 'orca:pins:host-2': '["wt-2"]' })
@@ -147,8 +137,6 @@ describe('what the page will not keep', () => {
)
// The durable journal exceeds this bound at 48 unsettled sends; report not-sent rather than lose the operation id (ruling 7).
expect(refusal.refusal).toBe('too-large')
expect(refusal.message).toContain('orca:mobileStructuredSendOperations:v1')
expect(refusal.message).toContain(String(PAGE_STORAGE_MAX_VALUE_CHARS))
expect(writes).toEqual([])
expect(await pageAsyncStorage.getItem('orca:mobileStructuredSendOperations:v1')).toBeNull()
})
@@ -186,22 +174,6 @@ describe('what the page will not keep', () => {
expect(await pageAsyncStorage.getItem('orca:last-visited-worktree')).toBe(atBound)
})
it('drops a write it may not make rather than rejecting, because nobody catches one', async () => {
// Unlisted-key preference writers await setItem without catches, often under void callers; retain silent drop. Only oversize journal writes reject because the composer catches them (ruling 33.4).
publish()
await expect(
pageAsyncStorage.setItem('orca:notificationDeliveryPreferences', '{}')
).resolves.toBeUndefined()
expect(writes).toEqual([])
expect(await pageAsyncStorage.getItem('orca:notificationDeliveryPreferences')).toBeNull()
})
it('drops a removal it may not make, for the same reason', async () => {
publish()
await expect(pageAsyncStorage.removeItem('orca:pins:host-2')).resolves.toBeUndefined()
expect(writes).toEqual([])
})
it('drops a write the shell would not take, rather than rejecting', async () => {
granted = false
await expect(pageAsyncStorage.setItem('orca:pins:host-1', '["wt-1"]')).resolves.toBeUndefined()
@@ -104,16 +104,6 @@ describe('who in the page is holding the device Back key', () => {
expect(claims).toEqual([true, true])
})
// Reassert only a held claim: ready already cleared it at the shell, so unclaimed documents need no redundant false frame.
it('says nothing when it is holding nothing, because the shell already holds that', () => {
const { claims, stack } = consumers()
stack.reassert()
const release = stack.claim(() => true)
release()
stack.reassert()
expect(claims).toEqual([true, false])
})
it('gives the key back when the client closes, whoever was still holding it', () => {
const { claims, stack } = consumers()
stack.claim(() => true)
@@ -7,7 +7,6 @@ import {
PAGE_BUILD_ID_KEY,
PAGE_MOUNT_STATE_KEY,
PAGE_SESSION_ID_KEY,
shellRouteHref,
type PageMountTarget
} from './page-bootstrap'
import type { BridgeRpcClient, BridgeShellSession } from './bridge-rpc-client'
@@ -214,10 +213,6 @@ describe('the page bootstrap under a shell that named no screen', () => {
})
describe('the page bootstrap outside the shell', () => {
it('builds no client when nothing installed a channel', () => {
expect(createShellPageClient()).toBeNull()
})
it('says so and does nothing to the document, because no init is ever coming', () => {
const target = createTarget()
const page = bootstrap(target)
@@ -227,16 +222,3 @@ describe('the page bootstrap outside the shell', () => {
expect(target.dataset[PAGE_SESSION_ID_KEY]).toBeUndefined()
})
})
describe('the url the page writes for a route', () => {
it('is the pathname alone when the screen was opened with no params', () => {
expect(shellRouteHref({ pathname: '/h/host-a' })).toBe('/h/host-a')
expect(shellRouteHref({ pathname: '/h/host-a', params: {} })).toBe('/h/host-a')
})
it('escapes what a param holds rather than pasting it into a path', () => {
expect(shellRouteHref({ pathname: '/h/a', params: { name: 'a&b=c?d#e' } })).toBe(
'/h/a?name=a%26b%3Dc%3Fd%23e'
)
})
})
@@ -26,9 +26,13 @@ afterEach(() => {
})
describe('the page fault boundary', () => {
it('reports once, because a faulted page never renders the tree that threw again', async () => {
const faults: unknown[] = []
const render = (): ReactElement => boundary(Throws, (error) => faults.push(error))
it('reports a thrown route once across the bridge, including subsequent renders', async () => {
const pair = createFakeBridgePortPair()
await pair.flush()
const render = (): ReactElement =>
boundary(Throws, (error) => {
pair.client.notifyPageFault(error)
})
const rendered: { tree: ReactTestRenderer | null } = { tree: null }
await act(async () => {
rendered.tree = create(render())
@@ -36,19 +40,6 @@ describe('the page fault boundary', () => {
await act(async () => {
rendered.tree?.update(render())
})
expect(faults).toEqual([FAILURE])
})
it('carries the throw across a real bridge to the shell that mounted the page', async () => {
const pair = createFakeBridgePortPair()
await pair.flush()
await act(async () => {
create(
boundary(Throws, (error) => {
pair.client.notifyPageFault(error)
})
)
})
await pair.flush()
expect(pair.pageFaults).toEqual([
{ category: 'Error', message: 'the route threw', isRpcDeliveryUnknown: false }
@@ -26,15 +26,4 @@ describe('the page telling the shell it has a frame', () => {
await pair.flush()
expect(pair.pagePaintCount()).toBe(1)
})
it('costs the shell nothing to hear: no request, no subscription, no reply', async () => {
const rpc = createFakeRpcClient()
const pair = createFakeBridgePortPair({ rpc })
await pair.flush()
const framesToPage = pair.toPage.length
pair.client.notifyPagePainted()
await pair.flush()
expect(rpc.requests).toHaveLength(0)
expect(pair.toPage).toHaveLength(framesToPage)
})
})
@@ -4,7 +4,6 @@ import { describe, expect, it } from 'vitest'
import {
RouteScreenPaintProvider,
createRouteScreenPaintReporter,
reportAfterFirstPaint,
withRouteScreenPaintReport
} from './page-first-paint'
@@ -33,30 +32,6 @@ function frames() {
}
}
describe('when the page says it has a frame', () => {
it('waits for a frame boundary past the commit, never the same one', () => {
// The first animation callback may run before the commit paints; one frame would uncover an undrawn tree.
const clock = frames()
let reported = 0
reportAfterFirstPaint(clock.scheduler, () => {
reported += 1
})
expect(reported).toBe(0)
clock.tick()
expect(reported).toBe(0)
clock.tick()
expect(reported).toBe(1)
})
it('reports once and schedules nothing after it', () => {
const clock = frames()
reportAfterFirstPaint(clock.scheduler, () => {})
clock.tick()
clock.tick()
expect(clock.pending()).toBe(0)
})
})
function deferredRouteChunk() {
let arrive: (() => void) | null = null
const chunk = new Promise<{ default: ComponentType<Record<string, unknown>> }>((resolve) => {
@@ -1,4 +1,3 @@
// Model newer-desktop manifest routes as data: this tree’s build forbids declarations without modules, so same-tree fixtures cannot represent that mixed-version state.
import { createElement } from 'react'
import { act, create } from 'react-test-renderer'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -42,17 +41,10 @@ vi.mock('./MobileWebShellScreen', () => ({
}
}))
import { BRIDGE_MAX_ROUTE_PARAMS, BRIDGE_ROUTE_PATHNAME_PATTERN } from './bridge/bridge-caps'
import { grantsForRoute, matchesRoutePattern, routeViewOf } from './page-route-policy'
import { BRIDGE_MAX_ROUTE_PARAMS } from './bridge/bridge-caps'
import { shellScreenRouteKey } from './shell-screen-route'
import MobileWebPageCatchAllScreen from './catch-all-page-route'
function servesRoute(routes: Parameters<typeof routeViewOf>[0], pathname: string): boolean {
return routeViewOf(routes, pathname).pageRoutes.some((pattern) =>
matchesRoutePattern(pathname, pattern)
)
}
async function render(): Promise<void> {
await act(async () => {
create(createElement(MobileWebPageCatchAllScreen))
@@ -66,25 +58,11 @@ beforeEach(() => {
})
describe('the catch-all switch', () => {
it('opens the shell on the pathname it was reached by', async () => {
await render()
expect(dependencies.routes).toEqual([{ pathname: '/h/host-1/settings' }])
})
it('rebuilds a multi-segment pathname the bridge rule accepts', async () => {
dependencies.params = { hostId: 'host-1', page: ['a', 'b', 'c'] }
await render()
const pathname = dependencies.routes[0]?.pathname ?? ''
expect(pathname).toBe('/h/host-1/a/b/c')
expect(BRIDGE_ROUTE_PATHNAME_PATTERN.test(pathname)).toBe(true)
})
it('re-encodes each segment expo-router handed back decoded', async () => {
dependencies.params = { hostId: 'host 1', page: ['a b', 'c?d'] }
await render()
const pathname = dependencies.routes[0]?.pathname ?? ''
expect(pathname).toBe('/h/host%201/a%20b/c%3Fd')
expect(BRIDGE_ROUTE_PATHNAME_PATTERN.test(pathname)).toBe(true)
})
it('takes the first value of a repeated host id, not the joined array', async () => {
@@ -112,7 +90,7 @@ describe('the catch-all switch', () => {
// Omit absent query params to preserve route identity and avoid a trailing question mark in page history.
dependencies.params = { hostId: 'host-1', page: ['settings'] }
await render()
expect(dependencies.routes[0]).not.toHaveProperty('params')
expect(dependencies.routes).toEqual([{ pathname: '/h/host-1/settings' }])
})
it('keeps a key the deep link gave no value, which is not the same as no key', async () => {
@@ -137,13 +115,6 @@ describe('the catch-all switch', () => {
expect(route && shellScreenRouteKey(route)).toBe('/h/host-1/files?q=a+b%26c%3Dd%2Fe')
})
it('drops the fragment expo-router parks under `#`, which is not a query', async () => {
// Expo seeds # from the fragment; it is not a query param to forward.
dependencies.params = { hostId: 'host-1', page: ['session', 'wt-1'], '#': 'files' }
await render()
expect(dependencies.routes[0]).not.toHaveProperty('params')
})
it('keeps the rest of the query when a fragment rides along with it', async () => {
dependencies.params = { hostId: 'host-1', page: ['session', 'wt-1'], '#': 'files', tab: 'diff' }
await render()
@@ -173,38 +144,3 @@ describe('the catch-all switch', () => {
}
})
})
const FUTURE_MANIFEST = [
{ pathname: '/h/[hostId]/insights', grants: ['navigate', 'storage', 'haptics'] },
{
pathname: '/h/[hostId]/insights/[worktreeId]',
grants: ['navigate', 'storage', 'externalLink', 'haptics']
},
{ pathname: '/h/[hostId]/future', grants: ['navigate', 'storage', 'haptics', 'native.nope'] }
]
describe('the gate a catch-all pathname meets', () => {
it('renders a manifest route this app has no route file for', () => {
expect(servesRoute(FUTURE_MANIFEST, '/h/H1/insights')).toBe(true)
expect(servesRoute(FUTURE_MANIFEST, '/h/H1/insights/W1')).toBe(true)
expect(grantsForRoute(FUTURE_MANIFEST, '/h/H1/insights/W1')).toEqual([
'navigate',
'storage',
'externalLink',
'haptics'
])
})
it('refuses a pathname the manifest does not list', () => {
expect(servesRoute(FUTURE_MANIFEST, '/h/H1/settings')).toBe(false)
expect(grantsForRoute(FUTURE_MANIFEST, '/h/H1/settings')).toEqual([])
})
it('refuses a listed route needing a grant this app does not implement', () => {
expect(servesRoute(FUTURE_MANIFEST, '/h/H1/future')).toBe(false)
expect(routeViewOf(FUTURE_MANIFEST, '/h/H1/future').pageRoutes).toEqual([
'/h/[hostId]/insights',
'/h/[hostId]/insights/[worktreeId]'
])
})
})
@@ -208,10 +208,13 @@ class WaylandScreenshotTest(unittest.TestCase):
return types.SimpleNamespace(returncode=0)
def test_ambiguous_missing_and_hidden_windows_never_capture_another_region(self):
for clients in ([], self.clients * 2, [{**self.clients[0], "hidden": True}],
[{**self.clients[0], "workspace": {"id": 3}}],
[{**self.clients[0], "size": [700, 480]}],
[{**self.clients[0], "pid": 43}], [{**self.clients[0], "size": [0, 480]}]):
for clients in (
[],
self.clients * 2,
[{**self.clients[0], "hidden": True}],
[{**self.clients[0], "workspace": {"id": 3}}],
[{**self.clients[0], "size": [700, 480]}],
):
with self.subTest(clients=clients):
self.clients = clients
self.commands.clear()
@@ -224,7 +227,6 @@ class WaylandScreenshotTest(unittest.TestCase):
"rect": {"x": 98, "y": 20, "width": 644, "height": 512},
"window_rect": {"x": 2, "y": 30, "width": 640, "height": 480}, "visible": True}]}]}
def sway(command, **options):
self.assertEqual(command, ["/usr/bin/swaymsg", "-t", "get_tree", "-r"])
options["stdout"].write(json.dumps(tree).encode())
return types.SimpleNamespace(returncode=0)
with patch.dict(runtime.os.environ, {"HYPRLAND_INSTANCE_SIGNATURE": "", "SWAYSOCK": "fixture"}), \
@@ -301,9 +303,13 @@ class KWinScreenshotTest(unittest.TestCase):
def test_windows_kwin_cannot_place_never_reach_the_portal(self):
cover = {**self.target, "pid": 7, "caption": "Other", "captionNormal": "Other", "stackingOrder": 4,
"frame": [450, 300, 200, 200]}
for windows in ([], [self.target, dict(self.target)], [{**self.target, "shown": False}],
[{**self.target, "pid": 43}], [{**self.target, "client": [100, 50, 500, 300]}],
[{**self.target, "screen": [0, 400, 640, 400]}], [self.target, cover]):
for windows in (
[self.target, dict(self.target)],
[{**self.target, "shown": False}],
[{**self.target, "client": [100, 50, 500, 300]}],
[{**self.target, "screen": [0, 400, 640, 400]}],
[self.target, cover],
):
with self.subTest(windows=windows):
self.portal_calls.clear()
result = self.capture(*windows)
@@ -377,7 +383,6 @@ class RuntimeRenderTest(unittest.TestCase):
self.assertEqual(focused.depth, 30)
def test_window_only_protection_preserves_completed_semantic_action(self):
button = FakeAccessible("button", "Continue")
effects = []
@@ -405,7 +410,6 @@ class RuntimeRenderTest(unittest.TestCase):
runtime.run_operation({"tool": "click", "app": "Fixture"})
self.assertEqual(effects, ["clicked"])
def test_pointer_input_waits_for_activation_and_uses_restored_geometry(self):
operations = (
{"tool": "click", "x": 5, "y": 6},
@@ -445,15 +449,12 @@ class RuntimeRenderTest(unittest.TestCase):
def test_restoration_requires_selected_window_focus_before_keyboard_input(self):
restore_window = runtime.restore_window
cases = (
{"name": "already active", "initial": 71, "expected": True, "native": False},
{"name": "delayed AT-SPI focus", "ack": False, "delay": 0.1, "expected": True, "native": False},
{"name": "ineffective true acknowledgment", "ack": True, "expected": True, "native": True},
{"name": "unmanaged helper", "ids": "70\n71\n", "managed": [71], "expected": True, "native": True},
{"name": "two accessible windows", "windows": 2},
{"name": "two native windows", "ids": "72\n71\n"},
{"name": "missing managed stack", "managed": None},
{"name": "failed managed window identity", "managed": [71, None]},
{"name": "invalid managed window identity", "managed": [71, 0]},
{"name": "Wayland", "session": "wayland"},
{"name": "search timeout", "timeout": "search"},
{"name": "activation timeout", "timeout": "windowactivate"},
@@ -461,7 +462,7 @@ class RuntimeRenderTest(unittest.TestCase):
)
for case in cases:
with self.subTest(case=case["name"]), SnapshotFixture(FakeAccessible("frame", "Editor")) as fixture:
active = [case.get("initial", 99)]
active = [99]
activations, keys = [], []
if case.get("windows") == 2:
fixture.app.children.append(FakeAccessible("frame", "Sibling"))
@@ -577,9 +578,7 @@ class RuntimeRenderTest(unittest.TestCase):
("type_text", True, "not-editable", 1, (6, 11)),
("paste_text", False, "not-editable", 1, (6, 11)),
("paste_text", True, "not-editable", 1, (6, 11)),
("type_text", False, "count-error", TimeoutError("selection timed out"), (6, 11)),
("type_text", False, "multiple", 2, (6, 11)),
("type_text", False, "range-error", 1, TimeoutError("range timed out")),
("type_text", False, "range-outside", 1, (6, 12)),
)
for tool, active, name, count, selection in cases:
@@ -588,11 +587,11 @@ class RuntimeRenderTest(unittest.TestCase):
states = [FakeStateType.FOCUSED] + ([] if name == "not-editable" else [FakeStateType.EDITABLE])
field.get_state_set = lambda: FakeStateSet(*states)
field.get_editable_text_iface = lambda: field
selected = types.SimpleNamespace(start_offset=selection[0], end_offset=selection[1]) if isinstance(selection, tuple) else selection
selected = types.SimpleNamespace(start_offset=selection[0], end_offset=selection[1])
with self.subTest(tool=tool, active=active, case=name), SnapshotFixture(
FakeAccessible("frame", "Editor", children=[field])
) as fixture, patch.object(runtime.Atspi.Text, "get_n_selections", return_value=count, side_effect=count if isinstance(count, Exception) else None), \
patch.object(runtime.Atspi.Text, "get_selection", return_value=selected, side_effect=selected if isinstance(selected, Exception) else None), \
) as fixture, patch.object(runtime.Atspi.Text, "get_n_selections", return_value=count), \
patch.object(runtime.Atspi.Text, "get_selection", return_value=selected), \
patch.object(runtime.Atspi.EditableText, "insert_text", wraps=FakeEditableText.insert_text) as insert, \
patch.object(runtime, "type_text") as keys, patch.object(runtime, "paste_text") as paste:
if active:
@@ -615,7 +614,11 @@ class RuntimeRenderTest(unittest.TestCase):
def test_partial_text_replacement_fails_without_typing_again(self):
tool = "type_text"
for failure in (False, True, TimeoutError("provider timed out"), "wrong-range"):
for failure in (
True,
TimeoutError("provider timed out"),
"wrong-range",
):
field = FakeAccessible("text", "Message", value="Hello world")
field.caret, field.selection = 11, (6, 11)
field.get_state_set = lambda: FakeStateSet(FakeStateType.FOCUSED, FakeStateType.EDITABLE)
@@ -688,19 +691,6 @@ class RuntimeRenderTest(unittest.TestCase):
keys.assert_not_called()
paste.assert_not_called()
def test_tree_marks_controls_without_enabled_or_sensitive_state_disabled(self):
disabled = FakeAccessible("push button", "Continue")
disabled.get_state_set = lambda: FakeStateSet(FakeStateType.SHOWING)
enabled = FakeAccessible("push button", "Cancel")
enabled.get_state_set = lambda: FakeStateSet(FakeStateType.ENABLED, FakeStateType.SENSITIVE)
unreadable = FakeAccessible("push button", "Help")
root = FakeAccessible("frame", "Form", children=[disabled, enabled, unreadable])
with SnapshotFixture(root):
lines = runtime.make_snapshot("Fixture", False)["treeLines"]
self.assertIn("\t1 push button (disabled) Continue", lines)
self.assertIn("\t2 push button Cancel", lines)
self.assertIn("\t3 push button Help", lines)
def test_compacted_browser_records_keep_their_own_frames_and_indexes(self):
tabs = [FakeAccessible("page tab", f"Tab {i}", value="1" if i == 9 else "") for i in range(10)]
buttons = [FakeAccessible("button", f"Other {i}") for i in range(10)]
@@ -713,43 +703,20 @@ class RuntimeRenderTest(unittest.TestCase):
by_name = {item["name"]: item for item in snapshot["elements"]}
for node, expected_x in ((tabs[-1], 110), (buttons[8], 200)):
self.assertEqual(by_name[node.name]["frame"]["x"], expected_x)
self.assertNotIn("Tab 0", by_name)
indexes = [item["index"] for item in snapshot["elements"]]
self.assertEqual(len(indexes), len(set(indexes)))
def test_cut_tree_marks_hidden_children_and_root_reads_them(self):
def test_root_reads_a_subtree_beyond_the_full_snapshot_limit(self):
items = [FakeAccessible("button", f"A{i}") for i in range(3)]
root = FakeAccessible("frame", "Main", children=[
FakeAccessible("list", "Items", children=items), FakeAccessible("button", "After"),
])
with SnapshotFixture(root), patch.object(runtime, "MAX_NODES", 4):
snapshot = runtime.make_snapshot("Fixture", False)
self.assertEqual(snapshot["treeLines"], [
"0 frame Main",
"\t1 list Items",
"\t\t2 button A0",
"\t\t3 button A1",
"\t\t... 1 more not shown (snapshot limit)",
"\t... 1 more not shown (snapshot limit)",
])
items_record = next(item for item in snapshot["elements"] if item["name"] == "Items")
subtree = runtime.run_operation({"tool": "get_app_state", "app": "Fixture", "noScreenshot": True, "root": items_record})["snapshot"]
self.assertEqual(subtree["treeLines"], ["0 list Items", "\t1 button A0", "\t2 button A1", "\t3 button A2"])
self.assertEqual(subtree["elements"][-1]["runtimeId"], [0, 0, 2])
if __name__ == "__main__":
unittest.main()
@@ -20,10 +20,8 @@ final class AttributeValueCoercionTests: XCTestCase {
func testIntegerScientificNotationIsParsedExactly() {
let cases: [(String, Int64)] = [
("1e3", 1_000),
("9.007199254740993e15", 9_007_199_254_740_993),
("10.0e-1", 1),
("+0.000E999999999999999999999", 0),
]
for (requested, expected) in cases {
@@ -52,7 +50,7 @@ final class AttributeValueCoercionTests: XCTestCase {
}
func testNonIntegralAndOutOfRangeIntegerFormsUseStringFallback() {
for requested in ["1e-1", "9223372036854775808", "-9223372036854775809", "1e999999999999999999999"] {
for requested in ["1e-1", "9223372036854775808", "1e999999999999999999999"] {
XCTAssertEqual(
AttributeValueCoercion(existingValue: NSNumber(value: 1), requested: requested).writeValue,
.string(requested)
@@ -12,7 +12,7 @@ final class BackgroundInputTransportTests: XCTestCase {
func testMouseEventsNameTheWindowAndCarryAWindowLocalLocation() throws {
try XCTSkipUnless(BackgroundInputTransport.isAvailable, "private symbols missing: \(BackgroundInputTransport.missingSymbols)")
let point = CGPoint(x: 340, y: 275)
for type in [CGEventType.leftMouseDown, .rightMouseUp, .otherMouseDown, .leftMouseDragged] {
for type in [CGEventType.leftMouseDown] {
let event = try BackgroundInputTransport.mouseEvent(type, target: target, at: point, button: .left, clickState: 2, flags: .maskCommand)
XCTAssertEqual(event.getIntegerValueField(CGEventField(rawValue: 51)!), 9001, "\(type)")
XCTAssertEqual(try windowLocation(of: event), CGPoint(x: 40, y: 75), "\(type)")
@@ -22,11 +22,9 @@ final class BackgroundInputTransportTests: XCTestCase {
}
}
func testTypedTextRidesTheKeyDownOnly() throws {
let bareKeyUp = try XCTUnwrap(CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false))
for (text, characters) in [("hé", ["h", "é"]), ("🚀e\u{301}👩‍💻", ["🚀", "e\u{301}", "👩‍💻"])] {
for (text, characters) in [("🚀e\u{301}👩‍💻", ["🚀", "e\u{301}", "👩‍💻"])] {
let events = try BackgroundInputTransport.textEvents(text)
XCTAssertEqual(events.map { $0.type }, characters.flatMap { _ in [CGEventType.keyDown, .keyUp] })
XCTAssertEqual(events.filter { $0.type == .keyDown }.map(unicodeString), characters)
@@ -18,7 +18,6 @@ final class ElementActionabilityTests: XCTestCase {
var nodes: [Int: Node]
var retriesLeft = 5
var onRetry: (FakeTree) -> Void = { _ in }
init(_ nodes: [Int: Node]) {
self.nodes = nodes
@@ -55,7 +54,6 @@ final class ElementActionabilityTests: XCTestCase {
func waitBeforeRetry() -> Bool {
guard retriesLeft > 0 else { return false }
retriesLeft -= 1
onRetry(self)
return true
}
}
@@ -80,27 +78,6 @@ final class ElementActionabilityTests: XCTestCase {
XCTAssertFalse(ElementActionability.waitUntilEnabled(3, ax: tree))
}
func testAnElementThatEnablesWithinTheWaitIsClicked() {
let tree = scrollingWindow(button: .init(role: "AXButton", parent: 2, frame: CGRect(x: 10, y: 10, width: 80, height: 20), enabled: false))
tree.onRetry = { $0.nodes[3]?.enabled = true }
XCTAssertTrue(ElementActionability.waitUntilEnabled(3, ax: tree))
}
func testAnElementBelowTheScrolledAreaIsScrolledIntoViewThenClicked() throws {
let tree = scrollingWindow(button: .init(
role: "AXButton",
parent: 2,
frame: CGRect(x: 10, y: 250, width: 80, height: 20),
scrollsTo: CGRect(x: 10, y: 150, width: 80, height: 20)
))
guard case let .ready(point) = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else {
return XCTFail("the button should be clickable once scrolled into view")
}
XCTAssertEqual(point, CGPoint(x: 50, y: 160))
}
func testAnElementThatCannotBeScrolledIntoViewIsRefused() throws {
let tree = scrollingWindow(button: .init(role: "AXButton", parent: 2, frame: CGRect(x: 10, y: 250, width: 80, height: 20)))
@@ -113,9 +113,7 @@ foreach ($case in @(
$inputCalls = @([OrcaDesktopWin32]::Calls | Where-Object { $_ -like "move:*" -or $_ -in @("mouse", "modified") })
if ($activates) {
Assert-TestEqual $denied $false "$($case.tool) successful activation"
Assert-TestEqual $result.ok $true "$($case.tool) result"
if ($inputCalls.Count -eq 0) { throw "$($case.tool) did not send pointer input after activation" }
if ([OrcaDesktopWin32]::FocusReads -lt 2) { throw "$($case.tool) did not wait for activation" }
Assert-TestEqual $inputCalls[0] "move:505,206" "$($case.tool) geometry after delayed activation"
Assert-TestEqual $result.action.delivery "foreground" "$($case.tool) pointer delivery"
} else {