diff --git a/browser-runtime/docs/architecture.md b/browser-runtime/docs/architecture.md index 1a9a666..622a387 100644 --- a/browser-runtime/docs/architecture.md +++ b/browser-runtime/docs/architecture.md @@ -44,7 +44,7 @@ Duplication stops the runtime before it copies the persistent partition. It then Cookies, site data, history, and bookmarks survive the copy. Later changes remain separate. Profile names carry no special authority. Copies do not inherit agent grants. -The application data path remains unchanged. Old profiles and settings remain available. +The host keeps the profiles and settings in its local app data folder. Before the first start, it moves the data of releases up to 0.1.48 from the roaming folder. Each tab belongs to one RuneStone window. A transfer token moves a live tab between windows. Split panes open independent tabs with the same URL and profile. Find uses Chromium match counts and selection. diff --git a/docs/development.md b/docs/development.md index 3748beb..f7d45ea 100644 --- a/docs/development.md +++ b/docs/development.md @@ -114,6 +114,7 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command | Workspace state: tab order, pins, bookmarks, templates, Project Management boards | `.runestone/` in the workspace | | Installed plugins and their settings | The app data folder. See [plugin storage](plugin-host.md#storage-and-recovery). | | Preferences: general settings, appearance, custom themes, display language | `settings.json` in the app config folder | +| Browser profiles, bookmarks, history, browser settings, and Chromium caches | `browser/` in the local app data folder. On Windows, this is `%LOCALAPPDATA%\com.runestone.app\browser\`. See [Built-in browser runtime](#built-in-browser-runtime). | | Window layout and the open tabs of each workspace | The WebView storage (`localStorage`) of the app. RuneStone can lose these values without harm. | #### The settings file @@ -292,6 +293,11 @@ The installer includes the staged engine from `src-tauri/browser-engine/`. Each browser window gets a session token at startup. Native requests check that token, and cleanup revokes it. +The browser data is in the Tauri `app_local_data_dir()`. Releases up to 0.1.48 kept it in `app_data_dir()`, which roams on Windows. +Before the engine starts, `src-tauri/src/browser.rs` moves an old `browser` folder to the new place. Across volumes, it copies the folder and then deletes the old one. +If the new folder exists, the host uses it and leaves the old folder. If the move fails, the engine does not start, and the error names both folders. +On macOS and Linux, the two folders are the same, so nothing moves. + ## Development help | Problem | Action | diff --git a/src-tauri/src/browser.rs b/src-tauri/src/browser.rs index 03e0e65..5bbd852 100644 --- a/src-tauri/src/browser.rs +++ b/src-tauri/src/browser.rs @@ -110,9 +110,40 @@ struct Worker { healthy: bool, } +/// Browser profiles, settings, and Chromium state. On Windows this is Local AppData, +/// so that the Chromium caches stay out of the roaming profile. fn root(app: &AppHandle) -> Result { + Ok(app.path().app_local_data_dir()?.join("browser")) +} +/// Releases up to 0.1.48 kept the browser data in the app data folder, which roams on Windows. +fn legacy_root(app: &AppHandle) -> Result { Ok(app.path().app_data_dir()?.join("browser")) } +/// Move the browser data of an earlier release from `legacy` to `current`. The engine must not run. +/// Nothing moves when the paths are the same, when `legacy` does not exist, or when `current` exists. +/// When the rename fails, for example across volumes, copy the folder. `legacy` stays until the copy is complete. +fn migrate_profiles(legacy: &Path, current: &Path, rename: impl Fn(&Path, &Path) -> std::io::Result<()>) -> Result<()> { + if legacy == current || !legacy.is_dir() || fs::symlink_metadata(current).is_ok() { + return Ok(()); + } + let failed = |error: Error| -> Error { + format!("RuneStone could not move the browser profiles from {} to {}: {error}", legacy.display(), current.display()).into() + }; + let parent = current.parent().ok_or("Invalid browser profile folder.")?; + fs::create_dir_all(parent).map_err(|error| failed(error.into()))?; + if rename(legacy, current).is_ok() { + return Ok(()); + } + let temporary = parent.join(format!(".browser-move-{}", uuid::Uuid::new_v4().simple())); + let copied = copy_profile(legacy, &temporary, &mut 0, &mut 0, false).and_then(|()| Ok(rename(&temporary, current)?)); + if let Err(error) = copied { + let _ = fs::remove_dir_all(&temporary); + return Err(failed(error)); + } + // The copy is complete. If the removal fails, only an old copy stays behind. + let _ = fs::remove_dir_all(legacy); + Ok(()) +} fn executable(app: &AppHandle) -> Result { let name = if cfg!(windows) { "RuneStone-Browser.exe" @@ -166,6 +197,7 @@ fn authenticate_connection( impl Worker { fn start(app: &AppHandle, routing: Arc>) -> Result { let directory = root(app)?; + migrate_profiles(&legacy_root(app)?, &directory, |from, to| fs::rename(from, to))?; fs::create_dir_all(&directory)?; let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?; listener.set_nonblocking(true)?; @@ -351,7 +383,8 @@ fn profile_id(value: &str) -> bool { .bytes() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-') } -fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64) -> Result<()> { +/// Copy a profile folder and refuse links. `limited` applies the limit for profile duplication. +fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64, limited: bool) -> Result<()> { if !source.exists() { fs::create_dir_all(target)?; return Ok(()); @@ -365,12 +398,12 @@ fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64 fs::create_dir_all(target)?; for entry in fs::read_dir(source)? { let entry = entry?; - copy_profile(&entry.path(), &target.join(entry.file_name()), files, bytes)?; + copy_profile(&entry.path(), &target.join(entry.file_name()), files, bytes, limited)?; } } else if metadata.is_file() { *files += 1; *bytes += metadata.len(); - if *files > 50_000 || *bytes > 2_000_000_000 { + if limited && (*files > 50_000 || *bytes > 2_000_000_000) { return Err("This profile exceeds the duplication limit.".into()); } fs::copy(source, target)?; @@ -517,7 +550,7 @@ impl BrowserState { if destination.exists() { return Err("The destination profile already exists.".into()); } - copy_profile(&source, &destination, &mut 0, &mut 0)?; + copy_profile(&source, &destination, &mut 0, &mut 0, true)?; *guard = Some(Worker::start(app, routing.clone())?); let result = guard.as_mut().unwrap().request("commitDuplicate", plan)?; let snapshot = routing.lock()?.snapshot(result, owner); @@ -744,7 +777,7 @@ mod tests { fs::create_dir_all(&outside).unwrap(); fs::write(source.join("Cookies"), b"cookies").unwrap(); fs::write(outside.join("secret.txt"), b"secret").unwrap(); - copy_profile(&source, &base.join("plain"), &mut 0, &mut 0).unwrap(); + copy_profile(&source, &base.join("plain"), &mut 0, &mut 0, true).unwrap(); assert_eq!(fs::read(base.join("plain").join("Cookies")).unwrap(), b"cookies"); let link = source.join("linked"); // A junction needs no symbolic-link privilege on Windows. @@ -759,7 +792,7 @@ mod tests { .success()); #[cfg(unix)] std::os::unix::fs::symlink(&outside, &link).unwrap(); - let error = copy_profile(&source, &base.join("copy"), &mut 0, &mut 0).unwrap_err(); + let error = copy_profile(&source, &base.join("copy"), &mut 0, &mut 0, true).unwrap_err(); assert!(error.to_string().contains("links"), "{error}"); assert!(!base.join("copy").join("linked").join("secret.txt").exists()); #[cfg(windows)] @@ -788,6 +821,76 @@ mod tests { assert!(worker.healthy); assert_eq!(worker.request("state", json!({})).unwrap(), json!({ "tabs": [] })); } + fn profile_fixture(base: &Path) -> (PathBuf, PathBuf) { + let legacy = base.join("Roaming").join("browser"); + fs::create_dir_all(legacy.join("Partitions").join("runestone-user")).unwrap(); + fs::write(legacy.join("browser.json"), b"{\"version\":1}").unwrap(); + fs::write(legacy.join("Partitions").join("runestone-user").join("Cookies"), b"cookies").unwrap(); + (legacy, base.join("Local").join("browser")) + } + fn temporary_base() -> PathBuf { + std::env::temp_dir().join(format!("runestone-migrate-{}", uuid::Uuid::new_v4())) + } + #[test] + fn migration_moves_profiles_and_keeps_existing_ones() { + let base = temporary_base(); + let (legacy, current) = profile_fixture(&base); + migrate_profiles(&legacy, ¤t, |from, to| fs::rename(from, to)).unwrap(); + assert!(!legacy.exists()); + assert_eq!(fs::read(current.join("Partitions").join("runestone-user").join("Cookies")).unwrap(), b"cookies"); + // A second start finds no old folder. + migrate_profiles(&legacy, ¤t, |_, _| panic!("Nothing must move.")).unwrap(); + // When both folders exist, the new one wins and the old one stays. + let (legacy, _) = profile_fixture(&base); + fs::write(current.join("browser.json"), b"current").unwrap(); + migrate_profiles(&legacy, ¤t, |_, _| panic!("Nothing must move.")).unwrap(); + assert_eq!(fs::read(current.join("browser.json")).unwrap(), b"current"); + assert!(legacy.join("browser.json").exists()); + // The same path (macOS and Linux) and a missing old folder change nothing. + migrate_profiles(¤t, ¤t, |_, _| panic!("Nothing must move.")).unwrap(); + let empty = base.join("empty"); + migrate_profiles(&base.join("missing"), &empty, |_, _| panic!("Nothing must move.")).unwrap(); + assert!(!empty.exists()); + fs::remove_dir_all(&base).unwrap(); + } + #[test] + fn migration_copies_when_the_rename_fails() { + let base = temporary_base(); + let (legacy, current) = profile_fixture(&base); + let source = legacy.clone(); + let across_volumes = |from: &Path, to: &Path| { + if from == source { Err(std::io::Error::other("not the same device")) } else { fs::rename(from, to) } + }; + migrate_profiles(&legacy, ¤t, across_volumes).unwrap(); + assert!(!legacy.exists()); + assert_eq!(fs::read(current.join("browser.json")).unwrap(), b"{\"version\":1}"); + assert_eq!(fs::read(current.join("Partitions").join("runestone-user").join("Cookies")).unwrap(), b"cookies"); + let names: Vec<_> = fs::read_dir(base.join("Local")).unwrap().map(|entry| entry.unwrap().file_name()).collect(); + assert_eq!(names, vec![std::ffi::OsString::from("browser")], "No temporary copy stays."); + fs::remove_dir_all(&base).unwrap(); + } + #[test] + fn a_failed_copy_keeps_the_old_profiles() { + let base = temporary_base(); + let (legacy, current) = profile_fixture(&base); + let outside = base.join("outside"); + fs::create_dir_all(&outside).unwrap(); + let link = legacy.join("linked"); + #[cfg(windows)] + assert!(Command::new("cmd").args(["/C", "mklink", "/J"]).arg(&link).arg(&outside).stdout(Stdio::null()).status().unwrap().success()); + #[cfg(unix)] + std::os::unix::fs::symlink(&outside, &link).unwrap(); + let error = migrate_profiles(&legacy, ¤t, |_, _| Err(std::io::Error::other("not the same device"))).unwrap_err(); + assert!(error.to_string().contains("could not move the browser profiles"), "{error}"); + assert!(legacy.join("browser.json").exists()); + assert!(!current.exists()); + assert_eq!(fs::read_dir(base.join("Local")).unwrap().count(), 0, "No temporary copy stays."); + #[cfg(windows)] + fs::remove_dir(&link).unwrap(); + #[cfg(unix)] + fs::remove_file(&link).unwrap(); + fs::remove_dir_all(&base).unwrap(); + } #[test] fn profile_names_cannot_escape_storage() { for value in ["../other", "a/b", "a\\b", "C:", "", "."] {