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 -7
View File
@@ -7,7 +7,8 @@
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { saveBackgroundImage, removeBackgroundImage } from './backgroundImages';
import { APPEARANCE_KEY, DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, BACKGROUND_POSITIONS, BACKGROUND_SIZES, parseAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
import { onSettingsChange } from '$lib/settings/store';
import { DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
let appearance = $state<Appearance>({ ...DEFAULT_APPEARANCE });
let error = $state('');
let status = $state('');
@@ -43,12 +44,16 @@
run: () => change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, [field]: value } }) })) }).close;
}
onMount(() => {
const read = () => { try { installed = customThemes(); appearance = parseAppearance(localStorage.getItem(APPEARANCE_KEY)); } catch { error = $t('Could not read appearance settings.'); } };
read(); window.addEventListener('storage', read); window.addEventListener('focus', read);
return () => { window.removeEventListener('storage', read); window.removeEventListener('focus', read); };
const read = () => { try { installed = customThemes(); appearance = readAppearance(); } catch { error = $t('Could not read appearance settings.'); } };
read();
const stops = [onSettingsChange('appearance', read), onSettingsChange('customThemes', read)];
return () => stops.forEach(stop => stop());
});
function change(next: Appearance) {
try { saveAppearance(next); appearance = normalizeAppearance(next); error = ''; return true; }
try {
saveAppearance(next).catch(() => { error = $t('Could not save appearance settings.'); });
appearance = normalizeAppearance(next); error = ''; return true;
}
catch { error = $t('Could not save appearance settings.'); return false; }
}
function changeOverlay(input: HTMLInputElement) {
@@ -68,7 +73,7 @@
try {
if (file.size > 65536) throw new Error($t('Choose a theme smaller than 64 KiB.'));
const theme = parseCustomTheme(JSON.parse(await file.text()), appearance.mode);
installTheme(theme); installed = customThemes();
installTheme(theme).catch(reason => { error = String(reason); }); installed = customThemes();
change({ ...appearance, theme: `custom:${theme.id}` });
} catch (reason) { error = String(reason); }
finally { themeInput.value = ''; }
@@ -121,7 +126,7 @@
<button onclick={() => themeInput.click()}>{$t("Install theme")}</button>
<button disabled={exporting} onclick={() => void exportTemplate()}>{exporting ? $t('Exporting…') : $t('Export theme template')}</button>
{#if appearance.theme.startsWith('custom:')}<IconButton icon="trash" label={$t("Remove custom theme")} onclick={() => {
try { removeTheme(appearance.theme.slice(7)); installed = customThemes(); change({ ...appearance, theme: 'default' }); }
try { removeTheme(appearance.theme.slice(7)).catch(() => { error = 'Could not remove this theme.'; }); installed = customThemes(); change({ ...appearance, theme: 'default' }); }
catch { error = 'Could not remove this theme.'; }
}} />{/if}
</div>
+11 -14
View File
@@ -1,27 +1,24 @@
<script lang="ts">
import { syncLocale } from '$lib/i18n';
import { onMount } from 'svelte';
import { APPEARANCE_KEY, applyAppearance, parseAppearance } from './appearance';
import { CUSTOM_THEMES_KEY } from './customThemes';
import { onSettingsChange, readSection, writeSection } from '$lib/settings/store';
import { applyAppearance, readAppearance } from './appearance';
onMount(() => {
const stopLocale = syncLocale();
const read = () => {
try {
const raw = localStorage.getItem(APPEARANCE_KEY);
const appearance = parseAppearance(raw);
const canonical = JSON.stringify(appearance);
if (raw !== null && raw !== canonical) localStorage.setItem(APPEARANCE_KEY, canonical);
const stored = readSection('appearance');
const appearance = readAppearance();
// Save the normalized value, for example a new ID for a renamed theme.
if (stored !== undefined && JSON.stringify(stored) !== JSON.stringify(appearance)) {
writeSection('appearance', appearance).catch(() => { /* The normalized value applies until the next save. */ });
}
applyAppearance(appearance);
}
catch { /* Keep the current appearance if storage is unavailable. */ }
catch { /* Keep the current appearance if the settings are unavailable. */ }
};
const sync = (event: StorageEvent) => { if (event.key === APPEARANCE_KEY || event.key === CUSTOM_THEMES_KEY || event.key === null) read(); };
read();
window.addEventListener('storage', sync);
window.addEventListener('focus', read);
return () => { stopLocale(); window.removeEventListener('storage', sync); window.removeEventListener('focus', read); };
const stops = [onSettingsChange('appearance', read), onSettingsChange('customThemes', read)];
return () => { stopLocale(); stops.forEach(stop => stop()); };
});
</script>
+14 -4
View File
@@ -1,6 +1,8 @@
import { customThemes, FONT_ROLES, type ThemeFonts, type ThemeColors, type CustomTheme } from './customThemes.ts';
import { readBackgroundImage } from './backgroundImages.ts';
import { characterTheme, characterSyntax, SYNTAX_ROLES } from './characterThemes.ts';
import { readSection, writeSection } from '../settings/store.ts';
/** The old localStorage key. The appearance section of the settings file replaces it. */
export const APPEARANCE_KEY = 'runestone.appearance';
export const THEMES = ['default', 'claude', 'sakura', 'harvest-moon', 'crimson-pilot', 'silver-serpent'] as const;
export const BUILTIN_THEMES = [
@@ -18,10 +20,11 @@ export const BACKGROUND_POSITIONS = ['center', 'top left', 'top', 'top right', '
export const BACKGROUND_SIZES = ['cover', 'contain', 'auto'] as const;
export type Appearance = { transparency?: { enabled: boolean; amount: number }; theme: ThemeName; mode: 'light' | 'dark'; newTabBackground?: { image?: string; imageId?: string; overlay?: number; position?: typeof BACKGROUND_POSITIONS[number]; size?: typeof BACKGROUND_SIZES[number] } };
export const DEFAULT_APPEARANCE: Appearance = { theme: 'default', mode: 'dark' };
export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown; transparency?: unknown } | null): Appearance {
/** `themes` is the list of custom themes. By default, it is the saved list. */
export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown; transparency?: unknown } | null, themes?: CustomTheme[]): Appearance {
const savedTheme = typeof value?.theme === 'string' && Object.hasOwn(LEGACY_THEME_IDS, value.theme) ? LEGACY_THEME_IDS[value.theme] : value?.theme;
const theme: ThemeName = typeof savedTheme === 'string' && (/^custom:[a-z][a-z0-9-]{0,63}$/.test(savedTheme) || (THEMES as readonly string[]).includes(savedTheme)) ? savedTheme as ThemeName : 'default';
const selectedCustom = theme.startsWith('custom:') ? customThemes(value?.mode === 'light' ? 'light' : 'dark').find(item => `custom:${item.id}` === theme) : undefined;
const selectedCustom = theme.startsWith('custom:') ? (themes ?? customThemes(value?.mode === 'light' ? 'light' : 'dark')).find(item => `custom:${item.id}` === theme) : undefined;
const result: Appearance = { theme, mode: selectedCustom ? customThemeMode(selectedCustom.colors) : characterTheme(theme)?.mode ?? (theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark') };
if (value?.transparency && typeof value.transparency === 'object') {
const source = value.transparency as { enabled?: unknown; amount?: unknown };
@@ -43,6 +46,11 @@ export function parseAppearance(raw: string | null): Appearance {
try { return normalizeAppearance(JSON.parse(raw || 'null')); }
catch { return { ...DEFAULT_APPEARANCE }; }
}
/** The saved appearance, normalized. */
export function readAppearance(): Appearance {
const value = readSection('appearance');
return normalizeAppearance(value && typeof value === 'object' && !Array.isArray(value) ? value : null);
}
const keys = ['bg', 'bg-elevated', 'bg-active', 'border', 'text-dim', 'text', 'text-strong', 'accent', 'selection'] as const;
const palettes = {
default: {
@@ -203,9 +211,11 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
}
window.dispatchEvent(new CustomEvent('runestone-theme-changed'));
}
export function saveAppearance(value: Appearance) {
/** Save and apply an appearance. Throws at once if browser storage refuses it. The promise reports a failed save. */
export function saveAppearance(value: Appearance): Promise<void> {
const appearance = normalizeAppearance(value);
localStorage.setItem(APPEARANCE_KEY, JSON.stringify(appearance));
const saved = writeSection('appearance', appearance);
applyAppearance(appearance);
return saved;
}
+14 -35
View File
@@ -1,3 +1,6 @@
import { readSection, writeSection } from '../settings/store.ts';
/** The old localStorage key. The customThemes section of the settings file replaces it. */
export const CUSTOM_THEMES_KEY = "runestone.custom-themes";
export const COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global", "syntax-string", "syntax-number", "syntax-comment", "syntax-type", "syntax-function"] as const;
export type ThemeColors = Partial<Record<typeof COLOR_TOKENS[number], string>>;
@@ -38,48 +41,24 @@ export function parseCustomTheme(input: unknown, legacyMode: "light" | "dark" =
return { schema: 2, id: value.id, name: value.name.trim(), colors: colors(value.schema === 1 ? legacyMode : "colors"), ...(fonts ? { fonts } : {}) };
}
const pendingLegacy = new Map<string, CustomTheme[]>();
/** The saved custom themes. Version 1 themes use the palette of `legacyMode`, by default the saved appearance mode. */
export function customThemes(legacyMode?: "light" | "dark"): CustomTheme[] {
try {
const raw = localStorage.getItem(CUSTOM_THEMES_KEY) || "[]";
const pending = pendingLegacy.get(raw);
if (pending) return pending.map(theme => ({ ...theme, colors: { ...theme.colors } }));
const stored = JSON.parse(raw);
const stored = readSection('customThemes');
if (!Array.isArray(stored)) return [];
if (!legacyMode) {
try { legacyMode = JSON.parse(localStorage.getItem('runestone.appearance') || 'null')?.mode === 'light' ? 'light' : 'dark'; }
catch { legacyMode = 'dark'; }
}
const parsed = stored.flatMap(value => { try { return [parseCustomTheme(value, legacyMode)]; } catch { return []; } });
if (stored.some(value => value?.schema === 1)) {
// Retain both original palettes before converting the saved selection to one palette.
try {
const backupKey = `${CUSTOM_THEMES_KEY}.legacy`;
const backup = JSON.parse(localStorage.getItem(backupKey) || '[]');
if (!Array.isArray(backup)) throw new Error('Invalid legacy backup');
const originals = backup;
for (const value of stored.filter(value => value?.schema === 1)) {
if (!originals.some(item => JSON.stringify(item) === JSON.stringify(value))) originals.push(value);
}
localStorage.setItem(backupKey, JSON.stringify(originals));
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(stored.map(value => {
try { return parseCustomTheme(value, legacyMode); } catch { return value; }
})));
} catch {
// Storage failures must not hide readable themes or change their chosen palette.
pendingLegacy.set(raw, parsed);
}
}
return parsed;
if (!legacyMode) legacyMode = (readSection('appearance') as { mode?: unknown } | undefined)?.mode === 'light' ? 'light' : 'dark';
const mode = legacyMode;
return stored.flatMap(value => { try { return [parseCustomTheme(value, mode)]; } catch { return []; } });
} catch { return []; }
}
export function installTheme(theme: CustomTheme): void {
/** Throws at once if browser storage refuses the change. The promise reports a failed save. */
export function installTheme(theme: CustomTheme): Promise<void> {
const list = customThemes().filter(item => item.id !== theme.id);
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify([...list, parseCustomTheme(theme)]));
return writeSection('customThemes', [...list, parseCustomTheme(theme)]);
}
export function removeTheme(id: string): void {
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(customThemes().filter(item => item.id !== id)));
/** Throws at once if browser storage refuses the change. The promise reports a failed save. */
export function removeTheme(id: string): Promise<void> {
return writeSection('customThemes', customThemes().filter(item => item.id !== id));
}