Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pkgs/id/contract/shell-contract.v1.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}
Expand Down
1 change: 1 addition & 0 deletions pkgs/id/crates/id-core/src/screen_codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ pub fn decode_view_patch(bytes: &[u8]) -> Result<ViewPatchFrame, ScreenCodecErro
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use proptest::prelude::*;

Expand Down
93 changes: 93 additions & 0 deletions pkgs/id/web/src/screen-codec.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
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", () => {
Comment on lines +29 to +30

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add property-based coverage for the binary decoder

The new parser is covered only by fixed golden vectors and example rejection cases, despite having explicit invariants for numeric ranges, exact keys, frame bounds, and Rust wire compatibility. This violates the testing doctrine in AGENTS.md, which requires property-based tests where code has invariants; the existing Rust property tests exercise only the Rust codec, not this browser decoder. Add generated Rust-compatible frames and malformed mutations with parity and rejection oracles rather than relying exclusively on these examples.

AGENTS.md reference: AGENTS.md:L37-L39

Useful? React with 👍 / 👎.

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();
});
});
135 changes: 135 additions & 0 deletions pkgs/id/web/src/screen-codec.ts
Original file line number Diff line number Diff line change
@@ -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 });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Decode safely representable uint64 counters as numbers

When sequence, view_revision, or base_view_revision exceeds 0xffffffff, Rust encodes it as a MessagePack uint64. With this configuration, msgpackr 1.12.1's uint64 handler returns a bigint, which the number-only isUint validation rejects even when the value is within Number.MAX_SAFE_INTEGER. Consequently, a world whose event cursor crosses this boundary rejects every binary patch and repeatedly requests full views. Configure safe uint64 conversion or explicitly normalize bounded bigint values before validation.

Useful? React with 👍 / 👎.


function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

function hasExactlyKeys(value: Record<string, unknown>, 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,
};
}
10 changes: 9 additions & 1 deletion pkgs/id/web/src/world-program.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions pkgs/id/web/src/world-surface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
24 changes: 23 additions & 1 deletion pkgs/id/web/src/world.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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", () => {
Expand All @@ -617,6 +637,7 @@ function initWorld(): void {
after: cursor || null,
world: selectedWorld(),
screen_patches: true,
screen_msgpack: true,
device_input: {
keys: 128,
encoder: false,
Expand All @@ -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;
Expand Down