BREP_app 0.3.0

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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
//! AUTOSAVE + CRASH RECOVERY — the answer to "the tab closed and my last hour
//! is gone".
//!
//! Nothing here touches what the user saved. A Save still writes the document
//! under its own name and nothing else; this module keeps ONE extra blob
//! ([`RECOVERY_KEY`]) holding a copy of every open document that currently has
//! unsaved changes, and offers those copies back at the next boot.
//!
//! # Two rules that decide the shape
//!
//! * **Growth is debounced, shrinkage is immediate.** An edit burst (a slider
//!   drag, a run of parameter tweaks) re-arms a [`AUTOSAVE_DEBOUNCE`] timer and
//!   the blob is written once the burst settles. But the moment a document
//!   LEAVES the dirty set — a Save, a "Discard and close", an undo back to the
//!   clean baseline — the blob is rewritten (or removed) on that same frame,
//!   because a reload inside the debounce window must never offer work the user
//!   just saved or just threw away.
//! * **Recovery is a prompt, never an automatic restore.** The shell boots the
//!   seed model on purpose (a document that wedges the kernel must not wedge
//!   every boot after it — see `BrepApp::new`), and the prompt keeps that: the
//!   autosaved copies are listed, and only a click loads one. The prompt cannot
//!   be dismissed sideways (Esc / click-outside), because the seed tab's first
//!   edit would then overwrite the blob with itself and the offer would be gone
//!   for good.
//!
//! A restored document comes back DIRTY ([`Document::recovered`]): what it
//! holds is exactly what was never saved, so the tab dot lights and the close
//! guard asks, until a Save writes it somewhere. It is also autosaved again
//! after the next debounce, so a second crash loses nothing either.
//!
//! The change detector is the cheap per-frame tuple `(document id, applied run
//! generation, dirty marker)` — the same key the tab strip's dirty dot uses
//! (`Document::refresh_dirty_marker`), so a metadata-only edit that moves no
//! generation lags one edit here exactly as it does there. Serialising a
//! document happens only when a write is actually due.

use std::collections::HashMap;

use eframe::egui;

use crate::document::{Document, Documents};
use crate::store::{ModelStore, RECOVERY_KEY};

/// Seconds a dirty set must hold still before its documents are written.
pub const AUTOSAVE_DEBOUNCE: f64 = 2.0;

/// The blob's schema number; a blob from a different one is ignored.
const SCHEMA: u64 = 1;

/// One autosaved document as it sits in the blob.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct RecoveryEntry {
    /// The store identity the document had (`None` = untitled).
    #[serde(default)]
    pub name: Option<String>,
    /// The tab title at the time of the write.
    pub title: String,
    /// Wall-clock Unix seconds of the write (0 when unknown).
    #[serde(default)]
    pub saved_at: f64,
    /// The model request JSON — the same `.BREP.json` text a Save writes.
    pub model: String,
}

#[derive(serde::Serialize, serde::Deserialize)]
struct Blob {
    schema: u64,
    documents: Vec<RecoveryEntry>,
}

/// The per-frame autosave driver the shell owns.
#[derive(Default)]
pub struct Autosave {
    /// `(document id, applied generation, dirty marker)` per open tab, as of the
    /// last tick — the change detector.
    captured: Vec<(u64, u64, bool)>,
    /// The egui clock time the current debounce window was (re)armed at.
    armed_at: Option<f64>,
    /// What the blob holds — `(name, model)` per entry — as far as this session
    /// knows: `None` at boot (the prompt owns the stored blob until it resolves),
    /// `Some(empty)` once it is known to be absent. Compared before every write
    /// so an unchanged dirty set never rewrites megabytes.
    written: Option<Vec<(Option<String>, String)>>,
    /// Store failures raised by a write, drained by the shell into the toasts.
    errors: Vec<String>,
}

impl Autosave {
    pub fn new() -> Self {
        Self::default()
    }

    /// Advance the autosave by one frame. `now` is the egui clock
    /// (`ctx.input().time`, seconds; never `Instant`, which traps on wasm).
    /// Returns the seconds until an armed write comes due, so the shell can ask
    /// for a repaint then — the frame loop is otherwise idle and the deadline
    /// would never be observed.
    pub fn tick(&mut self, docs: &Documents, store: &dyn ModelStore, now: f64) -> Option<f64> {
        let snapshot: Vec<(u64, u64, bool)> = docs
            .iter()
            .map(|doc| (doc.id(), doc.engine.applied_generation(), doc.dirty_marker()))
            .collect();
        if snapshot != self.captured {
            let dirty_before: Vec<u64> = dirty_ids(&self.captured);
            let dirty_now: Vec<u64> = dirty_ids(&snapshot);
            let shrank = dirty_before.iter().any(|id| !dirty_now.contains(id));
            self.captured = snapshot;
            if shrank {
                // A save, a discarded close, an undo to clean: whatever left the
                // set must stop being offered NOW. The write captures every
                // still-dirty document's current state too, so nothing armed
                // is left over.
                self.write(docs, store);
                self.armed_at = None;
            } else if !dirty_now.is_empty() {
                self.armed_at = Some(now);
            }
        }
        if let Some(armed) = self.armed_at {
            let remaining = AUTOSAVE_DEBOUNCE - (now - armed);
            if remaining > 0.0 {
                return Some(remaining);
            }
            self.write(docs, store);
            self.armed_at = None;
        }
        None
    }

    /// The prompt resolved (restore or discard removed the blob): the store is
    /// known empty, so the next dirty document is a fresh write.
    pub fn note_cleared(&mut self) {
        self.written = Some(Vec::new());
    }

    /// Store failures since the last drain, oldest first.
    pub fn take_errors(&mut self) -> Vec<String> {
        std::mem::take(&mut self.errors)
    }

    /// Write the dirty documents (or remove the blob when there are none),
    /// unless the store already holds exactly that.
    fn write(&mut self, docs: &Documents, store: &dyn ModelStore) {
        let entries: Vec<RecoveryEntry> = docs
            .iter()
            .filter(|doc| doc.dirty_marker())
            .map(|doc| RecoveryEntry {
                name: doc.name().map(str::to_string),
                title: doc.title(),
                saved_at: wall_clock(),
                model: doc.engine.history_request_json(),
            })
            .collect();
        let key: Vec<(Option<String>, String)> = entries
            .iter()
            .map(|entry| (entry.name.clone(), entry.model.clone()))
            .collect();
        if self.written.as_ref() == Some(&key) {
            return;
        }
        let result = if entries.is_empty() {
            store.remove(RECOVERY_KEY)
        } else {
            store.write(RECOVERY_KEY, &encode(&entries))
        };
        match result {
            Ok(()) => self.written = Some(key),
            Err(error) => self.errors.push(format!("autosave failed: {error}")),
        }
    }
}

fn dirty_ids(snapshot: &[(u64, u64, bool)]) -> Vec<u64> {
    snapshot
        .iter()
        .filter(|(_, _, dirty)| *dirty)
        .map(|(id, _, _)| *id)
        .collect()
}

fn encode(entries: &[RecoveryEntry]) -> String {
    serde_json::to_string(&Blob {
        schema: SCHEMA,
        documents: entries.to_vec(),
    })
    .expect("serialize recovery blob")
}

/// The autosaved documents worth offering: the blob's entries minus any whose
/// named store copy already holds the same model (a Save that landed before
/// the shrink write did — content is compared as parsed JSON so formatting
/// differences never manufacture a prompt). Empty when there is no blob, or it
/// is from another schema.
pub fn read_entries(store: &dyn ModelStore) -> Vec<RecoveryEntry> {
    let Some(text) = store.read(RECOVERY_KEY) else {
        return Vec::new();
    };
    let Ok(blob) = serde_json::from_str::<Blob>(&text) else {
        return Vec::new();
    };
    if blob.schema != SCHEMA {
        return Vec::new();
    }
    blob.documents
        .into_iter()
        .filter(|entry| !entry.model.is_empty())
        .filter(|entry| !already_saved(store, entry))
        .collect()
}

fn already_saved(store: &dyn ModelStore, entry: &RecoveryEntry) -> bool {
    let Some(name) = &entry.name else {
        return false;
    };
    let Some(saved) = store.read(name) else {
        return false;
    };
    match (
        serde_json::from_str::<serde_json::Value>(&saved),
        serde_json::from_str::<serde_json::Value>(&entry.model),
    ) {
        (Ok(saved), Ok(model)) => saved == model,
        _ => false,
    }
}

/// Open every entry as a tab of its own (dirty, under the name it had). An
/// entry the engine cannot load is reported, not restored. When the session is
/// still the pristine boot seed — one clean, untitled tab — that tab is
/// replaced rather than kept beside the restored work, for the same reason the
/// `?loadModel=` boot path replaces it: the user asked for THEIR document, and
/// a demo cube next to it is noise. Returns the restored count and the failures.
pub fn restore_entries(entries: &[RecoveryEntry], docs: &mut Documents) -> (usize, Vec<String>) {
    let pristine_seed =
        docs.len() == 1 && docs.active().name().is_none() && !docs.active().is_dirty();
    let mut restored = 0usize;
    let mut failures = Vec::new();
    for entry in entries {
        let mut engine = docs.spawn_engine();
        if let Err(error) = engine.load_model_and_fit(&entry.model) {
            failures.push(format!("could not restore \"{}\": {error}", entry.title));
            continue;
        }
        docs.open_document(Document::recovered(engine, entry.name.clone()));
        restored += 1;
    }
    if restored > 0 && pristine_seed {
        docs.close(0);
    }
    (restored, failures)
}

/// Wall-clock Unix seconds. `SystemTime` traps on wasm32; the browser's clock
/// is `Date.now()`.
pub fn wall_clock() -> f64 {
    #[cfg(target_arch = "wasm32")]
    {
        js_sys::Date::now() / 1000.0
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs_f64())
            .unwrap_or(0.0)
    }
}

/// "just now" / "3 min ago" / "2 h ago" / "4 d ago" for a `saved_at` stamp,
/// or empty when the stamp is unknown.
fn age_label(saved_at: f64, now: f64) -> String {
    if saved_at <= 0.0 {
        return String::new();
    }
    let seconds = (now - saved_at).max(0.0);
    if seconds < 60.0 {
        "just now".to_string()
    } else if seconds < 3600.0 {
        format!("{} min ago", (seconds / 60.0).floor() as u64)
    } else if seconds < 86_400.0 {
        format!("{} h ago", (seconds / 3600.0).floor() as u64)
    } else {
        format!("{} d ago", (seconds / 86_400.0).floor() as u64)
    }
}

/// How the prompt resolved this frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Resolution {
    /// `Restore`: this many tabs were opened (the failures were toasted).
    Restored(usize),
    /// `Discard`: the blob is gone.
    Discarded,
}

/// The boot-time **Recover unsaved work?** modal. Armed with the entries
/// [`read_entries`] found; open until one of its two buttons resolves it.
#[derive(Default)]
pub struct RecoveryPanel {
    entries: Vec<RecoveryEntry>,
    hits: HashMap<String, egui::Rect>,
}

impl RecoveryPanel {
    pub fn new() -> Self {
        Self::default()
    }

    /// Offer `entries` (nothing is shown for an empty list).
    pub fn arm(&mut self, entries: Vec<RecoveryEntry>) {
        self.entries = entries;
    }

    pub fn is_open(&self) -> bool {
        !self.entries.is_empty()
    }

    /// Forget the last frame's button rects (the shell calls this when the
    /// prompt is closed, so a verifier never reads a rect of a modal that is
    /// no longer there).
    pub fn clear_hits(&mut self) {
        self.hits.clear();
    }

    /// Draw the modal while entries are pending. Returns the resolution on the
    /// frame a button lands; `docs` gains the restored tabs and `store` loses
    /// the blob on either button. Failures to load an entry are queued on the
    /// active engine as notices.
    pub fn show(
        &mut self,
        ctx: &egui::Context,
        docs: &mut Documents,
        store: &dyn ModelStore,
    ) -> Option<Resolution> {
        self.hits.clear();
        if self.entries.is_empty() {
            return None;
        }
        let now = wall_clock();
        let count = self.entries.len();
        let mut restore = false;
        let mut discard = false;
        egui::Modal::new(egui::Id::new("brep-recovery")).show(ctx, |ui| {
            ui.set_width(440.0);
            ui.heading("Recover unsaved work?");
            ui.add_space(4.0);
            ui.label(format!(
                "The last session ended with {count} document{} unsaved. \
                 Autosaved copies are still here.",
                if count == 1 { "" } else { "s" }
            ));
            ui.add_space(6.0);
            for entry in &self.entries {
                let age = age_label(entry.saved_at, now);
                let line = if age.is_empty() {
                    format!("{}", entry.title)
                } else {
                    format!("{}  ({age})", entry.title)
                };
                ui.label(line);
            }
            ui.add_space(8.0);
            ui.horizontal(|ui| {
                let r = ui.button("Restore");
                self.hits.insert("recovery:restore".into(), r.rect);
                if r.clicked() {
                    restore = true;
                }
                let d = ui.button("Discard");
                self.hits.insert("recovery:discard".into(), d.rect);
                if d.clicked() {
                    discard = true;
                }
            });
            ui.add_space(2.0);
            ui.weak("Restored documents open as new tabs with unsaved changes.");
        });
        // Esc / click-outside deliberately do NOT dismiss (see the module doc):
        // the offer survives until a button decides.
        if restore {
            let entries = std::mem::take(&mut self.entries);
            let (restored, failures) = restore_entries(&entries, docs);
            for failure in failures {
                docs.engine_mut().push_notice(failure);
            }
            let _ = store.remove(RECOVERY_KEY);
            Some(Resolution::Restored(restored))
        } else if discard {
            self.entries.clear();
            let _ = store.remove(RECOVERY_KEY);
            Some(Resolution::Discarded)
        } else {
            None
        }
    }

    /// `{open, entries:[{title, name, savedAt}]}` — the `__brepRecovery` global.
    pub fn state_json(&self) -> String {
        let entries: Vec<serde_json::Value> = self
            .entries
            .iter()
            .map(|entry| {
                serde_json::json!({
                    "title": entry.title,
                    "name": entry.name,
                    "savedAt": entry.saved_at,
                })
            })
            .collect();
        serde_json::json!({ "open": self.is_open(), "entries": entries }).to_string()
    }

    /// The modal's button rects (`recovery:restore` / `recovery:discard`) as
    /// `{key: [x, y, w, h]}`, empty while closed.
    pub fn hits_json(&self) -> String {
        let map: serde_json::Map<String, serde_json::Value> = self
            .hits
            .iter()
            .map(|(key, rect)| {
                (
                    key.clone(),
                    serde_json::json!([rect.min.x, rect.min.y, rect.width(), rect.height()]),
                )
            })
            .collect();
        serde_json::Value::Object(map).to_string()
    }
}

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

    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 documents() -> Documents {
        Documents::new(Box::new(EngineState::new))
    }

    /// Open `BOX_SEED` as a named, clean tab.
    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)
    }

    /// Resize the active tab's box — an ordinary edit that re-runs the history.
    fn edit_active(docs: &mut Documents, size: f64) {
        docs.engine_mut()
            .update_feature_params(
                "Box",
                &format!(
                    r#"{{"id":"Box","sizeX":{size},"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();
    }

    /// The debounce: an edit arms a write that lands only once the dirty set
    /// has held still for `AUTOSAVE_DEBOUNCE`; a second edit inside the window
    /// re-arms it. The written entry carries the document's name and model.
    #[test]
    fn an_edit_is_written_after_the_debounce_not_before() {
        let store = MemModelStore::new();
        let mut docs = documents();
        named(&mut docs, "part-a");
        docs.refresh_dirty_markers();
        let mut autosave = Autosave::new();
        assert_eq!(autosave.tick(&docs, &store, 0.0), None, "nothing dirty, nothing armed");
        assert!(store.read(RECOVERY_KEY).is_none());

        edit_active(&mut docs, 19.0);
        let due = autosave.tick(&docs, &store, 1.0).expect("armed");
        assert!((due - AUTOSAVE_DEBOUNCE).abs() < 1e-9);
        assert!(store.read(RECOVERY_KEY).is_none(), "not yet: the burst may continue");

        // A second edit inside the window restarts the clock.
        edit_active(&mut docs, 21.0);
        let due = autosave.tick(&docs, &store, 2.5).expect("re-armed");
        assert!((due - AUTOSAVE_DEBOUNCE).abs() < 1e-9);
        assert_eq!(autosave.tick(&docs, &store, 4.0), Some(0.5));
        assert!(store.read(RECOVERY_KEY).is_none());

        assert_eq!(autosave.tick(&docs, &store, 4.5), None, "written, nothing armed");
        let entries = read_entries(&store);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name.as_deref(), Some("part-a"));
        assert_eq!(entries[0].title, "part-a");
        assert_eq!(entries[0].model, docs.engine().history_request_json());
        assert!(entries[0].model.contains("\"sizeX\":21"), "the LAST edit is what was captured: {}", entries[0].model);
        assert!(entries[0].saved_at > 0.0);
        assert!(autosave.take_errors().is_empty());
    }

    /// Shrinkage is immediate: a Save (mark_clean) removes the blob on the very
    /// next tick, with no debounce, and an unchanged dirty set never rewrites.
    #[test]
    fn saving_removes_the_blob_immediately() {
        let store = MemModelStore::new();
        let mut docs = documents();
        named(&mut docs, "part-a");
        docs.refresh_dirty_markers();
        let mut autosave = Autosave::new();
        autosave.tick(&docs, &store, 0.0);
        edit_active(&mut docs, 19.0);
        autosave.tick(&docs, &store, 1.0);
        autosave.tick(&docs, &store, 3.5);
        assert!(store.read(RECOVERY_KEY).is_some());
        let writes_before = store.writes();

        // Ticks with nothing new never touch the store.
        autosave.tick(&docs, &store, 5.0);
        autosave.tick(&docs, &store, 9.0);
        assert_eq!(store.writes(), writes_before);

        docs.active_mut().mark_clean();
        docs.refresh_dirty_markers();
        assert_eq!(autosave.tick(&docs, &store, 9.1), None);
        assert!(store.read(RECOVERY_KEY).is_none(), "removed on the frame the save landed");
        assert!(read_entries(&store).is_empty());
    }

    /// Closing a dirty tab (the "Discard and close" door) also shrinks the set,
    /// and a still-dirty sibling keeps its entry.
    #[test]
    fn a_closed_tab_leaves_the_blob_and_a_dirty_sibling_stays() {
        let store = MemModelStore::new();
        let mut docs = documents();
        named(&mut docs, "part-a");
        named(&mut docs, "part-b");
        docs.refresh_dirty_markers();
        let mut autosave = Autosave::new();
        autosave.tick(&docs, &store, 0.0);
        docs.activate(1);
        edit_active(&mut docs, 19.0);
        docs.activate(2);
        edit_active(&mut docs, 23.0);
        autosave.tick(&docs, &store, 1.0);
        autosave.tick(&docs, &store, 3.5);
        assert_eq!(read_entries(&store).len(), 2);

        docs.close(2);
        docs.refresh_dirty_markers();
        autosave.tick(&docs, &store, 3.6);
        let entries = read_entries(&store);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name.as_deref(), Some("part-a"));
    }

    /// Restore opens each entry as its own DIRTY tab under its old name, an
    /// untitled entry comes back untitled, and the pristine boot seed is
    /// replaced rather than kept beside the restored work.
    #[test]
    fn restore_reopens_dirty_documents_and_replaces_the_pristine_seed() {
        let store = MemModelStore::new();
        let mut source = documents();
        named(&mut source, "part-a");
        edit_active(&mut source, 19.0);
        // An untitled dirty document too.
        let mut engine = source.spawn_engine();
        engine.set_history_json(BOX_SEED).unwrap();
        source.open_document(Document::new(engine));
        edit_active(&mut source, 5.0);
        let mut autosave = Autosave::new();
        autosave.tick(&source, &store, 0.0);
        autosave.tick(&source, &store, 3.0);
        let entries = read_entries(&store);
        assert_eq!(entries.len(), 2);

        let mut docs = documents();
        assert_eq!(docs.len(), 1, "the boot seed");
        let (restored, failures) = restore_entries(&entries, &mut docs);
        assert_eq!(restored, 2);
        assert!(failures.is_empty());
        assert_eq!(docs.len(), 2, "the pristine seed was replaced");
        assert_eq!(docs.get(0).unwrap().title(), "part-a");
        assert_eq!(docs.get(0).unwrap().name(), Some("part-a"));
        assert_eq!(docs.get(1).unwrap().title(), "untitled");
        assert!(docs.get(1).unwrap().name().is_none());
        docs.refresh_dirty_markers();
        assert!(docs.iter().all(Document::is_dirty), "recovered work is unsaved work");
        assert!(docs.iter().all(Document::dirty_marker));
        assert_eq!(docs.active().engine.scene.solids().len(), 1, "geometry is resident");
        assert!(docs.get(0).unwrap().engine.history_request_json().contains("\"sizeX\":19"));

        // A Save then clears it like any other document.
        docs.get_mut(0).unwrap().mark_clean();
        assert!(!docs.get(0).unwrap().is_dirty());
    }

    /// A dirty seed is NOT replaced, and an unloadable entry is reported rather
    /// than silently dropped.
    #[test]
    fn restore_keeps_a_dirty_seed_and_reports_a_broken_entry() {
        let mut docs = documents();
        docs.engine_mut().set_history_json(BOX_SEED).unwrap();
        docs.active_mut().mark_clean();
        edit_active(&mut docs, 11.0);
        let entries = vec![
            RecoveryEntry {
                name: None,
                title: "untitled".into(),
                saved_at: 0.0,
                model: BOX_SEED.into(),
            },
            RecoveryEntry {
                name: Some("broken".into()),
                title: "broken".into(),
                saved_at: 0.0,
                model: "not json".into(),
            },
        ];
        let (restored, failures) = restore_entries(&entries, &mut docs);
        assert_eq!(restored, 1);
        assert_eq!(failures.len(), 1);
        assert!(failures[0].contains("broken"));
        assert_eq!(docs.len(), 2, "the dirty seed stayed");
    }

    /// An entry whose named store copy already holds the same model is not
    /// offered (a Save that landed before the shrink write), compared as JSON
    /// so formatting never manufactures a prompt; a foreign schema and a
    /// missing blob offer nothing.
    #[test]
    fn a_blob_matching_the_saved_copy_is_not_offered() {
        let store = MemModelStore::new();
        assert!(read_entries(&store).is_empty());
        let model = r#"{"expressions":"","configurator":{},"features":[]}"#;
        let pretty = "{\n  \"features\": [],\n  \"configurator\": {},\n  \"expressions\": \"\"\n}";
        store.put("part-a", pretty);
        store.put(
            RECOVERY_KEY,
            &encode(&[
                RecoveryEntry {
                    name: Some("part-a".into()),
                    title: "part-a".into(),
                    saved_at: 1.0,
                    model: model.into(),
                },
                RecoveryEntry {
                    name: Some("part-b".into()),
                    title: "part-b".into(),
                    saved_at: 1.0,
                    model: model.into(),
                },
            ]),
        );
        let entries = read_entries(&store);
        assert_eq!(entries.len(), 1, "part-a is already saved; part-b has no copy");
        assert_eq!(entries[0].name.as_deref(), Some("part-b"));

        store.put(RECOVERY_KEY, r#"{"schema":99,"documents":[{"title":"x","model":"{}"}]}"#);
        assert!(read_entries(&store).is_empty());
        store.put(RECOVERY_KEY, "not json");
        assert!(read_entries(&store).is_empty());
    }

    /// After the prompt resolves, the autosave knows the blob is gone and the
    /// restored (dirty) documents are written again after the debounce.
    #[test]
    fn restored_documents_are_autosaved_again() {
        let store = MemModelStore::new();
        store.put(
            RECOVERY_KEY,
            &encode(&[RecoveryEntry {
                name: Some("part-a".into()),
                title: "part-a".into(),
                saved_at: 1.0,
                model: BOX_SEED.into(),
            }]),
        );
        let mut docs = documents();
        let entries = read_entries(&store);
        restore_entries(&entries, &mut docs);
        store.remove(RECOVERY_KEY).unwrap();
        let mut autosave = Autosave::new();
        autosave.note_cleared();
        docs.refresh_dirty_markers();
        assert!(autosave.tick(&docs, &store, 0.0).is_some(), "a dirty tab arms a write");
        assert!(store.read(RECOVERY_KEY).is_none());
        assert_eq!(autosave.tick(&docs, &store, 2.5), None);
        assert_eq!(read_entries(&store).len(), 1);
    }

    #[test]
    fn age_labels_are_coarse() {
        assert_eq!(age_label(0.0, 100.0), "");
        assert_eq!(age_label(90.0, 100.0), "just now");
        assert_eq!(age_label(100.0, 100.0 + 5.0 * 60.0), "5 min ago");
        assert_eq!(age_label(100.0, 100.0 + 3.0 * 3600.0), "3 h ago");
        assert_eq!(age_label(100.0, 100.0 + 2.0 * 86_400.0), "2 d ago");
    }
}