Keep preferences in one settings file and move tab transfer to the host

Keep the user preferences in settings.json in the app config folder.
WebView storage can be lost, and the host cannot read it. The file has
a schema number, a revision number, and one value for each section:
general, appearance, customThemes, customThemesLegacy, and language.
- settings_read gives all sections, the revision, and a one-time
  notice.
- settings_write replaces one section, writes the file atomically, and
  sends settings-changed to all windows. The limit is 8 MiB.
- settings_migrate writes the first file only when no file exists.
- The host moves a damaged file to settings.corrupt-<seconds>.json,
  starts from the defaults, and reports this one time.

Each window loads the sections before its first render. One store in
src/lib/settings/store.ts replaces the storage listeners. When no file
exists, the window normalizes the old localStorage values and migrates
them. The old keys stay in place for one release. The window layout
and the open tabs stay in localStorage on purpose. The browser preview
keeps all preferences in localStorage.

Keep tab transfer offers in host memory, not in localStorage, because
an offer can hold unsaved text. A window takes an offer once. The host
checks the workspace root and a 120 second expiry. When the receiver
accepts the tab, the host sends tab-transfer-accepted to the source
window only. A refused offer stays open, and the source tab stays open.
A new window and a drop on the tab ribbon use one check.

The smoke harness serves the new commands from one shared state for
each browser context. Tests read saved values from the mock settings
file. Rust, unit, and smoke tests cover the changes.
This commit is contained in:
Knotty Wyvern
2026-10-27 23:56:00 -07:00
parent a0eef01ed0
commit 5d5ba9e1f7
51 changed files with 1665 additions and 213 deletions
+12
View File
@@ -9,6 +9,8 @@ mod browser;
mod git;
mod completion;
mod settings;
mod preferences;
mod tab_transfer;
mod spelling;
mod theme;
mod backgrounds;
@@ -28,6 +30,8 @@ pub fn run() {
.manage(browser::BrowserState::default())
.manage(completion::CompletionState::default())
.manage(settings::SettingsState::default())
.manage(preferences::PreferencesState::default())
.manage(tab_transfer::TabTransferState::default())
.invoke_handler(tauri::generate_handler![
backgrounds::backgrounds_choose_folder,
backgrounds::backgrounds_default_folder,
@@ -41,6 +45,13 @@ pub fn run() {
spelling::spelling_menu_select,
spelling::spelling_menu_uninstall,
settings::settings_open_window,
preferences::settings_read,
preferences::settings_write,
preferences::settings_migrate,
tab_transfer::tab_transfer_offer,
tab_transfer::tab_transfer_take,
tab_transfer::tab_transfer_finish,
tab_transfer::tab_transfer_cancel,
completion::completion_request,
completion::completion_cancel,
browser::browser_request,
@@ -110,6 +121,7 @@ pub fn run() {
// with short locks only. A cleanup thread stops processes and erases files.
settings::close_owned_window(app, label);
spelling::close_window(app, label);
app.state::<tab_transfer::TabTransferState>().release_window(label);
app.state::<completion::CompletionState>().close_window(label);
let browser_tabs = app.state::<browser::BrowserState>().release_window(label);
let staging = app.state::<plugins::PluginState>().try_release_window(label);
+403
View File
@@ -0,0 +1,403 @@
//! User preferences in one file: `<app config dir>/settings.json`.
//!
//! The file holds a `schema` number, a `revision` number, and one value for each section.
//! The host does not interpret the section values. The frontend normalizes them.
//! Every write replaces the complete file atomically and sends `settings-changed` to all windows.
//! Plugin settings stay in the app data folder (see `plugins.rs`).
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use serde::Serialize;
use serde_json::{Map, Value};
use tauri::{AppHandle, Emitter, Manager};
use crate::error::{Error, Result};
use crate::fsutil;
pub const FILE_NAME: &str = "settings.json";
pub const SCHEMA: u64 = 1;
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
pub const SECTIONS: [&str; 5] = ["general", "appearance", "customThemes", "customThemesLegacy", "language"];
/// The appearance section can hold an image data URL of up to 3,000,000 characters.
pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
pub const CHANGED_EVENT: &str = "settings-changed";
/// All sections, as the frontend reads them at startup.
#[derive(Serialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Snapshot {
/// False when no settings file exists yet. The frontend then migrates its old values.
pub exists: bool,
pub revision: u64,
pub sections: Map<String, Value>,
/// A message for the user, sent once after the host replaced a damaged file.
#[serde(skip_serializing_if = "Option::is_none")]
pub notice: Option<String>,
}
/// The payload of `settings-changed`.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Change {
pub section: String,
pub revision: u64,
pub value: Value,
}
struct Loaded {
document: Map<String, Value>,
exists: bool,
notice: Option<String>,
}
/// The settings file and its in-memory copy. One lock serializes all reads and writes.
pub struct Store {
path: PathBuf,
loaded: Option<Loaded>,
}
fn empty_document() -> Map<String, Value> {
let mut document = Map::new();
document.insert("schema".into(), SCHEMA.into());
document.insert("revision".into(), 0.into());
document
}
fn revision(document: &Map<String, Value>) -> u64 {
document.get("revision").and_then(Value::as_u64).unwrap_or(0)
}
fn check_section(section: &str) -> Result<()> {
if SECTIONS.contains(&section) { Ok(()) } else { Err(Error::new(format!("Unknown settings section: {section}"))) }
}
/// Parse the file. `None` means that the file is damaged.
fn parse(bytes: &[u8]) -> Option<Map<String, Value>> {
if bytes.len() > MAX_FILE_BYTES { return None; }
let Value::Object(document) = serde_json::from_slice(bytes).ok()? else { return None };
let schema = document.get("schema").and_then(Value::as_u64)?;
if schema == 0 { return None; }
if document.get("revision").is_some_and(|value| value.as_u64().is_none()) { return None; }
Some(document)
}
fn encode(document: &Map<String, Value>) -> Result<Vec<u8>> {
let mut bytes = serde_json::to_vec_pretty(document)?;
bytes.push(b'\n');
if bytes.len() > MAX_FILE_BYTES {
return Err(Error::new("The settings are larger than 8 MiB. Remove the background image data or some custom themes, then try again."));
}
Ok(bytes)
}
fn temp_path(path: &Path) -> Result<PathBuf> {
let parent = path.parent().ok_or_else(|| Error::new("The settings file has no folder."))?;
Ok(parent.join(format!(".settings-{}.tmp", uuid::Uuid::new_v4())))
}
/// Move a damaged file aside to `settings.corrupt-<seconds>.json`, with a counter if that name exists.
fn keep_damaged_copy(path: &Path) -> Result<PathBuf> {
let seconds = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
let parent = path.parent().ok_or_else(|| Error::new("The settings file has no folder."))?;
for attempt in 0..100u32 {
let name = if attempt == 0 { format!("settings.corrupt-{seconds}.json") } else { format!("settings.corrupt-{seconds}-{attempt}.json") };
let copy = parent.join(name);
match fsutil::rename_no_replace(path, &copy) {
Ok(()) => return Ok(copy),
Err(reason) if reason.kind() == io::ErrorKind::AlreadyExists => continue,
Err(reason) => return Err(reason.into()),
}
}
Err(Error::new("Could not keep a copy of the damaged settings file."))
}
impl Store {
pub fn new(path: PathBuf) -> Self {
Self { path, loaded: None }
}
fn load(&mut self) -> Result<&mut Loaded> {
if self.loaded.is_none() {
self.loaded = Some(self.read_file()?);
}
Ok(self.loaded.as_mut().expect("loaded above"))
}
fn read_file(&self) -> Result<Loaded> {
let bytes = match fsutil::open_entry(&self.path) {
Ok(file) => fsutil::read_to_limit(file, MAX_FILE_BYTES as u64)?,
Err(reason) if reason.kind() == io::ErrorKind::NotFound => {
return Ok(Loaded { document: empty_document(), exists: false, notice: None });
}
Err(reason) => return Err(Error::new(format!("Could not read the settings file {}: {reason}", self.path.display()))),
};
if let Some(document) = bytes.as_deref().and_then(parse) {
return Ok(Loaded { document, exists: true, notice: None });
}
// Keep the damaged file for the user, then start again from the defaults.
let copy = keep_damaged_copy(&self.path)?;
let document = empty_document();
fsutil::create_file(&self.path, &temp_path(&self.path)?, &encode(&document)?)?;
let notice = format!(
"RuneStone could not read your settings file, so the default settings apply. A copy of the damaged file is at {}.",
copy.display()
);
Ok(Loaded { document, exists: true, notice: Some(notice) })
}
/// All known sections. The notice of a replaced file goes to the first reader only.
pub fn read(&mut self) -> Result<Snapshot> {
let loaded = self.load()?;
let sections = SECTIONS.iter()
.filter_map(|name| loaded.document.get(*name).map(|value| ((*name).to_owned(), value.clone())))
.collect();
Ok(Snapshot { exists: loaded.exists, revision: revision(&loaded.document), sections, notice: loaded.notice.take() })
}
/// Replace one section. `null` removes it. Unknown top-level keys stay in the file.
pub fn write(&mut self, section: &str, value: Value) -> Result<Change> {
check_section(section)?;
let path = self.path.clone();
let loaded = self.load()?;
let mut document = loaded.document.clone();
let next = revision(&document) + 1;
if value.is_null() { document.remove(section); } else { document.insert(section.into(), value.clone()); }
document.insert("revision".into(), next.into());
if document.get("schema").and_then(Value::as_u64).is_none_or(|schema| schema < SCHEMA) {
document.insert("schema".into(), SCHEMA.into());
}
let bytes = encode(&document)?;
if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; }
fsutil::replace_file(&path, &temp_path(&path)?, &bytes)
.map_err(|reason| Error::new(format!("Could not save the settings file {}: {reason}", path.display())))?;
loaded.document = document;
loaded.exists = true;
Ok(Change { section: section.into(), revision: next, value })
}
/// Write the first file from the migrated values. When a file exists, keep it and return it unchanged.
pub fn migrate(&mut self, sections: Map<String, Value>) -> Result<Snapshot> {
for name in sections.keys() { check_section(name)?; }
let path = self.path.clone();
if self.load()?.exists { return self.read(); }
let mut document = empty_document();
document.insert("revision".into(), 1.into());
for (name, value) in sections {
if !value.is_null() { document.insert(name, value); }
}
let bytes = encode(&document)?;
if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; }
match fsutil::create_file(&path, &temp_path(&path)?, &bytes) {
Ok(()) => {
let loaded = self.load()?;
loaded.document = document;
loaded.exists = true;
}
// Another process wrote the file first. Use its values.
Err(reason) if reason.kind() == io::ErrorKind::AlreadyExists => self.loaded = None,
Err(reason) => return Err(Error::new(format!("Could not create the settings file {}: {reason}", path.display()))),
}
self.read()
}
}
#[derive(Default)]
pub struct PreferencesState(Mutex<Option<Store>>);
fn settings_path(app: &AppHandle) -> Result<PathBuf> {
Ok(app.path().app_config_dir().map_err(|reason| Error::new(format!("app config dir: {reason}")))?.join(FILE_NAME))
}
/// Run `task` with the store on a blocking thread, because it reads and writes files.
async fn with_store<T: Send + 'static>(app: &AppHandle, task: impl FnOnce(&mut Store) -> Result<T> + Send + 'static) -> Result<T> {
let app = app.clone();
tauri::async_runtime::spawn_blocking(move || {
let state = app.state::<PreferencesState>();
let mut guard = state.0.lock()?;
if guard.is_none() { *guard = Some(Store::new(settings_path(&app)?)); }
task(guard.as_mut().expect("set above"))
}).await?
}
#[tauri::command]
pub async fn settings_read(app: AppHandle) -> Result<Snapshot> {
with_store(&app, Store::read).await
}
#[tauri::command]
pub async fn settings_write(app: AppHandle, section: String, value: Value) -> Result<Change> {
let change = with_store(&app, move |store| store.write(&section, value)).await?;
// Every window shows the same preferences, so the change goes to all of them.
let _ = app.emit(CHANGED_EVENT, &change);
Ok(change)
}
#[tauri::command]
pub async fn settings_migrate(app: AppHandle, sections: Map<String, Value>) -> Result<Snapshot> {
with_store(&app, move |store| store.migrate(sections)).await
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::fs;
fn fixture(name: &str) -> (PathBuf, PathBuf) {
let dir = std::env::temp_dir().join(format!("rs-preferences-{name}-{}", uuid::Uuid::new_v4()));
fs::create_dir(&dir).unwrap();
let path = dir.join(FILE_NAME);
(dir, path)
}
fn on_disk(path: &Path) -> Value {
serde_json::from_slice(&fs::read(path).unwrap()).unwrap()
}
fn files(dir: &Path) -> Vec<String> {
let mut names: Vec<_> = fs::read_dir(dir).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
}
#[test]
fn a_missing_file_reads_as_empty_and_does_not_exist() {
let (dir, path) = fixture("missing");
let snapshot = Store::new(path.clone()).read().unwrap();
assert_eq!(snapshot, Snapshot { exists: false, revision: 0, sections: Map::new(), notice: None });
assert!(!path.exists());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn writes_replace_one_section_and_increase_the_revision() {
let (dir, path) = fixture("write");
let mut store = Store::new(path.clone());
let first = store.write("general", json!({ "autosaveSeconds": 7 })).unwrap();
assert_eq!(first, Change { section: "general".into(), revision: 1, value: json!({ "autosaveSeconds": 7 }) });
let second = store.write("language", json!("fr")).unwrap();
assert_eq!(second.revision, 2);
assert_eq!(on_disk(&path), json!({ "schema": SCHEMA, "revision": 2, "general": { "autosaveSeconds": 7 }, "language": "fr" }));
// A new store reads the same values from the file.
let snapshot = Store::new(path.clone()).read().unwrap();
assert!(snapshot.exists);
assert_eq!(snapshot.revision, 2);
assert_eq!(Value::Object(snapshot.sections), json!({ "general": { "autosaveSeconds": 7 }, "language": "fr" }));
store.write("language", Value::Null).unwrap();
assert!(on_disk(&path).get("language").is_none());
assert_eq!(files(&dir), vec![FILE_NAME.to_owned()], "No temporary files remain");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn writes_reject_unknown_sections_and_values_above_the_limit() {
let (dir, path) = fixture("limits");
let mut store = Store::new(path.clone());
assert!(store.write("plugins", json!({})).is_err());
assert!(store.write("../general", json!({})).is_err());
// A data URL of 3,000,000 characters fits.
let image = format!("data:image/png;base64,{}", "A".repeat(3_000_000));
store.write("appearance", json!({ "newTabBackground": { "image": image } })).unwrap();
let before = fs::read(&path).unwrap();
let error = store.write("customThemes", json!(["x".repeat(MAX_FILE_BYTES)])).unwrap_err();
assert!(error.to_string().contains("8 MiB"), "{error}");
assert_eq!(fs::read(&path).unwrap(), before, "A refused write leaves the file unchanged");
assert_eq!(store.read().unwrap().revision, 1);
assert_eq!(files(&dir), vec![FILE_NAME.to_owned()]);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn writes_keep_unknown_top_level_keys() {
let (dir, path) = fixture("unknown");
fs::write(&path, r#"{ "schema": 1, "revision": 4, "future": { "a": 1 }, "general": {} }"#).unwrap();
let mut store = Store::new(path.clone());
assert_eq!(store.read().unwrap().sections.keys().collect::<Vec<_>>(), vec!["general"]);
assert_eq!(store.write("language", json!("ja")).unwrap().revision, 5);
assert_eq!(on_disk(&path)["future"], json!({ "a": 1 }));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_damaged_file_is_kept_aside_and_reported_once() {
for (name, contents) in [("syntax", "{ broken".as_bytes()), ("array", b"[1, 2]"), ("schema", br#"{ "revision": 1 }"#), ("revision", br#"{ "schema": 1, "revision": "x" }"#)] {
let (dir, path) = fixture(name);
fs::write(&path, contents).unwrap();
let mut store = Store::new(path.clone());
let snapshot = store.read().unwrap();
assert!(snapshot.exists, "{name}: no migration after a damaged file");
assert_eq!(snapshot.revision, 0);
assert!(snapshot.sections.is_empty());
let notice = snapshot.notice.expect("The first read reports the damaged file");
let copies: Vec<_> = files(&dir).into_iter().filter(|file| file.starts_with("settings.corrupt-")).collect();
assert_eq!(copies.len(), 1, "{name}");
assert!(notice.contains(&copies[0]), "{notice}");
assert_eq!(fs::read(dir.join(&copies[0])).unwrap(), contents, "{name}: the copy keeps the damaged bytes");
assert_eq!(on_disk(&path), json!({ "schema": SCHEMA, "revision": 0 }));
assert_eq!(store.read().unwrap().notice, None, "Report the damaged file once");
assert_eq!(Store::new(path.clone()).read().unwrap().notice, None, "The new file is valid");
fs::remove_dir_all(dir).unwrap();
}
}
#[test]
fn a_file_above_the_limit_counts_as_damaged() {
let (dir, path) = fixture("large");
fs::write(&path, vec![b' '; MAX_FILE_BYTES + 1]).unwrap();
assert!(Store::new(path.clone()).read().unwrap().notice.is_some());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn migration_writes_the_first_file_only() {
let (dir, path) = fixture("migrate");
let mut store = Store::new(path.clone());
let sections = json!({ "general": { "autosaveEnabled": false }, "language": "fr", "customThemes": [] });
let Value::Object(sections) = sections else { unreachable!() };
let snapshot = store.migrate(sections.clone()).unwrap();
assert!(snapshot.exists);
assert_eq!(snapshot.revision, 1);
assert_eq!(snapshot.sections, sections);
assert_eq!(on_disk(&path)["language"], json!("fr"));
// A second migration, for example from a second window, keeps the existing file.
store.write("language", json!("ja")).unwrap();
let mut other = Store::new(path.clone());
let again = other.migrate(Map::from_iter([("language".to_owned(), json!("en"))])).unwrap();
assert_eq!(again.sections["language"], json!("ja"));
assert_eq!(on_disk(&path)["language"], json!("ja"));
let Value::Object(unknown) = json!({ "plugins": {} }) else { unreachable!() };
assert!(Store::new(dir.join("other.json")).migrate(unknown).is_err());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn migration_uses_a_file_that_another_writer_created_first() {
let (dir, path) = fixture("race");
let mut store = Store::new(path.clone());
assert!(!store.read().unwrap().exists);
fs::write(&path, r#"{ "schema": 1, "revision": 3, "language": "ja" }"#).unwrap();
let snapshot = store.migrate(Map::from_iter([("language".to_owned(), json!("fr"))])).unwrap();
assert_eq!(snapshot.revision, 3);
assert_eq!(snapshot.sections["language"], json!("ja"));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn writes_create_a_missing_config_folder() {
let (dir, _) = fixture("folder");
let path = dir.join("nested").join(FILE_NAME);
Store::new(path.clone()).write("language", json!("fr")).unwrap();
assert_eq!(on_disk(&path)["language"], json!("fr"));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn the_change_event_carries_the_section_revision_and_value() {
let change = Change { section: "language".into(), revision: 9, value: json!("fr") };
assert_eq!(serde_json::to_value(&change).unwrap(), json!({ "section": "language", "revision": 9, "value": "fr" }));
let snapshot = Snapshot { exists: true, revision: 2, sections: Map::new(), notice: None };
assert_eq!(serde_json::to_value(&snapshot).unwrap(), json!({ "exists": true, "revision": 2, "sections": {} }));
}
}
+265
View File
@@ -0,0 +1,265 @@
//! Tab transfer between windows of one workspace.
//!
//! An offer holds a tab's state, including unsaved text, in memory only. It never goes to disk.
//! 1. The source window offers the tab and puts the offer ID in the drag data or the new window URL.
//! 2. The receiving window takes the offer. A take checks the workspace root and the expiry.
//! 3. The receiving window finishes the offer. If it accepted the tab, the host sends
//! `tab-transfer-accepted` to the source window only, and the source closes its tab.
//! A refused offer becomes available again. The source tab stays open until it receives the event.
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use serde::Serialize;
use tauri::{AppHandle, Emitter, State, Window};
use crate::error::{Error, Result};
/// An offer expires after this time if no window took it.
pub const EXPIRY: Duration = Duration::from_secs(120);
/// A taken offer that the receiver never finished is removed after this time.
const TAKEN_EXPIRY: Duration = Duration::from_secs(240);
/// A text buffer holds the text and its saved copy, and an image tab holds a data URL.
pub const MAX_PAYLOAD_BYTES: usize = 64 * 1024 * 1024;
const MAX_OFFERS: usize = 32;
pub const ACCEPTED_EVENT: &str = "tab-transfer-accepted";
pub const EXPIRED: &str = "This tab transfer expired. Drag the tab again.";
pub const OTHER_WORKSPACE: &str = "Move tabs only between windows of the same workspace.";
struct Offer {
source: String,
root: String,
payload: String,
created: Instant,
taker: Option<String>,
}
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Accepted {
pub id: String,
}
#[derive(Default)]
pub struct TabTransferState(Mutex<HashMap<String, Offer>>);
fn check_id(id: &str) -> Result<()> {
uuid::Uuid::parse_str(id).map(|_| ()).map_err(|_| Error::new("Invalid tab transfer."))
}
fn prune(offers: &mut HashMap<String, Offer>, now: Instant) {
offers.retain(|_, offer| {
let age = now.saturating_duration_since(offer.created);
if offer.taker.is_some() { age < TAKEN_EXPIRY } else { age < EXPIRY }
});
}
impl TabTransferState {
/// Keep a tab offer from `source`. The source window creates the ID, because a drag needs its data at once.
pub fn offer(&self, id: &str, source: &str, root: &str, payload: String, now: Instant) -> Result<()> {
check_id(id)?;
if payload.len() > MAX_PAYLOAD_BYTES {
return Err(Error::new("This tab is too large to move to another window. Save it, then open the file in the other window."));
}
serde_json::from_str::<serde::de::IgnoredAny>(&payload).map_err(|_| Error::new("Invalid tab transfer."))?;
let mut offers = self.0.lock()?;
prune(&mut offers, now);
if offers.contains_key(id) { return Err(Error::new("Invalid tab transfer.")); }
if offers.len() >= MAX_OFFERS {
// Remove the oldest open offer. Its source tab stays open.
if let Some(oldest) = offers.iter().filter(|(_, offer)| offer.taker.is_none())
.min_by_key(|(_, offer)| offer.created).map(|(key, _)| key.clone()) {
offers.remove(&oldest);
} else {
return Err(Error::new("Too many tab transfers are in progress. Try again."));
}
}
offers.insert(id.into(), Offer { source: source.into(), root: root.into(), payload, created: now, taker: None });
Ok(())
}
/// Give the offer to `taker` once. A different workspace leaves the offer for another window.
pub fn take(&self, id: &str, taker: &str, root: &str, now: Instant) -> Result<String> {
check_id(id)?;
let mut offers = self.0.lock()?;
prune(&mut offers, now);
let offer = offers.get_mut(id).filter(|offer| offer.taker.is_none()).ok_or_else(|| Error::new(EXPIRED))?;
if offer.root != root { return Err(Error::new(OTHER_WORKSPACE)); }
offer.taker = Some(taker.into());
Ok(offer.payload.clone())
}
/// End the take of `taker`. Return the source window to acknowledge when the taker accepted the tab.
/// A refused offer stays available for another window until it expires.
pub fn finish(&self, id: &str, taker: &str, accepted: bool) -> Result<Option<String>> {
check_id(id)?;
let mut offers = self.0.lock()?;
let Some(offer) = offers.get_mut(id).filter(|offer| offer.taker.as_deref() == Some(taker)) else {
return Err(Error::new(EXPIRED));
};
if !accepted {
offer.taker = None;
return Ok(None);
}
Ok(offers.remove(id).map(|offer| offer.source))
}
/// Withdraw an open offer of `source`. A taken offer stays until its receiver finishes it.
pub fn cancel(&self, id: &str, source: &str) -> Result<()> {
check_id(id)?;
let mut offers = self.0.lock()?;
if offers.get(id).is_some_and(|offer| offer.source == source && offer.taker.is_none()) {
offers.remove(id);
}
Ok(())
}
/// Remove the offers of a closed window, and release the offers that it took.
pub fn release_window(&self, label: &str) {
let Ok(mut offers) = self.0.lock() else { return };
offers.retain(|_, offer| offer.source != label);
for offer in offers.values_mut() {
if offer.taker.as_deref() == Some(label) { offer.taker = None; }
}
}
}
#[tauri::command]
pub async fn tab_transfer_offer(window: Window, state: State<'_, TabTransferState>, id: String, root: String, payload: String) -> Result<String> {
state.offer(&id, window.label(), &root, payload, Instant::now())?;
Ok(id)
}
#[tauri::command]
pub async fn tab_transfer_take(window: Window, state: State<'_, TabTransferState>, id: String, root: String) -> Result<String> {
state.take(&id, window.label(), &root, Instant::now())
}
#[tauri::command]
pub async fn tab_transfer_finish(app: AppHandle, window: Window, state: State<'_, TabTransferState>, id: String, accepted: bool) -> Result<()> {
if let Some(source) = state.finish(&id, window.label(), accepted)? {
// Only the source window closes its tab.
app.emit_to(source.as_str(), ACCEPTED_EVENT, Accepted { id })?;
}
Ok(())
}
#[tauri::command]
pub async fn tab_transfer_cancel(window: Window, state: State<'_, TabTransferState>, id: String) -> Result<()> {
state.cancel(&id, window.label())
}
#[cfg(test)]
mod tests {
use super::*;
const ID: &str = "00000000-0000-4000-8000-000000000001";
const ROOT: &str = "C:\\workspace";
fn offered(now: Instant) -> TabTransferState {
let state = TabTransferState::default();
state.offer(ID, "main", ROOT, r#"{"buffer":{"contents":"unsaved"}}"#.into(), now).unwrap();
state
}
#[test]
fn an_offer_is_taken_once() {
let now = Instant::now();
let state = offered(now);
assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap(), r#"{"buffer":{"contents":"unsaved"}}"#);
assert_eq!(state.take(ID, "workspace-3", ROOT, now).unwrap_err().to_string(), EXPIRED);
assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main"));
assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED);
assert_eq!(state.finish(ID, "workspace-2", true).unwrap_err().to_string(), EXPIRED);
}
#[test]
fn an_offer_expires_after_two_minutes() {
let now = Instant::now();
let state = offered(now);
assert!(state.take(ID, "workspace-2", ROOT, now + EXPIRY - Duration::from_secs(1)).is_ok());
assert_eq!(state.finish(ID, "workspace-2", false).unwrap(), None);
assert_eq!(state.take(ID, "workspace-2", ROOT, now + EXPIRY).unwrap_err().to_string(), EXPIRED);
// A taken offer survives the expiry until its receiver finishes it.
let state = offered(now);
state.take(ID, "workspace-2", ROOT, now).unwrap();
state.offer("00000000-0000-4000-8000-000000000002", "main", ROOT, "{}".into(), now + EXPIRY).unwrap();
assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main"));
}
#[test]
fn a_different_workspace_cannot_take_the_offer_and_leaves_it_open() {
let now = Instant::now();
let state = offered(now);
assert_eq!(state.take(ID, "workspace-2", "C:\\other", now).unwrap_err().to_string(), OTHER_WORKSPACE);
assert!(state.take(ID, "workspace-3", ROOT, now).is_ok());
}
#[test]
fn only_the_taker_finishes_and_only_acceptance_acknowledges_the_source() {
let now = Instant::now();
let state = offered(now);
state.take(ID, "workspace-2", ROOT, now).unwrap();
assert_eq!(state.finish(ID, "workspace-3", true).unwrap_err().to_string(), EXPIRED);
// A refusal sends nothing, and another window can take the offer.
assert_eq!(state.finish(ID, "workspace-2", false).unwrap(), None);
state.take(ID, "workspace-3", ROOT, now).unwrap();
// The acknowledgement goes to the source window, not to the taker.
assert_eq!(state.finish(ID, "workspace-3", true).unwrap().as_deref(), Some("main"));
}
#[test]
fn offers_check_the_id_the_size_and_json() {
let now = Instant::now();
let state = TabTransferState::default();
assert!(state.offer("not-a-uuid", "main", ROOT, "{}".into(), now).is_err());
assert!(state.offer(ID, "main", ROOT, "{".into(), now).is_err());
let large = format!("\"{}\"", "x".repeat(MAX_PAYLOAD_BYTES));
assert!(state.offer(ID, "main", ROOT, large, now).unwrap_err().to_string().contains("too large"));
state.offer(ID, "main", ROOT, "{}".into(), now).unwrap();
assert!(state.offer(ID, "main", ROOT, "{}".into(), now).is_err(), "An ID is used once");
assert!(state.take("../x", "workspace-2", ROOT, now).is_err());
}
#[test]
fn the_oldest_open_offer_makes_room_for_a_new_one() {
let now = Instant::now();
let state = TabTransferState::default();
let ids: Vec<String> = (0..=MAX_OFFERS).map(|index| format!("00000000-0000-4000-8000-{index:012}")).collect();
for (index, id) in ids.iter().enumerate() {
state.offer(id, "main", ROOT, "{}".into(), now + Duration::from_millis(index as u64)).unwrap();
}
assert_eq!(state.take(&ids[0], "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED);
assert!(state.take(&ids[MAX_OFFERS], "workspace-2", ROOT, now).is_ok());
}
#[test]
fn the_source_cancels_only_its_open_offers() {
let now = Instant::now();
let state = offered(now);
state.cancel(ID, "workspace-2").unwrap();
assert!(state.take(ID, "workspace-2", ROOT, now).is_ok());
state.cancel(ID, "main").unwrap();
assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main"), "A taken offer stays until it finishes");
let state = offered(now);
state.cancel(ID, "main").unwrap();
assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED);
}
#[test]
fn closing_a_window_removes_its_offers_and_releases_its_takes() {
let now = Instant::now();
let state = offered(now);
state.take(ID, "workspace-2", ROOT, now).unwrap();
state.release_window("workspace-2");
assert!(state.take(ID, "workspace-3", ROOT, now).is_ok());
state.release_window("main");
assert_eq!(state.finish(ID, "workspace-3", true).unwrap_err().to_string(), EXPIRED);
}
#[test]
fn the_acknowledgement_names_the_offer() {
assert_eq!(serde_json::to_value(Accepted { id: ID.into() }).unwrap(), serde_json::json!({ "id": ID }));
}
}