diff --git a/Cargo.lock b/Cargo.lock index 35d34b470..db22f6f04 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -274,15 +274,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arboard" version = "3.7.0" @@ -1039,6 +1030,15 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "constant_time_eq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] + [[package]] name = "cookie-factory" version = "0.3.3" @@ -1327,7 +1327,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip 9.1.1", + "zip", ] [[package]] @@ -1879,7 +1879,7 @@ dependencies = [ "verifysign", "winreg", "winsafe", - "zip 9.1.1", + "zip", ] [[package]] @@ -1962,7 +1962,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259e dependencies = [ "flate2", "thiserror 2.0.21", - "zip 9.1.1", + "zip", ] [[package]] @@ -2099,17 +2099,6 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" -[[package]] -name = "derive_arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - [[package]] name = "deunicode" version = "1.6.2" @@ -2716,6 +2705,7 @@ dependencies = [ "log", "proptest", "rustls", + "rustls-native-certs", "rustls-pki-types", "serde_json", "tungstenite", @@ -2780,7 +2770,7 @@ dependencies = [ "thiserror 2.0.21", "wat", "web-time", - "zip 2.6.1", + "zip", ] [[package]] @@ -2809,7 +2799,7 @@ dependencies = [ "serde_json", "sha1", "sha2", - "zip 2.6.1", + "zip", ] [[package]] @@ -2927,7 +2917,7 @@ dependencies = [ "toml", "tungstenite", "wat", - "zip 2.6.1", + "zip", ] [[package]] @@ -8704,6 +8694,20 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" @@ -8744,33 +8748,21 @@ dependencies = [ [[package]] name = "zip" -version = "2.6.1" +version = "9.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" -dependencies = [ - "arbitrary", - "crc32fast", - "crossbeam-utils", - "flate2", - "indexmap", - "memchr", - "zopfli", -] - -[[package]] -name = "zip" -version = "9.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "518b847fd864440c379748ad684c449f293af68978a485a4ff16f7c901c1f7c4" +checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" dependencies = [ + "constant_time_eq", "crc32fast", "flate2", "getrandom 0.4.3", "indexmap", + "libc", "memchr", "nix", "typed-path", "windows-sys 0.61.2", + "zeroize", ] [[package]] @@ -8785,18 +8777,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zopfli" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] - [[package]] name = "zune-core" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index 9fd9a8e06..f05ad8b41 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -121,7 +121,7 @@ icu_segmenter = { version = "2.3", default-features = false, features = ["compil # dependencies, BSD-3-Clause, no_std so the web build keeps it too). deunicode = "1.6" linesweeper = "0.5" -zip = { version = "2", default-features = false, features = ["deflate"] } +zip = { version = "=9.8.2", default-features = false, features = ["deflate-flate2"] } # `.fig` import: raw deflate chunks (already built for zip) and zstd chunks (pure Rust, MIT, wasm-safe). flate2 = { version = "1", default-features = false, features = ["rust_backend"] } ruzstd = { version = "0.9.1", default-features = false, features = ["std"] } diff --git a/ROADMAP.md b/ROADMAP.md index d923214de..4a1ebb201 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-28 | minor | M8: the MCP prompt `implement_design` takes an agent through building the selected design in a codebase: `design_context` for what the designer set, connected components reused through `component_mappings` and `sync_mappings`, tokens before literal values, real files from `export_assets`, the annotations and `responsive` for what the design states beyond its size, and `compare_design` to check the result. With nothing selected it asks which frame to build, and it reports what it approximated, assumed or couldn't check. A test now checks that every tool and result field the server instructions and prompts name exists, as one already did for command ids. Numbers unchanged | | 2026-11-28 | minor | M7, #1687: variables export and import as DTCG design tokens (format 2025.10), the files token build pipelines read. `variable.export {format: "dtcg", mode?}` (also Variables ▸ Export… ▸ Design tokens (DTCG)…, saved as `.tokens.json`) writes a group per collection and a token per variable, nested by the `/` parts of its name: colours as `colorSpace`/`components`/`alpha` objects (with `hex` in sRGB, `display-p3` in a Display P3 file), numbers as px dimensions or plain numbers where layers use them unitless, aliases as `{group.token}` (one leaving the exported collections as the value it shows), colour calculations as the colour they show; strings and booleans, which DTCG has no type for, every mode's value and the variable's scopes go under `$extensions` (`ai.storyteller.figcraft`), and `mode` picks which mode is `$value`. `variable.import` reads a file holding a `$value` as tokens: each top-level group a collection (top-level tokens one named Tokens), types handed down from groups, `color` (object or `#hex`), `dimension` (px, rem at 16 px, or the older `16px` string), `number`, `fontWeight` (number or name), `duration` (ms), `fontFamily`, strings, booleans and aliases (an untyped alias takes its target's type); without our modes a collection fills the default mode of this file's collection of its name. Composite tokens (typography, shadows and the like) are skipped and counted in the warnings, never dropped silently. Tests: `dtcg_tests` (format, three) and `variables_io_tests::design_tokens_export_and_import_round_trip`, `plain_design_tokens_update_the_default_mode` (engine). Numbers unchanged | | 2026-11-27 | minor | M8: visual verification for agents. `inspect.compare` and the MCP tool `compare_design` compare a capture of a built page, made by the agent's own browser tools, with a frame, on this computer: the layers that differ, deepest and largest first, each a position (with its offset), colour (expected and actual) or content difference, with text held to twice the tolerance. A retina capture is the same design. Numbers unchanged. Tests: `visual_compare_tests`, MCP `compare_design`. | | 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged | diff --git a/apps/figcraft-server/src/hardening_tests.rs b/apps/figcraft-server/src/hardening_tests.rs index 186b8d9c0..119a8dc4b 100644 --- a/apps/figcraft-server/src/hardening_tests.rs +++ b/apps/figcraft-server/src/hardening_tests.rs @@ -47,7 +47,7 @@ pub(crate) fn archive(bomb: usize, padding: usize) -> Vec { let mut out = zip::ZipWriter::new(Cursor::new(Vec::new())); for i in 0..src.len() { let f = src.by_index_raw(i).unwrap(); - if bomb > 0 && f.name() == "library/document.json" { + if bomb > 0 && f.name().expect("ZIP member name") == "library/document.json" { continue; } out.raw_copy_file(f).unwrap(); diff --git a/apps/figcraft-server/src/store/files.rs b/apps/figcraft-server/src/store/files.rs index fcc0fd109..8db73d063 100644 --- a/apps/figcraft-server/src/store/files.rs +++ b/apps/figcraft-server/src/store/files.rs @@ -90,7 +90,7 @@ impl Store { if let Some(why) = self.low_disk() { return Err(why); } - let replica = Replica::from_snapshot(snapshot).map_err(|e| format!("the file couldn't be read: {e}"))?; + let replica = Replica::from_snapshot(snapshot.to_vec()).map_err(|e| format!("the file couldn't be read: {e}"))?; if replica.document().node_count() > self.cfg.core.max_nodes { return Err(format!("the file has more than {} layers", self.cfg.core.max_nodes)); } diff --git a/apps/figcraft-web/src/host.rs b/apps/figcraft-web/src/host.rs index 57b67ca85..1e5687124 100644 --- a/apps/figcraft-web/src/host.rs +++ b/apps/figcraft-web/src/host.rs @@ -24,6 +24,17 @@ //! - Everything else is a copy or export that never becomes the document: `false` — rendered //! images, SVG and PDF, `.fig` copies, and the variables exports (a `.variables.json` //! sidecar's `.json` extension doesn't make it a document). +//! - Confirmed saves, opt-in: with `?save=managed` in the URL, or `data-save="managed"` on the +//! canvas ([`crate::query::confirms_saves`]), each Save and Save As of the document carries an +//! `id` (`save-1`, `save-2`, …) and the document keeps its unsaved changes until the host answers +//! `figcraft:saved` with that `id` ([`crate::host_saves`]). Then it is saved as of the file the +//! host stored, so edits made meanwhile stay unsaved, and a Save As becomes the document's file +//! only then. Answers for any other `id` are ignored; a newer save replaces the one waiting; a +//! file the host opens forgets it (the user is told). Without an answer within 30 seconds the save counts as not +//! stored: the user is told and the host gets `figcraft:failed` with the `id`. Copies and exports +//! carry no `id` and `saveAs: false`. A host that doesn't opt in sees no change: every file +//! counts as saved once it is posted. `craft-web-host` has no message yet for a host to refuse a +//! save, so a refusal shows as the timeout. //! - `figcraft:dirty` whenever unsaved changes appear or go away, `figcraft:failed` when the app //! couldn't start. //! @@ -31,10 +42,14 @@ //! edit; `?author=` names the user for comments and board notes. use std::cell::RefCell; +use std::collections::VecDeque; use std::rc::Rc; use craft_web_host::web::{FileData, Host, Message}; -use figcraft_ui_egui::FigApp; +use figcraft_engine::cmd::file::FileSnapshot; +use figcraft_ui_egui::{Delivery, FigApp}; + +use crate::host_saves::HostSaves; /// The app id in the host messages (`figcraft:ready`). const APP: &str = "figcraft"; @@ -42,38 +57,87 @@ const APP: &str = "figcraft"; /// The longest user name taken from `?author=`. const MAX_AUTHOR_CHARS: usize = 200; -/// Files the host sent, on their way to the app's own open queue ([`figcraft_ui_egui::pending_open`]): -/// `(name, bytes)`. -pub type OpenQueue = Rc)>>>; +/// What the host sent, in the order it came, for the shell's next frame ([`Bridge::frame`]). +enum FromHost { + /// A file to open: `(name, bytes)`. + Open(String, Vec), + /// The save with this `id` is stored. + Saved(String), +} #[derive(Clone)] pub struct Bridge { host: Rc, - /// The file the host opened, and after a `saveAs` hand-over the document's file: the name a - /// Save under (`saveAs: false`) is decided against. - host_file: Rc>>, + /// The host confirms saves (`?save=managed`): document saves wait for its `saved`. + confirms_saves: bool, + /// The document's file and the save waiting for the host ([`crate::host_saves`]). + saves: Rc>>, + /// Messages heard and not yet handled. The listener only queues them: a page host can answer + /// while a post is still running, so nothing else is borrowed there. + inbox: Rc>>, } impl Bridge { /// The bridge for this page, or `None` when FigCraft isn't hosted: no `?host=parent` and no /// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app - /// with downloads), or a parent on another origin. - pub fn connect(canvas: &web_sys::HtmlCanvasElement) -> Option { - Some(Self { host: Rc::new(Host::connect(APP, canvas)?), host_file: Rc::default() }) + /// with downloads), or a parent on another origin. `confirms_saves`: the host opted in to + /// confirmed saves. + pub fn connect(canvas: &web_sys::HtmlCanvasElement, confirms_saves: bool) -> Option { + Some(Self { host: Rc::new(Host::connect(APP, canvas)?), confirms_saves, saves: Rc::default(), inbox: Rc::default() }) } - /// Hear the files the host sends, and queue each one on `opens` for the app's own open path - /// (the shell drains it into [`figcraft_ui_egui::pending_open`] every frame, so a host file - /// opens like a dropped one). - pub fn listen(&self, opens: OpenQueue, ctx: egui::Context) { - let host_file = self.host_file.clone(); + /// Hear the host's messages. They are handled in the shell's next frame ([`Bridge::frame`]), + /// in the order they came. + pub fn listen(&self, ctx: egui::Context) { + let inbox = self.inbox.clone(); self.host.listen(move |message| { - if let Message::Open { name, data } = message { - deliver_open(&opens, &ctx, &host_file, &name, &data); + let heard = match message { + Message::Open { name, data } => open_bytes(&name, &data), + Message::Saved { id } => Some(FromHost::Saved(id)), + _ => None, + }; + if let Some(heard) = heard { + inbox.borrow_mut().push_back(heard); + ctx.request_repaint(); } }); } + /// Every frame: handle what the host sent, in order (a file opens on the app's own open path, + /// as a dropped one does; a `saved` marks its document saved), and end a save that waited too + /// long. `now_ms`: the app's clock, which also wakes the app when the waiting save times out. + pub fn frame(&self, fig: &mut FigApp, ctx: &egui::Context, now_ms: u64) { + let heard = std::mem::take(&mut *self.inbox.borrow_mut()); + for message in heard { + match message { + FromHost::Open(name, bytes) => { + let forgotten = self.saves.borrow_mut().opened(&name); + if let Some(save) = forgotten { + fig.document_not_stored(&save.name, &figcraft_ui_egui::save_forgotten_on_open()); + } + queue_open(fig, name, bytes); + } + FromHost::Saved(id) => { + let confirmed = self.saves.borrow_mut().saved(&id); + match confirmed { + Some(save) => fig.document_stored(&save.name, save.file), + None => log::info!("host confirmed save {id:?}, which isn't the one waiting; ignored"), + } + } + } + } + let expired = self.saves.borrow_mut().expire(now_ms); + if let Some(save) = expired { + let secs = self.saves.borrow().timeout_ms() / 1000; + let _ = self.host.post_failed(&format!("save {} was not confirmed within {secs} seconds", save.id), Some(&save.id)); + fig.document_not_stored(&save.name, &figcraft_ui_egui::save_unconfirmed(usize::try_from(secs).unwrap_or(usize::MAX))); + } + let wait = self.saves.borrow().wait_ms(now_ms); + if let Some(wait) = wait { + ctx.request_repaint_after(std::time::Duration::from_millis(wait)); + } + } + /// `?author=`: the host's name for the user signs comments and board notes. pub fn set_author(app: &mut FigApp, author: &str) { let author: String = author.trim().chars().take(MAX_AUTHOR_CHARS).collect(); @@ -93,24 +157,53 @@ impl Bridge { /// The document file the host opened or the last Save As made, if any. pub fn host_file(&self) -> Option { - self.host_file.borrow().clone() + self.saves.borrow().host_file().map(str::to_string) } - /// Hand a file the app would otherwise download to the host; `false` when nothing was - /// delivered. The `saveAs` rule is this module's documentation's. + /// Hand a file the app would otherwise download to the host, without an `id`; `false` when + /// nothing was delivered. To a host that confirms saves only copies and exports come this way + /// (the document's own file goes through [`post_document`](Self::post_document)), so they are + /// `saveAs: false`; to one that doesn't, the `saveAs` rule is this module's documentation's. pub fn post_save(&self, path: &str, bytes: &[u8]) -> bool { let name = file_name(path); - let host_file = self.host_file.borrow().clone(); - let save_as = crate::hostmode::save_as(&name, host_file.as_deref()); + let save_as = !self.confirms_saves && self.saves.borrow().save_as(&name); let sent = self.host.post_save(&name, bytes, None, save_as).is_ok(); // After a Save As hand-over the host has the new file: the next Save of it sends its name // with `saveAs: false`. A failed send changes nothing, so a retry is still a Save As. if sent && save_as { - *self.host_file.borrow_mut() = Some(name); + self.saves.borrow_mut().adopt(&name); } sent } + /// Hand the host the document's own file (Save, Save As) as `file`. To a host that confirms + /// saves it goes with an `id` and stays unsaved until the host answers ([`Delivery::Pending`]); + /// otherwise as [`post_save`](Self::post_save). + pub fn post_document(&self, path: &str, bytes: &[u8], file: FileSnapshot, now_ms: u64, ctx: &egui::Context) -> Delivery { + if !self.confirms_saves { + return if self.post_save(path, bytes) { Delivery::Saved } else { Delivery::Refused }; + } + let name = file_name(path); + // Recorded before the post: a page host can answer while it is still dispatching. + let (started, timeout_ms) = { + let mut saves = self.saves.borrow_mut(); + (saves.start(&name, file, now_ms), saves.timeout_ms()) + }; + match self.host.post_save(&name, bytes, Some(&started.id), started.save_as) { + Ok(()) => { + // Schedule the timeout wakeup immediately so an idle tab still times out if the + // host never answers after this frame. + ctx.request_repaint_after(std::time::Duration::from_millis(timeout_ms)); + Delivery::Pending + } + Err(e) => { + log::error!("couldn't hand {name} to the host: {e}"); + self.saves.borrow_mut().failed(&started.id); + Delivery::Refused + } + } + } + /// Report unsaved changes when they appear or go away, not every frame (the crate does not /// repeat a state it already reported). pub fn set_dirty(&self, dirty: bool) { @@ -118,23 +211,33 @@ impl Bridge { } } -/// The file an open message carries, queued for the app's own open path, or nothing when the -/// payload isn't one (a `File` the app doesn't read, or over the open limit). -fn deliver_open(opens: &OpenQueue, ctx: &egui::Context, host_file: &RefCell>, name: &str, data: &FileData) { +/// The app's own open queue gets a file the host sent: the same "Opening as a new file" card as a +/// dropped file, and `file.open` with the contents once read. +fn queue_open(fig: &mut FigApp, name: String, bytes: Vec) { + let read: figcraft_ui_egui::ReadFuture = Box::pin(std::future::ready(Ok(bytes))); + fig.ui.pending_opens.push(figcraft_ui_egui::pending_open::PendingOpen { + label: name.clone(), + params: serde_json::json!({ "name": name }), + command: "file.open", + target: None, + read: Some(read), + }); +} + +/// The file an open message carries, copied out for the next frame, or nothing when the payload +/// isn't one (a `File` the app doesn't read, or over the open limit). Once handled it is the +/// document's file: a Save of it under this name is `saveAs: false`. +fn open_bytes(name: &str, data: &FileData) -> Option { let name = crate::hostmode::open_name(name); let FileData::Bytes(array) = data else { log::warn!("host file {name} came as a File; FigCraft reads bytes only; not opened"); - return; + return None; }; if figcraft_ui_egui::browser_can_read(&name, data.size()).is_err() { log::warn!("host file {name} is too large to open in the browser; not opened"); - return; + return None; } - // The document's file is now the one the host sent: a Save of it under this name is - // `saveAs: false`. - *host_file.borrow_mut() = Some(name.clone()); - opens.borrow_mut().push((name, array.to_vec())); - ctx.request_repaint(); + Some(FromHost::Open(name, array.to_vec())) } /// The last component of `path`, or the whole of it when there is none. diff --git a/apps/figcraft-web/src/host_saves.rs b/apps/figcraft-web/src/host_saves.rs new file mode 100644 index 000000000..5c2f7e58c --- /dev/null +++ b/apps/figcraft-web/src/host_saves.rs @@ -0,0 +1,262 @@ +//! Confirmed saves: what the bridge ([`crate::host`]) knows about the files it handed a host page, +//! kept apart from the browser so every step is testable without one (like [`crate::hostmode`]). +//! +//! A host that confirms saves (`?save=managed`, [`crate::query::confirms_saves`]) gets each +//! Save and Save As of the document with an `id` and answers `saved` with that `id` once it stored +//! the file. Until then the document keeps its unsaved changes. Only one document save waits at a +//! time: a newer one replaces it, and an answer for any other `id` (an older save, a repeat, one +//! the host made up) is ignored. A save the host doesn't answer within the timeout counts as not +//! stored. A file the host opens forgets the save still waiting, so a late answer can't touch +//! the file opened since. +//! +//! The file the host opened, or the one the last Save As made, is kept here too: a Save As becomes +//! the document's file only once the host confirms it, so after a failed one the next Save is +//! still a Save As. + +/// How long a document save waits for the host's answer before it counts as not stored. +pub const DEFAULT_TIMEOUT_MS: u64 = 30_000; + +/// A document save handed to the host and not answered yet. +#[derive(Debug)] +pub struct PendingSave { + /// The `id` the save carried; the host's `saved` names it. + pub id: String, + /// The file name it went out under. + pub name: String, + /// It went out as `saveAs: true`: confirmed, it becomes the document's file. + pub save_as: bool, + /// When it was handed over, in the caller's clock (milliseconds). + pub started_at_ms: u64, + /// The document as handed over. In the app this is its `FileSnapshot` (the tab's uid, its + /// revision and contents), which marks the document saved as of the snapshot once confirmed. + pub file: F, +} + +/// A document save just handed to [`HostSaves::start`]: what to post with it. +#[derive(Debug, PartialEq, Eq)] +pub struct Started { + pub id: String, + pub save_as: bool, +} + +/// The bridge's record of the document's file and the save waiting for the host. +#[derive(Debug)] +pub struct HostSaves { + host_file: Option, + /// The number in the next save's `id`. Never reset, so an `id` is never used twice on a page. + next_id: u64, + pending: Option>, + timeout_ms: u64, +} + +impl Default for HostSaves { + fn default() -> Self { + Self::new(DEFAULT_TIMEOUT_MS) + } +} + +impl HostSaves { + pub fn new(timeout_ms: u64) -> Self { + Self { host_file: None, next_id: 1, pending: None, timeout_ms } + } + + /// How long a save waits for its answer, in milliseconds. + pub fn timeout_ms(&self) -> u64 { + self.timeout_ms + } + + /// The file the host opened, or the one the last confirmed (or, without confirmation, posted) + /// Save As made. + pub fn host_file(&self) -> Option<&str> { + self.host_file.as_deref() + } + + /// Whether a file named `name` goes out as `saveAs: true` now ([`crate::hostmode::save_as`]). + pub fn save_as(&self, name: &str) -> bool { + crate::hostmode::save_as(name, self.host_file.as_deref()) + } + + /// A Save As went to a host that doesn't confirm saves: `name` is the document's file now. + pub fn adopt(&mut self, name: &str) { + self.host_file = Some(name.to_string()); + } + + /// The host sent the file `name` to open: it is the document's file now. A save still waiting + /// was for the document open before, so it is forgotten and returned; its answer, if one + /// comes, is ignored, and that document keeps its unsaved changes. + pub fn opened(&mut self, name: &str) -> Option> { + self.host_file = Some(name.to_string()); + self.pending.take() + } + + /// A Save or Save As of the document as `file`, under `name`, handed over at `now_ms`: the `id` + /// and `saveAs` to post it with. A save still waiting is replaced, so its answer is ignored. + pub fn start(&mut self, name: &str, file: F, now_ms: u64) -> Started { + let id = format!("save-{}", self.next_id); + self.next_id += 1; + let save_as = self.save_as(name); + self.pending = Some(PendingSave { id: id.clone(), name: name.to_string(), save_as, started_at_ms: now_ms, file }); + Started { id, save_as } + } + + /// The host's `saved` for `id`: the save it confirms, when that is the one waiting. A Save As + /// becomes the document's file now. Any other `id` changes nothing. + pub fn saved(&mut self, id: &str) -> Option> { + let save = self.take(id)?; + if save.save_as { + self.host_file = Some(save.name.clone()); + } + Some(save) + } + + /// The save `id` could not be stored (the post failed, or the host refused it): the save, + /// when that is the one waiting. The document's file stays as it was. Any other `id` changes + /// nothing. + pub fn failed(&mut self, id: &str) -> Option> { + self.take(id) + } + + /// The save waiting since longer than the timeout at `now_ms`, which then counts as failed. + pub fn expire(&mut self, now_ms: u64) -> Option> { + let waiting = self.pending.as_ref()?; + if now_ms.saturating_sub(waiting.started_at_ms) < self.timeout_ms { + return None; + } + self.pending.take() + } + + /// How long from `now_ms` until the waiting save times out (so the app wakes then), or + /// `None` when none waits. + pub fn wait_ms(&self, now_ms: u64) -> Option { + let waiting = self.pending.as_ref()?; + Some((waiting.started_at_ms.saturating_add(self.timeout_ms)).saturating_sub(now_ms)) + } + + fn take(&mut self, id: &str) -> Option> { + if self.pending.as_ref().is_some_and(|p| p.id == id) { self.pending.take() } else { None } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The document as handed over: in these tests, a label for the revision saved. + type Saves = HostSaves<&'static str>; + + fn opened(name: &str) -> Saves { + let mut saves = Saves::default(); + assert!(saves.opened(name).is_none()); + saves + } + + #[test] + fn each_save_gets_an_id_of_its_own() { + let mut saves = opened("Poster.figcraft"); + let first = saves.start("Poster.figcraft", "r1", 0).id; + let second = saves.start("Poster.figcraft", "r2", 0).id; + assert_ne!(first, second); + saves.opened("Other.figcraft"); + let third = saves.start("Other.figcraft", "r3", 0).id; + assert!(third != first && third != second, "opening a file doesn't start the ids over"); + } + + #[test] + fn a_confirmed_save_hands_back_what_was_saved() { + let mut saves = opened("Poster.figcraft"); + let started = saves.start("Poster.figcraft", "r1", 5); + assert!(!started.save_as, "a Save of the host's own file"); + let save = saves.saved(&started.id).expect("the waiting save"); + assert_eq!((save.file, save.name.as_str(), save.started_at_ms), ("r1", "Poster.figcraft", 5)); + assert!(saves.wait_ms(5).is_none(), "nothing waits any more"); + assert!(saves.saved(&started.id).is_none(), "a repeated answer changes nothing"); + } + + #[test] + fn a_save_as_becomes_the_document_s_file_only_once_confirmed() { + let mut saves = opened("Poster.figcraft"); + let started = saves.start("Poster 2.figcraft", "r1", 0); + assert!(started.save_as); + assert_eq!(saves.host_file(), Some("Poster.figcraft"), "not before the host stored it"); + saves.saved(&started.id); + assert_eq!(saves.host_file(), Some("Poster 2.figcraft")); + assert!(!saves.start("Poster 2.figcraft", "r2", 0).save_as, "the next Save is of that file"); + } + + #[test] + fn a_failed_save_as_leaves_the_document_s_file_so_a_retry_is_still_a_save_as() { + let mut saves = opened("Poster.figcraft"); + let started = saves.start("Poster 2.figcraft", "r1", 0); + let save = saves.failed(&started.id).expect("the waiting save"); + assert_eq!(save.file, "r1"); + assert_eq!(saves.host_file(), Some("Poster.figcraft")); + assert!(saves.start("Poster 2.figcraft", "r1", 0).save_as); + } + + #[test] + fn answers_for_other_ids_change_nothing() { + let mut saves = opened("Poster.figcraft"); + let started = saves.start("Poster 2.figcraft", "r1", 0); + for id in ["", "save-0", "save-99", "Save-1 ", "nonsense"] { + assert!(saves.saved(id).is_none(), "{id:?}"); + assert!(saves.failed(id).is_none(), "{id:?}"); + } + assert_eq!(saves.host_file(), Some("Poster.figcraft")); + assert!(saves.saved(&started.id).is_some(), "the real answer still counts"); + } + + #[test] + fn a_newer_save_replaces_the_one_waiting() { + let mut saves = opened("Poster.figcraft"); + let older = saves.start("Poster 2.figcraft", "r1", 0); + let newer = saves.start("Poster.figcraft", "r2", 10); + assert!(saves.saved(&older.id).is_none(), "a late answer for the older save is ignored"); + assert!(saves.failed(&older.id).is_none()); + assert_eq!(saves.host_file(), Some("Poster.figcraft"), "the older Save As never became the file"); + assert_eq!(saves.saved(&newer.id).map(|s| s.file), Some("r2")); + } + + #[test] + fn a_save_left_unanswered_times_out() { + let mut saves = Saves::new(1_000); + saves.opened("Poster.figcraft"); + let started = saves.start("Poster 2.figcraft", "r1", 100); + assert!(saves.expire(100).is_none()); + assert!(saves.expire(1_099).is_none(), "still inside the timeout"); + let remaining = saves.wait_ms(600).expect("a save waits"); + assert!(remaining > 0 && remaining < saves.timeout_ms(), "{remaining}"); + let save = saves.expire(1_100).expect("timed out"); + assert_eq!(save.file, "r1"); + assert_eq!(saves.host_file(), Some("Poster.figcraft"), "a timed-out Save As isn't the file"); + assert!(saves.saved(&started.id).is_none(), "an answer after the timeout is ignored"); + assert!(saves.expire(5_000).is_none() && saves.wait_ms(5_000).is_none()); + } + + #[test] + fn a_clock_that_goes_back_does_not_end_the_wait_early() { + let mut saves = Saves::new(1_000); + saves.start("Untitled.figcraft", "r1", 500); + assert!(saves.expire(0).is_none()); + assert!(saves.wait_ms(0).is_some_and(|w| w >= saves.timeout_ms())); + } + + #[test] + fn opening_a_file_forgets_the_save_still_waiting() { + let mut saves = opened("Poster.figcraft"); + let started = saves.start("Poster 2.figcraft", "r1", 0); + let dropped = saves.opened("Other.figcraft").expect("the save that waited"); + assert_eq!(dropped.file, "r1"); + assert!(saves.saved(&started.id).is_none(), "its late answer is ignored"); + assert_eq!(saves.host_file(), Some("Other.figcraft"), "and can't rename the file opened since"); + assert!(saves.expire(u64::MAX).is_none()); + } + + #[test] + fn without_confirmation_a_save_as_is_the_document_s_file_once_posted() { + let mut saves = Saves::default(); + assert!(saves.save_as("Untitled.figcraft"), "the host never sent a file"); + saves.adopt("Untitled.figcraft"); + assert!(!saves.save_as("Untitled.figcraft")); + assert!(!saves.save_as("Untitled.png"), "an export is never the document's file"); + } +} diff --git a/apps/figcraft-web/src/main.rs b/apps/figcraft-web/src/main.rs index 36d37ed39..59d2e008f 100644 --- a/apps/figcraft-web/src/main.rs +++ b/apps/figcraft-web/src/main.rs @@ -21,13 +21,14 @@ //! `http://` on a trusted network to reach plain `ws://` hosts on other machines. //! - host mode: `?host=parent` (a same-origin page embedding FigCraft in an `