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
+82 -3
View File
@@ -59,8 +59,14 @@ export function settle(page) {
*
* `commands(test)` runs in the page and returns a map from command name to handler `(args, test) => result`.
* It cannot use variables from the test file. Pass data through `state`, which must be JSON.
* `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options) }`.
* `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options), settings(section), writeSettings(section, value) }`.
* A command without a handler throws "Unhandled IPC", or returns null when `strict` is false.
*
* Default handlers serve the settings file (`settings_*`) and tab transfers (`tab_transfer_*`). `commands` can replace them.
* All pages of one browser context share their state: the settings file and the offers are in localStorage under
* test keys, and a BroadcastChannel sends `settings-changed` to every page and `tab-transfer-accepted` to the source page.
* Without a settings file, the app migrates the old localStorage keys, so a test can seed preferences there before the first load.
* `test.settings(section)` reads a section of the file. `test.writeSettings(section, value)` acts as a write from another window.
*/
export function mockTauri(target, { label = "main", state = {}, commands, strict = true } = {}) {
const options = JSON.stringify({ label, state, strict });
@@ -142,7 +148,80 @@ function installMock(options, commands) {
return Object.assign(handlers, { files: store, folders: dirs, root, name });
};
const test = { state: options.state, calls: [], emit, label: options.label, workspace };
// The settings file and the tab transfer offers of the desktop host (src-tauri/src/preferences.rs, tab_transfer.rs).
// `crypto.randomUUID` needs a secure context, which `about:blank` is not.
const pageId = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
const channel = typeof BroadcastChannel === "function" ? new BroadcastChannel("runestone-smoke-host") : { postMessage() {} };
channel.addEventListener?.("message", ({ data }) => { if (!data.target || data.target === pageId) emit(data.event, data.payload); });
// `target` is a page ID. Without it, every page of the context receives the event, this page too.
const broadcast = (event, payload, target) => {
if (!target || target === pageId) emit(event, payload);
if (target !== pageId) channel.postMessage({ event, payload, target });
};
const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers";
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language"];
const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } };
const settingsFile = () => readJson(SETTINGS_FILE, null);
const snapshot = () => {
const file = settingsFile();
return { exists: !!file, revision: file?.revision ?? 0, sections: Object.fromEntries(SECTIONS.filter(name => file && name in file).map(name => [name, file[name]])) };
};
const writeSettings = (section, value) => {
if (!SECTIONS.includes(section)) throw `Unknown settings section: ${section}`;
const file = settingsFile() ?? { schema: 1, revision: 0 };
file.revision += 1;
if (value === null || value === undefined) delete file[section]; else file[section] = value;
localStorage.setItem(SETTINGS_FILE, JSON.stringify(file));
const change = { section, revision: file.revision, value: value ?? null };
broadcast("settings-changed", change);
return change;
};
const offers = () => {
const list = readJson(TRANSFERS, {});
for (const [id, offer] of Object.entries(list)) if (Date.now() - offer.created >= (offer.taker ? 240000 : 120000)) delete list[id];
return list;
};
const saveOffers = list => localStorage.setItem(TRANSFERS, JSON.stringify(list));
const expired = "This tab transfer expired. Drag the tab again.";
const defaults = {
settings_read: () => snapshot(),
settings_migrate: ({ sections }) => {
if (!settingsFile()) localStorage.setItem(SETTINGS_FILE, JSON.stringify({ schema: 1, revision: 1, ...sections }));
return snapshot();
},
settings_write: ({ section, value }) => writeSettings(section, value),
tab_transfer_offer: ({ id, root, payload }) => {
const list = offers();
if (list[id]) throw "Invalid tab transfer.";
list[id] = { source: pageId, root, payload, created: Date.now(), taker: null };
saveOffers(list);
return id;
},
tab_transfer_take: ({ id, root }) => {
const list = offers(), offer = list[id];
if (!offer || offer.taker) throw expired;
if (offer.root !== root) throw "Move tabs only between windows of the same workspace.";
offer.taker = pageId;
saveOffers(list);
return offer.payload;
},
tab_transfer_finish: ({ id, accepted }) => {
const list = offers(), offer = list[id];
if (!offer || offer.taker !== pageId) throw expired;
if (accepted) delete list[id]; else offer.taker = null;
saveOffers(list);
if (accepted) broadcast("tab-transfer-accepted", { id }, offer.source);
return null;
},
tab_transfer_cancel: ({ id }) => {
const list = offers();
if (list[id]?.source === pageId && !list[id].taker) { delete list[id]; saveOffers(list); }
return null;
},
};
const test = { state: options.state, calls: [], emit, label: options.label, workspace, settings: section => settingsFile()?.[section], writeSettings };
// Look up the test's handlers first. A test can return a Proxy, so do not copy its keys.
const table = commands ? commands(test) || {} : {};
window.isTauri = true;
window.__TEST__ = test;
@@ -164,7 +243,7 @@ function installMock(options, commands) {
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return null; }
if (command === "plugin:event|emit" || command === "plugin:event|emit_to") { emit(args.event, args.payload); return null; }
const handler = table[command];
const handler = typeof table[command] === "function" ? table[command] : defaults[command];
if (typeof handler === "function") {
const result = await handler(args, test);
return result === undefined ? null : result;