diff --git a/apps/solidcraft-web/src/disk.rs b/apps/solidcraft-web/src/disk.rs index dc3396903..19af6aa5f 100644 --- a/apps/solidcraft-web/src/disk.rs +++ b/apps/solidcraft-web/src/disk.rs @@ -59,6 +59,34 @@ pub fn make_id(ms: u64, random: u64) -> String { format!("{ms:x}-{random:x}") } +/// How long a remembered file may go unused, and unreferenced by the recent designs and the +/// autosave, before the browser's copy of its handle is dropped. +pub const HANDLE_MAX_AGE_MS: f64 = 90.0 * 24.0 * 3600.0 * 1000.0; + +/// What to do with the remembered handles. +#[derive(Debug, Default, PartialEq)] +pub struct PrunePlan { + /// Handles to forget. + pub delete: Vec, + /// Handles seen unused for the first time: start their clock. + pub stamp: Vec, +} + +/// Decide which of the remembered handles `ids` (id, when it was last stamped) to forget: those +/// that no recent design or autosave (`keep`) names and that have gone unused for `max_age`. One +/// never stamped starts its clock now, so a file another tab has just saved is never dropped. +pub fn plan_prune(ids: &[(String, Option)], keep: &std::collections::HashSet, now: f64, max_age: f64) -> PrunePlan { + let mut plan = PrunePlan::default(); + for (id, stamped) in ids.iter().filter(|(id, _)| !keep.contains(id)) { + match stamped { + None => plan.stamp.push(id.clone()), + Some(at) if now - at > max_age => plan.delete.push(id.clone()), + Some(_) => {} + } + } + plan +} + /// Where a design saved with Save As goes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SaveTarget { @@ -112,7 +140,7 @@ mod web { use wasm_bindgen_futures::{JsFuture, spawn_local}; use web_sys::{FileSystemFileHandle, IdbDatabase, IdbObjectStore, IdbOpenDbRequest, IdbRequest, IdbTransactionMode}; - use super::{is_abort, make_id, opens_design, parse, path, save_type}; + use super::{HANDLE_MAX_AGE_MS, is_abort, make_id, opens_design, parse, path, plan_prune, save_type}; use crate::files::{Files, err, read_handle}; const DB: &str = "solidcraft-disk-handles"; @@ -397,10 +425,106 @@ mod web { db.transaction_with_str_and_mode(STORE, mode).map_err(err)?.object_store(STORE).map_err(err) } + /// Key of the time a handle was last used (the handle's own key is its id). + fn stamp_key(id: &str) -> String { + format!("at:{id}") + } + async fn remember(id: &str, handle: &FileSystemFileHandle) -> Result<(), String> { let db = open_db().await?; - let req = store(&db, IdbTransactionMode::Readwrite)?.put_with_key(handle, &id.into()).map_err(err)?; - result(&req).await.map(|_| ()) + let store = store(&db, IdbTransactionMode::Readwrite)?; + result(&store.put_with_key(handle, &id.into()).map_err(err)?).await?; + result(&store.put_with_key(&js_sys::Date::now().into(), &stamp_key(id).into()).map_err(err)?).await.map(|_| ()) + } + + /// Note that the file was used now. + async fn touch(id: &str) { + let Ok(db) = open_db().await else { return }; + if let Ok(store) = store(&db, IdbTransactionMode::Readwrite) + && let Ok(req) = store.put_with_key(&js_sys::Date::now().into(), &stamp_key(id).into()) + { + let _ = result(&req).await; + } + } + + /// The ids of every remembered file. + pub async fn known_ids() -> Result, String> { + let db = open_db().await?; + let req = store(&db, IdbTransactionMode::Readonly)?.get_all_keys().map_err(err)?; + let keys: Array = result(&req).await?.dyn_into().map_err(|_| "no keys".to_string())?; + Ok(keys.iter().filter_map(|k| k.as_string()).filter(|k| !k.starts_with("at:")).collect()) + } + + async fn forget(ids: &[String]) -> Result<(), String> { + let db = open_db().await?; + let store = store(&db, IdbTransactionMode::Readwrite)?; + for id in ids { + result(&store.delete(&id.as_str().into()).map_err(err)?).await?; + result(&store.delete(&stamp_key(id).into()).map_err(err)?).await?; + HANDLES.with(|h| h.borrow_mut().remove(id)); + } + Ok(()) + } + + /// Forget the remembered files nothing refers to any more (`keep`: the ids the recent designs + /// and the autosave name), once they have gone unused for a long while. + pub fn prune(keep: std::collections::HashSet) { + spawn_local(async move { + let r = async { + // A transaction ends when the page awaits anything but its own requests, so each + // step opens its own. + let known = known_ids().await?; + let db = open_db().await?; + let reading = store(&db, IdbTransactionMode::Readonly)?; + let mut ids = Vec::new(); + for id in known { + let at = result(&reading.get(&stamp_key(&id).into()).map_err(err)?).await?.as_f64(); + ids.push((id, at)); + } + let plan = plan_prune(&ids, &keep, js_sys::Date::now(), HANDLE_MAX_AGE_MS); + for id in &plan.stamp { + touch(id).await; + } + forget(&plan.delete).await + }; + if let Err(e) = r.await { + log::warn!("remembered files weren't tidied: {e}"); + } + }); + } + + /// Open a design remembered from an earlier session (a recent one, after a reload): ask once + /// for access to the file (call in the click), read it into the engine's files and queue it + /// to open. A file that is gone is forgotten and dropped from the recent designs. + pub fn restore(files: &Rc, path: &str) { + let Some((id, name)) = parse(path) else { return }; + let (files, path, id, name) = (files.clone(), path.to_string(), id.to_string(), name.to_string()); + spawn_local(async move { + let r = async { + let handle = handle_for(&id).await?; + ensure_readwrite(&handle).await?; + read_handle(&handle).await + }; + match r.await { + Ok(bytes) => { + vfs::insert(&path, bytes); + files.opened.borrow_mut().push(path); + files.wake(); + touch(&id).await; + } + Err(e) => { + let gone = e.contains("NotFoundError") || e.contains("could not be found") || e.contains("no longer remembers"); + if gone { + let _ = forget(std::slice::from_ref(&id)).await; + files.disk_known.borrow_mut().remove(&id); + files.gone.borrow_mut().push(path); + files.say(format!("{name} isn't where it was saved any more"), true); + } else { + files.say(format!("{name}: {e}"), true); + } + } + } + }); } async fn recall(id: &str) -> Result, String> { @@ -455,6 +579,22 @@ mod tests { assert_eq!(route("/upload/part.step"), WriteTo::Memory); } + #[test] + fn only_unreferenced_handles_unused_for_long_are_forgotten() { + let keep: std::collections::HashSet = ["recent".to_string()].into(); + let day = 24.0 * 3600.0 * 1000.0; + let now = 1000.0 * day; + let ids = vec![ + ("recent".to_string(), Some(now - 200.0 * day)), + ("old".to_string(), Some(now - 100.0 * day)), + ("fresh".to_string(), Some(now - 5.0 * day)), + ("unstamped".to_string(), None), + ]; + let plan = plan_prune(&ids, &keep, now, HANDLE_MAX_AGE_MS); + assert_eq!(plan, PrunePlan { delete: vec!["old".to_string()], stamp: vec!["unstamped".to_string()] }); + assert_eq!(plan_prune(&[], &keep, now, HANDLE_MAX_AGE_MS), PrunePlan::default()); + } + #[test] fn handle_ids_differ_by_time_and_by_chance() { assert_ne!(make_id(1, 5), make_id(2, 5)); diff --git a/apps/solidcraft-web/src/files.rs b/apps/solidcraft-web/src/files.rs index 79341a976..4c3169773 100644 --- a/apps/solidcraft-web/src/files.rs +++ b/apps/solidcraft-web/src/files.rs @@ -57,6 +57,10 @@ pub struct Files { pub incoming: RefCell, Intent)>>, /// Designs opened from the computer's disk: their paths in the engine's files. pub opened: RefCell>, + /// The ids of the files remembered from earlier sessions (see `disk::restore`). + pub disk_known: RefCell>, + /// Recent designs whose file is gone: to drop from the recent list. + pub gone: RefCell>, /// Disk designs whose last write failed: they are not saved. pub unsaved: RefCell>, /// Messages for the status line (errors and confirmations). @@ -90,7 +94,7 @@ impl Files { } /// Run a frame (the app sleeps until something happens). - fn wake(&self) { + pub fn wake(&self) { if let Some(c) = self.ctx.borrow().as_ref() { c.request_repaint(); } @@ -267,6 +271,10 @@ pub fn start(files: &Rc) { } let files = files.clone(); spawn_local(async move { + match disk::known_ids().await { + Ok(ids) => files.disk_known.borrow_mut().extend(ids), + Err(e) => log::info!("no remembered files: {e}"), + } match read_all().await { Ok(all) => { if local_only() { diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index feb74f40a..49414f2d2 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -136,6 +136,11 @@ mod web { self.app.open_path(&path); self.files.panel.set(false); } + // Recent designs whose file is gone are dropped from the list. + for path in self.files.gone.borrow_mut().drain(..) { + self.app.home.recent.retain(|r| *r != path); + self.app.home.opened_at.remove(&path); + } for (text, error) in self.files.messages.borrow_mut().drain(..) { self.app.set_status(text, error); } @@ -203,7 +208,9 @@ mod web { let mut entries = self.files.entries.borrow().clone(); entries.sort_by(|a, b| b.modified.total_cmp(&a.modified)); let recent = &mut self.app.home.recent; - recent.retain(|p| vfs::exists(p)); + let known = self.files.disk_known.borrow().clone(); + // A design on the computer's disk stays listed while its file is remembered. + recent.retain(|p| vfs::exists(p) || disk::parse(p).is_some_and(|(id, _)| known.contains(id))); for e in entries.iter().filter(|e| solidcraft_engine::io::is_design_path(&e.name)) { let p = format!("{}{}", files::OPFS, e.name); if !recent.contains(&p) { @@ -211,6 +218,10 @@ mod web { } } recent.truncate(solidcraft_ui_egui::home::MAX_RECENT); + // Remembered files that no recent design or autosave names are forgotten in time. + let recovered = self.files.recovery.borrow().as_ref().and_then(|(_, p)| p.clone()); + let keep = recent.iter().chain(recovered.as_ref()).filter_map(|p| disk::parse(p)).map(|(id, _)| id.to_string()).collect(); + disk::prune(keep); } /// The stored designs: open, insert, rename, delete, download; open from the computer. @@ -563,6 +574,7 @@ mod web { let files = Rc::new(Files::default()); files::start(&files); let (panel, opener, saver, shown) = (files.clone(), files.clone(), files.clone(), files.clone()); + let (restorable, restorer) = (files.clone(), files.clone()); let services = Services { // Open shows the browser's open dialog for a design where it has one // (the file keeps its handle, so Save writes back to it); otherwise, @@ -587,6 +599,12 @@ mod web { SaveTarget::Download => Box::pin(std::future::ready(Some(format!("{}{name}", files::DOWNLOADS)))), } })), + // A recent design on the disk, from an earlier session, opens by asking + // the browser for its remembered file. + can_restore: Some(Box::new(move |path: &str| { + disk::parse(path).is_some_and(|(id, _)| restorable.disk_known.borrow().contains(id)) + })), + restore_file: Some(Box::new(move |path: &str| disk::restore(&restorer, path))), download_design: Some(Box::new(files::download)), browser_files: Some(Box::new(move || shown.panel.set(true))), install_app: Some(crate::install::service(&cc.egui_ctx)), diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index d80917d73..5b22a549b 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -210,6 +210,8 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services { http_download: Some(std::sync::Arc::new(http_download)), // Already an installed app: only the browser build offers to install. install_app: None, + can_restore: None, + restore_file: None, download_design: None, browser_files: None, agent_http: Some(std::sync::Arc::new(agent_http)), diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index 3fd5d3a09..3dc2cd8cd 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -425,8 +425,17 @@ pub fn open_sample(app: &mut SolveApp, i: usize) { } } +/// Is this recent design there to open: in memory, or something the host can bring back? +pub fn available(app: &SolveApp, path: &str) -> bool { + solidcraft_engine::io::vfs::exists(path) || app.services.can_restore.as_ref().is_some_and(|can| can(path)) +} + pub fn open_recent(app: &mut SolveApp, path: &str) { if !solidcraft_engine::io::vfs::exists(path) { + if let Some(restore) = app.services.restore_file.as_ref().filter(|_| available(app, path)) { + restore(path); + return; + } app.set_status(format!("{path} is no longer there"), true); return; } @@ -529,9 +538,12 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let Some(p) = recent.get(i) else { return }; let path = std::path::Path::new(p); let name = path.file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| p.clone()); - let missing = !solidcraft_engine::io::vfs::exists(p); + let missing = !available(app, p); let mut sub = if missing { app.tr("home.missing").to_string() + } else if p.starts_with("/disk/") { + // The web build remembers files it saved on the computer. + crate::i18n::tr_label("On your computer").to_string() } else if p.starts_with("/opfs/") { // The web build keeps designs in the browser's own storage. app.tr("home.in_this_browser").to_string() @@ -695,6 +707,24 @@ mod tests { assert!(sample_picture(samples.len()).is_none()); } + /// A recent design the host can bring back (the browser build's remembered files) is not + /// "missing": choosing it asks the host to restore it, and one the host doesn't know still is. + #[test] + fn a_recent_design_the_host_can_restore_is_asked_for_not_reported_missing() { + let mut h = crate::scenario::Harness::new(); + let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::::new())); + let sink = asked.clone(); + h.app.services.can_restore = Some(Box::new(|p| p.starts_with("/disk/known/"))); + h.app.services.restore_file = Some(Box::new(move |p| sink.borrow_mut().push(p.to_string()))); + assert!(available(&h.app, "/disk/known/Bracket.solidcraft")); + assert!(!available(&h.app, "/disk/other/Bracket.solidcraft")); + open_recent(&mut h.app, "/disk/known/Bracket.solidcraft"); + assert_eq!(*asked.borrow(), ["/disk/known/Bracket.solidcraft"]); + open_recent(&mut h.app, "/disk/other/Bracket.solidcraft"); + assert_eq!(asked.borrow().len(), 1, "a file the host doesn't remember is not asked for"); + assert!(h.app.status.as_ref().is_some_and(|(text, _, error)| *error && text.contains("no longer there"))); + } + /// Rebuild the shipped pictures from the authoritative sample command scripts. #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2f5e5148b..f142dd786 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -332,6 +332,12 @@ pub struct Services { /// Hand a design's bytes to the user as a downloaded file (name, bytes); the browser build's /// File > Download design. None: the host saves real files, so there is nothing to offer. pub download_design: Option Result<(), String>>>, + /// Whether a recent design that is not in memory can be brought back by the host (the browser + /// build remembers files it saved to the disk); None: it can't. + pub can_restore: Option bool>>, + /// Bring such a design back and open it when it arrives (asks the user for access, so call it + /// in the click that chose it). + pub restore_file: Option>, /// Show the designs the browser keeps for itself; None: the host has no such store. pub browser_files: Option>, /// HTTP for the agent chat's API agents (OpenAI-compatible endpoints); None: no API agents. diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 787254f2a..6cd97f516 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -503,7 +503,7 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { } crate::ui_kit::Menu::button(ui, app.tr("ui.open_recent"), |ui| { for path in app.home.recent.clone() { - let missing = !solidcraft_engine::io::vfs::exists(&path); + let missing = !crate::home::available(app, &path); let label = format!("{path}{}", if missing { " (missing)" } else { "" }); if crate::context_menu::button(ui, &label, "open").clicked() { crate::home::open_recent(app, &path);