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:
@@ -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']);
|
||||
});
|
||||
@@ -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/);
|
||||
});
|
||||
Reference in New Issue
Block a user