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