mirror of
https://github.com/stablyai/orca.git
synced 2026-09-23 00:02:29 +00:00
* feat(mobile): put media picking behind a platform seam (OTA phase C, C7.6) The session screen picks images three ways — the photo library, Files, and the pasteboard — and all three are native modules a page cannot import: the codegen lookup `expo-image-picker` and `expo-document-picker` run at import throws in a browser, and the route manifest imports every route, so one of them in a page closure is the whole bundle down rather than one picker. `src/platform/media-picker.ts` is the phone's, delegating to the same three calls the screen already made. `.web.ts` is the page's: `native.media.pick`, then `read` in order to `eof`, then `release` for every handle it was handed, including the ones its caller never took — the shell holds eight staged files at a time and an abandoned pick otherwise waits out the five-minute TTL. A refusal rejects with the shell's code on it and is never folded into the empty answer that means the user cancelled. The bytes are concatenated decoded and encoded once, because the wire promises `eof` and nothing about the length: a shell answering a range shorter than the one asked for ends a chunk on a partial base64 group, and a reader joining the strings would fold that padding into the middle of the file. The census walks the session route module's own closure — the route is not registered until C7.7 — and names any module that reaches a picker or `Clipboard.getImageAsync` directly. Today that is the two modules C7.6's next commit moves, listed by name so the list goes empty rather than the rule going quiet. Inert: nothing calls the seam yet. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * feat(mobile): put the session's paste and attach on the media seam (OTA phase C, C7.6) The terminal paste read the pasteboard through `expo-clipboard` directly and the two attach paths called `pickMobileImage`/`pickMobileImages`, so the page's closure carried `expo-image-picker` and `expo-document-picker` — native modules whose import throws in a browser. All three now go through the seam. Text is `native.clipboard.read` on the page, which the clipboard seam gains a reader for: `expo-clipboard` resolves to `navigator.clipboard` there, which needs a secure context the iOS shell's custom scheme is not. An image is `pick { source: 'clipboard' }` rather than an inline value, because a clipboard image is 24 MiB of base64 against an 8 MiB reply ceiling. The census over the session closure is empty now and asserts the seam is in it, so a rule that found nothing is one that had something to find: with the three call sites restored it names all three. `mobile-image-source-picker.ts` stays the phone's implementation, reached only through the seam's native sibling, and resolves out of the web closure entirely. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * feat(mobile): resize a clipboard image on the page with a canvas (OTA phase C, C7.6) The paste hook carried the raster shrink inline over `expo-image-manipulator` and two `expo-file-system` writes. Both are native: the manipulator has no browser build, and the temp file exists only to work around an iOS loader that cannot decode a large base64 data URI, which a browser does not need. Split into `mobile-clipboard-image-resize.ts`, unchanged, and a `.web.ts` that decodes one `<img>` from the data URL the shell's `img-src 'self' data:` already admits, draws it into a canvas at the target size and reads the PNG back out of `toDataURL`. It reports the canvas's own size rather than the size asked for, because a browser clamps a canvas past its area limit and the downscale loop above would otherwise retry a raster that never shrank; and it awaits `decode()` rather than `onload`, which never fires for a source the browser cannot read and would leave the paste waiting on a promise nothing settles. Measured in Chromium under the shipped header, on a noise PNG because that is what PNG compresses least: 1400x1000 encodes to 5,476,032 base64 characters and converges in one pass to 368x263 and 397,220, which is 75.8% of the upload path's 512 KiB chunk. Zero policy violations and zero page errors. Red under three mutations: the source returned unchanged, a reported size the canvas did not draw, and `onload` in place of `decode()`. `computeMobileClipboardImageDownscale` moves to a leaf for the reason the upload-chunk constant has one: the check wants the arithmetic and not the upload path's RPC operations behind it. The page closure now carries none of `expo-image-picker`, `expo-document-picker`, `expo-image-manipulator` or `expo-file-system`, pinned beside the seam census. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * feat(mobile): give the two WebView editors their plain web fallbacks (OTA phase C, C7.6) `MobileRichMarkdownEditor` and `MobileHtmlPreview` are the session closure's other two `react-native-webview` consumers. On the web that package renders the line "React Native WebView does not support this platform" where the surface was, so nothing it was mounted for works and the closure pays for a module that cannot do its job. Ruling 8: each gets the plain state it already degrades to, and no second renderer. The editor renders the Markdown source in one field on the text-input seam, so the screen around it keeps the text, every edit through `onChange`, and Save, Discard, Copy and Refresh; the degradation is the formatting toolbar, whose fifteen commands are the rich document's. The preview renders its own Source tab; the degradation is the rendered artifact, and the toggle goes with it, because a control that can only be in one position is a control that lies. Neither is smaller than a DOM renderer, which is why neither is one here. The editor's toolbar would need a `contenteditable` implementation with its own escaping, and the preview has no nested frame to sandbox agent-produced HTML in at all — the shell's policy carries `frame-src 'none'` and `child-src 'none'`. `dismissKeyboard` blurs the field rather than calling `Keyboard.dismiss`, which is a stub on React Native Web; `onKeyboardInsetChange` is never called, because it exists to correct for a WebView's covered area and on the page `keyboard-occlusion.web.ts` is the only measurement there is. The closure census names the one consumer left, `TerminalWebView.tsx`, which is C7.5's: with both siblings removed it names all three. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): read a destructured clipboard alias in the media census (OTA phase C, C7.6) The census recognised `Clipboard.getImageAsync` as a property access and nothing else, so `const { getImageAsync } = Clipboard` reached the same function without ever writing one and the closure was approved. On the page that call is `navigator.clipboard`, which needs a secure context the iOS shell's custom scheme is not, so the approval was for a path that dies at the browser clipboard API. Aliases are now resolved to a fixpoint — `const pasteboard = Clipboard` makes `pasteboard` the module too, and the chain has no length limit — and a destructuring off any of them is reported at its declaration, which is the line to delete. The destructured name is read the way the import clause's is, off `propertyName` when the element renames it, so `{ getImageAsync: readImage }` is the same offence spelled differently. A binding element's `name` can be a nested pattern and a `propertyName` can be computed, so the text is taken only off a node that has one. Red-first with each shape planted in the scratch tree before the rule moved: the plain destructuring, the renamed one and the re-destructured chain were all missed. Dropping the fixpoint afterwards loses the chain; reading the local name instead of the property loses the rename. `{ getStringAsync } = Clipboard` stays unreported, because text off the pasteboard is the clipboard seam's and not this rule's. The session closure is still empty under the widened rule. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): release every item a clipboard pick answered (OTA phase C, C7.6) `readClipboardImage` destructured the first staged item and released only that one, while `pickImage` already guards the same shape through `readPicked`. `multiple: false` is what the page asks for and not what a shell promises, so a caller taking the first of several would hold the rest against the eight-handle cap until the five-minute TTL. Today's shell stages at most one on the clipboard arm, so this is the seam's own docstring made true rather than a leak in the field. Red-first with two staged clipboard items: releasing only the one read leaves `media-2` held, and the second is now returned without ever being read, which is what the single-image pick does. The refusal case is one path over both codes a pick can answer with: the registry's `native_media_handle_cap`, raised before a picker runs, and ruling 6c's `native_media_too_large`, raised once a picked item has been weighed. A code outside the seam's vocabulary floors to `native_verb_failed` rather than crossing verbatim, which is what makes naming the exact code load-bearing. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * test(mobile): read the upload chunk from its module in the resize check (OTA phase C, C7.6) The canvas resize check restated `512 * 1024` as the budget it holds a run to. A check carrying its own copy of a product constant is one that goes on passing after the upload path's chunk has moved, which is the reason the harness reads the CSP, the protocol version and the window caps out of their own sources. `readClipboardImageUploadChunkBase64Chars` joins them, evaluating the product the way the window caps reader does. Proved live by moving the constant: at 64 MiB the run reds on the fixture no longer being over the budget, and it is back to 512 KiB here. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): read element access in the media census and correct two claims (OTA phase C, C7.6) Round 2, four lows. The census read `Clipboard.getImageAsync` and not `Clipboard['getImageAsync']`, which is the same call, the spelling a bundler produces, and the one a reader reaches for to get around a rule about dots. Element access with a string literal is now read the same way; a computed key is not, because its value is not in the source and guessing would report a line nobody can act on. The closure test cannot back this up — `expo-clipboard` legitimately sits in the session closure — so the scratch fixture is the whole of the evidence, and it reds with the arm removed. The fixture also could not tell the alias fixpoint from one source-order pass: every planted chain happened to be declared in the order a single walk learns it. `reverse-order-alias.ts` is declared back to front, and is valid at run time because the destructure sits inside a function the module body finishes before anything calls. Bounding the loop to one pass now reds it. The canvas resize justified reading its size back off the element by a browser clamping past its area limit. That is not what browsers do: the width attribute reflects whatever it was assigned, so the returned size is always the target. The real reason is narrower and is now what the comment and the override entry say — the dimensions and the bytes come from one element, so a caller's bookkeeping cannot describe a raster that was not encoded. The override entry also carried a stray apostrophe in `img-src 'self' data:`. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): say what the clipboard contract shipped as, and read a backticked key (OTA phase C, C7.6) Round 3, three lows. The merge took main's `clipboard.ts` byte for byte, so its reader docstring still described the state C7.2 shipped: one verb on the web, and a page whose lack of an image verb degraded into the old path. The design that shipped is the other one — this seam owns the pasteboard on both platforms and the page's `readImage` runs `native.media.pick { source: 'clipboard' }` with the chunked read behind it. The prose now says that, and says that null still means an empty pasteboard while every other outcome rejects. The same merge left `clipboard` twice in the paste hook's dependency list, one from each side. Deduped. The census read a quoted element-access key and not a backticked one, so ``Clipboard[`getImageAsync`]`` escaped a rule that catches both other spellings. A template with no substitution is a string literal with a different quote, and reading only one of the two leaves the other as the way around. The computed-key plant could not see the literal-kind check at all: its variable was named `key`, so reading the identifier's text found nothing either way. It is now named after the method and holds a different one, which makes dropping the kind check a false positive on a call that reads text. Red-first: the backticked access planted before the rule moved is missed; ignoring template keys afterwards misses it again; accepting any key node reports the computed plant. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): hold canPickMedia to all three verbs and seed the census from import() (OTA phase C, C7.6) Two bot findings. `canPickMedia` answered true on `native.media.pick` and `native.media.read` alone, but every image read releases what it picked. On a route without `native.media.release` the release rejects, the cleanup swallows it by design, and the staged file stays live to the five-minute TTL: eight pastes and the next pick is refused at the handle cap, with nothing on screen to say why. A route missing one verb has no working image path, so `contents()` now says so up front rather than after four of them. Red-first: a route granted pick and read but not release answered `image: true`. The census seeded its aliases from static import and export declarations only, so `const Clipboard = await import('expo-clipboard')` produced no offender — while the bundler resolves a literal dynamic import into the closure exactly as a static one. A dynamic import is now read wherever it appears: `await` and parentheses unwrapped, the assigned identifier seeded as an alias, a destructuring off one reported at its declaration, and a picker module reported at the call, since reaching one at all is the offence. A specifier that is not a literal is left alone, for the reason a computed key is. Red-first with all three forms planted and the seeding removed: the namespace alias, the destructuring and the picker import are each missed. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb * fix(mobile): seed the media census from a backticked import() too (OTA phase C, C7.6 bots) CodeRabbit: `import(`expo-image-picker`)` is as static to the bundler as the quoted form, but the census read only a string literal specifier, so a backticked one joined the closure unseen. A no-substitution template literal now seeds it the same way; the planted fixture is reported at its line and was unreported before the arm. pullfrog: the clipboard seam's docstring counted the web read as two verbs where its web sibling counts one for text and three for an image. It now counts the same way in both files. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
387 lines
15 KiB
JavaScript
387 lines
15 KiB
JavaScript
import { createServer } from 'node:http'
|
|
import { readFile } from 'node:fs/promises'
|
|
import { join } from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
|
|
export const projectDir = fileURLToPath(new URL('../..', import.meta.url))
|
|
|
|
/**
|
|
* Both CSP constants are a list of quoted directives with `//` comments between them, and those
|
|
* comments quote directive text. Dropping comment lines first is what keeps a comment out of the
|
|
* header a test serves.
|
|
*/
|
|
export function parseCspDirectives(source, startMarker, endMarker) {
|
|
const start = source.indexOf(startMarker)
|
|
const end = source.indexOf(endMarker)
|
|
if (start === -1 || end < start) {
|
|
throw new Error(`could not find ${startMarker} .. ${endMarker}`)
|
|
}
|
|
const body = source
|
|
.slice(start, end)
|
|
.split('\n')
|
|
.filter((line) => !line.trimStart().startsWith('//'))
|
|
.join('\n')
|
|
const directives = [...body.matchAll(/"([^"]+)"/g)].map((match) => match[1])
|
|
if (directives.length < 10) {
|
|
throw new Error('could not parse the shell CSP')
|
|
}
|
|
return directives.join('; ')
|
|
}
|
|
|
|
/**
|
|
* The shipped policy, read from the Kotlin source so a test cannot drift from what the shell
|
|
* actually sends. Parsed rather than imported: the constant lives in a JVM module.
|
|
*/
|
|
export async function readShellCsp() {
|
|
const source = await readFile(
|
|
join(
|
|
projectDir,
|
|
'mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellCsp.kt'
|
|
),
|
|
'utf8'
|
|
)
|
|
return parseCspDirectives(source, 'listOf(', ').joinToString')
|
|
}
|
|
|
|
/**
|
|
* The envelope version the page speaks, read from the contract rather than written down twice. A
|
|
* bumped `v` would otherwise reach a test as a 30s timeout naming nothing.
|
|
*/
|
|
export async function readBridgeProtocolVersion() {
|
|
const source = await readFile(
|
|
join(projectDir, 'mobile/src/mobile-web-shell/bridge/bridge-envelope.ts'),
|
|
'utf8'
|
|
)
|
|
const match = /BRIDGE_PROTOCOL_VERSION = (\d+)/.exec(source)
|
|
if (!match) {
|
|
throw new Error('could not read BRIDGE_PROTOCOL_VERSION')
|
|
}
|
|
return Number(match[1])
|
|
}
|
|
|
|
/**
|
|
* The bridge's window caps, read from the modules that define them.
|
|
*
|
|
* The shell double below has to price a frame the way `BridgeHostSubscriptions` does, and a double
|
|
* carrying its own copy of these numbers is a double that goes on passing after the real host's
|
|
* changed. `BRIDGE_MAX_UNACKED_BYTES` is written as a product, so the reader evaluates one.
|
|
*/
|
|
export async function readBridgeWindowCaps() {
|
|
const sources = await Promise.all(
|
|
[
|
|
'mobile/src/mobile-web-shell/bridge/bridge-caps.ts',
|
|
'mobile/src/mobile-web-shell/bridge-host-subscriptions.ts'
|
|
].map((path) => readFile(join(projectDir, path), 'utf8'))
|
|
)
|
|
const source = sources.join('\n')
|
|
const read = (name) => {
|
|
const match = new RegExp(`${name} = ([0-9*\\s]+)`).exec(source)
|
|
if (!match) {
|
|
throw new Error(`could not read ${name}`)
|
|
}
|
|
return match[1]
|
|
.split('*')
|
|
.map((part) => Number(part.trim()))
|
|
.reduce((product, factor) => product * factor, 1)
|
|
}
|
|
return {
|
|
maxMessageBytes: read('BRIDGE_MAX_MESSAGE_BYTES'),
|
|
maxUnackedFrames: read('BRIDGE_MAX_UNACKED_FRAMES'),
|
|
maxUnackedBytes: read('BRIDGE_MAX_UNACKED_BYTES')
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The base64 one append of the clipboard-image upload carries, read from the leaf that defines it.
|
|
*
|
|
* The page's canvas resize is measured against this, so a check carrying its own copy is one that
|
|
* goes on passing after the upload path's chunk has moved. Written as a product, so the reader
|
|
* evaluates one the way the window caps above do.
|
|
*/
|
|
export async function readClipboardImageUploadChunkBase64Chars() {
|
|
const source = await readFile(
|
|
join(projectDir, 'mobile/src/session/mobile-clipboard-image-upload-chunk.ts'),
|
|
'utf8'
|
|
)
|
|
const match = /MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS = ([0-9*\s]+)/.exec(source)
|
|
if (!match) {
|
|
throw new Error('could not read MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS')
|
|
}
|
|
return match[1]
|
|
.split('*')
|
|
.map((part) => Number(part.trim()))
|
|
.reduce((product, factor) => product * factor, 1)
|
|
}
|
|
|
|
/**
|
|
* The JPEG quality the pane asks Chromium for, read from the module that sends it. A test that
|
|
* encoded its fixtures at a retyped quality would certify the budget at a number nothing ships.
|
|
*/
|
|
export async function readBrowserFrameQuality() {
|
|
const source = await readFile(
|
|
join(projectDir, 'mobile/src/browser/browser-screencast-request-parameters.ts'),
|
|
'utf8'
|
|
)
|
|
const match = /BROWSER_FRAME_QUALITY = (\d+)/.exec(source)
|
|
if (!match) {
|
|
throw new Error('could not read BROWSER_FRAME_QUALITY')
|
|
}
|
|
return Number(match[1]) / 100
|
|
}
|
|
|
|
/** The grant the shell offers every page, read from the same source for the same reason. */
|
|
export async function readBridgeFaultGrant() {
|
|
const source = await readFile(
|
|
join(projectDir, 'mobile/src/mobile-web-shell/bridge/bridge-envelope.ts'),
|
|
'utf8'
|
|
)
|
|
const match = /BRIDGE_FAULT_GRANT = '([a-zA-Z]+)'/.exec(source)
|
|
if (!match) {
|
|
throw new Error('could not read BRIDGE_FAULT_GRANT')
|
|
}
|
|
return match[1]
|
|
}
|
|
|
|
/**
|
|
* The shell's half of the bridge, as the page's channel sees it.
|
|
*
|
|
* The entry mounts nothing until `init` lands, so a render check with no shell renders no route at
|
|
* all. This answers `ready`, answers the methods `replies` names, and refuses everything else: a
|
|
* real reply would make this file the place domain behaviour is decided, and every screen below
|
|
* already has a state for an RPC that failed. `grants` and `pageRoutes` are what the shell would
|
|
* have negotiated, and every notify the page posts is kept whole in `__orcaRenderCheckNotifies`,
|
|
* because a control that handed something to the shell and one that did nothing look the same on
|
|
* the document.
|
|
*
|
|
* It answers RPC the way a refusing host does and serves a screencast stream the way the real
|
|
* `BridgeHostSubscriptions` does, including its whole `canCarry` rule and the page's acks. It is
|
|
* not the host: it decides no domain behaviour, and every reply a screen sees is one a check
|
|
* named.
|
|
*
|
|
* Serialized as a page init script, so it takes plain data and closes over nothing.
|
|
*/
|
|
export function installShellDouble({
|
|
version,
|
|
sessionId,
|
|
buildId,
|
|
route,
|
|
host,
|
|
storage,
|
|
faultGrant,
|
|
grants,
|
|
pageRoutes = null,
|
|
replies,
|
|
streams = [],
|
|
windowCaps = null
|
|
}) {
|
|
// Where the page's own fault reports land. Read back after the render, so a route that threw
|
|
// under the boundary names itself instead of timing out as a page that never mounted.
|
|
globalThis.__orcaRenderCheckFaults = []
|
|
// Every grant-gated notify the page posted, whole and in order. A control that decided to hand
|
|
// something to the shell and a control that did nothing look identical on the document; this is
|
|
// the only thing that tells them apart.
|
|
globalThis.__orcaRenderCheckNotifies = []
|
|
// Every request the page issued, whole and in order, so a check can say which verb a gesture
|
|
// produced and with what geometry rather than only that something was sent.
|
|
globalThis.__orcaRenderCheckRequests = []
|
|
// The subscriptions the double accepted, with the `wantsBinary` each one asked for: the negative
|
|
// case is "the page did not ask", which no assertion on the frames can see.
|
|
globalThis.__orcaRenderCheckSubscribes = []
|
|
// Binary events this double refused to post because they exceeded the frame cap, which is the
|
|
// shell's drop rule reproduced where the page can watch it survive one.
|
|
globalThis.__orcaRenderCheckDroppedFrames = []
|
|
// Every ack seq the page posted, in order. Without this a stream that never acked and one that
|
|
// acked every frame look the same from the page's side.
|
|
globalThis.__orcaRenderCheckAcks = []
|
|
const openStreams = new Map()
|
|
const channel = {
|
|
postMessage: (json) => {
|
|
const frame = JSON.parse(json)
|
|
const answer = (message) => {
|
|
// A microtask, not a task: the page posts `ready` while its script is still running, and
|
|
// this keeps the answer behind it without moving a timer the page's backoff reads.
|
|
queueMicrotask(() => {
|
|
channel.onmessage?.({ data: JSON.stringify(message) })
|
|
})
|
|
}
|
|
if (frame.type === 'ready') {
|
|
answer({
|
|
v: version,
|
|
type: 'init',
|
|
sessionId,
|
|
buildId,
|
|
connection: {
|
|
state: 'connected',
|
|
reconnectAttempt: 0,
|
|
lastConnectedAt: 1,
|
|
lastInboundAt: 1,
|
|
generation: 0
|
|
},
|
|
grants: {
|
|
rpc: { maxPendingRequests: 64, maxSubscriptions: 32 },
|
|
// The fault grant alone unless the caller named a set: every check needs that one,
|
|
// and a check that names none must not be handed an undefined list.
|
|
native: grants ?? [faultGrant]
|
|
},
|
|
...(pageRoutes === null ? {} : { pageRoutes }),
|
|
// Omitted for a shell too old to name one, which is the case the page has a panel for.
|
|
...(route === null ? {} : { route }),
|
|
...(host === null ? {} : { host }),
|
|
storage
|
|
})
|
|
return
|
|
}
|
|
if (frame.type === 'notify') {
|
|
globalThis.__orcaRenderCheckNotifies.push(frame)
|
|
if (frame.name === faultGrant) {
|
|
globalThis.__orcaRenderCheckFaults.push(frame.error.message)
|
|
}
|
|
return
|
|
}
|
|
// The result the caller named for this method, carried in the envelope a real host uses.
|
|
// Anything unnamed still takes the refusal below, so a screen only ever sees data a test
|
|
// asked for.
|
|
if (frame.type === 'subscribe' && streams.includes(frame.method)) {
|
|
globalThis.__orcaRenderCheckSubscribes.push({
|
|
id: frame.id,
|
|
method: frame.method,
|
|
params: frame.params,
|
|
wantsBinary: frame.wantsBinary === true
|
|
})
|
|
// Accepted by saying nothing, exactly as the real host does: a subscription is open until
|
|
// an `error` or an `end` closes it, and the first thing the page hears is an event.
|
|
openStreams.set(frame.id, { seq: 0, unacked: [], unackedBytes: 0 })
|
|
return
|
|
}
|
|
if (frame.type === 'ack') {
|
|
// The page's ack is what reopens the window, so a double that ignored it would drop
|
|
// frames the real host carries. Read exactly as `BridgeHostSubscriptions.ack` reads it.
|
|
const stream = openStreams.get(frame.id)
|
|
if (stream) {
|
|
let acked = 0
|
|
for (const pending of stream.unacked) {
|
|
if (pending.seq > frame.seq) {
|
|
break
|
|
}
|
|
stream.unackedBytes -= pending.bytes
|
|
acked += 1
|
|
}
|
|
stream.unacked.splice(0, acked)
|
|
globalThis.__orcaRenderCheckAcks.push(frame.seq)
|
|
}
|
|
return
|
|
}
|
|
if (frame.type === 'cancel') {
|
|
openStreams.delete(frame.id)
|
|
return
|
|
}
|
|
if (frame.type === 'request') {
|
|
globalThis.__orcaRenderCheckRequests.push({ method: frame.method, params: frame.params })
|
|
}
|
|
if (frame.type === 'request' && replies && Object.hasOwn(replies, frame.method)) {
|
|
answer({
|
|
v: version,
|
|
type: 'reply',
|
|
id: frame.id,
|
|
payload: { id: frame.id, ok: true, result: replies[frame.method] }
|
|
})
|
|
return
|
|
}
|
|
if (frame.type === 'request' || frame.type === 'subscribe') {
|
|
answer({
|
|
v: version,
|
|
type: 'error',
|
|
id: frame.id,
|
|
error: {
|
|
category: 'RenderCheckShellDouble',
|
|
message: 'the render check answers no RPC',
|
|
isRpcDeliveryUnknown: false
|
|
}
|
|
})
|
|
}
|
|
},
|
|
onmessage: null
|
|
}
|
|
/**
|
|
* One screencast frame from the shell, priced the way `BridgeHostSubscriptions` prices it.
|
|
*
|
|
* All three arms of the host's `canCarry`, not just the size one: a frame over the message cap,
|
|
* a window already holding the most frames it may, and a window whose bytes this frame would
|
|
* push past the limit. Dropping is the behaviour under test — the event goes nowhere, the
|
|
* stream stays open, and the next frame paints — so a double that posted an uncarriable frame
|
|
* would prove the page decodes something no shell could have sent.
|
|
*
|
|
* The window only stays open because the page acks, which the `ack` arm above consumes. That is
|
|
* what makes a long stream a real test of both rather than of neither.
|
|
*/
|
|
globalThis.__orcaRenderCheckEmitBinary = (id, binary) => {
|
|
const stream = openStreams.get(id)
|
|
if (!stream) {
|
|
return 'no-stream'
|
|
}
|
|
const seq = stream.seq + 1
|
|
const json = JSON.stringify({ v: version, type: 'event', id, seq, binary })
|
|
const bytes = new TextEncoder().encode(json).length
|
|
const carries =
|
|
windowCaps === null ||
|
|
(bytes <= windowCaps.maxMessageBytes &&
|
|
stream.unacked.length < windowCaps.maxUnackedFrames &&
|
|
stream.unackedBytes + bytes <= windowCaps.maxUnackedBytes)
|
|
if (!carries) {
|
|
globalThis.__orcaRenderCheckDroppedFrames.push(binary.frameSeq)
|
|
return 'dropped'
|
|
}
|
|
stream.seq = seq
|
|
stream.unacked.push({ seq, bytes })
|
|
stream.unackedBytes += bytes
|
|
channel.onmessage?.({ data: json })
|
|
return 'posted'
|
|
}
|
|
globalThis.orcaBridge = channel
|
|
}
|
|
|
|
/**
|
|
* The page server the render checks run against: the built bundle, under the shell's own policy.
|
|
*
|
|
* `transformChunk` is how a check poisons one route chunk without building a second bundle.
|
|
*/
|
|
export async function createBundleServer({ outDir, cspHeader, transformChunk }) {
|
|
const server = createServer((request, response) => {
|
|
const path = new URL(request.url, 'http://localhost').pathname
|
|
// A browser asks for this on its own and the shell's WebView never does. The bundle carries
|
|
// no icon, so a 404 would put a console error in every check that runs against a full Chrome
|
|
// -- which is what CI resolves -- and none against the bundled headless shell.
|
|
if (path === '/favicon.ico') {
|
|
response.writeHead(204)
|
|
response.end()
|
|
return
|
|
}
|
|
// A route path serves the entrypoint and the page routes client-side. A path naming a file
|
|
// has to come out of the bundle or 404, the same as the shell's manifest map: answering it
|
|
// with the document instead would hide a publicPath the script cannot fetch from.
|
|
const namesAFile = path.slice(path.lastIndexOf('/')).includes('.')
|
|
const file = namesAFile ? path.slice(1) : 'index.html'
|
|
readFile(join(outDir, file)).then(
|
|
(real) => {
|
|
const bytes = transformChunk ? transformChunk(path, real) : real
|
|
const headers = {
|
|
'content-type': file.endsWith('.js') ? 'text/javascript' : 'text/html'
|
|
}
|
|
// The document carries the shell's real policy, so a directive the page violates fails
|
|
// here rather than on a phone. Assets carry none, exactly as the native handler does.
|
|
if (file === 'index.html' && cspHeader) {
|
|
headers['content-security-policy'] = cspHeader
|
|
}
|
|
response.writeHead(200, headers)
|
|
response.end(bytes)
|
|
},
|
|
() => {
|
|
response.writeHead(404)
|
|
response.end()
|
|
}
|
|
)
|
|
})
|
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
|
return { server, origin: `http://127.0.0.1:${String(server.address().port)}` }
|
|
}
|