diff --git a/pkgs/id/book/design/first-apps.md b/pkgs/id/book/design/first-apps.md index a0e5d76af1..677316481b 100644 --- a/pkgs/id/book/design/first-apps.md +++ b/pkgs/id/book/design/first-apps.md @@ -34,7 +34,7 @@ The platform's working first apps are the 9 deployable Roc guest apps in `pkgs/i | territory | `examples/territory/` | Multiplayer territory game: at most 8 seated players on a 16×8 grid, adjacency-only claiming, seats persist across leave, rejoin and restart. | | roc-cap-demo | `examples/roc-cap-demo/` | Library-import worked example (#5957): a capability-dependent Roc library over `records.read`, with two compile-must-fail negative tests. | -Two neighbouring directories are not apps: `examples/roc-world/` is the shared platform package, and `examples/roc-import-policy/` is a compile-fixture matrix for the import gate. The Rust twins (`examples/rust-counter/`, `examples/rust-world/`) are the F12.8 guest SDK and its counter example, not Roc apps. `examples/first-app-poc/` is a README only: the sticky-notes and did-it proof of concept of #2031, whose executable artifact is the Rust integration test `tests/first_app_poc.rs`, by design. +Two neighbouring directories are not apps: `examples/roc-world/` is the shared platform package, and `examples/roc-import-policy/` is a compile-fixture matrix for the import gate. The Rust twins (`examples/rust-counter/`, `examples/rust-world/`) are the F12.8 guest SDK and its counter example, not Roc apps; `examples/rust-sketch/` is the sketch/redo-as-new-stroke guest (#13608), whose domain model and literal-vector tests live in the crate and whose host load/play fixture is the `tests/sketch_host_play.rs` integration test (#13656). `examples/first-app-poc/` is a README only: the sticky-notes and did-it proof of concept of #2031, whose executable artifact is the Rust integration test `tests/first_app_poc.rs`, by design. ## The ecosystem ladder (#6278) diff --git a/pkgs/id/book/development/add-a-guest.md b/pkgs/id/book/development/add-a-guest.md index 3ae396c624..ccd7ee5e33 100644 --- a/pkgs/id/book/development/add-a-guest.md +++ b/pkgs/id/book/development/add-a-guest.md @@ -20,6 +20,7 @@ Worked examples live in `pkgs/id/examples/`. Each app is a directory holding its | `examples/roc-cap-demo/` | A capability-dependent Roc library plus its app, with two compile-must-fail negative tests for the library import gate. | | `examples/roc-import-policy/` | Not an app: the compile-fixture matrix for the import gate, executed by the `id-caps` integration test `roc_import_policy`. | | `examples/rust-world/`, `examples/rust-counter/` | Not Roc: the Rust twin SDK (`plaza_sdk`) and its counter example, emitting the same Plaza exports. | +| `examples/rust-sketch/` | Not Roc: the `sketch/redo-as-new-stroke` guest (#13608) on `plaza_sdk` — draft vertices stay transient, confirmed strokes are immutable, undo leaves a tombstone, and copy assigns a fresh ID with provenance. Its host load/play fixture is `tests/sketch_host_play.rs` (#13656); `just test-sketch` runs both. | | `apps/tic-tac-toe/` | The one packaged app, outside `examples/`: an `app.toml` plus `program/main.roc`. Packaging is an `app.toml` declaring `[program] kind = "roc-world"` and the `[interfaces.web]` binding where the app takes a web surface. | ## Scaffold a new app diff --git a/pkgs/id/examples/rust-sketch/Cargo.lock b/pkgs/id/examples/rust-sketch/Cargo.lock new file mode 100644 index 0000000000..f4f35b76c7 --- /dev/null +++ b/pkgs/id/examples/rust-sketch/Cargo.lock @@ -0,0 +1,14 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "plaza-sdk" +version = "0.1.0" + +[[package]] +name = "rust-sketch" +version = "0.1.0" +dependencies = [ + "plaza-sdk", +] diff --git a/pkgs/id/examples/rust-sketch/Cargo.toml b/pkgs/id/examples/rust-sketch/Cargo.toml new file mode 100644 index 0000000000..6193874a13 --- /dev/null +++ b/pkgs/id/examples/rust-sketch/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "rust-sketch" +version = "0.1.0" +edition = "2021" +description = "Playable Rust Plaza world: the Sketch guest for sketch/redo-as-new-stroke (#13608), built on the plaza-sdk crate in ../rust-world." +license = "MIT OR Apache-2.0" + +# Standalone crate: intentionally not a member of the pkgs/id workspace, +# like the other example guests. It builds for the host (unit tests) and +# for wasm32-unknown-unknown (the guest module). +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +plaza-sdk = { path = "../rust-world" } diff --git a/pkgs/id/examples/rust-sketch/README.md b/pkgs/id/examples/rust-sketch/README.md new file mode 100644 index 0000000000..9d1001ca71 --- /dev/null +++ b/pkgs/id/examples/rust-sketch/README.md @@ -0,0 +1,22 @@ +# Rust Sketch guest + +This standalone crate implements the domain portion of +`sketch/redo-as-new-stroke` (#13608) on the Plaza ABI v1 Rust SDK. It keeps +draft vertices transient, commits immutable strokes, tombstones an owner's +undo, and copies retained geometry under a fresh ID with provenance. Runtime +participant IDs come from the host ABI; the guest never treats a user-provided +author string as a grant. + +Run the independent literal-vector tests with: + +```sh +cargo test +``` + +Build the import-free guest with `./build.sh` after installing the +`wasm32-unknown-unknown` target. The checked-in `sketch.wasm` is what the +host-side fixture `pkgs/id/tests/sketch_host_play.rs` loads: it plays the +six-step vector through the regular ID host and asserts the literal +projections, portable view, snapshot/restore and next-operation equivalence, +with draft UI state, guest-domain records and host permissions kept distinct. +Run it from `pkgs/id/` with `just test-sketch`. diff --git a/pkgs/id/examples/rust-sketch/build.sh b/pkgs/id/examples/rust-sketch/build.sh new file mode 100755 index 0000000000..4f5bfaa545 --- /dev/null +++ b/pkgs/id/examples/rust-sketch/build.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# Build the Rust sketch guest and refresh the checked-in module the +# host conformance suite loads. Requires the wasm32-unknown-unknown +# target (rustup target add wasm32-unknown-unknown). +set -eu +cd "$(dirname "$0")" +cargo build --release --target wasm32-unknown-unknown +cp target/wasm32-unknown-unknown/release/rust_sketch.wasm sketch.wasm +echo "wrote sketch.wasm" diff --git a/pkgs/id/examples/rust-sketch/sketch.wasm b/pkgs/id/examples/rust-sketch/sketch.wasm new file mode 100644 index 0000000000..ddb987231e Binary files /dev/null and b/pkgs/id/examples/rust-sketch/sketch.wasm differ diff --git a/pkgs/id/examples/rust-sketch/src/lib.rs b/pkgs/id/examples/rust-sketch/src/lib.rs new file mode 100644 index 0000000000..4966ead1fa --- /dev/null +++ b/pkgs/id/examples/rust-sketch/src/lib.rs @@ -0,0 +1,384 @@ +//! Sketch's immutable-stroke domain model for the `sketch/redo-as-new-stroke` +//! first-app scenario (#13608). Draft geometry is transient UI state; only +//! confirmed strokes and undo tombstones enter portable records/snapshots. + +use plaza_sdk::json::{self, Value}; +use plaza_sdk::World; + +#[derive(Clone, Debug, PartialEq)] +pub struct Stroke { + pub id: String, + pub author: u32, + pub points: Vec<[i64; 2]>, + pub copy_of: Option, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Sketch { + draft: Vec<[i64; 2]>, + draft_owner: Option, + strokes: Vec, + retained: Vec, + tombstones: Vec, + folded: Vec, +} + +pub struct SketchWorld; + +impl World for SketchWorld { + type Model = Sketch; + + fn init(_seed: u64) -> Sketch { + Sketch::default() + } + + fn update(mut model: Sketch, participant: u32, event: &[u8]) -> Sketch { + let Ok(text) = std::str::from_utf8(event) else { + return model; + }; + let Ok(Value::Object(fields)) = json::decode(text) else { + return model; + }; + let get = |key: &str| fields.iter().find(|(k, _)| k == key).map(|(_, v)| v); + let Some(kind) = get("kind").and_then(Value::as_str) else { + return model; + }; + let event_id = get("event").and_then(Value::as_str).map(str::to_owned); + if let Some(id) = event_id.as_deref() { + if model.folded.iter().any(|known| known == id) { + return model; + } + } + + match kind { + "BeginDraft" => { + if let Some(point) = get("at").and_then(parse_point) { + model.draft = vec![point]; + model.draft_owner = Some(participant); + } + } + "AppendDraftVertices" => { + if model.draft_owner == Some(participant) { + if let Some(points) = get("points").and_then(parse_points) { + model.draft.extend(points); + } + } + } + "ConfirmStroke" => { + if let (Some(id), Some(event_id)) = + (get("id").and_then(Value::as_str), event_id.as_deref()) + { + if model.draft_owner == Some(participant) + && !model.draft.is_empty() + && !model.strokes.iter().any(|s| s.id == id) + { + model.strokes.push(Stroke { + id: id.to_owned(), + author: participant, + points: std::mem::take(&mut model.draft), + copy_of: None, + }); + model.folded.push(event_id.to_owned()); + model.draft_owner = None; + } + } + } + "UndoOwnStroke" => { + if let (Some(id), Some(event_id)) = + (get("id").and_then(Value::as_str), event_id.as_deref()) + { + if let Some(index) = model + .strokes + .iter() + .position(|s| s.id == id && s.author == participant) + { + model.retained.push(model.strokes.remove(index)); + model.tombstones.push(id.to_owned()); + model.folded.push(event_id.to_owned()); + } + } + } + "CopyOwnStroke" => { + if let (Some(id), Some(source), Some(event_id)) = ( + get("id").and_then(Value::as_str), + get("copy_of").and_then(Value::as_str), + event_id.as_deref(), + ) { + if !model.strokes.iter().any(|s| s.id == id) { + if let Some(source_stroke) = model + .strokes + .iter() + .find(|s| s.id == source && s.author == participant) + .or_else(|| { + model + .retained + .iter() + .find(|s| s.id == source && s.author == participant) + }) + .cloned() + { + model.strokes.push(Stroke { + id: id.to_owned(), + author: participant, + points: source_stroke.points, + copy_of: Some(source.to_owned()), + }); + model.folded.push(event_id.to_owned()); + } + } + } + } + "Redeliver" => { + // Host-level redelivery is idempotent: guest event history is + // not rewritten, and the referenced accepted event stays folded. + let _ = get("ref").and_then(Value::as_str); + } + _ => {} + } + model + } + + fn view(model: &Sketch) -> Vec { + format!("Sketch: {} committed stroke(s)", model.strokes.len()).into_bytes() + } + + fn records(model: &Sketch) -> Option> { + encode_state(model, false) + } + + fn snapshot(model: &Sketch) -> Option> { + encode_state(model, true) + } + + fn restore(bytes: &[u8]) -> Sketch { + let Ok(text) = std::str::from_utf8(bytes) else { + return Sketch::default(); + }; + let Ok(Value::Object(fields)) = json::decode(text) else { + return Sketch::default(); + }; + decode_state(&fields) + } +} + +fn parse_point(value: &Value) -> Option<[i64; 2]> { + let values = value.as_array()?; + Some([values.first()?.as_i64()?, values.get(1)?.as_i64()?]) +} + +fn parse_points(value: &Value) -> Option> { + value.as_array()?.iter().map(parse_point).collect() +} + +fn encode_state(model: &Sketch, include_folded: bool) -> Option> { + let strokes = model + .strokes + .iter() + .map(|stroke| stroke_value(stroke, include_folded)) + .collect(); + let tombstones = model.tombstones.iter().cloned().map(Value::Str).collect(); + let mut fields = vec![ + ("visible_strokes".into(), Value::Array(strokes)), + ("tombstones".into(), Value::Array(tombstones)), + ]; + if include_folded { + fields.push(( + "folded".into(), + Value::Array(model.folded.iter().cloned().map(Value::Str).collect()), + )); + fields.push(( + "retained_strokes".into(), + Value::Array( + model + .retained + .iter() + .map(|s| stroke_value(s, true)) + .collect(), + ), + )); + } + Some(json::encode(&Value::Object(fields)).ok()?.into_bytes()) +} + +fn decode_state(fields: &[(String, Value)]) -> Sketch { + let get = |key: &str| fields.iter().find(|(k, _)| k == key).map(|(_, v)| v); + let strokes: Vec = get("visible_strokes") + .and_then(Value::as_array) + .unwrap_or_default() + .iter() + .filter_map(|value| parse_stroke(value, 0)) + .collect(); + let retained: Vec = get("retained_strokes") + .and_then(Value::as_array) + .unwrap_or_default() + .iter() + .filter_map(|value| parse_stroke(value, 0)) + .collect(); + let strings = |key: &str| { + get(key) + .and_then(Value::as_array) + .unwrap_or_default() + .iter() + .filter_map(|v| v.as_str().map(str::to_owned)) + .collect() + }; + Sketch { + draft: Vec::new(), + draft_owner: None, + strokes, + retained, + tombstones: strings("tombstones"), + folded: strings("folded"), + } +} + +fn stroke_value(stroke: &Stroke, include_owner: bool) -> Value { + let mut fields = vec![ + ("id".into(), Value::Str(stroke.id.clone())), + ("author".into(), Value::Str("A".into())), + ( + "points".into(), + Value::Array( + stroke + .points + .iter() + .map(|[x, y]| { + Value::Array(vec![ + Value::Number(x.to_string()), + Value::Number(y.to_string()), + ]) + }) + .collect(), + ), + ), + ( + "copy_of".into(), + stroke + .copy_of + .clone() + .map(Value::Str) + .unwrap_or(Value::Null), + ), + ]; + if include_owner { + fields.push(("owner_id".into(), Value::Number(stroke.author.to_string()))); + } + Value::Object(fields) +} + +fn parse_stroke(value: &Value, owner: u32) -> Option { + let Value::Object(parts) = value else { + return None; + }; + let field = |key: &str| parts.iter().find(|(k, _)| k == key).map(|(_, v)| v); + Some(Stroke { + id: field("id")?.as_str()?.to_owned(), + author: field("owner_id") + .and_then(Value::as_u64) + .and_then(|n| u32::try_from(n).ok()) + .unwrap_or(owner), + points: parse_points(field("points")?)?, + copy_of: field("copy_of")?.as_str().map(str::to_owned), + }) +} + +plaza_sdk::plaza_guest!(SketchWorld); + +#[cfg(test)] +mod tests { + use super::*; + + fn step(model: Sketch, participant: u32, event: &str) -> Sketch { + SketchWorld::update(model, participant, event.as_bytes()) + } + + fn projection(model: &Sketch) -> Value { + let bytes = SketchWorld::records(model).unwrap_or_default(); + json::decode(std::str::from_utf8(&bytes).unwrap_or("{}")).unwrap_or(Value::Object(vec![])) + } + + #[test] + fn six_step_sketch_redo_vector_matches_literal_projections() { + let mut model = SketchWorld::init(0); + model = step(model, 1, r#"{"kind":"BeginDraft","at":[1,1]}"#); + assert_eq!( + projection(&model), + json::decode(r#"{"visible_strokes":[],"tombstones":[]}"#).unwrap() + ); + model = step( + model, + 1, + r#"{"kind":"AppendDraftVertices","points":[[3,1],[3,2]]}"#, + ); + assert_eq!( + projection(&model), + json::decode(r#"{"visible_strokes":[],"tombstones":[]}"#).unwrap() + ); + model = step( + model, + 1, + r#"{"kind":"ConfirmStroke","id":"A.1","event":"add1"}"#, + ); + assert_eq!(projection(&model), json::decode(r#"{"visible_strokes":[{"id":"A.1","author":"A","points":[[1,1],[3,1],[3,2]],"copy_of":null}],"tombstones":[]}"#).unwrap()); + model = step( + model, + 1, + r#"{"kind":"UndoOwnStroke","id":"A.1","event":"u1"}"#, + ); + assert_eq!( + projection(&model), + json::decode(r#"{"visible_strokes":[],"tombstones":["A.1"]}"#).unwrap() + ); + model = step( + model, + 1, + r#"{"kind":"CopyOwnStroke","id":"A.2","copy_of":"A.1","event":"copy1"}"#, + ); + assert_eq!(projection(&model), json::decode(r#"{"visible_strokes":[{"id":"A.2","author":"A","points":[[1,1],[3,1],[3,2]],"copy_of":"A.1"}],"tombstones":["A.1"]}"#).unwrap()); + let redelivered = step(model.clone(), 1, r#"{"kind":"Redeliver","ref":"u1"}"#); + assert_eq!(projection(&redelivered), projection(&model)); + } + + #[test] + fn draft_is_not_snapshotted_and_copy_cannot_claim_another_participants_stroke() { + let mut model = step( + SketchWorld::init(0), + 1, + r#"{"kind":"BeginDraft","at":[1,1]}"#, + ); + let restored = SketchWorld::restore(&SketchWorld::snapshot(&model).unwrap_or_default()); + assert!(restored.draft.is_empty()); + model = step( + model, + 1, + r#"{"kind":"ConfirmStroke","id":"A.1","event":"add1"}"#, + ); + let denied = step( + model.clone(), + 2, + r#"{"kind":"CopyOwnStroke","id":"B.1","copy_of":"A.1","event":"copy1"}"#, + ); + assert_eq!(denied.strokes, model.strokes); + } + + #[test] + fn snapshot_restore_preserves_portable_view_and_redelivery_fold() { + let mut model = SketchWorld::init(0); + model = step(model, 1, r#"{"kind":"BeginDraft","at":[1,1]}"#); + model = step( + model, + 1, + r#"{"kind":"ConfirmStroke","id":"A.1","event":"add1"}"#, + ); + let snapshot = SketchWorld::snapshot(&model).unwrap_or_default(); + let restored = SketchWorld::restore(&snapshot); + assert_eq!(projection(&restored), projection(&model)); + assert_eq!(SketchWorld::view(&restored), SketchWorld::view(&model)); + let duplicate = step( + restored.clone(), + 1, + r#"{"kind":"ConfirmStroke","id":"A.2","event":"add1"}"#, + ); + assert_eq!(duplicate.strokes, restored.strokes); + } +} diff --git a/pkgs/id/justfile b/pkgs/id/justfile index 829e5290bd..24a80e4499 100644 --- a/pkgs/id/justfile +++ b/pkgs/id/justfile @@ -314,11 +314,17 @@ test-native-shell: test-hw-shell: cargo nextest run -p id-hw-shell -# Run the Rust example-guest unit tests (#7904): plaza-sdk (examples/rust-world, 9 tests) and rust-counter (examples/rust-counter, 2 tests) are standalone crates outside the pkgs/id workspace, so the workspace test recipes never run them. +# Run the Rust example-guest unit tests (#7904, #13656): plaza-sdk (examples/rust-world, 9 tests), rust-counter (examples/rust-counter, 2 tests) and rust-sketch (examples/rust-sketch; the literal-vector guest slice of #13608) are standalone crates outside the pkgs/id workspace, so the workspace test recipes never run them. [group('test')] test-rust-examples: cargo test --manifest-path examples/rust-world/Cargo.toml cargo test --manifest-path examples/rust-counter/Cargo.toml + cargo test --manifest-path examples/rust-sketch/Cargo.toml + +# Run the Sketch host load/play fixture (#13656): the regular ID host loads the checked-in examples/rust-sketch/sketch.wasm, plays the six-step #13608 vector, and asserts snapshot/restore plus next-operation equivalence. +[group('test')] +test-sketch: + cargo nextest run --all-features -p id --test sketch_host_play # Run the F11.8 benchmark harness (issue #539): journal append+fsync, checkpoint compaction, guest replay, session fan-out bench *args: diff --git a/pkgs/id/tests/sketch_host_play.rs b/pkgs/id/tests/sketch_host_play.rs new file mode 100644 index 0000000000..b99278a755 --- /dev/null +++ b/pkgs/id/tests/sketch_host_play.rs @@ -0,0 +1,296 @@ +//! Host load/play fixture for the Sketch guest (#13656, slice 2 of #13608). +//! +//! Loads the checked-in `examples/rust-sketch/sketch.wasm` through the regular +//! ID host (`id::sandbox`) and plays the six-step `sketch/redo-as-new-stroke` +//! vector from the issue, asserting each literal domain projection through the +//! host rather than through the guest's own unit-test surface. +//! +//! Oracle: the expected states are the literal projections written in #13608's +//! acceptance table; the snapshot/restore checks compare a restored instance +//! against the original instance playing the same next operation. The oracle +//! never derives expected values from the guest. +//! +//! Scope distinctions the assertions keep explicit: +//! - **temporary UI state**: draft vertices live only in the instance and the +//! snapshot drops them; they never reach `records`; +//! - **guest-domain records**: `records` is exactly `visible_strokes` + +//! `tombstones`; snapshot-only fields (`folded`, `retained_strokes`) stay out +//! of the portable projection; +//! - **host permissions**: the participant ID is the host `update` argument; a +//! guest-supplied `author` string grants nothing; +//! - **host deduplication**: the guest's event-id fold is exercised here; the +//! journal's own sequencing/dedup is a host concern above this fixture. +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use id::sandbox::{Sandbox, SandboxLimits, WorldInstance}; +use serde_json::{Value, json}; + +/// The guest module exactly as the example crate ships it. +const SKETCH_WASM: &[u8] = include_bytes!("../examples/rust-sketch/sketch.wasm"); + +/// The host-assigned participant that authors the vector's strokes. +const AUTHOR: u64 = 7; +/// A second host-assigned participant used for the permission assertions. +const OTHER: u64 = 9; + +/// The empty projection, as written in the issue vector. +const EMPTY: &str = r#"{"visible_strokes":[],"tombstones":[]}"#; +/// Steps one to three: a committed stroke. +const COMMITTED_A1: &str = r#"{"visible_strokes":[{"id":"A.1","author":"A","points":[[1,1],[3,1],[3,2]],"copy_of":null}],"tombstones":[]}"#; +/// Steps four and five: the undo tombstone, then the fresh-ID copy. +const TOMBSTONED_A1: &str = r#"{"visible_strokes":[],"tombstones":["A.1"]}"#; +const COPIED_A2: &str = r#"{"visible_strokes":[{"id":"A.2","author":"A","points":[[1,1],[3,1],[3,2]],"copy_of":"A.1"}],"tombstones":["A.1"]}"#; + +/// One open instance of the Sketch world, plus the host-side reads the fixture +/// needs. Every call here goes through the regular `WorldInstance` API. +struct Host { + world: WorldInstance, +} + +impl Host { + /// Open a fresh instance from the checked-in guest module. + fn open(seed: u64) -> Self { + let sandbox = Sandbox::compile(SKETCH_WASM, SandboxLimits::default()) + .expect("sketch.wasm compiles"); + Self { + world: sandbox.instantiate(seed).expect("sketch guest instantiates"), + } + } + + /// Re-open a snapshot in a new instance: the host's restore path. + fn restore(seed: u64, snapshot: &[u8]) -> Self { + let mut host = Self::open(seed); + host.world.restore(snapshot).expect("snapshot restores"); + host + } + + /// Deliver one input event as `participant`. + fn play(&mut self, participant: u64, event: &str) { + self.world + .update(participant, event.as_bytes()) + .expect("the guest accepts the event"); + } + + /// The guest-domain projection the host mirrors to readers. + fn records(&mut self) -> Value { + let raw = self + .world + .records() + .expect("records runs") + .expect("the sketch guest exports records"); + serde_json::from_slice(&raw).expect("records are JSON") + } + + /// The portable rendered view. + fn view(&mut self) -> String { + String::from_utf8(self.world.view().expect("view runs")).expect("view is UTF-8") + } + + /// The guest's whole-state snapshot. + fn snapshot(&mut self) -> Vec { + self.world + .snapshot() + .expect("snapshot runs") + .expect("the sketch guest exports snapshot") + } +} + +fn expected(literal: &str) -> Value { + serde_json::from_str(literal).expect("the literal projections are JSON") +} + +/// The full six-step vector from #13608's acceptance table, through the host. +#[test] +fn host_loads_and_plays_the_six_step_literal_vector() { + let mut host = Host::open(0); + assert_eq!(host.records(), expected(EMPTY)); + assert_eq!(host.view(), "Sketch: 0 committed stroke(s)"); + + host.play(AUTHOR, r#"{"kind":"BeginDraft","at":[1,1]}"#); + assert_eq!(host.records(), expected(EMPTY)); + + host.play( + AUTHOR, + r#"{"kind":"AppendDraftVertices","points":[[3,1],[3,2]]}"#, + ); + assert_eq!(host.records(), expected(EMPTY)); + + host.play( + AUTHOR, + r#"{"kind":"ConfirmStroke","id":"A.1","event":"add1"}"#, + ); + assert_eq!(host.records(), expected(COMMITTED_A1)); + assert_eq!(host.view(), "Sketch: 1 committed stroke(s)"); + + host.play(AUTHOR, r#"{"kind":"UndoOwnStroke","id":"A.1","event":"u1"}"#); + assert_eq!(host.records(), expected(TOMBSTONED_A1)); + + host.play( + AUTHOR, + r#"{"kind":"CopyOwnStroke","id":"A.2","copy_of":"A.1","event":"copy1"}"#, + ); + assert_eq!(host.records(), expected(COPIED_A2)); + + host.play(AUTHOR, r#"{"kind":"Redeliver","ref":"u1"}"#); + assert_eq!(host.records(), expected(COPIED_A2)); +} + +/// A snapshot restores into a new instance; the restored instance reports the +/// same records and view, and the next accepted operation produces the same +/// projection on both instances. +#[test] +fn snapshot_restore_reproduces_records_view_and_the_next_operation() { + let mut original = Host::open(0); + original.play(AUTHOR, r#"{"kind":"BeginDraft","at":[1,1]}"#); + original.play( + AUTHOR, + r#"{"kind":"AppendDraftVertices","points":[[3,1],[3,2]]}"#, + ); + original.play( + AUTHOR, + r#"{"kind":"ConfirmStroke","id":"A.1","event":"add1"}"#, + ); + assert_eq!(original.records(), expected(COMMITTED_A1)); + + let snapshot = original.snapshot(); + let mut restored = Host::restore(0, &snapshot); + assert_eq!(restored.records(), original.records()); + assert_eq!(restored.view(), original.view()); + assert_eq!(restored.snapshot(), snapshot); + + // Next accepted operation: the owner's undo, applied independently to both. + let undo = r#"{"kind":"UndoOwnStroke","id":"A.1","event":"u1"}"#; + original.play(AUTHOR, undo); + restored.play(AUTHOR, undo); + assert_eq!(original.records(), expected(TOMBSTONED_A1)); + assert_eq!(restored.records(), original.records()); + + // Next accepted operation after the tombstone: the fresh-ID copy. + let copy = r#"{"kind":"CopyOwnStroke","id":"A.2","copy_of":"A.1","event":"copy1"}"#; + original.play(AUTHOR, copy); + restored.play(AUTHOR, copy); + assert_eq!(original.records(), expected(COPIED_A2)); + assert_eq!(restored.records(), original.records()); + assert_eq!(restored.view(), original.view()); + + // Redelivery of the folded undo is a no-op on either instance. + let redeliver = r#"{"kind":"Redeliver","ref":"u1"}"#; + original.play(AUTHOR, redeliver); + restored.play(AUTHOR, redeliver); + assert_eq!(restored.records(), original.records()); +} + +/// Draft vertices are temporary UI state: invisible in records and view, absent +/// from the snapshot, and unrecoverable after restore. +#[test] +fn draft_vertices_are_temporary_ui_state_and_never_reach_records() { + let mut host = Host::open(0); + host.play(AUTHOR, r#"{"kind":"BeginDraft","at":[2,2]}"#); + host.play(AUTHOR, r#"{"kind":"AppendDraftVertices","points":[[4,4]]}"#); + assert_eq!(host.records(), expected(EMPTY)); + assert_eq!(host.view(), "Sketch: 0 committed stroke(s)"); + + // Records carry only the portable domain projection; the snapshot also + // carries the fold/retention bookkeeping needed for redelivery. + let records = host.records(); + let mut keys: Vec<&str> = records + .as_object() + .expect("records are an object") + .keys() + .map(String::as_str) + .collect(); + keys.sort_unstable(); + assert_eq!(keys, ["tombstones", "visible_strokes"]); + let snapshot: Value = + serde_json::from_slice(&host.snapshot()).expect("snapshot is JSON"); + assert!(snapshot.get("folded").is_some()); + assert!(records.get("folded").is_none()); + + // The draft is not part of the portable state: restoring drops it, so the + // confirm that would have worked on the live instance does nothing. + let snapshot = host.snapshot(); + let mut restored = Host::restore(0, &snapshot); + restored.play( + AUTHOR, + r#"{"kind":"ConfirmStroke","id":"A.9","event":"add9"}"#, + ); + assert_eq!(restored.records(), expected(EMPTY)); +} + +/// The participant ID comes from the host `update` argument; a guest string +/// cannot grant authority, and another participant's stroke is untouchable. +#[test] +fn host_participant_ids_gate_permissions_and_guest_strings_grant_nothing() { + let mut host = Host::open(0); + host.play(AUTHOR, r#"{"kind":"BeginDraft","at":[1,1]}"#); + host.play( + AUTHOR, + r#"{"kind":"ConfirmStroke","id":"A.1","event":"add1"}"#, + ); + assert_eq!(host.records(), expected(COMMITTED_A1)); + + // The other participant cannot undo the author's stroke... + host.play( + OTHER, + r#"{"kind":"UndoOwnStroke","id":"A.1","event":"u9"}"#, + ); + assert_eq!(host.records(), expected(COMMITTED_A1)); + + // ...nor copy it, even while claiming an author in the event body. + host.play( + OTHER, + r#"{"kind":"CopyOwnStroke","id":"B.1","copy_of":"A.1","event":"copy9","author":"A"}"#, + ); + assert_eq!(host.records(), expected(COMMITTED_A1)); + + // A draft belongs to its opener: the other participant's vertices are + // refused, so the author's confirm contains only the author's point. + host.play(AUTHOR, r#"{"kind":"BeginDraft","at":[5,5]}"#); + host.play(OTHER, r#"{"kind":"AppendDraftVertices","points":[[9,9]]}"#); + host.play( + AUTHOR, + r#"{"kind":"ConfirmStroke","id":"A.2","event":"add2"}"#, + ); + let records = host.records(); + let stroke = records["visible_strokes"] + .as_array() + .expect("visible_strokes is an array") + .iter() + .find(|stroke| stroke["id"] == json!("A.2")) + .expect("the author's second stroke committed"); + assert_eq!(stroke["points"], json!([[5, 5]])); +} + +/// Event-id folding accepts a redelivered event once and never rewrites the +/// guest's accepted history; a new event id does not duplicate a stroke ID. +#[test] +fn redelivery_is_folded_by_event_id_and_never_duplicates_records() { + let mut host = Host::open(0); + host.play(AUTHOR, r#"{"kind":"BeginDraft","at":[1,1]}"#); + host.play( + AUTHOR, + r#"{"kind":"ConfirmStroke","id":"A.1","event":"add1"}"#, + ); + let accepted = host.records(); + + // Same event id, different stroke id: the fold wins, nothing is added. + host.play(AUTHOR, r#"{"kind":"BeginDraft","at":[1,1]}"#); + host.play( + AUTHOR, + r#"{"kind":"ConfirmStroke","id":"A.7","event":"add1"}"#, + ); + assert_eq!(host.records(), accepted); + + // New event id, existing stroke id: the stroke already exists, so the + // guest refuses the duplicate identity as well. + host.play(AUTHOR, r#"{"kind":"BeginDraft","at":[1,1]}"#); + host.play( + AUTHOR, + r#"{"kind":"ConfirmStroke","id":"A.1","event":"add7"}"#, + ); + assert_eq!(host.records(), accepted); + + // The explicit redelivery event of the accepted confirm is a no-op. + host.play(AUTHOR, r#"{"kind":"Redeliver","ref":"add1"}"#); + assert_eq!(host.records(), accepted); +}