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
@@ -15,11 +15,17 @@ try {
const identity=await page.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/path.js')).appDataDir());
assert.match(identity, /[\\/]com\.runestone\.spelling-test[\\/]?$/);
const pending=context.waitForEvent('page');
// The source window offers the tab through the host and waits for the acknowledgement that the host sends to it alone.
const token=await page.evaluate(async()=>{
const {invoke}=await import('/node_modules/@tauri-apps/api/core.js');
const {listen}=await import('/node_modules/@tauri-apps/api/event.js');
const {getCurrentWindow}=await import('/node_modules/@tauri-apps/api/window.js');
const root=await invoke('workspace_last_path');
const token=crypto.randomUUID(), id=crypto.randomUUID();
localStorage.setItem('runestone.tab-transfer.'+token,JSON.stringify({root,created:Date.now(),reading:false,buffer:{id,relPath:'empty:'+id,name:'New tab',kind:'empty',imageUrl:null,contents:'',saved:'',chrome:'Writing',chromeOverride:null}}));
window.__nativeTransferAccepted=false;
await listen('tab-transfer-accepted',event=>{ if(event.payload.id===token) window.__nativeTransferAccepted=true; },{target:getCurrentWindow().label});
const payload=JSON.stringify({reading:false,buffer:{id,relPath:'empty:'+id,name:'New tab',kind:'empty',imageUrl:null,contents:'',saved:'',chrome:'Writing',chromeOverride:null}});
await invoke('tab_transfer_offer',{id:token,root,payload});
await invoke('workspace_open_window',{path:root,transfer:token});
return token;
});
@@ -28,7 +34,7 @@ try {
assert.ok(transferred.url().includes('?tabTransfer='+token));
assert.ok(!transferred.url().includes('index.html'));
assert.equal(await transferred.getByText('404',{exact:true}).count(),0);
await page.waitForFunction(token=>localStorage.getItem('runestone.tab-transfer.'+token+'.accepted') === 'true',token);
await page.waitForFunction(()=>window.__nativeTransferAccepted===true);
console.log('PASS: native empty-tab transfer loads the splash screen and acknowledges its saved tab state.');
await transferred.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().close()); transferred=undefined;
settings=context.pages().find(page => page.url().includes('settingsWindow=true'));
+2 -1
View File
@@ -88,7 +88,8 @@ try {
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
const largeImage = Buffer.concat([pixel, Buffer.alloc(1_900_000 - pixel.length)]);
await page.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'native-large.png', mimeType: 'image/png', buffer: largeImage });
await page.waitForFunction(() => !!JSON.parse(localStorage.getItem('runestone.appearance'))?.newTabBackground?.imageId);
// The appearance is in the settings file of the host.
await page.waitForFunction(() => window.__TAURI_INTERNALS__.invoke('settings_read').then(file => !!file.sections.appearance?.newTabBackground?.imageId));
await page.goto(`${origin}/`);
// The image is on the work area layer behind the empty tab (src/lib/layout/Workbench.svelte:1258, :1543-1549).
await page.locator('.empty').waitFor();
+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 });
+8 -3
View File
@@ -3,6 +3,7 @@ import { test } from 'node:test';
import { catalogs, messageRows } from '../../src/lib/i18n/messages.ts';
import { get } from 'svelte/store';
import { LANGUAGE_KEY, locale, normalizeLocale, setLocale, t, translate, syncLocale } from '../../src/lib/i18n/index.ts';
import { initSettings } from '../../src/lib/settings/store.ts';
test('Every catalog entry has all translations and preserves its placeholders', () => {
const seen = new Set<string>();
for (const [english, ...translations] of messageRows) {
@@ -22,7 +23,7 @@ test('Locale parsing rejects unsupported values and interpolation preserves user
assert.equal(translate('fr', 'Missing source text'), 'Missing source text');
assert.equal(translate('ja', 'Close {name}', { name: '<script>例.md</script>' }), '<script>例.md</script>を閉じる');
});
test('Language saves before reactive changes and syncs across windows', () => {
test('Language saves before reactive changes and syncs across windows', async () => {
const stored = new Map<string, string>();
const events = new Map<string, Function>();
const priorStorage = globalThis.localStorage, priorWindow = globalThis.window, priorDocument = globalThis.document;
@@ -30,8 +31,10 @@ test('Language saves before reactive changes and syncs across windows', () => {
globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as unknown as Storage;
globalThis.window = { addEventListener: (key: string, handler: Function) => events.set(key, handler), removeEventListener: (key: string) => events.delete(key) } as unknown as Window & typeof globalThis;
globalThis.document = { documentElement: { lang: '' } } as unknown as Document;
// Without the desktop host, the settings store keeps the language in localStorage and listens for storage events.
await initSettings(() => ({}));
const stop = syncLocale();
setLocale('fr');
await setLocale('fr');
assert.equal(stored.get(LANGUAGE_KEY), 'fr');
assert.equal(get(t)('Settings'), 'Paramètres');
assert.equal(document.documentElement.lang, 'fr');
@@ -40,7 +43,9 @@ test('Language saves before reactive changes and syncs across windows', () => {
globalThis.localStorage.setItem = () => { throw new Error('Storage unavailable'); };
assert.throws(() => setLocale('ja'));
assert.equal(get(locale), 'zh-CN');
stop(); assert.equal(events.size, 0);
stop();
stored.set(LANGUAGE_KEY, 'ja'); events.get('storage')!({ key: LANGUAGE_KEY });
assert.equal(get(locale), 'zh-CN', 'A stopped sync ignores later changes');
} finally { globalThis.localStorage = priorStorage; globalThis.window = priorWindow; globalThis.document = priorDocument; locale.set('en'); }
});
+28 -11
View File
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings } from "../../../src/lib/workspace/settings.ts";
import { DEFAULT_SETTINGS, SETTINGS_KEY, normalizeSettings, parseSettings, readSettings, saveSettings } from "../../../src/lib/workspace/settings.ts";
test("missing or damaged preferences keep safe defaults", () => {
for (const raw of [null, "{broken", "null", "[]", "42", '"text"']) {
@@ -12,21 +12,38 @@ test("missing or damaged preferences keep safe defaults", () => {
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false });
});
function withStorage(storage: Pick<Storage, "getItem" | "setItem">, body: () => void) {
const prior = globalThis.localStorage;
try { globalThis.localStorage = storage as Storage; body(); }
finally { globalThis.localStorage = prior; }
}
test("preferences persist and load at both interval limits", () => {
const store = new Map<string, string>();
for (const autosaveSeconds of [1, 23, 300]) {
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false };
saveSettings({ setItem: (key, value) => { store.set(key, value); } }, settings);
assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings);
}
withStorage({ getItem: (key: string) => store.get(key) ?? null, setItem: (key: string, value: string) => { store.set(key, value); } }, () => {
for (const autosaveSeconds of [1, 23, 300]) {
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false };
void saveSettings(settings);
assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings);
assert.deepEqual(readSettings(), settings);
}
});
});
test("invalid changes never reach storage and storage failures reach the caller", () => {
let writes = 0;
const storage = { setItem: () => { writes++; } };
for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) {
assert.throws(() => saveSettings(storage, { autosaveEnabled: true, autosaveSeconds, showInternalFolder: false }));
}
withStorage({ getItem: () => null, setItem: () => { writes++; } }, () => {
for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) {
assert.throws(() => saveSettings({ autosaveEnabled: true, autosaveSeconds, showInternalFolder: false }));
}
});
assert.equal(writes, 0);
assert.throws(() => saveSettings({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_SETTINGS }), /Storage unavailable/);
withStorage({ getItem: () => null, setItem: () => { throw new Error("Storage unavailable"); } }, () => {
assert.throws(() => saveSettings({ ...DEFAULT_SETTINGS }), /Storage unavailable/);
});
});
test("stored values of any type normalize to safe settings", () => {
for (const value of [undefined, null, 42, "text", [], { autosaveSeconds: 0 }]) assert.deepEqual(normalizeSettings(value), DEFAULT_SETTINGS);
assert.deepEqual(normalizeSettings({ autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true }), { autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true });
});
+69
View File
@@ -0,0 +1,69 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { migrateLegacyPreferences } from '../../../src/lib/settings/migration.ts';
import { LEGACY_KEYS } from '../../../src/lib/settings/store.ts';
const palette = { bg: '#123', text: '#abcdef', accent: '#AABBCC' };
const reader = (values: Record<string, string>) => (key: string) => Object.hasOwn(values, key) ? values[key] : null;
test('Migration reads the four old keys and the theme backup, and normalizes each value', () => {
const custom = { schema: 2, id: 'night', name: 'Night', colors: { ...palette, bg: '#000000' } };
const sections = migrateLegacyPreferences(reader({
'runestone.settings': JSON.stringify({ autosaveEnabled: false, autosaveSeconds: 900, extra: true }),
'runestone.appearance': JSON.stringify({ theme: 'custom:night', mode: 'light', transparency: { amount: 140 } }),
'runestone.custom-themes': JSON.stringify([custom, { schema: 2, id: '../bad' }]),
'runestone.custom-themes.legacy': JSON.stringify([{ schema: 1, id: 'kept' }]),
'runestone.language': 'fr',
}));
assert.deepEqual(sections, {
general: { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false },
language: 'fr',
customThemes: [custom],
customThemesLegacy: [{ schema: 1, id: 'kept' }],
// The mode comes from the migrated custom theme, not from a store that is still empty.
appearance: { theme: 'custom:night', mode: 'dark', transparency: { enabled: true, amount: 100 } },
});
});
test('Migration of version 1 themes keeps the saved palette and adds the originals to the backup once', () => {
const legacy = { schema: 1, id: 'old', name: 'Old', light: { ...palette, bg: '#fff' }, dark: palette };
const sections = migrateLegacyPreferences(reader({
'runestone.appearance': JSON.stringify({ theme: 'custom:old', mode: 'light' }),
'runestone.custom-themes': JSON.stringify([legacy]),
'runestone.custom-themes.legacy': JSON.stringify([legacy]),
}));
assert.deepEqual(sections.customThemes, [{ schema: 2, id: 'old', name: 'Old', colors: legacy.light }]);
assert.deepEqual(sections.customThemesLegacy, [legacy]);
assert.deepEqual(sections.appearance, { theme: 'custom:old', mode: 'light' });
});
test('Missing keys give no sections, so the defaults apply', () => {
assert.deepEqual(migrateLegacyPreferences(() => null), {});
assert.deepEqual(migrateLegacyPreferences(() => { throw new Error('Storage unavailable'); }), {});
});
test('Damaged old values become defaults and unknown languages become English', () => {
const sections = migrateLegacyPreferences(reader({
'runestone.settings': '{broken',
'runestone.appearance': '[1, 2]',
'runestone.custom-themes': '{"not":"a list"}',
'runestone.language': 'de',
}));
assert.deepEqual(sections, {
general: { autosaveEnabled: true, autosaveSeconds: 5, showInternalFolder: false },
language: 'en',
appearance: { theme: 'default', mode: 'dark' },
});
});
test('Migration keeps renamed theme IDs and a background image data URL', () => {
const image = 'data:image/png;base64,' + 'A'.repeat(40);
const sections = migrateLegacyPreferences(reader({
'runestone.appearance': JSON.stringify({ theme: 'holo', mode: 'dark', newTabBackground: { image, overlay: 0.4 } }),
}));
assert.deepEqual(sections.appearance, { theme: 'harvest-moon', mode: 'dark', newTabBackground: { image, overlay: 0.4, position: 'center', size: 'cover' } });
});
test('Every section has one old key', () => {
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.language', 'runestone.settings']);
});
+118
View File
@@ -0,0 +1,118 @@
// The settings store with a mock desktop host. Each test file runs in its own process,
// so the mock is installed before the first import of the store.
import { test } from 'node:test';
import assert from 'node:assert/strict';
type Handler = (args: Record<string, unknown>) => unknown;
const calls: { command: string; args: Record<string, unknown> }[] = [];
const callbacks = new Map<number, (event: unknown) => void>();
const listeners = new Map<string, number[]>();
const handlers = new Map<string, Handler>();
let sequence = 0;
const host = globalThis as unknown as Record<string, unknown>;
host.isTauri = true;
host.window = globalThis;
host.__TAURI_INTERNALS__ = {
transformCallback: (callback: (event: unknown) => void) => { callbacks.set(++sequence, callback); return sequence; },
invoke: async (command: string, args: Record<string, unknown> = {}) => {
calls.push({ command, args });
if (command === 'plugin:event|listen') {
listeners.set(args.event as string, [...listeners.get(args.event as string) ?? [], args.handler as number]);
return args.handler;
}
const handler = handlers.get(command);
if (!handler) throw new Error(`Unhandled IPC: ${command}`);
return handler(args);
},
};
function emit(event: string, payload: unknown) {
for (const id of listeners.get(event) ?? []) callbacks.get(id)?.({ event, id, payload });
}
const legacy = new Map<string, string>();
host.localStorage = { getItem: (key: string) => legacy.get(key) ?? null, setItem: (key: string, value: string) => legacy.set(key, value) };
const store = await import('../../../src/lib/settings/store.ts');
const { migrateLegacyPreferences } = await import('../../../src/lib/settings/migration.ts');
let file: Record<string, unknown> | null = null;
let revision = 0;
// While `gate` is set, the host holds each write until the gate opens.
let gate: Promise<void> | undefined;
function closeGate() {
let open!: () => void;
gate = new Promise<void>(resolve => { open = resolve; });
return () => { gate = undefined; open(); };
}
handlers.set('settings_read', () => ({ exists: file !== null, revision, sections: { ...file } }));
handlers.set('settings_migrate', args => {
if (file === null) { file = { ...(args.sections as Record<string, unknown>) }; revision = 1; }
return { exists: true, revision, sections: { ...file }, notice: 'Notice once' };
});
handlers.set('settings_write', async args => {
if (gate) await gate;
const section = args.section as string;
file![section] = args.value;
revision += 1;
return { section, revision, value: args.value };
});
test('The first start migrates the old localStorage values, and later reads come from memory', async () => {
legacy.set('runestone.language', 'ja');
legacy.set('runestone.settings', JSON.stringify({ autosaveSeconds: 12 }));
await store.initSettings(migrateLegacyPreferences);
await store.initSettings(() => { throw new Error('Migrates once'); });
assert.deepEqual(calls.filter(call => !call.command.startsWith('plugin:')).map(call => call.command), ['settings_read', 'settings_migrate']);
assert.equal(calls[0].command, 'plugin:event|listen', 'The listener starts before the read');
assert.equal(store.readSection('language'), 'ja');
assert.deepEqual(store.readSection('general'), { autosaveEnabled: true, autosaveSeconds: 12, showInternalFolder: false });
assert.equal(legacy.get('runestone.language'), 'ja', 'The old value stays in place');
assert.equal(store.takeSettingsNotice(), 'Notice once');
assert.equal(store.takeSettingsNotice(), null);
});
test('A write shows at once, merges quick writes, and runs subscribers', async () => {
let changes = 0;
const stop = store.onSettingsChange('language', () => { changes++; });
const open = closeGate();
const first = store.writeSection('language', 'fr');
const second = store.writeSection('language', 'zh-CN');
const third = store.writeSection('language', 'en');
assert.equal(store.readSection('language'), 'en');
assert.equal(changes, 3);
open();
await Promise.all([first, second, third]);
const writes = calls.filter(call => call.command === 'settings_write').map(call => call.args.value);
assert.deepEqual(writes, ['fr', 'en'], 'The writes during the first one merge into the last value');
assert.equal(file!.language, 'en');
stop();
});
test('Changes from other windows apply in revision order, and old changes do not', () => {
let changes = 0;
const stop = store.onSettingsChange('appearance', () => { changes++; });
emit('settings-changed', { section: 'appearance', revision: 50, value: { theme: 'claude', mode: 'light' } });
assert.deepEqual(store.readSection('appearance'), { theme: 'claude', mode: 'light' });
emit('settings-changed', { section: 'appearance', revision: 40, value: { theme: 'sakura', mode: 'light' } });
assert.deepEqual(store.readSection('appearance'), { theme: 'claude', mode: 'light' });
emit('settings-changed', { section: 'unknown', revision: 60, value: 1 });
assert.equal(changes, 1);
stop();
emit('settings-changed', { section: 'appearance', revision: 70, value: null });
assert.equal(store.readSection('appearance'), undefined, 'null removes the section');
assert.equal(changes, 1, 'A stopped subscriber does not run');
});
test('A change from another window during a local write applies after the write when it is newer', async () => {
const open = closeGate();
const pending = store.writeSection('general', { autosaveSeconds: 30 });
emit('settings-changed', { section: 'general', revision: 1000, value: { autosaveSeconds: 60 } });
assert.deepEqual(store.readSection('general'), { autosaveSeconds: 30 }, 'No old value appears during the write');
open();
await pending;
assert.deepEqual(store.readSection('general'), { autosaveSeconds: 60 }, 'The host saved the other window last');
});
test('A failed write reaches the caller', async () => {
handlers.set('settings_write', () => { throw 'Disk full'; });
await assert.rejects(store.writeSection('customThemes', []), /Disk full/);
});
+14 -10
View File
@@ -81,8 +81,16 @@ test('Opaque mode retains background ownership and the amount for re-enabling',
test('Saved legacy light themes migrate once and preserve both original palettes', async () => {
const { customThemes, CUSTOM_THEMES_KEY } = await import('../../../src/lib/theme/customThemes.ts');
const { migrateLegacyPreferences } = await import('../../../src/lib/settings/migration.ts');
const { LEGACY_KEYS } = await import('../../../src/lib/settings/store.ts');
const legacy = { schema: 1, id: 'saved-light', name: 'Saved light', light: { ...palette, bg: '#fff' }, dark: { ...palette, bg: '#111' } };
const stored = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]);
const old = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]);
const sections = migrateLegacyPreferences(key => old.get(key) ?? null);
assert.equal((sections.customThemes as { schema: number }[])[0].schema, 2);
assert.deepEqual(sections.customThemesLegacy, [legacy]);
assert.deepEqual(sections.appearance, { theme: 'custom:saved-light', mode: 'light' });
// The browser preview store reads the sections from their old keys.
const stored = new Map(Object.entries(sections).map(([section, value]) => [LEGACY_KEYS[section as keyof typeof LEGACY_KEYS], JSON.stringify(value)]));
const previous = globalThis.localStorage;
try {
globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as unknown as Storage;
@@ -90,22 +98,18 @@ test('Saved legacy light themes migrate once and preserve both original palettes
assert.deepEqual(themeModes('custom:saved-light'), ['light']);
assert.equal(normalizeAppearance({ theme: 'custom:saved-light', mode: 'dark' }).mode, 'light');
assert.deepEqual(exportAppearanceTheme('custom:saved-light').colors.bg, '#fff');
assert.equal(JSON.parse(stored.get(CUSTOM_THEMES_KEY)!)[0].schema, 2);
assert.deepEqual(JSON.parse(stored.get(`${CUSTOM_THEMES_KEY}.legacy`)!)[0], legacy);
assert.deepEqual(customThemes('dark')[0].colors, legacy.light);
assert.deepEqual(customThemes('dark')[0].colors, legacy.light, 'The converted theme keeps its palette in both modes');
} finally { globalThis.localStorage = previous; }
});
test('Legacy migration storage failure leaves the original palette available', async () => {
test('Reading custom themes never writes, and an unconverted version 1 theme uses the requested palette', async () => {
const { customThemes, CUSTOM_THEMES_KEY } = await import('../../../src/lib/theme/customThemes.ts');
const legacy = { schema: 1, id: 'quota-light', name: 'Quota light', light: { ...palette, bg: '#fefefe' }, dark: palette };
const raw = JSON.stringify([legacy]);
const previous = globalThis.localStorage;
let original = raw;
try {
globalThis.localStorage = { getItem: (key: string) => key === CUSTOM_THEMES_KEY ? original : null, setItem: () => { throw new Error('Quota exceeded'); } } as unknown as Storage;
globalThis.localStorage = { getItem: (key: string) => key === CUSTOM_THEMES_KEY ? JSON.stringify([legacy]) : null, setItem: () => { throw new Error('Quota exceeded'); } } as unknown as Storage;
assert.deepEqual(customThemes('light')[0].colors, legacy.light);
assert.equal(original, raw);
assert.deepEqual(customThemes('dark')[0].colors, legacy.light);
assert.deepEqual(customThemes('dark')[0].colors, palette);
assert.deepEqual(customThemes()[0].colors, palette, 'Without a saved appearance, the dark palette applies');
} finally { globalThis.localStorage = previous; }
});
+26
View File
@@ -0,0 +1,26 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { TAB_TRANSFER_ID, parseTabTransfer } from '../../../src/lib/workspace/tabTransfer.ts';
const buffer = { id: 'one', relPath: 'a.md', name: 'a.md', kind: 'text', contents: 'Unsaved', saved: 'Saved' };
test('A buffer transfer needs a path, its text, and its saved text', () => {
assert.deepEqual(parseTabTransfer(JSON.stringify({ buffer, reading: true })), { buffer, reading: true });
assert.equal(parseTabTransfer(JSON.stringify({ buffer })).reading, false);
for (const field of ['relPath', 'contents', 'saved'] as const) {
assert.throws(() => parseTabTransfer(JSON.stringify({ buffer: { ...buffer, [field]: 1 } })), /Invalid tab transfer/);
}
});
test('A plugin transfer needs a state object, and other payloads are invalid', () => {
const plugin = { owner: 'test.plugin', id: 'board' };
assert.deepEqual(parseTabTransfer(JSON.stringify({ plugin, reading: false })), { plugin, reading: false });
for (const payload of ['{', 'null', '[]', '{}', '{"plugin":"text"}', '{"buffer":null}']) {
assert.throws(() => parseTabTransfer(payload), /Invalid tab transfer/, payload);
}
});
test('Transfer IDs are UUIDs', () => {
assert.ok(TAB_TRANSFER_ID.test(crypto.randomUUID()));
for (const id of ['', '../x', 'runestone.tab-transfer.1']) assert.ok(!TAB_TRANSFER_ID.test(id), id);
});