Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions pkgs/id/crates/id-worlds/src/world_session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1164,6 +1164,21 @@ async fn joined<I: SessionIo>(
.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 —
Expand Down
55 changes: 55 additions & 0 deletions pkgs/id/crates/id-worlds/src/world_session/resume.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down
58 changes: 40 additions & 18 deletions pkgs/id/crates/id-worlds/src/world_session/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AtomicU64>);

impl crate::world::WorldProgram for WideScreen {
fn view(&mut self, _viewer: &Participant) -> anyhow::Result<Option<String>> {
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!({
Expand All @@ -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!({
Expand All @@ -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::<crate::world_presentation::ScreenPatch>(
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]
Expand Down
199 changes: 199 additions & 0 deletions pkgs/id/web/src/world-resume.test.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, unknown>> = [];

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<string, unknown>);
}

/** 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<string, unknown>): void {
this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(frame) }));
}

sent(type: string): Array<Record<string, unknown>> {
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 = <T extends HTMLElement>(selector: string): T => {
const found = root.querySelector<T>(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<HTMLElement>("[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<HTMLInputElement>("[data-world-capability]").value = "guest-capability";
q<HTMLButtonElement>("[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<HTMLElement>("[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);
});
});
Loading