From d488f321cab9f53a603b5bc596731a54b81ad8eb Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 13:07:32 -0600 Subject: [PATCH] =?UTF-8?q?feat(id):=20revisioned=20JSON=20ScreenPatch=20v?= =?UTF-8?q?iew=20frames=20=E2=80=94=20#805=20Phase=201=20(task=205842)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkgs/id/Cargo.lock | 1 + pkgs/id/contract/shell-contract.v1.json | 14 +- pkgs/id/crates/id-core/Cargo.toml | 7 + .../crates/id-core/src/world_presentation.rs | 30 +++- pkgs/id/src/shell_contract/tests.rs | 3 + pkgs/id/src/world_session/mod.rs | 170 +++++++++++++++--- pkgs/id/src/world_session/tests.rs | 6 + pkgs/id/src/world_session/types.rs | 11 ++ pkgs/id/web/src/world-surface.test.ts | 74 +++++++- pkgs/id/web/src/world-surface.ts | 32 ++++ pkgs/id/web/src/world.ts | 49 ++++- 11 files changed, 361 insertions(+), 36 deletions(-) diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 1a9ef6f6d8..f8d4a026f5 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -3082,6 +3082,7 @@ dependencies = [ "tracing", "unicode-segmentation", "unicode-width", + "vt100", ] [[package]] diff --git a/pkgs/id/contract/shell-contract.v1.json b/pkgs/id/contract/shell-contract.v1.json index c891ffcac8..a0410090e0 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": 3, + "revision": 4, "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. A new frame kind waits for the journal format work (F11.12, #227).", "max_frame_bytes": 1048576, "routing_fields": ["world"], @@ -43,7 +43,8 @@ "opens": "joined", "fields": { "capability": { "type": "string", "max_bytes": 256 }, - "after": "u64?" + "after": "u64?", + "screen_patches": { "type": "bool", "optional": true, "nullable": false } } }, "info": { @@ -279,7 +280,14 @@ }, "view": { "class": "ephemeral", - "fields": { "sequence": "u64", "data": "string", "surface": "object?" } + "fields": { + "sequence": "u64", + "data": "string", + "surface": "object?", + "view_revision": "u64", + "base_view_revision": "u64?", + "patch": "object?" + } }, "program_changed": { "class": "reply", diff --git a/pkgs/id/crates/id-core/Cargo.toml b/pkgs/id/crates/id-core/Cargo.toml index 226cb4769f..11ad735b2c 100644 --- a/pkgs/id/crates/id-core/Cargo.toml +++ b/pkgs/id/crates/id-core/Cargo.toml @@ -36,6 +36,13 @@ unicode-width = "0.2" [dev-dependencies] # Decodes the QR images rendered by the extracted module's round-trip tests. rqrr = { version = "0.11.0", default-features = false } +# Crate-split fallout (#3447): the presentation ANSI-diff tests and the +# connectivity startup-wait tests moved into this crate with the modules, +# but their test-only dependencies stayed behind in the parent crate's +# dev-dependencies, so this crate's test targets did not compile on +# their own. Same pins as the parent crate. Dev only; no runtime effect. +vt100 = "=0.16.2" +iroh = { version = "1", features = ["test-utils"] } [lints.rust] # Rust compiler lints diff --git a/pkgs/id/crates/id-core/src/world_presentation.rs b/pkgs/id/crates/id-core/src/world_presentation.rs index 3c52fda43e..8954aeac03 100644 --- a/pkgs/id/crates/id-core/src/world_presentation.rs +++ b/pkgs/id/crates/id-core/src/world_presentation.rs @@ -202,12 +202,7 @@ impl ScreenPatch { cells[start..end].clone_from_slice(&run.cells); covered_until = end; } - Some(ScreenSurface { - version: prev.version, - width: prev.width, - height: prev.height, - cells, - }) + ScreenSurface::from_cells(usize::from(prev.width), usize::from(prev.height), cells).ok() } /// Whether the patch changes nothing (the two screens are identical). @@ -669,6 +664,29 @@ mod tests { assert_eq!(bad.apply(&small), None, "run past the last cell"); } + #[test] + fn patch_refuses_a_result_that_is_not_a_valid_screen() { + let previous = grid(2, 1, " "); + let invalid = ScreenPatch { + version: 1, + width: 2, + height: 1, + runs: vec![CellRun { + start: 0, + cells: vec![ + ScreenCell { + symbol: "界".to_owned(), + columns: 2, + ..cell("界") + }, + cell("x"), + ], + }], + }; + + assert_eq!(invalid.apply(&previous), None); + } + #[test] fn ansi_diff_repaints_changed_rows_with_terminal_parity_and_byte_savings() { let previous = grid(80, 24, " "); diff --git a/pkgs/id/src/shell_contract/tests.rs b/pkgs/id/src/shell_contract/tests.rs index 98124e2deb..f05f7ac4bc 100644 --- a/pkgs/id/src/shell_contract/tests.rs +++ b/pkgs/id/src/shell_contract/tests.rs @@ -143,6 +143,9 @@ fn every_server_frame_variant_is_in_the_contract_and_nothing_else_is() { sequence: 1, data: "x", surface: None, + view_revision: 0, + base_view_revision: None, + patch: None, }, ServerFrame::RecordsTicket { ticket: "t".to_owned(), diff --git a/pkgs/id/src/world_session/mod.rs b/pkgs/id/src/world_session/mod.rs index 2e00f24660..2615c9e8a0 100644 --- a/pkgs/id/src/world_session/mod.rs +++ b/pkgs/id/src/world_session/mod.rs @@ -1058,12 +1058,23 @@ pub(crate) fn moderation_authority( /// Serve one session against its resolved world, starting from its first frame. async fn run_world_session(service: &WorldService, io: &mut I, frame: ClientFrame) { match frame { - ClientFrame::Join { capability, after } => { + ClientFrame::Join { + capability, + after, + screen_patches, + } => { if capability.len() > MAX_CAPABILITY_BYTES { let _ = send_error(service.frame_meter(), io, "invalid join capability").await; return; } - joined(service, io, JoinCapability::from_wire(capability), after).await; + joined( + service, + io, + JoinCapability::from_wire(capability), + after, + screen_patches, + ) + .await; } ClientFrame::Invite { admin_token, @@ -1440,12 +1451,23 @@ async fn query_session(service: &WorldService, io: &mut I, first: }, }; match frame { - ClientFrame::Join { capability, after } => { + ClientFrame::Join { + capability, + after, + screen_patches, + } => { if capability.len() > MAX_CAPABILITY_BYTES { let _ = send_error(service.frame_meter(), io, "invalid join capability").await; return; } - joined(service, io, JoinCapability::from_wire(capability), after).await; + joined( + service, + io, + JoinCapability::from_wire(capability), + after, + screen_patches, + ) + .await; return; } ClientFrame::Info { capability } => { @@ -1848,6 +1870,7 @@ async fn joined( io: &mut I, token: JoinCapability, after: Option, + screen_patches: bool, ) { let world = service.world(); // Subscribe before taking the snapshot so no event can fall in the gap; @@ -1864,6 +1887,7 @@ async fn joined( }; let mut cursor = snapshot.current_sequence; let mut viewport = None; + let mut view_state = ViewRevisionState::default(); if let Some(after) = after { match world.events_after(token.clone(), after).await { Ok(page) if page.needs_snapshot => { @@ -1894,6 +1918,8 @@ async fn joined( &token, event.sequence, viewport, + &mut view_state, + screen_patches, ) .await { @@ -1917,7 +1943,18 @@ async fn joined( { return; } - if !send_view(service.frame_meter(), world, io, &token, cursor, viewport).await { + if !send_view( + service.frame_meter(), + world, + io, + &token, + cursor, + viewport, + &mut view_state, + screen_patches, + ) + .await + { return; } @@ -1935,7 +1972,16 @@ async fn joined( tokio::select! { inbound = io.recv() => match inbound { Inbound::Text(text) => { - if !handle_client_frame(service, io, &token, &text, &mut viewport, cursor).await { + if !handle_client_frame( + service, + io, + &token, + &text, + &mut viewport, + cursor, + &mut view_state, + screen_patches, + ).await { break; } } @@ -1959,7 +2005,11 @@ async fn joined( if !send_json(service.frame_meter(), io, &ServerFrame::ProgramChanged { module_hash, sequence: cursor, - }).await || !send_view(service.frame_meter(), world, io, &token, cursor, viewport).await { + }).await { + break; + } + view_state.reset(); + if !send_view(service.frame_meter(), world, io, &token, cursor, viewport, &mut view_state, screen_patches).await { break; } } @@ -1982,7 +2032,7 @@ async fn joined( if !send_json(service.frame_meter(), io, &ServerFrame::Event { event: &shown }).await { break; } - if !send_view(service.frame_meter(), world, io, &token, cursor, viewport).await { + if !send_view(service.frame_meter(), world, io, &token, cursor, viewport, &mut view_state, screen_patches).await { break; } } @@ -1992,7 +2042,8 @@ async fn joined( break; } cursor = snapshot.current_sequence; - if !send_view(service.frame_meter(), world, io, &token, cursor, viewport).await { + view_state.reset(); + if !send_view(service.frame_meter(), world, io, &token, cursor, viewport, &mut view_state, screen_patches).await { break; } } @@ -2001,7 +2052,7 @@ async fn joined( changed = views.changed() => match changed { Ok(()) => { let sequence = *views.borrow_and_update(); - if !send_view(service.frame_meter(), world, io, &token, sequence, viewport).await { + if !send_view(service.frame_meter(), world, io, &token, sequence, viewport, &mut view_state, screen_patches).await { break; } } @@ -2035,6 +2086,18 @@ impl Drop for PresenceGuard { } } +#[derive(Default)] +struct ViewRevisionState { + next_revision: u64, + screen: Option<(u64, crate::world_presentation::ScreenSurface)>, +} + +impl ViewRevisionState { + fn reset(&mut self) { + self.screen = None; + } +} + async fn send_view( meter: &WorldMetrics, world: &WorldHandle, @@ -2042,6 +2105,8 @@ async fn send_view( token: &JoinCapability, sequence: u64, viewport: Option, + view_state: &mut ViewRevisionState, + screen_patches: bool, ) -> bool { let view = match viewport { Some(viewport) => { @@ -2066,18 +2131,66 @@ async fn send_view( Ok(surface) => surface, Err(_) => return send_error(meter, io, "invalid world screen presentation").await, }; - send_json( - meter, - io, - &ServerFrame::View { - sequence, - data: &data, - surface: surface.as_ref(), - }, - ) - .await + let view_revision = view_state.next_revision; + view_state.next_revision = view_state.next_revision.saturating_add(1); + let screen = match surface.as_ref() { + Some(crate::world_presentation::WorldSurface::Screen(screen)) => Some(screen), + _ => None, + }; + + if let (true, Some(screen), Some((base_view_revision, previous))) = + (screen_patches, screen, view_state.screen.as_ref()) + { + if let Some(patch) = crate::world_presentation::ScreenPatch::diff(previous, screen) + { + let delta_frame = ServerFrame::View { + sequence, + data: "", + surface: None, + view_revision, + base_view_revision: Some(*base_view_revision), + patch: Some(&patch), + }; + let full_frame = ServerFrame::View { + sequence, + data: &data, + surface: surface.as_ref(), + view_revision, + base_view_revision: None, + patch: None, + }; + 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(meter, io, &delta_frame).await; + if sent { + view_state.screen = Some((view_revision, screen.clone())); + } + return sent; + } + } + } + + let full_frame = ServerFrame::View { + sequence, + data: &data, + surface: surface.as_ref(), + view_revision, + base_view_revision: None, + patch: None, + }; + let sent = send_json(meter, io, &full_frame).await; + if sent && screen_patches { + view_state.screen = screen.map(|screen| (view_revision, screen.clone())); + } else { + view_state.reset(); + } + sent + } + Ok(None) => { + view_state.reset(); + true } - Ok(None) => true, Err(_) => false, } } @@ -2134,6 +2247,8 @@ async fn handle_client_frame( text: &str, viewport: &mut Option, sequence: u64, + view_state: &mut ViewRevisionState, + screen_patches: bool, ) -> bool { let world = service.world(); let Ok(value) = serde_json::from_str::(text) else { @@ -2196,7 +2311,18 @@ async fn handle_client_frame( width: clamped_width, height: clamped_height, }); - return send_view(service.frame_meter(), world, io, token, sequence, *viewport).await; + view_state.reset(); + return send_view( + service.frame_meter(), + world, + io, + token, + sequence, + *viewport, + view_state, + screen_patches, + ) + .await; } ClientFrame::Paste { text } => { let Ok(bytes) = normalize_paste(&text) else { diff --git a/pkgs/id/src/world_session/tests.rs b/pkgs/id/src/world_session/tests.rs index 7a8968ffb4..b88c0fed2b 100644 --- a/pkgs/id/src/world_session/tests.rs +++ b/pkgs/id/src/world_session/tests.rs @@ -881,6 +881,9 @@ mod tests { sequence: 3, data: "count=1", surface: None, + view_revision: 0, + base_view_revision: None, + patch: None, }) .unwrap(); assert!(view.contains("\"type\":\"view\"")); @@ -898,6 +901,9 @@ mod tests { sequence: 8, data, surface: Some(&surface), + view_revision: 1, + base_view_revision: None, + patch: None, }) .unwrap(); assert!(encoded.contains("\"data\":\"{\\\"kind\\\":\\\"screen\\\"")); diff --git a/pkgs/id/src/world_session/types.rs b/pkgs/id/src/world_session/types.rs index fbc0bf27e2..5a1273d50c 100644 --- a/pkgs/id/src/world_session/types.rs +++ b/pkgs/id/src/world_session/types.rs @@ -82,6 +82,9 @@ pub(crate) enum ClientFrame { Join { capability: String, after: Option, + /// Opt in to revisioned JSON screen patches. Omitted by v1 clients. + #[serde(default)] + screen_patches: bool, }, Info { capability: String, @@ -286,6 +289,14 @@ pub(crate) enum ServerFrame<'a> { /// Optional typed screen surface. Older clients can continue using `data`. #[serde(skip_serializing_if = "Option::is_none")] surface: Option<&'a crate::world_presentation::WorldSurface>, + /// Monotonic within this session; independent of the world event cursor. + view_revision: u64, + /// Present only when `patch` applies to this exact prior view revision. + #[serde(skip_serializing_if = "Option::is_none")] + base_view_revision: Option, + /// A negotiated screen delta. `data` is empty and `surface` omitted. + #[serde(skip_serializing_if = "Option::is_none")] + patch: Option<&'a crate::world_presentation::ScreenPatch>, }, ModuleInfo { world_id: String, diff --git a/pkgs/id/web/src/world-surface.test.ts b/pkgs/id/web/src/world-surface.test.ts index a2a3a5314e..a3ecc6a3a0 100644 --- a/pkgs/id/web/src/world-surface.test.ts +++ b/pkgs/id/web/src/world-surface.test.ts @@ -1,11 +1,83 @@ import { describe, expect, it } from "vitest"; -import { renderWorldSurface, type ScreenSurface } from "./world-surface"; +import { applyScreenPatch, renderWorldSurface, type ScreenSurface } from "./world-surface"; function makeScreen(cells: ScreenSurface["cells"]): ScreenSurface { return { kind: "screen", version: 1, width: cells.length, height: 1, cells }; } describe("world screen presenter", () => { + it("applies revision-independent cell runs to the same validated surface as a full frame", () => { + const previous: ScreenSurface = { + kind: "screen", + version: 1, + width: 4, + height: 1, + cells: [ + { symbol: "a", fg: 0, bg: 0, bold: false, columns: 1 }, + { symbol: "b", fg: 0, bg: 0, bold: false, columns: 1 }, + { symbol: "c", fg: 0, bg: 0, bold: false, columns: 1 }, + { symbol: "d", fg: 0, bg: 0, bold: false, columns: 1 }, + ], + }; + const patch = { + version: 1, + width: 4, + height: 1, + runs: [ + { start: 0, cells: [{ symbol: "界", fg: 0, bg: 0, bold: false, columns: 2 }, { symbol: "", fg: 0, bg: 0, bold: false, columns: 0 }] }, + { start: 3, cells: [{ symbol: "x", fg: 4, bg: 0, bold: true, columns: 1 }] }, + ], + }; + const full: ScreenSurface = { ...previous, cells: [...patch.runs[0].cells, previous.cells[2], ...patch.runs[1].cells] }; + const applied = applyScreenPatch(previous, patch); + expect(applied).toEqual(full); + const root = document.createElement("div"); + expect(applied && renderWorldSurface(root, applied)).toBe(true); + expect(renderWorldSurface(document.createElement("div"), full)).toBe(true); + }); + + it("rejects malformed, overlapping, out-of-range, and invalid-cell patches", () => { + const previous = makeScreen([ + { symbol: "a", fg: 0, bg: 0, bold: false, columns: 1 }, + { symbol: "b", fg: 0, bg: 0, bold: false, columns: 1 }, + ]); + const patch = (runs: Array<{ start: number; cells: ScreenSurface["cells"] }>) => ({ + version: 1, + width: 2, + height: 1, + runs, + }); + expect(applyScreenPatch(previous, patch([{ start: 1, cells: [previous.cells[1]] }, { start: 1, cells: [previous.cells[0]] }]))).toBeNull(); + expect(applyScreenPatch(previous, patch([{ start: 2, cells: [previous.cells[0]] }]))).toBeNull(); + expect( + applyScreenPatch( + previous, + patch([ + { + start: 0, + cells: [ + { symbol: "界", fg: 0, bg: 0, bold: false, columns: 2 }, + { symbol: "x", fg: 0, bg: 0, bold: false, columns: 1 }, + ], + }, + ]), + ), + ).not.toBeNull(); + const invalid = applyScreenPatch( + previous, + patch([ + { + start: 0, + cells: [ + { symbol: "界", fg: 0, bg: 0, bold: false, columns: 2 }, + { symbol: "x", fg: 0, bg: 0, bold: false, columns: 1 }, + ], + }, + ]), + ); + expect(invalid && renderWorldSurface(document.createElement("div"), invalid)).toBe(false); + }); + it("uses text nodes and fixed palette styles, not guest HTML", () => { const root = document.createElement("div"); const markup = "<"; diff --git a/pkgs/id/web/src/world-surface.ts b/pkgs/id/web/src/world-surface.ts index 29de837fc3..b97984e2f6 100644 --- a/pkgs/id/web/src/world-surface.ts +++ b/pkgs/id/web/src/world-surface.ts @@ -16,6 +16,38 @@ export type ScreenCell = { columns: number; }; +export type ScreenPatch = { + version: number; + width: number; + height: number; + runs: Array<{ start: number; cells: ScreenCell[] }>; +}; + +/** Apply a bounded, ordered row-major patch without mutating its base. */ +export function applyScreenPatch(previous: ScreenSurface, patch: ScreenPatch): ScreenSurface | null { + if ( + !previous || + !patch || + patch.version !== previous.version || + patch.width !== previous.width || + patch.height !== previous.height || + !Array.isArray(patch.runs) || + previous.cells.length !== previous.width * previous.height + ) { + return null; + } + const cells = previous.cells.slice(); + let coveredUntil = 0; + for (const run of patch.runs) { + if (!run || !Number.isInteger(run.start) || run.start < coveredUntil || !Array.isArray(run.cells)) return null; + const end = run.start + run.cells.length; + if (!Number.isSafeInteger(end) || end > cells.length) return null; + for (let index = 0; index < run.cells.length; index++) cells[run.start + index] = run.cells[index]; + coveredUntil = end; + } + return { ...previous, cells }; +} + const MAX_SCREEN_WIDTH = 120; const MAX_SCREEN_HEIGHT = 50; const MAX_SCREEN_CELLS = MAX_SCREEN_WIDTH * MAX_SCREEN_HEIGHT; diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index 2b7d63efb5..965961996c 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -2,7 +2,7 @@ import { terminalBytesForKey } from "./world-keyboard"; import { parseWorldSeed } from "./world-seed"; -import { renderWorldSurface, type ScreenSurface } from "./world-surface"; +import { applyScreenPatch, renderWorldSurface, type ScreenPatch, type ScreenSurface } from "./world-surface"; type WorldFrame = { type: @@ -28,6 +28,9 @@ type WorldFrame = { sequence?: number; data?: string; surface?: ScreenSurface; + view_revision?: number; + base_view_revision?: number; + patch?: ScreenPatch; invite?: { capability?: string; participant_id?: number; display_name?: string }; capability?: string; records?: Record; @@ -116,6 +119,8 @@ function initWorld(): void { capability.value = sessionStorage.getItem(storageKey) ?? ""; let socket: WebSocket | null = null; let cursor = 0; + let renderedSurface: ScreenSurface | null = null; + let renderedViewRevision: number | null = null; let records: Record = {}; let recordsAfter: string | null = null; let recordsPending = false; @@ -173,8 +178,34 @@ function initWorld(): void { break; } case "view": - if (frame.surface && renderWorldSurface(view, frame.surface)) break; - if (frame.data !== undefined) view.textContent = frame.data; + if (frame.patch) { + if ( + renderedSurface && + renderedViewRevision === frame.base_view_revision && + typeof frame.view_revision === "number" + ) { + const patched = applyScreenPatch(renderedSurface, frame.patch); + if (patched && renderWorldSurface(view, patched)) { + renderedSurface = patched; + renderedViewRevision = frame.view_revision; + break; + } + } + // 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(); + break; + } + if (frame.surface && renderWorldSurface(view, frame.surface)) { + renderedSurface = frame.surface; + renderedViewRevision = frame.view_revision ?? null; + break; + } + if (frame.data !== undefined) { + view.textContent = frame.data; + renderedSurface = null; + renderedViewRevision = frame.view_revision ?? null; + } break; case "records": { if (!recordsPending) return; @@ -297,6 +328,8 @@ function initWorld(): void { // (block) this connection's first fetch. recordsPending = false; recordsRefetch = false; + renderedSurface = null; + renderedViewRevision = null; const scheme = location.protocol === "https:" ? "wss:" : "ws:"; // #1461: every handler captures THIS connection's socket (`ws`) and // ignores events once it is no longer the current one. The handlers @@ -310,7 +343,15 @@ function initWorld(): void { ws.addEventListener("open", () => { if (ws !== socket) return; reconnects = 0; - ws.send(JSON.stringify({ type: "join", capability: token, after: cursor || null, world: selectedWorld() })); + ws.send( + JSON.stringify({ + type: "join", + capability: token, + after: cursor || null, + world: selectedWorld(), + screen_patches: true, + }), + ); sendViewport(); }); ws.addEventListener("message", (event) => {