diff --git a/pkgs/id/contract/shell-contract.v1.json b/pkgs/id/contract/shell-contract.v1.json index f2abfd3e77..693df42f3e 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": 11, + "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.", "max_frame_bytes": 1048576, "routing_fields": ["world"], @@ -13,7 +13,7 @@ }, "websocket": { "path": "/ws/world", - "envelope": "text-message", + "envelope": "text-message; binary-message for negotiated binary view patches (revision 12)", "session": "one WebSocket connection" }, "ssh-exec": { @@ -45,6 +45,7 @@ "capability": { "type": "string", "max_bytes": 256 }, "after": "u64?", "screen_patches": { "type": "bool", "optional": true, "nullable": false }, + "screen_msgpack": { "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 } } @@ -589,6 +590,7 @@ "redacted_keys": ["seed"] }, "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.", "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` (the portable screen document). A shell that does not understand it renders `data`.", "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/src/frames.rs b/pkgs/id/crates/id-core/src/frames.rs index 3c775ad068..2877d64e6a 100644 --- a/pkgs/id/crates/id-core/src/frames.rs +++ b/pkgs/id/crates/id-core/src/frames.rs @@ -61,6 +61,30 @@ pub async fn write_frame_to(send: &mut W, payload: &[u8]) Ok(()) } +/// First byte of a binary frame body on a length-prefixed transport +/// (F12.11 phase 3, #12242). Text frames are JSON objects and always +/// start with `{`; a leading NUL therefore marks a frame body as +/// binary unambiguously, without changing the v1 text envelope bytes. +/// Only sessions that negotiated binary frames ever emit one, and a +/// receiver that did not negotiate treats the body as malformed input, +/// exactly like a non-UTF-8 body. +pub const BINARY_FRAME_MARKER: u8 = 0; + +/// The frame body for `payload` as a binary frame: the marker byte +/// followed by the payload. +pub fn mark_binary_frame(payload: &[u8]) -> Vec { + let mut body = Vec::with_capacity(1 + payload.len()); + body.push(BINARY_FRAME_MARKER); + body.extend_from_slice(payload); + body +} + +/// The binary payload of a frame body, when the body carries the +/// binary marker; `None` for text bodies. +pub fn unmark_binary_frame(body: &[u8]) -> Option<&[u8]> { + body.strip_prefix(&[BINARY_FRAME_MARKER]) +} + /// Read one frame from any byte stream. `Ok(None)` means the peer finished /// cleanly between frames. /// @@ -315,6 +339,16 @@ pub async fn read_frame(recv: &mut RecvStream) -> Result>> { mod tests { use super::*; + #[test] + fn binary_frame_marking_round_trips_and_leaves_text_alone() { + let marked = mark_binary_frame(&[0x82, 0xa7, b'v']); + assert_eq!(unmark_binary_frame(&marked), Some(&[0x82, 0xa7, b'v'][..])); + assert_eq!(unmark_binary_frame(&[]), None); + assert_eq!(unmark_binary_frame(br#"{"type":"view"}"#), None); + // An empty binary payload is still a binary frame. + assert_eq!(unmark_binary_frame(&mark_binary_frame(&[])), Some(&[][..])); + } + #[tokio::test] async fn the_byte_stream_framing_round_trips_and_ends_cleanly() { let (mut client, mut server) = tokio::io::duplex(64); diff --git a/pkgs/id/crates/id-core/src/screen_codec.rs b/pkgs/id/crates/id-core/src/screen_codec.rs index 0fdc5291a2..50b471e491 100644 --- a/pkgs/id/crates/id-core/src/screen_codec.rs +++ b/pkgs/id/crates/id-core/src/screen_codec.rs @@ -74,13 +74,93 @@ pub fn decode_patch(bytes: &[u8]) -> Result { Ok(frame.patch) } +/// One negotiated binary view frame (F12.11 phase 3, #12242): the +/// `ScreenPatch` a `view` server frame carries, plus the envelope +/// fields that frame carries alongside the patch — the world-event +/// `sequence`, the target `view_revision`, the `base_view_revision` +/// the patch applies to, and the resume token naming the target +/// revision. A session sends this instead of the JSON `view` frame +/// only after the client negotiated binary patches at join; the +/// world-event cursor and view-revision semantics are unchanged. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ViewPatchFrame { + /// World-event cursor this view follows. + pub sequence: u64, + /// The session view revision this patch produces. + pub view_revision: u64, + /// The view revision the patch applies to. + pub base_view_revision: Option, + /// Resume token naming `view_revision`, when one is issued. + pub resume_token: Option, + /// The screen delta itself. + pub patch: ScreenPatch, +} + +#[derive(Serialize)] +#[serde(deny_unknown_fields)] +struct VersionedViewPatch<'a> { + version: u8, + #[serde(borrow)] + frame: &'a ViewPatchFrame, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct OwnedVersionedViewPatch { + version: u8, + frame: ViewPatchFrame, +} + +/// Encodes a view frame as one versioned MessagePack value. +pub fn encode_view_patch(frame: &ViewPatchFrame) -> Result, ScreenCodecError> { + let bytes = rmp_serde::to_vec_named(&VersionedViewPatch { + version: SCREEN_CODEC_VERSION, + frame, + })?; + if bytes.len() > MAX_SCREEN_FRAME_BYTES { + return Err(ScreenCodecError::TooLarge); + } + Ok(bytes) +} + +/// Decodes one bounded, versioned MessagePack view 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)); + } + Ok(frame.frame) +} + #[cfg(test)] mod tests { use proptest::prelude::*; - use super::{decode_patch, encode_patch}; + use super::{ + MAX_SCREEN_FRAME_BYTES, ScreenCodecError, ViewPatchFrame, decode_patch, decode_view_patch, + encode_patch, encode_view_patch, + }; use crate::world_presentation::{CellRun, ScreenCell, ScreenPatch, 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', + b'e', 0x85, 0xa8, b's', b'e', b'q', b'u', b'e', b'n', b'c', b'e', 0x07, 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', 0x03, 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', 0x02, 0xac, b'r', b'e', b's', b'u', b'm', b'e', b'_', b't', b'o', b'k', b'e', b'n', + 0xc0, 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, + ]; + fn screen_cell() -> impl Strategy { ( prop_oneof![ @@ -153,5 +233,76 @@ mod tests { let encoded = encode_patch(&patch).unwrap(); prop_assert_eq!(decode_patch(&encoded).unwrap(), patch); } + + #[test] + fn view_patch_frames_round_trip_through_messagepack( + 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(&frame).unwrap(); + prop_assert_eq!(decode_view_patch(&encoded).unwrap(), frame); + } + } + + fn sample_view_patch() -> ViewPatchFrame { + ViewPatchFrame { + sequence: 7, + view_revision: 3, + base_view_revision: Some(2), + resume_token: None, + patch: ScreenPatch { + version: 1, + width: 2, + height: 1, + runs: Vec::new(), + }, + } + } + + #[test] + fn view_patch_matches_versioned_messagepack_golden_vector() { + let encoded = encode_view_patch(&sample_view_patch()).unwrap(); + assert_eq!(encoded, GOLDEN_VIEW_PATCH); + assert_eq!( + decode_view_patch(GOLDEN_VIEW_PATCH).unwrap(), + sample_view_patch() + ); + } + + #[test] + fn view_patch_rejects_unsupported_version_and_malformed_frames() { + let mut unsupported = encode_view_patch(&sample_view_patch()).unwrap(); + unsupported[9] = 2; + assert!(matches!( + decode_view_patch(&unsupported), + Err(ScreenCodecError::UnsupportedVersion(2)) + )); + assert!(matches!( + decode_view_patch(&[0xc1]), + Err(ScreenCodecError::Invalid(_)) + )); + + let mut trailing = encode_view_patch(&sample_view_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) + )); } } diff --git a/pkgs/id/crates/id-web/src/world_ws.rs b/pkgs/id/crates/id-web/src/world_ws.rs index b293875f22..34a75fe81e 100644 --- a/pkgs/id/crates/id-web/src/world_ws.rs +++ b/pkgs/id/crates/id-web/src/world_ws.rs @@ -678,7 +678,10 @@ impl SessionIo for WsIo { return Inbound::Text(text.to_string()); } Some(Ok(Message::Text(_))) => return Inbound::Oversized, - Some(Ok(Message::Binary(_))) => return Inbound::Unsupported, + Some(Ok(Message::Binary(bytes))) if bytes.len() <= MAX_FRAME_BYTES => { + return Inbound::Bytes(bytes.to_vec()); + } + Some(Ok(Message::Binary(_))) => return Inbound::Oversized, Some(Ok(Message::Ping(payload))) => { if self.sender.send(Message::Pong(payload)).await.is_err() { return Inbound::Closed; @@ -693,6 +696,17 @@ impl SessionIo for WsIo { async fn send(&mut self, frame: String) -> bool { self.sender.send(Message::Text(frame.into())).await.is_ok() } + + fn supports_bytes(&self) -> bool { + true + } + + async fn send_bytes(&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..6ac2d7b565 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, 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 +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, 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..babc135050 100644 --- a/pkgs/id/crates/id-worlds/src/world_net.rs +++ b/pkgs/id/crates/id-worlds/src/world_net.rs @@ -417,9 +417,12 @@ impl StreamIo { .await; if admitted { match read_frame_body(&mut recv, len).await { - Ok(body) => match String::from_utf8(body) { - Ok(text) => Inbound::Text(text), - Err(_) => Inbound::Unsupported, + Ok(body) => match crate::frames::unmark_binary_frame(&body) { + Some(payload) => Inbound::Bytes(payload.to_vec()), + None => match String::from_utf8(body) { + Ok(text) => Inbound::Text(text), + Err(_) => Inbound::Unsupported, + }, }, Err(_) => Inbound::Closed, } @@ -478,6 +481,27 @@ impl SessionIo for StreamIo { write_frame(&mut self.send, frame.as_bytes()).await.is_ok() } + fn supports_bytes(&self) -> bool { + true + } + + async fn send_bytes(&mut self, frame: Vec) -> bool { + // Same charge and envelope as a text frame; the body carries + // the binary marker so the peer's reader reports it as bytes. + let body = crate::frames::mark_binary_frame(&frame); + let admitted = charge_frame_with_backpressure( + &self.abuse, + self.remote, + self.authorized.load(Ordering::Acquire), + body.len(), + ) + .await; + if !admitted { + return false; + } + write_frame(&mut self.send, &body).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 c0a3dbd7eb..432b1763a9 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/mod.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/mod.rs @@ -226,7 +226,7 @@ pub async fn run_session_with(hub: &WorldHub, io: &mut I, config: let _ = send_error(&unattributed, io, "world frame is too large").await; return; } - Ok(Inbound::Unsupported) => { + Ok(Inbound::Unsupported) | Ok(Inbound::Bytes(_)) => { let _ = send_error(&unattributed, io, "frames must be UTF-8 text").await; return; } @@ -1122,6 +1122,7 @@ async fn joined( token: JoinCapability, after: Option, screen_patches: bool, + screen_msgpack: bool, resume_token: Option, agent_profile: bool, device_input: Option, @@ -1160,6 +1161,12 @@ async fn joined( .then_some(resume_token) .flatten() .filter(|token| token.len() <= MAX_RESUME_TOKEN_BYTES); + // Binary patch negotiation (F12.11 phase 3, contract revision 12): + // the client offered MessagePack patches and the transport carries + // bytes, so patch frames go out as binary frames. Anything less — + // 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(); if let Some(after) = after { match world.events_after(token.clone(), after).await { Ok(page) if page.needs_snapshot => { @@ -1287,7 +1294,7 @@ async fn joined( Inbound::Oversized => { if !send_error(service.frame_meter(), io, "world frame is too large").await { break; } } - Inbound::Unsupported => { + Inbound::Unsupported | Inbound::Bytes(_) => { if !send_error(service.frame_meter(), io, "frames must be UTF-8 text").await { break; } } Inbound::Closed => break, @@ -2402,6 +2409,19 @@ async fn send_json(meter: &WorldMetrics, io: &mut I, frame: &impl } } +/// Send one already-encoded binary frame, metered like [`send_json`]. +async fn send_binary(meter: &WorldMetrics, io: &mut I, frame: Vec) -> bool { + if frame.len() > MAX_FRAME_BYTES { + return false; + } + let bytes = frame.len() as u64; + let sent = io.send_bytes(frame).await; + if sent { + meter.add_frame_bytes(bytes); + } + sent +} + async fn send_error(meter: &WorldMetrics, io: &mut I, message: &str) -> bool { send_error_with_code(meter, io, None, message).await } 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 eaba618d8d..d1cd219ad1 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, + screen_msgpack, resume_token, agent_profile, device_input, @@ -35,6 +36,7 @@ pub(crate) async fn run_world_session( JoinCapability::from_wire(capability), after, screen_patches, + screen_msgpack, resume_token, agent_profile, device_input, @@ -501,7 +503,7 @@ async fn query_session( let _ = send_error(service.frame_meter(), io, "world frame is too large").await; return; } - Inbound::Unsupported => { + Inbound::Unsupported | Inbound::Bytes(_) => { let _ = send_error(service.frame_meter(), io, "frames must be UTF-8 text").await; return; @@ -514,6 +516,7 @@ async fn query_session( capability, after, screen_patches, + screen_msgpack, resume_token, agent_profile, device_input, @@ -529,6 +532,7 @@ async fn query_session( JoinCapability::from_wire(capability), after, screen_patches, + screen_msgpack, 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 70c7fa160a..b36677a9cb 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/tests.rs @@ -4332,5 +4332,313 @@ mod tests { assert!(frame.get("view").is_none()); assert!(peer.next().await.is_none()); } + + /// One frame a byte-capable transport delivered, text and + /// binary kept apart the way a real transport reports them. + #[derive(Debug)] + enum SentFrame { + Text(String), + Bytes(Vec), + } + + /// In-memory byte-capable transport: like [`ChannelIo`], but + /// it carries binary frames and says so. + struct ByteChannelIo { + inbound: mpsc::Receiver, + outbound: mpsc::Sender, + } + + impl SessionIo for ByteChannelIo { + async fn recv(&mut self) -> Inbound { + self.inbound.recv().await.unwrap_or(Inbound::Closed) + } + + async fn send(&mut self, frame: String) -> bool { + self.outbound.send(SentFrame::Text(frame)).await.is_ok() + } + + fn supports_bytes(&self) -> bool { + true + } + + async fn send_bytes(&mut self, frame: Vec) -> bool { + self.outbound.send(SentFrame::Bytes(frame)).await.is_ok() + } + } + + struct BytePeer { + to_server: mpsc::Sender, + from_server: mpsc::Receiver, + task: tokio::task::JoinHandle<()>, + } + + impl BytePeer { + fn connect(service: WorldService) -> Self { + let (to_server, inbound) = mpsc::channel(16); + let (outbound, from_server) = mpsc::channel(64); + let hub = WorldHub::single(service); + let task = tokio::spawn(async move { + let mut io = ByteChannelIo { inbound, outbound }; + run_session_with(&hub, &mut io, SessionConfig::default()).await; + }); + Self { + to_server, + from_server, + task, + } + } + + async fn say(&self, frame: serde_json::Value) { + self.to_server + .send(Inbound::Text(frame.to_string())) + .await + .unwrap(); + } + + async fn say_bytes(&self, frame: Vec) { + self.to_server.send(Inbound::Bytes(frame)).await.unwrap(); + } + + async fn next(&mut self) -> Option { + tokio::time::timeout(Duration::from_mins(1), self.from_server.recv()) + .await + .expect("timed out waiting for a server frame") + } + + async fn next_text(&mut self) -> serde_json::Value { + match self.next().await { + Some(SentFrame::Text(text)) => serde_json::from_str(&text).unwrap(), + other => panic!("expected a text frame, got {other:?}"), + } + } + + /// The next view-shaped frame, in whichever representation + /// the session negotiated. + async fn next_view_frame(&mut self) -> SentFrame { + loop { + let frame = self.next().await.expect("a frame"); + match &frame { + SentFrame::Text(text) => { + let value: serde_json::Value = serde_json::from_str(text).unwrap(); + if value["type"] == "view" { + return frame; + } + } + SentFrame::Bytes(_) => return frame, + } + } + } + + async fn close(self) { + let Self { + to_server, + from_server, + task, + } = self; + let _ = to_server.send(Inbound::Closed).await; + drop(from_server); + task.await.unwrap(); + } + } + + /// Drives the two-session resume dance on a byte-capable + /// transport and returns the retained token, the base + /// revision, and the screen the first session ended on. + async fn retained_token_on_byte_transport( + svc: &WorldService, + capability: &crate::world::JoinCapability, + step: &AtomicU64, + ) -> (String, u64, crate::world_presentation::ScreenSurface) { + let mut first = BytePeer::connect(svc.clone()); + first + .say(serde_json::json!({ + "type": "join", + "capability": capability.expose(), + "screen_patches": true, + "screen_msgpack": 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": 2, "height": 1})) + .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 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; + (token, base_revision, applied) + } + + #[tokio::test] + async fn msgpack_negotiated_resume_patch_arrives_as_a_binary_frame() { + 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 svc = WorldService::new(world.clone(), None); + let (_, capability) = world + .issue("player".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + let (token, base_revision, mut applied) = + retained_token_on_byte_transport(&svc, &capability, &step).await; + + let mut resumed = BytePeer::connect(svc.clone()); + resumed + .say(serde_json::json!({ + "type": "join", + "capability": capability.expose(), + "screen_patches": true, + "screen_msgpack": 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)); + assert!( + frame.resume_token.is_some(), + "the binary frame names its target revision with a token" + ); + applied = frame + .patch + .apply(&applied) + .expect("the binary patch applies to its base"); + + // Parity: the binary-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)); + let world = WorldHandle::spawn_with_program( + WorldCore::new("lobby", WorldLimits::default()).unwrap(), + Box::new(StepScreen(Arc::clone(&step))), + ); + let svc = WorldService::new(world.clone(), None); + let (_, capability) = world + .issue("player".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + + // The plain ChannelIo cannot carry bytes, so the offer + // cannot be taken up: the session negotiates down to the + // JSON patch path instead of failing or guessing. + let mut first = Peer::connect(svc.clone(), SessionConfig::default()); + first + .say(serde_json::json!({ + "type": "join", + "capability": capability.expose(), + "screen_patches": true, + "screen_msgpack": true, + })) + .await; + assert_eq!(first.next().await.unwrap()["type"], "snapshot"); + assert!(next_view(&mut first).await["patch"].is_null()); + first + .say(serde_json::json!({"type": "resize", "width": 2, "height": 1})) + .await; + let resized = next_view(&mut first).await; + let token = resized["resume_token"].as_str().unwrap().to_owned(); + let base_revision = resized["view_revision"].as_u64().unwrap(); + + step.store(2, Ordering::Relaxed); + let mut resumed = Peer::connect(svc, SessionConfig::default()); + resumed + .say(serde_json::json!({ + "type": "join", + "capability": capability.expose(), + "screen_patches": true, + "screen_msgpack": true, + "resume_token": token, + })) + .await; + assert_eq!(resumed.next().await.unwrap()["type"], "snapshot"); + let catch_up = next_view(&mut resumed).await; + assert!( + !catch_up["patch"].is_null(), + "the catch-up is a JSON patch frame: {catch_up}" + ); + assert_eq!( + catch_up["base_view_revision"].as_u64().unwrap(), + base_revision + ); + } + + #[tokio::test] + async fn a_binary_first_frame_fails_safely() { + let world = WorldHandle::spawn_with_program( + WorldCore::new("lobby", WorldLimits::default()).unwrap(), + Box::new(StepScreen(Arc::new(AtomicU64::new(0)))), + ); + let svc = WorldService::new(world, None); + let mut peer = BytePeer::connect(svc); + peer.say_bytes(vec![0xc1, 0x00, 0xff]).await; + let frame = peer.next_text().await; + assert_eq!(frame["type"], "error"); + assert_eq!(frame["message"], "frames must be UTF-8 text"); + assert!(peer.next().await.is_none(), "the session ends"); + } + + #[tokio::test] + async fn a_binary_frame_after_join_fails_safely() { + let world = WorldHandle::spawn_with_program( + WorldCore::new("lobby", WorldLimits::default()).unwrap(), + Box::new(StepScreen(Arc::new(AtomicU64::new(0)))), + ); + let svc = WorldService::new(world.clone(), None); + let (_, capability) = world + .issue("player".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + let mut peer = BytePeer::connect(svc); + peer.say(serde_json::json!({ + "type": "join", + "capability": capability.expose(), + "screen_patches": true, + "screen_msgpack": true, + })) + .await; + assert_eq!(peer.next_text().await["type"], "snapshot"); + assert!(matches!(peer.next_view_frame().await, SentFrame::Text(_))); + + // A binary client frame is malformed input: an error, and + // the session carries on — it is not silently decoded. + peer.say_bytes(vec![0x82, 0xa7, b'v']).await; + let frame = peer.next_text().await; + assert_eq!(frame["type"], "error"); + assert_eq!(frame["message"], "frames must be UTF-8 text"); + peer.say(serde_json::json!({"type": "resize", "width": 2, "height": 1})) + .await; + assert!(matches!(peer.next_view_frame().await, SentFrame::Text(_))); + } } } 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 a4d3e97465..b23128eac6 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/types.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/types.rs @@ -45,6 +45,12 @@ pub(crate) const MAX_CONCURRENT_MODULE_UPLOADS: usize = 2; pub enum Inbound { /// A complete text frame no larger than [`MAX_FRAME_BYTES`]. Text(String), + /// A complete binary frame no larger than [`MAX_FRAME_BYTES`], on a + /// transport that carries bytes. Client frames are text by protocol, + /// so the driver fails a binary frame safely, exactly like + /// [`Inbound::Unsupported`]; the variant exists so byte-capable + /// transports can report the frame instead of discarding it. + Bytes(Vec), /// A frame larger than [`MAX_FRAME_BYTES`] (its contents are discarded). Oversized, /// A frame that is not UTF-8 text. @@ -53,15 +59,28 @@ pub enum Inbound { Closed, } -/// Moves whole text frames for one session. +/// Moves whole frames for one session. /// /// `recv` must be cancel-safe: the driver races it against world events and a /// cancelled call must not lose or split a frame. pub trait SessionIo: Send { /// Next inbound frame. fn recv(&mut self) -> impl Future + Send; - /// Send one frame. Returns `false` when the peer is gone. + /// Send one text frame. Returns `false` when the peer is gone. fn send(&mut self, frame: String) -> impl Future + Send; + /// Whether this transport can carry binary frames. Only a session + /// on a byte-capable transport may negotiate binary screen patches + /// (F12.11 phase 3); on any other transport the negotiation falls + /// back to the JSON patch path. + fn supports_bytes(&self) -> bool { + false + } + /// Send one binary frame. Returns `false` when the peer is gone — + /// and on transports that cannot carry bytes, which never send. + fn send_bytes(&mut self, frame: Vec) -> impl Future + Send { + let _ = frame; + std::future::ready(false) + } /// Mark this session authorized after its application-level /// capability or admin credential has been validated. fn mark_authorized(&mut self) {} @@ -192,6 +211,15 @@ pub(crate) enum ClientFrame { /// Opt in to revisioned JSON screen patches. Omitted by v1 clients. #[serde(default)] screen_patches: bool, + /// Opt in to negotiated binary screen patches (F12.11 phase 3, + /// contract revision 12): when `screen_patches` is also set and + /// the transport carries bytes, patch frames arrive as versioned + /// MessagePack binary frames instead of JSON `view` frames. + /// Anywhere else — no patch opt-in, a text-only transport — the + /// session keeps the JSON patch path unchanged. Omitted by + /// clients that predate the revision. + #[serde(default)] + screen_msgpack: 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..6e55a23b04 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,11 @@ 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, + /// Negotiated binary patches (F12.11 phase 3, contract revision + /// 12): the join offered `screen_msgpack`, patches are on, and the + /// transport carries bytes, so patch frames are sent as versioned + /// MessagePack binary frames instead of JSON `view` frames. + pub(crate) msgpack_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 @@ -270,6 +275,34 @@ pub(crate) async fn send_view( }; 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()); + // Negotiated binary patches (F12.11 phase 3): the + // 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. + if view_state.msgpack_patches { + let binary = id_core::screen_codec::ViewPatchFrame { + sequence, + view_revision, + base_view_revision: Some(*base_view_revision), + resume_token: resume_token.clone(), + patch: patch.clone(), + }; + if let (Ok(bytes), Ok(full)) = ( + id_core::screen_codec::encode_view_patch(&binary), + &full_size, + ) { + if bytes.len() < *full { + let sent = send_binary(service.frame_meter(), io, bytes).await; + if sent { + view_state.screen = Some((view_revision, screen.clone())); + view_state.note_view_sent(view_revision, Some(screen)); + } + return sent; + } + } + } 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 { diff --git a/pkgs/id/crates/id-worlds/src/world_ssh.rs b/pkgs/id/crates/id-worlds/src/world_ssh.rs index eae5de6fe5..3e9b749690 100644 --- a/pkgs/id/crates/id-worlds/src/world_ssh.rs +++ b/pkgs/id/crates/id-worlds/src/world_ssh.rs @@ -54,7 +54,7 @@ use crate::directory_auth::Caller; use crate::directory_view::{ DirectoryAction, DirectoryOutcome, HELP, Line, parse_line, render_text, }; -use crate::frames::{Decoded, FrameBuffer, encode_frame}; +use crate::frames::{Decoded, FrameBuffer, encode_frame, mark_binary_frame, unmark_binary_frame}; use crate::world::hex_encode; use crate::world_hub::{ResolveError, WorldHub}; #[cfg(test)] @@ -744,6 +744,9 @@ impl SessionIo for SshFrameIo { loop { match self.buffer.next_frame() { Some(Decoded::Frame(body)) => { + if let Some(payload) = unmark_binary_frame(&body) { + return Inbound::Bytes(payload.to_vec()); + } return String::from_utf8(body).map_or(Inbound::Unsupported, Inbound::Text); } // As on iroh, an oversized length ends the stream unread. @@ -764,6 +767,19 @@ impl SessionIo for SshFrameIo { Err(_) => false, } } + + fn supports_bytes(&self) -> bool { + true + } + + async fn send_bytes(&mut self, frame: Vec) -> bool { + // Same envelope as a text frame; the body carries the binary + // marker so the peer's reader reports it as bytes. + match encode_frame(&mark_binary_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