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;
@@ -31,7 +31,7 @@ await runSmoke('appearance/backgroundImages', async ({ browser }) => {
const imageInput = () => settings.getByLabel('Background image file', { exact: true });
const background = () => main.locator('.workarea-background').evaluate(node => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(node).backgroundImage)?.[1]);
const decoded = (page, url) => page.evaluate(async url => { const image = new Image(); image.src = url; await image.decode(); return image.naturalWidth; }, url);
const savedImageId = () => settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId);
const savedImageId = () => settings.evaluate(() => window.__TEST__.settings('appearance').newTabBackground.imageId);
const picker = name => settings.locator('.picker').and(settings.getByRole('button', { name, exact: true }));
await main.goto(smokeUrl); await main.locator('.empty').waitFor();
@@ -59,7 +59,7 @@ await runSmoke('appearance/backgroundImages', async ({ browser }) => {
await imageInput().setInputFiles(largeFile);
await main.waitForFunction(old => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(document.querySelector('.workarea-background')).backgroundImage)?.[1] !== old, url);
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image decodes');
assert.ok(await settings.evaluate(() => localStorage.getItem('runestone.appearance').length < 500), 'Image bytes stay outside localStorage');
assert.ok(await settings.evaluate(() => JSON.stringify(window.__TEST__.settings('appearance')).length < 500), 'Image bytes stay outside the settings file');
await main.reload(); await main.locator('.empty').waitFor();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image survives reload');
@@ -52,7 +52,7 @@ await runSmoke('appearance/backgroundLayout', async ({ browser }) => {
for (const mode of ['light', 'dark']) {
await settings.evaluate(async mode => {
const appearance = await import('/src/lib/theme/appearance.ts');
appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode });
appearance.saveAppearance({ ...appearance.readAppearance(), mode });
window.dispatchEvent(new Event('focus'));
}, mode);
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
@@ -21,7 +21,7 @@ await runSmoke('appearance/backgroundOverlay', async ({ page: settings }) => {
});
const input = settings.getByRole('spinbutton', { name: 'Image overlay percentage' });
const slider = settings.getByRole('slider', { name: 'Image overlay', exact: true });
const saved = () => settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.overlay);
const saved = () => settings.evaluate(() => window.__TEST__.settings('appearance').newTabBackground.overlay);
await input.fill('-37');
assert.equal(await slider.inputValue(), '-37');
assert.equal(await saved(), -0.37);
@@ -42,7 +42,7 @@ await runSmoke('appearance/backgroundOverlay', async ({ page: settings }) => {
for (const mode of ['light', 'dark']) {
await settings.evaluate(async mode => {
const appearance = await import('/src/lib/theme/appearance.ts');
appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode });
appearance.saveAppearance({ ...appearance.readAppearance(), mode });
window.dispatchEvent(new Event('focus'));
}, mode);
for (const width of [1100, 360]) {
@@ -196,15 +196,15 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
console.log(`PASS: ${theme} ${mode}, colors, fonts, IDE syntax, export, saved state, window sync, narrow menu, keyboard and focus`);
}
for (const [previous, theme, label] of [['holo', 'harvest-moon', 'Harvest Moon'], ['asuka', 'crimson-pilot', 'Crimson Pilot'], ['malfoid', 'silver-serpent', 'Silver Serpent']]) {
await settings.evaluate(theme => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode: 'dark' })), previous);
await settings.evaluate(theme => window.__TEST__.writeSettings('appearance', { theme, mode: 'dark' }), previous);
await openSettings();
assert.equal((await picker('Color theme').textContent()).trim(), label);
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), theme);
await choose('Color theme', label);
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).theme), theme);
assert.equal(await settings.evaluate(() => window.__TEST__.settings('appearance').theme), theme);
}
for (const [removed, mode] of [['renamon', 'light'], ['asuka-school', 'dark']]) {
await settings.evaluate(({ theme, mode }) => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode })), { theme: removed, mode });
await settings.evaluate(({ theme, mode }) => window.__TEST__.writeSettings('appearance', { theme, mode }), { theme: removed, mode });
await settings.setViewportSize({ width: 1100, height: 780 });
await openSettings();
await waitForAppearance('default', mode);
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/colorThemeMenu", async ({ browser }) => {
// The settings window changes the main window through shared localStorage, so both pages need one context.
// The settings window changes the main window through the mock settings file, so both pages need one context.
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
await mockTauri(context, {
commands: test => ({
@@ -6,7 +6,7 @@ import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/
const name = "appearance/newTabBackground";
await runSmoke(name, async ({ browser }) => {
const output = await outputDir(name);
// The settings window changes the main window through shared localStorage and IndexedDB, so both pages need one context.
// The settings window changes the main window through the mock settings file and shared IndexedDB, so both pages need one context.
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
await mockTauri(context, {
commands: test => ({
@@ -35,15 +35,15 @@ await runSmoke(name, async ({ browser }) => {
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage === "none", layer);
for (const mode of ["light", "dark"]) {
await settings.evaluate(async mode => {
const { saveAppearance, parseAppearance, APPEARANCE_KEY } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ ...parseAppearance(localStorage.getItem(APPEARANCE_KEY)), theme: "default", mode });
const { saveAppearance, readAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ ...readAppearance(), theme: "default", mode });
window.dispatchEvent(new Event("focus"));
}, mode);
await settings.setViewportSize({ width: 650, height: 760 });
await settings.screenshot({ path: path.join(output, `appearance-${mode}-narrow.png`) });
}
assert.equal(await settings.getByRole("button", { name: "Reset background", exact: true }).isDisabled(), true);
await page.waitForFunction(() => !JSON.parse(localStorage.getItem("runestone.appearance")).newTabBackground);
await page.waitForFunction(() => !window.__TEST__.settings("appearance").newTabBackground);
assert.deepEqual([...page.errors, ...settings.errors], []);
console.log("PASS: background image applies, survives a reload, and is removed; Reset background is disabled");
});
+3 -3
View File
@@ -99,7 +99,7 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
assert.notDeepEqual(await editorIds(), before, "A new file creates a new Monaco editor");
await expectAppearance(theme, mode);
await waitForSyntax();
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.appearance"))), { theme, mode });
assert.deepEqual(await settings.evaluate(() => window.__TEST__.settings("appearance")), { theme, mode });
await settings.screenshot({ path: path.join(output, `appearance-${theme}-${mode}.png`) });
await main.screenshot({ path: path.join(output, `appearance-editor-${theme}-${mode}.png`) });
if (theme === "sakura") {
@@ -140,11 +140,11 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
["terminal", "dark", "default", "dark"],
["sakura", "dark", "sakura", "light"],
]) {
await settings.evaluate(value => localStorage.setItem("runestone.appearance", JSON.stringify(value)), { theme, mode: savedMode });
await settings.evaluate(value => window.__TEST__.writeSettings("appearance", value), { theme, mode: savedMode });
await settings.reload();
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
await expectAppearance(expectedTheme, mode);
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.appearance"))), { theme: expectedTheme, mode });
assert.deepEqual(await settings.evaluate(() => window.__TEST__.settings("appearance")), { theme: expectedTheme, mode });
console.log(`PASS: saved ${theme} ${savedMode} migrates to ${expectedTheme} ${mode}`);
}
for (const [theme, mode] of [["default", "dark"], ["claude", "light"], ["claude", "dark"], ["sakura", "light"]]) {
@@ -27,7 +27,7 @@ await runSmoke('appearance/themeVariants', async ({ browser }) => {
}, { theme, mode });
const slider = page.locator('#surface-transparency');
await slider.fill('100');
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).transparency.amount), 100);
assert.equal(await page.evaluate(() => window.__TEST__.settings('appearance').transparency.amount), 100);
await slider.focus(); await page.keyboard.press('Home'); assert.equal(await slider.inputValue(), '0');
await page.keyboard.press('End'); assert.equal(await slider.inputValue(), '100');
await page.screenshot({ path: path.join(output, `${theme}-${mode}-slider-focus.png`) });
+1 -1
View File
@@ -160,7 +160,7 @@ await runSmoke("links/linkMenus", async ({ page }) => {
}
await writerMenu('Workspace note'); await item('Open in new window').click();
await page.waitForFunction(() => window.__TEST__.windows.length === 1);
await page.evaluate(() => { const {transfer}=window.__TEST__.windows[0]; dispatchEvent(new StorageEvent('storage',{key:`runestone.tab-transfer.${transfer}.accepted`,newValue:'true'})); });
await page.evaluate(() => { const {transfer}=window.__TEST__.windows[0]; window.__TEST__.emit('tab-transfer-accepted',{id:transfer}); });
assert.equal(await page.getByRole('tab',{name:/b.md/}).count(),1,'Opening a linked document in a new window keeps the source tab');
await page.locator('[data-tree-rel="a.md"]').click();
await writerMenu('Workspace note'); await item('Bookmark').click();
@@ -35,7 +35,7 @@ await runSmoke('settings/displayLanguage', async ({ browser }) => {
await main.getByRole('button', { name: files, exact: true }).waitFor();
assert.equal(await settings.locator('html').getAttribute('lang'), language);
assert.equal(await main.locator('html').getAttribute('lang'), language);
assert.equal(await settings.evaluate(() => localStorage.getItem('runestone.language')), language);
assert.equal(await settings.evaluate(() => window.__TEST__.settings('language')), language);
await settings.reload();
await settings.getByRole('heading', { name: heading, exact: true }).waitFor();
// Arrow keys and Escape retain shared menu focus behavior.
+2 -2
View File
@@ -63,7 +63,7 @@ await runSmoke("settings/general", async ({ browser }) => {
assert.equal(await interval.inputValue(), "2", "Interval survives reload");
await changeSeconds(0);
await settings.getByRole("alert").filter({ hasText: "whole number" }).waitFor();
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 2);
assert.equal(await page.evaluate(() => window.__TEST__.settings("general").autosaveSeconds), 2);
await changeSeconds(2);
await settings.getByRole("textbox", { name: "Search settings" }).fill("plugins");
await settings.getByText("No plugins installed.", { exact: true }).waitFor();
@@ -113,7 +113,7 @@ await runSmoke("settings/general", async ({ browser }) => {
assert.equal(await other.getByRole("spinbutton", { name: "Auto-save interval" }).inputValue(), "3");
assert.equal(await other.getByRole("switch", { name: "Auto-save", exact: true }).isChecked(), false);
await other.getByRole("button", { name: "Restore defaults" }).click();
await page.waitForFunction(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveEnabled);
await page.waitForFunction(() => window.__TEST__.settings("general").autosaveEnabled);
await showSettings();
await enabled.waitFor();
assert(await enabled.isChecked(), "Other windows receive changes");
+1 -1
View File
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tabs/windowTransfer", async ({ browser }) => {
// The transfer passes through localStorage, so the source and target windows need one context.
// The mock host shares its transfer offers in one context, so the source and target windows need one context.
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await mockTauri(context, {
commands: test => ({
+1 -1
View File
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/folderActions", async ({ browser }) => {
// The settings window shares localStorage with the main window, so both pages need one context.
// The settings window shares the mock settings file with the main window, so both pages need one context.
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await mockTauri(context, {
commands: test => {
+1 -1
View File
@@ -148,7 +148,7 @@ await runSmoke('tree/renameUndo', async ({ browser }) => {
const saved = await page.evaluate(token => {
const layout = JSON.stringify({ leftOpen: true, rightOpen: true, leftWidth: 280, rightWidth: 260, leftView: 'files' });
localStorage.setItem('runestone.workbenchLayout', layout);
localStorage.setItem(`runestone.tab-transfer.${token}`, JSON.stringify({ root: 'C:\\host-todo-test', created: Date.now(), buffer: { id: 'moved', relPath: 'a.md', name: 'a.md', kind: 'text', contents: '# Transferred', saved: '# Note', chrome: 'Writing', pinned: true } }));
void window.__TAURI_INTERNALS__.invoke('tab_transfer_offer', { id: token, root: 'C:\\host-todo-test', payload: JSON.stringify({ buffer: { id: 'moved', relPath: 'a.md', name: 'a.md', kind: 'text', contents: '# Transferred', saved: '# Note', chrome: 'Writing', pinned: true } }) });
return layout;
}, token);
const detached = await openPage(context, { timeout: 30000 });