BREP_app 0.2.1

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//! The MULTI-DOCUMENT model — the app holds N open models, exactly ONE of which
//! is active.
//!
//! Before this, the shell owned a single `EngineState` and the document's
//! IDENTITY (its store name + the clean baseline the dirty flag compares
//! against) lived on the file dialog. That pairing is what a document IS, so it
//! moves here: [`Document`] = one engine + its identity, [`Documents`] = the
//! open list + the active index.
//!
//! # Why the accessor lives on `Documents` and not on `BrepApp`
//!
//! Half the shell passes DISJOINT `&mut` borrows of its own fields in one call
//! (`self.history.show(ui, self.docs.engine_mut(), …)`, and the whole
//! [`DockContext`](crate::panels::dock::DockContext)). A `BrepApp::engine_mut()`
//! would borrow ALL of `self` and every one of those sites would stop compiling.
//! `self.docs.engine_mut()` borrows only the `docs` FIELD, so it composes with a
//! borrow of any other field exactly as `self.state` used to.
//!
//! # One runner per document
//!
//! Each engine installs its own history runner (a native thread, or — on wasm —
//! its own web worker), because a runner owns the RESIDENT kernel state for the
//! document it executes: sharing one would make a background document's reply
//! land against the wrong resident registry. The shell therefore pumps EVERY
//! open document each frame, not just the active one, so a run that outlives a
//! tab switch is applied to the engine that submitted it. The cost is real and
//! deliberately unpaid-for here: N documents means N runner threads/workers and
//! N full scenes in memory. Opening a large assembly in a second tab costs what
//! opening it in a second window would.
//!
//! # Display settings are the SESSION's; the workbench is the DOCUMENT's
//!
//! Theme / UI scale / colors / wireframe / lod live on `EngineState.settings`,
//! so without a rule they would silently become per-tab (change the theme, switch
//! tabs, watch it flip back). [`carry_settings`] copies them from the outgoing
//! engine to the incoming one on every activation, and `workbench` is EXCLUDED
//! there: a saved document remembers the workbench it was authored in and
//! restores it on open, which is what makes the Assembly panes appear when you
//! switch to an assembly tab and vanish when you switch back to a part.
//!
//! A BRAND NEW tab is the one place the workbench IS carried — by
//! [`Documents::spawn_engine`], BEFORE the caller loads anything into the
//! engine, so a document that declares a workbench still overrides it during
//! the load and one that does not (a New document, a file saved before the
//! field existed) simply continues the session you were working in.

use crate::store::ModelStore;
use brep_render::engine_state::EngineState;

/// Builds a fresh engine for a new document — the platform runner, the viewcube,
/// and the persisted display settings, all applied before anything is loaded
/// into it. Injected by the shell so tests (which need the SYNCHRONOUS inline
/// runner) can construct documents without a background thread.
pub type EngineFactory = Box<dyn Fn() -> EngineState>;

/// The empty model a **New** document starts from.
pub const EMPTY_DOCUMENT: &str = r#"{"expressions":"","configurator":{},"features":[]}"#;

/// ONE open model: the engine that owns it plus the identity the file lane needs
/// — the store name it was opened from / saved to, and the clean baseline.
pub struct Document {
    /// The windowing-agnostic brain for THIS document (scene, camera, history,
    /// settings, selection). Panels borrow it; it is never forked.
    pub engine: EngineState,
    /// The store identity (`None` = a never-saved "untitled" model). The RAW
    /// identity, not the display name — a native dialog hands back a full path
    /// and a plain Save must write back to it.
    name: Option<String>,
    /// The model request JSON as of the last New / Open / Save — the baseline
    /// the dirty flag compares the live history against.
    saved_signature: Option<String>,
    /// The cached tab-strip dirty dot. See [`Document::dirty_marker`] for why
    /// this is not simply `is_dirty()`.
    dirty_marker: bool,
    /// The applied-run generation `dirty_marker` was computed at.
    marker_generation: Option<u64>,
    /// A process-unique handle, so the shell can notice "the active document is
    /// a different one now" without comparing indices (closing a tab BEFORE the
    /// active one moves the index without changing the document).
    id: u64,
}

impl Document {
    /// Wrap `engine` as a document, taking its CURRENT model as the clean
    /// baseline — so a freshly loaded (or freshly emptied) document is clean and
    /// the first edit marks it dirty.
    pub fn new(engine: EngineState) -> Self {
        let saved_signature = Some(engine.history_request_json());
        Self {
            engine,
            name: None,
            saved_signature,
            dirty_marker: false,
            marker_generation: None,
            id: next_document_id(),
        }
    }

    /// The raw store identity, or `None` for a never-saved document.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    pub fn set_name(&mut self, name: Option<String>) {
        self.name = name;
    }

    /// The tab label: the bare display name, or `untitled`.
    pub fn title(&self) -> String {
        match &self.name {
            Some(name) => crate::store::model_display_name(name),
            None => "untitled".to_string(),
        }
    }

    /// Snapshot the current model as the clean baseline (after New / Open /
    /// Save, or a `?loadModel=` boot-load).
    pub fn mark_clean(&mut self) {
        self.saved_signature = Some(self.engine.history_request_json());
        self.dirty_marker = false;
        self.marker_generation = Some(self.engine.applied_generation());
    }

    /// Dirty = the live model differs from the last saved/opened baseline.
    /// (Rolling the history does NOT change the request document, so navigating
    /// steps never marks dirty — only real edits/add/delete/reorder do.)
    ///
    /// HONEST but not free: it serializes the whole request document, which for
    /// an assembly carrying an embedded parts library is megabytes. Every place
    /// where being wrong would cost the user work — the close prompt, Save —
    /// calls THIS. The per-frame tab dot calls [`Self::dirty_marker`] instead.
    pub fn is_dirty(&self) -> bool {
        match &self.saved_signature {
            Some(saved) => *saved != self.engine.history_request_json(),
            None => true,
        }
    }

    /// The cached dirty flag the tab strip draws, recomputed only when the
    /// document's APPLIED RUN generation moved. Every ordinary edit (a param
    /// change, add, delete, reorder, undo) re-runs the history and bumps that
    /// generation, so the dot tracks editing; a mutation that changes the
    /// document WITHOUT a re-run (an object-metadata write) can leave the dot
    /// one edit behind. That is a marker being briefly optimistic, never a lost
    /// edit: [`Self::is_dirty`] is recomputed honestly at the close prompt.
    ///
    /// The alternative — serializing every open document every frame — is a
    /// per-frame multi-megabyte cost per tab, and the app pays no such cost today.
    pub fn refresh_dirty_marker(&mut self) {
        let generation = self.engine.applied_generation();
        if self.marker_generation == Some(generation) {
            return;
        }
        self.marker_generation = Some(generation);
        self.dirty_marker = self.is_dirty();
    }

    pub fn dirty_marker(&self) -> bool {
        self.dirty_marker
    }

    /// The document's process-unique handle (identity across index shuffles).
    pub fn id(&self) -> u64 {
        self.id
    }
}

/// Every open document + which one is active. Always holds AT LEAST ONE
/// document: closing the last tab leaves a fresh untitled one in its place, so
/// [`Documents::engine_mut`] is infallible and the shell never has to render a
/// "no document" state that would be an empty viewport with extra steps.
pub struct Documents {
    open: Vec<Document>,
    active: usize,
    /// How a new tab's engine is built (platform runner + persisted settings).
    new_engine: EngineFactory,
}

impl Documents {
    /// A session holding ONE empty document built by `new_engine`.
    pub fn new(new_engine: EngineFactory) -> Self {
        let first = Document::new(new_engine());
        Self {
            open: vec![first],
            active: 0,
            new_engine,
        }
    }

    /// A fresh engine for a document about to be opened — the caller loads into
    /// it and hands the result to [`Self::open_document`].
    ///
    /// Seeded with the WHOLE of the session's settings, workbench included, so
    /// a new tab continues what you were doing. The load that follows overrides
    /// the workbench if the document names one (see the module header).
    pub fn spawn_engine(&self) -> EngineState {
        let mut engine = (self.new_engine)();
        carry_settings(&self.engine().settings_json(), &mut engine, true);
        engine
    }

    pub fn engine(&self) -> &EngineState {
        &self.open[self.active].engine
    }

    pub fn engine_mut(&mut self) -> &mut EngineState {
        &mut self.open[self.active].engine
    }

    pub fn active(&self) -> &Document {
        &self.open[self.active]
    }

    pub fn active_mut(&mut self) -> &mut Document {
        &mut self.open[self.active]
    }

    pub fn active_index(&self) -> usize {
        self.active
    }

    /// The ACTIVE document's handle — the shell compares it frame to frame to
    /// notice a switch from ANY source (a tab click, a close, New, Open, Open
    /// Part, the session restore) with one check instead of a hook per site.
    pub fn active_id(&self) -> u64 {
        self.open[self.active].id
    }

    pub fn len(&self) -> usize {
        self.open.len()
    }

    pub fn get(&self, index: usize) -> Option<&Document> {
        self.open.get(index)
    }

    pub fn get_mut(&mut self, index: usize) -> Option<&mut Document> {
        self.open.get_mut(index)
    }

    pub fn iter(&self) -> std::slice::Iter<'_, Document> {
        self.open.iter()
    }

    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Document> {
        self.open.iter_mut()
    }

    /// The tab holding the document stored under `name`, if any.
    pub fn index_of(&self, name: &str) -> Option<usize> {
        self.open
            .iter()
            .position(|doc| doc.name.as_deref() == Some(name))
    }

    /// Activate the tab already holding `name`; `false` when it is not open.
    /// The "focus the existing tab" half of open-or-focus.
    pub fn focus_named(&mut self, name: &str) -> bool {
        match self.index_of(name) {
            Some(index) => {
                self.activate(index);
                true
            }
            None => false,
        }
    }

    /// Add `doc` as a new tab and make it active.
    pub fn open_document(&mut self, doc: Document) -> usize {
        self.open.push(doc);
        let index = self.open.len() - 1;
        self.activate(index);
        index
    }

    /// Make tab `index` active, carrying the session's display settings over to
    /// it. Out-of-range indices are ignored (a stale click never panics).
    pub fn activate(&mut self, index: usize) {
        if index >= self.open.len() || index == self.active {
            return;
        }
        let settings = self.open[self.active].engine.settings_json();
        self.active = index;
        carry_settings(&settings, &mut self.open[index].engine, false);
    }

    /// Close tab `index`. Closing the LAST document leaves a fresh untitled one
    /// (the always-one-document invariant); closing a tab before the active one
    /// keeps the same document active at its new index.
    ///
    /// The caller is responsible for the unsaved-changes prompt — this is the
    /// mechanical close (`panels::file` owns the confirmation).
    pub fn close(&mut self, index: usize) {
        if index >= self.open.len() {
            return;
        }
        // Taken BEFORE the removal: if the closing tab was the active one, its
        // settings are the session's and must survive into whatever is shown next.
        let settings = self.open[self.active].engine.settings_json();
        let closed_active = index == self.active;
        self.open.remove(index);
        // The replacement for a session closed down to nothing is a brand-new
        // tab, so it takes the WHOLE of the session's settings — workbench
        // included — exactly as `New` does through `spawn_engine`.
        let refilled = self.open.is_empty();
        if refilled {
            self.open.push(Document::new((self.new_engine)()));
            self.active = 0;
        } else if closed_active {
            self.active = index.min(self.open.len() - 1);
        } else if index < self.active {
            self.active -= 1;
        }
        if closed_active {
            let active = self.active;
            carry_settings(&settings, &mut self.open[active].engine, refilled);
        }
    }

    /// Refresh every tab's dirty dot (see [`Document::refresh_dirty_marker`]).
    pub fn refresh_dirty_markers(&mut self) {
        for doc in &mut self.open {
            doc.refresh_dirty_marker();
        }
    }

    // --- session persistence --------------------------------------------------

    /// The persisted session: the NAMED documents in tab order plus the active
    /// one's name. A never-saved document has no store identity, so it cannot be
    /// restored and is not listed — reloading loses an unsaved scratch document
    /// exactly as it did when the app held one document and persisted none.
    pub fn session_json(&self) -> String {
        let open: Vec<&str> = self.open.iter().filter_map(Document::name).collect();
        serde_json::json!({
            "open": open,
            "active": self.active().name(),
        })
        .to_string()
    }

    /// Restore a persisted session, REPLACING the current open list. Names the
    /// store no longer holds (or cannot load) are skipped — a deleted file must
    /// not stop the rest of the session coming back — and the count of documents
    /// actually restored is returned, so the caller can seed instead when it is 0.
    pub fn restore_session(&mut self, store: &dyn ModelStore, json: &str) -> usize {
        let Ok(session) = serde_json::from_str::<serde_json::Value>(json) else {
            return 0;
        };
        let names: Vec<String> = session["open"]
            .as_array()
            .map(|list| {
                list.iter()
                    .filter_map(|name| name.as_str().map(str::to_string))
                    .collect()
            })
            .unwrap_or_default();
        let wanted_active = session["active"].as_str().unwrap_or_default().to_string();

        let mut restored: Vec<Document> = Vec::new();
        let mut active = 0usize;
        for name in names {
            let Some(contents) = store.read(&name) else {
                continue;
            };
            let mut engine = (self.new_engine)();
            if engine.load_model_and_fit(&contents).is_err() {
                continue;
            }
            let mut doc = Document::new(engine);
            doc.set_name(Some(name.clone()));
            if name == wanted_active {
                active = restored.len();
            }
            restored.push(doc);
        }
        if restored.is_empty() {
            return 0;
        }
        self.open = restored;
        self.active = active;
        self.open.len()
    }
}

/// Copy the SESSION-scoped display settings (theme, UI scale, colors, wireframe,
/// projection, lod…) from a `settings_json()` snapshot into `target`.
/// `with_workbench` is true ONLY when seeding a brand-new engine — see the
/// module header for why activation must never carry it.
fn carry_settings(settings_json: &str, target: &mut EngineState, with_workbench: bool) {
    let Ok(mut settings) = serde_json::from_str::<serde_json::Value>(settings_json) else {
        return;
    };
    if !with_workbench {
        if let Some(object) = settings.as_object_mut() {
            object.remove("workbench");
        }
    }
    let _ = target.apply_settings_json(&settings.to_string());
}

/// Hand out the next document handle. A plain process counter: handles only ever
/// need to be distinct WITHIN a session, and they never reach storage.
fn next_document_id() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static NEXT: AtomicU64 = AtomicU64::new(1);
    NEXT.fetch_add(1, Ordering::Relaxed)
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;
    use crate::store::MemModelStore;

    /// The test factory: the SYNCHRONOUS inline runner, so a load's solids are
    /// resident by the time the call returns.
    fn documents() -> Documents {
        Documents::new(Box::new(EngineState::new))
    }

    const BOX_SEED: &str = r#"{"expressions":"","configurator":{},"features":[
        {"type":"P.CU","inputParams":{"id":"Box","sizeX":8.0,"sizeY":8.0,"sizeZ":8.0,
         "transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},
         "boolean":{"targets":[],"operation":"NONE"}},"persistentData":{}}
    ]}"#;

    fn named(docs: &mut Documents, name: &str) -> usize {
        let mut engine = docs.spawn_engine();
        engine.set_history_json(BOX_SEED).unwrap();
        let mut doc = Document::new(engine);
        doc.set_name(Some(name.to_string()));
        docs.open_document(doc)
    }

    /// A session starts with exactly one (empty, untitled, clean) document, and
    /// every opened document becomes the active tab.
    #[test]
    fn a_session_always_holds_at_least_one_document() {
        let mut docs = documents();
        assert_eq!(docs.len(), 1);
        assert_eq!(docs.active_index(), 0);
        assert_eq!(docs.active().title(), "untitled");
        assert!(!docs.active().is_dirty(), "a fresh document is clean");

        named(&mut docs, "part-a");
        assert_eq!(docs.len(), 2);
        assert_eq!(docs.active_index(), 1, "an opened document takes focus");
        assert_eq!(docs.active().title(), "part-a");
    }

    /// Open-or-focus: a name already open activates ITS tab instead of adding a
    /// second one.
    #[test]
    fn focus_named_activates_the_existing_tab() {
        let mut docs = documents();
        named(&mut docs, "part-a");
        named(&mut docs, "part-b");
        assert_eq!(docs.active_index(), 2);

        assert!(docs.focus_named("part-a"), "already open");
        assert_eq!(docs.active_index(), 1);
        assert_eq!(docs.len(), 3, "focusing never adds a tab");
        assert!(!docs.focus_named("part-z"), "never opened");
        assert_eq!(docs.active_index(), 1, "a miss leaves the focus alone");
    }

    /// The index fixup: closing a tab BEFORE the active one keeps the same
    /// document active (its handle is unchanged); closing the active one falls
    /// to its neighbour; closing the last one leaves a fresh untitled document.
    #[test]
    fn closing_fixes_up_the_active_index() {
        let mut docs = documents();
        named(&mut docs, "part-a"); // index 1
        named(&mut docs, "part-b"); // index 2
        docs.activate(2);
        let active_id = docs.active_id();

        // Close the untitled tab BEFORE the active one: same document, new index.
        docs.close(0);
        assert_eq!(docs.len(), 2);
        assert_eq!(docs.active_index(), 1);
        assert_eq!(docs.active_id(), active_id, "the same document stays active");
        assert_eq!(docs.active().title(), "part-b");

        // Close the ACTIVE (last) tab: focus falls back to its neighbour.
        docs.close(1);
        assert_eq!(docs.len(), 1);
        assert_eq!(docs.active_index(), 0);
        assert_eq!(docs.active().title(), "part-a");
        assert_ne!(docs.active_id(), active_id, "a different document is active");

        // Close the ONLY tab: a fresh untitled document takes its place.
        docs.close(0);
        assert_eq!(docs.len(), 1, "there is always a document");
        assert_eq!(docs.active().title(), "untitled");
        assert_eq!(docs.active().engine.history_len(), 0);

        // Out-of-range indices are ignored rather than panicking.
        docs.close(7);
        assert_eq!(docs.len(), 1);
    }

    /// Dirty tracking is per document: editing one tab never marks another, and
    /// the cached tab-strip marker follows the honest flag across a re-run.
    #[test]
    fn dirty_tracking_is_per_document() {
        let mut docs = documents();
        named(&mut docs, "part-a");
        named(&mut docs, "part-b");
        docs.refresh_dirty_markers();
        assert!(docs.iter().all(|doc| !doc.is_dirty()), "all clean");
        assert!(docs.iter().all(|doc| !doc.dirty_marker()));

        // Edit the ACTIVE document (part-b).
        docs.engine_mut()
            .update_feature_params(
                "Box",
                r#"{"id":"Box","sizeX":19.0,"sizeY":8.0,"sizeZ":8.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}"#,
            )
            .unwrap();
        docs.refresh_dirty_markers();
        assert!(docs.active().is_dirty(), "the edited document is dirty");
        assert!(docs.active().dirty_marker(), "…and its tab dot lights");
        assert!(!docs.get(1).unwrap().is_dirty(), "the other tab is untouched");
        assert!(!docs.get(1).unwrap().dirty_marker());

        // Saving (marking clean) clears both the flag and the dot.
        docs.active_mut().mark_clean();
        docs.refresh_dirty_markers();
        assert!(!docs.active().is_dirty());
        assert!(!docs.active().dirty_marker());
    }

    /// Display settings are the SESSION's: a theme change follows a tab switch.
    /// The workbench is the DOCUMENT's and must NOT follow it — that is what
    /// makes the Assembly panes appear on an assembly tab and vanish on a part.
    #[test]
    fn switching_carries_display_settings_but_not_the_workbench() {
        let mut docs = documents();
        docs.engine_mut()
            .apply_settings_json(r#"{"workbench":"assembly","wireframe":true}"#)
            .unwrap();
        named(&mut docs, "part-a");
        docs.engine_mut()
            .apply_settings_json(r#"{"workbench":"sheetMetal"}"#)
            .unwrap();
        assert!(
            docs.engine().settings.wireframe,
            "the new tab inherited the session's display settings"
        );

        // Back to the first tab: it keeps its own workbench, and picks up the
        // display setting changed while it was in the background.
        docs.engine_mut()
            .apply_settings_json(r#"{"wireframe":false}"#)
            .unwrap();
        docs.activate(0);
        assert_eq!(docs.engine().settings.workbench, "assembly", "per document");
        assert!(!docs.engine().settings.wireframe, "per session");

        docs.activate(1);
        assert_eq!(docs.engine().settings.workbench, "sheetMetal");
    }

    /// The session round-trips through the store: only NAMED documents are
    /// listed, the active one comes back active, and a name whose file has gone
    /// is skipped rather than failing the whole restore.
    #[test]
    fn the_session_round_trips_and_tolerates_a_missing_file() {
        let store = MemModelStore::new();
        store.put("part-a", BOX_SEED);
        store.put("part-b", BOX_SEED);

        let mut docs = documents();
        named(&mut docs, "part-a");
        named(&mut docs, "part-b");
        docs.activate(1);
        let session = docs.session_json();
        let parsed: serde_json::Value = serde_json::from_str(&session).unwrap();
        assert_eq!(
            parsed["open"].as_array().unwrap().len(),
            2,
            "the untitled tab is not persistable: {session}"
        );
        assert_eq!(parsed["active"], "part-a");

        let mut restored = documents();
        assert_eq!(restored.restore_session(&store, &session), 2);
        assert_eq!(restored.len(), 2);
        assert_eq!(restored.active().title(), "part-a");
        assert!(!restored.active().is_dirty(), "a restored document is clean");
        assert_eq!(restored.active().engine.scene.solids().len(), 1);

        // One file removed: the rest of the session still comes back.
        store.remove("part-a").unwrap();
        let mut partial = documents();
        assert_eq!(partial.restore_session(&store, &session), 1);
        assert_eq!(partial.active().title(), "part-b");

        // Nothing restorable → 0, and the caller seeds instead.
        store.remove("part-b").unwrap();
        let mut none = documents();
        assert_eq!(none.restore_session(&store, &session), 0);
        assert_eq!(none.len(), 1, "the untouched boot document survives");
        assert_eq!(none.restore_session(&store, "not json"), 0);
    }
}