From c164e5055637c382111920d6214377abea0cd69a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 21 Nov 2026 06:20:24 -0600 Subject: [PATCH 1/5] feat(id): add versioned MessagePack screen codec --- pkgs/id/Cargo.lock | 1 + pkgs/id/crates/id-core/Cargo.toml | 3 +- pkgs/id/crates/id-core/src/lib.rs | 2 + pkgs/id/crates/id-core/src/screen_codec.rs | 75 +++++++++++++++++++ .../crates/id-core/src/world_presentation.rs | 57 ++++++++++++++ 5 files changed, 137 insertions(+), 1 deletion(-) create mode 100644 pkgs/id/crates/id-core/src/screen_codec.rs diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index f1bcdcc8b4..61a5e93114 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -4894,6 +4894,7 @@ dependencies = [ "proptest", "qrcode", "rand 0.10.3", + "rmp-serde", "rqrr", "serde", "serde_json", diff --git a/pkgs/id/crates/id-core/Cargo.toml b/pkgs/id/crates/id-core/Cargo.toml index c81587740a..1d7158e7fd 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 = [] +world = ["dep:rmp-serde"] sandbox = [] web = ["dep:qrcode"] test-utils = [] @@ -45,6 +45,7 @@ postcard = { version = "1", features = ["alloc"] } qrcode = { version = "0.14.1", default-features = false, optional = true } serde = { version = "1", features = ["derive"] } serde_json = "1" +rmp-serde = { version = "1", optional = true } tempfile = "3" thiserror = "2" tokio = { version = "1", features = ["full"] } diff --git a/pkgs/id/crates/id-core/src/lib.rs b/pkgs/id/crates/id-core/src/lib.rs index 6aafef241a..81618f9743 100644 --- a/pkgs/id/crates/id-core/src/lib.rs +++ b/pkgs/id/crates/id-core/src/lib.rs @@ -69,6 +69,8 @@ pub mod test_forgeries; pub mod petname; #[cfg(feature = "world")] pub mod world_presentation; +#[cfg(feature = "world")] +pub mod screen_codec; #[cfg(feature = "web")] pub mod qr; diff --git a/pkgs/id/crates/id-core/src/screen_codec.rs b/pkgs/id/crates/id-core/src/screen_codec.rs new file mode 100644 index 0000000000..603051292a --- /dev/null +++ b/pkgs/id/crates/id-core/src/screen_codec.rs @@ -0,0 +1,75 @@ +//! Versioned MessagePack encoding for the transport-neutral F12.11 screen patch. + +use std::io::Cursor; + +use serde::{Deserialize, Serialize}; + +use crate::world_presentation::ScreenPatch; + +/// Version of the MessagePack screen-patch wire representation. +pub const SCREEN_CODEC_VERSION: u8 = 1; +/// Maximum complete logical frame size, matching the session frame limit. +pub const MAX_SCREEN_FRAME_BYTES: usize = 1024 * 1024; + +#[derive(Serialize)] +#[serde(deny_unknown_fields)] +struct VersionedPatch<'a> { + version: u8, + #[serde(borrow)] + patch: &'a ScreenPatch, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct OwnedVersionedPatch { + version: u8, + patch: ScreenPatch, +} + +/// Errors produced while encoding or decoding a versioned screen patch. +#[derive(Debug, thiserror::Error)] +pub enum ScreenCodecError { + /// The encoded frame exceeds the shared session frame limit. + #[error("screen frame exceeds the 1 MiB limit")] + TooLarge, + /// The payload is not exactly one valid MessagePack value. + #[error("invalid MessagePack screen frame: {0}")] + Invalid(#[from] rmp_serde::decode::Error), + /// A serialization error occurred while encoding a screen patch. + #[error("could not encode MessagePack screen frame: {0}")] + Encode(#[from] rmp_serde::encode::Error), + /// The frame uses a codec version this implementation does not support. + #[error("unsupported screen codec version {0}")] + UnsupportedVersion(u8), + /// The MessagePack value has trailing bytes after its one complete value. + #[error("trailing bytes after screen frame")] + TrailingBytes, +} + +/// Encodes a patch as one versioned MessagePack value. +pub fn encode_patch(patch: &ScreenPatch) -> Result, ScreenCodecError> { + let bytes = rmp_serde::to_vec_named(&VersionedPatch { + version: SCREEN_CODEC_VERSION, + patch, + })?; + if bytes.len() > MAX_SCREEN_FRAME_BYTES { + return Err(ScreenCodecError::TooLarge); + } + Ok(bytes) +} + +/// Decodes one bounded, versioned MessagePack patch value. +pub fn decode_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 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 { + return Err(ScreenCodecError::UnsupportedVersion(frame.version)); + } + Ok(frame.patch) +} diff --git a/pkgs/id/crates/id-core/src/world_presentation.rs b/pkgs/id/crates/id-core/src/world_presentation.rs index 132573f822..3c0f8a3967 100644 --- a/pkgs/id/crates/id-core/src/world_presentation.rs +++ b/pkgs/id/crates/id-core/src/world_presentation.rs @@ -1502,6 +1502,63 @@ mod tests { ScreenSurface::from_cells(width, height, vec![cell(fill); width * height]).unwrap() } + fn codec_patch() -> ScreenPatch { + ScreenPatch { + version: 1, + width: 2, + height: 1, + runs: Vec::new(), + } + } + + #[test] + fn screen_codec_matches_versioned_messagepack_golden_vector() { + let golden = [ + 0x82, 0xa7, b'v', b'e', b'r', b's', b'i', b'o', b'n', 0x01, 0xa5, b'p', b'a', + b't', b'c', b'h', 0x84, 0xa7, b'v', b'e', b'r', b's', b'i', b'o', b'n', 0x01, + 0xa5, b'w', b'i', b'd', b't', b'h', 0x02, 0xa6, b'h', b'e', b'i', b'g', b'h', + b't', 0x01, 0xa4, b'r', b'u', b'n', b's', 0x90, + ]; + + let encoded = crate::screen_codec::encode_patch(&codec_patch()).unwrap(); + assert_eq!(encoded, golden); + assert_eq!(crate::screen_codec::decode_patch(&golden).unwrap(), codec_patch()); + } + + #[test] + fn screen_codec_rejects_unsupported_version_and_malformed_frames() { + use crate::screen_codec::{ScreenCodecError, decode_patch}; + + let mut unsupported = crate::screen_codec::encode_patch(&codec_patch()).unwrap(); + unsupported[9] = 2; + assert!(matches!( + decode_patch(&unsupported), + Err(ScreenCodecError::UnsupportedVersion(2)) + )); + assert!(matches!( + decode_patch(&[0xc1]), + Err(ScreenCodecError::Invalid(_)) + )); + + let mut trailing = crate::screen_codec::encode_patch(&codec_patch()).unwrap(); + trailing.push(0xc0); + assert!(matches!( + decode_patch(&trailing), + Err(ScreenCodecError::TrailingBytes) + )); + } + + #[test] + fn screen_codec_rejects_frames_over_one_mibibyte() { + use crate::screen_codec::{MAX_SCREEN_FRAME_BYTES, ScreenCodecError, decode_patch}; + + let oversized = vec![0; MAX_SCREEN_FRAME_BYTES + 1]; + assert!(matches!( + decode_patch(&oversized), + Err(ScreenCodecError::TooLarge) + )); + } + #[test] fn test_rust_screen_presenter_matches_the_shared_web_parity_corpus() { let corpus: ScreenCellParityCorpus = serde_json::from_str(include_str!( From 0ca23c9a54f3bea3eba445f922bd030f1dc88f06 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 21 Nov 2026 07:35:53 -0600 Subject: [PATCH 2/5] feat(id): negotiate binary screen patches --- doc/2026-11-01_design_id805.md | 23 ++++ ...Z_design_screenpatch_binary_negotiation.md | 19 +++ pkgs/id/contract/shell-contract.v1.json | 34 +++++- pkgs/id/crates/id-cli/src/commands/serve.rs | 6 +- pkgs/id/crates/id-core/src/screen_codec.rs | 95 +++++++++++++++ .../crates/id-core/src/world_presentation.rs | 95 ++++++++++++++- pkgs/id/crates/id-web/src/world_ws.rs | 34 +++++- .../id-worlds/src/shell_contract/tests.rs | 16 ++- pkgs/id/crates/id-worlds/src/world_net.rs | 38 +++++- .../crates/id-worlds/src/world_session/mod.rs | 2 + .../src/world_session/session_core.rs | 4 + .../id-worlds/src/world_session/tests.rs | 115 +++++++++++++++++- .../id-worlds/src/world_session/types.rs | 13 ++ .../id-worlds/src/world_session/view.rs | 43 +++++-- pkgs/id/crates/id-worlds/src/world_ssh.rs | 18 ++- pkgs/id/web/src/world-contract.test.ts | 41 +++++++ pkgs/id/web/src/world-program.test.ts | 12 +- pkgs/id/web/src/world-wire.test.ts | 83 +++++++++++++ pkgs/id/web/src/world-wire.ts | 46 +++++++ pkgs/id/web/src/world.ts | 56 +++++++-- 20 files changed, 760 insertions(+), 33 deletions(-) create mode 100644 doc/2026-11-21T13-10-15Z_design_screenpatch_binary_negotiation/2026-11-21T13-10-15Z_design_screenpatch_binary_negotiation.md create mode 100644 pkgs/id/web/src/world-wire.test.ts create mode 100644 pkgs/id/web/src/world-wire.ts diff --git a/doc/2026-11-01_design_id805.md b/doc/2026-11-01_design_id805.md index 771ac2ee02..f5d25bb730 100644 --- a/doc/2026-11-01_design_id805.md +++ b/doc/2026-11-01_design_id805.md @@ -401,3 +401,26 @@ repeatable size/CPU measurements in phases 4–5. `pkgs/id/src/web/world_ws.rs`, and `pkgs/id/web/src/world-surface.ts`. - `pkgs/id/contract/shell-contract.v1.json`. - [F12.11 roadmap entry](../.opencode/plans/phase-12-platform-flexibility.md#L50). + +--- + +## 2026-11-21T12:34:42Z Clarification: Q1 and Q2 answered; phase 3 unblocked + +The answers were recorded on [issue #805](https://github.com/developing-today/code/issues/805#issuecomment-7062344563): + +- **Q1: option B.** F11.12 gates journaled frame kinds. Binary screen encoding + is a versioned v2 representation of the existing ephemeral `View`, on a + separately negotiated route, with no journal entry. V1 JSON stays. The shell + contract wording must say the gate applies to journaled kinds only. +- **Q2: option B.** The future under-10% measurement uses the complete logical + `View` payload passed to `SessionIo`, patch metadata included and outer + transport framing excluded, compared with a full snapshot in the same + protocol version and codec. F11.9 raw sizes are reported separately. + +This clears the phase-3 gate; it does not pull compression or the size +measurement into phase 3. The implementation adds a distinct v2 route while +leaving v1 text JSON unchanged. Phases 1 and 2 are already represented in the +current Rust code (revisioned JSON patches and retained resume baselines), +despite the older path references and open questions above. Phase 3 must keep +the event `sequence`, view revisions, full-view fallback, and join +authorization semantics intact. diff --git a/doc/2026-11-21T13-10-15Z_design_screenpatch_binary_negotiation/2026-11-21T13-10-15Z_design_screenpatch_binary_negotiation.md b/doc/2026-11-21T13-10-15Z_design_screenpatch_binary_negotiation/2026-11-21T13-10-15Z_design_screenpatch_binary_negotiation.md new file mode 100644 index 0000000000..245ed5fcab --- /dev/null +++ b/doc/2026-11-21T13-10-15Z_design_screenpatch_binary_negotiation/2026-11-21T13-10-15Z_design_screenpatch_binary_negotiation.md @@ -0,0 +1,19 @@ +# Negotiated binary ScreenPatch v2 completion + +This note records the design for completing the in-progress #12242 transport slice in a returning implementation session. The governing requirements remain [design_id805](../../../doc/2026-11-01_design_id805.md) §§3, 5–6 and issue [#12242](https://github.com/developing-today/code/issues/12242); this note narrows how the existing v2 transport makes binary delivery explicit and recoverable. + +## Intent + +Use the versioned `/ws/world/2`, `/id-world/2`, and `id-world/2` transports for ephemeral MessagePack ScreenPatch frames while preserving v1 text-JSON behavior and authorization. Binary delivery must be an explicit client opt-in, not an accidental consequence of reaching a v2 route. Preserve sequence, view-revision, event-cursor, and resume-token semantics; compression and bandwidth measurement remain out of scope. + +## Decisions + +- Add an optional `binary_view_patches` boolean to the join frame. A server sends binary ScreenPatch frames only when this flag and the existing `screen_patches` flag are both true and the selected transport supports binary. Missing or false means text-JSON full views/patches. The versioned route remains a transport-version choice; the join field negotiates this optional representation. +- Keep the join capability as the sole authorization check. Resume tokens remain cursors, not credentials; an absent, stale, foreign, or malformed token results in a full view. +- The browser opts in on the v2 WebSocket route, retains the most recently applied view's resume token, and includes it on reconnect. A binary decode failure requests a fresh viewport/full-view resynchronization. +- Bump the additive shell-contract revision and document the new join field plus the `version` field in the binary envelope. V1 clients remain compatible because the field is optional and omitted by them. +- Keep SSH and Iroh adapters' legacy text framing unless their negotiated adapter implements byte-safe framing; the existing v2 transport registration may advertise support only where the adapter supports it. + +## Completion checks + +Add Rust coverage for the join gate and codec rejection, plus TypeScript coverage for the shared binary golden vector, resume-token round-trip, and decode-error resynchronization. Run the focused Rust and browser checks and record exact outcomes in the task checkpoint. Do not alter patch/resume-token semantics or add compression. diff --git a/pkgs/id/contract/shell-contract.v1.json b/pkgs/id/contract/shell-contract.v1.json index f2abfd3e77..7061d05f2d 100644 --- a/pkgs/id/contract/shell-contract.v1.json +++ b/pkgs/id/contract/shell-contract.v1.json @@ -1,8 +1,8 @@ { "contract": "id-shell", "version": 1, - "revision": 11, - "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.", + "revision": 12, + "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. Protocol v2 is a separate transport version for ephemeral binary screen-view patches only; it does not change the journaled frame kinds or v1 JSON behavior.", "max_frame_bytes": 1048576, "routing_fields": ["world"], "transports": { @@ -22,6 +22,35 @@ "session": "one SSH session channel running the exec command" } }, + "protocol_v2": { + "client_frames": "Same text-JSON client frames and authorization rules as v1; binary_view_patches on join explicitly opts into binary ScreenPatch delivery and requires screen_patches.", + "server_view_patch": { + "class": "ephemeral", + "encoding": "versioned-messagepack", + "codec_version": 1, + "fields": ["version", "type", "sequence", "view_revision", "base_view_revision", "resume_token?", "patch"], + "compatibility": "Only selected view patches are binary when the join explicitly opts in with binary_view_patches and screen_patches; full views and all other server frames remain text JSON. The v1 transports and payloads are unchanged. Browser clients fall back to the v1 WebSocket path when the v2 route is unavailable before opening.", + "compression": "not negotiated" + }, + "transports": { + "iroh": { + "alpn": "/id-world/2", + "envelope": "u32be-length-prefix", + "session": "one bidirectional QUIC stream" + }, + "websocket": { + "path": "/ws/world/2", + "envelope": "text-message-controls-and-full-views;binary-message-view-patches", + "session": "one WebSocket connection" + }, + "ssh-exec": { + "command": "id-world/2", + "envelope": "u32be-length-prefix", + "session": "one SSH session channel running the exec command" + } + }, + "gate": "F11.12 applies to journaled frame kinds; ephemeral presentation view patches may use this versioned transport." + }, "phases": { "opening": "The session's first frame. It may carry the `world` routing field; absent means the host's default world.", "query": "After an opening query frame: further query frames, or a join.", @@ -45,6 +74,7 @@ "capability": { "type": "string", "max_bytes": 256 }, "after": "u64?", "screen_patches": { "type": "bool", "optional": true, "nullable": false }, + "binary_view_patches": { "type": "bool", "optional": true, "nullable": false }, "agent_profile": { "type": "bool", "optional": true, "nullable": false }, "resume_token": { "type": "string", "optional": true, "nullable": true, "max_bytes": 64 } } diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index 4abe578ef6..b1ae092239 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -1796,7 +1796,11 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { #[cfg(feature = "world")] let router_builder = match (world_hub.as_ref(), world_protocol) { (Some(hub), Some(world_protocol)) => router_builder - .accept(id_worlds::world_net::WORLD_ALPN, world_protocol) + .accept(id_worlds::world_net::WORLD_ALPN, world_protocol.clone()) + .accept( + id_worlds::world_net::WORLD_ALPN_V2, + world_protocol.with_binary_view_patches(), + ) .accept( id_worlds::world_replication_net::REPLICATION_ALPN, id_worlds::world_replication_net::WorldReplicationProtocol::new( diff --git a/pkgs/id/crates/id-core/src/screen_codec.rs b/pkgs/id/crates/id-core/src/screen_codec.rs index 603051292a..e334f46eba 100644 --- a/pkgs/id/crates/id-core/src/screen_codec.rs +++ b/pkgs/id/crates/id-core/src/screen_codec.rs @@ -6,6 +6,21 @@ use serde::{Deserialize, Serialize}; use crate::world_presentation::ScreenPatch; +/// The logical contents of a binary `view` patch frame. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +pub struct ScreenPatchFrame { + /// Existing world-event cursor; independent of screen revisions. + pub sequence: u64, + /// Revision produced by applying this patch. + pub view_revision: u64, + /// Exact screen revision this patch applies to. + pub base_view_revision: u64, + /// Optional token for resuming from this target revision. + pub resume_token: Option, + /// Canonical transport-neutral screen delta. + pub patch: ScreenPatch, +} + /// Version of the MessagePack screen-patch wire representation. pub const SCREEN_CODEC_VERSION: u8 = 1; /// Maximum complete logical frame size, matching the session frame limit. @@ -26,6 +41,34 @@ struct OwnedVersionedPatch { patch: ScreenPatch, } +#[derive(Serialize)] +#[serde(deny_unknown_fields)] +struct VersionedViewPatch<'a> { + version: u8, + #[serde(rename = "type")] + frame_type: &'static str, + sequence: u64, + view_revision: u64, + base_view_revision: u64, + #[serde(skip_serializing_if = "Option::is_none")] + resume_token: Option<&'a str>, + patch: &'a ScreenPatch, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct OwnedVersionedViewPatch { + version: u8, + #[serde(rename = "type")] + frame_type: String, + sequence: u64, + view_revision: u64, + base_view_revision: u64, + #[serde(default)] + resume_token: Option, + patch: ScreenPatch, +} + /// Errors produced while encoding or decoding a versioned screen patch. #[derive(Debug, thiserror::Error)] pub enum ScreenCodecError { @@ -44,6 +87,9 @@ pub enum ScreenCodecError { /// The MessagePack value has trailing bytes after its one complete value. #[error("trailing bytes after screen frame")] TrailingBytes, + /// The binary frame is not the supported `view` frame kind. + #[error("invalid binary screen frame type")] + InvalidFrameType, } /// Encodes a patch as one versioned MessagePack value. @@ -73,3 +119,52 @@ pub fn decode_patch(bytes: &[u8]) -> Result { } Ok(frame.patch) } + +/// Encodes a complete binary session view-patch frame, including the event +/// cursor and screen revision metadata needed to safely apply the patch. +pub fn encode_view_patch( + sequence: u64, + view_revision: u64, + base_view_revision: u64, + resume_token: Option<&str>, + patch: &ScreenPatch, +) -> Result, ScreenCodecError> { + let bytes = rmp_serde::to_vec_named(&VersionedViewPatch { + version: SCREEN_CODEC_VERSION, + frame_type: "view", + sequence, + view_revision, + base_view_revision, + resume_token, + patch, + })?; + if bytes.len() > MAX_SCREEN_FRAME_BYTES { + return Err(ScreenCodecError::TooLarge); + } + Ok(bytes) +} + +/// Decodes one bounded binary session view-patch frame. +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 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 { + return Err(ScreenCodecError::UnsupportedVersion(frame.version)); + } + if frame.frame_type != "view" { + return Err(ScreenCodecError::InvalidFrameType); + } + Ok(ScreenPatchFrame { + sequence: frame.sequence, + view_revision: frame.view_revision, + base_view_revision: frame.base_view_revision, + resume_token: frame.resume_token, + patch: frame.patch, + }) +} diff --git a/pkgs/id/crates/id-core/src/world_presentation.rs b/pkgs/id/crates/id-core/src/world_presentation.rs index 3c0f8a3967..d458bc391c 100644 --- a/pkgs/id/crates/id-core/src/world_presentation.rs +++ b/pkgs/id/crates/id-core/src/world_presentation.rs @@ -1514,15 +1514,100 @@ mod tests { #[test] fn screen_codec_matches_versioned_messagepack_golden_vector() { let golden = [ - 0x82, 0xa7, b'v', b'e', b'r', b's', b'i', b'o', b'n', 0x01, 0xa5, b'p', b'a', - b't', b'c', b'h', 0x84, 0xa7, b'v', b'e', b'r', b's', b'i', b'o', b'n', 0x01, - 0xa5, b'w', b'i', b'd', b't', b'h', 0x02, 0xa6, b'h', b'e', b'i', b'g', b'h', - b't', 0x01, 0xa4, b'r', b'u', b'n', b's', 0x90, + 0x82, 0xa7, b'v', b'e', b'r', b's', b'i', b'o', b'n', 0x01, 0xa5, b'p', b'a', b't', + b'c', b'h', 0x84, 0xa7, b'v', b'e', b'r', b's', b'i', b'o', b'n', 0x01, 0xa5, b'w', + b'i', b'd', b't', b'h', 0x02, 0xa6, b'h', b'e', b'i', b'g', b'h', b't', 0x01, 0xa4, + b'r', b'u', b'n', b's', 0x90, ]; let encoded = crate::screen_codec::encode_patch(&codec_patch()).unwrap(); assert_eq!(encoded, golden); - assert_eq!(crate::screen_codec::decode_patch(&golden).unwrap(), codec_patch()); + assert_eq!( + crate::screen_codec::decode_patch(&golden).unwrap(), + codec_patch() + ); + } + + #[test] + fn screen_codec_round_trips_complete_view_patch_metadata() { + let patch = codec_patch(); + let encoded = + crate::screen_codec::encode_view_patch(41, 9, 8, Some("resume-9"), &patch).unwrap(); + let decoded = crate::screen_codec::decode_view_patch(&encoded).unwrap(); + assert_eq!(decoded.sequence, 41); + assert_eq!(decoded.view_revision, 9); + assert_eq!(decoded.base_view_revision, 8); + assert_eq!(decoded.resume_token.as_deref(), Some("resume-9")); + assert_eq!(decoded.patch, patch); + } + + #[test] + fn screen_codec_view_patch_matches_cross_language_golden_vector() { + let golden = [ + 0x87, 0xa7, b'v', b'e', b'r', b's', b'i', b'o', b'n', 0x01, 0xa4, b't', b'y', b'p', + b'e', 0xa4, b'v', b'i', b'e', b'w', 0xa8, b's', b'e', b'q', b'u', b'e', b'n', b'c', + b'e', 0x29, 0xad, b'v', b'i', b'e', b'w', b'_', b'r', b'e', b'v', b'i', b's', b'i', + b'o', b'n', 0x09, 0xb2, b'b', b'a', b's', b'e', b'_', b'v', b'i', b'e', b'w', b'_', + b'r', b'e', b'v', b'i', b's', b'i', b'o', b'n', 0x08, 0xac, b'r', b'e', b's', b'u', + b'm', b'e', b'_', b't', b'o', b'k', b'e', b'n', 0xa8, b'r', b'e', b's', b'u', b'm', + b'e', b'-', b'9', 0xa5, b'p', b'a', b't', b'c', b'h', 0x84, 0xa7, b'v', b'e', b'r', + b's', b'i', b'o', b'n', 0x01, 0xa5, b'w', b'i', b'd', b't', b'h', 0x02, 0xa6, b'h', + b'e', b'i', b'g', b'h', b't', 0x01, 0xa4, b'r', b'u', b'n', b's', 0x90, + ]; + let encoded = + crate::screen_codec::encode_view_patch(41, 9, 8, Some("resume-9"), &codec_patch()) + .unwrap(); + assert_eq!(encoded, golden); + assert_eq!( + crate::screen_codec::decode_view_patch(&golden) + .unwrap() + .sequence, + 41 + ); + } + + #[test] + fn screen_codec_view_patch_rejects_unsupported_malformed_and_trailing_frames() { + use crate::screen_codec::{MAX_SCREEN_FRAME_BYTES, ScreenCodecError, decode_view_patch}; + + let mut unsupported = + crate::screen_codec::encode_view_patch(41, 9, 8, Some("resume-9"), &codec_patch()) + .unwrap(); + unsupported[9] = 2; + assert!(matches!( + decode_view_patch(&unsupported), + Err(ScreenCodecError::UnsupportedVersion(2)) + )); + + let mut wrong_type = + crate::screen_codec::encode_view_patch(41, 9, 8, Some("resume-9"), &codec_patch()) + .unwrap(); + // The key `type` is followed by the four-byte value `view`. + wrong_type[16] = b'e'; + assert!(matches!( + decode_view_patch(&wrong_type), + Err(ScreenCodecError::InvalidFrameType) + )); + + assert!(matches!( + decode_view_patch(&[0xc1]), + Err(ScreenCodecError::Invalid(_)) + )); + + let mut trailing = + crate::screen_codec::encode_view_patch(41, 9, 8, Some("resume-9"), &codec_patch()) + .unwrap(); + trailing.push(0xc0); + assert!(matches!( + decode_view_patch(&trailing), + Err(ScreenCodecError::TrailingBytes) + )); + + let oversized = vec![0; MAX_SCREEN_FRAME_BYTES + 1]; + assert!(matches!( + decode_view_patch(&oversized), + Err(ScreenCodecError::TooLarge) + )); } #[test] diff --git a/pkgs/id/crates/id-web/src/world_ws.rs b/pkgs/id/crates/id-web/src/world_ws.rs index b293875f22..211d1be58f 100644 --- a/pkgs/id/crates/id-web/src/world_ws.rs +++ b/pkgs/id/crates/id-web/src/world_ws.rs @@ -58,7 +58,9 @@ pub fn world_routes() -> axum::Router { /// server (or served side by side) without either seeing the /// other's channel. pub fn world_routes_at(socket: &str) -> axum::Router { - world_http_routes().route(socket, axum::routing::get(handler)) + world_http_routes() + .route(socket, axum::routing::get(handler)) + .route(&format!("{socket}/2"), axum::routing::get(handler_v2)) } /// The shared world HTTP surface - invite, metrics, directory and @@ -654,13 +656,29 @@ async fn invite_handler( } async fn handler(State(state): State, ws: WebSocketUpgrade) -> Response { + handler_with_version(state, ws, false).await +} + +async fn handler_v2(State(state): State, ws: WebSocketUpgrade) -> Response { + handler_with_version(state, ws, true).await +} + +async fn handler_with_version( + state: WorldWebState, + ws: WebSocketUpgrade, + binary_view_patches: bool, +) -> Response { let Some(hub) = state.hub else { return StatusCode::NOT_FOUND.into_response(); }; ws.max_message_size(MAX_FRAME_BYTES) .on_upgrade(move |socket| async move { let (sender, receiver) = socket.split(); - let mut io = WsIo { sender, receiver }; + let mut io = WsIo { + sender, + receiver, + binary_view_patches, + }; run_session(&hub, &mut io).await; }) } @@ -668,6 +686,7 @@ async fn handler(State(state): State, ws: WebSocketUpgrade) -> Re struct WsIo { sender: SplitSink, receiver: SplitStream, + binary_view_patches: bool, } impl SessionIo for WsIo { @@ -693,6 +712,17 @@ impl SessionIo for WsIo { async fn send(&mut self, frame: String) -> bool { self.sender.send(Message::Text(frame.into())).await.is_ok() } + + fn binary_view_patches(&self) -> bool { + self.binary_view_patches + } + + async fn send_binary(&mut self, frame: Vec) -> bool { + self.sender + .send(Message::Binary(frame.into())) + .await + .is_ok() + } } #[cfg(test)] 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 afe0a8dfee..3af6d89e74 100644 --- a/pkgs/id/crates/id-worlds/src/shell_contract/tests.rs +++ b/pkgs/id/crates/id-worlds/src/shell_contract/tests.rs @@ -137,6 +137,18 @@ fn the_embedded_contract_is_version_one_and_matches_the_host_limits() { assert_eq!(contract.redacted_keys, ["seed"]); } +#[test] +fn protocol_v2_adds_only_versioned_ephemeral_binary_view_patches() { + let contract: serde_json::Value = serde_json::from_str(SHELL_CONTRACT_JSON).unwrap(); + let v2 = &contract["protocol_v2"]; + assert_eq!(v2["transports"]["iroh"]["alpn"], "/id-world/2"); + assert_eq!(v2["transports"]["websocket"]["path"], "/ws/world/2"); + assert_eq!(v2["transports"]["ssh-exec"]["command"], "id-world/2"); + assert_eq!(v2["server_view_patch"]["class"], "ephemeral"); + assert_eq!(v2["server_view_patch"]["codec_version"], 1); + assert_eq!(v2["server_view_patch"]["compression"], "not negotiated"); +} + #[test] fn every_client_frame_variant_is_in_the_contract_and_nothing_else_is() { let named: BTreeSet = contract().client_frames.keys().cloned().collect(); @@ -606,7 +618,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, 11); + assert_eq!(contract.revision, 12); assert_eq!(contract.client_frames["pointer"].class, FrameClass::Event); assert_eq!(contract.client_frames["hover"].class, FrameClass::Ephemeral); assert_eq!( @@ -719,7 +731,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, 11); + assert_eq!(contract.revision, 12); assert_eq!( contract.client_frames["screen_subscribe"].class, FrameClass::Ephemeral diff --git a/pkgs/id/crates/id-worlds/src/world_net.rs b/pkgs/id/crates/id-worlds/src/world_net.rs index 656d807015..76ef6983c6 100644 --- a/pkgs/id/crates/id-worlds/src/world_net.rs +++ b/pkgs/id/crates/id-worlds/src/world_net.rs @@ -86,6 +86,8 @@ use crate::world_session::{ /// ALPN for world sessions. Within version 1 frames may gain fields and /// variants; removing or changing one needs `/id-world/2`. pub const WORLD_ALPN: &[u8] = b"/id-world/1"; +/// Versioned world-session transport for negotiated binary view patches. +pub const WORLD_ALPN_V2: &[u8] = b"/id-world/2"; /// Public module state returned by a world's `info` frame. #[derive(Clone, Debug, PartialEq, Eq)] @@ -117,6 +119,7 @@ pub use crate::frames::{read_frame, write_frame}; #[derive(Clone, Debug)] pub struct WorldProtocol { hub: WorldHub, + binary_view_patches: bool, /// The shared #2244 P0-A abuse evaluator: one bucket set per remote /// endpoint, shared across every stream and connection that /// endpoint opens, plus the counter registry operators read via @@ -142,6 +145,19 @@ impl WorldProtocol { Self::with_local_node(hub, [0; 32]) } + /// Serve the explicitly versioned protocol with binary screen patches. + #[must_use] + pub fn new_v2(hub: impl Into) -> Self { + Self::new(hub).with_binary_view_patches() + } + + /// Use binary view-patch frames for a separately registered v2 ALPN. + #[must_use] + pub fn with_binary_view_patches(mut self) -> Self { + self.binary_view_patches = true; + self + } + /// Like [`WorldProtocol::new`], with the serving node's id recorded /// as the local side of every counter-registry row. The zero id from /// `new` means "this serving node"; rows are keyed by remote @@ -196,6 +212,7 @@ impl WorldProtocol { } Self { hub: hub.into(), + binary_view_patches: false, abuse: Arc::new(Mutex::new(evaluator)), connection_cap_refusals: Arc::new(AtomicU64::new(0)), } @@ -356,9 +373,10 @@ impl ProtocolHandler for WorldProtocol { }; let hub = self.hub.clone(); let abuse = Arc::clone(&self.abuse); + let binary_view_patches = self.binary_view_patches; sessions.spawn(async move { let _permit = permit; - let mut io = StreamIo::new(send, recv, abuse, remote_endpoint); + let mut io = StreamIo::new(send, recv, abuse, remote_endpoint, binary_view_patches); run_session(&hub, &mut io).await; io.finish(); }); @@ -380,6 +398,7 @@ struct StreamIo { abuse: Arc>, remote: AbuseEndpointId, authorized: Arc, + binary_view_patches: bool, } impl StreamIo { @@ -388,6 +407,7 @@ impl StreamIo { mut recv: RecvStream, abuse: Arc>, remote: AbuseEndpointId, + binary_view_patches: bool, ) -> Self { let (tx, frames) = mpsc::channel(8); let reader_abuse = Arc::clone(&abuse); @@ -442,6 +462,7 @@ impl StreamIo { abuse, remote, authorized: reader_authorized, + binary_view_patches, } } @@ -478,6 +499,21 @@ impl SessionIo for StreamIo { write_frame(&mut self.send, frame.as_bytes()).await.is_ok() } + fn binary_view_patches(&self) -> bool { + self.binary_view_patches + } + + async fn send_binary(&mut self, frame: Vec) -> bool { + let admitted = charge_frame_with_backpressure( + &self.abuse, + self.remote, + self.authorized.load(Ordering::Acquire), + frame.len(), + ) + .await; + admitted && write_frame(&mut self.send, &frame).await.is_ok() + } + fn mark_authorized(&mut self) { self.authorized.store(true, Ordering::Release); } 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 01c90865cd..d7830d23f1 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/mod.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/mod.rs @@ -1122,6 +1122,7 @@ async fn joined( token: JoinCapability, after: Option, screen_patches: bool, + binary_view_patches: bool, resume_token: Option, agent_profile: bool, documents_store: Option, @@ -1146,6 +1147,7 @@ async fn joined( let mut viewport = None; let mut view_state = ViewRevisionState::default(); view_state.participant = participant_id; + view_state.binary_view_patches = binary_view_patches && screen_patches; // Agent profile (contract revision 11, #6300 section 4.2): the join // flag is the capability advertisement; it changes only what this // session is sent (semantic diffs for its subscription), never its 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 4aea5f0f2f..89e72e3b2a 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 @@ -20,6 +20,7 @@ pub(crate) async fn run_world_session( capability, after, screen_patches, + binary_view_patches, resume_token, agent_profile, } => { @@ -34,6 +35,7 @@ pub(crate) async fn run_world_session( JoinCapability::from_wire(capability), after, screen_patches, + binary_view_patches, resume_token, agent_profile, documents_store, @@ -512,6 +514,7 @@ async fn query_session( capability, after, screen_patches, + binary_view_patches, resume_token, agent_profile, } => { @@ -526,6 +529,7 @@ async fn query_session( JoinCapability::from_wire(capability), after, screen_patches, + binary_view_patches, resume_token, agent_profile, documents_store.clone(), 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 8803b4d0c8..5e2081ab13 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/tests.rs @@ -26,6 +26,8 @@ mod tests { struct ChannelIo { inbound: mpsc::Receiver, outbound: mpsc::Sender, + binary_outbound: mpsc::Sender>, + binary_view_patches: bool, } impl SessionIo for ChannelIo { @@ -35,11 +37,18 @@ mod tests { async fn send(&mut self, frame: String) -> bool { self.outbound.send(frame).await.is_ok() } + fn binary_view_patches(&self) -> bool { + self.binary_view_patches + } + async fn send_binary(&mut self, frame: Vec) -> bool { + self.binary_view_patches && self.binary_outbound.send(frame).await.is_ok() + } } struct Peer { to_server: mpsc::Sender, from_server: mpsc::Receiver, + from_server_binary: mpsc::Receiver>, task: tokio::task::JoinHandle<()>, } @@ -49,15 +58,34 @@ mod tests { } fn connect_hub(hub: WorldHub, config: SessionConfig) -> Self { + Self::connect_hub_with_binary(hub, config, false) + } + + fn connect_with_binary(service: WorldService, config: SessionConfig) -> Self { + Self::connect_hub_with_binary(WorldHub::single(service), config, true) + } + + fn connect_hub_with_binary( + hub: WorldHub, + config: SessionConfig, + binary_view_patches: bool, + ) -> Self { let (to_server, inbound) = mpsc::channel(16); let (outbound, from_server) = mpsc::channel(64); + let (binary_outbound, from_server_binary) = mpsc::channel(64); let task = tokio::spawn(async move { - let mut io = ChannelIo { inbound, outbound }; + let mut io = ChannelIo { + inbound, + outbound, + binary_outbound, + binary_view_patches, + }; run_session_with(&hub, &mut io, config).await; }); Self { to_server, from_server, + from_server_binary, task, } } @@ -85,6 +113,12 @@ mod tests { .expect("timed out waiting for a server frame") } + async fn next_binary(&mut self) -> Option> { + tokio::time::timeout(Duration::from_mins(1), self.from_server_binary.recv()) + .await + .expect("timed out waiting for a binary server frame") + } + async fn next(&mut self) -> Option { self.next_text() .await @@ -95,10 +129,12 @@ mod tests { let Self { to_server, from_server, + from_server_binary, task, } = self; let _ = to_server.send(Inbound::Closed).await; drop(from_server); + drop(from_server_binary); task.await.unwrap(); } } @@ -4015,6 +4051,82 @@ mod tests { ); } + #[tokio::test] + async fn negotiated_binary_v2_sends_catch_up_patch_after_text_snapshot() { + let step = Arc::new(AtomicU64::new(0)); + let world = WorldHandle::spawn_with_program( + WorldCore::new("lobby", WorldLimits::default()).unwrap(), + Box::new(StepScreen(Arc::clone(&step))), + ); + let service = WorldService::new(world.clone(), None); + let (_, capability) = world + .issue("player".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + + let mut initial = Peer::connect(service.clone(), SessionConfig::default()); + initial + .say(serde_json::json!({ + "type": "join", + "capability": capability.expose(), + "screen_patches": true, + })) + .await; + assert_eq!(initial.next().await.unwrap()["type"], "snapshot"); + let opening = next_view(&mut initial).await; + let base = screen_of(&opening); + let token = opening["resume_token"].as_str().unwrap().to_owned(); + let base_revision = opening["view_revision"].as_u64().unwrap(); + + step.store(1, Ordering::Relaxed); + let mut resumed = Peer::connect_with_binary(service, SessionConfig::default()); + resumed + .say(serde_json::json!({ + "type": "join", + "capability": capability.expose(), + "screen_patches": true, + "binary_view_patches": true, + "resume_token": token, + })) + .await; + assert_eq!(resumed.next().await.unwrap()["type"], "snapshot"); + let bytes = resumed.next_binary().await.unwrap(); + let patch = id_core::screen_codec::decode_view_patch(&bytes).unwrap(); + assert_eq!(patch.base_view_revision, base_revision); + let applied = patch.patch.apply(&base).unwrap(); + assert_eq!(applied.cells[0].symbol, "0"); + assert_eq!(applied.cells[1].symbol, "1"); + resumed.close().await; + initial.close().await; + } + + #[tokio::test] + async fn binary_transport_requires_explicit_join_opt_in() { + let world = WorldHandle::spawn_with_program( + WorldCore::new("lobby", WorldLimits::default()).unwrap(), + Box::new(StepScreen(Arc::new(AtomicU64::new(0)))), + ); + let service = WorldService::new(world.clone(), None); + let (_, capability) = world + .issue("player".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + + let mut peer = Peer::connect_with_binary(service, SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "join", + "capability": capability.expose(), + "screen_patches": true, + })) + .await; + assert_eq!(peer.next().await.unwrap()["type"], "snapshot"); + let view = peer.next().await.unwrap(); + assert_eq!(view["type"], "view"); + assert!(view["surface"].is_object()); + assert!(peer.from_server_binary.try_recv().is_err()); + peer.close().await; + } + #[tokio::test] async fn unknown_resume_tokens_fall_back_to_a_full_view() { let world = WorldHandle::spawn_with_program( @@ -4097,6 +4209,7 @@ mod tests { "type": "join", "capability": capability.expose(), "screen_patches": true, + "binary_view_patches": true, "resume_token": token, })) .await; 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 3799baa699..d027e546fc 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/types.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/types.rs @@ -62,6 +62,15 @@ pub trait SessionIo: Send { fn recv(&mut self) -> impl Future + Send; /// Send one frame. Returns `false` when the peer is gone. fn send(&mut self, frame: String) -> impl Future + Send; + /// Whether this negotiated transport sends screen patches as binary v2. + fn binary_view_patches(&self) -> bool { + false + } + /// Send one binary screen-patch frame. Unsupported transports keep the + /// default fail-closed behavior; v1 continues to use [`Self::send`]. + fn send_binary(&mut self, _frame: Vec) -> impl Future + Send { + async { false } + } /// Mark this session authorized after its application-level /// capability or admin credential has been validated. fn mark_authorized(&mut self) {} @@ -192,6 +201,10 @@ pub(crate) enum ClientFrame { /// Opt in to revisioned JSON screen patches. Omitted by v1 clients. #[serde(default)] screen_patches: bool, + /// Opt in to binary MessagePack view patches on transports that support + /// them. Requires `screen_patches`; omitted by v1 clients. + #[serde(default)] + binary_view_patches: 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 9f8bb3051e..7ac01e0960 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/view.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/view.rs @@ -42,6 +42,8 @@ pub(crate) struct ViewRevisionState { screen: Option<(u64, crate::world_presentation::ScreenSurface)>, /// The participant this connection joined as, bound into resume tokens. pub(crate) participant: u64, + /// Client opt-in, additionally gated by the selected transport adapter. + pub(crate) binary_view_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 @@ -268,15 +270,42 @@ pub(crate) async fn send_view( patch: None, resume_token: resume_token.as_deref(), }; - let delta_size = serde_json::to_vec(&delta_frame).map(|bytes| bytes.len()); let full_size = serde_json::to_vec(&full_frame).map(|bytes| bytes.len()); - if matches!((delta_size, full_size), (Ok(delta), Ok(full)) if delta < full) { - let sent = send_json(service.frame_meter(), io, &delta_frame).await; - if sent { - view_state.screen = Some((view_revision, screen.clone())); - view_state.note_view_sent(view_revision, Some(screen)); + if view_state.binary_view_patches && io.binary_view_patches() { + if let (Ok(binary), Ok(full)) = ( + id_core::screen_codec::encode_view_patch( + sequence, + view_revision, + *base_view_revision, + resume_token.as_deref(), + &patch, + ), + full_size, + ) { + if binary.len() < full { + let bytes = binary.len() as u64; + let sent = io.send_binary(binary).await; + if sent { + service.frame_meter().add_frame_bytes(bytes); + } + if sent { + view_state.screen = Some((view_revision, screen.clone())); + view_state.note_view_sent(view_revision, Some(screen)); + } + return sent; + } + } + } else { + let delta_size = serde_json::to_vec(&delta_frame).map(|bytes| bytes.len()); + if matches!((delta_size, full_size), (Ok(delta), Ok(full)) if delta < full) + { + let sent = send_json(service.frame_meter(), io, &delta_frame).await; + if sent { + view_state.screen = Some((view_revision, screen.clone())); + view_state.note_view_sent(view_revision, Some(screen)); + } + return sent; } - return sent; } } } diff --git a/pkgs/id/crates/id-worlds/src/world_ssh.rs b/pkgs/id/crates/id-worlds/src/world_ssh.rs index eae5de6fe5..166ec9a253 100644 --- a/pkgs/id/crates/id-worlds/src/world_ssh.rs +++ b/pkgs/id/crates/id-worlds/src/world_ssh.rs @@ -162,6 +162,8 @@ impl iroh::protocol::ProtocolHandler for SshTunnelProtocol { /// The exec command that carries the frame protocol (shell contract /// transport `ssh-exec`). pub const WORLD_EXEC_COMMAND: &str = "id-world/1"; +/// Versioned frame command with binary screen-patch support. +pub const WORLD_EXEC_COMMAND_V2: &str = "id-world/2"; /// Unread frame bytes one exec channel may queue before the host ends its /// session. The handler must never wait for space (it shares the loop that /// flushes output), and dropping bytes would corrupt the framing, so a flood @@ -421,7 +423,8 @@ impl Handler for SshClient { ) -> Result<(), russh::Error> { // The frame protocol is the only command, and one session (shell or // frames) runs per connection. - if data != WORLD_EXEC_COMMAND.as_bytes() + let binary_view_patches = data == WORLD_EXEC_COMMAND_V2.as_bytes(); + if (data != WORLD_EXEC_COMMAND.as_bytes() && !binary_view_patches) || self.login.is_none() || self.input.is_some() || self.exec.is_some() @@ -437,6 +440,7 @@ impl Handler for SshClient { bytes, buffer: FrameBuffer::default(), backlog: Arc::clone(&self.exec_backlog), + binary_view_patches, }; let hub = self.hub.clone(); let documents_store = self.blobs.clone(); @@ -736,6 +740,7 @@ struct SshFrameIo { bytes: mpsc::UnboundedReceiver>, buffer: FrameBuffer, backlog: Arc, + binary_view_patches: bool, } impl SessionIo for SshFrameIo { @@ -764,6 +769,17 @@ impl SessionIo for SshFrameIo { Err(_) => false, } } + + fn binary_view_patches(&self) -> bool { + self.binary_view_patches + } + + async fn send_binary(&mut self, frame: Vec) -> bool { + match encode_frame(&frame) { + Ok(bytes) => self.handle.data(self.channel, bytes).await.is_ok(), + Err(_) => false, + } + } } /// [`SessionIo`] for one SSH shell: the join frame first, then terminal lines diff --git a/pkgs/id/web/src/world-contract.test.ts b/pkgs/id/web/src/world-contract.test.ts index e51caafbf7..215152a3c0 100644 --- a/pkgs/id/web/src/world-contract.test.ts +++ b/pkgs/id/web/src/world-contract.test.ts @@ -200,6 +200,13 @@ describe("shell contract validator", () => { ok: true, type: "join", }); + expect( + checkClientFrame( + contract, + { type: "join", capability: cap, screen_patches: true, binary_view_patches: true }, + "opening", + ).ok, + ).toBe(true); expect(checkClientFrame(contract, { type: "resize", width: 500, height: 200 }, "joined").ok).toBe(true); expect(checkClientFrame(contract, { type: "input", data_hex: "1b5b41" }, "joined").ok).toBe(true); expect(checkClientFrame(contract, { type: "records", capability: cap, after: "k" }, "joined").ok).toBe(true); @@ -379,6 +386,10 @@ class FakeSocket extends EventTarget { this.dispatchEvent(new MessageEvent("message", { data })); } + deliverBinary(data: Uint8Array): void { + this.dispatchEvent(new MessageEvent("message", { data: data.buffer })); + } + sent(type: string): Array> { return this.transcript .filter((entry) => entry.from === "client" && (entry.frame as { type?: string }).type === type) @@ -434,6 +445,36 @@ describe("web shell conformance", () => { // Join. q("[data-world-capability]").value = "guest-capability"; q("[data-world-join]").click(); + const v2Attempt = FakeSocket.all.at(-1) as FakeSocket; + expect(v2Attempt.url).toMatch(/\/ws\/world\/2$/); + v2Attempt.open(); + expect(v2Attempt.sent("join")[0]).toMatchObject({ + binary_view_patches: true, + screen_patches: true, + }); + v2Attempt.deliver({ + type: "snapshot", + snapshot: { world_id: "lobby", current_sequence: 3, participants: [] }, + }); + v2Attempt.deliver({ type: "view", sequence: 3, data: "resume base", view_revision: 1, resume_token: "resume-1" }); + const resizeCount = v2Attempt.sent("resize").length; + v2Attempt.deliverBinary(new Uint8Array([0xc1])); + expect(v2Attempt.sent("resize")).toHaveLength(resizeCount + 1); + + // Rejoin keeps the v2 route and resumes from the latest applied view. + q("[data-world-join]").click(); + const v2Reconnect = FakeSocket.all.at(-1) as FakeSocket; + v2Reconnect.open(); + expect(v2Reconnect.sent("join")[0]).toMatchObject({ + binary_view_patches: true, + resume_token: "resume-1", + }); + + // A host without the v2 route refuses an upgrade before opening it; + // the browser retries the unchanged JSON session on the v1 path. + q("[data-world-join]").click(); + const rejectedV2Upgrade = FakeSocket.all.at(-1) as FakeSocket; + rejectedV2Upgrade.close(); const session = FakeSocket.all.at(-1) as FakeSocket; expect(session.url).toMatch(/\/ws\/world$/); session.open(); diff --git a/pkgs/id/web/src/world-program.test.ts b/pkgs/id/web/src/world-program.test.ts index 3ff7037aa9..1462627472 100644 --- a/pkgs/id/web/src/world-program.test.ts +++ b/pkgs/id/web/src/world-program.test.ts @@ -120,10 +120,18 @@ describe("program-only surface (#2146 phase 2)", () => { q("[data-world-capability]").value = "guest-capability"; q("[data-world-join]").click(); const session = FakeSocket.all.at(-1) as FakeSocket; - expect(session.url).toMatch(/\/ws\/world$/); + expect(session.url).toMatch(/\/ws\/world\/2$/); 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, + binary_view_patches: true, + resume_token: null, + }, ]); // Text rendering through the trusted presenter: guest output diff --git a/pkgs/id/web/src/world-wire.test.ts b/pkgs/id/web/src/world-wire.test.ts new file mode 100644 index 0000000000..fae396d581 --- /dev/null +++ b/pkgs/id/web/src/world-wire.test.ts @@ -0,0 +1,83 @@ +import { Packr } from "msgpackr"; +import { describe, expect, it } from "vitest"; +import { decodeBinaryViewPatch } from "./world-wire"; + +const packr = new Packr({ useRecords: false }); + +describe("binary v2 world view frames", () => { + it("decodes the shared Rust MessagePack golden vector", () => { + const rustGolden = new Uint8Array([ + 0x87, 0xa7, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x01, 0xa4, 0x74, 0x79, 0x70, 0x65, 0xa4, 0x76, 0x69, + 0x65, 0x77, 0xa8, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63, 0x65, 0x29, 0xad, 0x76, 0x69, 0x65, 0x77, + 0x5f, 0x72, 0x65, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x09, 0xb2, 0x62, 0x61, 0x73, 0x65, 0x5f, 0x76, + 0x69, 0x65, 0x77, 0x5f, 0x72, 0x65, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x08, 0xac, 0x72, 0x65, 0x73, + 0x75, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xa8, 0x72, 0x65, 0x73, 0x75, 0x6d, 0x65, 0x2d, + 0x39, 0xa5, 0x70, 0x61, 0x74, 0x63, 0x68, 0x84, 0xa7, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x01, + 0xa5, 0x77, 0x69, 0x64, 0x74, 0x68, 0x02, 0xa6, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x01, 0xa4, 0x72, + 0x75, 0x6e, 0x73, 0x90, + ]); + expect(decodeBinaryViewPatch(rustGolden)).toEqual({ + type: "view", + sequence: 41, + view_revision: 9, + base_view_revision: 8, + resume_token: "resume-9", + patch: { version: 1, width: 2, height: 1, runs: [] }, + }); + }); + + it("decodes the view revisions and patch from the MessagePack envelope", () => { + const frame = { + version: 1, + type: "view", + sequence: 41, + view_revision: 9, + base_view_revision: 8, + resume_token: "resume-9", + patch: { version: 1, width: 2, height: 1, runs: [] }, + }; + + expect(decodeBinaryViewPatch(packr.pack(frame))).toEqual({ + type: "view", + sequence: 41, + view_revision: 9, + base_view_revision: 8, + resume_token: "resume-9", + patch: frame.patch, + }); + }); + + it("fails closed for unsupported, malformed, or non-view frames", () => { + expect( + decodeBinaryViewPatch( + packr.pack({ + version: 2, + type: "view", + sequence: 1, + view_revision: 1, + base_view_revision: 0, + patch: {}, + }), + ), + ).toBeNull(); + expect( + decodeBinaryViewPatch( + packr.pack({ + version: 1, + type: "event", + sequence: 1, + view_revision: 1, + base_view_revision: 0, + patch: {}, + }), + ), + ).toBeNull(); + expect(decodeBinaryViewPatch(new Uint8Array([0xc1]))).toBeNull(); + const validPrefix = packr.pack({ version: 1, type: "view" }); + expect(decodeBinaryViewPatch(new Uint8Array([...validPrefix, 0xc0]))).toBeNull(); + }); + + it("rejects frames larger than the Rust codec limit", () => { + expect(decodeBinaryViewPatch(new Uint8Array(1024 * 1024 + 1))).toBeNull(); + }); +}); diff --git a/pkgs/id/web/src/world-wire.ts b/pkgs/id/web/src/world-wire.ts new file mode 100644 index 0000000000..3f9a6708e1 --- /dev/null +++ b/pkgs/id/web/src/world-wire.ts @@ -0,0 +1,46 @@ +import { Unpackr } from "msgpackr"; +import type { ScreenPatch } from "./world-surface"; + +export type BinaryViewPatchFrame = { + type: "view"; + sequence: number; + view_revision: number; + base_view_revision: number; + resume_token?: string; + patch: ScreenPatch; +}; + +const MAX_BINARY_VIEW_FRAME_BYTES = 1024 * 1024; +const unpackr = new Unpackr({ useRecords: false }); + +/** Decode and validate the v2 MessagePack envelope before applying a patch. */ +export function decodeBinaryViewPatch(bytes: ArrayBuffer | Uint8Array): BinaryViewPatchFrame | null { + if (bytes.byteLength > MAX_BINARY_VIEW_FRAME_BYTES) return null; + try { + const decoded: unknown = unpackr.unpack(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)); + if (!isRecord(decoded) || decoded.version !== 1 || decoded.type !== "view") return null; + if ( + !Number.isSafeInteger(decoded.sequence) || + !Number.isSafeInteger(decoded.view_revision) || + !Number.isSafeInteger(decoded.base_view_revision) || + !isRecord(decoded.patch) || + (decoded.resume_token !== undefined && typeof decoded.resume_token !== "string") + ) { + return null; + } + return { + type: "view", + sequence: decoded.sequence as number, + view_revision: decoded.view_revision as number, + base_view_revision: decoded.base_view_revision as number, + ...(typeof decoded.resume_token === "string" ? { resume_token: decoded.resume_token } : {}), + patch: decoded.patch as unknown as ScreenPatch, + }; + } catch { + return null; + } +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index cb426bcc73..9823d71e37 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -5,6 +5,7 @@ import { advanceHostViewCursor, parseWorldHostViewPage, parseWorldInviteResponse import { terminalBytesForKey } from "./world-keyboard"; import { parseWorldSeed } from "./world-seed"; import { applyScreenPatch, renderWorldSurface, type ScreenPatch, type ScreenSurface } from "./world-surface"; +import { decodeBinaryViewPatch } from "./world-wire"; type WorldFrame = { type: @@ -39,6 +40,7 @@ type WorldFrame = { reason?: string; view_revision?: number; base_view_revision?: number; + resume_token?: string | null; patch?: ScreenPatch; invite?: { capability?: string; participant_id?: number; display_name?: string }; capability?: string; @@ -133,6 +135,7 @@ function initWorld(): void { capability.value = sessionStorage.getItem(storageKey) ?? ""; let socket: WebSocket | null = null; let cursor = 0; + let resumeToken: string | null = null; let renderedSurface: ScreenSurface | null = null; let renderedViewRevision: number | null = null; let records: Record = {}; @@ -141,6 +144,7 @@ function initWorld(): void { let recordsRefetch = false; let reconnects = 0; let intentionalClose = false; + let useBinaryWorldV2 = true; let hostMode = false; // Bumped when a host-view load starts and when the user leaves host // mode (Join world): a host response that lands after a mode switch is @@ -233,13 +237,22 @@ function initWorld(): void { inviteOutput.hidden = false; }; - const receive = (raw: string) => { + const receive = (raw: string | ArrayBuffer) => { let parsed: unknown; - try { - parsed = JSON.parse(raw) as unknown; - } catch { - rejectFrame(); - return; + if (typeof raw === "string") { + try { + parsed = JSON.parse(raw) as unknown; + } catch { + rejectFrame(); + return; + } + } else { + parsed = decodeBinaryViewPatch(raw); + if (parsed === null) { + rejectFrame(); + sendViewport(); + return; + } } if (!isRecord(parsed) || typeof parsed.type !== "string") { rejectFrame(); @@ -292,11 +305,15 @@ function initWorld(): void { (frame.view_revision !== undefined && frame.view_revision !== null && !isFiniteNumber(frame.view_revision)) || (frame.base_view_revision !== undefined && frame.base_view_revision !== null && - !isFiniteNumber(frame.base_view_revision)) + !isFiniteNumber(frame.base_view_revision)) || + (frame.resume_token !== undefined && + frame.resume_token !== null && + typeof frame.resume_token !== "string") ) { rejectFrame(); return; } + if (isFiniteNumber(frame.sequence)) cursor = Math.max(cursor, frame.sequence); if (frame.patch) { if ( renderedSurface && @@ -307,6 +324,7 @@ function initWorld(): void { if (patched && renderWorldSurface(view, patched)) { renderedSurface = patched; renderedViewRevision = frame.view_revision; + resumeToken = frame.resume_token ?? null; break; } } @@ -321,6 +339,7 @@ function initWorld(): void { // The authoritative screen is replaced, so drop its patch base. renderedSurface = null; renderedViewRevision = frame.view_revision ?? null; + resumeToken = frame.resume_token ?? null; formPresenter.present(frame.surface); break; } @@ -328,6 +347,7 @@ function initWorld(): void { formPresenter.present(null); renderedSurface = frame.surface; renderedViewRevision = frame.view_revision ?? null; + resumeToken = frame.resume_token ?? null; break; } if (frame.data !== undefined) { @@ -335,6 +355,7 @@ function initWorld(): void { view.textContent = frame.data; renderedSurface = null; renderedViewRevision = frame.view_revision ?? null; + resumeToken = frame.resume_token ?? null; } break; } @@ -598,17 +619,20 @@ function initWorld(): void { renderedSurface = null; renderedViewRevision = null; const scheme = location.protocol === "https:" ? "wss:" : "ws:"; + let opened = false; // #1461: every handler captures THIS connection's socket (`ws`) and // ignores events once it is no longer the current one. The handlers // used to read the shared mutable `socket`, so a retired socket's // async close event (dispatched after a rejoin had already replaced // 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}`); + const ws = new WebSocket(`${scheme}//${location.host}${worldSocketPath}${useBinaryWorldV2 ? "/2" : ""}`); + ws.binaryType = "arraybuffer"; socket = ws; setStatus("Connecting…"); ws.addEventListener("open", () => { if (ws !== socket) return; + opened = true; reconnects = 0; ws.send( JSON.stringify({ @@ -617,13 +641,19 @@ function initWorld(): void { after: cursor || null, world: selectedWorld(), screen_patches: true, + binary_view_patches: useBinaryWorldV2, + resume_token: useBinaryWorldV2 ? resumeToken : undefined, }), ); sendViewport(); }); ws.addEventListener("message", (event) => { if (ws !== socket) return; - receive(String(event.data)); + if (typeof event.data === "string" || event.data instanceof ArrayBuffer) { + receive(event.data); + } else { + rejectFrame(); + } }); ws.addEventListener("error", () => { if (ws !== socket) return; @@ -636,6 +666,14 @@ function initWorld(): void { recordsPending = false; recordsRefetch = false; if (intentionalClose) return; + // Older hosts do not register the v2 route. Fall back only when the + // upgrade itself failed; once a v2 session opened, reconnects keep v2. + if (!opened && useBinaryWorldV2) { + useBinaryWorldV2 = false; + reconnects = 0; + connect(); + return; + } setStatus("Disconnected; retrying…", "error"); const wait = Math.min(500 * 2 ** reconnects++, 10_000); window.setTimeout(() => { From 78a99a67a4d4098f92470a321d2caf0bcbc5170e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 06:15:38 -0600 Subject: [PATCH 3/5] test(id): round-trip populated screen patches --- pkgs/id/crates/id-core/src/screen_codec.rs | 82 ++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/pkgs/id/crates/id-core/src/screen_codec.rs b/pkgs/id/crates/id-core/src/screen_codec.rs index 603051292a..0fdc5291a2 100644 --- a/pkgs/id/crates/id-core/src/screen_codec.rs +++ b/pkgs/id/crates/id-core/src/screen_codec.rs @@ -73,3 +73,85 @@ pub fn decode_patch(bytes: &[u8]) -> Result { } Ok(frame.patch) } + +#[cfg(test)] +mod tests { + use proptest::prelude::*; + + use super::{decode_patch, encode_patch}; + use crate::world_presentation::{CellRun, ScreenCell, ScreenPatch, StyleToken}; + + fn screen_cell() -> impl Strategy { + ( + prop_oneof![ + Just(String::new()), + Just("a".to_owned()), + Just("Ω".to_owned()), + Just("水".to_owned()), + Just("🧭".to_owned()), + Just("e\u{301}".to_owned()), + ], + any::(), + any::(), + any::(), + 0_u8..=2, + prop_oneof![ + Just(None), + Just(Some(StyleToken::Emphasis)), + Just(Some(StyleToken::Muted)), + Just(Some(StyleToken::Heading)), + Just(Some(StyleToken::Code)), + Just(Some(StyleToken::Warning)), + Just(Some(StyleToken::Success)), + Just(Some(StyleToken::Link)), + ], + ) + .prop_map(|(symbol, fg, bg, bold, columns, token)| ScreenCell { + symbol, + fg, + bg, + bold, + columns, + token, + }) + } + + fn populated_patch() -> impl Strategy { + ( + any::(), + 36_u16..=120, + 1_u16..=50, + prop::collection::vec(prop::collection::vec(screen_cell(), 1..=8), 1..=4), + ) + .prop_map(|(version, width, height, cell_runs)| { + let mut next_start = 0_u32; + let runs = cell_runs + .into_iter() + .map(|cells| { + let run = CellRun { + start: next_start, + cells, + }; + // Leave one unchanged cell between runs. The strategy's + // bounds keep every run inside the minimum width of 36. + next_start += u32::try_from(run.cells.len()).unwrap() + 1; + run + }) + .collect(); + ScreenPatch { + version, + width, + height, + runs, + } + }) + } + + proptest! { + #[test] + fn populated_screen_patches_round_trip_through_messagepack(patch in populated_patch()) { + let encoded = encode_patch(&patch).unwrap(); + prop_assert_eq!(decode_patch(&encoded).unwrap(), patch); + } + } +} From 2b9428d20efd2f1bbc68087e3198ced434771129 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 06:20:00 -0600 Subject: [PATCH 4/5] fix(id): preserve screen baseline on reconnect --- pkgs/id/web/src/world-contract.test.ts | 46 +++++++++++++++++++++++--- pkgs/id/web/src/world.ts | 33 +++++++++++++----- 2 files changed, 66 insertions(+), 13 deletions(-) diff --git a/pkgs/id/web/src/world-contract.test.ts b/pkgs/id/web/src/world-contract.test.ts index 215152a3c0..7d936a7577 100644 --- a/pkgs/id/web/src/world-contract.test.ts +++ b/pkgs/id/web/src/world-contract.test.ts @@ -1,6 +1,7 @@ import { readFileSync } from "node:fs"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { Packr } from "msgpackr"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { Conformance, @@ -456,12 +457,17 @@ describe("web shell conformance", () => { type: "snapshot", snapshot: { world_id: "lobby", current_sequence: 3, participants: [] }, }); - v2Attempt.deliver({ type: "view", sequence: 3, data: "resume base", view_revision: 1, resume_token: "resume-1" }); - const resizeCount = v2Attempt.sent("resize").length; - v2Attempt.deliverBinary(new Uint8Array([0xc1])); - expect(v2Attempt.sent("resize")).toHaveLength(resizeCount + 1); + const screenA = { + kind: "screen", + version: 1, + width: 1, + height: 1, + cells: [{ symbol: "A", fg: 7, bg: 0, bold: false, columns: 1 }], + }; + v2Attempt.deliver({ type: "view", sequence: 3, data: "", surface: screenA, view_revision: 1, resume_token: "resume-1" }); - // Rejoin keeps the v2 route and resumes from the latest applied view. + // Rejoin keeps the exact applied screen baseline, so the server can send + // a patch without a same-size resize resetting its retained baseline. q("[data-world-join]").click(); const v2Reconnect = FakeSocket.all.at(-1) as FakeSocket; v2Reconnect.open(); @@ -469,6 +475,36 @@ describe("web shell conformance", () => { binary_view_patches: true, resume_token: "resume-1", }); + expect(v2Reconnect.sent("resize")).toHaveLength(0); + v2Reconnect.deliverBinary( + new Uint8Array( + new Packr({ useRecords: false }).pack({ + version: 1, + type: "view", + sequence: 3, + base_view_revision: 1, + view_revision: 2, + patch: { + version: 1, + width: 1, + height: 1, + runs: [{ start: 0, cells: [{ symbol: "B", fg: 7, bg: 0, bold: false, columns: 1 }] }], + }, + resume_token: "resume-2", + }), + ), + ); + expect(q("[data-world-view]").textContent).toContain("B"); + const screenPane = q("[data-world-view]"); + Object.defineProperty(screenPane, "clientWidth", { configurable: true, value: 96 }); + Object.defineProperty(screenPane, "clientHeight", { configurable: true, value: 32 }); + const beforeViewportChange = v2Reconnect.sent("resize").length; + for (const observer of FakeResizeObserver.all) observer.fire(); + expect(v2Reconnect.sent("resize")).toHaveLength(beforeViewportChange + 1); + expect(v2Reconnect.sent("resize").at(-1)).toMatchObject({ width: 10, height: 2 }); + const resizeCount = v2Reconnect.sent("resize").length; + v2Reconnect.deliverBinary(new Uint8Array([0xc1])); + expect(v2Reconnect.sent("resize")).toHaveLength(resizeCount + 1); // A host without the v2 route refuses an upgrade before opening it; // the browser retries the unchanged JSON session on the v1 path. diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index 9823d71e37..57c7c800e0 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -138,6 +138,7 @@ function initWorld(): void { let resumeToken: string | null = null; let renderedSurface: ScreenSurface | null = null; let renderedViewRevision: number | null = null; + let sentViewport: { width: number; height: number } | null = null; let records: Record = {}; let recordsAfter: string | null = null; let recordsPending = false; @@ -250,7 +251,7 @@ function initWorld(): void { parsed = decodeBinaryViewPatch(raw); if (parsed === null) { rejectFrame(); - sendViewport(); + sendViewport(true); return; } } @@ -329,8 +330,8 @@ function initWorld(): void { } } // A gap or invalid patch means the browser no longer has the exact - // base. A same-size resize asks the server to reset with a full view. - sendViewport(); + // base. Force a same-size resize to request a fresh full view. + sendViewport(true); break; } if (frame.surface && frame.surface.kind === "form") { @@ -501,14 +502,30 @@ function initWorld(): void { } }); - const sendViewport = () => { + const hasResumableScreen = () => + useBinaryWorldV2 && + resumeToken !== null && + renderedSurface !== null && + renderedViewRevision !== null; + const sendViewport = (force = false) => { if (hostMode || socket?.readyState !== WebSocket.OPEN) return; const fontSize = Number.parseFloat(getComputedStyle(view).fontSize) || 16; const width = Math.max(1, Math.min(500, Math.floor(view.clientWidth / (fontSize * 0.6)))); const height = Math.max(1, Math.min(200, Math.floor(view.clientHeight / fontSize))); + const sameAsLast = sentViewport?.width === width && sentViewport.height === height; + // A same-size resize resets the server's retained screen baseline. Keep + // it out of an unchanged v2 reconnect so the resume token can catch up. + if (!force && sameAsLast) return; + // A forced resync or a real viewport change invalidates the local base too. + if (force || sentViewport !== null) { + renderedSurface = null; + renderedViewRevision = null; + resumeToken = null; + } socket.send(JSON.stringify({ type: "resize", width, height })); + sentViewport = { width, height }; }; - const viewportObserver = new ResizeObserver(sendViewport); + const viewportObserver = new ResizeObserver(() => sendViewport()); viewportObserver.observe(view); recordsRefresh.addEventListener("click", requestRecords); @@ -616,8 +633,6 @@ function initWorld(): void { // (block) this connection's first fetch. recordsPending = false; recordsRefetch = false; - renderedSurface = null; - renderedViewRevision = null; const scheme = location.protocol === "https:" ? "wss:" : "ws:"; let opened = false; // #1461: every handler captures THIS connection's socket (`ws`) and @@ -645,7 +660,9 @@ function initWorld(): void { resume_token: useBinaryWorldV2 ? resumeToken : undefined, }), ); - sendViewport(); + // New sessions and v1 fallbacks need an initial resize. A v2 resume + // keeps the already-established viewport unless it actually changed. + sendViewport(!hasResumableScreen()); }); ws.addEventListener("message", (event) => { if (ws !== socket) return; From 3751be8a99d399284c5aef79a5f8f38147a60582 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 06:43:19 -0600 Subject: [PATCH 5/5] fix(id): restore viewport before screen resume --- .../crates/id-worlds/src/world_session/mod.rs | 15 +++++ .../id-worlds/src/world_session/resume.rs | 13 ++++ .../id-worlds/src/world_session/tests.rs | 59 +++++++++++++------ 3 files changed, 69 insertions(+), 18 deletions(-) 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 d7830d23f1..49538c530b 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/mod.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/mod.rs @@ -1161,6 +1161,21 @@ async fn joined( .then_some(resume_token) .flatten() .filter(|token| token.len() <= MAX_RESUME_TOKEN_BYTES); + // A retained baseline also records the viewport that produced it. Restore + // that viewport before the first view consumes the one-shot resume token. + if let Some(resume) = view_state.pending_resume.as_deref() { + if let Some((width, height)) = service + .resume_baselines + .lock() + .await + .viewport_for(resume, participant_id) + { + viewport = Some(Viewport { + width: usize::from(width), + height: usize::from(height), + }); + } + } 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/resume.rs b/pkgs/id/crates/id-worlds/src/world_session/resume.rs index 8ed5fab6d0..e0e0f8661a 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/resume.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/resume.rs @@ -143,6 +143,19 @@ impl BaselineCache { Some(baseline) } + /// Peek the viewport bound to a live token without consuming its baseline. + /// + /// Reconnected sessions need this before their first view is rendered; + /// `take_matching` still performs the one-shot, shape-checked consume. + pub(crate) fn viewport_for(&mut self, token: &str, participant: u64) -> Option<(u16, u16)> { + self.evict_expired(); + let (_, baseline) = self + .entries + .iter() + .find(|(candidate, _)| candidate == token)?; + (baseline.participant == participant).then_some((baseline.width, baseline.height)) + } + fn next_token(&mut self) -> String { let mut hasher = blake3::Hasher::new(); hasher.update(b"developing-today/id-world-resume-token/v1\0"); 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 5e2081ab13..3c7730ecea 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/tests.rs @@ -4163,27 +4163,38 @@ mod tests { } /// A 3x1 program: its default view is 3x1, a 2x1 viewport fits it to 2x1. - struct WideScreen; + struct WideScreen(Arc); impl crate::world::WorldProgram for WideScreen { fn view(&mut self, _viewer: &Participant) -> anyhow::Result> { + let first = if self.0.load(Ordering::Relaxed) == 0 { + "a" + } else { + "x" + }; Ok(Some( - r#"{"kind":"screen","version":1,"width":3,"height":1,"rows":["abc"]}"# - .to_owned(), + serde_json::json!({ + "kind": "screen", + "version": 1, + "width": 3, + "height": 1, + "rows": [format!("{first}bc")], + }) + .to_string(), )) } } #[tokio::test] - async fn a_wrong_viewport_resume_token_falls_back_to_a_full_view() { + async fn a_resume_token_restores_the_viewport_before_catching_up() { + let step = Arc::new(AtomicU64::new(0)); let world = WorldHandle::spawn_with_program( WorldCore::new("lobby", WorldLimits::default()).unwrap(), - Box::new(WideScreen), + Box::new(WideScreen(Arc::clone(&step))), ); let svc = WorldService::new(world.clone(), None); let (_, capability) = world.issue("player", WorldScopes::GUEST).await.unwrap(); - // The token is issued for the 2x1 viewport this session resized to. let mut first = Peer::connect(svc.clone(), SessionConfig::default()); first .say(serde_json::json!({ @@ -4193,37 +4204,49 @@ mod tests { })) .await; assert_eq!(first.next().await.unwrap()["type"], "snapshot"); - assert!(next_view(&mut first).await["patch"].is_null()); + assert_eq!(screen_of(&next_view(&mut first).await).width, 3); + + // The token is issued for the 2x1 viewport this session resized to. first .say(serde_json::json!({"type": "resize", "width": 2, "height": 1})) .await; let resized = next_view(&mut first).await; - assert_eq!(screen_of(&resized).width, 2); + let base = screen_of(&resized); + assert_eq!(base.width, 2); let token = resized["resume_token"].as_str().unwrap().to_owned(); + let base_revision = resized["view_revision"].as_u64().unwrap(); - // Reconnecting without that viewport asks for the default 3x1 - // view: the retained baseline is the wrong shape, so it is a miss. + // The next session must restore that viewport before rendering + // and consuming the resume token, otherwise the baseline is a miss. + step.store(1, Ordering::Relaxed); let mut resumed = Peer::connect(svc, SessionConfig::default()); resumed .say(serde_json::json!({ "type": "join", "capability": capability.expose(), "screen_patches": true, - "binary_view_patches": true, "resume_token": token, })) .await; assert_eq!(resumed.next().await.unwrap()["type"], "snapshot"); - let view = next_view(&mut resumed).await; + let catch_up = next_view(&mut resumed).await; assert!( - view["patch"].is_null(), - "a wrong-viewport token gets a full view: {view}" + !catch_up["patch"].is_null(), + "a retained viewport token yields a catch-up patch: {catch_up}" ); - assert_eq!(screen_of(&view).width, 3); - assert!( - view["resume_token"].is_string(), - "the full view issues a token for the new viewport" + assert_eq!( + catch_up["base_view_revision"].as_u64(), + Some(base_revision) ); + let patch = serde_json::from_value::( + catch_up["patch"].clone(), + ) + .unwrap(); + let applied = patch.apply(&base).expect("the catch-up patch uses its retained base"); + assert_eq!(applied.width, 2); + assert_eq!(applied.cells[0].symbol, "x"); + resumed.close().await; + first.close().await; } #[tokio::test]