From bcdf790ff5a9f30829bf2da7dcf064b0cc786b47 Mon Sep 17 00:00:00 2001 From: archer Date: Sun, 22 Nov 2026 19:15:33 +0000 Subject: [PATCH 1/4] feat(id-web): decode negotiated binary screen patches in the browser (#12242) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The TS half of F12.11 phase 3, on the Rust slice merged in #12655: the session join now offers screen_msgpack alongside screen_patches, binary WebSocket messages decode through a strict MessagePack view-patch decoder at golden-vector parity with id-core's screen_codec, and a decoded patch applies exactly like a JSON view frame's patch — with the same full-view fallback (a same-size resize) when the frame is malformed, unsupported, or its base revision does not match. JSON patches on an offered session remain accepted, per the contract's offer-and-observe rule. --- pkgs/id/web/src/screen-codec.test.ts | 95 ++++++++++++++++++++ pkgs/id/web/src/screen-codec.ts | 130 +++++++++++++++++++++++++++ pkgs/id/web/src/world-surface.ts | 2 + pkgs/id/web/src/world.ts | 24 ++++- 4 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 pkgs/id/web/src/screen-codec.test.ts create mode 100644 pkgs/id/web/src/screen-codec.ts diff --git a/pkgs/id/web/src/screen-codec.test.ts b/pkgs/id/web/src/screen-codec.test.ts new file mode 100644 index 0000000000..95c0e3f90e --- /dev/null +++ b/pkgs/id/web/src/screen-codec.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from "vitest"; +import { decodeViewPatch } from "./screen-codec"; + +/** + * Golden-vector parity with the Rust codec (id-core screen_codec, + * #12242/#12655): GOLDEN_VIEW_PATCH_B64 is byte-for-byte the vector + * pinned by the Rust test + * `view_patch_matches_versioned_messagepack_golden_vector` — the + * two suites must agree on exactly what one frame is. The oracle is + * the MessagePack layout the Rust encoder produces. Base64 keeps + * the literals stable under the formatter. + */ +const GOLDEN_VIEW_PATCH_B64 = + "gqd2ZXJzaW9uAaVmcmFtZYWoc2VxdWVuY2UHrXZpZXdfcmV2aXNpb24DsmJhc2Vfdmlld19yZXZpc2lvbgKscmVzdW1lX3Rva2VuwKVwYXRjaISndmVyc2lvbgGld2lkdGgCpmhlaWdodAGkcnVuc5A="; +const GOLDEN_VIEW_PATCH = Uint8Array.from(atob(GOLDEN_VIEW_PATCH_B64), (c) => c.charCodeAt(0)); + +/** + * The same envelope with a populated patch: the golden vector's + * patch with its empty `runs` replaced by the populated runs of the + * #12241 patch golden (cells "A" with the warning token and "水" + * double-width). The byte splice is exact — both patches share + * version, width, and height — and the decode assertion below pins + * the result. + */ +const POPULATED_VIEW_PATCH_B64 = + "gqd2ZXJzaW9uAaVmcmFtZYWoc2VxdWVuY2UHrXZpZXdfcmV2aXNpb24DsmJhc2Vfdmlld19yZXZpc2lvbgKscmVzdW1lX3Rva2VuwKVwYXRjaISndmVyc2lvbgGld2lkdGgCpmhlaWdodAGkcnVuc5GCpXN0YXJ0AKVjZWxsc5KGpnN5bWJvbKFBomZnAaJiZwKkYm9sZMOnY29sdW1ucwGldG9rZW6nd2FybmluZ4Wmc3ltYm9so+awtKJmZwCiYmcApGJvbGTCp2NvbHVtbnMC"; +const POPULATED_VIEW_PATCH = Uint8Array.from(atob(POPULATED_VIEW_PATCH_B64), (c) => + 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( + "gqd2ZXJzaW9uAaVwYXRjaISmdmVyc2lvbgFld2lkdGgCpmhlaWdodAGkcnVuc5GCpXN0YXJ0AKVjZWxsc5KGpnN5bWJvbKFBomZnAaJiZwKkYm9sZMOnY29sdW1ucwGldG9rZW6nd2FybmluZ4Wmc3ltYm9so+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..c39fc31a9d --- /dev/null +++ b/pkgs/id/web/src/screen-codec.ts @@ -0,0 +1,130 @@ +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 { + if (!isRecord(value) || !hasExactlyKeys(value, ["symbol", "fg", "bg", "bold", "columns", "token"])) { + 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; + if (value.token !== null && (typeof value.token !== "string" || !STYLE_TOKENS.has(value.token))) { + return null; + } + return { + symbol: value.symbol, + fg: value.fg, + bg: value.bg, + bold: value.bold, + columns: value.columns, + token: value.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-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; From babe9c73a03b1de6007dc614893fcbc957b84251 Mon Sep 17 00:00:00 2001 From: archer Date: Sun, 22 Nov 2026 19:25:48 +0000 Subject: [PATCH 2/4] style(id-web): biome line for the populated golden vector --- pkgs/id/web/src/screen-codec.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/pkgs/id/web/src/screen-codec.test.ts b/pkgs/id/web/src/screen-codec.test.ts index 95c0e3f90e..8fac32d9de 100644 --- a/pkgs/id/web/src/screen-codec.test.ts +++ b/pkgs/id/web/src/screen-codec.test.ts @@ -24,9 +24,7 @@ const GOLDEN_VIEW_PATCH = Uint8Array.from(atob(GOLDEN_VIEW_PATCH_B64), (c) => c. */ const POPULATED_VIEW_PATCH_B64 = "gqd2ZXJzaW9uAaVmcmFtZYWoc2VxdWVuY2UHrXZpZXdfcmV2aXNpb24DsmJhc2Vfdmlld19yZXZpc2lvbgKscmVzdW1lX3Rva2VuwKVwYXRjaISndmVyc2lvbgGld2lkdGgCpmhlaWdodAGkcnVuc5GCpXN0YXJ0AKVjZWxsc5KGpnN5bWJvbKFBomZnAaJiZwKkYm9sZMOnY29sdW1ucwGldG9rZW6nd2FybmluZ4Wmc3ltYm9so+awtKJmZwCiYmcApGJvbGTCp2NvbHVtbnMC"; -const POPULATED_VIEW_PATCH = Uint8Array.from(atob(POPULATED_VIEW_PATCH_B64), (c) => - c.charCodeAt(0), -); +const POPULATED_VIEW_PATCH = Uint8Array.from(atob(POPULATED_VIEW_PATCH_B64), (c) => c.charCodeAt(0)); describe("decodeViewPatch", () => { it("decodes the Rust golden view-patch frame", () => { From da4617d03eb782f5465bf389ded1ae215a56c998 Mon Sep 17 00:00:00 2001 From: archer Date: Sun, 22 Nov 2026 19:49:01 +0000 Subject: [PATCH 3/4] fix(id): declare the join's device_input in the shell contract; pin the full join shape in world-program device_input entered the shell's join in #12281 without a contract field, leaving test-web-unit red on main (the conformance walk rejects the undeclared field and every later frame's phase check cascades). The host already parses the field (world_session join handling); this declares it, and the program test now expects the complete join the shell sends, screen_msgpack included. --- pkgs/id/contract/shell-contract.v1.json | 1 + pkgs/id/web/src/screen-codec.test.ts | 2 +- pkgs/id/web/src/screen-codec.ts | 15 ++++++++++----- pkgs/id/web/src/world-program.test.ts | 10 +++++++++- 4 files changed, 21 insertions(+), 7 deletions(-) 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/web/src/screen-codec.test.ts b/pkgs/id/web/src/screen-codec.test.ts index 8fac32d9de..cae4034bfe 100644 --- a/pkgs/id/web/src/screen-codec.test.ts +++ b/pkgs/id/web/src/screen-codec.test.ts @@ -84,7 +84,7 @@ describe("decodeViewPatch", () => { // offered as a view patch it must fail safely, not decode. const patchOnly = Uint8Array.from( atob( - "gqd2ZXJzaW9uAaVwYXRjaISmdmVyc2lvbgFld2lkdGgCpmhlaWdodAGkcnVuc5GCpXN0YXJ0AKVjZWxsc5KGpnN5bWJvbKFBomZnAaJiZwKkYm9sZMOnY29sdW1ucwGldG9rZW6nd2FybmluZ4Wmc3ltYm9so+awtKJmZwCiYmcApGJvbGTCp2NvbHVtbnMC", + "gqd2ZXJzaW9uAaVwYXRjaISndmVyc2lvbgGld2lkdGgCpmhlaWdodAGkcnVuc5GCpXN0YXJ0AKVjZWxsc5KGpnN5bWJvbKFBomZnAaJiZwKkYm9sZMOnY29sdW1ucwGldG9rZW6nd2FybmluZ4Wmc3ltYm9so+awtKJmZwCiYmcApGJvbGTCp2NvbHVtbnMC", ), (c) => c.charCodeAt(0), ); diff --git a/pkgs/id/web/src/screen-codec.ts b/pkgs/id/web/src/screen-codec.ts index c39fc31a9d..69fa3af3ed 100644 --- a/pkgs/id/web/src/screen-codec.ts +++ b/pkgs/id/web/src/screen-codec.ts @@ -48,13 +48,18 @@ function isUintOrNull(value: unknown, max: number): value is number | null { } function decodeCell(value: unknown): ScreenPatch["runs"][number]["cells"][number] | null { - if (!isRecord(value) || !hasExactlyKeys(value, ["symbol", "fg", "bg", "bold", "columns", "token"])) { - return 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; - if (value.token !== null && (typeof value.token !== "string" || !STYLE_TOKENS.has(value.token))) { + const token = "token" in value ? value.token : null; + if (token !== null && (typeof token !== "string" || !STYLE_TOKENS.has(token))) { return null; } return { @@ -63,7 +68,7 @@ function decodeCell(value: unknown): ScreenPatch["runs"][number]["cells"][number bg: value.bg, bold: value.bold, columns: value.columns, - token: value.token, + token, }; } 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 From 9d593ebc1e66f3ce18858c71f4c07b66db0a4784 Mon Sep 17 00:00:00 2001 From: archer Date: Sun, 22 Nov 2026 20:00:44 +0000 Subject: [PATCH 4/4] fix(id-core): allow unwrap/expect in the screen_codec tests so clippy-lint passes The #12655 test module used unwrap() in its proptest strategies and golden tests without the test-module allow the codebase requires (pkgs/id AGENTS.md); clippy-lint has been red on main since the merge. No production code changes. --- pkgs/id/crates/id-core/src/screen_codec.rs | 1 + 1 file changed, 1 insertion(+) 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