Skip to main content

brep_app/
store.rs

1//! The persistent-storage / filesystem seam — the ONE platform exception in
2//! the engine-native UI. Settings, dock layout, and model documents all use the
3//! same [`ModelStore::read`] / [`ModelStore::write`] API. Only its backend differs:
4//! desktop writes files; the browser mirrors an ASYNC, swappable
5//! `mirror_store::StoreBackend` — IndexedDB today, a remote server next — into
6//! memory and writes behind it, which is what keeps this whole API synchronous.
7//!
8//! Desktop reads the real filesystem on every call. The browser CANNOT: IndexedDB
9//! has no synchronous read on the main thread, so "go to the live filesystem every
10//! time" is not implementable there — the mirror is not a convenience, it is the
11//! only way this API can be synchronous at all. What the mirror owes in exchange
12//! is that it never falls behind the storage it stands for, and the key space has
13//! MORE than one writer: every other tab of the same origin. So each tab announces
14//! the key it committed and re-reads the keys it is told about
15//! (`mirror_store::MirrorStore::refresh_key`, over the `brep-app:store` broadcast
16//! in `web_model`). Save a part in one tab and the tab holding the assembly can
17//! insert it — no reload.
18
19/// Reserved persistent-object names used internally for application state.
20pub const SETTINGS_KEY: &str = "@settings";
21pub const FEATURE_PALETTE_DISPLAY_KEY: &str = "@feature_palette_display";
22pub const DOCK_LAYOUT_KEY: &str = "@dock_layout";
23/// Pinned explorer locations (a JSON array of navigable location strings),
24/// persisted through the ordinary `read`/`write` CRUD like the other reserved
25/// keys so the sidebar needs no dedicated trait surface.
26pub const PINNED_KEY: &str = "@pinned";
27/// The AUTOSAVE blob: every open document that had unsaved changes the last
28/// time the shell's autosave fired (see `crate::recovery`), so a crash, a
29/// closed tab or a reload can offer that work back. Written debounced, removed
30/// the moment nothing is dirty; never listed as a document.
31pub const RECOVERY_KEY: &str = "@recovery";
32/// The KiCad library folders the KiCad import last used (`panels::kicad_import`).
33/// Desktop only: the web build cannot read a KiCad library, so it never writes it.
34pub const KICAD_LIBRARY_KEY: &str = "@kicad_library";
35/// The adoption importer's ledgers (`plm::adoption::ImportLedgers`), per PLM
36/// server and per imported folder: what a stopped import resumes from. It
37/// never leaves the machine — it records THIS machine's runs against a
38/// server, and the source tree it describes is on this machine.
39pub const PLM_IMPORT_KEY: &str = "@plm_import";
40/// Explicitly installed executable packages stay on this machine, including in PLM mode.
41pub const PLUGINS_KEY: &str = "@plugins";
42/// Explicitly saved JavaScript editor source, local even in PLM mode.
43pub const JAVASCRIPT_DRAFT_KEY: &str = "@javascript_draft";
44/// Recent document identities, shared through the user preference store.
45pub const RECENT_DOCUMENTS_KEY: &str = "@recent_documents";
46/// The File menu's recent-document thumbnails (`plm::thumbnail::recent`): ONE
47/// JSON map, store name → base64 PNG, pruned to [`RECENT_DOCUMENTS_KEY`]'s
48/// names, so it is bounded by the recent list. Local, not a preference: a
49/// picture cache of this machine's saves, never sent to a PLM server (which
50/// keeps its own thumbnail per revision). One reserved name rather than a key
51/// derived per document, because a derived name would fall through
52/// [`KeySpace::of`] to `Documents` — listed by Open, written as a model file,
53/// routed to the PLM server.
54pub const RECENT_THUMBNAILS_KEY: &str = "@recent_thumbnails";
55
56/// The reserved names that are a user's PREFERENCES (plm-cad-integration-todo
57/// D1): state that follows the user, not the machine. A file backend keeps them
58/// where it always has; a PLM backend serves them from its per-user store (P5).
59///
60/// `@pinned` is listed here as what it IS — explorer FOLDER locations, not
61/// document identities — so in PLM mode it pins workspace folders (S14), never
62/// `part/…/rev/…` keys.
63pub const PREFERENCE_KEYS: &[&str] = &[
64    SETTINGS_KEY,
65    DOCK_LAYOUT_KEY,
66    PINNED_KEY,
67    FEATURE_PALETTE_DISPLAY_KEY,
68    KICAD_LIBRARY_KEY,
69    RECENT_DOCUMENTS_KEY,
70];
71
72/// The reserved names that never have to leave the machine to be safe: the
73/// local-first copy of `@recovery` — a PLM session MIRRORS it to the server
74/// after the local write (D1, S1's composition); the local copy is what a
75/// network drop cannot take away — and `@plm_import`, which is never
76/// mirrored.
77///
78/// The CAM workbench's user tool library (`panels::cam_library`) is LOCAL
79/// too: a preference key is served per user by a PLM, whose server
80/// allow-lists the preference names (`BREP_plm` `api::preferences::KEYS`),
81/// so a new preference would be refused by every deployed server and the
82/// sign-in's preference load fails on the first refused key. The library
83/// stays on the machine until the PLM gains the key and the backend
84/// tolerates a server that lacks it.
85pub const LOCAL_KEYS: &[&str] = &[
86    RECOVERY_KEY,
87    PLM_IMPORT_KEY,
88    PLUGINS_KEY,
89    JAVASCRIPT_DRAFT_KEY,
90    RECENT_THUMBNAILS_KEY,
91    crate::panels::cam_library::CAM_TOOL_LIBRARY_KEY,
92];
93
94/// Which of the three key spaces a store name belongs to (D1, the round 10
95/// answer). Every name is exactly one of them:
96///
97/// * **Documents** — model documents; the PLM's store routes
98///   (`part/<part>/rev/<revision>`), a file path or a browser `/models/...`
99///   name on the file backends.
100/// * **Preferences** — [`PREFERENCE_KEYS`].
101/// * **Local** — [`LOCAL_KEYS`].
102///
103/// The browser's explorer DIRECTORY rows are none of the three: they belong to
104/// the file backends only (a PLM user's folders are the workspace, S14), so they
105/// never reach this classifier — see `mirror_store::key_space`.
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub enum KeySpace {
108    Documents,
109    Preferences,
110    Local,
111}
112
113impl KeySpace {
114    /// The key space of a store NAME (what callers pass to
115    /// [`ModelStore::read`] / [`ModelStore::write`]).
116    pub fn of(name: &str) -> Self {
117        if PREFERENCE_KEYS.contains(&name) {
118            KeySpace::Preferences
119        } else if LOCAL_KEYS.contains(&name) {
120            KeySpace::Local
121        } else {
122            KeySpace::Documents
123        }
124    }
125}
126
127/// How much of a document a store holds right now — the synchronous answer to
128/// "can `read` give me this?" that a store with an index-only hydrate owes.
129///
130/// A store that holds everything it lists (the native filesystem, a browser
131/// origin hydrated whole) only ever answers `Absent` or `Resident`. A store
132/// hydrated from an INDEX (the mirror's `OnDisk` entries — the PLM catalog is
133/// the corpus that needs it) also answers `OnDisk`: the name exists and its
134/// size is known, but its bytes are still on the backend, and a `read` of it
135/// returns `None` while it asks for them.
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137pub enum Residency {
138    Absent,
139    OnDisk,
140    Resident,
141}
142
143/// A document as a caller can use it this frame: its bytes, still loading,
144/// or not there ([`read_now`]).
145#[derive(Clone, Debug, PartialEq, Eq)]
146pub enum ReadNow {
147    Ready(String),
148    Loading,
149    Absent,
150}
151
152/// Read `name`, telling "not loaded yet" from "gone".
153///
154/// Not simply `read` then `residency`: a `read` of an `OnDisk` entry asks the
155/// backend for the bytes, and a backend that answers at once (an in-process
156/// router, a local cache) lands them INSIDE that read. `read` has already
157/// said `None`, and `residency` now says `Resident`. Read naively, that is a
158/// document reported missing that is there. So a `None` that turned resident
159/// is read again.
160pub fn read_now(store: &dyn ModelStore, name: &str) -> ReadNow {
161    if let Some(contents) = store.read(name) {
162        return ReadNow::Ready(contents);
163    }
164    match store.residency(name) {
165        Residency::Resident => store.read(name).map_or(ReadNow::Absent, ReadNow::Ready),
166        Residency::OnDisk => ReadNow::Loading,
167        Residency::Absent => ReadNow::Absent,
168    }
169}
170
171/// A file selected outside the model store. Keeping bytes verbatim allows the
172/// same upload channel to carry binary STL as well as text CAD formats.
173pub struct ImportedFile {
174    pub name: String,
175    pub bytes: Vec<u8>,
176}
177
178/// One entry exposed to the common in-application filesystem browser.
179#[derive(Clone, Debug, PartialEq)]
180pub struct BrowserEntry {
181    pub name: String,
182    pub identity: String,
183    pub is_dir: bool,
184    /// File size in bytes for the Size column. `None` for directories or where
185    /// the backend cannot report it.
186    pub size: Option<u64>,
187    /// Last-modified time as whole Unix seconds for the Date column. `None` where
188    /// unavailable — the browser key/value backends store values, not timestamps.
189    pub modified: Option<f64>,
190}
191
192/// A quick-access destination for the explorer's left sidebar.
193#[derive(Clone, Debug, PartialEq, Eq)]
194pub struct BrowserPlace {
195    /// Human label shown in the sidebar (e.g. `"Home"`, `"Models"`, a disk name).
196    pub label: String,
197    /// The navigable location — pass to [`ModelStore::browser_navigate`].
198    pub location: String,
199    /// Which built-in glyph the widget draws for this place.
200    pub kind: PlaceKind,
201}
202
203/// The category of a [`BrowserPlace`], so the widget owns the icon styling.
204#[derive(Clone, Copy, Debug, PartialEq, Eq)]
205pub enum PlaceKind {
206    Home,
207    Documents,
208    Downloads,
209    Models,
210    Root,
211}
212// A MODEL is a whole document
213// (the engine-owned `HistoryRequest` JSON — one `.nbrep` recipe), and the
214// file panel needs to *enumerate*, read, and write NAMED documents, plus (in the
215// browser) hand a file to / take a file from the user's real filesystem. The same
216// trait also stores reserved application-state blobs. Platform-specific behavior
217// remains behind two `#[cfg]`-gated implementations.
218//
219// The trait is deliberately a **named-document CRUD** (`list` / `read` / `write`
220// / `remove`) plus a poll-based **file-interchange** side-channel. That shape is
221// exactly what a later **GitHub backend** needs: `list` = a repo directory
222// listing, `read` = fetch a file's contents, `write` = create/update (commit)
223// a file, `remove` = delete a file — the model name is the path within the repo.
224// An async backend (GitHub over HTTP, or the browser File System Access API /
225// OPFS whose main-thread API is async) slots in behind the SAME trait by driving
226// its request on a background task and surfacing the result through the
227// `begin_import` → `take_import` poll pattern used here for uploads, so the
228// synchronous panel code never changes. GitHub itself is a deferred follow-up;
229// this lands the seam it plugs into.
230
231/// The media type an exported file is handed to the user with, from its own
232/// extension.
233///
234/// A browser download IS its media type: the type on the `Blob` is what decides
235/// whether the file opens in a viewer, is offered as a download, or is mailed on
236/// correctly — the name alone is a hint. So the two export doors below take it
237/// from here rather than each hard-coding one, which is what they used to do
238/// (`model/gltf-binary` on everything the byte lane carried, because GLB was the
239/// only thing it carried, and `application/octet-stream` on every text export).
240///
241/// Unknown extensions fall back to `application/octet-stream`, which is the
242/// correct "some bytes, download them" answer.
243///
244/// It is also the type a file is UPLOADED to the PLM with (attachments and
245/// workspace files), so a model stored there comes back down as the same
246/// opaque bytes and keeps its name.
247pub fn media_type(file_name: &str) -> &'static str {
248    let extension = std::path::Path::new(file_name)
249        .extension()
250        .map(|extension| extension.to_string_lossy().to_ascii_lowercase())
251        .unwrap_or_default();
252    match extension.as_str() {
253        "pdf" => "application/pdf",
254        "svg" => "image/svg+xml",
255        "glb" => "model/gltf-binary",
256        // The 3MF Consortium's registered type for the package.
257        "3mf" => "model/3mf",
258        "json" => "application/json",
259        // The PCB's fabrication bundle.
260        "zip" => "application/zip",
261        // A model document is JSON inside, but typed as opaque bytes: a browser
262        // that sees a JSON type on a download may "correct" the name to
263        // `bracket.nbrep.json`, and the name is the only thing that routes it.
264        "nbrep" | "fbrep" | "tbrep" => "application/octet-stream",
265        // The CAD text formats. `model/step+zip` is the registered type for a
266        // zipped STEP; a plain `.step` file is `model/step`.
267        "step" | "stp" => "model/step",
268        "iges" | "igs" => "model/iges",
269        "x_t" | "xmt_txt" => "model/vnd.parasolid.transmit.text",
270        "stl" => "model/stl",
271        "obj" => "model/obj",
272        "dxf" => "image/vnd.dxf",
273        "csv" => "text/csv",
274        "txt" => "text/plain",
275        "md" => "text/markdown",
276        "png" => "image/png",
277        "jpg" | "jpeg" => "image/jpeg",
278        _ => "application/octet-stream",
279    }
280}
281
282/// Write `bytes` to `path` so that a crash or a full disk mid-save never leaves
283/// a short or empty file where the last good one was: a temporary beside
284/// `path` (`<name>.<pid>-<n>.tmp`, unique per write, never a sibling's name),
285/// written, flushed to disk, then renamed over `path`; on any failure the
286/// temporary is removed and `path` is untouched. `secret` creates the
287/// temporary owner-only (0600 on unix) from the first byte. The app's one
288/// atomic write: model saves, exports, the PLM config/token (I4), and the
289/// reserved application files the write-behind lane lands off the UI thread.
290#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
291pub(crate) fn write_atomic(path: &std::path::Path, bytes: &[u8], secret: bool) -> std::io::Result<()> {
292    use std::io::Write;
293    use std::sync::atomic::{AtomicU64, Ordering};
294    static NEXT: AtomicU64 = AtomicU64::new(0);
295    let name = path
296        .file_name()
297        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "no file name"))?;
298    let mut temp_name = name.to_os_string();
299    temp_name.push(format!(".{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
300    let temp = path.with_file_name(temp_name);
301    let mut options = std::fs::OpenOptions::new();
302    options.write(true).create_new(true);
303    #[cfg(unix)]
304    if secret {
305        use std::os::unix::fs::OpenOptionsExt;
306        // Created 0600, never chmod-ed down afterwards: there is no instant at
307        // which a secret sits in a file another user could open.
308        options.mode(0o600);
309    }
310    #[cfg(not(unix))]
311    let _ = secret;
312    let written = options
313        .open(&temp)
314        .and_then(|mut file| {
315            file.write_all(bytes)?;
316            file.sync_all()
317        })
318        .and_then(|()| std::fs::rename(&temp, path));
319    if written.is_err() {
320        let _ = std::fs::remove_file(&temp);
321    }
322    written
323}
324
325/// The application's single persistent-storage abstraction. Reserved application
326/// keys and named model documents are read and written through the same methods.
327/// All methods take `&self`; mutable backend state lives behind interior mutability.
328pub trait ModelStore {
329    /// Bounded file management over this host's persistent file store.
330    #[cfg(feature = "automation")]
331    fn files(&self, _request: &brep_mcp_core::files::Request) -> Result<brep_mcp_core::files::Reply, String> {
332        Err("files is unsupported by this store backend".into())
333    }
334    /// None while persistence is in flight; otherwise the operation's result.
335    #[cfg(feature = "automation")]
336    fn files_settled(&self, _request: &brep_mcp_core::files::Request) -> Option<Result<(), String>> { Some(Ok(())) }
337
338    /// A short human label of where documents persist, for the panel header
339    /// (e.g. `"filesystem: ~/.config/brep-app/models"` or `"browser storage"`).
340    fn backend_label(&self) -> String {
341        "persistent storage".into()
342    }
343
344    /// The names of the documents currently available to **Open** (bare names,
345    /// no extension). May be empty on a backend that cannot enumerate — then the
346    /// panel falls back to the name field / import.
347    fn list(&self) -> Vec<String> {
348        Vec::new()
349    }
350
351    /// Read a stored document by name, or `None` if absent/unreadable.
352    fn read(&self, name: &str) -> Option<String>;
353
354    /// Create or overwrite the document `name` with `contents`. `Err` carries a
355    /// message the panel surfaces in its status line.
356    fn write(&self, name: &str, contents: &str) -> Result<(), String>;
357
358    /// Delete the document `name` (best-effort; `Ok` if it is already gone).
359    fn remove(&self, _name: &str) -> Result<(), String> {
360        Ok(())
361    }
362
363    /// A monotonic count of this store's MUTATIONS — every `write`, `remove`
364    /// and `browser_write` that landed, WHOEVER made it. A read never moves
365    /// it; two reads that agree mean nothing was written in between.
366    ///
367    /// This is a cache-invalidation key, which is why it is REQUIRED rather
368    /// than defaulted: a default would let a new backend (the GitHub one this
369    /// trait is shaped for) compile while silently never invalidating
370    /// anything, which is the failure it exists to stop. The outdated-parts
371    /// badge (`panels::update_components`) used to key on the file dialog's
372    /// own save counter, which counts Save / Save As / native Save-As and
373    /// NOTHING else — so a KiCad re-import (`panels::kicad_bulk::write_part`)
374    /// or the explorer's delete row could change a part's source under an open
375    /// assembly, move no other generation, and leave the badge dark.
376    fn mutation_generation(&self) -> u64;
377
378    /// Whether `name` is absent, listed but not yet loaded, or readable now
379    /// (see [`Residency`]). The default answers from `read`, which is exact for
380    /// every store that holds what it lists; only an index-hydrated store
381    /// overrides it. No caller branches on `OnDisk` yet — it is here so one
382    /// CAN tell "not loaded yet" from "gone" without a second store API.
383    fn residency(&self, name: &str) -> Residency {
384        match self.read(name) {
385            Some(_) => Residency::Resident,
386            None => Residency::Absent,
387        }
388    }
389
390    /// What kind of identity `identity` is on THIS store (see
391    /// [`DocumentIdentity`] and the enumeration above it). Every file backend
392    /// keys by path, so the default never parses: a browser folder named
393    /// `part/7/rev` holds a document, not a revision.
394    fn identity(&self, identity: &str) -> DocumentIdentity {
395        DocumentIdentity::Path(identity.to_string())
396    }
397
398    /// The name a person sees for `identity`: the tab title, the name field.
399    /// The default is the file rule, `model_display_name`; a PLM store knows
400    /// the part number and revision label from its index, which the key alone
401    /// does not carry.
402    fn display_name(&self, identity: &str) -> String {
403        model_display_name(identity)
404    }
405
406    /// The identity of `file_name` beside the document `identity` — or `None`
407    /// on a store with no folders to be beside (the PLM, where a family member
408    /// or a spun-out part is a new part instead, S7 / S9). The default is the
409    /// file rule, [`sibling_identity`].
410    fn sibling_of(&self, identity: &str, file_name: &str) -> Option<String> {
411        Some(sibling_identity(identity, file_name))
412    }
413
414    /// The ONE spelling of the document `name` resolves to, as the explorer
415    /// spells it (`BrowserEntry::identity`), so two names for one document
416    /// compare equal: a bare `bolt` and `/home/u/.config/brep-app/models/bolt.nbrep`
417    /// on the desktop, `sub/bolt` and `/models/sub/bolt.nbrep` in the browser.
418    ///
419    /// The adoption importer (S13) needs it. An assembly's `sourceKey`s are
420    /// whatever name the part was inserted by, and the importer must match
421    /// each one to the file it walked. The default is `name` unchanged, which
422    /// is right for a store with one spelling per document (a PLM store's
423    /// revision keys).
424    fn canonical_identity(&self, name: &str) -> String {
425        name.to_string()
426    }
427
428    /// [`Self::canonical_identity`] as a function that outlives the borrow:
429    /// what the open documents compare identities with (a tab is named by the
430    /// explorer's spelling, a `sourceKey` by whatever the part was inserted
431    /// by — `crate::document::live_link`).
432    fn canonicalizer(&self) -> Canonicalizer {
433        std::rc::Rc::new(str::to_string)
434    }
435
436    /// Persistence failures that surfaced AFTER a `write` / `remove` already
437    /// returned `Ok` — the price of a WRITE-BEHIND backend (see
438    /// `mirror_store`). The app shell drains this once per frame into the toast
439    /// overlay, so a save that never reached storage is never silent: the
440    /// in-memory copy means nothing is lost mid-session, but the user has to know
441    /// it will not survive a reload. Empty on a backend that writes synchronously
442    /// (native files), which reports through `write`'s `Err` instead.
443    fn take_persistence_errors(&self) -> Vec<String> {
444        Vec::new()
445    }
446
447    /// The documents (as named to `write`) whose write failed AFTER `write`
448    /// returned `Ok`, each once. The frame loop marks their tabs unsaved again:
449    /// a Save that never reached the server must not leave a clean tab, or
450    /// closing it loses the edit without a question. Empty on a backend that
451    /// writes synchronously, whose `write` returns the `Err` itself.
452    fn take_failed_writes(&self) -> Vec<String> {
453        Vec::new()
454    }
455
456    /// The last write of `name` failed after it returned: what [`Self::read`]
457    /// gives is this session's, not the backend's. A Save that would skip the
458    /// write because the store "already holds" the text must write it.
459    fn write_failed(&self, name: &str) -> bool {
460        let _ = name;
461        false
462    }
463
464    /// For a [`Self::write_failed`] key: the content hash of the document the
465    /// failed write was based on (empty: unknown).
466    fn failed_write_base(&self, name: &str) -> Option<String> {
467        let _ = name;
468        None
469    }
470
471    /// [`Self::write`], but only over the document whose content hash is
472    /// `expected` (a PLM revision's `If-Match`): a backend holding a newer one
473    /// refuses it, and the failure says so. A store with no such check writes.
474    fn write_if(&self, name: &str, contents: &str, expected: &str) -> Result<(), String> {
475        let _ = expected;
476        self.write(name, contents)
477    }
478
479    /// The PLM this session is on, or is configured for and not on (why, when
480    /// known): what the Settings PLM tab shows (plan S1 part 3). `None` is the
481    /// file-based app, and the tab is absent.
482    fn plm_session(&self) -> Option<crate::plm::connection::Session> {
483        None
484    }
485
486    /// Where this session's PLM server URL is kept: the Settings PLM tab's
487    /// Server URL field reads it, in every native session (file or PLM).
488    /// `None` where no `plm.json` exists to write — the browser, whose PLM is
489    /// the server that serves its page, and the in-memory stores.
490    fn plm_url_setting(&self) -> Option<crate::plm::connection::UrlSetting> {
491        None
492    }
493
494    /// Save the Server URL to `plm.json` as `--plm-configure` does
495    /// ([`crate::plm::config::repoint`]: a malformed URL is refused, and a
496    /// different server drops this machine's token). A file session that was
497    /// on `plm.json` reports the new server from here on (signed out), so the
498    /// tab's sign-in reaches it at once; a PLM session stays on its server
499    /// until the next start.
500    fn save_plm_url(&self, url: &str) -> Result<crate::plm::connection::UrlSaved, String> {
501        let _ = url;
502        Err("this session keeps no PLM settings".into())
503    }
504
505    /// The signed-in PLM client of a session whose store IS the PLM, for the
506    /// calls that are not store reads and writes (Generate, spin-out, the
507    /// lifecycle verbs). `None` on every file store, and on a PLM configured
508    /// but not connected.
509    fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
510        None
511    }
512
513    /// What the PLM's store index says of revision `key` (`part/…/rev/…`):
514    /// its part number, label, lifecycle and lock, as the session last read
515    /// them. `None` on every file store and for a key the index does not list.
516    /// No request: this is the index the session already holds.
517    fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
518        let _ = key;
519        None
520    }
521
522    /// This session's checkout of the PLM revision `key` just landed: its
523    /// index row reads it as checked out to us now, before the change feed
524    /// says so (a Save planned meanwhile must not ask to check it out again).
525    /// A no-op on every file store.
526    fn note_checked_out(&self, key: &str) {
527        let _ = key;
528    }
529
530    /// Whether the index row of the PLM revision `key` lists our own last
531    /// write of it, with nothing newer listed since: what the change feed
532    /// names for it is our own save, which a reader need not read back.
533    /// `false` on every file store.
534    fn plm_written_by_us(&self, key: &str) -> bool {
535        let _ = key;
536        false
537    }
538
539    /// Bring the held index up to date after the change feed moved: `keys`
540    /// are the revisions the feed named, `stale` means it could not say. A
541    /// no-op on every file store.
542    fn refresh_plm_index(&self, keys: &[String], stale: bool) {
543        let _ = (keys, stale);
544    }
545
546    /// Remember a document that has already been durably written through a PLM
547    /// request. Update the session mirror without issuing a second write.
548    fn remember_saved_document(&self, name: &str, contents: &str) {
549        let _ = (name, contents);
550    }
551
552    /// This machine's own files, browsable, for the file chooser (any file,
553    /// any folder): the native file store itself, or the file store a PLM
554    /// session keeps beside the server. `None` in the browser, which picks
555    /// through [`Self::begin_pick_file`] instead.
556    fn local_files(&self) -> Option<&dyn ModelStore> {
557        None
558    }
559
560    /// The browser's file chooser for ANY file (not the model lane's
561    /// `.nbrep` input): the choice arrives later through
562    /// [`Self::take_picked_file`], under the file's own name.
563    fn begin_pick_file(&self) -> Result<(), String> {
564        Err("this platform has no file chooser".into())
565    }
566
567    /// The file [`Self::begin_pick_file`]'s chooser delivered, once.
568    fn take_picked_file(&self) -> Option<ImportedFile> {
569        None
570    }
571
572    /// Writes handed to a WRITE-BEHIND backend that have not settled yet,
573    /// the desktop's own state files included: the close path and exit wait
574    /// for all of them. Always 0 on a backend that writes synchronously.
575    fn pending_writes(&self) -> usize {
576        0
577    }
578
579    /// The part of [`Self::pending_writes`] the status bar's working
580    /// indicator names as saving ("Saving to browser storage"): documents and
581    /// state on their way to a backend. The desktop's own settings, layout,
582    /// recents and recovery files written behind are not a save the user
583    /// would recognise, and are left out. Also what a flow waiting for its
584    /// save to reach the server (Generate, a PLM follow) counts.
585    fn pending_saves(&self) -> usize {
586        self.pending_writes()
587    }
588
589    /// [`Self::pending_writes`], leaving out the writes of the documents
590    /// stored under `names`: what `settle` (MCP `store_writes`) on one
591    /// document waits for while other tabs save. A store that cannot tell its
592    /// writes apart counts all. The desktop's write-behind state files are
593    /// never counted here: everything in the process reads them through the
594    /// lane, so no settled state depends on their fsync.
595    fn pending_writes_except(&self, names: &[&str]) -> usize {
596        let _ = names;
597        self.pending_writes()
598    }
599
600    // --- common file-browser filesystem --------------------------------------
601
602    /// Current directory shown by the embedded explorer.
603    fn browser_location(&self) -> String {
604        self.backend_label()
605    }
606
607    /// Directories and matching files at the current explorer location.
608    /// Directories are never filtered. The default implementation presents the
609    /// backend's named model collection as a flat virtual directory.
610    fn browser_entries(&self, _extensions: &[&str]) -> Vec<BrowserEntry> {
611        self.list()
612            .into_iter()
613            .map(|name| BrowserEntry {
614                identity: name.clone(),
615                name,
616                is_dir: false,
617                size: None,
618                modified: None,
619            })
620            .collect()
621    }
622
623    fn browser_enter(&self, _identity: &str) -> Result<(), String> {
624        Err("this storage backend has no directories".into())
625    }
626
627    fn browser_up(&self) -> Result<(), String> {
628        Ok(())
629    }
630
631    fn browser_home(&self) -> Result<(), String> {
632        Ok(())
633    }
634
635    fn browser_root(&self) -> Result<(), String> {
636        Ok(())
637    }
638
639    /// Navigate the explorer directly to `location` — a value previously returned
640    /// by [`Self::browser_location`], a [`BrowserPlace::location`], a breadcrumb
641    /// ancestor, or a user-typed path. `Err` if it is not a directory this backend
642    /// can browse. Powers the breadcrumb, the sidebar, back/forward, and the
643    /// path-edit field. Default: unsupported.
644    fn browser_navigate(&self, _location: &str) -> Result<(), String> {
645        Err("this storage backend cannot navigate to a path".into())
646    }
647
648    /// Quick-access places for the explorer's left sidebar (home, documents, the
649    /// models root, disks…). Default: none, and the sidebar hides itself.
650    fn browser_places(&self) -> Vec<BrowserPlace> {
651        Vec::new()
652    }
653
654    /// Create a child directory at the current browser location.
655    fn browser_create_dir(&self, _name: &str) -> Result<(), String> {
656        Err("this storage backend cannot create directories".into())
657    }
658
659    /// Write a filename at the current browser location and return its stable
660    /// identity for subsequent plain Save operations.
661    fn browser_write(&self, name: &str, contents: &str) -> Result<String, String> {
662        self.write(name, contents)?;
663        Ok(name.to_string())
664    }
665
666    /// Write `contents` under EXACTLY `file_name` (extension kept: no model
667    /// extension munging, unlike [`Self::browser_write`]) at the current
668    /// browser location, and return the written file's full identity. The
669    /// Save-file chooser's door: on desktop every export goes through it once
670    /// the user has chosen the folder in the explorer. Default: unsupported —
671    /// the browser has no folders to choose and downloads instead
672    /// ([`Self::export_file_named_bytes`]).
673    fn browser_write_bytes(&self, _file_name: &str, _contents: &[u8]) -> Result<String, String> {
674        Err("this storage backend cannot write a file at a location".into())
675    }
676
677    /// Files available to the in-app explorer for a foreign-format import.
678    /// Names retain their extension. Browser storage returns none and offers an
679    /// Upload button instead; desktop enumerates its application files directory.
680    fn list_external_files(&self, _extensions: &[&str]) -> Vec<String> {
681        Vec::new()
682    }
683
684    /// Read one entry returned by [`Self::list_external_files`].
685    fn read_external_file(&self, _name: &str) -> Option<Vec<u8>> {
686        None
687    }
688
689    // --- real-file interchange (the platform "fallback") ----------------------
690    // The browser cannot silently write to an arbitrary path; these methods let
691    // it move a document to/from the user's real filesystem. Desktop instead
692    // browses and writes its application files directory directly.
693
694    /// Whether this backend can exchange files with the user's real filesystem
695    /// (browser download+upload). The panel shows the Upload affordance only when
696    /// this is `true`.
697    fn supports_file_interchange(&self) -> bool {
698        false
699    }
700
701    /// Hand `contents` to the user as a file named after `name` (browser: a
702    /// download; native w/ dialog: a Save-As). Returns the saved document's
703    /// identity — the full path the user chose on native (so the caller can
704    /// re-save straight to it), the bare download name on the web — or `None`
705    /// when the user cancelled. No-op (`None`) by default.
706    fn export_file(&self, name: &str, contents: &str) -> Result<Option<String>, String> {
707        let _ = (name, contents);
708        Ok(None)
709    }
710
711    /// Begin importing a real file — opens the platform picker. The result is
712    /// retrieved later via [`Self::take_import`] (upload/read is async in the
713    /// browser). No-op by default.
714    fn begin_import(&self) -> Result<(), String> {
715        Ok(())
716    }
717
718    /// Poll for a completed import, consuming it.
719    /// `None` until a `begin_import` finishes. Default: never any.
720    fn take_import(&self) -> Option<ImportedFile> {
721        None
722    }
723
724    // --- format-typed interchange (CAD / mesh) --------------------------------
725    // The model lanes above trade the `.nbrep` recipe; import/export of a
726    // foreign format (STEP text, ASCII STL) needs a DIFFERENT picker filter and
727    // must NOT mangle the file extension. These two methods add that lane while
728    // leaving the model lanes byte-for-byte. They share the SAME `take_import`
729    // pickup channel — the panel routes the result by its filename extension.
730
731    /// Begin importing a real file behind a specific picker `filter` (a human
732    /// label + dot-less extensions, e.g. `("STEP", &["step","stp"])`). The chosen
733    /// file's contents + its FULL name (extension preserved, so the panel can
734    /// route it) arrive via [`Self::take_import`]. Default: reuse [`Self::begin_import`].
735    fn begin_import_filtered(&self, _filter: (&str, &[&str])) -> Result<(), String> {
736        self.begin_import()
737    }
738
739    /// Hand `contents` to the user under EXACTLY `file_name` (extension included,
740    /// no model-extension munging) — the Save-As / download for a foreign export
741    /// format. The file's media type comes from its extension
742    /// ([`media_type`]). Default no-op (interchange unsupported).
743    fn export_file_named(&self, _file_name: &str, _contents: &str) -> Result<(), String> {
744        Ok(())
745    }
746
747    /// [`Self::export_file_named`] for a BINARY format (GLB, a sheet PDF). Every
748    /// text export could go through this one — text is bytes — but the text
749    /// method stays because the browser's `Blob` takes a string directly and
750    /// routing UTF-8 through a `Uint8Array` for every STEP file would be a copy
751    /// for nothing. Both lanes type the file the same way, from its extension,
752    /// so which lane an export takes is a question about copies and never about
753    /// what the user receives. Default no-op, like its text sibling.
754    fn export_file_named_bytes(&self, _file_name: &str, _contents: &[u8]) -> Result<(), String> {
755        Ok(())
756    }
757}
758
759/// Construct the platform's one persistent store for application state and models.
760/// A native file store rooted at `dir` — the seam an automation host uses to
761/// keep a session's settings, autosave and recovery blob out of the user's
762/// own config directory.
763///
764/// Laid out the way the SHIPPED app lays out its own config directory: models
765/// in `<dir>/models`, reserved application state beside them in `<dir>`. A
766/// session whose store collapsed the two would show the app its own
767/// `dock_layout.json` and `recovery.json` as documents in the Open dialog —
768/// rows a user never sees, in the one place automation exists to drive.
769///
770/// A `plm.json` in `dir` (what the test-mcp PLM fixture writes) makes the
771/// session a PLM session instead: see [`boot_native_store`]. Only the files
772/// count here — never `BREP_PLM_URL` — so a host's own environment cannot leak
773/// into a session it isolated. No `plm.json` is exactly the file store of
774/// before the PLM existed.
775#[cfg(not(target_arch = "wasm32"))]
776pub fn native_store_at(dir: std::path::PathBuf) -> Box<dyn ModelStore> {
777    match crate::plm::config::resolve(&dir, &|_| None, &Default::default()) {
778        Ok(None) => Box::new(native_model::FileModelStore::rooted_at(dir)),
779        Ok(Some(config)) => boot_native_store(dir, config),
780        Err(e) => file_store_with_notice(dir, format!("PLM config: {e}")),
781    }
782}
783
784/// The file store at `root`, saying on its first frame why it is not the PLM.
785#[cfg(not(target_arch = "wasm32"))]
786pub fn file_store_with_notice(root: std::path::PathBuf, reason: String) -> Box<dyn ModelStore> {
787    Box::new(
788        native_model::FileModelStore::rooted_at(root)
789            .with_notice(format!("{reason} — this session uses the file stores"))
790            .with_plm_reason(reason),
791    )
792}
793
794#[cfg(not(target_arch = "wasm32"))]
795pub use native_boot::{boot_native_store, check_native_plm, start_native_boot, NativeFileBackend, PendingBoot, BOOT_TIMEOUT};
796
797pub fn default_model_store() -> Box<dyn ModelStore> {
798    #[cfg(not(target_arch = "wasm32"))]
799    {
800        Box::new(native_model::FileModelStore::new())
801    }
802    #[cfg(target_arch = "wasm32")]
803    {
804        // Already built and HYDRATED by [`hydrate_web_store`] inside the async
805        // wasm entry point, so this is a hand-off, not a construction.
806        web_model::take_boot_store()
807    }
808}
809
810/// wasm: bring up browser persistence and pull the whole key space into memory.
811/// MUST be awaited before `eframe::WebRunner::start`, because everything
812/// downstream of it — [`default_model_store`], every `read` in `BrepApp::new` and
813/// in the frame loop — is synchronous and assumes a complete mirror.
814#[cfg(target_arch = "wasm32")]
815pub async fn hydrate_web_store() {
816    web_model::hydrate().await;
817}
818
819/// wasm: wake the reactive frame loop when an async file upload completes (see
820/// [`web_model::set_repaint_ctx`]). Re-exported here so the app shell reaches it
821/// as `store::set_repaint_ctx` without knowing the platform module.
822#[cfg(target_arch = "wasm32")]
823pub use web_model::set_repaint_ctx;
824
825/// Ask for a frame from anywhere, any thread: an async answer has landed that
826/// the frame loop should pick up. Browser: the egui context registered at boot.
827/// Native: the PLM executor's wake hook (the frame loop's `request_repaint`).
828pub(crate) fn wake_ui() {
829    #[cfg(target_arch = "wasm32")]
830    web_model::wake_frame_loop();
831    #[cfg(not(target_arch = "wasm32"))]
832    crate::plm::native::request_wake();
833}
834
835/// Desktop: block until the reserved application files written behind
836/// (`@settings`, `@dock_layout`, `@recovery`, ...) are on disk, or `limit`
837/// passed; `true` when every write queued before the call has landed. Called once the window has closed,
838/// and by tests that read those files from disk. Never from the frame.
839#[cfg(not(target_arch = "wasm32"))]
840pub fn flush_writes(limit: std::time::Duration) -> bool {
841    native_model::write_behind::flush(limit)
842}
843
844/// Run a background task (a PLM request, a store write, a thumbnail upload) and
845/// wake the frame loop whenever it makes progress. The app repaints only on
846/// input and explicit requests, so an answer that lands while the user is not
847/// moving the mouse is otherwise not shown, and a step that waits for the next
848/// frame does not run, until they do. Natively the PLM executor's waker already
849/// wakes the loop; in the browser the task is wrapped so each poll (after the
850/// I/O it was waiting on) requests a repaint.
851pub(crate) fn spawn_waking(task: impl std::future::Future<Output = ()> + 'static) {
852    #[cfg(target_arch = "wasm32")]
853    wasm_bindgen_futures::spawn_local(web_model::WakeOnPoll(Box::pin(task)));
854    #[cfg(not(target_arch = "wasm32"))]
855    crate::plm::native::spawn(task);
856}
857
858/// The document extension for a model recipe (`<name>.nbrep`) — the NORMAL
859/// part's. A bare name with no class extension means this one; a family
860/// (`.fbrep`) or template (`.tbrep`) keeps its extension in its name, so its
861/// class survives every round trip (see [`crate::document_class`]).
862pub const MODEL_EXT: &str = ".nbrep";
863
864/// Every model document extension, dot-less, for the explorer's filters.
865pub const MODEL_EXTENSIONS: &[&str] = &["nbrep", "fbrep", "tbrep"];
866
867/// A document file name with its class extension made lowercase, and
868/// `.nbrep` added when it has none: `Bolt` -> `Bolt.nbrep`,
869/// `Bolt.FBREP` -> `Bolt.fbrep`.
870pub fn model_file_name(name: &str) -> String {
871    let class = crate::document_class::DocumentClass::of_name(name).unwrap_or_default();
872    class.file_name(name)
873}
874
875// --- Desktop: the PLM session store ---------------------------------------------
876/// The native half of plan S2: the mirror over a remote backend, hydrated
877/// before the first frame, exactly as the wasm entry point hydrates IndexedDB
878/// before `WebRunner::start`. Built ONLY when a PLM is configured; the
879/// file-based app never reaches this module.
880#[cfg(not(target_arch = "wasm32"))]
881mod native_boot {
882    use super::mirror_store::{BackendFuture, MirrorStore, StoreBackend, DIR_PREFIX, PREFIX};
883    use super::native_model::FileModelStore;
884    use super::{BrowserEntry, BrowserPlace, ModelStore, Residency};
885    use crate::plm::config::PlmConfig;
886    use crate::plm::PlmFuture;
887    use std::path::{Path, PathBuf};
888    use std::rc::Rc;
889
890    /// How long the boot waits for sign-in and the index before giving up and
891    /// starting on the file stores. The window is blank while it waits, so this
892    /// is a bound on a hung server, not an expected duration.
893    pub const BOOT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
894
895    /// Every reserved name this backend stores: exactly the user's preferences
896    /// and the machine's local keys (D1's split, `PREFERENCE_KEYS` ∪
897    /// `LOCAL_KEYS`). DERIVED, not listed: a hand-kept copy once lacked
898    /// `@plm_import`, and every PLM session refused to keep its import ledger.
899    fn reserved() -> impl Iterator<Item = &'static str> {
900        super::PREFERENCE_KEYS.iter().chain(super::LOCAL_KEYS).copied()
901    }
902
903    /// A `StoreBackend` over the native file store: the mirror's keys mapped
904    /// back to the names `FileModelStore` has always used, so `@recovery` lands
905    /// in `<root>/recovery.json` in a PLM session exactly as it does in a file
906    /// session. It is the PLM session's LOCAL key space (D1: the local-first
907    /// copy of `@recovery`), handed to the PLM client to compose.
908    ///
909    /// Every call is answered with a resolved future. Documents are written
910    /// synchronously; the reserved keys are handed to the file store's
911    /// write-behind lane, which keeps the newest value per file and lands
912    /// writes of one key in call order, so `orders_writes_per_key` holds.
913    pub struct NativeFileBackend {
914        files: FileModelStore,
915    }
916
917    impl NativeFileBackend {
918        pub fn rooted_at(root: PathBuf) -> Self {
919            Self { files: FileModelStore::rooted_at(root) }
920        }
921
922        /// The store name a mirror key stands for; `None` for an explorer
923        /// directory row, which this backend does not hold.
924        fn name_of(key: &str) -> Option<String> {
925            if let Some(name) = reserved().find(|name| MirrorStore::key(name) == key) {
926                return Some(name.to_string());
927            }
928            if key.starts_with(DIR_PREFIX) {
929                return None;
930            }
931            key.strip_prefix(PREFIX).map(str::to_string)
932        }
933    }
934
935    fn ready<T: 'static>(value: Result<T, String>) -> BackendFuture<T> {
936        Box::pin(std::future::ready(value))
937    }
938
939    impl StoreBackend for NativeFileBackend {
940        fn label(&self) -> String {
941            self.files.backend_label()
942        }
943
944        fn load_all(&self) -> BackendFuture<Vec<(String, String)>> {
945            let reserved = reserved().map(|name| name.to_string());
946            let documents = self.files.list();
947            let all = reserved
948                .chain(documents)
949                .filter_map(|name| self.files.read(&name).map(|value| (MirrorStore::key(&name), value)))
950                .collect();
951            ready(Ok(all))
952        }
953
954        fn orders_writes_per_key(&self) -> bool {
955            true
956        }
957
958        fn get(&self, key: &str) -> BackendFuture<Option<String>> {
959            ready(Ok(Self::name_of(key).and_then(|name| self.files.read(&name))))
960        }
961
962        fn put(&self, key: &str, value: &str) -> BackendFuture<()> {
963            ready(match Self::name_of(key) {
964                Some(name) => self.files.write(&name, value),
965                None => Err(format!("{key}: the local store keeps no explorer folders")),
966            })
967        }
968
969        fn delete(&self, key: &str) -> BackendFuture<()> {
970            ready(match Self::name_of(key) {
971                Some(name) => self.files.remove(&name),
972                None => Ok(()),
973            })
974        }
975    }
976
977    /// Connect to the configured PLM: sign in, check versions, and hand back
978    /// the composed backend (documents and preferences on the server, `local`
979    /// on this machine): S1's `plm::client::open_session`. A refusal is a
980    /// sentence, and the session starts on the file stores saying it.
981    fn plm_connect(config: PlmConfig, local: Rc<dyn StoreBackend>) -> PlmFuture<Rc<dyn StoreBackend>> {
982        crate::plm::client::open_session(config, local)
983    }
984
985    /// The session store for a configured PLM, hydrated before this returns.
986    /// Any failure — refused sign-in, a version the server does not serve, an
987    /// index that will not load, no answer within [`BOOT_TIMEOUT`] — starts the
988    /// session on the file stores at `root` instead, saying why on the first
989    /// frame. A PLM never makes the app fail to start.
990    pub fn boot_native_store(root: PathBuf, config: PlmConfig) -> Box<dyn ModelStore> {
991        let (url, source) = (config.url.clone(), config.url_source);
992        let booted = boot_with(&root, config, plm_connect, BOOT_TIMEOUT);
993        boot_outcome(root, url, source, booted)
994    }
995
996    /// What a boot ends in: the PLM session, or the file stores at `root`
997    /// saying why on the first frame.
998    fn boot_outcome(
999        root: PathBuf,
1000        url: String,
1001        source: crate::plm::config::Source,
1002        booted: Result<NativeMirrorStore, String>,
1003    ) -> Box<dyn ModelStore> {
1004        match booted {
1005            Ok(store) => Box::new(store),
1006            Err(reason) => {
1007                let reason = format!("PLM at {url}: {reason}");
1008                Box::new(
1009                    FileModelStore::rooted_at(root)
1010                        .with_plm_launch(url, source)
1011                        .with_notice(format!("{reason} — this session uses the file stores"))
1012                        .with_plm_reason(reason),
1013                )
1014            }
1015        }
1016    }
1017
1018    /// [`boot_native_store`] without blocking the frame (the PLM tab's
1019    /// Connect now): the sign-in and the index load run on the frame loop's
1020    /// executor, each phase bounded by [`BOOT_TIMEOUT`] as at start, and the
1021    /// frame takes the store from [`PendingBoot::poll`] once the boot ends.
1022    pub fn start_native_boot(root: PathBuf, config: PlmConfig) -> PendingBoot {
1023        start_boot_with(root, config, plm_connect, BOOT_TIMEOUT)
1024    }
1025
1026    /// A boot [`start_native_boot`] began, still on its way.
1027    pub struct PendingBoot {
1028        state: Rc<std::cell::RefCell<BootState>>,
1029        task: crate::plm::native::Abort,
1030        root: PathBuf,
1031        url: String,
1032        source: crate::plm::config::Source,
1033        timeout: std::time::Duration,
1034    }
1035
1036    struct BootState {
1037        /// When the phase now waiting (sign-in, then the index) began.
1038        phase_since: std::time::Instant,
1039        booted: Option<Result<NativeMirrorStore, String>>,
1040    }
1041
1042    impl PendingBoot {
1043        /// The store once the boot has ended, as [`boot_native_store`] would
1044        /// have returned it (a refusal or a phase past its limit gives the file
1045        /// stores saying why); `None` while it is still waiting. A phase past
1046        /// its limit drops the boot's task.
1047        pub fn poll(&mut self) -> Option<Box<dyn ModelStore>> {
1048            let finished = self.state.borrow_mut().booted.take();
1049            let booted = match finished {
1050                Some(booted) => booted,
1051                None if self.state.borrow().phase_since.elapsed() > self.timeout => {
1052                    self.task.abort();
1053                    Err(format!("no answer within {} s", self.timeout.as_secs()))
1054                }
1055                None => return None,
1056            };
1057            Some(boot_outcome(self.root.clone(), self.url.clone(), self.source, booted))
1058        }
1059    }
1060
1061    /// [`start_native_boot`] with the connector and the time limit passed in.
1062    pub(super) fn start_boot_with(
1063        root: PathBuf,
1064        config: PlmConfig,
1065        connect: impl FnOnce(PlmConfig, Rc<dyn StoreBackend>) -> PlmFuture<Rc<dyn StoreBackend>>,
1066        timeout: std::time::Duration,
1067    ) -> PendingBoot {
1068        let (url, source) = (config.url.clone(), config.url_source);
1069        let (files, local) = boot_parts(&root, &config);
1070        let state = Rc::new(std::cell::RefCell::new(BootState { phase_since: std::time::Instant::now(), booted: None }));
1071        let theirs = state.clone();
1072        let connecting = connect(config, local);
1073        let task = crate::plm::native::spawn_abortable(async move {
1074            let booted = async {
1075                let backend = connecting.await?;
1076                theirs.borrow_mut().phase_since = std::time::Instant::now();
1077                let entries = backend.load_index().await.map_err(|e| format!("the store index would not load ({e})"))?;
1078                Ok::<_, String>(mirror_of(backend, entries, files))
1079            }
1080            .await;
1081            theirs.borrow_mut().booted = Some(booted);
1082        });
1083        PendingBoot { state, task, root, url, source, timeout }
1084    }
1085
1086    /// The two stores every boot starts from: the session's real-file lane and
1087    /// the local backend the PLM connector keeps this machine's keys in.
1088    fn boot_parts(root: &Path, config: &PlmConfig) -> (FileModelStore, Rc<dyn StoreBackend>) {
1089        let files = FileModelStore::rooted_at(root.to_path_buf()).with_plm_launch(config.url.clone(), config.url_source);
1090        let local: Rc<dyn StoreBackend> = Rc::new(NativeFileBackend::rooted_at(root.to_path_buf()));
1091        (files, local)
1092    }
1093
1094    /// The PLM session store around a connected backend and its index.
1095    fn mirror_of(backend: Rc<dyn StoreBackend>, entries: Vec<(String, super::mirror_store::Entry)>, files: FileModelStore) -> NativeMirrorStore {
1096        let wake: Rc<dyn Fn()> = Rc::new(crate::plm::native::request_wake);
1097        let core = MirrorStore::from_index(backend, entries, Some(wake));
1098        NativeMirrorStore { core, files }
1099    }
1100
1101    /// `brep-app --plm-check`: the boot's own sign-in and version check, and
1102    /// nothing else — no index, no store.
1103    pub fn check_native_plm(root: PathBuf, config: PlmConfig) -> Result<(), String> {
1104        let local: Rc<dyn StoreBackend> = Rc::new(NativeFileBackend::rooted_at(root));
1105        crate::plm::native::block_on_for(plm_connect(config, local), BOOT_TIMEOUT)
1106            .ok_or_else(|| format!("no answer within {} s", BOOT_TIMEOUT.as_secs()))?
1107            .map(|_| ())
1108    }
1109
1110    /// [`boot_native_store`] with the connector and the time limit passed in,
1111    /// so a test can boot against a backend of its own.
1112    pub(super) fn boot_with(
1113        root: &Path,
1114        config: PlmConfig,
1115        connect: impl FnOnce(PlmConfig, Rc<dyn StoreBackend>) -> PlmFuture<Rc<dyn StoreBackend>>,
1116        timeout: std::time::Duration,
1117    ) -> Result<NativeMirrorStore, String> {
1118        use crate::plm::native::block_on_for;
1119        let late = || format!("no answer within {} s", timeout.as_secs());
1120        let (files, local) = boot_parts(root, &config);
1121        let backend = block_on_for(connect(config, local), timeout).ok_or_else(late)??;
1122        // The index, not the documents: a catalog of thousands of parts must
1123        // not load at boot or stream into memory behind the first frame.
1124        // Document bodies remain OnDisk until read on demand.
1125        let entries = block_on_for(backend.load_index(), timeout)
1126            .ok_or_else(late)?
1127            .map_err(|e| format!("the store index would not load ({e})"))?;
1128        Ok(mirror_of(backend, entries, files))
1129    }
1130
1131    /// The native PLM session store: the mirror (every CRUD and explorer
1132    /// method) plus this machine's real-file lane — a STEP or PDF export still
1133    /// lands in `<root>/models` and an external file is still read from disk,
1134    /// as in a file session.
1135    pub(super) struct NativeMirrorStore {
1136        pub(super) core: MirrorStore,
1137        files: FileModelStore,
1138    }
1139
1140    impl ModelStore for NativeMirrorStore {
1141        #[cfg(feature = "automation")]
1142        fn files(&self, request: &brep_mcp_core::files::Request) -> Result<brep_mcp_core::files::Reply, String> { self.files.files(request) }
1143
1144        // --- delegated to the mirror ------------------------------------------
1145        fn backend_label(&self) -> String {
1146            self.core.backend_label()
1147        }
1148        fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
1149            self.core.plm_client()
1150        }
1151        fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
1152            self.core.plm_revision(key)
1153        }
1154        fn note_checked_out(&self, key: &str) {
1155            self.core.note_checked_out(key)
1156        }
1157        fn plm_written_by_us(&self, key: &str) -> bool {
1158            self.core.plm_written_by_us(key)
1159        }
1160        fn refresh_plm_index(&self, keys: &[String], stale: bool) {
1161            self.core.refresh_plm_index(keys, stale)
1162        }
1163        fn remember_saved_document(&self, name: &str, contents: &str) {
1164            self.core.remember_saved_document(name, contents)
1165        }
1166        fn list(&self) -> Vec<String> {
1167            self.core.list()
1168        }
1169        fn read(&self, name: &str) -> Option<String> {
1170            self.core.read(name)
1171        }
1172        fn residency(&self, name: &str) -> Residency {
1173            self.core.residency(name)
1174        }
1175        fn canonical_identity(&self, name: &str) -> String {
1176            self.core.canonical_identity(name)
1177        }
1178        fn canonicalizer(&self) -> super::Canonicalizer {
1179            self.core.canonicalizer()
1180        }
1181        fn write(&self, name: &str, contents: &str) -> Result<(), String> {
1182            self.core.write(name, contents)
1183        }
1184        fn remove(&self, name: &str) -> Result<(), String> {
1185            self.core.remove(name)
1186        }
1187        fn mutation_generation(&self) -> u64 {
1188            self.core.mutation_generation()
1189        }
1190        // The native queue these failures come from is run by the frame loop
1191        // itself (`BrepApp::ui`'s first line), not here: a store call behind an
1192        // early return would stall it.
1193        fn take_persistence_errors(&self) -> Vec<String> {
1194            let mut errors = self.core.take_persistence_errors();
1195            // This machine's local files (`@recovery`, `@plm_import`, ...)
1196            // are written behind by the file lane; their failures land here.
1197            errors.extend(super::native_model::write_behind::take_errors(self.files.root()));
1198            errors
1199        }
1200        fn take_failed_writes(&self) -> Vec<String> {
1201            self.core.take_failed_writes()
1202        }
1203        fn write_failed(&self, name: &str) -> bool {
1204            self.core.write_failed(name)
1205        }
1206        fn failed_write_base(&self, name: &str) -> Option<String> {
1207            self.core.failed_write_base(name)
1208        }
1209        fn write_if(&self, name: &str, contents: &str, expected: &str) -> Result<(), String> {
1210            self.core.write_if(name, contents, expected)
1211        }
1212        fn plm_session(&self) -> Option<crate::plm::connection::Session> {
1213            use crate::plm::connection::{parse_label, Keep, Session, Status};
1214            let (url, username) = parse_label(&self.core.backend_label())?;
1215            Some(Session { status: Status::Connected { url, username }, keep: Keep::Files(self.files.root().to_path_buf()) })
1216        }
1217        // The URL lives in the local file lane: `files` was told this
1218        // launch's URL and where it came from.
1219        fn plm_url_setting(&self) -> Option<crate::plm::connection::UrlSetting> {
1220            self.files.plm_url_setting()
1221        }
1222        fn save_plm_url(&self, url: &str) -> Result<crate::plm::connection::UrlSaved, String> {
1223            self.files.save_plm_url(url)
1224        }
1225        fn pending_writes(&self) -> usize {
1226            // The server's writes, plus the local files still being written
1227            // behind (the close path must wait for `@recovery` too).
1228            self.core.pending_writes() + super::native_model::write_behind::count(self.files.root())
1229        }
1230        fn pending_saves(&self) -> usize {
1231            self.core.pending_writes()
1232        }
1233        fn pending_writes_except(&self, names: &[&str]) -> usize {
1234            self.core.pending_writes_except(names)
1235        }
1236        fn browser_location(&self) -> String {
1237            self.core.browser_location()
1238        }
1239        fn browser_entries(&self, extensions: &[&str]) -> Vec<BrowserEntry> {
1240            self.core.browser_entries(extensions)
1241        }
1242        fn browser_enter(&self, identity: &str) -> Result<(), String> {
1243            self.core.browser_enter(identity)
1244        }
1245        fn browser_up(&self) -> Result<(), String> {
1246            self.core.browser_up()
1247        }
1248        fn browser_home(&self) -> Result<(), String> {
1249            self.core.browser_home()
1250        }
1251        fn browser_root(&self) -> Result<(), String> {
1252            self.core.browser_root()
1253        }
1254        fn browser_navigate(&self, location: &str) -> Result<(), String> {
1255            self.core.browser_navigate(location)
1256        }
1257        fn browser_places(&self) -> Vec<BrowserPlace> {
1258            self.core.browser_places()
1259        }
1260        fn browser_create_dir(&self, name: &str) -> Result<(), String> {
1261            self.core.browser_create_dir(name)
1262        }
1263        fn browser_write(&self, name: &str, contents: &str) -> Result<String, String> {
1264            self.core.browser_write(name, contents)
1265        }
1266        // The Save-file chooser browses the LOCAL files (`local_files`), so a
1267        // write at its location is the file store's; delegated like its
1268        // export siblings below rather than to the PLM's document mirror.
1269        fn browser_write_bytes(&self, file_name: &str, contents: &[u8]) -> Result<String, String> {
1270            self.files.browser_write_bytes(file_name, contents)
1271        }
1272
1273        // --- this machine's real files ----------------------------------------
1274        fn local_files(&self) -> Option<&dyn ModelStore> {
1275            Some(&self.files)
1276        }
1277        fn list_external_files(&self, extensions: &[&str]) -> Vec<String> {
1278            self.files.list_external_files(extensions)
1279        }
1280        fn read_external_file(&self, name: &str) -> Option<Vec<u8>> {
1281            self.files.read_external_file(name)
1282        }
1283        fn export_file_named(&self, file_name: &str, contents: &str) -> Result<(), String> {
1284            self.files.export_file_named(file_name, contents)
1285        }
1286        fn export_file_named_bytes(&self, file_name: &str, contents: &[u8]) -> Result<(), String> {
1287            self.files.export_file_named_bytes(file_name, contents)
1288        }
1289    }
1290
1291}
1292
1293
1294
1295
1296
1297
1298// --- Document identity -----------------------------------------------------------
1299//
1300// A document's IDENTITY is the raw string the app keys it by: the name handed
1301// to `read` / `write`, kept on the open tab, and copied into everything that
1302// has to find the document again. On the file backends it is a path (native),
1303// a `/models/...` path (browser) or a bare name (the models folder). On a PLM
1304// store it is `part/<part id>/rev/<revision id>` — always a concrete revision,
1305// since the CAD app has no floating occurrences (D3).
1306//
1307// Every place the app keys a document by identity (plm-cad-integration-todo
1308// S0, enumerated 2026-09-25 by grep, not recalled):
1309//
1310// MINTED (a new identity comes into being):
1311//  1. `BrowserEntry.identity` — `browser_entries` rows; `browser_write`'s
1312//     return value (Save As, the STEP-to-part lane `panels/step_parts.rs`).
1313//  2. `Document::name` (`document.rs`) — the open tab's identity, set by Open
1314//     / Save / Save As (`panels/file.rs` `save_to`, `save_as`, the open path)
1315//     and by recovery. The ROOT: items 3 and 5 are copies of it.
1316//  3. The recovery blob's per-entry `name` (`recovery.rs` `RecoveryEntry`),
1317//     copied from `Document::name`, read back by `already_saved` and restored
1318//     onto the tab.
1319//  4. `sibling_identity` — a document beside another: a family's members
1320//     (`family_table.rs` `member_identity`, `generate_family`'s
1321//     `file_name_of`) and a spun-out part (`panels/file.rs`
1322//     `spin_out_target`). There are no folders on a PLM store: S7 / S9
1323//     replace these with a new part.
1324//  5. The ACOMP occurrence chain's `sourceKey` — `partsLibrary.<part>.sourceKey`
1325//     in an assembly document, written at insert (`panels/file.rs`
1326//     `insert_component_document`, `panels/step_parts.rs`) from the part's
1327//     identity; RESOLVED by `store.read(sourceKey)` in
1328//     `panels/update_components.rs`, `panels/parts_library.rs`
1329//     (`write_through`), `panels/component_actions.rs` (`part_source_key`,
1330//     Edit Part), `panels/bom.rs`, `panels/ecad_parts.rs` (open requests) and
1331//     `app.rs`. S13 rewrites file-path sourceKeys to revision keys.
1332//
1333// DERIVED (read off an identity's shape):
1334//  6. `model_display_name` (tab title, name field, duplicate-open check in
1335//     `panels/file.rs` `name_is_free`), `file_name_of`, and
1336//     `DocumentClass::of_name` (a document's class from its EXTENSION) — a
1337//     revision key has neither a file name nor an extension; on a PLM store
1338//     the class comes from the index (P3 / S7).
1339//
1340// NOT identities, though the plan's first draft listed them:
1341//  * `@pinned` holds explorer FOLDER locations, never documents — in PLM mode
1342//    it pins workspace folders (S14) and stays a Preferences key.
1343// `@recent_documents` holds document identities in most-recent-first order;
1344// it is a user preference and opens through the same file-dialog door.
1345//
1346// The seam: `ModelStore::identity`, `ModelStore::display_name` and
1347// `ModelStore::sibling_of`, whose defaults are exactly the path rules below,
1348// so a file backend is unchanged and a PLM backend supplies its own.
1349
1350/// [`ModelStore::canonicalizer`]'s answer.
1351pub type Canonicalizer = std::rc::Rc<dyn Fn(&str) -> String>;
1352
1353/// A document identity read for its shape — see the enumeration above.
1354#[derive(Clone, Debug, PartialEq, Eq)]
1355pub enum DocumentIdentity {
1356    /// A native path, a browser `/models/...` path, or a bare name.
1357    Path(String),
1358    /// A PLM document key, `part/<part id>/rev/<revision id>`.
1359    Revision { part: String, revision: String },
1360}
1361
1362impl DocumentIdentity {
1363    /// Read `key` as a PLM revision key — `part/<id>/rev/<id>`, both halves
1364    /// non-empty and slash-free, the same split the server's store routes make.
1365    ///
1366    /// Only a PLM-backed store may call this on its identities: the SHAPE is
1367    /// not proof, since a browser document at `models/part/7/rev/3.nbrep`
1368    /// lists as `part/7/rev/3`. That is why the file backends never parse.
1369    pub fn parse_revision_key(key: &str) -> Option<Self> {
1370        match key.split('/').collect::<Vec<_>>().as_slice() {
1371            ["part", part, "rev", revision] if !part.is_empty() && !revision.is_empty() => {
1372                Some(DocumentIdentity::Revision {
1373                    part: crate::plm::identity::unsegment(part)?,
1374                    revision: crate::plm::identity::unsegment(revision)?,
1375                })
1376            }
1377            _ => None,
1378        }
1379    }
1380
1381    /// The raw string this identity is keyed by.
1382    pub fn key(&self) -> String {
1383        match self {
1384            DocumentIdentity::Path(path) => path.clone(),
1385            DocumentIdentity::Revision { part, revision } => crate::plm::identity::document_key(part, revision),
1386        }
1387    }
1388}
1389
1390/// The identity of the file `file_name` in the same folder as the document
1391/// `identity`: a native path, a browser `/models/...` path, or — for a
1392/// document known only by a bare name — the bare `file_name`, which both
1393/// stores resolve into their models folder.
1394pub fn sibling_identity(identity: &str, file_name: &str) -> String {
1395    match identity.rfind(['/', '\\']) {
1396        Some(cut) => format!("{}{file_name}", &identity[..=cut]),
1397        None => file_name.to_string(),
1398    }
1399}
1400
1401/// The last path component of a document identity (`/a/b/bolt.fbrep` ->
1402/// `bolt.fbrep`), extension kept.
1403pub fn file_name_of(identity: &str) -> String {
1404    identity.rsplit(['/', '\\']).next().unwrap_or(identity).to_string()
1405}
1406
1407/// Strip the model extension (and any directory) from a filename to get the
1408/// bare display name — shared by both platform impls (and the file panel, which
1409/// shows the bare name while keeping the raw identity for re-saves).
1410pub(crate) fn model_display_name(file_name: &str) -> String {
1411    let base = file_name
1412        .rsplit(['/', '\\'])
1413        .next()
1414        .unwrap_or(file_name);
1415    // Only the NORMAL extension is implied: a family or template keeps its
1416    // extension in its name, which is what carries its class.
1417    match crate::document_class::DocumentClass::of_name(base) {
1418        Some(crate::document_class::DocumentClass::Normal) => {
1419            crate::document_class::strip_class_extension(base).to_string()
1420        }
1421        _ => base.to_string(),
1422    }
1423}
1424
1425// --- Desktop: application models/files directory -------------------------------
1426#[cfg(not(target_arch = "wasm32"))]
1427mod native_model {
1428    use super::{
1429        model_display_name, BrowserEntry, BrowserPlace, ModelStore, PlaceKind, Residency, DOCK_LAYOUT_KEY,
1430        FEATURE_PALETTE_DISPLAY_KEY, KICAD_LIBRARY_KEY, PINNED_KEY, PLM_IMPORT_KEY, RECOVERY_KEY,
1431        SETTINGS_KEY,
1432    };
1433    use std::cell::{Cell, RefCell};
1434    use std::path::{Path, PathBuf};
1435
1436    /// Persist models as `<config>/brep-app/models/<name>.nbrep` and reserved
1437    /// application state as files under `<config>/brep-app`. Enumerable (for the
1438    /// Open list) and unit-testable without a display.
1439    ///
1440    /// Open, Save As, import, and export are all driven by the application's
1441    /// common egui explorer; no OS-native dialog is involved.
1442    /// The PLM a config root names (D5's files only: what this machine keeps),
1443    /// as "not connected, reason unknown". A file that cannot be read is
1444    /// reported the same way, with the reason.
1445    fn configured_plm(root: &std::path::Path) -> Option<crate::plm::connection::Session> {
1446        use crate::plm::connection::{Keep, Session, Status};
1447        let status = match crate::plm::config::resolve(root, &|_| None, &Default::default()) {
1448            Ok(None) => return None,
1449            Ok(Some(config)) => Status::NotConnected { url: config.url, reason: None },
1450            Err(e) if root.join("plm.json").exists() => Status::NotConnected { url: String::new(), reason: Some(e) },
1451            Err(_) => return None,
1452        };
1453        Some(Session { status, keep: Keep::Files(root.to_path_buf()) })
1454    }
1455
1456    /// The write-behind lane for the reserved application files (settings,
1457    /// dock layout, recovery blob, recents, ...): `FileModelStore::write`
1458    /// hands the bytes here and returns, and a writer thread per directory
1459    /// (started on demand, gone once that directory is drained) does the
1460    /// atomic write and its fsync. On a disk shared with builds one fsync has
1461    /// measured seconds, and a settings slider writes on every frame of its
1462    /// drag, so this work does not belong in the frame.
1463    ///
1464    /// Process-wide and keyed by the resolved PATH, not per store: a PLM
1465    /// session holds two `FileModelStore`s over the same root (its file lane
1466    /// and the local backend), and each must see the other's pending writes.
1467    ///
1468    /// * Latest value wins per path: a write over a pending one replaces it,
1469    ///   so a burst lands as at most two disk writes (the one in flight, then
1470    ///   the newest). Writes of one path therefore still land in call order.
1471    /// * An entry stays readable until its write LANDS: the writer copies it
1472    ///   out with its sequence number and removes it afterwards only if no
1473    ///   newer value arrived meanwhile. A read never falls through to the old
1474    ///   file while the new one is being written.
1475    /// * The lock is never held across file I/O.
1476    /// * A failed write is reported through
1477    ///   [`ModelStore::take_persistence_errors`]; the entry is dropped, so
1478    ///   reads go back to what is on disk.
1479    pub(crate) mod write_behind {
1480        use std::collections::HashMap;
1481        use std::path::{Path, PathBuf};
1482        use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
1483        use std::time::{Duration, Instant};
1484
1485        #[derive(Clone)]
1486        enum Op {
1487            Put(Arc<str>),
1488            Remove,
1489        }
1490
1491        struct Entry {
1492            op: Op,
1493            seq: u64,
1494            /// Copied out by the writer and being written now.
1495            taken: bool,
1496        }
1497
1498        #[derive(Default)]
1499        struct State {
1500            pending: HashMap<PathBuf, Entry>,
1501            next_seq: u64,
1502            /// Failed writes with the file each was for: a store drains only
1503            /// the failures under its own root.
1504            errors: Vec<(PathBuf, String)>,
1505            /// Directories with a writer thread running. Each directory has
1506            /// its own writer, so one app's fsyncs never queue behind another
1507            /// store's (a test binary or an MCP host runs many apps in one
1508            /// process); a file always maps to the same directory, so the
1509            /// writes to it keep their order. A writer exits once its
1510            /// directory has nothing left.
1511            writers: std::collections::HashSet<PathBuf>,
1512            /// The last text read from each reserved file, with the size and
1513            /// modification time it had: a frame that reads `@recent_documents`
1514            /// or `@pinned` pays one stat, not an open and a read. Dropped for
1515            /// a path when the lane writes it.
1516            read_cache: HashMap<PathBuf, (u64, std::time::SystemTime, String)>,
1517        }
1518
1519        struct Lane {
1520            state: Mutex<State>,
1521            /// Signalled on new work and on every landed write.
1522            changed: Condvar,
1523        }
1524
1525        fn lane() -> &'static Lane {
1526            static LANE: OnceLock<Lane> = OnceLock::new();
1527            LANE.get_or_init(|| Lane { state: Mutex::new(State::default()), changed: Condvar::new() })
1528        }
1529
1530        fn lock() -> MutexGuard<'static, State> {
1531            lane().state.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
1532        }
1533
1534        fn enqueue(path: PathBuf, op: Op) {
1535            let mut state = lock();
1536            state.next_seq += 1;
1537            let seq = state.next_seq;
1538            let dir = directory(&path);
1539            state.pending.insert(path, Entry { op, seq, taken: false });
1540            if !state.writers.contains(&dir) {
1541                let for_writer = dir.clone();
1542                let spawned =
1543                    std::thread::Builder::new().name("brep-store-writer".into()).spawn(move || writer(for_writer));
1544                match spawned {
1545                    Ok(_) => {
1546                        state.writers.insert(dir);
1547                    }
1548                    Err(e) => {
1549                        // No thread: write here, as the store always did.
1550                        drop(state);
1551                        log::warn!("store writer thread did not start ({e}); writing on the caller");
1552                        while write_one(&dir) {}
1553                        return;
1554                    }
1555                }
1556            }
1557            drop(state);
1558            lane().changed.notify_all();
1559        }
1560
1561        /// Queue `contents` for `path`.
1562        pub(crate) fn put(path: PathBuf, contents: &str) {
1563            enqueue(path, Op::Put(Arc::from(contents)));
1564        }
1565
1566        /// Queue the removal of `path` (a missing file is not an error).
1567        pub(crate) fn remove(path: PathBuf) {
1568            enqueue(path, Op::Remove);
1569        }
1570
1571        /// What a pending write says `path` holds: `Some(Some(text))` for a
1572        /// pending write, `Some(None)` for a pending removal, `None` when
1573        /// nothing is pending and the disk is the answer.
1574        pub(crate) fn pending(path: &Path) -> Option<Option<String>> {
1575            lock().pending.get(path).map(|entry| match &entry.op {
1576                Op::Put(text) => Some(text.to_string()),
1577                Op::Remove => None,
1578            })
1579        }
1580
1581        /// What `path` holds: a pending write's value, else the file (served
1582        /// from the read cache while its size and modification time match).
1583        pub(crate) fn read(path: &Path) -> Option<String> {
1584            if let Some(pending) = pending(path) {
1585                return pending;
1586            }
1587            let Ok(meta) = std::fs::metadata(path) else {
1588                lock().read_cache.remove(path);
1589                return None;
1590            };
1591            let stamp = meta.modified().ok().map(|modified| (meta.len(), modified));
1592            if let Some((len, modified)) = stamp {
1593                if let Some((cached_len, cached_modified, text)) = lock().read_cache.get(path) {
1594                    if *cached_len == len && *cached_modified == modified {
1595                        return Some(text.clone());
1596                    }
1597                }
1598            }
1599            let text = std::fs::read_to_string(path).ok()?;
1600            if let Some((len, modified)) = stamp {
1601                let mut state = lock();
1602                // A write queued meanwhile is newer than what was just read.
1603                if !state.pending.contains_key(path) {
1604                    state.read_cache.insert(path.to_path_buf(), (len, modified, text.clone()));
1605                }
1606            }
1607            Some(text)
1608        }
1609
1610        /// Whether `path` has a pending write (not a removal).
1611        pub(crate) fn pending_put(path: &Path) -> Option<bool> {
1612            lock().pending.get(path).map(|entry| matches!(entry.op, Op::Put(_)))
1613        }
1614
1615        /// Writes still pending for files under `root`: a store counts its
1616        /// own, never another store's (the lane is process-wide).
1617        pub(crate) fn count(root: &Path) -> usize {
1618            lock().pending.keys().filter(|path| path.starts_with(root)).count()
1619        }
1620
1621        /// Failed writes under `root` since the last drain, oldest first.
1622        pub(crate) fn take_errors(root: &Path) -> Vec<String> {
1623            let mut state = lock();
1624            let (mine, others) = std::mem::take(&mut state.errors).into_iter().partition(|(path, _)| path.starts_with(root));
1625            state.errors = others;
1626            mine.into_iter().map(|(_, error)| error).collect()
1627        }
1628
1629        /// Block until every write queued before this call has landed (or
1630        /// was replaced by a newer one) or `limit` passed; `true` when they
1631        /// have. Writes queued meanwhile are not waited for, so a test binary's
1632        /// other tests writing all along cannot starve it. For process exit
1633        /// and tests — never the frame.
1634        pub(crate) fn flush(limit: Duration) -> bool {
1635            let deadline = Instant::now() + limit;
1636            let mut state = lock();
1637            let upto = state.next_seq;
1638            while state.pending.values().any(|entry| entry.seq <= upto) {
1639                let now = Instant::now();
1640                if now >= deadline {
1641                    // Exit and tests only: name what did not land, and
1642                    // whether its write is in flight (a stalled fsync) or
1643                    // still queued.
1644                    for (path, entry) in state.pending.iter().filter(|(_, entry)| entry.seq <= upto) {
1645                        let at = if entry.taken { "being written" } else { "queued" };
1646                        eprintln!("write-behind: {} not landed after {limit:?} ({at})", path.display());
1647                    }
1648                    return false;
1649                }
1650                state = match lane().changed.wait_timeout(state, deadline - now) {
1651                    Ok((state, _)) => state,
1652                    Err(poisoned) => poisoned.into_inner().0,
1653                };
1654            }
1655            true
1656        }
1657
1658        /// The directory whose writer lands `path`.
1659        fn directory(path: &Path) -> PathBuf {
1660            path.parent().map(Path::to_path_buf).unwrap_or_default()
1661        }
1662
1663        /// Land `dir`'s writes, oldest first, then exit. The exit is decided
1664        /// under the lock an enqueue takes, so a write queued for `dir` either
1665        /// is seen here or starts a new writer.
1666        fn writer(dir: PathBuf) {
1667            loop {
1668                if !write_one(&dir) {
1669                    let mut state = lock();
1670                    let more = state.pending.iter().any(|(path, entry)| !entry.taken && directory(path) == dir);
1671                    if !more {
1672                        state.writers.remove(&dir);
1673                        return;
1674                    }
1675                }
1676            }
1677        }
1678
1679        /// Write `dir`'s oldest untaken entry; `false` when there was none.
1680        fn write_one(dir: &Path) -> bool {
1681            let job = {
1682                let mut state = lock();
1683                let Some((path, entry)) = state
1684                    .pending
1685                    .iter_mut()
1686                    .filter(|(path, entry)| !entry.taken && directory(path) == dir)
1687                    .min_by_key(|(_, entry)| entry.seq)
1688                else {
1689                    return false;
1690                };
1691                entry.taken = true;
1692                (path.clone(), entry.op.clone(), entry.seq)
1693            };
1694            let (path, op, seq) = job;
1695            let result = match &op {
1696                Op::Put(text) => {
1697                    let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty());
1698                    parent
1699                        .map_or(Ok(()), std::fs::create_dir_all)
1700                        .and_then(|()| super::super::write_atomic(&path, text.as_bytes(), false))
1701                        .map_err(|e| format!("write {}: {e}", path.display()))
1702                }
1703                Op::Remove => match std::fs::remove_file(&path) {
1704                    Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
1705                        Err(format!("remove {}: {e}", path.display()))
1706                    }
1707                    _ => Ok(()),
1708                },
1709            };
1710            {
1711                let mut state = lock();
1712                if state.pending.get(&path).is_some_and(|entry| entry.seq == seq) {
1713                    state.pending.remove(&path);
1714                }
1715                state.read_cache.remove(&path);
1716                if let Err(error) = result {
1717                    log::warn!("{error}");
1718                    state.errors.push((path.clone(), error));
1719                }
1720            }
1721            lane().changed.notify_all();
1722            // The frame loop shows a "Saving" activity while writes are
1723            // pending; ask for the frame that clears it.
1724            crate::plm::native::request_wake();
1725            true
1726        }
1727    }
1728
1729    pub struct FileModelStore {
1730        app_dir: PathBuf,
1731        dir: PathBuf,
1732        browser_dir: RefCell<PathBuf>,
1733        /// See [`ModelStore::mutation_generation`]. A plain `Cell` — this store
1734        /// is built once and held behind one `Box`, never cloned.
1735        mutations: Cell<u64>,
1736        /// Said once, on the first frame: why a session that asked for a PLM is
1737        /// on the file stores instead. Empty in every file-only session.
1738        notices: RefCell<Vec<String>>,
1739        /// The PLM configured in `app_dir` (read once, when the store is
1740        /// built) and why this session is not on it: the PLM tab's status.
1741        plm: RefCell<Option<crate::plm::connection::Session>>,
1742        /// Where `plm`'s URL came from: `plm.json`, unless the launch named
1743        /// it by switch or variable ([`Self::with_plm_launch`]).
1744        plm_source: Cell<crate::plm::config::Source>,
1745        /// The explorer's last listing (see [`Listing`]).
1746        listing: RefCell<Option<Listing>>,
1747        /// The models folder's document names [`ModelStore::list`] last read.
1748        names: RefCell<Option<Names>>,
1749    }
1750
1751    /// The document names `list` read, and what they were taken under. The
1752    /// File state blob asks for them on every frame; without this each frame
1753    /// did a `read_dir`. A name list changes only when a file is created,
1754    /// deleted or renamed, which moves the folder's own modification time,
1755    /// so it is reused while that time and this store's mutation generation
1756    /// match, never when taken within [`RACY_WINDOW`] of that time, and for at
1757    /// most [`LISTING_TTL`].
1758    struct Names {
1759        dir_modified: Option<std::time::SystemTime>,
1760        generation: u64,
1761        taken: std::time::Instant,
1762        racy: bool,
1763        names: Vec<String>,
1764    }
1765
1766    /// One directory listing the explorer drew, and what it was taken under.
1767    /// The explorer asks for its folder on every frame it is open; without
1768    /// this each frame did a `read_dir` and three stats per entry. Reused
1769    /// while the folder, the extensions, the folder's own modification time
1770    /// (a file created, deleted or renamed in it) and this store's mutation
1771    /// generation all match, and for at most [`LISTING_TTL`] — a file
1772    /// rewritten in place by another program changes no folder time, so its
1773    /// size and date are re-read within that.
1774    struct Listing {
1775        dir: PathBuf,
1776        extensions: Vec<String>,
1777        dir_modified: Option<std::time::SystemTime>,
1778        generation: u64,
1779        taken: std::time::Instant,
1780        /// Taken within [`RACY_WINDOW`] of the folder's modification time (or
1781        /// with none known): a change in the same clock tick would leave that
1782        /// time unmoved, so the listing is never reused (git's racy-clean rule).
1783        racy: bool,
1784        entries: Vec<BrowserEntry>,
1785    }
1786
1787    const LISTING_TTL: std::time::Duration = std::time::Duration::from_secs(1);
1788    /// File times come from a coarse clock (a few ms on Linux).
1789    const RACY_WINDOW: std::time::Duration = std::time::Duration::from_millis(100);
1790
1791    impl FileModelStore {
1792        pub fn new() -> Self {
1793            // The one config-directory rule, shared with the PLM's two files.
1794            let app_dir = crate::plm::config::app_config_dir();
1795            let plm = configured_plm(&app_dir);
1796            Self {
1797                dir: app_dir.join("models"),
1798                browser_dir: RefCell::new(app_dir.join("models")),
1799                app_dir,
1800                mutations: Cell::new(0),
1801                notices: RefCell::new(Vec::new()),
1802                plm: RefCell::new(plm),
1803                plm_source: Cell::new(crate::plm::config::Source::File),
1804                listing: RefCell::new(None),
1805                names: RefCell::new(None),
1806            }
1807        }
1808
1809        /// A store rooted at an explicit directory — used by the round-trip test.
1810        /// The tests stay headless and exercise the same egui explorer path.
1811        ///
1812        /// COLLAPSES the two directories [`Self::new`] keeps apart: models and
1813        /// reserved state land together. That is what a unit test wants and
1814        /// what a session must not have — see [`Self::rooted_at`].
1815        #[cfg_attr(not(test), allow(dead_code))]
1816        pub fn with_dir(dir: PathBuf) -> Self {
1817            Self {
1818                app_dir: dir.clone(),
1819                browser_dir: RefCell::new(dir.clone()),
1820                dir,
1821                mutations: Cell::new(0),
1822                notices: RefCell::new(Vec::new()),
1823                plm: RefCell::new(None),
1824                plm_source: Cell::new(crate::plm::config::Source::File),
1825                listing: RefCell::new(None),
1826                names: RefCell::new(None),
1827            }
1828        }
1829
1830        /// A store rooted at `root` with the SAME split [`Self::new`] makes
1831        /// under the user's config directory: models in `<root>/models`,
1832        /// reserved application state in `<root>`. The models directory is
1833        /// created now, so the explorer opens on a real location rather than on
1834        /// a path that does not exist yet.
1835        pub fn rooted_at(root: PathBuf) -> Self {
1836            let models = root.join("models");
1837            let _ = std::fs::create_dir_all(&models);
1838            let plm = configured_plm(&root);
1839            Self {
1840                app_dir: root,
1841                browser_dir: RefCell::new(models.clone()),
1842                dir: models,
1843                mutations: Cell::new(0),
1844                notices: RefCell::new(Vec::new()),
1845                plm: RefCell::new(plm),
1846                plm_source: Cell::new(crate::plm::config::Source::File),
1847                listing: RefCell::new(None),
1848                names: RefCell::new(None),
1849            }
1850        }
1851
1852        /// Queue `notice` for the first frame's notice drain (see
1853        /// [`ModelStore::take_persistence_errors`]).
1854        pub fn with_notice(self, notice: String) -> Self {
1855            self.notices.borrow_mut().push(notice);
1856            self
1857        }
1858
1859        /// The PLM this launch resolved — `url` from `source`, which may be
1860        /// `--plm-url` or `BREP_PLM_URL` rather than this root's `plm.json` —
1861        /// as the session the PLM tab shows (not connected, reason unknown).
1862        pub fn with_plm_launch(self, url: String, source: crate::plm::config::Source) -> Self {
1863            use crate::plm::connection::{Keep, Session, Status};
1864            *self.plm.borrow_mut() = Some(Session { status: Status::NotConnected { url, reason: None }, keep: Keep::Files(self.app_dir.clone()) });
1865            self.plm_source.set(source);
1866            self
1867        }
1868
1869        /// Keep why this session is not on its configured PLM, for the PLM
1870        /// tab (the notice above is drained on the first frame).
1871        pub fn with_plm_reason(self, reason: String) -> Self {
1872            if let Some(session) = self.plm.borrow_mut().as_mut() {
1873                if let crate::plm::connection::Status::NotConnected { url, reason: kept } = &mut session.status {
1874                    // The boot's sentence names the server first; the tab
1875                    // already does.
1876                    let own = format!("PLM at {url}: ");
1877                    *kept = Some(reason.strip_prefix(&own).map(str::to_string).unwrap_or(reason));
1878                }
1879            }
1880            self
1881        }
1882
1883        /// The root D5's files live in.
1884        pub(crate) fn root(&self) -> &std::path::Path {
1885            &self.app_dir
1886        }
1887
1888        /// Record that a write or a delete LANDED (see
1889        /// [`ModelStore::mutation_generation`]).
1890        fn bump(&self) {
1891            self.mutations.set(self.mutations.get().wrapping_add(1));
1892        }
1893
1894        /// Resolve a name to a path. Explicit paths remain supported for existing
1895        /// callers; a bare name maps to `<dir>/<sanitized>.nbrep`.
1896        fn resolve(&self, name: &str) -> PathBuf {
1897            Self::resolve_in(&self.app_dir, &self.dir, name)
1898        }
1899
1900        fn resolve_in(app_dir: &Path, dir: &Path, name: &str) -> PathBuf {
1901            if let Some(path) = Self::reserved_path(app_dir, name) {
1902                return path;
1903            }
1904            Self::document_path(dir, name)
1905        }
1906
1907        /// The file a RESERVED application name (`@settings`, `@dock_layout`,
1908        /// `@recovery`, ...) lives in, or `None` for a document name. These
1909        /// are the writes that go through the write-behind lane
1910        /// ([`write_behind`]): the UI's own state, never a user's Save.
1911        fn reserved_path(app_dir: &Path, name: &str) -> Option<PathBuf> {
1912            let file = match name {
1913                SETTINGS_KEY => "settings.json",
1914                FEATURE_PALETTE_DISPLAY_KEY => "feature_palette_display.json",
1915                DOCK_LAYOUT_KEY => "dock_layout.json",
1916                PINNED_KEY => "pinned.json",
1917                RECOVERY_KEY => "recovery.json",
1918                KICAD_LIBRARY_KEY => "kicad_library.json",
1919                crate::panels::cam_library::CAM_TOOL_LIBRARY_KEY => "cam_tools.json",
1920                super::RECENT_DOCUMENTS_KEY => "recent_documents.json",
1921                super::RECENT_THUMBNAILS_KEY => "recent_thumbnails.json",
1922                PLM_IMPORT_KEY => "plm_import.json",
1923                super::PLUGINS_KEY => "plugins.json",
1924                super::JAVASCRIPT_DRAFT_KEY => "javascript_draft.js",
1925                _ => return None,
1926            };
1927            Some(app_dir.join(file))
1928        }
1929
1930        fn document_path(dir: &Path, name: &str) -> PathBuf {
1931            if name.contains('/') || name.contains('\\') {
1932                return PathBuf::from(name);
1933            }
1934            let class = crate::document_class::DocumentClass::of_name(name).unwrap_or_default();
1935            let safe: String = crate::document_class::strip_class_extension(name)
1936                .chars()
1937                .map(|c| {
1938                    if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
1939                        c
1940                    } else {
1941                        '_'
1942                    }
1943                })
1944                .collect();
1945            dir.join(class.file_name(&safe))
1946        }
1947
1948        fn home_dir() -> PathBuf {
1949            std::env::var_os("HOME")
1950                .map(PathBuf::from)
1951                .or_else(|| std::env::current_dir().ok())
1952                .unwrap_or_else(|| PathBuf::from("."))
1953        }
1954
1955        fn matches_extension(path: &Path, extensions: &[&str]) -> bool {
1956            extensions.is_empty()
1957                || extensions.iter().any(|extension| {
1958                    let wanted = extension.trim_start_matches('.').to_ascii_lowercase();
1959                    let name = path
1960                        .file_name()
1961                        .unwrap_or_default()
1962                        .to_string_lossy()
1963                        .to_ascii_lowercase();
1964                    name.ends_with(&format!(".{wanted}"))
1965                })
1966        }
1967    }
1968
1969    impl ModelStore for FileModelStore {
1970        #[cfg(feature = "automation")]
1971        fn files(&self, request: &brep_mcp_core::files::Request) -> Result<brep_mcp_core::files::Reply, String> {
1972            std::fs::create_dir_all(&self.dir).map_err(|e| e.to_string())?;
1973            let backend = brep_mcp_core::files::native::NativeFiles::new([
1974                ("documents".into(), self.dir.clone()), ("workspace".into(), self.dir.clone()),
1975            ])?;
1976            let reply = brep_mcp_core::files::execute(&backend, request)?;
1977            if !request.operation.annotations().read_only { self.mutations.set(self.mutations.get().wrapping_add(1)); }
1978            Ok(reply)
1979        }
1980
1981        fn backend_label(&self) -> String {
1982            format!("filesystem: {}", self.dir.display())
1983        }
1984
1985        fn local_files(&self) -> Option<&dyn ModelStore> {
1986            Some(self)
1987        }
1988
1989        // Documents are written synchronously, so a Save's failure is its
1990        // `Err`. The reserved application files go through the write-behind
1991        // lane, whose failures arrive here after `write` returned; so does the
1992        // boot notice.
1993        fn take_persistence_errors(&self) -> Vec<String> {
1994            let mut errors = std::mem::take(&mut *self.notices.borrow_mut());
1995            errors.extend(write_behind::take_errors(&self.app_dir));
1996            errors
1997        }
1998
1999        /// The reserved application files under this store's root still being
2000        /// written (the close path waits on this before quitting).
2001        fn pending_writes(&self) -> usize {
2002            write_behind::count(&self.app_dir)
2003        }
2004
2005        /// Only the application's own files are written behind here.
2006        fn pending_saves(&self) -> usize {
2007            0
2008        }
2009
2010        /// Settle never waits on a state file's fsync: documents are
2011        /// written before `write` returns, and the state files are read
2012        /// through the lane, pending values first.
2013        fn pending_writes_except(&self, _names: &[&str]) -> usize {
2014            0
2015        }
2016
2017        fn plm_session(&self) -> Option<crate::plm::connection::Session> {
2018            self.plm.borrow().clone()
2019        }
2020
2021        fn plm_url_setting(&self) -> Option<crate::plm::connection::UrlSetting> {
2022            use crate::plm::connection::{Status, UrlSetting};
2023            let plm = self.plm.borrow();
2024            let url = plm.as_ref().map(|session| match &session.status {
2025                Status::Connected { url, .. } | Status::NotConnected { url, .. } => url.clone(),
2026            });
2027            Some(UrlSetting {
2028                dir: self.app_dir.clone(),
2029                url: url.filter(|url| !url.is_empty()),
2030                source: plm.as_ref().map(|_| self.plm_source.get()),
2031            })
2032        }
2033
2034        fn save_plm_url(&self, url: &str) -> Result<crate::plm::connection::UrlSaved, String> {
2035            let (url, token_dropped) = crate::plm::config::repoint(&self.app_dir, url)?;
2036            // A session on plm.json moves to the new server now (signed out:
2037            // the tab's sign-in reaches it). One a switch or variable named
2038            // keeps that URL for this launch; plm.json is for the next.
2039            if self.plm_source.get() == crate::plm::config::Source::File {
2040                *self.plm.borrow_mut() = configured_plm(&self.app_dir);
2041            }
2042            Ok(crate::plm::connection::UrlSaved { url, token_dropped })
2043        }
2044
2045        fn list(&self) -> Vec<String> {
2046            let dir_modified = std::fs::metadata(&self.dir).and_then(|meta| meta.modified()).ok();
2047            let generation = self.mutations.get();
2048            if let Some(cached) = self.names.borrow().as_ref() {
2049                if !cached.racy
2050                    && cached.dir_modified == dir_modified
2051                    && cached.generation == generation
2052                    && cached.taken.elapsed() < LISTING_TTL
2053                {
2054                    return cached.names.clone();
2055                }
2056            }
2057            let mut names: Vec<String> = std::fs::read_dir(&self.dir)
2058                .into_iter()
2059                .flatten()
2060                .flatten()
2061                .filter_map(|entry| {
2062                    let name = entry.file_name().to_string_lossy().into_owned();
2063                    crate::document_class::DocumentClass::of_name(&name)
2064                        .is_some()
2065                        .then(|| model_display_name(&name))
2066                })
2067                .collect();
2068            names.sort();
2069            *self.names.borrow_mut() = Some(Names {
2070                racy: dir_modified.is_none_or(|modified| {
2071                    std::time::SystemTime::now().duration_since(modified).map_or(true, |age| age < RACY_WINDOW)
2072                }),
2073                dir_modified,
2074                generation,
2075                taken: std::time::Instant::now(),
2076                names: names.clone(),
2077            });
2078            names
2079        }
2080
2081        fn read(&self, name: &str) -> Option<String> {
2082            if let Some(path) = Self::reserved_path(&self.app_dir, name) {
2083                return write_behind::read(&path);
2084            }
2085            std::fs::read_to_string(self.resolve(name)).ok()
2086        }
2087
2088        // A stat, not a read: an assembly's Save asks this of every part it places.
2089        fn residency(&self, name: &str) -> Residency {
2090            let path = self.resolve(name);
2091            let present = write_behind::pending_put(&path).unwrap_or_else(|| path.is_file());
2092            if present { Residency::Resident } else { Residency::Absent }
2093        }
2094
2095        fn write(&self, name: &str, contents: &str) -> Result<(), String> {
2096            // The UI's own state (settings, layout, recovery, recents) is
2097            // written behind: the frame never waits on its fsync.
2098            if let Some(path) = Self::reserved_path(&self.app_dir, name) {
2099                write_behind::put(path, contents);
2100                self.bump();
2101                return Ok(());
2102            }
2103            let path = self.resolve(name);
2104            if let Some(parent) = path.parent() {
2105                std::fs::create_dir_all(parent).map_err(|e| format!("create models dir: {e}"))?;
2106            }
2107            super::write_atomic(&path, contents.as_bytes(), false).map_err(|e| format!("write {}: {e}", path.display()))?;
2108            self.bump();
2109            Ok(())
2110        }
2111
2112        fn mutation_generation(&self) -> u64 {
2113            self.mutations.get()
2114        }
2115
2116        fn remove(&self, name: &str) -> Result<(), String> {
2117            if let Some(path) = Self::reserved_path(&self.app_dir, name) {
2118                // A delete that finds nothing changes nothing (see below).
2119                if write_behind::pending_put(&path).unwrap_or_else(|| path.is_file()) {
2120                    write_behind::remove(path);
2121                    self.bump();
2122                }
2123                return Ok(());
2124            }
2125            match std::fs::remove_file(self.resolve(name)) {
2126                // A delete that found nothing changed nothing, so it does not
2127                // count: the generation tracks CONTENT, not calls.
2128                Ok(()) => {
2129                    self.bump();
2130                    Ok(())
2131                }
2132                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2133                Err(e) => Err(format!("remove: {e}")),
2134            }
2135        }
2136
2137        fn canonical_identity(&self, name: &str) -> String {
2138            // `resolve` is where every read and write goes, so it IS the
2139            // document a name means; the explorer spells paths the same way.
2140            self.resolve(name).to_string_lossy().into_owned()
2141        }
2142
2143        fn canonicalizer(&self) -> super::Canonicalizer {
2144            let (app_dir, dir) = (self.app_dir.clone(), self.dir.clone());
2145            std::rc::Rc::new(move |name| Self::resolve_in(&app_dir, &dir, name).to_string_lossy().into_owned())
2146        }
2147
2148        fn browser_location(&self) -> String {
2149            self.browser_dir.borrow().display().to_string()
2150        }
2151
2152        fn browser_entries(&self, extensions: &[&str]) -> Vec<BrowserEntry> {
2153            let dir = self.browser_dir.borrow().clone();
2154            let dir_modified = std::fs::metadata(&dir).and_then(|meta| meta.modified()).ok();
2155            let generation = self.mutations.get();
2156            if let Some(listing) = self.listing.borrow().as_ref() {
2157                if !listing.racy
2158                    && listing.dir == dir
2159                    && listing.extensions.iter().map(String::as_str).eq(extensions.iter().copied())
2160                    && listing.dir_modified == dir_modified
2161                    && listing.generation == generation
2162                    && listing.taken.elapsed() < LISTING_TTL
2163                {
2164                    return listing.entries.clone();
2165                }
2166            }
2167            let mut entries: Vec<BrowserEntry> = std::fs::read_dir(&dir)
2168                .into_iter()
2169                .flatten()
2170                .flatten()
2171                .filter_map(|entry| {
2172                    let path = entry.path();
2173                    let is_dir = path.is_dir();
2174                    if !(is_dir || (path.is_file() && Self::matches_extension(&path, extensions))) {
2175                        return None;
2176                    }
2177                    let meta = entry.metadata().ok();
2178                    let size = meta.as_ref().filter(|m| m.is_file()).map(|m| m.len());
2179                    let modified = meta
2180                        .as_ref()
2181                        .and_then(|m| m.modified().ok())
2182                        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
2183                        .map(|d| d.as_secs_f64());
2184                    Some(BrowserEntry {
2185                        name: entry.file_name().to_string_lossy().into_owned(),
2186                        identity: path.to_string_lossy().into_owned(),
2187                        is_dir,
2188                        size,
2189                        modified,
2190                    })
2191                })
2192                .collect();
2193            entries.sort_by(|a, b| {
2194                b.is_dir
2195                    .cmp(&a.is_dir)
2196                    .then_with(|| a.name.to_ascii_lowercase().cmp(&b.name.to_ascii_lowercase()))
2197            });
2198            *self.listing.borrow_mut() = Some(Listing {
2199                dir,
2200                extensions: extensions.iter().map(|extension| extension.to_string()).collect(),
2201                racy: dir_modified.is_none_or(|modified| {
2202                    std::time::SystemTime::now().duration_since(modified).map_or(true, |age| age < RACY_WINDOW)
2203                }),
2204                dir_modified,
2205                generation,
2206                taken: std::time::Instant::now(),
2207                entries: entries.clone(),
2208            });
2209            entries
2210        }
2211
2212        fn browser_enter(&self, identity: &str) -> Result<(), String> {
2213            let path = PathBuf::from(identity);
2214            if !path.is_dir() {
2215                return Err(format!("not a directory: {}", path.display()));
2216            }
2217            *self.browser_dir.borrow_mut() = path;
2218            Ok(())
2219        }
2220
2221        fn browser_up(&self) -> Result<(), String> {
2222            let parent = self.browser_dir.borrow().parent().map(Path::to_path_buf);
2223            if let Some(parent) = parent {
2224                *self.browser_dir.borrow_mut() = parent;
2225            }
2226            Ok(())
2227        }
2228
2229        fn browser_home(&self) -> Result<(), String> {
2230            *self.browser_dir.borrow_mut() = Self::home_dir();
2231            Ok(())
2232        }
2233
2234        fn browser_root(&self) -> Result<(), String> {
2235            let current = self.browser_dir.borrow().clone();
2236            let root = current
2237                .ancestors()
2238                .last()
2239                .map(Path::to_path_buf)
2240                .unwrap_or_else(|| PathBuf::from(std::path::MAIN_SEPARATOR.to_string()));
2241            *self.browser_dir.borrow_mut() = root;
2242            Ok(())
2243        }
2244
2245        fn browser_navigate(&self, location: &str) -> Result<(), String> {
2246            // Rebuilt from its components: a typed `C:\models/sub` (or
2247            // `/models//sub/`) is the folder the walker lists as
2248            // `C:\models\sub`, and a file written there must carry the same
2249            // identity, or one file reads as two.
2250            let path: PathBuf = PathBuf::from(location).components().collect();
2251            if path.is_dir() {
2252                *self.browser_dir.borrow_mut() = path;
2253                Ok(())
2254            } else {
2255                Err(format!("not a directory: {location}"))
2256            }
2257        }
2258
2259        fn browser_places(&self) -> Vec<BrowserPlace> {
2260            let home = Self::home_dir();
2261            let mut places = vec![BrowserPlace {
2262                label: "Home".into(),
2263                location: home.display().to_string(),
2264                kind: PlaceKind::Home,
2265            }];
2266            for (label, sub, kind) in [
2267                ("Documents", "Documents", PlaceKind::Documents),
2268                ("Downloads", "Downloads", PlaceKind::Downloads),
2269            ] {
2270                let path = home.join(sub);
2271                if path.is_dir() {
2272                    places.push(BrowserPlace {
2273                        label: label.into(),
2274                        location: path.display().to_string(),
2275                        kind,
2276                    });
2277                }
2278            }
2279            places.push(BrowserPlace {
2280                label: "Models".into(),
2281                location: self.dir.display().to_string(),
2282                kind: PlaceKind::Models,
2283            });
2284            places.push(BrowserPlace {
2285                label: "/".into(),
2286                location: "/".into(),
2287                kind: PlaceKind::Root,
2288            });
2289            places
2290        }
2291
2292        fn browser_create_dir(&self, name: &str) -> Result<(), String> {
2293            let name = PathBuf::from(name);
2294            if name.components().count() != 1 {
2295                return Err("folder name must be one path component".into());
2296            }
2297            let path = self.browser_dir.borrow().join(name);
2298            std::fs::create_dir(&path)
2299                .map_err(|e| format!("create folder {}: {e}", path.display()))
2300        }
2301
2302        fn browser_write(&self, name: &str, contents: &str) -> Result<String, String> {
2303            let file_name = PathBuf::from(name)
2304                .file_name()
2305                .ok_or("invalid file name")?
2306                .to_string_lossy()
2307                .into_owned();
2308            let file_name = super::model_file_name(&file_name);
2309            let path = self.browser_dir.borrow().join(file_name);
2310            super::write_atomic(&path, contents.as_bytes(), false)
2311                .map_err(|e| format!("write {}: {e}", path.display()))?;
2312            // This door writes the file ITSELF rather than going through
2313            // `write`, so it has to move the generation itself.
2314            self.bump();
2315            Ok(path.to_string_lossy().into_owned())
2316        }
2317
2318        fn browser_write_bytes(&self, file_name: &str, contents: &[u8]) -> Result<String, String> {
2319            let file_name = PathBuf::from(file_name)
2320                .file_name()
2321                .ok_or("invalid file name")?
2322                .to_owned();
2323            let folder = self.browser_dir.borrow().clone();
2324            // The folder the explorer shows normally exists; the models folder
2325            // of a fresh store may not yet (the export lane made it too).
2326            std::fs::create_dir_all(&folder).map_err(|e| format!("create {}: {e}", folder.display()))?;
2327            let path = folder.join(file_name);
2328            super::write_atomic(&path, contents, false)
2329                .map_err(|e| format!("write {}: {e}", path.display()))?;
2330            Ok(path.to_string_lossy().into_owned())
2331        }
2332
2333        fn list_external_files(&self, extensions: &[&str]) -> Vec<String> {
2334            let wanted: Vec<String> = extensions
2335                .iter()
2336                .map(|extension| extension.trim_start_matches('.').to_ascii_lowercase())
2337                .collect();
2338            let mut names: Vec<String> = std::fs::read_dir(&self.dir)
2339                .into_iter()
2340                .flatten()
2341                .flatten()
2342                .filter_map(|entry| {
2343                    let path = entry.path();
2344                    path.is_file().then_some(path)
2345                })
2346                .filter_map(|path| {
2347                    let extension = path.extension()?.to_string_lossy().to_ascii_lowercase();
2348                    wanted.contains(&extension).then(|| {
2349                        path.file_name()
2350                            .unwrap_or_default()
2351                            .to_string_lossy()
2352                            .into_owned()
2353                    })
2354                })
2355                .collect();
2356            names.sort();
2357            names
2358        }
2359
2360        fn read_external_file(&self, name: &str) -> Option<Vec<u8>> {
2361            let path = PathBuf::from(name);
2362            let path = if path.is_absolute() || path.components().count() > 1 {
2363                path
2364            } else {
2365                self.browser_dir.borrow().join(path)
2366            };
2367            std::fs::read(path).ok()
2368        }
2369
2370        fn export_file_named(&self, file_name: &str, contents: &str) -> Result<(), String> {
2371            self.export_file_named_bytes(file_name, contents.as_bytes())
2372        }
2373
2374        fn export_file_named_bytes(&self, file_name: &str, contents: &[u8]) -> Result<(), String> {
2375            std::fs::create_dir_all(&self.dir)
2376                .map_err(|e| format!("create models dir: {e}"))?;
2377            let name = PathBuf::from(file_name)
2378                .file_name()
2379                .ok_or("invalid export file name")?
2380                .to_owned();
2381            let path = self.dir.join(name);
2382            super::write_atomic(&path, contents, false)
2383                .map_err(|e| format!("write {}: {e}", path.display()))
2384        }
2385    }
2386}
2387
2388// --- The mirrored store: a synchronous facade over an ASYNC backend ------------
2389//
2390// The browser has no synchronous storage big enough for this application. The
2391// measured numbers that forced this module into existence: one imported STEP
2392// part serialises to a ~35 MB native BREP payload, and an imported assembly
2393// document runs 1.0x-12.8x its source STEP text — against `localStorage`'s
2394// ~5-10 MB per-origin quota. Every backend with room (IndexedDB today, a remote
2395// server tomorrow) is ASYNC, while [`ModelStore`] is synchronous and the egui
2396// frame loop that calls it is immediate-mode.
2397//
2398// The reconciliation is this module: an in-memory `BTreeMap` MIRROR of the whole
2399// key space, hydrated from the backend inside the already-async wasm entry
2400// point (`lib.rs::start`) BEFORE the app is constructed. Because hydration
2401// completes before the first `read` can happen, a synchronous read never has a
2402// "not loaded yet" state to represent, and none of the ~55 call sites change.
2403// Writes mutate the mirror synchronously (so the very next `read` sees them) and
2404// are pushed to the backend WRITE-BEHIND; a push that fails afterwards surfaces
2405// through [`ModelStore::take_persistence_errors`].
2406//
2407// Hydration is the only WHOLE-key-space read, not the only read. It cannot be:
2408// the backend is shared with every other tab of the origin, and a mirror that
2409// only ever loaded at boot goes stale the moment someone else saves — which is
2410// what made a part saved in one tab un-insertable in another until the user hit
2411// reload. [`MirrorStore::refresh_key`] re-reads ONE key through
2412// [`StoreBackend::get`] and folds it in, so the correction costs a single record
2413// rather than the corpus; what drives it is platform business, and lives in
2414// [`web_model`](super::web_model).
2415pub(crate) mod mirror_store {
2416    use super::{
2417        model_display_name, BrowserEntry, BrowserPlace, KeySpace, ModelStore, PlaceKind,
2418        Residency, DOCK_LAYOUT_KEY, FEATURE_PALETTE_DISPLAY_KEY, KICAD_LIBRARY_KEY, PINNED_KEY,
2419        PLM_IMPORT_KEY, RECOVERY_KEY, SETTINGS_KEY,
2420    };
2421    use std::cell::{Cell, RefCell};
2422    use std::collections::{BTreeMap, BTreeSet, VecDeque};
2423    use std::future::Future;
2424    use std::pin::Pin;
2425    use std::rc::Rc;
2426
2427    /// The persisted key scheme, VERBATIM from the `localStorage` era so an
2428    /// existing origin's keys keep their meaning under any backend: model
2429    /// documents live at `brep-app:model:<relative name>`, explorer folders at
2430    /// `brep-app:dir:<relative path>/`, and the three reserved application blobs
2431    /// at `brep-app:settings` / `:dock_layout` / `:pinned` (see [`MirrorStore::key`]).
2432    pub(crate) const PREFIX: &str = "brep-app:model:";
2433    pub(crate) const DIR_PREFIX: &str = "brep-app:dir:";
2434    /// Ordinary binary/text files stay separate from model documents.
2435    pub(crate) const FILE_PREFIX: &str = "brep-app:file:";
2436
2437    #[cfg(feature = "automation")]
2438    mod files { include!("store_files.rs"); }
2439
2440
2441    /// How many distinct persistence failures the error log keeps before the
2442    /// oldest is dropped. The log is a user-facing notice channel, not telemetry.
2443    const MAX_ERRORS: usize = 64;
2444
2445    /// The future a [`StoreBackend`] hands back. Boxed (not `async fn` in the
2446    /// trait) because the store is used as `dyn StoreBackend`, and deliberately
2447    /// NOT `Send`: every host is single-threaded (the browser main thread; the
2448    /// native test executor below).
2449    pub(crate) type BackendFuture<T> = Pin<Box<dyn Future<Output = Result<T, String>>>>;
2450
2451    /// One hydrated key's value in the mirror: the bytes themselves, or only
2452    /// the fact that they exist and how many there are.
2453    ///
2454    /// `OnDisk` is what makes an index-only hydrate possible: `list`,
2455    /// `browser_entries` and sizes answer from it with no bytes in memory, and
2456    /// the bytes arrive later — on the first `read`, or from
2457    /// [`MirrorStore::prefetch`] in the background.
2458    #[derive(Clone, Debug, PartialEq, Eq)]
2459    // `OnDisk` is built only by an index-only backend: the tests' today, the
2460    // PLM's in S1.
2461    #[cfg_attr(not(test), allow(dead_code))]
2462    pub(crate) enum Entry {
2463        Resident(String),
2464        OnDisk { bytes: u64 },
2465    }
2466
2467    /// One row of a PLM index answer: the mirror key, its size and the hash
2468    /// of the document the server holds (sha256, hex — what
2469    /// [`crate::plm::content_hash`] computes of the same bytes).
2470    pub(crate) struct IndexRow {
2471        pub(crate) key: String,
2472        pub(crate) bytes: u64,
2473        pub(crate) content_hash: String,
2474    }
2475
2476    impl Entry {
2477        /// The value's size in bytes, whether or not it is loaded.
2478        pub(crate) fn len(&self) -> u64 {
2479            match self {
2480                Entry::Resident(value) => value.len() as u64,
2481                Entry::OnDisk { bytes } => *bytes,
2482            }
2483        }
2484    }
2485
2486    /// The key space a BACKEND key belongs to (see [`KeySpace`]), or `None` for
2487    /// an explorer directory row (`brep-app:dir:`), which only the file backends
2488    /// hold — a PLM user's folders are the workspace (S14), not store keys.
2489    /// A key this module did not mint counts as a document.
2490    #[cfg_attr(not(test), allow(dead_code))] // routed by S1's PLM session
2491    pub(crate) fn key_space(key: &str) -> Option<KeySpace> {
2492        if key.starts_with(DIR_PREFIX) || key.starts_with(FILE_PREFIX) {
2493            return None;
2494        }
2495        for name in super::PREFERENCE_KEYS.iter().chain(super::LOCAL_KEYS) {
2496            if key == MirrorStore::key(name) {
2497                return Some(KeySpace::of(name));
2498            }
2499        }
2500        Some(KeySpace::Documents)
2501    }
2502
2503    /// Where a [`MirrorStore`]'s bytes actually live — the swappable persistence
2504    /// seam.
2505    ///
2506    /// The contract is deliberately narrow and platform-free: **string keys,
2507    /// string values, `String` errors, async everywhere**. No `JsValue`, no
2508    /// `web_sys` type, no IndexedDB concept crosses it, and the mirror above it
2509    /// knows nothing about how a key is stored. [`IdbBackend`](super::web_model)
2510    /// is the only implementation today; the intended SECOND one is a remote
2511    /// HTTP/AJAX backend that pushes and pulls the same key space to a central
2512    /// server, and it must be able to land without touching this module.
2513    ///
2514    /// The obligations an implementation carries:
2515    ///
2516    /// * **Per-key FIFO — the mirror's, unless the backend says it is its own.**
2517    ///   Two `put`s of the same key must land in call order, whatever order
2518    ///   their futures are polled in. IndexedDB gets this for free (a
2519    ///   `readwrite` transaction commits in creation order, and
2520    ///   [`IdbBackend`](super::web_model) creates the transaction and issues the
2521    ///   request synchronously inside `put`), and says so through
2522    ///   [`Self::orders_writes_per_key`]. Every other backend — an HTTP one has
2523    ///   no such guarantee — gets the mirror's per-key send queue: a key's next
2524    ///   `put`/`delete` is not even ISSUED until its previous one has settled.
2525    /// * **`load_index` or `load_all` hydrates the whole key space** — every key
2526    ///   is present in the answer; `load_index` may leave values
2527    ///   [`Entry::OnDisk`].
2528    /// * **`get` sees other clients' writes.** The mirror calls it to correct
2529    ///   itself after someone else wrote the key, and to load an `OnDisk`
2530    ///   entry, so it must read THROUGH any per-connection cache of the
2531    ///   implementation's own.
2532    ///
2533    /// ## Index hydration
2534    ///
2535    /// A full hydrate holds EVERY saved document resident for the session: a
2536    /// non-issue for a browser origin (IndexedDB is local, and still hydrates
2537    /// whole through the `load_index` default), untenable for a remote catalog
2538    /// of thousands of parts. So the mirror's value is an [`Entry`], a backend
2539    /// may answer [`Self::load_index`] with sizes instead of bytes, and the
2540    /// bytes arrive on demand ([`ModelStore::read`] asks for them) or in the
2541    /// background ([`MirrorStore::prefetch`]). All of it sits behind THIS trait
2542    /// and behind [`ModelStore`], so no call site moved.
2543    pub(crate) trait StoreBackend {
2544        /// A short human label for the storage panel header (see
2545        /// [`ModelStore::backend_label`]).
2546        fn label(&self) -> String;
2547
2548        /// The signed-in client of a backend that talks to a PLM (see
2549        /// [`ModelStore::plm_client`]). `None` for every local backend.
2550        fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
2551            None
2552        }
2553
2554        /// See [`ModelStore::plm_revision`]. `None` for every local backend.
2555        fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
2556            let _ = key;
2557            None
2558        }
2559
2560        /// See [`ModelStore::note_checked_out`].
2561        fn note_checked_out(&self, key: &str) {
2562            let _ = key;
2563        }
2564
2565        /// See [`ModelStore::plm_written_by_us`].
2566        fn plm_written_by_us(&self, key: &str) -> bool {
2567            let _ = key;
2568            false
2569        }
2570
2571
2572        /// The index rows of `keys` (store keys, `part/<p>/rev/<r>`), as the
2573        /// LAZY entries the mirror reconciles on a feed move: `(mirror key,
2574        /// [`Entry::OnDisk`], content hash)`. A key the server no longer
2575        /// lists is absent from the answer. `Err` from a backend that keeps no
2576        /// index: the mirror then leaves its entries alone.
2577        fn index_rows(&self, keys: &[String]) -> BackendFuture<Vec<IndexRow>> {
2578            let _ = keys;
2579            Box::pin(async { Err("this store keeps no index".to_string()) })
2580        }
2581
2582        /// The whole index as [`Self::index_rows`] answers it, for a stale
2583        /// feed (a resync): every document the server lists.
2584        fn index_all(&self) -> BackendFuture<Vec<IndexRow>> {
2585            Box::pin(async { Err("this store keeps no index".to_string()) })
2586        }
2587
2588        /// Pull the entire key space, values included.
2589        fn load_all(&self) -> BackendFuture<Vec<(String, String)>>;
2590
2591        /// Pull the entire key space as METADATA: every key, with its bytes
2592        /// where they are cheap and only its size ([`Entry::OnDisk`]) where they
2593        /// are not. Called ONCE, during the async boot, before any
2594        /// [`MirrorStore`] exists.
2595        ///
2596        /// The default is [`Self::load_all`] with every value resident — exactly
2597        /// the hydrate a local backend has always done. A remote backend
2598        /// overrides it (the PLM's `GET /api/store/index` IS this call).
2599        fn load_index(&self) -> BackendFuture<Vec<(String, Entry)>> {
2600            let all = self.load_all();
2601            Box::pin(async move {
2602                Ok(all
2603                    .await?
2604                    .into_iter()
2605                    .map(|(key, value)| (key, Entry::Resident(value)))
2606                    .collect())
2607            })
2608        }
2609
2610        /// `true` when this backend ALREADY lands two writes of one key in call
2611        /// order without help (IndexedDB), so the mirror issues every write
2612        /// the moment it is made. The default, `false`, puts the backend behind
2613        /// the mirror's per-key send queue — the safe answer for a backend that
2614        /// has not thought about it.
2615        fn orders_writes_per_key(&self) -> bool {
2616            false
2617        }
2618
2619        /// Read ONE key's CURRENT value straight from the backend — `None` when
2620        /// it is absent.
2621        ///
2622        /// This is the LIVE read, and it exists because the mirror is not the
2623        /// only writer of its key space: a SECOND TAB of the same origin holds
2624        /// its own mirror over the same IndexedDB (and a remote backend would
2625        /// have other clients still). Hydration alone therefore goes stale the
2626        /// moment someone else saves — the user's "I saved a part in one tab and
2627        /// the other tab cannot insert it until I reload". [`MirrorStore::refresh_key`]
2628        /// answers that by re-reading exactly the key that changed. It is also
2629        /// how an [`Entry::OnDisk`] value is loaded.
2630        ///
2631        /// REQUIRED rather than defaulted, for the reason
2632        /// [`ModelStore::mutation_generation`] is: a `None`-returning default
2633        /// would let a new backend compile while silently making every external
2634        /// change look like a deletion.
2635        fn get(&self, key: &str) -> BackendFuture<Option<String>>;
2636
2637        /// Persist `value` under `key`, creating or overwriting.
2638        fn put(&self, key: &str, value: &str) -> BackendFuture<()>;
2639
2640        /// [`Self::put`] only over the document whose content hash is
2641        /// `expected`. A backend that can tell refuses a newer one with an
2642        /// error starting [`CHANGED_ELSEWHERE`]; one that cannot just puts.
2643        fn put_if(&self, key: &str, value: &str, expected: &str) -> BackendFuture<()> {
2644            let _ = expected;
2645            self.put(key, value)
2646        }
2647
2648        /// Delete `key`. Succeeding on an absent key is correct.
2649        fn delete(&self, key: &str) -> BackendFuture<()>;
2650
2651        /// Commit a bounded file rename as one transaction. A failure must
2652        /// preserve the source keys; stores without this primitive refuse it.
2653        #[cfg(feature = "automation")]
2654        fn move_files(&self, _entries: Vec<(String, String, String)>) -> BackendFuture<()> {
2655            Box::pin(async { Err("atomic file moves are unsupported by this backend".into()) })
2656        }
2657
2658    }
2659
2660    /// A [`StoreBackend`] that sends each [`KeySpace`] to its own backend — the
2661    /// shape D1 gives a PLM session: documents to the store routes, preferences
2662    /// to the per-user store (P5), `@recovery` to the machine. Explorer
2663    /// directory rows travel with the documents, since only a file backend
2664    /// holds them; a documents backend with no folders refuses them itself.
2665    ///
2666    /// Hydration is the union of the three indexes. A key one backend returns
2667    /// that belongs to ANOTHER space is dropped rather than trusted: a backend
2668    /// is authoritative for its own space only.
2669    #[cfg_attr(not(test), allow(dead_code))] // composed by S1's PLM session
2670    pub(crate) struct KeySpaceRouter {
2671        pub(crate) documents: Rc<dyn StoreBackend>,
2672        pub(crate) preferences: Rc<dyn StoreBackend>,
2673        pub(crate) local: Rc<dyn StoreBackend>,
2674    }
2675
2676    #[cfg_attr(not(test), allow(dead_code))]
2677    impl KeySpaceRouter {
2678        fn route(&self, key: &str) -> &Rc<dyn StoreBackend> {
2679            match key_space(key) {
2680                Some(KeySpace::Preferences) => &self.preferences,
2681                Some(KeySpace::Local) => &self.local,
2682                Some(KeySpace::Documents) | None => &self.documents,
2683            }
2684        }
2685
2686        fn serves(space: KeySpace, key: &str) -> bool {
2687            match key_space(key) {
2688                Some(found) => found == space,
2689                None => space == KeySpace::Documents,
2690            }
2691        }
2692
2693        fn spaces(&self) -> [(KeySpace, &Rc<dyn StoreBackend>); 3] {
2694            [
2695                (KeySpace::Documents, &self.documents),
2696                (KeySpace::Preferences, &self.preferences),
2697                (KeySpace::Local, &self.local),
2698            ]
2699        }
2700    }
2701
2702    impl StoreBackend for KeySpaceRouter {
2703        fn label(&self) -> String {
2704            self.documents.label()
2705        }
2706
2707        fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
2708            self.documents.plm_client()
2709        }
2710
2711        fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
2712            self.documents.plm_revision(key)
2713        }
2714        fn note_checked_out(&self, key: &str) {
2715            self.documents.note_checked_out(key)
2716        }
2717        fn plm_written_by_us(&self, key: &str) -> bool {
2718            self.documents.plm_written_by_us(key)
2719        }
2720
2721
2722        fn index_rows(&self, keys: &[String]) -> BackendFuture<Vec<IndexRow>> {
2723            self.documents.index_rows(keys)
2724        }
2725        fn index_all(&self) -> BackendFuture<Vec<IndexRow>> {
2726            self.documents.index_all()
2727        }
2728
2729        fn load_all(&self) -> BackendFuture<Vec<(String, String)>> {
2730            let requests: Vec<_> = self
2731                .spaces()
2732                .into_iter()
2733                .map(|(space, backend)| (space, backend.load_all()))
2734                .collect();
2735            Box::pin(async move {
2736                let mut all = Vec::new();
2737                for (space, request) in requests {
2738                    all.extend(
2739                        request
2740                            .await?
2741                            .into_iter()
2742                            .filter(|(key, _)| Self::serves(space, key)),
2743                    );
2744                }
2745                Ok(all)
2746            })
2747        }
2748
2749        fn load_index(&self) -> BackendFuture<Vec<(String, Entry)>> {
2750            let requests: Vec<_> = self
2751                .spaces()
2752                .into_iter()
2753                .map(|(space, backend)| (space, backend.load_index()))
2754                .collect();
2755            Box::pin(async move {
2756                let mut all = Vec::new();
2757                for (space, request) in requests {
2758                    all.extend(
2759                        request
2760                            .await?
2761                            .into_iter()
2762                            .filter(|(key, _)| Self::serves(space, key)),
2763                    );
2764                }
2765                Ok(all)
2766            })
2767        }
2768
2769        fn orders_writes_per_key(&self) -> bool {
2770            self.spaces()
2771                .iter()
2772                .all(|(_, backend)| backend.orders_writes_per_key())
2773        }
2774
2775        fn get(&self, key: &str) -> BackendFuture<Option<String>> {
2776            self.route(key).get(key)
2777        }
2778
2779        fn put(&self, key: &str, value: &str) -> BackendFuture<()> {
2780            self.route(key).put(key, value)
2781        }
2782
2783        fn put_if(&self, key: &str, value: &str, expected: &str) -> BackendFuture<()> {
2784            self.route(key).put_if(key, value, expected)
2785        }
2786
2787        fn delete(&self, key: &str) -> BackendFuture<()> {
2788            self.route(key).delete(key)
2789        }
2790    }
2791
2792    /// The backend installed when persistence could NOT be brought up (IndexedDB
2793    /// blocked in a private window, storage denied, the boot hydrate never ran).
2794    ///
2795    /// There is deliberately no quiet fallback to `localStorage`: a 5 MB backend
2796    /// silently standing in for a hundreds-of-megabytes one is the failure mode
2797    /// this whole change exists to end. Instead the session stays fully usable
2798    /// IN MEMORY — the mirror still holds everything written this session — while
2799    /// every write reports, loudly and repeatedly, that nothing is being saved.
2800    // Built by the browser's boot today; a native session falls back to the file stores instead.
2801    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
2802    pub(crate) struct UnavailableBackend {
2803        reason: String,
2804    }
2805
2806    // See `UnavailableBackend`.
2807    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
2808    impl UnavailableBackend {
2809        pub(crate) fn new(reason: impl Into<String>) -> Self {
2810            Self {
2811                reason: reason.into(),
2812            }
2813        }
2814    }
2815
2816    impl StoreBackend for UnavailableBackend {
2817        fn label(&self) -> String {
2818            format!("NOT SAVING — {} · use Download to keep your work", self.reason)
2819        }
2820
2821        fn load_all(&self) -> BackendFuture<Vec<(String, String)>> {
2822            let reason = self.reason.clone();
2823            Box::pin(async move { Err(reason) })
2824        }
2825
2826        fn get(&self, _key: &str) -> BackendFuture<Option<String>> {
2827            let reason = self.reason.clone();
2828            Box::pin(async move { Err(reason) })
2829        }
2830
2831        fn put(&self, _key: &str, _value: &str) -> BackendFuture<()> {
2832            let reason = self.reason.clone();
2833            Box::pin(async move { Err(reason) })
2834        }
2835
2836        fn delete(&self, _key: &str) -> BackendFuture<()> {
2837            let reason = self.reason.clone();
2838            Box::pin(async move { Err(reason) })
2839        }
2840    }
2841
2842    /// What a backend's refusal starts with when it holds a newer document
2843    /// than the one a conditional write ([`StoreBackend::put_if`]) was based on.
2844    pub(crate) const CHANGED_ELSEWHERE: &str = "changed elsewhere: ";
2845
2846    /// Persistence failures that happened AFTER the synchronous `write` returned
2847    /// `Ok` — the price of write-behind. Nothing is lost mid-session (the mirror
2848    /// holds it), but the user MUST learn that it did not persist, so the log is
2849    /// drained into the toast overlay every frame.
2850    ///
2851    /// The cursor (rather than a `Vec::drain`) keeps the full history addressable
2852    /// for the `__brepStoreErrors` verification hook while still handing the UI
2853    /// each message exactly once.
2854    pub(crate) struct ErrorLog {
2855        log: RefCell<Vec<String>>,
2856        drained: Cell<usize>,
2857        /// The documents whose write failed, not yet taken by the frame loop,
2858        /// which marks their tabs unsaved again ([`ModelStore::take_failed_writes`]).
2859        failed_writes: RefCell<Vec<String>>,
2860        /// Keys whose LAST write failed: the mirror holds what was sent (this
2861        /// session reads it), the backend does not ([`ModelStore::write_failed`]);
2862        /// with the content hash of the backend's document that write was
2863        /// based on (empty: unknown), for the retry's `If-Match`.
2864        unsynced: RefCell<BTreeMap<String, String>>,
2865        /// Per key, the base of the write last issued.
2866        bases: RefCell<BTreeMap<String, String>>,
2867        /// Wakes the reactive frame loop so a failure recorded from an async
2868        /// callback is toasted THIS frame instead of waiting for stray input.
2869        wake: Option<Rc<dyn Fn()>>,
2870    }
2871
2872    impl ErrorLog {
2873        fn new(wake: Option<Rc<dyn Fn()>>) -> Self {
2874            Self {
2875                log: RefCell::new(Vec::new()),
2876                drained: Cell::new(0),
2877                failed_writes: RefCell::new(Vec::new()),
2878                unsynced: RefCell::new(BTreeMap::new()),
2879                bases: RefCell::new(BTreeMap::new()),
2880                wake,
2881            }
2882        }
2883
2884        /// Record one failure. An identical message that is still UNDRAINED is
2885        /// collapsed (a burst of failing writes shows one toast, not six); once
2886        /// the UI has shown it, the same message can be recorded again — every
2887        /// failed save is reported.
2888        pub(crate) fn record(&self, message: String) {
2889            {
2890                let mut log = self.log.borrow_mut();
2891                let undrained = log.len() > self.drained.get();
2892                if undrained && log.last().map(|last| *last == message).unwrap_or(false) {
2893                    return;
2894                }
2895                log.push(message);
2896                if log.len() > MAX_ERRORS {
2897                    log.remove(0);
2898                    self.drained.set(self.drained.get().saturating_sub(1));
2899                }
2900            }
2901            if let Some(wake) = &self.wake {
2902                wake();
2903            }
2904        }
2905
2906        /// The write of document `name` failed: besides its message, the frame
2907        /// loop learns WHICH document, so its tab reads unsaved again.
2908        pub(crate) fn record_failed_write(&self, name: &str) {
2909            let mut failed = self.failed_writes.borrow_mut();
2910            if !failed.iter().any(|n| n == name) {
2911                failed.push(name.to_string());
2912            }
2913        }
2914
2915        fn take_failed_writes(&self) -> Vec<String> {
2916            std::mem::take(&mut *self.failed_writes.borrow_mut())
2917        }
2918
2919        /// A write of `key` is issued, based on the backend's document with
2920        /// content hash `base` (empty: unknown).
2921        fn note_base(&self, key: &str, base: String) {
2922            self.bases.borrow_mut().insert(key.to_string(), base);
2923        }
2924
2925        /// A write of `key` settled. Failed, the key is unsynced, keeping the
2926        /// base of its FIRST failed write (the backend's document before this
2927        /// session's unconfirmed writes); landed, or refused because the
2928        /// backend holds a newer document (`refused`), it is not.
2929        fn mark_unsynced(&self, key: &str, failed: bool) {
2930            let mut unsynced = self.unsynced.borrow_mut();
2931            if failed {
2932                let base = self.bases.borrow().get(key).cloned().unwrap_or_default();
2933                unsynced.entry(key.to_string()).or_insert(base);
2934            } else {
2935                unsynced.remove(key);
2936            }
2937        }
2938
2939        fn unsynced(&self, key: &str) -> Option<String> {
2940            self.unsynced.borrow().get(key).cloned()
2941        }
2942
2943        /// Messages recorded since the last drain (what the UI has not shown yet).
2944        fn drain(&self) -> Vec<String> {
2945            let log = self.log.borrow();
2946            let from = self.drained.get().min(log.len());
2947            self.drained.set(log.len());
2948            log[from..].to_vec()
2949        }
2950
2951        /// Every message recorded this session (verification hook).
2952        // The browser's `__brepStoreErrors` verification hook.
2953        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
2954        fn all(&self) -> Vec<String> {
2955            self.log.borrow().clone()
2956        }
2957    }
2958
2959    /// Drive one write-behind push to completion.
2960    ///
2961    /// wasm: hand it to the browser's microtask queue, which is the whole point —
2962    /// the caller's `write` already returned. Native: the frame-driven executor
2963    /// ([`crate::plm::native`]), the same shape — polled once at once (so a
2964    /// backend whose futures are already resolved finishes inside `write`, as
2965    /// every test that does not care about timing assumes), parked if still
2966    /// pending, and polled again once its waker fires and the frame loop (or a
2967    /// test's [`test_executor::drive`]) runs the queue. Keeping the shape
2968    /// identical means the native tests exercise the REAL write-behind path
2969    /// (spawn, await, record the error) rather than a synchronous stand-in — and
2970    /// the parking is what lets a test hold one write open and watch what the
2971    /// per-key queue does with the next.
2972    #[cfg(target_arch = "wasm32")]
2973    fn spawn(task: impl Future<Output = ()> + 'static) {
2974        super::spawn_waking(task);
2975    }
2976
2977    #[cfg(not(target_arch = "wasm32"))]
2978    fn spawn(task: impl Future<Output = ()> + 'static) {
2979        crate::plm::native::spawn(task);
2980    }
2981
2982    /// [`spawn`] for one document's write: natively the task is tagged with
2983    /// the document's store name, so `settle` on another document can leave
2984    /// it out (`plm::native::pending_except`).
2985    fn spawn_for(name: &str, task: impl Future<Output = ()> + 'static) {
2986        #[cfg(not(target_arch = "wasm32"))]
2987        crate::plm::native::tagged(name, || spawn(task));
2988        #[cfg(target_arch = "wasm32")]
2989        {
2990            let _ = name;
2991            spawn(task);
2992        }
2993    }
2994
2995
2996    /// A synchronous [`ModelStore`] over an asynchronous [`StoreBackend`]: the
2997    /// hydrated mirror plus write-behind. Cheap to clone — every field is shared,
2998    /// so a clone is another handle on the SAME session state (used by the
2999    /// verification hooks).
3000    #[derive(Clone)]
3001    pub(crate) struct MirrorStore {
3002        /// The whole key space, keyed EXACTLY as the backend keys it. A value
3003        /// is [`Entry::OnDisk`] until something asks for its bytes.
3004        entries: Rc<RefCell<BTreeMap<String, Entry>>>,
3005        /// The explorer's current virtual directory (`/` or `/models/...`).
3006        browser_dir: Rc<RefCell<String>>,
3007        backend: Rc<dyn StoreBackend>,
3008        errors: Rc<ErrorLog>,
3009        /// Pushes issued but not yet settled. Zero means everything written so
3010        /// far is durable — which is what makes a "save, reload, still there"
3011        /// check non-racy (see the `__brepStorePending` hook).
3012        pending: Rc<Cell<usize>>,
3013        /// See [`ModelStore::mutation_generation`]. SHARED like every other
3014        /// field: a clone is another handle on the same session state, and the
3015        /// `__brepStoreWrite` verification hook holds one — a write through
3016        /// that hook has to move the generation the app reads.
3017        mutations: Rc<Cell<u64>>,
3018        /// How many of our OWN pushes are still in flight, PER KEY. Used by
3019        /// [`Self::refresh_key`] to leave a key alone while this session is
3020        /// mid-write on it: pulling another tab's value in on top of a save we
3021        /// have already returned `Ok` for would show the user someone else's
3022        /// bytes under their own file name.
3023        in_flight: Rc<RefCell<BTreeMap<String, usize>>>,
3024        /// Repaint the reactive frame loop. The `ErrorLog` holds this for write
3025        /// failures; the store needs its own handle because an EXTERNAL change
3026        /// arrives on an async callback too, and a list that updates only when
3027        /// the user happens to move the mouse is the stale list all over again.
3028        wake: Option<Rc<dyn Fn()>>,
3029        /// `OnDisk` keys whose bytes have been asked of the backend and not yet
3030        /// answered, so a second `read` of one does not ask again.
3031        loading: Rc<RefCell<BTreeSet<String>>>,
3032        /// The per-key send queue (see [`StoreBackend::orders_writes_per_key`]):
3033        /// for each key with a write in flight, the writes made after it, not
3034        /// yet issued. A key is present exactly while its drain task runs.
3035        queues: Rc<RefCell<BTreeMap<String, VecDeque<QueuedWrite>>>>,
3036        /// A monotonic clock of authority: every local mutation of a key and
3037        /// every index request issued takes the next tick.
3038        clock: Rc<Cell<u64>>,
3039        /// Per key, the tick of the authority that last set it here — a local
3040        /// write, delete, remembered save, loaded body, or the ISSUE tick of
3041        /// the index answer applied to it. An index answer applies to a key
3042        /// only if it was issued after that tick (see [`Self::reconcile`]).
3043        freshness: Rc<RefCell<BTreeMap<String, u64>>>,
3044        /// A whole-index answer also speaks for keys never seen locally.
3045        full_index_authority: Rc<Cell<u64>>,
3046        /// The explorer's last listing and what it was taken from: an open
3047        /// Insert or Open dialog lists the folder every frame, and walking a
3048        /// 5,000-part key space each time was the dialog's frame cost.
3049        listing: Rc<RefCell<Option<(ListingKey, Vec<BrowserEntry>)>>>,
3050    }
3051
3052    /// What a folder listing of [`MirrorStore`] depends on: the folder, the
3053    /// extensions asked for, and the key space as its mutation count, its
3054    /// size and its byte total say (a body that loads keeps its count but
3055    /// may move its size).
3056    #[derive(Clone, PartialEq)]
3057    struct ListingKey {
3058        dir: String,
3059        extensions: Vec<String>,
3060        mutations: u64,
3061        keys: usize,
3062        bytes: u64,
3063    }
3064
3065    /// A write the per-key queue holds back: the document name its failure is
3066    /// reported under, and the backend call, made only when its turn comes.
3067    type QueuedWrite = (String, Box<dyn FnOnce() -> BackendFuture<()>>);
3068
3069    impl MirrorStore {
3070        /// Build the session store from an already-hydrated key space.
3071        /// `wake` (`None` off-browser) is called when a write-behind failure is
3072        /// recorded, to repaint the reactive frame loop.
3073        // The browser's boot and the tests; the native boot hydrates from an index.
3074        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
3075        pub(crate) fn new(
3076            backend: Rc<dyn StoreBackend>,
3077            entries: Vec<(String, String)>,
3078            wake: Option<Rc<dyn Fn()>>,
3079        ) -> Self {
3080            Self::from_index(
3081                backend,
3082                entries
3083                    .into_iter()
3084                    .map(|(key, value)| (key, Entry::Resident(value)))
3085                    .collect(),
3086                wake,
3087            )
3088        }
3089
3090        /// Build the session store from an INDEX ([`StoreBackend::load_index`]):
3091        /// every key present, some values only [`Entry::OnDisk`].
3092        pub(crate) fn from_index(
3093            backend: Rc<dyn StoreBackend>,
3094            entries: Vec<(String, Entry)>,
3095            wake: Option<Rc<dyn Fn()>>,
3096        ) -> Self {
3097            Self {
3098                entries: Rc::new(RefCell::new(entries.into_iter().collect())),
3099                browser_dir: Rc::new(RefCell::new("/models".into())),
3100                backend,
3101                errors: Rc::new(ErrorLog::new(wake.clone())),
3102                pending: Rc::new(Cell::new(0)),
3103                mutations: Rc::new(Cell::new(0)),
3104                in_flight: Rc::new(RefCell::new(BTreeMap::new())),
3105                wake,
3106                loading: Rc::new(RefCell::new(BTreeSet::new())),
3107                queues: Rc::new(RefCell::new(BTreeMap::new())),
3108                clock: Rc::new(Cell::new(0)),
3109                freshness: Rc::new(RefCell::new(BTreeMap::new())),
3110                full_index_authority: Rc::new(Cell::new(0)),
3111                listing: Rc::new(RefCell::new(None)),
3112            }
3113        }
3114        /// The next tick of the authority clock.
3115        fn tick(&self) -> u64 {
3116            let next = self.clock.get() + 1;
3117            self.clock.set(next);
3118            next
3119        }
3120        /// A local authority over `key` now: later index answers that were
3121        /// issued before this cannot touch it.
3122        fn stamp_local(&self, key: &str) {
3123            let tick = self.tick();
3124            self.freshness.borrow_mut().insert(key.to_string(), tick);
3125        }
3126
3127        /// The persisted key for a document/reserved name. UNCHANGED from the
3128        /// `localStorage` implementation this replaced, so an existing origin's
3129        /// data keeps its identity.
3130        pub(crate) fn key(name: &str) -> String {
3131            match name {
3132                SETTINGS_KEY => "brep-app:settings".into(),
3133                FEATURE_PALETTE_DISPLAY_KEY => "brep-app:feature_palette_display".into(),
3134                DOCK_LAYOUT_KEY => "brep-app:dock_layout".into(),
3135                PINNED_KEY => "brep-app:pinned".into(),
3136                RECOVERY_KEY => "brep-app:recovery".into(),
3137                // Desktop-only today (the web build cannot read a KiCad
3138                // library), but a reserved name that fell through to the
3139                // document arm would key as `brep-app:model:@kicad_library` and
3140                // LIST as a document the day anything wrote it here.
3141                KICAD_LIBRARY_KEY => "brep-app:kicad_library".into(),
3142                crate::panels::cam_library::CAM_TOOL_LIBRARY_KEY => "brep-app:cam_tools".into(),
3143                super::RECENT_DOCUMENTS_KEY => "brep-app:recent_documents".into(),
3144                super::RECENT_THUMBNAILS_KEY => "brep-app:recent_thumbnails".into(),
3145                PLM_IMPORT_KEY => "brep-app:plm_import".into(),
3146                super::PLUGINS_KEY => "brep-app:plugins".into(),
3147                super::JAVASCRIPT_DRAFT_KEY => "brep-app:javascript_draft".into(),
3148                _ => format!("{PREFIX}{}", Self::model_relative(name)),
3149            }
3150        }
3151
3152        /// A document name reduced to its store-relative form: no leading `/`, no
3153        /// `/models` root, no model extension.
3154        fn model_relative(name: &str) -> String {
3155            let name = name
3156                .trim_start_matches('/')
3157                .strip_prefix("models/")
3158                .unwrap_or_else(|| name.trim_start_matches('/'));
3159            // The key drops ONLY the normal extension (an existing origin's
3160            // keys keep their identity); a family or template keeps its own,
3161            // lowercased, so `bolt` the part and `bolt.fbrep` the family are
3162            // two keys.
3163            let name = name.trim_matches('/');
3164            match crate::document_class::DocumentClass::of_name(name) {
3165                Some(crate::document_class::DocumentClass::Normal) => {
3166                    crate::document_class::strip_class_extension(name).to_string()
3167                }
3168                Some(_) => super::model_file_name(name),
3169                None => name.to_string(),
3170            }
3171        }
3172
3173        fn virtual_model_path(relative: &str) -> String {
3174            format!("/models/{}", super::model_file_name(relative.trim_matches('/')))
3175        }
3176
3177        fn child_path(parent: &str, child: &str) -> String {
3178            if parent == "/" {
3179                format!("/{child}")
3180            } else {
3181                format!("{}/{child}", parent.trim_end_matches('/'))
3182            }
3183        }
3184
3185        /// Hand one backend write to the executor, counting it in `pending` (and
3186        /// under its KEY in `in_flight`) and routing its eventual failure to the
3187        /// error log.
3188        ///
3189        /// `request` is the backend call itself, not its future: behind the
3190        /// per-key send queue it is made only once every earlier write of the
3191        /// same key has SETTLED, which is the FIFO an HTTP backend cannot give
3192        /// itself. A backend that orders its own writes
3193        /// ([`StoreBackend::orders_writes_per_key`]) has it called at once, so
3194        /// IndexedDB creates its transaction inside `write` exactly as before.
3195        fn push(
3196            &self,
3197            name: &str,
3198            key: &str,
3199            request: impl FnOnce() -> BackendFuture<()> + 'static,
3200        ) {
3201            self.pending.set(self.pending.get() + 1);
3202            *self.in_flight.borrow_mut().entry(key.to_string()).or_insert(0) += 1;
3203            if self.backend.orders_writes_per_key() {
3204                let settle = self.settler(key);
3205                let tag = name;
3206                let name = name.to_string();
3207                let request = request();
3208                spawn_for(tag, async move { settle(&name, request.await) });
3209                return;
3210            }
3211            {
3212                let mut queues = self.queues.borrow_mut();
3213                if let Some(queue) = queues.get_mut(key) {
3214                    // A write of this key is still open: this one waits its turn.
3215                    queue.push_back((name.to_string(), Box::new(request)));
3216                    return;
3217                }
3218                queues.insert(key.to_string(), VecDeque::new());
3219            }
3220            // Nothing ahead of it: issue now, then drain whatever queues behind.
3221            let settle = self.settler(key);
3222            let queues = self.queues.clone();
3223            let key = key.to_string();
3224            let first = (name.to_string(), request());
3225            spawn_for(name, async move {
3226                let (name, request) = first;
3227                settle(&name, request.await);
3228                loop {
3229                    let next = {
3230                        let mut queues = queues.borrow_mut();
3231                        let next = queues.get_mut(&key).and_then(VecDeque::pop_front);
3232                        if next.is_none() {
3233                            queues.remove(&key);
3234                        }
3235                        next
3236                    };
3237                    let Some((name, request)) = next else {
3238                        break;
3239                    };
3240                    // A failed write does not cancel the next: each is its own
3241                    // save, and each failure is reported under its own name.
3242                    settle(&name, request().await);
3243                }
3244            });
3245        }
3246
3247        /// What one settled write does to the session's books: out of
3248        /// `pending` and `in_flight`, and into the error log if it failed.
3249        fn settler(&self, key: &str) -> impl Fn(&str, Result<(), String>) + 'static {
3250            let pending = self.pending.clone();
3251            let in_flight = self.in_flight.clone();
3252            let errors = self.errors.clone();
3253            let entries = self.entries.clone();
3254            let key = key.to_string();
3255            move |name, outcome| {
3256                pending.set(pending.get().saturating_sub(1));
3257                {
3258                    let mut in_flight = in_flight.borrow_mut();
3259                    if let Some(count) = in_flight.get_mut(&key) {
3260                        *count -= 1;
3261                        if *count == 0 {
3262                            in_flight.remove(&key);
3263                        }
3264                    }
3265                }
3266                match outcome {
3267                    Err(message) if message.starts_with(CHANGED_ELSEWHERE) => {
3268                        // The backend refused it because it holds a newer
3269                        // document than the one this write was based on: not
3270                        // ours any more. The mirror forgets what was sent, so
3271                        // the next read takes the newer document and a Save
3272                        // asks as for any document changed elsewhere.
3273                        errors.mark_unsynced(&key, false);
3274                        if let Some(entry) = entries.borrow_mut().get_mut(&key) {
3275                            let bytes = match entry {
3276                                Entry::Resident(text) => text.len() as u64,
3277                                Entry::OnDisk { bytes } => *bytes,
3278                            };
3279                            *entry = Entry::OnDisk { bytes };
3280                        }
3281                        errors.record_failed_write(name);
3282                        errors.record(format!("'{name}' was NOT saved: {}", &message[CHANGED_ELSEWHERE.len()..]));
3283                    }
3284                    Err(message) => {
3285                        errors.record_failed_write(name);
3286                        errors.mark_unsynced(&key, true);
3287                        errors.record(format!("'{name}' was NOT saved: {message}"));
3288                    }
3289                    Ok(()) => errors.mark_unsynced(&key, false),
3290                }
3291            }
3292        }
3293
3294        /// Fold ONE externally-changed key into the mirror: `Some` is the value
3295        /// the backend now holds, `None` means it is gone.
3296        ///
3297        /// A change that is not a change (the value we already had) stops here —
3298        /// no generation bump, no repaint — so an echo costs nothing. A real one
3299        /// moves [`ModelStore::mutation_generation`], which is exactly what that
3300        /// counter promises ("every mutation that landed, WHOEVER made it") and
3301        /// what relights the outdated-components badge on an assembly whose part
3302        /// was just re-saved in another tab.
3303        // The browser's other-tab channel today; natively, the PLM change feed (S1).
3304        /// Fold an index answer into the entries. `asked`: the mirror keys a
3305        /// feed move named (a key missing from the answer was deleted on the
3306        /// server); `None`: the answer is the WHOLE index (a stale-feed
3307        /// resync), so every model key it does not list was deleted.
3308        ///
3309        /// The ordering policy, per key: an answer applies only if it was
3310        /// ISSUED (`issued`, the clock tick taken before the request left)
3311        /// after the authority that last set the key here — a local write or
3312        /// delete, a remembered save, a loaded body, or a newer answer. So an
3313        /// answer that left before a save and lands after it cannot evict the
3314        /// saved copy or delete the saved key, even with nothing in flight
3315        /// any more; and two answers landing out of order leave the newer
3316        /// one's result standing. A key with a write in flight or queued is
3317        /// skipped as well. A resident entry whose bytes hash to the row's
3318        /// content hash is left alone (the server holds what this app holds).
3319        /// Everything else becomes the server's row, lazily: a resident copy
3320        /// the server has moved on from is re-read on its next `read` (no
3321        /// body is fetched here), and an open document's unsaved edits live in
3322        /// its tab, not here. Returns whether anything changed.
3323        pub(crate) fn reconcile(&self, asked: Option<&[String]>, rows: Vec<IndexRow>, issued: u64) -> bool {
3324            let busy = |key: &str| {
3325                self.in_flight.borrow().contains_key(key)
3326                    || self.queues.borrow().contains_key(key)
3327                    || self.full_index_authority.get() >= issued
3328                    || self.freshness.borrow().get(key).is_some_and(|&tick| tick >= issued)
3329            };
3330            let listed: BTreeSet<&str> = rows.iter().map(|row| row.key.as_str()).collect();
3331            let mut changed = false;
3332            {
3333                let mut entries = self.entries.borrow_mut();
3334                let gone: Vec<String> = match asked {
3335                    Some(asked) => asked.iter().filter(|key| !listed.contains(key.as_str())).cloned().collect(),
3336                    None => entries
3337                        .keys()
3338                        .filter(|key| key.starts_with(PREFIX) && !listed.contains(key.as_str()))
3339                        .cloned()
3340                        .collect(),
3341                };
3342                for key in gone {
3343                    if busy(&key) {
3344                        continue;
3345                    }
3346                    self.freshness.borrow_mut().insert(key.clone(), issued);
3347                    changed |= entries.remove(&key).is_some();
3348                }
3349                for row in rows {
3350                    if busy(&row.key) {
3351                        continue;
3352                    }
3353                    self.freshness.borrow_mut().insert(row.key.clone(), issued);
3354                    let same = match entries.get(&row.key) {
3355                        Some(Entry::Resident(held)) => {
3356                            crate::plm::content_hash(held.as_bytes()) == row.content_hash
3357                        }
3358                        Some(Entry::OnDisk { bytes }) => *bytes == row.bytes,
3359                        None => false,
3360                    };
3361                    if same {
3362                        continue;
3363                    }
3364                    entries.insert(row.key, Entry::OnDisk { bytes: row.bytes });
3365                    changed = true;
3366                }
3367            }
3368            if asked.is_none() {
3369                self.full_index_authority.set(self.full_index_authority.get().max(issued));
3370            }
3371            if changed {
3372                self.mutations.set(self.mutations.get().wrapping_add(1));
3373                if let Some(wake) = &self.wake {
3374                    wake();
3375                }
3376            }
3377            changed
3378        }
3379
3380        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
3381        pub(crate) fn apply_external(&self, key: &str, value: Option<String>) {
3382            self.stamp_local(key);
3383            let changed = {
3384                let mut entries = self.entries.borrow_mut();
3385                match value {
3386                    Some(value) => {
3387                        let same = matches!(entries.get(key), Some(Entry::Resident(held)) if *held == value);
3388                        if same {
3389                            false
3390                        } else {
3391                            entries.insert(key.to_string(), Entry::Resident(value));
3392                            true
3393                        }
3394                    }
3395                    None => entries.remove(key).is_some(),
3396                }
3397            };
3398            if !changed {
3399                return;
3400            }
3401            self.mutations.set(self.mutations.get().wrapping_add(1));
3402            if let Some(wake) = &self.wake {
3403                wake();
3404            }
3405        }
3406
3407        /// Re-read `key` from the backend and fold the result in — the LIVE read
3408        /// behind the mirror, driven by whatever tells this session that someone
3409        /// else wrote (on the web, the `brep-app:store` broadcast in
3410        /// [`web_model`](super::web_model)).
3411        ///
3412        /// A key this session is itself mid-write on is left ALONE: our own
3413        /// `write` already returned `Ok` against the mirror, and racing another
3414        /// tab's older bytes in on top of it would replace the user's save with a
3415        /// stranger's under the same name. Skipping costs no correctness. Which
3416        /// of two simultaneous saves of one file wins is settled by the backend's
3417        /// own ordering (IndexedDB commits same-store transactions in creation
3418        /// order), and it settles the same way for the mirror: if our put was
3419        /// created last it lands last, so the mirror already holds what the
3420        /// backend ends up holding — and the OTHER tab hears our commit and
3421        /// corrects itself.
3422        // See `apply_external`.
3423        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
3424        pub(crate) fn refresh_key(&self, key: String) {
3425            if self.in_flight.borrow().contains_key(&key) {
3426                return;
3427            }
3428            let store = self.clone();
3429            let request = self.backend.get(&key);
3430            spawn(async move {
3431                match request.await {
3432                    Ok(value) => store.apply_external(&key, value),
3433                    // A failed re-read leaves the mirror as it was. It is NOT a
3434                    // persistence failure — nothing of the user's was lost — so it
3435                    // does not go to the toast channel; the stale row is the cost,
3436                    // and the next write to that key notifies again.
3437                    Err(_) => {}
3438                }
3439            });
3440        }
3441
3442        /// Seed the log with a boot-time failure so the very first frame toasts it.
3443        // The browser's boot notice; the native boot reports through the file store it falls back to.
3444        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
3445        pub(crate) fn report(&self, message: String) {
3446            self.errors.record(message);
3447        }
3448
3449        /// Backend pushes issued but not yet settled (verification hook).
3450        pub(crate) fn pending(&self) -> usize {
3451            self.pending.get()
3452        }
3453
3454        /// Every persistence failure this session (verification hook).
3455        // Browser verification hooks.
3456        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
3457        pub(crate) fn error_history(&self) -> Vec<String> {
3458            self.errors.all()
3459        }
3460
3461        /// Byte length of a stored document, or `None` if absent (verification
3462        /// hook — a multi-megabyte payload is not worth marshalling into JS just
3463        /// to measure it).
3464        // Browser verification hooks.
3465        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
3466        pub(crate) fn len_of(&self, name: &str) -> Option<usize> {
3467            self.entries.borrow().get(&Self::key(name)).map(|v| v.len() as usize)
3468        }
3469
3470        /// Ask the backend for ONE `OnDisk` key's bytes, unless that is already
3471        /// asked. The answer lands through [`Self::resolve`].
3472        fn load(&self, key: &str) {
3473            if !self.loading.borrow_mut().insert(key.to_string()) {
3474                return;
3475            }
3476            let store = self.clone();
3477            let key = key.to_string();
3478            let issued = self.tick();
3479            let request = self.backend.get(&key);
3480            spawn(async move {
3481                let outcome = request.await;
3482                store.loading.borrow_mut().remove(&key);
3483                store.resolve(&key, outcome, issued);
3484            });
3485        }
3486
3487        /// Fold a loaded `OnDisk` value in — ONLY if the entry is still
3488        /// `OnDisk`. A write or a remove that happened while the bytes were on
3489        /// their way is newer than them, and wins.
3490        ///
3491        /// A failed load leaves the entry `OnDisk`, so the next `read` asks
3492        /// again. Like a failed refresh it does not toast: nothing of the
3493        /// user's was lost (S1 owns how a transport failure is shown).
3494        fn resolve(&self, key: &str, outcome: Result<Option<String>, String>, issued: u64) {
3495            let Ok(value) = outcome else {
3496                return;
3497            };
3498            // An index answered after this body request may name a newer
3499            // document while leaving the entry OnDisk (even at the same size).
3500            // Its authority also outranks this response; discard it so a next
3501            // demand read can fetch the current body.
3502            if self.full_index_authority.get() > issued
3503                || self.freshness.borrow().get(key).is_some_and(|&tick| tick > issued) {
3504                return;
3505            }
3506            {
3507                let mut entries = self.entries.borrow_mut();
3508                if !matches!(entries.get(key), Some(Entry::OnDisk { .. })) {
3509                    return;
3510                }
3511                self.stamp_local(key);
3512                match value {
3513                    Some(value) => entries.insert(key.to_string(), Entry::Resident(value)),
3514                    // Listed, then gone before we read it: the backend is
3515                    // authoritative, the listing was stale.
3516                    None => entries.remove(key),
3517                };
3518            }
3519            self.mutations.set(self.mutations.get().wrapping_add(1));
3520            if let Some(wake) = &self.wake {
3521                wake();
3522            }
3523        }
3524
3525
3526    }
3527
3528    impl MirrorStore {
3529        /// The explorer's listing of the current folder, read from the whole key
3530        /// space ([`ModelStore::browser_entries`] caches it).
3531        fn list_folder(&self, extensions: &[&str]) -> Vec<BrowserEntry> {
3532            let current = self.browser_dir.borrow().clone();
3533            if current == "/" {
3534                return vec![BrowserEntry {
3535                    name: "models".into(),
3536                    identity: "/models".into(),
3537                    is_dir: true,
3538                    size: None,
3539                    modified: None,
3540                }];
3541            }
3542            let relative_dir = current
3543                .strip_prefix("/models")
3544                .unwrap_or("")
3545                .trim_matches('/');
3546            let prefix = if relative_dir.is_empty() {
3547                String::new()
3548            } else {
3549                format!("{relative_dir}/")
3550            };
3551            let wanted: Vec<String> = extensions
3552                .iter()
3553                .map(|extension| extension.trim_start_matches('.').to_ascii_lowercase())
3554                .collect();
3555            let mut entries: BTreeMap<String, BrowserEntry> = BTreeMap::new();
3556            for (key, value) in self.entries.borrow().iter() {
3557                let (item, is_model) = if let Some(item) = key.strip_prefix(PREFIX) {
3558                    (item, true)
3559                } else if let Some(item) = key.strip_prefix(DIR_PREFIX) {
3560                    (item.trim_end_matches('/'), false)
3561                } else {
3562                    continue;
3563                };
3564                let Some(rest) = item.strip_prefix(&prefix) else {
3565                    continue;
3566                };
3567                if rest.is_empty() {
3568                    continue;
3569                }
3570                if let Some((child, _)) = rest.split_once('/') {
3571                    entries
3572                        .entry(child.to_string())
3573                        .or_insert_with(|| BrowserEntry {
3574                            name: child.to_string(),
3575                            identity: Self::child_path(&current, child),
3576                            is_dir: true,
3577                            size: None,
3578                            modified: None,
3579                        });
3580                } else if is_model {
3581                    let name = super::model_file_name(rest);
3582                    let lower = name.to_ascii_lowercase();
3583                    if wanted.is_empty()
3584                        || wanted
3585                            .iter()
3586                            .any(|extension| lower.ends_with(&format!(".{extension}")))
3587                    {
3588                        // Size = the mirrored JSON's byte length. `modified` stays
3589                        // None: the key space carries values, not timestamps.
3590                        entries.insert(
3591                            name.clone(),
3592                            BrowserEntry {
3593                                name,
3594                                identity: Self::virtual_model_path(item),
3595                                is_dir: false,
3596                                size: Some(value.len()),
3597                                modified: None,
3598                            },
3599                        );
3600                    }
3601                } else {
3602                    entries
3603                        .entry(rest.to_string())
3604                        .or_insert_with(|| BrowserEntry {
3605                            name: rest.to_string(),
3606                            identity: Self::child_path(&current, rest),
3607                            is_dir: true,
3608                            size: None,
3609                            modified: None,
3610                        });
3611                }
3612            }
3613            let mut entries: Vec<_> = entries.into_values().collect();
3614            entries.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then_with(|| a.name.cmp(&b.name)));
3615            entries
3616        }
3617    }
3618
3619    impl ModelStore for MirrorStore {
3620        #[cfg(feature = "automation")]
3621        fn files(&self, request: &brep_mcp_core::files::Request) -> Result<brep_mcp_core::files::Reply, String> {
3622            brep_mcp_core::files::execute(self, request)
3623        }
3624        #[cfg(feature = "automation")]
3625        fn files_settled(&self, request: &brep_mcp_core::files::Request) -> Option<Result<(), String>> { self.file_settlement(request) }
3626
3627        fn backend_label(&self) -> String {
3628            self.backend.label()
3629        }
3630
3631        fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
3632            self.backend.plm_client()
3633        }
3634
3635        fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
3636            self.backend.plm_revision(key)
3637        }
3638        fn note_checked_out(&self, key: &str) {
3639            self.backend.note_checked_out(key)
3640        }
3641        fn plm_written_by_us(&self, key: &str) -> bool {
3642            self.backend.plm_written_by_us(key)
3643        }
3644
3645        /// A feed move: what the server now lists for `keys` — or, `stale`,
3646        /// for everything — is folded into the entries as LAZY `OnDisk`
3647        /// rows, so a document another client, the web app or Generate made
3648        /// after this app booted is listed and opens without a reload (bodies
3649        /// load on demand, as at boot). See [`Self::reconcile`] for what is
3650        /// never touched.
3651        fn refresh_plm_index(&self, keys: &[String], stale: bool) {
3652            // A backend that keeps no index answers `Err` and nothing moves.
3653            if !stale && keys.is_empty() {
3654                return;
3655            }
3656            let store = self.clone();
3657            // The answer speaks for the server AS OF NOW: ticked before the
3658            // request leaves, so anything local that happens while it is on
3659            // the wire outranks it.
3660            let issued = self.tick();
3661            if stale {
3662                let request = self.backend.index_all();
3663                spawn(async move {
3664                    if let Ok(rows) = request.await {
3665                        store.reconcile(None, rows, issued);
3666                    }
3667                });
3668            } else {
3669                let asked: Vec<String> = keys.iter().map(|key| format!("{PREFIX}{key}")).collect();
3670                let request = self.backend.index_rows(keys);
3671                spawn(async move {
3672                    if let Ok(rows) = request.await {
3673                        store.reconcile(Some(&asked), rows, issued);
3674                    }
3675                });
3676            }
3677        }
3678        fn remember_saved_document(&self, name: &str, contents: &str) {
3679            let key = Self::key(name);
3680            self.stamp_local(&key);
3681            self.entries.borrow_mut().insert(key, Entry::Resident(contents.into()));
3682            self.mutations.set(self.mutations.get().wrapping_add(1));
3683        }
3684
3685        fn list(&self) -> Vec<String> {
3686            // `BTreeMap` iterates in key order, so the names come out sorted.
3687            self.entries
3688                .borrow()
3689                .keys()
3690                .filter_map(|key| key.strip_prefix(PREFIX).map(str::to_string))
3691                .collect()
3692        }
3693
3694        fn read(&self, name: &str) -> Option<String> {
3695            let key = Self::key(name);
3696            let held = self.entries.borrow().get(&key).cloned();
3697            match held {
3698                Some(Entry::Resident(value)) => Some(value),
3699                // Listed but not loaded: ask for it and answer `None` NOW — the
3700                // API is synchronous. The bytes land through `resolve`, which
3701                // moves the generation and wakes the frame, so a caller keyed on
3702                // the generation reads again. `residency` tells the two `None`s
3703                // apart.
3704                Some(Entry::OnDisk { .. }) => {
3705                    self.load(&key);
3706                    None
3707                }
3708                None => None,
3709            }
3710        }
3711
3712        fn canonical_identity(&self, name: &str) -> String {
3713            // The explorer's spelling of a document key (`browser_entries`);
3714            // a reserved name has no other spelling.
3715            match Self::key(name).strip_prefix(PREFIX) {
3716                Some(relative) => Self::virtual_model_path(relative),
3717                None => name.to_string(),
3718            }
3719        }
3720
3721        fn canonicalizer(&self) -> super::Canonicalizer {
3722            std::rc::Rc::new(|name| match Self::key(name).strip_prefix(PREFIX) {
3723                Some(relative) => Self::virtual_model_path(relative),
3724                None => name.to_string(),
3725            })
3726        }
3727
3728        fn residency(&self, name: &str) -> Residency {
3729            match self.entries.borrow().get(&Self::key(name)) {
3730                Some(Entry::Resident(_)) => Residency::Resident,
3731                Some(Entry::OnDisk { .. }) => Residency::OnDisk,
3732                None => Residency::Absent,
3733            }
3734        }
3735
3736        fn write(&self, name: &str, contents: &str) -> Result<(), String> {
3737            let key = Self::key(name);
3738            // What the backend holds as this write leaves (a PLM revision's
3739            // content hash): the base a retry sends if the write fails.
3740            let base = crate::plm::bom::revision_of_document(name)
3741                .and_then(|(part, revision)| self.plm_revision(&crate::plm::identity::document_key(&part, &revision)))
3742                .map(|row| row.content_hash)
3743                .unwrap_or_default();
3744            self.errors.note_base(&key, base);
3745            self.stamp_local(&key);
3746            self.entries
3747                .borrow_mut()
3748                .insert(key.clone(), Entry::Resident(contents.to_string()));
3749            // The mirror is authoritative for this session, so `Ok` is honest:
3750            // every subsequent read sees the new bytes. Durability is the
3751            // backend's job and its failure arrives via `take_persistence_errors`.
3752            let backend = self.backend.clone();
3753            let (put_key, contents) = (key.clone(), contents.to_string());
3754            self.push(name, &key, move || backend.put(&put_key, &contents));
3755            self.mutations.set(self.mutations.get().wrapping_add(1));
3756            Ok(())
3757        }
3758
3759        fn write_if(&self, name: &str, contents: &str, expected: &str) -> Result<(), String> {
3760            let key = Self::key(name);
3761            self.errors.note_base(&key, expected.to_string());
3762            self.stamp_local(&key);
3763            self.entries
3764                .borrow_mut()
3765                .insert(key.clone(), Entry::Resident(contents.to_string()));
3766            let backend = self.backend.clone();
3767            let (put_key, contents, expected) = (key.clone(), contents.to_string(), expected.to_string());
3768            self.push(name, &key, move || backend.put_if(&put_key, &contents, &expected));
3769            self.mutations.set(self.mutations.get().wrapping_add(1));
3770            Ok(())
3771        }
3772
3773        fn remove(&self, name: &str) -> Result<(), String> {
3774            let key = Self::key(name);
3775            self.stamp_local(&key);
3776            // The backend delete is pushed either way (the mirror may be
3777            // ahead of it), but only a delete that found something COUNTS —
3778            // the same rule `FileModelStore::remove` keeps.
3779            let existed = self.entries.borrow_mut().remove(&key).is_some();
3780            let backend = self.backend.clone();
3781            let delete_key = key.clone();
3782            self.push(name, &key, move || backend.delete(&delete_key));
3783            if existed {
3784                self.mutations.set(self.mutations.get().wrapping_add(1));
3785            }
3786            Ok(())
3787        }
3788
3789        // `browser_write` needs no bump of its own: it routes through `write`.
3790        fn mutation_generation(&self) -> u64 {
3791            self.mutations.get()
3792        }
3793
3794        fn pending_writes(&self) -> usize {
3795            self.pending()
3796        }
3797
3798        fn pending_writes_except(&self, names: &[&str]) -> usize {
3799            let skip: Vec<String> = names.iter().map(|name| Self::key(name)).collect();
3800            self.in_flight.borrow().iter().filter(|(key, _)| !skip.contains(key)).map(|(_, count)| *count).sum()
3801        }
3802
3803        fn take_persistence_errors(&self) -> Vec<String> {
3804            self.errors.drain()
3805        }
3806
3807        fn take_failed_writes(&self) -> Vec<String> {
3808            self.errors.take_failed_writes()
3809        }
3810
3811        fn write_failed(&self, name: &str) -> bool {
3812            self.errors.unsynced(&Self::key(name)).is_some()
3813        }
3814
3815        fn failed_write_base(&self, name: &str) -> Option<String> {
3816            self.errors.unsynced(&Self::key(name))
3817        }
3818
3819        fn browser_location(&self) -> String {
3820            // The RAW navigable path (breadcrumb / back-forward / path-edit rely on
3821            // this being feed-able straight back to `browser_navigate`); the human
3822            // "virtual filesystem" context lives in `backend_label`.
3823            self.browser_dir.borrow().clone()
3824        }
3825
3826        fn browser_entries(&self, extensions: &[&str]) -> Vec<BrowserEntry> {
3827            let key = {
3828                let entries = self.entries.borrow();
3829                ListingKey {
3830                    dir: self.browser_dir.borrow().clone(),
3831                    extensions: extensions.iter().map(|e| e.to_string()).collect(),
3832                    mutations: self.mutations.get(),
3833                    keys: entries.len(),
3834                    bytes: entries.values().map(Entry::len).sum(),
3835                }
3836            };
3837            if let Some((cached, listing)) = self.listing.borrow().as_ref() {
3838                if *cached == key {
3839                    return listing.clone();
3840                }
3841            }
3842            let listing = self.list_folder(extensions);
3843            *self.listing.borrow_mut() = Some((key, listing.clone()));
3844            listing
3845        }
3846
3847
3848        fn browser_enter(&self, identity: &str) -> Result<(), String> {
3849            if identity == "/models" || identity.starts_with("/models/") {
3850                *self.browser_dir.borrow_mut() = identity.trim_end_matches('/').to_string();
3851                Ok(())
3852            } else {
3853                Err("the browser virtual filesystem is rooted at /models".into())
3854            }
3855        }
3856
3857        fn browser_up(&self) -> Result<(), String> {
3858            let current = self.browser_dir.borrow().clone();
3859            if current == "/" {
3860                return Ok(());
3861            }
3862            let parent = current
3863                .rsplit_once('/')
3864                .map(|(parent, _)| parent)
3865                .unwrap_or("");
3866            *self.browser_dir.borrow_mut() = if parent.is_empty() {
3867                "/".into()
3868            } else {
3869                parent.into()
3870            };
3871            Ok(())
3872        }
3873
3874        fn browser_home(&self) -> Result<(), String> {
3875            *self.browser_dir.borrow_mut() = "/models".into();
3876            Ok(())
3877        }
3878
3879        fn browser_root(&self) -> Result<(), String> {
3880            *self.browser_dir.borrow_mut() = "/".into();
3881            Ok(())
3882        }
3883
3884        fn browser_navigate(&self, location: &str) -> Result<(), String> {
3885            let loc = location.trim_end_matches('/');
3886            let loc = if loc.is_empty() { "/" } else { loc };
3887            if loc == "/" || loc == "/models" || loc.starts_with("/models/") {
3888                *self.browser_dir.borrow_mut() = loc.to_string();
3889                Ok(())
3890            } else {
3891                Err("the browser virtual filesystem is rooted at /models".into())
3892            }
3893        }
3894
3895        fn browser_places(&self) -> Vec<BrowserPlace> {
3896            vec![
3897                BrowserPlace {
3898                    label: "Models".into(),
3899                    location: "/models".into(),
3900                    kind: PlaceKind::Models,
3901                },
3902                BrowserPlace {
3903                    label: "/".into(),
3904                    location: "/".into(),
3905                    kind: PlaceKind::Root,
3906                },
3907            ]
3908        }
3909
3910        fn browser_create_dir(&self, name: &str) -> Result<(), String> {
3911            if name.is_empty()
3912                || name == "."
3913                || name == ".."
3914                || name.contains('/')
3915                || name.contains('\\')
3916            {
3917                return Err("folder name must be one path component".into());
3918            }
3919            let current = self.browser_dir.borrow().clone();
3920            if !current.starts_with("/models") {
3921                return Err("folders can only be created under /models".into());
3922            }
3923            let relative = Self::child_path(&current, name)
3924                .trim_start_matches("/models/")
3925                .to_string();
3926            // A folder is a zero-length marker key; the explorer derives the tree
3927            // from the key prefixes alone.
3928            let key = format!("{DIR_PREFIX}{relative}/");
3929            self.entries
3930                .borrow_mut()
3931                .insert(key.clone(), Entry::Resident(String::new()));
3932            let backend = self.backend.clone();
3933            let put_key = key.clone();
3934            self.push(name, &key, move || backend.put(&put_key, ""));
3935            Ok(())
3936        }
3937
3938        fn browser_write(&self, name: &str, contents: &str) -> Result<String, String> {
3939            let file = model_display_name(name);
3940            if file.is_empty() {
3941                return Err("invalid file name".into());
3942            }
3943            let current = self.browser_dir.borrow().clone();
3944            if !current.starts_with("/models") {
3945                return Err("select a folder under /models".into());
3946            }
3947            let identity = Self::child_path(&current, &super::model_file_name(&file));
3948            self.write(&identity, contents)?;
3949            Ok(identity)
3950        }
3951    }
3952}
3953
3954#[cfg(target_arch = "wasm32")]
3955#[path = "store_host.rs"]
3956mod host;
3957
3958// --- Browser: IndexedDB documents + download / upload interchange --------------
3959#[cfg(target_arch = "wasm32")]
3960mod web_model {
3961    use super::mirror_store::{
3962        BackendFuture, MirrorStore, StoreBackend, UnavailableBackend, DIR_PREFIX, FILE_PREFIX, PREFIX,
3963    };
3964    use super::{
3965        model_display_name, BrowserEntry, BrowserPlace, ImportedFile, ModelStore,
3966    };
3967    use std::cell::RefCell;
3968    use std::future::Future;
3969    use std::pin::Pin;
3970    use std::rc::Rc;
3971    use std::task::{Context, Poll, Waker};
3972    use wasm_bindgen::prelude::*;
3973    use wasm_bindgen::JsCast;
3974
3975    // The origin-private persistent store on the web is **IndexedDB**. It replaced
3976    // `localStorage`, whose ~5-10 MB per-origin quota cannot hold a single native
3977    // BREP payload (a measured STEP import: ~35 MB), and it is the only browser
3978    // store that is both large and enumerable without a permission gesture (unlike
3979    // the File System Access API, which fails headless). Its API is ASYNC, hence
3980    // the mirror in [`mirror_store`](super::mirror_store); the key scheme is the
3981    // localStorage one, byte for byte. **Download + upload** below still bridge to
3982    // the user's REAL filesystem for portability.
3983    const DB_NAME: &str = "brep-app";
3984    const DB_VERSION: u32 = 1;
3985    /// The single key/value object store; keys are the `brep-app:*` strings.
3986    const STORE_NAME: &str = "kv";
3987    /// The cross-tab change channel. IndexedDB is shared by every tab of the
3988    /// origin but says NOTHING when another connection writes it, so each tab's
3989    /// hydrated mirror would sit at its boot-time contents until reloaded — save a
3990    /// part in one tab, and the tab holding the assembly cannot insert it. Every
3991    /// tab posts the key it just committed here and re-reads the keys it is told
3992    /// about; a [`BroadcastChannel`](web_sys::BroadcastChannel) never echoes to
3993    /// the object that sent the message, so a tab hears only the others.
3994    const CHANNEL_NAME: &str = "brep-app:store";
3995
3996    thread_local! {
3997        /// The single hidden `<input type=file>`, created once and reused.
3998        static IMPORT_INPUT: RefCell<Option<web_sys::HtmlInputElement>> = const { RefCell::new(None) };
3999        /// The most recent completed upload, awaiting the panel's poll.
4000        static IMPORTED: RefCell<Option<ImportedFile>> = const { RefCell::new(None) };
4001        /// The file chooser's own input and slot ([`ModelStore::begin_pick_file`]):
4002        /// a picked attachment must never be taken by the model-import lane.
4003        static PICK_INPUT: RefCell<Option<web_sys::HtmlInputElement>> = const { RefCell::new(None) };
4004        static PICKED: RefCell<Option<ImportedFile>> = const { RefCell::new(None) };
4005        /// The egui context, so an ASYNC callback (a `FileReader` load, a failed
4006        /// IndexedDB write) can wake the reactive eframe loop (the app only
4007        /// repaints on input events + explicit requests). Without it a completed
4008        /// upload — or a "your model did not save" notice — sits unshown until the
4009        /// user happens to move the mouse. Seeded once at boot via [`set_repaint_ctx`].
4010        static REPAINT_CTX: RefCell<Option<eframe::egui::Context>> = const { RefCell::new(None) };
4011        /// The store built by [`hydrate`] inside the async wasm entry point,
4012        /// waiting for `BrepApp::new` to pick it up through
4013        /// [`default_model_store`](super::default_model_store). The hand-off is a
4014        /// thread-local rather than a closure capture so the app constructor keeps
4015        /// its platform-free signature.
4016        static BOOT_STORE: RefCell<Option<IdbModelStore>> = const { RefCell::new(None) };
4017        /// Why a page the PLM serves is on IndexedDB instead (the PLM refused
4018        /// its session), shown once on the first frame.
4019        static BOOT_NOTICE: RefCell<Option<String>> = const { RefCell::new(None) };
4020        /// The same reason, kept for the PLM tab after the notice is drained.
4021        static BOOT_REASON: RefCell<Option<String>> = const { RefCell::new(None) };
4022    }
4023
4024    fn set_boot_notice(notice: String) {
4025        BOOT_REASON.with(|r| *r.borrow_mut() = Some(notice.clone()));
4026        BOOT_NOTICE.with(|n| *n.borrow_mut() = Some(format!("{notice} — this page uses the browser's storage")));
4027    }
4028
4029    /// Register the egui context used to wake the frame loop when an async browser
4030    /// upload — or a write-behind persistence failure — completes. Called once from
4031    /// the app shell at construction.
4032    pub fn set_repaint_ctx(ctx: eframe::egui::Context) {
4033        REPAINT_CTX.with(|c| *c.borrow_mut() = Some(ctx));
4034    }
4035
4036    /// Ask the reactive frame loop for a repaint. Reads `REPAINT_CTX` at CALL time,
4037    /// so it does not matter that the store is built (during boot) before the app
4038    /// shell registers the context.
4039    /// A task that asks for a frame after every poll; see [`super::spawn_waking`].
4040    pub(crate) struct WakeOnPoll(pub(crate) std::pin::Pin<Box<dyn Future<Output = ()>>>);
4041
4042    impl Future for WakeOnPoll {
4043        type Output = ();
4044        fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<()> {
4045            let poll = self.0.as_mut().poll(cx);
4046            wake_frame_loop();
4047            poll
4048        }
4049    }
4050
4051    pub(crate) fn wake_frame_loop() {
4052        REPAINT_CTX.with(|c| {
4053            if let Some(ctx) = c.borrow().as_ref() {
4054                ctx.request_repaint();
4055            }
4056        });
4057    }
4058
4059    // --- IndexedDB request/transaction -> Future ----------------------------------
4060    // Hand-rolled rather than pulling `indexed_db_futures`: this crate deliberately
4061    // keeps its wasm dependency tree thin (see the `ehttp` note in Cargo.toml about
4062    // the `getrandom` dep-tree problem), and the whole adapter is the ~60 lines
4063    // below. It owns its `Closure`s — dropping the future clears the handlers — so
4064    // a session of saves does not leak a pair of JS closures per write, which a
4065    // `Closure::forget()` sketch would.
4066
4067    #[derive(Default)]
4068    struct Settled {
4069        outcome: Option<Result<JsValue, String>>,
4070        waker: Option<Waker>,
4071    }
4072
4073    /// Which DOM event pair the future is listening to. Kept so `Drop` can detach
4074    /// the handlers (and with them the Rust closures' reference back to the target).
4075    enum EventSource {
4076        Request(web_sys::IdbRequest),
4077        Transaction(web_sys::IdbTransaction),
4078    }
4079
4080    /// One IndexedDB completion, as a `Future`.
4081    struct IdbFuture {
4082        source: EventSource,
4083        settled: Rc<RefCell<Settled>>,
4084        /// Owned so the closures live exactly as long as the future.
4085        _handlers: Vec<Closure<dyn FnMut(web_sys::Event)>>,
4086    }
4087
4088    fn settle(settled: &Rc<RefCell<Settled>>, outcome: Result<JsValue, String>) {
4089        let waker = {
4090            let mut settled = settled.borrow_mut();
4091            if settled.outcome.is_none() {
4092                settled.outcome = Some(outcome);
4093            }
4094            settled.waker.take()
4095        };
4096        if let Some(waker) = waker {
4097            waker.wake();
4098        }
4099    }
4100
4101    fn request_error(request: &web_sys::IdbRequest) -> String {
4102        request
4103            .error()
4104            .ok()
4105            .flatten()
4106            .map(|error| format!("{}: {}", error.name(), error.message()))
4107            .unwrap_or_else(|| "IndexedDB request failed".into())
4108    }
4109
4110    fn js_error(value: &JsValue) -> String {
4111        value
4112            .as_string()
4113            .or_else(|| js_sys::Reflect::get(value, &JsValue::from_str("message")).ok()?.as_string())
4114            .unwrap_or_else(|| format!("{value:?}"))
4115    }
4116
4117    /// Resolve when `request` succeeds, with its `result`.
4118    fn on_request(request: web_sys::IdbRequest) -> IdbFuture {
4119        let settled = Rc::new(RefCell::new(Settled::default()));
4120        let success = {
4121            let settled = settled.clone();
4122            let request = request.clone();
4123            Closure::wrap(Box::new(move |_event: web_sys::Event| {
4124                let value = request.result().unwrap_or(JsValue::UNDEFINED);
4125                settle(&settled, Ok(value));
4126            }) as Box<dyn FnMut(web_sys::Event)>)
4127        };
4128        let failure = {
4129            let settled = settled.clone();
4130            let request = request.clone();
4131            Closure::wrap(Box::new(move |_event: web_sys::Event| {
4132                settle(&settled, Err(request_error(&request)));
4133            }) as Box<dyn FnMut(web_sys::Event)>)
4134        };
4135        request.set_onsuccess(Some(success.as_ref().unchecked_ref()));
4136        request.set_onerror(Some(failure.as_ref().unchecked_ref()));
4137        IdbFuture {
4138            source: EventSource::Request(request),
4139            settled,
4140            _handlers: vec![success, failure],
4141        }
4142    }
4143
4144    /// Resolve when `transaction` COMMITS.
4145    ///
4146    /// A write must be awaited here, not on the `put` request's `onsuccess`: the
4147    /// request succeeds before the transaction commits, and a page reload can abort
4148    /// an uncommitted `readwrite` transaction. For a multi-megabyte payload that
4149    /// window is real, and "the save is durable" is exactly the claim the pending
4150    /// counter and the reload test rest on.
4151    fn on_transaction(transaction: web_sys::IdbTransaction) -> IdbFuture {
4152        let settled = Rc::new(RefCell::new(Settled::default()));
4153        let complete = {
4154            let settled = settled.clone();
4155            Closure::wrap(Box::new(move |_event: web_sys::Event| {
4156                settle(&settled, Ok(JsValue::UNDEFINED));
4157            }) as Box<dyn FnMut(web_sys::Event)>)
4158        };
4159        let describe = {
4160            let transaction = transaction.clone();
4161            move |fallback: &str| {
4162                transaction
4163                    .error()
4164                    .map(|error| format!("{}: {}", error.name(), error.message()))
4165                    .unwrap_or_else(|| fallback.to_string())
4166            }
4167        };
4168        let failure = {
4169            let settled = settled.clone();
4170            let describe = describe.clone();
4171            Closure::wrap(Box::new(move |_event: web_sys::Event| {
4172                settle(&settled, Err(describe("IndexedDB transaction failed")));
4173            }) as Box<dyn FnMut(web_sys::Event)>)
4174        };
4175        let abort = {
4176            let settled = settled.clone();
4177            Closure::wrap(Box::new(move |_event: web_sys::Event| {
4178                settle(
4179                    &settled,
4180                    Err(describe("IndexedDB transaction aborted (quota?)")),
4181                );
4182            }) as Box<dyn FnMut(web_sys::Event)>)
4183        };
4184        transaction.set_oncomplete(Some(complete.as_ref().unchecked_ref()));
4185        transaction.set_onerror(Some(failure.as_ref().unchecked_ref()));
4186        transaction.set_onabort(Some(abort.as_ref().unchecked_ref()));
4187        IdbFuture {
4188            source: EventSource::Transaction(transaction),
4189            settled,
4190            _handlers: vec![complete, failure, abort],
4191        }
4192    }
4193
4194    impl Future for IdbFuture {
4195        type Output = Result<JsValue, String>;
4196
4197        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
4198            let mut settled = self.settled.borrow_mut();
4199            if let Some(outcome) = settled.outcome.take() {
4200                return Poll::Ready(outcome);
4201            }
4202            settled.waker = Some(cx.waker().clone());
4203            Poll::Pending
4204        }
4205    }
4206
4207    impl Drop for IdbFuture {
4208        fn drop(&mut self) {
4209            // Detach the handlers, breaking the target -> closure -> target cycle
4210            // so the closures we own are actually freed.
4211            match &self.source {
4212                EventSource::Request(request) => {
4213                    request.set_onsuccess(None);
4214                    request.set_onerror(None);
4215                }
4216                EventSource::Transaction(transaction) => {
4217                    transaction.set_oncomplete(None);
4218                    transaction.set_onerror(None);
4219                    transaction.set_onabort(None);
4220                }
4221            }
4222        }
4223    }
4224
4225    // --- the IndexedDB backend -----------------------------------------------------
4226
4227    /// [`StoreBackend`] over one IndexedDB object store. The ONLY place in the
4228    /// crate that knows what IndexedDB is.
4229    pub(super) struct IdbBackend {
4230        db: web_sys::IdbDatabase,
4231        /// The cross-tab notification channel (see [`CHANNEL_NAME`]), or `None`
4232        /// where the browser does not offer one — then this tab still saves and
4233        /// still reads, it just will not hear about another tab's saves.
4234        channel: Option<web_sys::BroadcastChannel>,
4235    }
4236
4237    impl IdbBackend {
4238        /// Open (creating on first use) the application database. `Err` on any
4239        /// browser that blocks storage — private windows, "block all cookies"
4240        /// setups — which the caller turns into a loud, non-persisting session.
4241        ///
4242        /// `channel` is the tab's ONE [`BroadcastChannel`](web_sys::BroadcastChannel)
4243        /// handle, shared with [`hydrate`]'s listener: posting and listening on the
4244        /// same object is what keeps a tab from hearing its own writes back (the
4245        /// channel never delivers a message to the object that sent it).
4246        async fn open(channel: Option<web_sys::BroadcastChannel>) -> Result<Self, String> {
4247            let factory = web_sys::window()
4248                .ok_or("no window")?
4249                .indexed_db()
4250                .map_err(|e| js_error(&e))?
4251                .ok_or("no indexedDB on this window")?;
4252            let request = factory
4253                .open_with_u32(DB_NAME, DB_VERSION)
4254                .map_err(|e| js_error(&e))?;
4255
4256            // Create the object store on first open / version bump. The request is
4257            // captured directly (rather than read off the event target) so no
4258            // `EventTarget` binding is needed.
4259            let upgrading = request.clone();
4260            let upgrade = Closure::wrap(Box::new(move |_event: web_sys::Event| {
4261                if let Ok(value) = upgrading.result() {
4262                    if let Ok(db) = value.dyn_into::<web_sys::IdbDatabase>() {
4263                        // Errors here mean the store already exists — harmless.
4264                        let _ = db.create_object_store(STORE_NAME);
4265                    }
4266                }
4267            }) as Box<dyn FnMut(web_sys::Event)>);
4268            request.set_onupgradeneeded(Some(upgrade.as_ref().unchecked_ref()));
4269
4270            let opened = on_request(request.clone().unchecked_into::<web_sys::IdbRequest>()).await;
4271            request.set_onupgradeneeded(None);
4272            drop(upgrade);
4273
4274            let db = opened?
4275                .dyn_into::<web_sys::IdbDatabase>()
4276                .map_err(|_| "IndexedDB open returned no database".to_string())?;
4277            Ok(Self { db, channel })
4278        }
4279
4280        /// Tell the other tabs of this origin that `key` changed, so their mirrors
4281        /// can re-read it. Only the FILESYSTEM key space is announced: `@settings`,
4282        /// `@dock_layout`, `@recovery` and friends are per-tab working state, and
4283        /// syncing them live would have two windows fight over one layout.
4284        fn announce(channel: &Option<web_sys::BroadcastChannel>, key: &str) {
4285            if !key.starts_with(PREFIX) && !key.starts_with(DIR_PREFIX) && !key.starts_with(FILE_PREFIX) {
4286                return;
4287            }
4288            if let Some(channel) = channel {
4289                // A failed post costs this tab nothing it can act on — the write
4290                // itself landed — so it is dropped rather than toasted.
4291                let _ = channel.post_message(&JsValue::from_str(key));
4292            }
4293        }
4294
4295        /// Start a transaction and reach its object store. The transaction handle
4296        /// is returned so a write can await its COMMIT.
4297        fn transact(
4298            &self,
4299            mode: web_sys::IdbTransactionMode,
4300        ) -> Result<(web_sys::IdbTransaction, web_sys::IdbObjectStore), String> {
4301            let transaction = self
4302                .db
4303                .transaction_with_str_and_mode(STORE_NAME, mode)
4304                .map_err(|e| js_error(&e))?;
4305            let store = transaction.object_store(STORE_NAME).map_err(|e| js_error(&e))?;
4306            Ok((transaction, store))
4307        }
4308    }
4309
4310    impl StoreBackend for IdbBackend {
4311        fn label(&self) -> String {
4312            "browser storage (IndexedDB) · download/upload for files".into()
4313        }
4314
4315        /// IndexedDB commits `readwrite` transactions in creation order, and
4316        /// `put` / `delete` create theirs synchronously — so the mirror issues
4317        /// every write at once, exactly as it did before the send queue existed.
4318        fn orders_writes_per_key(&self) -> bool {
4319            true
4320        }
4321
4322        fn load_all(&self) -> BackendFuture<Vec<(String, String)>> {
4323            // Two whole-store requests in ONE readonly transaction rather than a
4324            // cursor: `getAllKeys` and `getAll` both come back in key order, so
4325            // zipping them reconstructs the key space in one round trip each.
4326            let started = (|| -> Result<(IdbFuture, IdbFuture), String> {
4327                let (_transaction, store) = self.transact(web_sys::IdbTransactionMode::Readonly)?;
4328                let keys = store.get_all_keys().map_err(|e| js_error(&e))?;
4329                let values = store.get_all().map_err(|e| js_error(&e))?;
4330                Ok((on_request(keys), on_request(values)))
4331            })();
4332            Box::pin(async move {
4333                let (keys, values) = started?;
4334                let keys = js_sys::Array::from(&keys.await?);
4335                let values = js_sys::Array::from(&values.await?);
4336                if keys.length() != values.length() {
4337                    return Err("IndexedDB returned mismatched keys and values".into());
4338                }
4339                let mut entries = Vec::with_capacity(keys.length() as usize);
4340                for i in 0..keys.length() {
4341                    let (Some(key), Some(value)) =
4342                        (keys.get(i).as_string(), values.get(i).as_string())
4343                    else {
4344                        // A non-string entry is not ours; skipping it is safer than
4345                        // failing the whole hydrate.
4346                        continue;
4347                    };
4348                    entries.push((key, value));
4349                }
4350                Ok(entries)
4351            })
4352        }
4353
4354        #[cfg(feature = "automation")]
4355        fn move_files(&self, entries: Vec<(String, String, String)>) -> BackendFuture<()> {
4356            let started = (|| -> Result<IdbFuture, String> {
4357                let (transaction, store) = self.transact(web_sys::IdbTransactionMode::Readwrite)?;
4358                for (old, new, value) in &entries {
4359                    let put = store.put_with_key(&JsValue::from_str(value), &JsValue::from_str(new));
4360                    let delete = put.and_then(|_| store.delete(&JsValue::from_str(old)));
4361                    if let Err(error) = delete {
4362                        let _ = transaction.abort();
4363                        return Err(js_error(&error));
4364                    }
4365                }
4366                Ok(on_transaction(transaction))
4367            })();
4368            let channel = self.channel.clone();
4369            Box::pin(async move {
4370                started?.await?;
4371                for (old, new, _) in entries {
4372                    Self::announce(&channel, &old);
4373                    Self::announce(&channel, &new);
4374                }
4375                Ok(())
4376            })
4377        }
4378
4379        fn get(&self, key: &str) -> BackendFuture<Option<String>> {
4380            let started = (|| -> Result<IdbFuture, String> {
4381                let (_transaction, store) = self.transact(web_sys::IdbTransactionMode::Readonly)?;
4382                let request = store.get(&JsValue::from_str(key)).map_err(|e| js_error(&e))?;
4383                Ok(on_request(request))
4384            })();
4385            Box::pin(async move {
4386                // An absent key resolves to `undefined`, which is the `None` the
4387                // mirror turns into a removal.
4388                Ok(started?.await?.as_string())
4389            })
4390        }
4391
4392        fn put(&self, key: &str, value: &str) -> BackendFuture<()> {
4393            // The transaction is created and the request issued SYNCHRONOUSLY, so
4394            // two writes of the same key commit in call order (IndexedDB commits
4395            // `readwrite` transactions in creation order) no matter how the futures
4396            // are later polled — the per-key FIFO obligation in `StoreBackend`.
4397            let started = (|| -> Result<IdbFuture, String> {
4398                let (transaction, store) =
4399                    self.transact(web_sys::IdbTransactionMode::Readwrite)?;
4400                store
4401                    .put_with_key(&JsValue::from_str(value), &JsValue::from_str(key))
4402                    .map_err(|e| js_error(&e))?;
4403                Ok(on_transaction(transaction))
4404            })();
4405            let channel = self.channel.clone();
4406            let key = key.to_string();
4407            Box::pin(async move {
4408                started?.await?;
4409                // AFTER the commit, never before: a tab told about the key reads
4410                // it back immediately, and must not be able to read the old bytes.
4411                Self::announce(&channel, &key);
4412                Ok(())
4413            })
4414        }
4415
4416        fn delete(&self, key: &str) -> BackendFuture<()> {
4417            let started = (|| -> Result<IdbFuture, String> {
4418                let (transaction, store) =
4419                    self.transact(web_sys::IdbTransactionMode::Readwrite)?;
4420                store
4421                    .delete(&JsValue::from_str(key))
4422                    .map_err(|e| js_error(&e))?;
4423                Ok(on_transaction(transaction))
4424            })();
4425            let channel = self.channel.clone();
4426            let key = key.to_string();
4427            Box::pin(async move {
4428                started?.await?;
4429                Self::announce(&channel, &key);
4430                Ok(())
4431            })
4432        }
4433    }
4434
4435    // --- boot ----------------------------------------------------------------------
4436
4437    /// Bring up browser persistence and hydrate the whole key space into memory.
4438    ///
4439    /// Called from the async wasm entry point BEFORE `eframe::WebRunner::start`, so
4440    /// by the time any synchronous [`ModelStore::read`] can run, the mirror is
4441    /// complete — that ordering is the entire reason the trait stays synchronous.
4442    ///
4443    /// On failure there is NO quiet fallback: the session gets an
4444    /// [`UnavailableBackend`], which keeps the app usable in memory while saying so
4445    /// in the panel header and toasting every write that does not persist.
4446    pub(super) async fn hydrate() {
4447        let wake: Rc<dyn Fn()> = Rc::new(wake_frame_loop);
4448        if super::host::available() {
4449            let backend: Rc<dyn StoreBackend> = Rc::new(super::host::HostBackend);
4450            let core = match backend.load_index().await {
4451                Ok(entries) => MirrorStore::from_index(backend, entries, Some(wake)),
4452                Err(error) => unavailable(format!("OrcaSlicer storage: {error}"), Some(wake)),
4453            };
4454            install_verification_hooks(&core);
4455            BOOT_STORE.with(|c| *c.borrow_mut() = Some(IdbModelStore { core }));
4456            return;
4457        }
4458        let channel = web_sys::BroadcastChannel::new(CHANNEL_NAME).ok();
4459        let core = match IdbBackend::open(channel.clone()).await {
4460            Ok(backend) => {
4461                let mut backend: Rc<dyn StoreBackend> = Rc::new(backend);
4462                // A page the PLM serves (D6, `/cad/app/`) keeps its documents
4463                // and preferences there, with `@recovery` in IndexedDB first.
4464                // A refusal keeps the page on IndexedDB and says why; a page
4465                // served from anywhere else never asks.
4466                match crate::plm::backend::open_web_session(backend.clone()).await {
4467                    Ok(Some(plm)) => backend = plm,
4468                    Ok(None) => {}
4469                    Err(sentence) => set_boot_notice(format!("PLM: {sentence}")),
4470                }
4471                // `load_index`'s default IS `load_all` with every value
4472                // resident, so a browser origin still hydrates whole; the
4473                // index-only PLM keeps document bodies unloaded until an actual
4474                // read. Never prefetch the catalog: its bodies can exceed WASM memory.
4475                match backend.load_index().await {
4476                    Ok(entries) => {
4477                        let core = MirrorStore::from_index(backend, entries, Some(wake));
4478                        // Hydration is the LAST all-at-once read. From here the
4479                        // mirror keeps up with the other tabs one key at a time,
4480                        // so a part saved next door is insertable here without a
4481                        // reload.
4482                        listen_for_other_tabs(&core, channel);
4483                        core
4484                    }
4485                    // The database opened but would not read. Writing against a
4486                    // half-known key space could overwrite documents the mirror
4487                    // never saw, so treat it as unavailable rather than risk that.
4488                    Err(message) => unavailable(
4489                        format!("IndexedDB could not be read ({message})"),
4490                        Some(wake),
4491                    ),
4492                }
4493            }
4494            Err(message) => unavailable(format!("IndexedDB unavailable ({message})"), Some(wake)),
4495        };
4496        install_verification_hooks(&core);
4497        BOOT_STORE.with(|c| *c.borrow_mut() = Some(IdbModelStore { core }));
4498    }
4499
4500    /// Subscribe this tab's mirror to the other tabs' commits: each message is a
4501    /// key one of them just wrote, and the mirror re-reads exactly that key.
4502    ///
4503    /// The handler is `forget()`-ed — one per tab, alive for the session, the same
4504    /// pattern the verification hooks use. It holds a `MirrorStore` clone, which is
4505    /// another handle on the SAME session state, not a copy of it.
4506    fn listen_for_other_tabs(core: &MirrorStore, channel: Option<web_sys::BroadcastChannel>) {
4507        let Some(channel) = channel else {
4508            return;
4509        };
4510        let core = core.clone();
4511        let on_message = Closure::wrap(Box::new(move |event: web_sys::MessageEvent| {
4512            if let Some(key) = event.data().as_string() {
4513                core.refresh_key(key);
4514            }
4515        }) as Box<dyn FnMut(web_sys::MessageEvent)>);
4516        channel.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
4517        on_message.forget();
4518        // The channel object itself must outlive this call — a dropped
4519        // `BroadcastChannel` stops delivering — and it does: `IdbBackend` holds the
4520        // same handle for the life of the session.
4521    }
4522
4523    /// A session with no persistence: empty, in-memory, and loud about it.
4524    fn unavailable(reason: String, wake: Option<Rc<dyn Fn()>>) -> MirrorStore {
4525        let core = MirrorStore::new(
4526            Rc::new(UnavailableBackend::new(reason.clone())),
4527            Vec::new(),
4528            wake,
4529        );
4530        // Seed the notice channel so the FIRST frame tells the user, before they
4531        // have saved anything and discovered it the hard way.
4532        core.report(if super::host::available() {
4533            format!("{reason} — this session will not be saved; check OrcaSlicer plugin permissions and reload")
4534        } else {
4535            format!("{reason} — this session will not be saved; use Download to keep your work")
4536        });
4537        core
4538    }
4539
4540    /// Hand the hydrated store to `BrepApp::new`. If boot never ran (no code path
4541    /// does that today), the app still starts — non-persisting and saying so.
4542    pub(super) fn take_boot_store() -> Box<dyn ModelStore> {
4543        let store = BOOT_STORE.with(|c| c.borrow_mut().take()).unwrap_or_else(|| {
4544            let wake: Rc<dyn Fn()> = Rc::new(wake_frame_loop);
4545            IdbModelStore {
4546                core: unavailable("storage was never initialised".into(), Some(wake)),
4547            }
4548        });
4549        Box::new(store)
4550    }
4551
4552    // --- verification hooks ---------------------------------------------------------
4553
4554    /// Publish `window.__brepStore*` handles onto the LIVE store, in the same
4555    /// spirit as the app shell's `__brep*` state globals: the headed verifier needs
4556    /// to write a payload far larger than any UI gesture can type, then prove it
4557    /// survived a reload. `__brepStorePending` is what makes that check non-racy —
4558    /// it reaches zero only once the backing transaction has COMMITTED.
4559    /// `__brepStoreRead` is the read side of the same seam: a script that saves
4560    /// through the UI has to be able to look at what landed.
4561    fn install_verification_hooks(core: &MirrorStore) {
4562        let Some(window) = web_sys::window() else {
4563            return;
4564        };
4565        let publish = |name: &str, value: &JsValue| {
4566            let _ = js_sys::Reflect::set(&window, &JsValue::from_str(name), value);
4567        };
4568
4569        let store = core.clone();
4570        let write = Closure::wrap(Box::new(move |name: String, contents: String| -> JsValue {
4571            match store.write(&name, &contents) {
4572                Ok(()) => JsValue::NULL,
4573                Err(message) => JsValue::from_str(&message),
4574            }
4575        }) as Box<dyn FnMut(String, String) -> JsValue>);
4576        publish("__brepStoreWrite", write.as_ref());
4577        write.forget();
4578
4579        let store = core.clone();
4580        let len = Closure::wrap(Box::new(move |name: String| -> f64 {
4581            store.len_of(&name).map(|n| n as f64).unwrap_or(-1.0)
4582        }) as Box<dyn FnMut(String) -> f64>);
4583        publish("__brepStoreLen", len.as_ref());
4584        len.forget();
4585
4586        // The READ sibling of `__brepStoreWrite`. Without it a headed script can
4587        // only prove a save happened, not WHAT was saved: the assemblies sweep
4588        // used to read the document straight out of `localStorage`, which the
4589        // IndexedDB migration silently emptied.
4590        let store = core.clone();
4591        let read = Closure::wrap(Box::new(move |name: String| -> JsValue {
4592            match store.read(&name) {
4593                Some(contents) => JsValue::from_str(&contents),
4594                None => JsValue::NULL,
4595            }
4596        }) as Box<dyn FnMut(String) -> JsValue>);
4597        publish("__brepStoreRead", read.as_ref());
4598        read.forget();
4599
4600        let store = core.clone();
4601        let list = Closure::wrap(Box::new(move || -> JsValue {
4602            JsValue::from_str(&serde_json::to_string(&store.list()).unwrap_or_default())
4603        }) as Box<dyn FnMut() -> JsValue>);
4604        publish("__brepStoreList", list.as_ref());
4605        list.forget();
4606
4607        let store = core.clone();
4608        let errors = Closure::wrap(Box::new(move || -> JsValue {
4609            JsValue::from_str(&serde_json::to_string(&store.error_history()).unwrap_or_default())
4610        }) as Box<dyn FnMut() -> JsValue>);
4611        publish("__brepStoreErrors", errors.as_ref());
4612        errors.forget();
4613
4614        // The DELETE sibling of `__brepStoreWrite`, so the two-tab check in
4615        // `web/verify_store.mjs` can prove the second half of live storage: a
4616        // document removed in one tab leaves the other tab's list as well.
4617        let store = core.clone();
4618        let remove = Closure::wrap(Box::new(move |name: String| -> JsValue {
4619            match store.remove(&name) {
4620                Ok(()) => JsValue::NULL,
4621                Err(message) => JsValue::from_str(&message),
4622            }
4623        }) as Box<dyn FnMut(String) -> JsValue>);
4624        publish("__brepStoreRemove", remove.as_ref());
4625        remove.forget();
4626
4627        let store = core.clone();
4628        let pending = Closure::wrap(Box::new(move || -> f64 { store.pending() as f64 })
4629            as Box<dyn FnMut() -> f64>);
4630        publish("__brepStorePending", pending.as_ref());
4631        pending.forget();
4632    }
4633
4634    // --- real-file interchange (download / upload) ----------------------------------
4635    // Free functions, not methods: they are pure browser plumbing with no store
4636    // state, and keeping them out of the store type leaves `IdbModelStore` as a
4637    // thin seam between the mirror and this lane.
4638
4639    /// Lazily create the reusable hidden file input, wiring its `change` handler
4640    /// (which reads the chosen file and stashes it for `take_import`). `accept` is
4641    /// (re)applied every call so the picker's filter matches the current lane (the
4642    /// `.nbrep` model lane vs. a `.step` import lane).
4643    /// The file chooser's hidden input, created once: any file, its own name
4644    /// kept whole, its bytes into [`PICKED`].
4645    fn pick_input() -> Option<web_sys::HtmlInputElement> {
4646        if let Some(existing) = PICK_INPUT.with(|c| c.borrow().clone()) {
4647            return Some(existing);
4648        }
4649        let document = web_sys::window()?.document()?;
4650        let input: web_sys::HtmlInputElement = document.create_element("input").ok()?.dyn_into().ok()?;
4651        input.set_type("file");
4652        input.set_hidden(true);
4653        let input_for_cb = input.clone();
4654        let onchange = Closure::wrap(Box::new(move |_e: web_sys::Event| {
4655            let Some(file) = input_for_cb.files().and_then(|files| files.get(0)) else { return };
4656            let name = file.name();
4657            let Ok(reader) = web_sys::FileReader::new() else { return };
4658            let reader_for_load = reader.clone();
4659            let onload = Closure::wrap(Box::new(move |_e: web_sys::Event| {
4660                if let Ok(value) = reader_for_load.result() {
4661                    let bytes = js_sys::Uint8Array::new(&value).to_vec();
4662                    PICKED.with(|c| *c.borrow_mut() = Some(ImportedFile { name: name.clone(), bytes }));
4663                    wake_frame_loop();
4664                }
4665            }) as Box<dyn FnMut(web_sys::Event)>);
4666            reader.set_onload(Some(onload.as_ref().unchecked_ref()));
4667            onload.forget();
4668            let _ = reader.read_as_array_buffer(&file);
4669        }) as Box<dyn FnMut(web_sys::Event)>);
4670        input.set_onchange(Some(onchange.as_ref().unchecked_ref()));
4671        onchange.forget();
4672        if let Some(body) = document.body() {
4673            let _ = body.append_child(&input);
4674        }
4675        PICK_INPUT.with(|c| *c.borrow_mut() = Some(input.clone()));
4676        Some(input)
4677    }
4678
4679    fn ensure_input(accept: &str) -> Option<web_sys::HtmlInputElement> {
4680        if let Some(existing) = IMPORT_INPUT.with(|c| c.borrow().clone()) {
4681            existing.set_accept(accept);
4682            return Some(existing);
4683        }
4684        let document = web_sys::window()?.document()?;
4685        let input: web_sys::HtmlInputElement =
4686            document.create_element("input").ok()?.dyn_into().ok()?;
4687        input.set_type("file");
4688        input.set_accept(accept);
4689        input.set_hidden(true);
4690
4691        // Read bytes so binary STL is not corrupted at the browser boundary.
4692        let input_for_cb = input.clone();
4693        let onchange = Closure::wrap(Box::new(move |_e: web_sys::Event| {
4694            let Some(files) = input_for_cb.files() else { return };
4695            let Some(file) = files.get(0) else { return };
4696            let name = file.name();
4697            let Ok(reader) = web_sys::FileReader::new() else { return };
4698            let reader_for_load = reader.clone();
4699            let onload = Closure::wrap(Box::new(move |_e: web_sys::Event| {
4700                if let Ok(value) = reader_for_load.result() {
4701                    let bytes = js_sys::Uint8Array::new(&value).to_vec();
4702                    IMPORTED.with(|c| *c.borrow_mut() = Some(ImportedFile {
4703                        name: model_display_name(&name),
4704                        bytes,
4705                    }));
4706                    // Wake the reactive frame loop so the file panel polls
4707                    // `take_import` THIS frame, not on the next stray input event.
4708                    wake_frame_loop();
4709                }
4710            }) as Box<dyn FnMut(web_sys::Event)>);
4711            reader.set_onload(Some(onload.as_ref().unchecked_ref()));
4712            // One small per-import leak (the app runs for the page lifetime).
4713            onload.forget();
4714            let _ = reader.read_as_array_buffer(&file);
4715        }) as Box<dyn FnMut(web_sys::Event)>);
4716        input.set_onchange(Some(onchange.as_ref().unchecked_ref()));
4717        onchange.forget(); // created once — leak is bounded
4718
4719        if let Some(body) = document.body() {
4720            let _ = body.append_child(&input);
4721        }
4722        IMPORT_INPUT.with(|c| *c.borrow_mut() = Some(input.clone()));
4723        Some(input)
4724    }
4725
4726    /// Offer `contents` to the user as a download named EXACTLY `file_name`, via a
4727    /// Blob object-URL + a synthetic anchor click.
4728    fn download(file_name: &str, mime: &str, contents: &str) -> Result<(), String> {
4729        let parts = js_sys::Array::of1(&JsValue::from_str(contents));
4730        let options = web_sys::BlobPropertyBag::new();
4731        options.set_type(mime);
4732        let blob = web_sys::Blob::new_with_str_sequence_and_options(&parts, &options)
4733            .map_err(|_| "blob create failed".to_string())?;
4734        click_download(file_name, &blob)
4735    }
4736
4737    /// [`download`] for BINARY content: the bytes are handed to the Blob as a
4738    /// `Uint8Array`, so nothing on the way out reinterprets them as UTF-8.
4739    fn download_bytes(file_name: &str, mime: &str, contents: &[u8]) -> Result<(), String> {
4740        let array = js_sys::Uint8Array::new_with_length(contents.len() as u32);
4741        array.copy_from(contents);
4742        let parts = js_sys::Array::of1(&array);
4743        let options = web_sys::BlobPropertyBag::new();
4744        options.set_type(mime);
4745        let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &options)
4746            .map_err(|_| "blob create failed".to_string())?;
4747        click_download(file_name, &blob)
4748    }
4749
4750    /// The half both downloads share: an object URL for `blob`, a synthetic
4751    /// anchor click carrying EXACTLY `file_name`, then the URL released.
4752    fn click_download(file_name: &str, blob: &web_sys::Blob) -> Result<(), String> {
4753        if super::host::available() {
4754            let name = file_name.to_owned();
4755            let blob = blob.clone();
4756            wasm_bindgen_futures::spawn_local(async move {
4757                let result = async {
4758                    let buffer = wasm_bindgen_futures::JsFuture::from(blob.array_buffer()).await
4759                        .map_err(|e| format!("export bytes: {e:?}"))?;
4760                    let bytes = js_sys::Uint8Array::new(&buffer).to_vec();
4761                    let binary: String = bytes.into_iter().map(char::from).collect();
4762                    let encoded = web_sys::window().ok_or("no window")?.btoa(&binary)
4763                        .map_err(|e| format!("export encoding: {e:?}"))?;
4764                    super::host::request(serde_json::json!({"op":"export", "name":name,
4765                        "base64":encoded})).await
4766                }.await;
4767                if let Err(error) = result {
4768                    BOOT_NOTICE.with(|n| *n.borrow_mut() = Some(format!("Local export failed: {error}")));
4769                    wake_frame_loop();
4770                }
4771            });
4772            return Ok(());
4773        }
4774        let document = web_sys::window()
4775            .and_then(|w| w.document())
4776            .ok_or("no document")?;
4777        let url = web_sys::Url::create_object_url_with_blob(blob)
4778            .map_err(|_| "object url failed".to_string())?;
4779        let anchor: web_sys::HtmlAnchorElement = document
4780            .create_element("a")
4781            .map_err(|_| "anchor create failed".to_string())?
4782            .dyn_into()
4783            .map_err(|_| "anchor cast failed".to_string())?;
4784        anchor.set_href(&url);
4785        anchor.set_download(file_name);
4786        anchor.click();
4787        let _ = web_sys::Url::revoke_object_url(&url);
4788        Ok(())
4789    }
4790
4791    /// The browser model store: the mirrored key space (which owns every CRUD and
4792    /// explorer method) plus this platform's real-file interchange lane.
4793    pub(super) struct IdbModelStore {
4794        core: MirrorStore,
4795    }
4796
4797    impl ModelStore for IdbModelStore {
4798        #[cfg(feature = "automation")]
4799        fn files(&self, request: &brep_mcp_core::files::Request) -> Result<brep_mcp_core::files::Reply, String> {
4800            self.core.files(request)
4801        }
4802        #[cfg(feature = "automation")]
4803        fn files_settled(&self, request: &brep_mcp_core::files::Request) -> Option<Result<(), String>> { self.core.files_settled(request) }
4804
4805        // --- delegated to the mirror ------------------------------------------
4806        fn backend_label(&self) -> String {
4807            self.core.backend_label()
4808        }
4809        fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
4810            self.core.plm_client()
4811        }
4812        fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
4813            self.core.plm_revision(key)
4814        }
4815        fn note_checked_out(&self, key: &str) {
4816            self.core.note_checked_out(key)
4817        }
4818        fn plm_written_by_us(&self, key: &str) -> bool {
4819            self.core.plm_written_by_us(key)
4820        }
4821        fn refresh_plm_index(&self, keys: &[String], stale: bool) {
4822            self.core.refresh_plm_index(keys, stale)
4823        }
4824        fn remember_saved_document(&self, name: &str, contents: &str) {
4825            self.core.remember_saved_document(name, contents)
4826        }
4827        fn list(&self) -> Vec<String> {
4828            self.core.list()
4829        }
4830        fn read(&self, name: &str) -> Option<String> {
4831            self.core.read(name)
4832        }
4833        fn residency(&self, name: &str) -> super::Residency {
4834            self.core.residency(name)
4835        }
4836        fn canonical_identity(&self, name: &str) -> String {
4837            self.core.canonical_identity(name)
4838        }
4839        fn canonicalizer(&self) -> super::Canonicalizer {
4840            self.core.canonicalizer()
4841        }
4842        fn write(&self, name: &str, contents: &str) -> Result<(), String> {
4843            self.core.write(name, contents)
4844        }
4845        fn remove(&self, name: &str) -> Result<(), String> {
4846            self.core.remove(name)
4847        }
4848        fn mutation_generation(&self) -> u64 {
4849            self.core.mutation_generation()
4850        }
4851        fn take_persistence_errors(&self) -> Vec<String> {
4852            let mut errors: Vec<String> = BOOT_NOTICE.with(|n| n.borrow_mut().take()).into_iter().collect();
4853            errors.extend(self.core.take_persistence_errors());
4854            errors
4855        }
4856        fn take_failed_writes(&self) -> Vec<String> {
4857            self.core.take_failed_writes()
4858        }
4859        fn write_failed(&self, name: &str) -> bool {
4860            self.core.write_failed(name)
4861        }
4862        fn failed_write_base(&self, name: &str) -> Option<String> {
4863            self.core.failed_write_base(name)
4864        }
4865        fn write_if(&self, name: &str, contents: &str, expected: &str) -> Result<(), String> {
4866            self.core.write_if(name, contents, expected)
4867        }
4868        fn plm_session(&self) -> Option<crate::plm::connection::Session> {
4869            use crate::plm::connection::{parse_label, Keep, Session, Status};
4870            if let Some((url, username)) = parse_label(&self.core.backend_label()) {
4871                return Some(Session { status: Status::Connected { url, username }, keep: Keep::BrowserSession });
4872            }
4873            let location = web_sys::window()?.location();
4874            if !crate::plm::backend::served_by_plm(&location.pathname().ok()?) {
4875                return None;
4876            }
4877            let reason = BOOT_REASON.with(|r| r.borrow().clone());
4878            Some(Session { status: Status::NotConnected { url: location.origin().ok()?, reason }, keep: Keep::BrowserSession })
4879        }
4880        fn pending_writes(&self) -> usize {
4881            self.core.pending_writes()
4882        }
4883        fn pending_writes_except(&self, names: &[&str]) -> usize {
4884            self.core.pending_writes_except(names)
4885        }
4886        fn browser_location(&self) -> String {
4887            self.core.browser_location()
4888        }
4889        fn browser_entries(&self, extensions: &[&str]) -> Vec<BrowserEntry> {
4890            self.core.browser_entries(extensions)
4891        }
4892        fn browser_enter(&self, identity: &str) -> Result<(), String> {
4893            self.core.browser_enter(identity)
4894        }
4895        fn browser_up(&self) -> Result<(), String> {
4896            self.core.browser_up()
4897        }
4898        fn browser_home(&self) -> Result<(), String> {
4899            self.core.browser_home()
4900        }
4901        fn browser_root(&self) -> Result<(), String> {
4902            self.core.browser_root()
4903        }
4904        fn browser_navigate(&self, location: &str) -> Result<(), String> {
4905            self.core.browser_navigate(location)
4906        }
4907        fn browser_places(&self) -> Vec<BrowserPlace> {
4908            self.core.browser_places()
4909        }
4910        fn browser_create_dir(&self, name: &str) -> Result<(), String> {
4911            self.core.browser_create_dir(name)
4912        }
4913        fn browser_write(&self, name: &str, contents: &str) -> Result<String, String> {
4914            self.core.browser_write(name, contents)
4915        }
4916
4917        // --- the browser's real-file lane -------------------------------------
4918        fn supports_file_interchange(&self) -> bool {
4919            true
4920        }
4921
4922        fn begin_pick_file(&self) -> Result<(), String> {
4923            let input = pick_input().ok_or("the browser's file chooser is unavailable")?;
4924            // Clear so choosing the same file again still fires `change`.
4925            input.set_value("");
4926            input.click();
4927            Ok(())
4928        }
4929
4930        fn take_picked_file(&self) -> Option<ImportedFile> {
4931            PICKED.with(|c| c.borrow_mut().take())
4932        }
4933
4934        /// Offer the document as a `<name>.nbrep` download. The returned
4935        /// identity is the bare name (the browser owns where the download lands).
4936        fn export_file(&self, name: &str, contents: &str) -> Result<Option<String>, String> {
4937            let name = model_display_name(name);
4938            let file_name = super::model_file_name(&name);
4939            download(&file_name, super::media_type(&file_name), contents)?;
4940            Ok(Some(name))
4941        }
4942
4943        fn begin_import(&self) -> Result<(), String> {
4944            let input =
4945                ensure_input(".nbrep,.fbrep,.tbrep").ok_or("file input unavailable")?;
4946            // Clear so re-selecting the same file still fires `change`.
4947            input.set_value("");
4948            input.click();
4949            Ok(())
4950        }
4951
4952        fn take_import(&self) -> Option<ImportedFile> {
4953            IMPORTED.with(|c| c.borrow_mut().take())
4954        }
4955
4956        // Format-typed interchange: the same hidden input, refiltered to the
4957        // requested extensions. The onchange handler stashes the file's real name
4958        // (its extension survives `model_display_name`, since that only strips
4959        // `.nbrep`), so the panel routes STEP imports by extension.
4960        fn begin_import_filtered(&self, filter: (&str, &[&str])) -> Result<(), String> {
4961            let accept = filter
4962                .1
4963                .iter()
4964                .map(|ext| format!(".{ext}"))
4965                .collect::<Vec<_>>()
4966                .join(",");
4967            let input = ensure_input(&accept).ok_or("file input unavailable")?;
4968            input.set_value("");
4969            input.click();
4970            Ok(())
4971        }
4972
4973        /// Offer `contents` as a download under EXACTLY `file_name` (extension
4974        /// kept) — the foreign-format sibling of [`Self::export_file`]. The
4975        /// media type is the file's own ([`super::media_type`]), so a sheet
4976        /// leaves as `image/svg+xml` and not as anonymous bytes.
4977        fn export_file_named(&self, file_name: &str, contents: &str) -> Result<(), String> {
4978            download(file_name, super::media_type(file_name), contents)
4979        }
4980
4981        /// The same, for bytes: `model/gltf-binary` for a GLB, `application/pdf`
4982        /// for a drawing sheet. It used to be glTF whatever the file was, which
4983        /// is why this lane could only ever carry one format.
4984        fn export_file_named_bytes(&self, file_name: &str, contents: &[u8]) -> Result<(), String> {
4985            download_bytes(file_name, super::media_type(file_name), contents)
4986        }
4987    }
4988}
4989
4990
4991