diff --git a/pkgs/id/contract/shell-contract.v1.json b/pkgs/id/contract/shell-contract.v1.json index 693df42f3e..c285bb27ee 100644 --- a/pkgs/id/contract/shell-contract.v1.json +++ b/pkgs/id/contract/shell-contract.v1.json @@ -46,6 +46,7 @@ "after": "u64?", "screen_patches": { "type": "bool", "optional": true, "nullable": false }, "screen_msgpack": { "type": "bool", "optional": true, "nullable": false }, + "device_input": { "type": "object", "optional": true, "nullable": false }, "agent_profile": { "type": "bool", "optional": true, "nullable": false }, "resume_token": { "type": "string", "optional": true, "nullable": true, "max_bytes": 64 } } diff --git a/pkgs/id/crates/id-core/src/screen_codec.rs b/pkgs/id/crates/id-core/src/screen_codec.rs index 50b471e491..45f68b06ba 100644 --- a/pkgs/id/crates/id-core/src/screen_codec.rs +++ b/pkgs/id/crates/id-core/src/screen_codec.rs @@ -141,6 +141,7 @@ pub fn decode_view_patch(bytes: &[u8]) -> Result c.charCodeAt(0)); + +describe("decodeViewPatch", () => { + it("decodes the Rust golden view-patch frame", () => { + expect(decodeViewPatch(GOLDEN_VIEW_PATCH)).toEqual({ + sequence: 7, + view_revision: 3, + base_view_revision: 2, + resume_token: null, + patch: { version: 1, width: 2, height: 1, runs: [] }, + }); + }); + + it("decodes a populated patch: runs, cells, style tokens, wide glyphs", () => { + expect(decodeViewPatch(POPULATED_VIEW_PATCH)).toEqual({ + sequence: 7, + view_revision: 3, + base_view_revision: 2, + resume_token: null, + patch: { + version: 1, + width: 2, + height: 1, + runs: [ + { + start: 0, + cells: [ + { symbol: "A", fg: 1, bg: 2, bold: true, columns: 1, token: "warning" }, + { symbol: "水", fg: 0, bg: 0, bold: false, columns: 2, token: null }, + ], + }, + ], + }, + }); + }); + + it("rejects an unsupported codec version", () => { + const bytes = new Uint8Array(GOLDEN_VIEW_PATCH); + bytes[9] = 2; // the version value, as in the Rust rejection test + expect(decodeViewPatch(bytes)).toBeNull(); + }); + + it("rejects trailing bytes after the one frame value", () => { + const bytes = new Uint8Array(GOLDEN_VIEW_PATCH.length + 1); + bytes.set(GOLDEN_VIEW_PATCH); + bytes[GOLDEN_VIEW_PATCH.length] = 0xc0; + expect(decodeViewPatch(bytes)).toBeNull(); + }); + + it("rejects truncated and non-MessagePack input", () => { + expect(decodeViewPatch(GOLDEN_VIEW_PATCH.slice(0, 40))).toBeNull(); + expect(decodeViewPatch(new Uint8Array([0xc1]))).toBeNull(); + expect(decodeViewPatch(new Uint8Array(0))).toBeNull(); + }); + + it("rejects the patch-only envelope (no frame fields)", () => { + // The #12241 {version, patch} value is a different frame kind; + // offered as a view patch it must fail safely, not decode. + const patchOnly = Uint8Array.from( + atob( + "gqd2ZXJzaW9uAaVwYXRjaISndmVyc2lvbgGld2lkdGgCpmhlaWdodAGkcnVuc5GCpXN0YXJ0AKVjZWxsc5KGpnN5bWJvbKFBomZnAaJiZwKkYm9sZMOnY29sdW1ucwGldG9rZW6nd2FybmluZ4Wmc3ltYm9so+awtKJmZwCiYmcApGJvbGTCp2NvbHVtbnMC", + ), + (c) => c.charCodeAt(0), + ); + expect(decodeViewPatch(patchOnly)).toBeNull(); + }); +}); diff --git a/pkgs/id/web/src/screen-codec.ts b/pkgs/id/web/src/screen-codec.ts new file mode 100644 index 0000000000..69fa3af3ed --- /dev/null +++ b/pkgs/id/web/src/screen-codec.ts @@ -0,0 +1,135 @@ +import { Unpackr } from "msgpackr"; +import type { ScreenPatch } from "./world-surface"; + +/** + * Browser decoder for the negotiated binary screen transport + * (F12.11 phase 3, #12242; Rust half in #12655): after a join that + * offers `screen_msgpack`, the host may send a screen patch as one + * binary WebSocket message — a versioned MessagePack value + * `{version, frame}` whose frame mirrors the JSON `view` frame's + * patch fields. The wire format is owned by the Rust codec + * (`id_core::screen_codec::encode_view_patch`, codec version 1); + * this decoder is deliberately as strict as the Rust one + * (deny-unknown-fields, one exact value, bounded size): anything + * else returns null and the caller falls back to a full view. + */ + +export interface ViewPatchFrame { + sequence: number; + view_revision: number; + base_view_revision: number | null; + resume_token: string | null; + patch: ScreenPatch; +} + +const SCREEN_CODEC_VERSION = 1; +/** The shared session frame limit, matching the Rust codec. */ +const MAX_SCREEN_FRAME_BYTES = 1024 * 1024; +/** StyleToken's serialized names (id-core world_presentation). */ +const STYLE_TOKENS = new Set(["emphasis", "muted", "heading", "code", "warning", "success", "link"]); + +const unpackr = new Unpackr({ useRecords: false, structuredClone: true }); + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function hasExactlyKeys(value: Record, keys: string[]): boolean { + const actual = Object.keys(value); + return actual.length === keys.length && keys.every((key) => key in value); +} + +function isUint(value: unknown, max: number): value is number { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= max; +} + +function isUintOrNull(value: unknown, max: number): value is number | null { + return value === null || isUint(value, max); +} + +function decodeCell(value: unknown): ScreenPatch["runs"][number]["cells"][number] | null { + // The Rust encoder omits `token` when it is None + // (skip_serializing_if), so a cell carries five or six keys. + if (!isRecord(value)) return null; + const keys = Object.keys(value); + const allowed = ["symbol", "fg", "bg", "bold", "columns", "token"]; + if (!allowed.slice(0, 5).every((key) => key in value)) return null; + if (!keys.every((key) => allowed.includes(key))) return null; + if (typeof value.symbol !== "string") return null; + if (!isUint(value.fg, 0xff) || !isUint(value.bg, 0xff) || !isUint(value.columns, 0xff)) return null; + if (typeof value.bold !== "boolean") return null; + const token = "token" in value ? value.token : null; + if (token !== null && (typeof token !== "string" || !STYLE_TOKENS.has(token))) { + return null; + } + return { + symbol: value.symbol, + fg: value.fg, + bg: value.bg, + bold: value.bold, + columns: value.columns, + token, + }; +} + +function decodePatch(value: unknown): ScreenPatch | null { + if (!isRecord(value) || !hasExactlyKeys(value, ["version", "width", "height", "runs"])) { + return null; + } + if (!isUint(value.version, 0xff) || !isUint(value.width, 0xffff) || !isUint(value.height, 0xffff)) { + return null; + } + if (!Array.isArray(value.runs)) return null; + const runs: ScreenPatch["runs"] = []; + for (const runValue of value.runs) { + if (!isRecord(runValue) || !hasExactlyKeys(runValue, ["start", "cells"])) return null; + if (!isUint(runValue.start, 0xffffffff) || !Array.isArray(runValue.cells)) return null; + const cells: ScreenPatch["runs"][number]["cells"] = []; + for (const cellValue of runValue.cells) { + const cell = decodeCell(cellValue); + if (!cell) return null; + cells.push(cell); + } + runs.push({ start: runValue.start, cells }); + } + return { version: value.version, width: value.width, height: value.height, runs }; +} + +/** + * Decode one binary view-patch frame. Returns null for anything + * that is not exactly one well-formed, supported-version frame — + * the caller treats null as "ask for a full view", never as data. + */ +export function decodeViewPatch(bytes: Uint8Array): ViewPatchFrame | null { + if (bytes.length === 0 || bytes.length > MAX_SCREEN_FRAME_BYTES) return null; + let values: unknown[]; + try { + values = unpackr.unpackMultiple(bytes); + } catch { + return null; + } + if (values.length !== 1) return null; + const envelope = values[0]; + if (!isRecord(envelope) || !hasExactlyKeys(envelope, ["version", "frame"])) return null; + if (envelope.version !== SCREEN_CODEC_VERSION) return null; + const frame = envelope.frame; + if ( + !isRecord(frame) || + !hasExactlyKeys(frame, ["sequence", "view_revision", "base_view_revision", "resume_token", "patch"]) + ) { + return null; + } + if (!isUint(frame.sequence, Number.MAX_SAFE_INTEGER)) return null; + if (!isUint(frame.view_revision, Number.MAX_SAFE_INTEGER)) return null; + if (!isUintOrNull(frame.base_view_revision, Number.MAX_SAFE_INTEGER)) return null; + if (frame.resume_token !== null && typeof frame.resume_token !== "string") return null; + const patch = decodePatch(frame.patch); + if (!patch) return null; + return { + sequence: frame.sequence, + view_revision: frame.view_revision, + base_view_revision: frame.base_view_revision, + resume_token: frame.resume_token, + patch, + }; +} diff --git a/pkgs/id/web/src/world-program.test.ts b/pkgs/id/web/src/world-program.test.ts index 3ff7037aa9..2e58bf0091 100644 --- a/pkgs/id/web/src/world-program.test.ts +++ b/pkgs/id/web/src/world-program.test.ts @@ -123,7 +123,15 @@ describe("program-only surface (#2146 phase 2)", () => { expect(session.url).toMatch(/\/ws\/world$/); session.open(); expect(session.sent("join")).toEqual([ - { type: "join", capability: "guest-capability", after: null, world: "arena", screen_patches: true }, + { + type: "join", + capability: "guest-capability", + after: null, + world: "arena", + screen_patches: true, + screen_msgpack: true, + device_input: { keys: 128, encoder: false, pointer: true, text_entry: "keyboard" }, + }, ]); // Text rendering through the trusted presenter: guest output diff --git a/pkgs/id/web/src/world-surface.ts b/pkgs/id/web/src/world-surface.ts index 4404e4ff29..b762305c3a 100644 --- a/pkgs/id/web/src/world-surface.ts +++ b/pkgs/id/web/src/world-surface.ts @@ -14,6 +14,8 @@ export type ScreenCell = { bg: number; bold: boolean; columns: number; + /** Style token name from the wire model, when the frame carries one. */ + token?: string | null; }; export type ScreenPatch = { diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index 5bec8b3039..18b9e0ba00 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -3,6 +3,7 @@ import { createFormPresenter, type FormPresenter, type FormSurface } from "./world-form"; import { advanceHostViewCursor, parseWorldHostViewPage, parseWorldInviteResponse } from "./world-http"; import { terminalBytesForKey } from "./world-keyboard"; +import { decodeViewPatch } from "./screen-codec"; import { parseWorldSeed } from "./world-seed"; import { applyScreenPatch, renderWorldSurface, type ScreenPatch, type ScreenSurface } from "./world-surface"; @@ -233,6 +234,24 @@ function initWorld(): void { inviteOutput.hidden = false; }; + const receiveBinary = (bytes: Uint8Array) => { + // Negotiated binary screen transport (#12242, Rust half #12655): + // a binary message is one versioned MessagePack view patch, + // applied exactly like a JSON view frame's patch. Anything + // undecodable or inapplicable falls back to asking for a full + // view, the same recovery as a JSON patch whose base mismatches. + const frame = decodeViewPatch(bytes); + if (frame && renderedSurface && renderedViewRevision === frame.base_view_revision) { + const patched = applyScreenPatch(renderedSurface, frame.patch); + if (patched && renderWorldSurface(view, patched)) { + renderedSurface = patched; + renderedViewRevision = frame.view_revision; + return; + } + } + sendViewport(); + }; + const receive = (raw: string) => { let parsed: unknown; try { @@ -605,6 +624,7 @@ function initWorld(): void { // it) scheduled a duplicate reconnect, and a stale socket's open // sent its join frame on the newer socket. const ws = new WebSocket(`${scheme}//${location.host}${worldSocketPath}`); + ws.binaryType = "arraybuffer"; socket = ws; setStatus("Connecting…"); ws.addEventListener("open", () => { @@ -617,6 +637,7 @@ function initWorld(): void { after: cursor || null, world: selectedWorld(), screen_patches: true, + screen_msgpack: true, device_input: { keys: 128, encoder: false, @@ -629,7 +650,8 @@ function initWorld(): void { }); ws.addEventListener("message", (event) => { if (ws !== socket) return; - receive(String(event.data)); + if (event.data instanceof ArrayBuffer) receiveBinary(new Uint8Array(event.data)); + else receive(String(event.data)); }); ws.addEventListener("error", () => { if (ws !== socket) return;