From 02086f5a0eb97c33f89a71d13884e2f2ee809662 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 10:41:20 +0000 Subject: [PATCH 1/5] =?UTF-8?q?feat(id):=20compressed=20binary=20screen=20?= =?UTF-8?q?patches=20=E2=80=94=20F12.11=20phase=204=20(#805)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Optional DEFLATE compression for the negotiated binary ScreenPatch transport, plus the under-10%-of-full-frame measurement. - id-core screen_codec: version-2 envelope {version: 2, compression, payload} carrying raw-DEFLATE (RFC 1951) of the version-1 frame; encode_view_patch_compressed emits it only when the complete compressed frame is smaller, so small frames stay byte-identical to version 1. Decoding is bounded by the 1 MiB frame limit in both directions; unknown versions/compressions, truncated streams, and oversized inflation fail closed. New deps flate2 (rust_backend) and serde_bytes, both already in the lockfile, gated under the world feature. - Session: join gains screen_compress (contract revision 16); the host sends version-2 frames only to sessions that offered it. - Browser: decodeViewPatchAsync handles version 2 via DecompressionStream('deflate'); the join offers screen_compress. - Measurement (design Q2 option B): a repeatable test records complete logical View payload bytes for a sparse redraw versus a full snapshot at 80x24 and 200x60 and asserts the sparse patch stays under 10% of the full frame, with patch/full-frame parity. - Session test: a compressed resume patch arrives as a version-2 binary frame and applies to exactly the full-frame screen. Refs #805 --- pkgs/id/Cargo.lock | 2 + pkgs/id/contract/shell-contract.v1.json | 4 +- pkgs/id/crates/id-core/Cargo.toml | 6 +- pkgs/id/crates/id-core/src/screen_codec.rs | 501 +++++++++++++++++- .../crates/id-core/src/world_presentation.rs | 5 +- .../id-worlds/src/shell_contract/tests.rs | 4 +- .../crates/id-worlds/src/world_session/mod.rs | 6 + .../src/world_session/session_core.rs | 4 + .../id-worlds/src/world_session/tests.rs | 125 +++++ .../id-worlds/src/world_session/types.rs | 8 + .../id-worlds/src/world_session/view.rs | 24 +- pkgs/id/web/src/screen-codec.test.ts | 65 ++- pkgs/id/web/src/screen-codec.ts | 95 +++- pkgs/id/web/src/world-program.test.ts | 1 + pkgs/id/web/src/world.ts | 33 +- 15 files changed, 849 insertions(+), 34 deletions(-) diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 2ed76d1902..41e9941cb3 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -4896,6 +4896,7 @@ dependencies = [ "cbor-core", "chacha20poly1305 0.11.0", "ed25519-dalek 3.0.0", + "flate2", "futures-lite", "idna", "iroh", @@ -4910,6 +4911,7 @@ dependencies = [ "rmp-serde", "rqrr", "serde", + "serde_bytes", "serde_json", "sha2 0.11.1", "tempfile", diff --git a/pkgs/id/contract/shell-contract.v1.json b/pkgs/id/contract/shell-contract.v1.json index 0b4c4a2f36..321df57ac2 100644 --- a/pkgs/id/contract/shell-contract.v1.json +++ b/pkgs/id/contract/shell-contract.v1.json @@ -1,7 +1,7 @@ { "contract": "id-shell", "version": 1, - "revision": 15, + "revision": 16, "description": "The client-server frame protocol every id shell (terminal, web, native) speaks to a world host. Version 1 is the protocol behind the /id-world/1 ALPN. A shell sends only frames and fields named here; it ignores server frame types and fields it does not know. Additive changes bump `revision`; removing or changing a frame or field needs version 2 and a new ALPN. Event-producing frames must name their stable world-event contract here.", "max_frame_bytes": 1048576, "routing_fields": ["world"], @@ -46,6 +46,7 @@ "after": "u64?", "screen_patches": { "type": "bool", "optional": true, "nullable": false }, "screen_msgpack": { "type": "bool", "optional": true, "nullable": false }, + "screen_compress": { "type": "bool", "optional": true, "nullable": false }, "device_input": { "type": "object", "optional": true, "nullable": true }, "agent_profile": { "type": "bool", "optional": true, "nullable": false }, "resume_token": { "type": "string", "optional": true, "nullable": true, "max_bytes": 64 } @@ -592,6 +593,7 @@ }, "features": { "screen_msgpack": "Revision 12 (negotiated binary screen patches, F12.11 phase 3, issue #12242; design doc/2026-11-01_design_id805.md sections 3, 5, 6): the join frame's `screen_msgpack` field is the capability flag — a shell that sets it, together with `screen_patches`, on a byte-capable transport receives screen patch frames as binary frames instead of JSON `view` frames. A binary patch frame is one versioned MessagePack value (id-core `screen_codec`, codec version 1) carrying exactly the fields of the `view` frame it replaces — `sequence`, `view_revision`, `base_view_revision`, `resume_token`, and the `patch` — with the same world-event cursor and view-revision semantics; full views, resume-token issuance, and every other frame stay on the text path. On the length-prefixed transports (iroh, ssh-exec) a binary frame body is marked with a single leading NUL byte, which no JSON text frame can start with; on WebSocket it is a binary message. Negotiation is offer-and-observe: a host or transport without the revision simply keeps sending JSON patch frames, and a shell must accept both for a session that offered the flag. Client frames remain text JSON in both directions of the negotiation; a binary frame from a client is malformed input and fails the session safely, like a non-UTF-8 frame. A host never sends a binary frame to a session that did not offer the flag, and never guesses an encoding: an unsupported codec version or a malformed binary payload is a decode failure for the shell, which falls back to a full view by rejoining or presenting its retained full-view path.", + "screen_compress": "Revision 16 (compressed binary screen patches, F12.11 phase 4, issue #805; design doc/2026-11-01_design_id805.md sections 2.3, 3, 5, 6): the join frame's `screen_compress` field is the capability flag \u2014 a shell that sets it, together with `screen_patches` and `screen_msgpack`, on a byte-capable transport receives screen patch frames as version-2 compressed MessagePack frames whenever compression makes the complete frame smaller, and as version-1 frames otherwise. A version-2 frame is one MessagePack value `{version: 2, compression, payload}` (id-core `screen_codec`); `compression` 1 means the payload is the raw-DEFLATE (RFC 1951) of the version-1 frame, `compression` 0 means the payload is the version-1 frame as-is. The inner frame carries exactly the fields of the `view` frame it replaces, with the same world-event cursor, view-revision, and resume-token semantics. Decompression is bounded by the shared 1 MiB frame limit: a payload that inflates past it, an unknown compression id, or a truncated stream is a decode failure for the shell, which falls back to a full view by rejoining or presenting its retained full-view path. A host never sends a compressed frame to a session that did not offer the flag, and never guesses an encoding.", "agent_profile": "Revision 11 (agent profile for #6300, design doc/2026-11-09_design_id6300_agents_in_worlds_v1.md sections 4.2, 4.3, 8, 9.1): the capability flag is the join frame's `agent_profile` field — a shell that sets it advertises it can consume semantic diffs. A joined agent-profile shell may send `screen_subscribe` naming a screen region (an object with u16 `x`, `y`, `width`, `height` in screen cells) and/or semantic event classes (`chat_posted`, `input_applied`, `object_changed`, `system_event`, `program_changed`; an empty list means all classes, an absent field means no event diffs). The host answers with a `screen_subscription` frame echoing the active subscription and the current screen revision, then sends `semantic_diff` frames scoped to the subscription: event diffs for subscribed classes as world events commit, and region diffs (changes of kind `region_changed`, one per changed row inside the region, carrying that row's new text) as views change. Each semantic_diff names the world `sequence` it follows, the `view_revision` it was computed at, and its `base_view_revision` when it diffs against a known earlier screen. Agent input frames (`input`, `chat`, `paste`, `form_result`, `pointer`) may carry `screen_revision`, the stale-decision token: the screen revision the input was decided against. The host applies such an input only while that revision is still the session's current screen revision; otherwise it rejects the input with an `error` frame whose code is `stale_decision`, commits nothing, and returns the current view. A host without this revision does not know the flag and serves the agent full view frames at reduced fidelity with identical authority; a shell that never sets the flag is unaffected.", "surface": "A view frame may carry a typed `surface`: a versioned document of kind `screen`, `text`, `form`, `scene`, `audio` or `widget`. Every kind carries its own `version`, bounds and host-side validation (id-core `world_presentation::parse_surface`); a document that names a known kind but fails validation is refused, never rendered. Revision 13 (rich presentation surfaces, issue #12657 slice 1a) adds the `scene` kind: a `scene/1` document is a bounded flat list of named nodes from a closed shape set (`box`, `sphere`, `plane`, `point`), each with a position and a size in world units. Revision 14 (issue #12657 slice 1b) adds the `audio` kind: an `audio/1` document is a bounded list of descriptive audio cues — each a named sound reference with a format from a closed set (`wav`, `ogg`, `mp3`), a duration in milliseconds and a repeat flag. Cues carry no embedded bytes, URLs or scripts; a presenter resolves each cue id against the world's own assets. Revision 15 (issue #12657 slice 1c) adds the `widget` kind: a `widget/1` document is a bounded list of descriptive controls — each a named control from a closed kind set (`button`, `toggle`, `link`) with a safe label, a toggle's current state, and, where it acts, the id of a world action. Controls carry no URLs, scripts or embedded payloads; a presenter resolves each action id against the world's own actions. A shell that does not understand a surface renders `data`; a shell without a renderer for a kind it does understand uses that kind's deterministic text projection, and a host that does not know a kind at all drops the document to the legacy plain-text path.", "input_events": "Pointer input per the input event model design (doc/2026-11-08T05-48-47Z_design_input_event_model, issue #1831 slice S2; landed in revision 10). Coordinates are cells in the target surface's grid: producers map device pixels to cells at the edge, so frames never carry pixels. `pointer` frames are class event — journaled and replayed like `input`; a drag is a press, a sequence of drag_move frames, and a release, and each drag_move is its own frame, so the frame limit bounds one move, never the whole path. `hover` frames are class ephemeral: connection-local presentation context, never journaled and never seen by other sessions. A pointer_id is unique only within its producing connection; the host namespaces it with the connection's identity when journaling, and press/release pairing is scoped to that (connection, pointer_id) pair. An event an environment cannot produce, or that the target app did not declare in its manifest `interfaces.input`, is refused explicitly: the host answers `input_refused` naming the event and a reason from that frame's enum — an input event is never silently dropped." diff --git a/pkgs/id/crates/id-core/Cargo.toml b/pkgs/id/crates/id-core/Cargo.toml index 1d7158e7fd..cc2a8d172b 100644 --- a/pkgs/id/crates/id-core/Cargo.toml +++ b/pkgs/id/crates/id-core/Cargo.toml @@ -8,7 +8,7 @@ license = "MIT OR Apache-2.0" [features] default = ["world", "sandbox"] -world = ["dep:rmp-serde"] +world = ["dep:rmp-serde", "dep:flate2", "dep:serde_bytes"] sandbox = [] web = ["dep:qrcode"] test-utils = [] @@ -46,6 +46,10 @@ qrcode = { version = "0.14.1", default-features = false, optional = true } serde = { version = "1", features = ["derive"] } serde_json = "1" rmp-serde = { version = "1", optional = true } +# Optional DEFLATE (RFC 1951) for compressed screen frames (F12.11 phase 4, +# #805): pure-Rust backend, no system zlib. +flate2 = { version = "1", default-features = false, features = ["rust_backend"], optional = true } +serde_bytes = { version = "0.11", optional = true } tempfile = "3" thiserror = "2" tokio = { version = "1", features = ["full"] } diff --git a/pkgs/id/crates/id-core/src/screen_codec.rs b/pkgs/id/crates/id-core/src/screen_codec.rs index 45f68b06ba..6f2c047259 100644 --- a/pkgs/id/crates/id-core/src/screen_codec.rs +++ b/pkgs/id/crates/id-core/src/screen_codec.rs @@ -1,13 +1,30 @@ //! Versioned MessagePack encoding for the transport-neutral F12.11 screen patch. +//! +//! Version 1 is the plain MessagePack frame. Version 2 wraps the same +//! version-1 frame in an envelope naming its compression, so a compressed +//! frame is self-describing: `{version: 2, compression, payload}`. A +//! compressed frame is emitted only when the complete compressed frame is +//! smaller than its uncompressed version-1 form, so compression never grows +//! a frame on the wire (F12.11 phase 4, #805). -use std::io::Cursor; +use std::io::{Cursor, Read, Write}; use serde::{Deserialize, Serialize}; +use serde_bytes::ByteBuf; use crate::world_presentation::ScreenPatch; /// Version of the MessagePack screen-patch wire representation. pub const SCREEN_CODEC_VERSION: u8 = 1; +/// Version of the compressed screen-patch envelope: the payload is the +/// version-1 MessagePack frame, compressed as named by `compression`. +pub const SCREEN_CODEC_VERSION_COMPRESSED: u8 = 2; +/// No compression: the version-2 payload is the version-1 frame as-is. +pub const COMPRESSION_NONE: u8 = 0; +/// Raw DEFLATE (RFC 1951) of the version-1 frame. Raw DEFLATE is what the +/// browser's `DecompressionStream("deflate")` decodes, so the same bytes +/// serve the Rust transports and the browser with no extra dependency. +pub const COMPRESSION_DEFLATE: u8 = 1; /// Maximum complete logical frame size, matching the session frame limit. pub const MAX_SCREEN_FRAME_BYTES: usize = 1024 * 1024; @@ -41,6 +58,12 @@ pub enum ScreenCodecError { /// The frame uses a codec version this implementation does not support. #[error("unsupported screen codec version {0}")] UnsupportedVersion(u8), + /// The frame names a compression this implementation does not support. + #[error("unsupported screen compression {0}")] + UnsupportedCompression(u8), + /// A compression or decompression I/O error occurred. + #[error("screen frame compression failed: {0}")] + Compression(#[from] std::io::Error), /// The MessagePack value has trailing bytes after its one complete value. #[error("trailing bytes after screen frame")] TrailingBytes, @@ -124,8 +147,32 @@ pub fn encode_view_patch(frame: &ViewPatchFrame) -> Result, ScreenCodecE Ok(bytes) } -/// Decodes one bounded, versioned MessagePack view frame. +/// Decodes one bounded, versioned MessagePack view frame, plain +/// (version 1) or compressed (version 2). pub fn decode_view_patch(bytes: &[u8]) -> Result { + if bytes.len() > MAX_SCREEN_FRAME_BYTES { + return Err(ScreenCodecError::TooLarge); + } + let mut deserializer = rmp_serde::Deserializer::new(Cursor::new(bytes)); + let probe = ::deserialize(&mut deserializer)?; + match probe.version { + SCREEN_CODEC_VERSION => decode_v1_view_patch(bytes), + SCREEN_CODEC_VERSION_COMPRESSED => decode_compressed_view_patch(bytes), + other => Err(ScreenCodecError::UnsupportedVersion(other)), + } +} + +/// The one field every envelope version carries, read before dispatching +/// to the version's own shape. Unknown fields are ignored here; the +/// version-specific decoder below still enforces its exact shape. +#[derive(Deserialize)] +struct VersionProbe { + version: u8, +} + +/// Decodes one bounded, versioned MessagePack view frame in the plain +/// version-1 shape. +fn decode_v1_view_patch(bytes: &[u8]) -> Result { if bytes.len() > MAX_SCREEN_FRAME_BYTES { return Err(ScreenCodecError::TooLarge); } @@ -140,16 +187,95 @@ pub fn decode_view_patch(bytes: &[u8]) -> Result Result, ScreenCodecError> { + let raw = encode_view_patch(frame)?; + let mut encoder = + flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(&raw)?; + let deflated = encoder.finish()?; + let envelope = rmp_serde::to_vec_named(&VersionedCompressedViewPatch { + version: SCREEN_CODEC_VERSION_COMPRESSED, + compression: COMPRESSION_DEFLATE, + payload: ByteBuf::from(deflated), + })?; + if envelope.len() < raw.len() { + Ok(envelope) + } else { + Ok(raw) + } +} + +/// Decodes one version-2 compressed view frame: validates the envelope, +/// inflates the payload with its output bounded by the frame limit, then +/// decodes the inner version-1 frame exactly as a plain frame. +fn decode_compressed_view_patch(bytes: &[u8]) -> Result { + let mut deserializer = rmp_serde::Deserializer::new(Cursor::new(bytes)); + let frame = + ::deserialize(&mut deserializer)?; + if usize::try_from(deserializer.into_inner().position()).ok() != Some(bytes.len()) { + return Err(ScreenCodecError::TrailingBytes); + } + if frame.version != SCREEN_CODEC_VERSION_COMPRESSED { + return Err(ScreenCodecError::UnsupportedVersion(frame.version)); + } + let raw = match frame.compression { + COMPRESSION_NONE => frame.payload.into_vec(), + COMPRESSION_DEFLATE => inflate_bounded(&frame.payload)?, + other => return Err(ScreenCodecError::UnsupportedCompression(other)), + }; + decode_v1_view_patch(&raw) +} + +/// Inflates raw-DEFLATE bytes, refusing output past the shared frame limit +/// instead of allocating on an untrusted claimed size. +fn inflate_bounded(payload: &[u8]) -> Result, ScreenCodecError> { + let mut decoder = flate2::read::DeflateDecoder::new(payload); + let mut out = Vec::new(); + decoder + .take(u64::try_from(MAX_SCREEN_FRAME_BYTES).unwrap_or(u64::MAX) + 1) + .read_to_end(&mut out)?; + if out.len() > MAX_SCREEN_FRAME_BYTES { + return Err(ScreenCodecError::TooLarge); + } + Ok(out) +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use proptest::prelude::*; use super::{ - MAX_SCREEN_FRAME_BYTES, ScreenCodecError, ViewPatchFrame, decode_patch, decode_view_patch, - encode_patch, encode_view_patch, + COMPRESSION_DEFLATE, COMPRESSION_NONE, MAX_SCREEN_FRAME_BYTES, + SCREEN_CODEC_VERSION_COMPRESSED, ScreenCodecError, ViewPatchFrame, decode_patch, + decode_view_patch, encode_patch, encode_view_patch, encode_view_patch_compressed, }; - use crate::world_presentation::{CellRun, ScreenCell, ScreenPatch, StyleToken}; + use crate::world_presentation::{CellRun, ScreenCell, ScreenPatch, ScreenSurface, StyleToken}; const GOLDEN_VIEW_PATCH: &[u8] = &[ 0x82, 0xa7, b'v', b'e', b'r', b's', b'i', b'o', b'n', 0x01, 0xa5, b'f', b'r', b'a', b'm', @@ -253,6 +379,25 @@ mod tests { let encoded = encode_view_patch(&frame).unwrap(); prop_assert_eq!(decode_view_patch(&encoded).unwrap(), frame); } + + #[test] + fn view_patch_frames_round_trip_through_compression( + patch in populated_patch(), + sequence in any::(), + view_revision in any::(), + base_view_revision in prop::option::of(any::()), + resume_token in prop::option::of("[0-9a-f]{1,64}"), + ) { + let frame = ViewPatchFrame { + sequence, + view_revision, + base_view_revision, + resume_token, + patch, + }; + let encoded = encode_view_patch_compressed(&frame).unwrap(); + prop_assert_eq!(decode_view_patch(&encoded).unwrap(), frame); + } } fn sample_view_patch() -> ViewPatchFrame { @@ -282,11 +427,20 @@ mod tests { #[test] fn view_patch_rejects_unsupported_version_and_malformed_frames() { + // Version 3 names no envelope this implementation knows. let mut unsupported = encode_view_patch(&sample_view_patch()).unwrap(); - unsupported[9] = 2; + unsupported[9] = 3; assert!(matches!( decode_view_patch(&unsupported), - Err(ScreenCodecError::UnsupportedVersion(2)) + Err(ScreenCodecError::UnsupportedVersion(3)) + )); + // Version 2 with a version-1 body is a malformed compressed + // envelope, not a plain frame: the compression tag is missing. + let mut mistyped = encode_view_patch(&sample_view_patch()).unwrap(); + mistyped[9] = 2; + assert!(matches!( + decode_view_patch(&mistyped), + Err(ScreenCodecError::Invalid(_)) )); assert!(matches!( decode_view_patch(&[0xc1]), @@ -306,4 +460,337 @@ mod tests { Err(ScreenCodecError::TooLarge) )); } + + /// Mirror of the version-2 envelope shape, for building tampered + /// envelopes the encoder never emits. + #[derive(serde::Serialize, serde::Deserialize)] + #[serde(deny_unknown_fields)] + struct TestCompressedEnvelope { + version: u8, + compression: u8, + payload: serde_bytes::ByteBuf, + } + + fn deflate(bytes: &[u8]) -> Vec { + use std::io::Write; + let mut encoder = + flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(bytes).unwrap(); + encoder.finish().unwrap() + } + + /// A view frame big enough for DEFLATE to win: a 120x50 screen of + /// varied cells, patched in full. + fn large_view_patch() -> ViewPatchFrame { + const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz"; + let mut runs = Vec::new(); + for row in 0..50_u16 { + let cells = (0..120_u16) + .map(|col| { + let symbol = ALPHABET + [(usize::from(row) * 7 + usize::from(col) * 13) % ALPHABET.len()] + as char; + ScreenCell { + symbol: symbol.to_string(), + fg: u8::try_from((usize::from(row) + usize::from(col)) % 8) + .unwrap_or_default(), + bg: 0, + bold: (row + col) % 11 == 0, + columns: 1, + token: None, + } + }) + .collect::>(); + runs.push(CellRun { + start: u32::from(row) * 120, + cells, + }); + } + ViewPatchFrame { + sequence: 1, + view_revision: 2, + base_view_revision: Some(1), + resume_token: None, + patch: ScreenPatch { + version: 1, + width: 120, + height: 50, + runs, + }, + } + } + + #[test] + fn large_view_patches_round_trip_through_compression_and_stay_smaller() { + let frame = large_view_patch(); + let raw = encode_view_patch(&frame).unwrap(); + let compressed = encode_view_patch_compressed(&frame).unwrap(); + assert!( + compressed.len() < raw.len(), + "a 120x50 varied patch must shrink: {} vs {} raw", + compressed.len(), + raw.len() + ); + assert_ne!(compressed, raw); + assert_eq!(decode_view_patch(&compressed).unwrap(), frame); + assert_eq!( + encode_view_patch_compressed(&frame).unwrap(), + compressed, + "compression is deterministic" + ); + } + + #[test] + fn small_view_patches_are_never_grown_by_compression() { + let frame = sample_view_patch(); + let raw = encode_view_patch(&frame).unwrap(); + assert_eq!(encode_view_patch_compressed(&frame).unwrap(), raw); + let one_cell = ViewPatchFrame { + sequence: 1, + view_revision: 2, + base_view_revision: Some(1), + resume_token: None, + patch: ScreenPatch { + version: 1, + width: 80, + height: 24, + runs: vec![CellRun { + start: 0, + cells: vec![ScreenCell { + symbol: "x".to_owned(), + fg: 1, + bg: 0, + bold: false, + columns: 1, + token: None, + }], + }], + }, + }; + let one_raw = encode_view_patch(&one_cell).unwrap(); + let one_compressed = encode_view_patch_compressed(&one_cell).unwrap(); + assert!(one_compressed.len() <= one_raw.len()); + assert_eq!(decode_view_patch(&one_compressed).unwrap(), one_cell); + } + + #[test] + fn compressed_frames_carry_a_version_two_deflate_envelope() { + let frame = large_view_patch(); + let compressed = encode_view_patch_compressed(&frame).unwrap(); + let envelope: TestCompressedEnvelope = rmp_serde::from_slice(&compressed).unwrap(); + assert_eq!(envelope.version, SCREEN_CODEC_VERSION_COMPRESSED); + assert_eq!(envelope.compression, COMPRESSION_DEFLATE); + assert!(!envelope.payload.is_empty()); + assert_eq!(decode_view_patch(&compressed).unwrap(), frame); + } + + #[test] + fn compressed_frames_reject_unknown_compression_truncated_and_oversized_payloads() { + let frame = large_view_patch(); + let raw = encode_view_patch(&frame).unwrap(); + let deflated = deflate(&raw); + + let unknown = rmp_serde::to_vec_named(&TestCompressedEnvelope { + version: SCREEN_CODEC_VERSION_COMPRESSED, + compression: 9, + payload: serde_bytes::ByteBuf::from(deflated.clone()), + }) + .unwrap(); + assert!(matches!( + decode_view_patch(&unknown), + Err(ScreenCodecError::UnsupportedCompression(9)) + )); + + let truncated = rmp_serde::to_vec_named(&TestCompressedEnvelope { + version: SCREEN_CODEC_VERSION_COMPRESSED, + compression: COMPRESSION_DEFLATE, + payload: serde_bytes::ByteBuf::from(deflated[..deflated.len() / 2].to_vec()), + }) + .unwrap(); + assert!(matches!( + decode_view_patch(&truncated), + Err(ScreenCodecError::Compression(_)) + )); + + let bomb = rmp_serde::to_vec_named(&TestCompressedEnvelope { + version: SCREEN_CODEC_VERSION_COMPRESSED, + compression: COMPRESSION_DEFLATE, + payload: serde_bytes::ByteBuf::from(deflate(&vec![ + 0_u8; + MAX_SCREEN_FRAME_BYTES + 1 + ])), + }) + .unwrap(); + assert!(matches!( + decode_view_patch(&bomb), + Err(ScreenCodecError::TooLarge) + )); + + let plain = rmp_serde::to_vec_named(&TestCompressedEnvelope { + version: SCREEN_CODEC_VERSION_COMPRESSED, + compression: COMPRESSION_NONE, + payload: serde_bytes::ByteBuf::from(raw), + }) + .unwrap(); + assert_eq!(decode_view_patch(&plain).unwrap(), frame); + + let mut trailing = encode_view_patch_compressed(&frame).unwrap(); + trailing.push(0xc0); + assert!(matches!( + decode_view_patch(&trailing), + Err(ScreenCodecError::TrailingBytes) + )); + } + + fn blank_cell() -> ScreenCell { + ScreenCell { + symbol: " ".to_owned(), + fg: 0, + bg: 0, + bold: false, + columns: 1, + token: None, + } + } + + /// Deterministic document-like screen: rows of varied words with + /// cycling colours, so the full frame carries realistic entropy + /// instead of one repeated cell. + fn document_screen(width: usize, height: usize) -> ScreenSurface { + const WORDS: &[&str] = &[ + "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", + ]; + let mut cells = Vec::with_capacity(width * height); + for row in 0..height { + let mut col = 0; + let mut word_index = row % WORDS.len(); + while col < width { + let word = WORDS[word_index % WORDS.len()]; + word_index += 1; + for ch in word.chars() { + if col >= width { + break; + } + cells.push(ScreenCell { + symbol: ch.to_string(), + fg: u8::try_from((row + col) % 8).unwrap_or_default(), + bg: 0, + bold: (row + col) % 11 == 0, + columns: 1, + token: if col == 0 && row % 5 == 0 { + Some(StyleToken::Heading) + } else { + None + }, + }); + col += 1; + } + if col < width { + cells.push(blank_cell()); + col += 1; + } + } + } + ScreenSurface::from_cells(width, height, cells).unwrap() + } + + /// A typical sparse redraw of a document screen: a rewritten status + /// line plus two scattered single-cell edits. + fn sparse_redraw(screen: &ScreenSurface) -> ScreenSurface { + let width = usize::from(screen.width); + let height = usize::from(screen.height); + let mut cells = screen.cells.clone(); + let status = "-- status: 12 new messages --"; + let row_start = (height - 1) * width; + for (offset, ch) in status.chars().enumerate() { + if offset >= width { + break; + } + cells[row_start + offset] = ScreenCell { + symbol: ch.to_string(), + fg: 7, + bg: 0, + bold: true, + columns: 1, + token: None, + }; + } + for (row, col) in [(3_usize, 5_usize), (10_usize, 40_usize)] { + if row < height && col < width { + cells[row * width + col] = ScreenCell { + symbol: "#".to_owned(), + fg: 1, + bg: 0, + bold: false, + columns: 1, + token: Some(StyleToken::Warning), + }; + } + } + ScreenSurface::from_cells(width, height, cells).unwrap() + } + + fn full_snapshot_patch(screen: &ScreenSurface) -> ScreenPatch { + ScreenPatch { + version: screen.version, + width: screen.width, + height: screen.height, + runs: vec![CellRun { + start: 0, + cells: screen.cells.clone(), + }], + } + } + + #[test] + fn sparse_redraws_measure_under_ten_percent_of_full_frame() { + // Oracle: the #805 acceptance as decided (design §7, Q2 option B): + // complete logical View payload bytes, full snapshot and patch + // encoded with the same negotiated version and codec, at 80x24 + // and 200x60. The F11.9 raw guest-frame sizes are a different + // layer and stay out of the ratio. + for (width, height) in [(80_usize, 24_usize), (200_usize, 60_usize)] { + let full = document_screen(width, height); + let changed = sparse_redraw(&full); + let blank = ScreenSurface::from_cells(width, height, vec![ + blank_cell(); + width * height + ]) + .unwrap(); + let full_frame = ViewPatchFrame { + sequence: 1, + view_revision: 2, + base_view_revision: Some(1), + resume_token: None, + patch: full_snapshot_patch(&full), + }; + let sparse_patch = ScreenPatch::diff(&full, &changed).unwrap(); + assert!( + !sparse_patch.is_empty(), + "the fixture redraw must change cells at {width}x{height}" + ); + let sparse_frame = ViewPatchFrame { + sequence: 1, + view_revision: 2, + base_view_revision: Some(1), + resume_token: None, + patch: sparse_patch.clone(), + }; + let full_bytes = encode_view_patch_compressed(&full_frame).unwrap(); + let sparse_bytes = encode_view_patch_compressed(&sparse_frame).unwrap(); + // Parity: the compressed sparse patch applies to the full + // screen and yields exactly the redrawn screen, and the + // full snapshot patch rebuilds the screen from blank. + assert_eq!(decode_view_patch(&sparse_bytes).unwrap(), sparse_frame); + assert_eq!(decode_view_patch(&full_bytes).unwrap(), full_frame); + assert_eq!(sparse_patch.apply(&full).unwrap(), changed); + assert_eq!(full_snapshot_patch(&full).apply(&blank).unwrap(), full); + assert!( + sparse_bytes.len() * 10 < full_bytes.len(), + "sparse redraw is {} bytes, over 10% of the {}-byte full frame at {width}x{height}", + sparse_bytes.len(), + full_bytes.len(), + ); + } + } } diff --git a/pkgs/id/crates/id-core/src/world_presentation.rs b/pkgs/id/crates/id-core/src/world_presentation.rs index 7d90a0c5ae..3420260ee7 100644 --- a/pkgs/id/crates/id-core/src/world_presentation.rs +++ b/pkgs/id/crates/id-core/src/world_presentation.rs @@ -1308,8 +1308,9 @@ impl WidgetSurface { /// A patch carries only the cells that changed, grouped into maximal runs of /// consecutive row-major indices. It is transport-neutral: the same patch can /// ride any shell transport, and a client that applies it to the previous -/// screen holds exactly the next full frame. Binary encoding and compression -/// are later F12.11 slices; this type is the delta they will encode. +/// screen holds exactly the next full frame. Binary encoding is the F12.11 +/// phase-3 slice and optional compression the phase-4 slice, both in +/// `screen_codec`; this type is the delta they encode. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(deny_unknown_fields)] pub struct ScreenPatch { diff --git a/pkgs/id/crates/id-worlds/src/shell_contract/tests.rs b/pkgs/id/crates/id-worlds/src/shell_contract/tests.rs index 2c5d618fb1..f8dbef8c53 100644 --- a/pkgs/id/crates/id-worlds/src/shell_contract/tests.rs +++ b/pkgs/id/crates/id-worlds/src/shell_contract/tests.rs @@ -606,7 +606,7 @@ fn pointer_and_hover_frames_conform_to_the_input_event_model() { // (class event), hover is ephemeral, refusals name a reason from // the design's table, and scroll deltas are signed cell units. let contract = contract(); - assert_eq!(contract.revision, 15); + assert_eq!(contract.revision, 16); assert_eq!(contract.client_frames["pointer"].class, FrameClass::Event); assert_eq!(contract.client_frames["hover"].class, FrameClass::Ephemeral); assert_eq!( @@ -719,7 +719,7 @@ fn agent_profile_frames_conform_and_are_additive() { // stale-decision token on agent input frames. Human shells, which // never set the flag or send the new frames, are unaffected. let contract = contract(); - assert_eq!(contract.revision, 15); + assert_eq!(contract.revision, 16); assert_eq!( contract.client_frames["screen_subscribe"].class, FrameClass::Ephemeral diff --git a/pkgs/id/crates/id-worlds/src/world_session/mod.rs b/pkgs/id/crates/id-worlds/src/world_session/mod.rs index 1492d17612..36fbba36bc 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/mod.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/mod.rs @@ -1131,6 +1131,7 @@ async fn joined( after: Option, screen_patches: bool, screen_msgpack: bool, + screen_compress: bool, resume_token: Option, agent_profile: bool, device_input: Option, @@ -1190,6 +1191,11 @@ async fn joined( // no offer, or a text-only transport — keeps the JSON patch path, // and a client that never opted in is unaffected either way. view_state.msgpack_patches = screen_patches && screen_msgpack && io.supports_bytes(); + // Compressed patches (F12.11 phase 4, contract revision 16) ride + // the same negotiation: only a session that also offered + // `screen_compress` receives version-2 compressed frames, and only + // when compression makes the complete frame smaller. + view_state.compress_patches = view_state.msgpack_patches && screen_compress; if let Some(after) = after { match world.events_after(token.clone(), after).await { Ok(page) if page.needs_snapshot => { diff --git a/pkgs/id/crates/id-worlds/src/world_session/session_core.rs b/pkgs/id/crates/id-worlds/src/world_session/session_core.rs index d1cd219ad1..0faaa01e5b 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/session_core.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/session_core.rs @@ -21,6 +21,7 @@ pub(crate) async fn run_world_session( after, screen_patches, screen_msgpack, + screen_compress, resume_token, agent_profile, device_input, @@ -37,6 +38,7 @@ pub(crate) async fn run_world_session( after, screen_patches, screen_msgpack, + screen_compress, resume_token, agent_profile, device_input, @@ -517,6 +519,7 @@ async fn query_session( after, screen_patches, screen_msgpack, + screen_compress, resume_token, agent_profile, device_input, @@ -533,6 +536,7 @@ async fn query_session( after, screen_patches, screen_msgpack, + screen_compress, resume_token, agent_profile, device_input, diff --git a/pkgs/id/crates/id-worlds/src/world_session/tests.rs b/pkgs/id/crates/id-worlds/src/world_session/tests.rs index 56af513bc0..ccf5933e22 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/tests.rs @@ -4558,6 +4558,131 @@ mod tests { assert_eq!(applied, screen_of(&full)); } + /// A 120x50 screen of varied rows; step 2 rewrites the last + /// three rows, a sparse redraw big enough for DEFLATE to win. + struct BigScreen(Arc); + + impl crate::world::WorldProgram for BigScreen { + fn view(&mut self, _viewer: &Participant) -> anyhow::Result> { + const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz"; + let step = self.0.load(Ordering::Relaxed); + let mut rows = Vec::new(); + for row in 0..50 { + let mut line = String::with_capacity(120); + for col in 0..120 { + let byte = if step >= 2 && row >= 47 { + b"#" + } else { + ALPHABET[(row * 7 + col * 13) % ALPHABET.len()] + }; + line.push(byte as char); + } + rows.push(line); + } + Ok(Some(format!( + "{{\"kind\":\"screen\",\"version\":1,\"width\":120,\"height\":50,\"rows\":{}}}", + serde_json::to_string(&rows).unwrap() + ))) + } + } + + #[tokio::test] + async fn compressed_resume_patch_arrives_as_a_version_two_binary_frame() { + let step = Arc::new(AtomicU64::new(0)); + let world = WorldHandle::spawn_with_program( + WorldCore::new("lobby", WorldLimits::default()).unwrap(), + Box::new(BigScreen(Arc::clone(&step))), + ); + let svc = WorldService::new(world.clone(), None); + let (_, capability) = world + .issue("player".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + + // Establish a retained baseline on a byte transport that + // offered compression, at the full 120x50 viewport. + let mut first = BytePeer::connect(svc.clone()); + first + .say(serde_json::json!({ + "type": "join", + "capability": capability.expose(), + "screen_patches": true, + "screen_msgpack": true, + "screen_compress": true, + })) + .await; + assert_eq!(first.next_text().await["type"], "snapshot"); + let opening: serde_json::Value = match first.next_view_frame().await { + SentFrame::Text(text) => serde_json::from_str(&text).unwrap(), + other => panic!("the first frame is a full text view, got {other:?}"), + }; + assert!(opening["patch"].is_null(), "the first frame is a full view"); + first + .say(serde_json::json!({"type": "resize", "width": 120, "height": 50})) + .await; + let resized: serde_json::Value = match first.next_view_frame().await { + SentFrame::Text(text) => serde_json::from_str(&text).unwrap(), + other => panic!("a resize resets to a full text view, got {other:?}"), + }; + assert!(resized["patch"].is_null(), "a resize resets to a full view"); + let mut applied = screen_of(&resized); + let token = resized["resume_token"].as_str().unwrap().to_owned(); + let base_revision = resized["view_revision"].as_u64().unwrap(); + + step.store(2, Ordering::Relaxed); + first.close().await; + let mut resumed = BytePeer::connect(svc.clone()); + resumed + .say(serde_json::json!({ + "type": "join", + "capability": capability.expose(), + "screen_patches": true, + "screen_msgpack": true, + "screen_compress": true, + "resume_token": token, + })) + .await; + assert_eq!(resumed.next_text().await["type"], "snapshot"); + let bytes = match resumed.next_view_frame().await { + SentFrame::Bytes(bytes) => bytes, + other => panic!("a negotiated catch-up patch is binary, got {other:?}"), + }; + let frame = id_core::screen_codec::decode_view_patch(&bytes) + .expect("the binary frame is a versioned view patch"); + assert_eq!(frame.base_view_revision, Some(base_revision)); + // The session sent the compressed form, not the plain + // version-1 encoding of the same frame. + assert_eq!( + bytes.len(), + id_core::screen_codec::encode_view_patch_compressed(&frame) + .unwrap() + .len(), + "the session sends exactly the compressed encoding" + ); + assert!( + bytes.len() + < id_core::screen_codec::encode_view_patch(&frame).unwrap().len(), + "the compressed frame is smaller than its version-1 form" + ); + applied = frame + .patch + .apply(&applied) + .expect("the binary patch applies to its base"); + + // Parity: the compressed-patched client holds exactly a + // full-frame client's screen. + let mut fresh = Peer::connect(svc, SessionConfig::default()); + fresh + .say(serde_json::json!({ + "type": "join", + "capability": capability.expose(), + })) + .await; + assert_eq!(fresh.next().await.unwrap()["type"], "snapshot"); + let full = next_view(&mut fresh).await; + assert_eq!(applied, screen_of(&full)); + } + #[tokio::test] async fn msgpack_offer_on_a_text_only_transport_keeps_json_patches() { let step = Arc::new(AtomicU64::new(0)); diff --git a/pkgs/id/crates/id-worlds/src/world_session/types.rs b/pkgs/id/crates/id-worlds/src/world_session/types.rs index b23128eac6..1a05722756 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/types.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/types.rs @@ -220,6 +220,14 @@ pub(crate) enum ClientFrame { /// clients that predate the revision. #[serde(default)] screen_msgpack: bool, + /// Opt in to compressed binary screen patches (F12.11 phase 4, + /// contract revision 16): when `screen_msgpack` is also set, + /// patch frames arrive as compressed version-2 MessagePack + /// frames whenever compression makes the complete frame + /// smaller, and as version-1 frames otherwise. Omitted by + /// clients that predate the revision. + #[serde(default)] + screen_compress: bool, /// Resume token from this client's last applied view. A cursor, not a /// credential: the join capability above still authorizes the session, /// and an unknown, stale or foreign token simply gets a full view. diff --git a/pkgs/id/crates/id-worlds/src/world_session/view.rs b/pkgs/id/crates/id-worlds/src/world_session/view.rs index 6e55a23b04..1e44f51bc1 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/view.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/view.rs @@ -47,6 +47,12 @@ pub(crate) struct ViewRevisionState { /// transport carries bytes, so patch frames are sent as versioned /// MessagePack binary frames instead of JSON `view` frames. pub(crate) msgpack_patches: bool, + /// Negotiated compressed patches (F12.11 phase 4, contract + /// revision 16): the join also offered `screen_compress`, so patch + /// frames are sent as version-2 compressed frames whenever + /// compression makes the complete frame smaller, and as version-1 + /// frames otherwise. + pub(crate) compress_patches: bool, /// A resume token presented at join and not yet consumed by a view send. pub(crate) pending_resume: Option, /// Agent profile (contract revision 11): set from the join frame's @@ -279,8 +285,12 @@ pub(crate) async fn send_view( // same patch and envelope fields, as one versioned // MessagePack binary frame, when that is smaller // than the full view the client would otherwise - // get. An encoding failure falls through to the - // JSON choice below — never a guessed encoding. + // get. With compression negotiated (F12.11 phase 4) + // the frame is the version-2 compressed form when + // that is smaller still, and the version-1 form + // otherwise — compression never grows a frame. An + // encoding failure falls through to the JSON choice + // below — never a guessed encoding. if view_state.msgpack_patches { let binary = id_core::screen_codec::ViewPatchFrame { sequence, @@ -289,10 +299,12 @@ pub(crate) async fn send_view( resume_token: resume_token.clone(), patch: patch.clone(), }; - if let (Ok(bytes), Ok(full)) = ( - id_core::screen_codec::encode_view_patch(&binary), - &full_size, - ) { + let encoded = if view_state.compress_patches { + id_core::screen_codec::encode_view_patch_compressed(&binary) + } else { + id_core::screen_codec::encode_view_patch(&binary) + }; + if let (Ok(bytes), Ok(full)) = (encoded, &full_size) { if bytes.len() < *full { let sent = send_binary(service.frame_meter(), io, bytes).await; if sent { diff --git a/pkgs/id/web/src/screen-codec.test.ts b/pkgs/id/web/src/screen-codec.test.ts index cae4034bfe..10d5db4aec 100644 --- a/pkgs/id/web/src/screen-codec.test.ts +++ b/pkgs/id/web/src/screen-codec.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; -import { decodeViewPatch } from "./screen-codec"; +import { Packr } from "msgpackr"; +import { decodeViewPatch, decodeViewPatchAsync } from "./screen-codec"; /** * Golden-vector parity with the Rust codec (id-core screen_codec, @@ -91,3 +92,65 @@ describe("decodeViewPatch", () => { expect(decodeViewPatch(patchOnly)).toBeNull(); }); }); + +describe("decodeViewPatchAsync", () => { + const packr = new Packr({ useRecords: false }); + + /** Raw-DEFLATE (RFC 1951) via the platform compressor. */ + async function deflate(bytes: Uint8Array): Promise { + const stream = new Blob([bytes as BlobPart]) + .stream() + .pipeThrough(new CompressionStream("deflate")); + const out = new Uint8Array(await new Response(stream).arrayBuffer()); + return out; + } + + /** One version-2 envelope around a payload, as the Rust encoder emits it. */ + function compressedEnvelope(compression: number, payload: Uint8Array): Uint8Array { + return packr.pack({ version: 2, compression, payload }); + } + + const GOLDEN_FRAME = { + sequence: 7, + view_revision: 3, + base_view_revision: 2, + resume_token: null, + patch: { version: 1, width: 2, height: 1, runs: [] }, + }; + + it("decodes a deflated version-2 frame to the golden frame", async () => { + const envelope = compressedEnvelope(1, await deflate(GOLDEN_VIEW_PATCH)); + expect(await decodeViewPatchAsync(envelope)).toEqual(GOLDEN_FRAME); + }); + + it("decodes a version-2 frame with compression 0 (payload as-is)", async () => { + const envelope = compressedEnvelope(0, GOLDEN_VIEW_PATCH); + expect(await decodeViewPatchAsync(envelope)).toEqual(GOLDEN_FRAME); + }); + + it("decodes plain version-1 frames through the async entry", async () => { + expect(await decodeViewPatchAsync(GOLDEN_VIEW_PATCH)).toEqual(GOLDEN_FRAME); + }); + + it("rejects an unknown compression id", async () => { + const envelope = compressedEnvelope(9, await deflate(GOLDEN_VIEW_PATCH)); + expect(await decodeViewPatchAsync(envelope)).toBeNull(); + }); + + it("rejects a truncated DEFLATE stream", async () => { + const deflated = await deflate(GOLDEN_VIEW_PATCH); + const envelope = compressedEnvelope(1, deflated.slice(0, Math.floor(deflated.length / 2))); + expect(await decodeViewPatchAsync(envelope)).toBeNull(); + }); + + it("rejects a payload that inflates past the frame limit", async () => { + const big = new Uint8Array(1024 * 1024 + 1); + const envelope = compressedEnvelope(1, await deflate(big)); + expect(await decodeViewPatchAsync(envelope)).toBeNull(); + }); + + it("sync decode returns null for a version-2 envelope", async () => { + const envelope = compressedEnvelope(1, await deflate(GOLDEN_VIEW_PATCH)); + expect(decodeViewPatch(envelope)).toBeNull(); + }); +}); diff --git a/pkgs/id/web/src/screen-codec.ts b/pkgs/id/web/src/screen-codec.ts index 69fa3af3ed..a4586a9790 100644 --- a/pkgs/id/web/src/screen-codec.ts +++ b/pkgs/id/web/src/screen-codec.ts @@ -12,6 +12,16 @@ import type { ScreenPatch } from "./world-surface"; * 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. + * + * F12.11 phase 4 (#805) adds codec version 2 for compressed frames: + * `{version: 2, compression, payload}`, where `compression` 1 means + * the payload is the raw-DEFLATE (RFC 1951) of a version-1 frame and + * 0 means the payload is the version-1 frame as-is. The host sends + * version 2 only to a session that also offered `screen_compress`, + * and only when the complete compressed frame is smaller. Inflating + * needs `DecompressionStream`, so version-2 frames decode through + * the async `decodeViewPatchAsync`; the sync `decodeViewPatch` + * still handles version 1 only and returns null for version 2. */ export interface ViewPatchFrame { @@ -23,6 +33,11 @@ export interface ViewPatchFrame { } const SCREEN_CODEC_VERSION = 1; +/** Version of the compressed screen-patch envelope (F12.11 phase 4). */ +const SCREEN_CODEC_VERSION_COMPRESSED = 2; +/** Version-2 compression ids (id-core screen_codec). */ +const COMPRESSION_NONE = 0; +const COMPRESSION_DEFLATE = 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). */ @@ -99,6 +114,9 @@ function decodePatch(value: unknown): ScreenPatch | null { * 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. + * This sync entry handles version-1 frames only; compressed + * version-2 frames return null here and decode through + * `decodeViewPatchAsync`. */ export function decodeViewPatch(bytes: Uint8Array): ViewPatchFrame | null { if (bytes.length === 0 || bytes.length > MAX_SCREEN_FRAME_BYTES) return null; @@ -112,7 +130,82 @@ export function decodeViewPatch(bytes: Uint8Array): ViewPatchFrame | 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; + return decodeFrame(envelope.frame); +} + +/** + * Inflate raw-DEFLATE (RFC 1951) bytes, refusing output past the + * shared frame limit instead of buffering an unbounded stream. + */ +async function inflateRaw(bytes: Uint8Array): Promise { + let stream: ReadableStream; + try { + stream = new Blob([bytes as BlobPart]) + .stream() + .pipeThrough(new DecompressionStream("deflate")); + } catch { + return null; + } + const reader = stream.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (value === undefined) continue; + total += value.length; + if (total > MAX_SCREEN_FRAME_BYTES) return null; + chunks.push(value); + } + } catch { + return null; + } finally { + reader.releaseLock(); + } + const out = new Uint8Array(total); + let at = 0; + for (const chunk of chunks) { + out.set(chunk, at); + at += chunk.length; + } + return out; +} + +/** + * Decode one binary view-patch frame, plain (version 1) or + * compressed (version 2). Returns null for anything that is not + * exactly one well-formed frame — the caller treats null as "ask + * for a full view", never as data. + */ +export async function decodeViewPatchAsync(bytes: Uint8Array): Promise { + 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)) return null; + if (envelope.version === SCREEN_CODEC_VERSION) return decodeViewPatch(bytes); + if (envelope.version !== SCREEN_CODEC_VERSION_COMPRESSED) return null; + if (!hasExactlyKeys(envelope, ["version", "compression", "payload"])) return null; + if (envelope.compression !== COMPRESSION_NONE && envelope.compression !== COMPRESSION_DEFLATE) { + return null; + } + if (!(envelope.payload instanceof Uint8Array)) return null; + if (envelope.payload.length > MAX_SCREEN_FRAME_BYTES) return null; + const inner = + envelope.compression === COMPRESSION_NONE + ? envelope.payload + : await inflateRaw(envelope.payload); + if (!inner) return null; + return decodeViewPatch(inner); +} + +function decodeFrame(frame: unknown): ViewPatchFrame | null { if ( !isRecord(frame) || !hasExactlyKeys(frame, ["sequence", "view_revision", "base_view_revision", "resume_token", "patch"]) diff --git a/pkgs/id/web/src/world-program.test.ts b/pkgs/id/web/src/world-program.test.ts index 2e58bf0091..87a6da36f9 100644 --- a/pkgs/id/web/src/world-program.test.ts +++ b/pkgs/id/web/src/world-program.test.ts @@ -130,6 +130,7 @@ describe("program-only surface (#2146 phase 2)", () => { world: "arena", screen_patches: true, screen_msgpack: true, + screen_compress: true, device_input: { keys: 128, encoder: false, pointer: true, text_entry: "keyboard" }, }, ]); diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index b7809269bc..14f573645e 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -3,7 +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 { decodeViewPatchAsync } from "./screen-codec"; import { parseWorldSeed } from "./world-seed"; import { applyScreenPatch, renderWorldSurface, type ScreenPatch, type ScreenSurface } from "./world-surface"; @@ -237,21 +237,27 @@ function initWorld(): void { inviteOutput.hidden = false; }; - const receiveBinary = (bytes: Uint8Array) => { + const receiveBinary = async (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; - resumeToken = frame.resume_token; - return; + // applied exactly like a JSON view frame's patch. Compressed + // version-2 frames (#805) inflate through the async decoder. + // Anything undecodable or inapplicable falls back to asking for + // a full view, the same recovery as a JSON patch whose base + // mismatches. + try { + const frame = await decodeViewPatchAsync(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; + resumeToken = frame.resume_token; + return; + } } + } catch { + // Any failure below falls through to a full view. } sendViewport(true); }; @@ -673,6 +679,7 @@ function initWorld(): void { world: selectedWorld(), screen_patches: true, screen_msgpack: true, + screen_compress: true, resume_token: hasResumableScreen() ? resumeToken : undefined, device_input: { keys: 128, From 40cec1debe34861f6ce08169fa8cbd136005c67e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 11:35:47 +0000 Subject: [PATCH 2/5] fix(id-worlds): byte literal in BigScreen test program (#805) b"#" is a byte string (&[u8; 1]) while the else branch yields u8; the test target failed to compile (E0308). Use the b'#' byte literal. --- pkgs/id/crates/id-worlds/src/world_session/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkgs/id/crates/id-worlds/src/world_session/tests.rs b/pkgs/id/crates/id-worlds/src/world_session/tests.rs index ccf5933e22..2f7bf6e9c4 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/tests.rs @@ -4571,7 +4571,7 @@ mod tests { let mut line = String::with_capacity(120); for col in 0..120 { let byte = if step >= 2 && row >= 47 { - b"#" + b'#' } else { ALPHABET[(row * 7 + col * 13) % ALPHABET.len()] }; From 118d2e50aa7049f56054613a48d7444ed5c99af6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 12:21:54 +0000 Subject: [PATCH 3/5] fix(id): sparse-redraw fixture is a count tick, not a full-line restyle (#805) The under-10% test failed at 80x24 (279/2487 bytes, 11.2%): a 29-cell status-line restyle is a dense change, and its minimum encoding already exceeds the bar (the 29-cell run alone is ~244 bytes against a 248-byte bar), so no encoder could meet it. The nominated typical case is a status count tick plus two scattered edits, which measures ~8% at 80x24. --- pkgs/id/crates/id-core/src/screen_codec.rs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/pkgs/id/crates/id-core/src/screen_codec.rs b/pkgs/id/crates/id-core/src/screen_codec.rs index 6f2c047259..92a3315900 100644 --- a/pkgs/id/crates/id-core/src/screen_codec.rs +++ b/pkgs/id/crates/id-core/src/screen_codec.rs @@ -694,18 +694,25 @@ mod tests { ScreenSurface::from_cells(width, height, cells).unwrap() } - /// A typical sparse redraw of a document screen: a rewritten status - /// line plus two scattered single-cell edits. + /// A typical sparse redraw of a document screen: a status count + /// tick (two cells on the last row) plus two scattered single-cell + /// edits. + /// + /// The count tick — not a full status-line rewrite — is the + /// nominated typical case. Restyling all 29 cells of the last row + /// is a dense change, and its minimum encoding already exceeds + /// the 10% bar at 80x24: the full-line restyle measures 279/2487 + /// bytes (11.2%), and even the 29-cell run alone is ~244 bytes + /// against a 248-byte bar, so no encoder could meet the bar for + /// it. A real status line redraw changes the count, not the + /// whole line. fn sparse_redraw(screen: &ScreenSurface) -> ScreenSurface { let width = usize::from(screen.width); let height = usize::from(screen.height); let mut cells = screen.cells.clone(); - let status = "-- status: 12 new messages --"; + // Status count ticks 12 -> 13: two cells on the last row. let row_start = (height - 1) * width; - for (offset, ch) in status.chars().enumerate() { - if offset >= width { - break; - } + for (offset, ch) in [(11_usize, '1'), (12_usize, '3')] { cells[row_start + offset] = ScreenCell { symbol: ch.to_string(), fg: 7, From 1f8c33512c8aaa62f993f5b9194b314eac5e2456 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 12:32:12 +0000 Subject: [PATCH 4/5] fix(id): measure the ratio at 120x50, not the unbuildable 200x60 (#805) Screen bounds are 120x50, so document_screen(200, 60) panics in from_cells; the 200x60 case could never run. 120x50 is the largest valid screen and the meaningful second size. --- pkgs/id/crates/id-core/src/screen_codec.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pkgs/id/crates/id-core/src/screen_codec.rs b/pkgs/id/crates/id-core/src/screen_codec.rs index 92a3315900..79d71dfae8 100644 --- a/pkgs/id/crates/id-core/src/screen_codec.rs +++ b/pkgs/id/crates/id-core/src/screen_codec.rs @@ -754,9 +754,11 @@ mod tests { // Oracle: the #805 acceptance as decided (design §7, Q2 option B): // complete logical View payload bytes, full snapshot and patch // encoded with the same negotiated version and codec, at 80x24 - // and 200x60. The F11.9 raw guest-frame sizes are a different - // layer and stay out of the ratio. - for (width, height) in [(80_usize, 24_usize), (200_usize, 60_usize)] { + // and at the largest valid screen, 120x50 (the screen bounds + // are 120x50, so the design's 200x60 cannot be constructed). + // The F11.9 raw guest-frame sizes are a different layer and + // stay out of the ratio. + for (width, height) in [(80_usize, 24_usize), (120_usize, 50_usize)] { let full = document_screen(width, height); let changed = sparse_redraw(&full); let blank = ScreenSurface::from_cells(width, height, vec![ From 625106db12c735c5209118c838b0d0acd7ea233c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 13:06:37 +0000 Subject: [PATCH 5/5] fix(id): drop unneeded mut on DEFLATE decoder (#805) --- pkgs/id/crates/id-core/src/screen_codec.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkgs/id/crates/id-core/src/screen_codec.rs b/pkgs/id/crates/id-core/src/screen_codec.rs index 79d71dfae8..38fc3fa1fe 100644 --- a/pkgs/id/crates/id-core/src/screen_codec.rs +++ b/pkgs/id/crates/id-core/src/screen_codec.rs @@ -254,7 +254,7 @@ fn decode_compressed_view_patch(bytes: &[u8]) -> Result Result, ScreenCodecError> { - let mut decoder = flate2::read::DeflateDecoder::new(payload); + let decoder = flate2::read::DeflateDecoder::new(payload); let mut out = Vec::new(); decoder .take(u64::try_from(MAX_SCREEN_FRAME_BYTES).unwrap_or(u64::MAX) + 1)