From a5a3d39353db2cb3c9b4f21baa9eeecbc5469948 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 16:45:12 -0600 Subject: [PATCH 1/2] fix(id): restore the viewport from the retained baseline on resume A resume token's retained baseline records the viewport that produced it, but joined() initialized every connection's viewport to None, so the first resumed view rendered at the program's default size and the shape-checked consume in send_view always missed for a baseline retained at a non-default viewport. The resume was silently a full view every time. BaselineCache gains a participant-bound, non-consuming peek (viewport_for); joined() restores the viewport from the retained baseline before the first send_view consumes the one-shot token. take_matching still performs the shape-checked consume, and a miss still falls back to a full view. The wrong-viewport test is replaced by the regression this behavior needs: a_resume_token_restores_the_viewport_before_catching_up (the test PR #12246 wrote but never ran), plus a unit test pinning that the peek does not consume. Ported from PR #12246 commit 3751be8, adapted to the post-#12242 session shape. Refs #12648 --- .../crates/id-worlds/src/world_session/mod.rs | 15 +++++ .../id-worlds/src/world_session/resume.rs | 55 ++++++++++++++++++ .../id-worlds/src/world_session/tests.rs | 58 +++++++++++++------ 3 files changed, 110 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 fb8d348947..420700a2b3 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/mod.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/mod.rs @@ -1164,6 +1164,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), + }); + } + } // 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 — 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..90f06f972f 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"); @@ -197,6 +210,18 @@ mod tests { ScreenBaseline::new(participant, revision, 1, 1, 1, screen("a")) } + fn screen_2x1() -> ScreenSurface { + let cell = |glyph: &str| ScreenCell { + symbol: glyph.to_owned(), + fg: 0, + bg: 0, + bold: false, + columns: 1, + token: None, + }; + ScreenSurface::from_cells(2, 1, vec![cell("a"), cell("b")]).expect("a 2x1 screen") + } + #[test] fn a_token_names_one_bound_baseline_and_is_consumed() { let mut cache = BaselineCache::default(); @@ -252,6 +277,36 @@ mod tests { ); } + #[test] + fn viewport_for_peeks_without_consuming() { + let mut cache = BaselineCache::default(); + let token = cache.issue(ScreenBaseline::new(7, 3, 1, 2, 1, screen_2x1())); + assert_eq!( + cache.viewport_for(&token, 8), + None, + "another participant peeks nothing" + ); + assert_eq!( + cache.viewport_for("not-a-token", 7), + None, + "an unknown token peeks nothing" + ); + assert_eq!( + cache.viewport_for(&token, 7), + Some((2, 1)), + "the bound viewport peeks" + ); + let taken = cache + .take_matching(&token, 7, 1, 2, 1) + .expect("the peek left the baseline in place"); + assert_eq!(taken.revision, 3); + assert_eq!( + cache.viewport_for(&token, 7), + None, + "a consumed token peeks nothing" + ); + } + #[test] fn tampered_tokens_are_misses() { let mut cache = BaselineCache::default(); 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 b36677a9cb..56af513bc0 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/tests.rs @@ -4255,27 +4255,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!({ @@ -4285,16 +4296,22 @@ 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 restores that viewport before rendering and + // consuming the resume token; without the restore the retained + // baseline is the wrong shape and the resume is a miss. + step.store(1, Ordering::Relaxed); let mut resumed = Peer::connect(svc, SessionConfig::default()); resumed .say(serde_json::json!({ @@ -4305,16 +4322,21 @@ mod tests { })) .await; assert_eq!(resumed.next().await.unwrap()["type"], "snapshot"); - let view = next_view(&mut resumed).await; - assert!( - view["patch"].is_null(), - "a wrong-viewport token gets a full view: {view}" - ); - assert_eq!(screen_of(&view).width, 3); + let catch_up = next_view(&mut resumed).await; assert!( - view["resume_token"].is_string(), - "the full view issues a token for the new viewport" + !catch_up["patch"].is_null(), + "a retained viewport token yields a catch-up patch: {catch_up}" ); + 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"); } #[tokio::test] From eaea23ead949763884be255b0cf508fb32916299 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 16:45:13 -0600 Subject: [PATCH 2/2] fix(id): browser retains its resume unit across reconnects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The browser never participated in resume: world.ts did not declare resume_token on the frame type, never adopted the token view frames carry, never offered one in the join frame, and connect() cleared the rendered surface and revision on every reconnect — so even a host willing to send a catch-up patch had nothing to patch against. Token, surface, and revision now move as one unit: adopted together from every applied view (JSON and MessagePack paths), offered in the join frame when the unit is complete, and retained across reconnects. A same-size resize no longer goes out on a resumable reconnect (it resets the host's retained baseline); a real viewport change or a forced resync drops all three together and asks for a full view. Host view (the read-only HTTP path) clears the token with the surface, since its renders are not session baselines. New world-resume.test.ts carries the coverage #12648 names: a catch-up patch applies after a reconnect with no intervening resize, and a viewport change drops the unit. Adapted from PR #12246 commit 2b9428d2 to the screen_msgpack negotiation that landed in #12242. Refs #12648 --- pkgs/id/web/src/world-resume.test.ts | 199 +++++++++++++++++++++++++++ pkgs/id/web/src/world.ts | 56 ++++++-- 2 files changed, 246 insertions(+), 9 deletions(-) create mode 100644 pkgs/id/web/src/world-resume.test.ts diff --git a/pkgs/id/web/src/world-resume.test.ts b/pkgs/id/web/src/world-resume.test.ts new file mode 100644 index 0000000000..9bfe83f497 --- /dev/null +++ b/pkgs/id/web/src/world-resume.test.ts @@ -0,0 +1,199 @@ +import { readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +/** + * #12648 regression tests: browser reconnect resume. + * + * Oracle: the host's resume contract (id-worlds world_session). A + * resume token names one retained screen baseline; presented at join + * while the client still holds the exact surface and revision it + * names, the host answers with a catch-up patch whose + * base_view_revision is that revision, and the patch applies to that + * surface. The browser's half of the contract: retain token + surface + * + revision as one unit across a reconnect, offer the token on + * rejoin, keep a same-size resize from resetting the host's retained + * baseline before the patch lands, and drop all three together when + * the viewport actually changes. + */ + +const here = dirname(fileURLToPath(import.meta.url)); + +/** The world page markup, read from the Rust template so the test cannot drift from it. */ +function worldPageMarkup(): string { + const source = readFileSync(resolve(here, "../../crates/id-web/src/templates.rs"), "utf8"); + const start = source.indexOf("pub fn render_world_page"); + const open = source.indexOf('r#"', start); + const close = source.indexOf('"#;', open); + if (start < 0 || open < 0 || close < 0) throw new Error("world page template not found in templates.rs"); + return source.slice(open + 3, close); +} + +class FakeSocket extends EventTarget { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + static readonly all: FakeSocket[] = []; + + readyState = FakeSocket.CONNECTING; + bufferedAmount = 0; + binaryType = "arraybuffer"; + onclose: ((event: Event) => void) | null = null; + readonly sentFrames: Array> = []; + + constructor(readonly url: string) { + super(); + FakeSocket.all.push(this); + } + + send(data: string): void { + if (this.readyState !== FakeSocket.OPEN) throw new Error(`send on a socket in state ${this.readyState}`); + this.sentFrames.push(JSON.parse(data) as Record); + } + + /** Server-initiated drop: the close EVENT arrives asynchronously, as in a browser. */ + close(): void { + if (this.readyState === FakeSocket.CLOSED) return; + this.readyState = FakeSocket.CLOSED; + setTimeout(() => this.dispatchEvent(new Event("close")), 0); + } + + serverDrop(): void { + this.close(); + } + + open(): void { + this.readyState = FakeSocket.OPEN; + this.dispatchEvent(new Event("open")); + } + + deliver(frame: Record): void { + this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(frame) })); + } + + sent(type: string): Array> { + return this.sentFrames.filter((frame) => frame.type === type); + } +} + +class FakeResizeObserver { + static readonly all: FakeResizeObserver[] = []; + + constructor(readonly callback: ResizeObserverCallback) { + FakeResizeObserver.all.push(this); + } + + observe(): void {} + unobserve(): void {} + disconnect(): void {} + + fire(): void { + this.callback([], this as unknown as ResizeObserver); + } +} + +describe("world page reconnect resume (#12648)", () => { + const realWebSocket = globalThis.WebSocket; + const realResizeObserver = globalThis.ResizeObserver; + let root: HTMLElement; + const q = (selector: string): T => { + const found = root.querySelector(selector); + if (!found) throw new Error(`missing ${selector}`); + return found; + }; + const viewText = () => q("[data-world-view]").textContent ?? ""; + + const screenA = { + kind: "screen", + version: 1, + width: 1, + height: 1, + cells: [{ symbol: "A", fg: 7, bg: 0, bold: false, columns: 1 }], + }; + + beforeAll(async () => { + vi.stubGlobal("WebSocket", FakeSocket); + vi.stubGlobal("ResizeObserver", FakeResizeObserver); + sessionStorage.clear(); + document.body.innerHTML = worldPageMarkup(); + await import("./world"); + root = document.querySelector("[data-world-app]") as HTMLElement; + expect(root.dataset.initialized).toBe("true"); + }); + + afterAll(() => { + vi.stubGlobal("WebSocket", realWebSocket); + vi.stubGlobal("ResizeObserver", realResizeObserver); + document.body.innerHTML = ""; + }); + + it("retains the resume unit across a reconnect and applies the catch-up patch", async () => { + q("[data-world-capability]").value = "guest-capability"; + q("[data-world-join]").click(); + const first = FakeSocket.all.at(-1) as FakeSocket; + first.open(); + expect(first.sent("join")).toHaveLength(1); + first.deliver({ + type: "snapshot", + snapshot: { world_id: "lobby", current_sequence: 3, participants: [] }, + }); + first.deliver({ + type: "view", + sequence: 3, + data: "", + surface: screenA, + view_revision: 1, + resume_token: "resume-1", + }); + expect(viewText()).toContain("A"); + + // Drop and let the backoff reconnect happen on its own. + first.serverDrop(); + await vi.waitFor(() => expect(FakeSocket.all.length).toBeGreaterThan(1), { timeout: 3000, interval: 50 }); + const resumed = FakeSocket.all.at(-1) as FakeSocket; + resumed.open(); + + // The rejoin offers the retained token, and no resize has reset + // the host's retained baseline before its answer. + expect(resumed.sent("join")[0]).toMatchObject({ resume_token: "resume-1" }); + expect(resumed.sent("resize")).toHaveLength(0); + + // The host's catch-up patch applies to the retained surface with + // no intervening resize or full view. + resumed.deliver({ + type: "view", + sequence: 3, + patch: { + version: 1, + width: 1, + height: 1, + runs: [{ start: 0, cells: [{ symbol: "B", fg: 7, bg: 0, bold: false, columns: 1 }] }], + }, + base_view_revision: 1, + view_revision: 2, + resume_token: "resume-2", + }); + expect(viewText()).toContain("B"); + expect(resumed.sent("resize")).toHaveLength(0); + }); + + it("drops the resume unit when the viewport actually changes", async () => { + const current = FakeSocket.all.at(-1) as FakeSocket; + const pane = q("[data-world-view]"); + Object.defineProperty(pane, "clientWidth", { configurable: true, value: 96 }); + Object.defineProperty(pane, "clientHeight", { configurable: true, value: 32 }); + for (const observer of FakeResizeObserver.all) observer.fire(); + // 96 / (16 * 0.6) = 10 columns, 32 / 16 = 2 rows. + expect(current.sent("resize").at(-1)).toMatchObject({ width: 10, height: 2 }); + + current.serverDrop(); + await vi.waitFor(() => expect(FakeSocket.all.length).toBeGreaterThan(2), { timeout: 3000, interval: 50 }); + const rejoined = FakeSocket.all.at(-1) as FakeSocket; + rejoined.open(); + expect(rejoined.sent("join")[0].resume_token).toBeUndefined(); + // A fresh session still reports its viewport on open. + expect(rejoined.sent("resize").length).toBeGreaterThan(0); + }); +}); diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index 18b9e0ba00..b7809269bc 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -41,6 +41,7 @@ type WorldFrame = { view_revision?: number; base_view_revision?: number; patch?: ScreenPatch; + resume_token?: string | null; invite?: { capability?: string; participant_id?: number; display_name?: string }; capability?: string; records?: Record; @@ -136,6 +137,8 @@ function initWorld(): void { let cursor = 0; let renderedSurface: ScreenSurface | null = null; let renderedViewRevision: number | null = null; + let resumeToken: string | null = null; + let sentViewport: { width: number; height: number } | null = null; let records: Record = {}; let recordsAfter: string | null = null; let recordsPending = false; @@ -246,10 +249,11 @@ function initWorld(): void { if (patched && renderWorldSurface(view, patched)) { renderedSurface = patched; renderedViewRevision = frame.view_revision; + resumeToken = frame.resume_token; return; } } - sendViewport(); + sendViewport(true); }; const receive = (raw: string) => { @@ -311,7 +315,8 @@ 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; @@ -326,12 +331,14 @@ function initWorld(): void { if (patched && renderWorldSurface(view, patched)) { renderedSurface = patched; renderedViewRevision = frame.view_revision; + resumeToken = frame.resume_token ?? null; 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(); + // base. A forced same-size resize asks the server to reset with a + // full view, and the stale unit is dropped with it. + sendViewport(true); break; } if (frame.surface && frame.surface.kind === "form") { @@ -339,6 +346,7 @@ function initWorld(): void { // browser's own input manifest; the program supplies data only. // The authoritative screen is replaced, so drop its patch base. renderedSurface = null; + resumeToken = null; renderedViewRevision = frame.view_revision ?? null; formPresenter.present(frame.surface); break; @@ -347,12 +355,14 @@ function initWorld(): void { formPresenter.present(null); renderedSurface = frame.surface; renderedViewRevision = frame.view_revision ?? null; + resumeToken = frame.resume_token ?? null; break; } if (frame.data !== undefined) { formPresenter.present(null); view.textContent = frame.data; renderedSurface = null; + resumeToken = null; renderedViewRevision = frame.view_revision ?? null; } break; @@ -499,14 +509,34 @@ function initWorld(): void { } }); - const sendViewport = () => { + // The resume unit: the token is worth sending only together with the + // exact surface and revision it names. All three are retained across + // reconnects and dropped together — a catch-up patch applies only to + // that exact base, and the host honors the token only for the + // viewport that produced the baseline. + const hasResumableScreen = () => resumeToken !== null && renderedSurface !== null && renderedViewRevision !== null; + const dropResumeUnit = () => { + renderedSurface = null; + renderedViewRevision = null; + resumeToken = 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 host's retained screen baseline. + // Keep it out of an unchanged reconnect so the resume token can + // catch up against the retained surface instead. + if (!force && sameAsLast) return; + // A forced resync or a real viewport change invalidates the local + // base too: the host answers with a full view at the new size. + if (force || sentViewport !== null) dropResumeUnit(); 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); @@ -533,6 +563,7 @@ function initWorld(): void { setStatus("Loading read-only host view…"); renderedSurface = null; renderedViewRevision = null; + resumeToken = null; const world = selectedWorld(); let after: string | null = null; let pages = 0; @@ -577,6 +608,7 @@ function initWorld(): void { } renderedSurface = null; renderedViewRevision = null; + resumeToken = null; if (result.surface && renderWorldSurface(view, result.surface)) { renderedSurface = result.surface; } else if (result.view) { @@ -614,8 +646,11 @@ function initWorld(): void { // (block) this connection's first fetch. recordsPending = false; recordsRefetch = false; - renderedSurface = null; - renderedViewRevision = null; + // The resume unit (surface, revision, token) deliberately survives + // a reconnect: the join below offers the token, and the host + // answers with a catch-up patch against exactly this surface — or + // a full view when the token misses, which replaces the unit + // wholesale. Clearing it here is what wasted the patch round-trip. 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 @@ -638,6 +673,7 @@ function initWorld(): void { world: selectedWorld(), screen_patches: true, screen_msgpack: true, + resume_token: hasResumableScreen() ? resumeToken : undefined, device_input: { keys: 128, encoder: false, @@ -646,7 +682,9 @@ function initWorld(): void { }, }), ); - sendViewport(); + // A fresh session needs its initial resize. A resumable + // reconnect keeps the established viewport unless it changed. + sendViewport(!hasResumableScreen()); }); ws.addEventListener("message", (event) => { if (ws !== socket) return;