feat(settings): make two Manager tabs agree with each other
docs/15 recorded this as a known v1 limitation, and with real users it is a one-star review waiting to happen: `save()` writes the whole settings object rather than a patch, so a tab opened before the language changed reverted that change the moment its own theme toggle fired. From the user's side that reads as "I changed it and it didn't stick" — unfalsifiable, and indistinguishable from a bug. Accepting the legal terms in one tab likewise left the other padlocked until reload. The adoption rule is field equality plus an in-flight guard, and between them they solve the echo problem and the debounce problem at once: 1. If this context has an unflushed write, ignore the incoming change entirely. It is about to overwrite that value anyway, and adopting first would clobber the choice the user just made — in the UI *and* in what gets persisted 200 ms later. That is last-write-wins, exactly the semantic docs/15 documented, and it converges because our write fires the same event in the other tab. 2. Otherwise adopt only fields that actually differ. Our own write always matches what we already hold, so self-echo suppression falls out for free — no `lastWritten` snapshot to keep in step and go stale, and no dependence on key order, which a $state spread and coerceSettings do not agree on. The fake-timer test covering rule 1 is the one that matters; without it the guard is an unverified assertion about a race. Legal acceptance is adopted **one way only, toward accepted.** App.svelte renders the gate in place of the tab body, so an externally-raised gate would unmount ImportTab mid-write and strand the import it was driving — recreating, through a third door, the deadlock the routing guard and the store-held attestation resolver were just written to close. Clearing storage elsewhere therefore does nothing; a reload re-evaluates it, and a reload has no in-flight work to strand. Three tests pin that asymmetry so a future simplification that makes it symmetrical fails loudly. subscribeStorage coerces through the same functions the read path uses — a second tab is not a more trustworthy source than disk, it is the same disk — and swallows a throwing handler, because an exception inside a chrome.* listener surfaces in chrome://extensions and docs/11 §5 counts that as a failed QA pass. Verified before writing any of it that WXT's fakeBrowser does implement storage.onChanged (unlike bookmarks.*), so no injectable event source was needed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
7 files changed
+346
-10
No files matched your search
@@ -21,7 +21,14 @@
|
||||
isGateRequired,
|
||||
} from '@/lib/stores/legal.svelte';
|
||||
import { getRoute, navigate, startRouting } from '@/lib/stores/route.svelte';
|
||||
import { flushSettings, getSettings, updateSettings } from '@/lib/stores/settings.svelte';
|
||||
import { subscribeStorage } from '@/lib/browser/storage';
|
||||
import { adoptExternalLegal } from '@/lib/stores/legal.svelte';
|
||||
import {
|
||||
adoptExternalSettings,
|
||||
flushSettings,
|
||||
getSettings,
|
||||
updateSettings,
|
||||
} from '@/lib/stores/settings.svelte';
|
||||
import { pushToast } from '@/lib/stores/toast.svelte';
|
||||
|
||||
// Settings are loaded and awaited in main.ts, before this ever mounts.
|
||||
@@ -55,11 +62,22 @@
|
||||
if (globalThis.document?.visibilityState === 'hidden') void flushSettings();
|
||||
};
|
||||
|
||||
// Two Manager tabs used to overwrite each other silently: `save()` writes
|
||||
// the whole settings object, so a tab holding a stale locale reverted the
|
||||
// other tab's language change the moment its own theme toggle fired.
|
||||
// Registered here rather than in main.ts because this is the only place
|
||||
// with a teardown path.
|
||||
const stopStorage = subscribeStorage((change) => {
|
||||
if (change.settings !== undefined) adoptExternalSettings(change.settings);
|
||||
if ('legal' in change) adoptExternalLegal(change.legal ?? null);
|
||||
});
|
||||
|
||||
globalThis.addEventListener('beforeunload', onBeforeUnload);
|
||||
globalThis.document?.addEventListener('visibilitychange', onVisibilityChange);
|
||||
|
||||
return () => {
|
||||
stopRouting();
|
||||
stopStorage();
|
||||
globalThis.removeEventListener('beforeunload', onBeforeUnload);
|
||||
globalThis.document?.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
};
|
||||
|
||||
@@ -81,15 +81,21 @@ export async function writeSettings(settings: Settings): Promise<void> {
|
||||
await browser.storage.local.set({ [SETTINGS_KEY]: settings });
|
||||
}
|
||||
|
||||
/** Keep only a well-formed acceptance record; anything else is "never accepted". */
|
||||
function coerceLegal(raw: unknown): LegalAcceptance | null {
|
||||
if (!isRecord(raw) || typeof raw.acceptedVersion !== 'number') return null;
|
||||
return {
|
||||
acceptedVersion: raw.acceptedVersion,
|
||||
// Coerced rather than left missing: `Intl.format(new Date(''))` throws a
|
||||
// RangeError inside a render, which would blank the About tab.
|
||||
acceptedAt: typeof raw.acceptedAt === 'string' ? raw.acceptedAt : '',
|
||||
};
|
||||
}
|
||||
|
||||
export async function readLegal(): Promise<LegalAcceptance | null> {
|
||||
try {
|
||||
const stored = await browser.storage.local.get(LEGAL_KEY);
|
||||
const raw = stored[LEGAL_KEY];
|
||||
if (!isRecord(raw) || typeof raw.acceptedVersion !== 'number') return null;
|
||||
return {
|
||||
acceptedVersion: raw.acceptedVersion,
|
||||
acceptedAt: typeof raw.acceptedAt === 'string' ? raw.acceptedAt : '',
|
||||
};
|
||||
return coerceLegal(stored[LEGAL_KEY]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -106,3 +112,44 @@ export async function writeLegal(acceptedVersion: number, nowIso: string): Promi
|
||||
[LEGAL_KEY]: { acceptedVersion, acceptedAt: nowIso } satisfies LegalAcceptance,
|
||||
});
|
||||
}
|
||||
|
||||
/** What changed, already coerced. A key absent from the event stays absent. */
|
||||
export interface StorageChange {
|
||||
settings?: Settings;
|
||||
legal?: LegalAcceptance | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Watch for writes made by another extension context — a second Manager tab.
|
||||
*
|
||||
* The event fires in *every* context including the one that wrote, so the
|
||||
* caller has to decide what is an echo of its own write; this layer only
|
||||
* decodes and hands over. Values are coerced through the same functions the
|
||||
* read path uses, because a second tab is not a more trustworthy source than
|
||||
* disk — it is the same disk.
|
||||
*
|
||||
* @returns an unsubscribe function.
|
||||
*/
|
||||
export function subscribeStorage(handler: (change: StorageChange) => void): () => void {
|
||||
const onChanged = (changes: Record<string, { newValue?: unknown }>, areaName: string): void => {
|
||||
// Everything this extension stores is in `local`; `sync` is never used
|
||||
// (docs/09 §1.3) and a write there is not ours to react to.
|
||||
if (areaName !== 'local') return;
|
||||
try {
|
||||
const change: StorageChange = {};
|
||||
if (SETTINGS_KEY in changes)
|
||||
change.settings = coerceSettings(changes[SETTINGS_KEY]?.newValue);
|
||||
if (LEGAL_KEY in changes) change.legal = coerceLegal(changes[LEGAL_KEY]?.newValue);
|
||||
if (change.settings !== undefined || 'legal' in change) handler(change);
|
||||
} catch {
|
||||
// A throw inside a chrome.* listener surfaces as an extension error in
|
||||
// chrome://extensions, which the QA pass treats as a failure. Nothing
|
||||
// here is worth that: the next read will pick up the same value.
|
||||
}
|
||||
};
|
||||
|
||||
browser.storage.onChanged.addListener(onChanged);
|
||||
return () => {
|
||||
browser.storage.onChanged.removeListener(onChanged);
|
||||
};
|
||||
}
|
||||
@@ -94,6 +94,28 @@ export async function loadLegal(): Promise<void> {
|
||||
status = decideLegalStatus(await readLegal(), LEGAL_VERSION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adopt an acceptance recorded by another Manager tab — **one way only**.
|
||||
*
|
||||
* Accepting in one tab drops the gate in the other. The reverse is deliberately
|
||||
* unreachable: `App.svelte` renders the gate *in place of* the tab body, so an
|
||||
* externally-raised gate would unmount `ImportTab` mid-write and strand the
|
||||
* import it was driving — recreating, through a third door, exactly the
|
||||
* deadlock the routing guard and the store-held attestation resolver exist to
|
||||
* close. Clearing storage in another tab therefore does nothing here; a reload
|
||||
* is what re-evaluates the gate downward, and that is a fresh page with no
|
||||
* in-flight work to strand.
|
||||
*
|
||||
* @returns whether the gate was dropped.
|
||||
*/
|
||||
export function adoptExternalLegal(acceptance: LegalAcceptance | null): boolean {
|
||||
if (status.kind === 'accepted') return false;
|
||||
const next = decideLegalStatus(acceptance, LEGAL_VERSION);
|
||||
if (next.kind !== 'accepted') return false;
|
||||
status = next;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record acceptance.
|
||||
*
|
||||
|
||||
@@ -50,6 +50,43 @@ export async function loadSettings(): Promise<void> {
|
||||
loaded = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adopt settings written by another Manager tab.
|
||||
*
|
||||
* Two rules, and between them they solve the echo problem and the debounce
|
||||
* problem at once:
|
||||
*
|
||||
* 1. **If this context has an unflushed write, ignore the change entirely.**
|
||||
* `save()` writes the whole object, not a patch, so this tab is about to
|
||||
* overwrite the incoming value anyway — and adopting it first would clobber
|
||||
* the choice the user just made, in the UI *and* in what gets persisted 200
|
||||
* ms later. Ignoring is last-write-wins, which is the semantic docs/15
|
||||
* already documented, and it converges because our write fires this same
|
||||
* event in the other tab.
|
||||
* 2. **Otherwise adopt only fields that actually differ.** Our own write always
|
||||
* matches what we already hold, so self-echo suppression falls out for free
|
||||
* — no `lastWritten` snapshot to keep in step and go stale, and no
|
||||
* dependence on key order, which `{...proxy}` and `coerceSettings` do not
|
||||
* agree on anyway.
|
||||
*
|
||||
* Deliberately does not schedule a save: adopting a value that is already on
|
||||
* disk and writing it straight back would make two tabs ping-pong forever.
|
||||
*
|
||||
* @returns whether anything changed.
|
||||
*/
|
||||
export function adoptExternalSettings(next: Settings): boolean {
|
||||
if (saveTimer !== undefined || pending !== undefined) return false;
|
||||
|
||||
const keys = Object.keys(DEFAULT_SETTINGS) as (keyof Settings)[];
|
||||
if (keys.every((key) => settings[key] === next[key])) return false;
|
||||
|
||||
// In place, never replaced — see updateSettings.
|
||||
Object.assign(settings, next);
|
||||
applyLocale();
|
||||
applyTheme(settings.theme);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a patch now, persist it shortly.
|
||||
*
|
||||
|
||||
@@ -1,19 +1,28 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fakeBrowser } from 'wxt/testing';
|
||||
import {
|
||||
DEFAULT_SETTINGS,
|
||||
readLegal,
|
||||
readSettings,
|
||||
type StorageChange,
|
||||
subscribeStorage,
|
||||
writeLegal,
|
||||
writeSettings,
|
||||
} from '@/lib/browser/storage';
|
||||
|
||||
// fakeBrowser DOES implement storage.local, so no hand-rolled mock is needed
|
||||
// here (unlike bookmarks — docs/11 §4).
|
||||
// fakeBrowser DOES implement storage.local — and, verified before this suite
|
||||
// was written, storage.onChanged too. No hand-rolled mock is needed here
|
||||
// (unlike bookmarks — docs/11 §4).
|
||||
beforeEach(() => {
|
||||
fakeBrowser.reset();
|
||||
// reset() clears stored data but leaves spies in place, so one test that
|
||||
// mocks a storage call would otherwise leak into every later test.
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
/** Let the storage event dispatch. */
|
||||
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve));
|
||||
|
||||
describe('settings', () => {
|
||||
it('returns the documented defaults on a fresh profile', async () => {
|
||||
expect(await readSettings()).toEqual(DEFAULT_SETTINGS);
|
||||
@@ -80,3 +89,84 @@ describe('legal acceptance', () => {
|
||||
expect(Object.keys(all).sort()).toEqual(['legal', 'settings']);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* `subscribeStorage` — docs/03 §4.
|
||||
*
|
||||
* The event fires in every extension context including the one that wrote, so
|
||||
* this layer only decodes and hands over; deciding what is an echo belongs to
|
||||
* the store, which is the only thing that knows what it was about to write.
|
||||
*/
|
||||
describe('subscribeStorage', () => {
|
||||
it('reports a settings write made elsewhere, already coerced', async () => {
|
||||
const seen: StorageChange[] = [];
|
||||
const stop = subscribeStorage((change) => seen.push(change));
|
||||
|
||||
await fakeBrowser.storage.local.set({ settings: { ...DEFAULT_SETTINGS, theme: 'dark' } });
|
||||
await settle();
|
||||
|
||||
expect(seen).toHaveLength(1);
|
||||
expect(seen[0]?.settings?.theme).toBe('dark');
|
||||
stop();
|
||||
});
|
||||
|
||||
it('coerces a malformed value field by field rather than passing it through', async () => {
|
||||
// A second tab is not a more trustworthy source than disk. It is the disk.
|
||||
const seen: StorageChange[] = [];
|
||||
const stop = subscribeStorage((change) => seen.push(change));
|
||||
|
||||
await fakeBrowser.storage.local.set({ settings: { theme: 'chartreuse', locale: 'vi' } });
|
||||
await settle();
|
||||
|
||||
expect(seen[0]?.settings).toEqual({ ...DEFAULT_SETTINGS, locale: 'vi' });
|
||||
stop();
|
||||
});
|
||||
|
||||
it('reports a legal acceptance, and a cleared one as null', async () => {
|
||||
const seen: StorageChange[] = [];
|
||||
const stop = subscribeStorage((change) => seen.push(change));
|
||||
|
||||
await writeLegal(1, '2026-08-03T00:00:00.000Z');
|
||||
await settle();
|
||||
expect(seen.at(-1)?.legal?.acceptedVersion).toBe(1);
|
||||
|
||||
await fakeBrowser.storage.local.remove('legal');
|
||||
await settle();
|
||||
expect(seen.at(-1)?.legal).toBeNull();
|
||||
stop();
|
||||
});
|
||||
|
||||
it('ignores keys this extension does not own', async () => {
|
||||
const seen: StorageChange[] = [];
|
||||
const stop = subscribeStorage((change) => seen.push(change));
|
||||
|
||||
await fakeBrowser.storage.local.set({ somethingElse: 1 });
|
||||
await settle();
|
||||
|
||||
expect(seen).toHaveLength(0);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('stops delivering once unsubscribed', async () => {
|
||||
const seen: StorageChange[] = [];
|
||||
const stop = subscribeStorage((change) => seen.push(change));
|
||||
stop();
|
||||
|
||||
await writeSettings({ ...DEFAULT_SETTINGS, theme: 'dark' });
|
||||
await settle();
|
||||
|
||||
expect(seen).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('swallows a throwing handler', async () => {
|
||||
// An exception inside a chrome.* listener surfaces as an extension error in
|
||||
// chrome://extensions, which docs/11 §5 treats as a failed QA pass.
|
||||
const stop = subscribeStorage(() => {
|
||||
throw new Error('handler blew up');
|
||||
});
|
||||
|
||||
await expect(writeSettings({ ...DEFAULT_SETTINGS })).resolves.toBeUndefined();
|
||||
await settle();
|
||||
stop();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { fakeBrowser } from 'wxt/testing';
|
||||
import { LEGAL_VERSION } from '@/lib/core/limits';
|
||||
import {
|
||||
acceptLegal,
|
||||
adoptExternalLegal,
|
||||
decideLegalStatus,
|
||||
getAcceptance,
|
||||
getBlockedRoutes,
|
||||
@@ -159,3 +160,54 @@ describe('acceptLegal', () => {
|
||||
expect(Object.keys(all)).not.toContain('legal');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Cross-tab adoption — docs/03 §4, docs/14 §2.
|
||||
*
|
||||
* Deliberately one-way. `App.svelte` renders the gate *in place of* the tab
|
||||
* body, so an externally-raised gate would unmount ImportTab mid-write and
|
||||
* strand the import it was driving — the same deadlock the routing guard and
|
||||
* the store-held attestation resolver exist to close, reached through a third
|
||||
* door. These tests exist so a future "simplification" that makes it
|
||||
* symmetrical fails loudly rather than shipping.
|
||||
*/
|
||||
describe('adoptExternalLegal', () => {
|
||||
it('drops the gate when another tab accepts', async () => {
|
||||
await loadLegal();
|
||||
expect(isGateRequired()).toBe(true);
|
||||
|
||||
expect(adoptExternalLegal({ acceptedVersion: LEGAL_VERSION, acceptedAt: 'x' })).toBe(true);
|
||||
expect(isGateRequired()).toBe(false);
|
||||
});
|
||||
|
||||
it('does NOT re-gate when another tab clears the acceptance', async () => {
|
||||
await fakeBrowser.storage.local.set({
|
||||
legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: 'x' },
|
||||
});
|
||||
await loadLegal();
|
||||
expect(isGateRequired()).toBe(false);
|
||||
|
||||
expect(adoptExternalLegal(null)).toBe(false);
|
||||
expect(isGateRequired()).toBe(false);
|
||||
});
|
||||
|
||||
it('does NOT re-gate on a superseded record either', async () => {
|
||||
await fakeBrowser.storage.local.set({
|
||||
legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: 'x' },
|
||||
});
|
||||
await loadLegal();
|
||||
|
||||
expect(adoptExternalLegal({ acceptedVersion: LEGAL_VERSION - 1, acceptedAt: 'old' })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isGateRequired()).toBe(false);
|
||||
});
|
||||
|
||||
it('ignores a stale record while the gate is up, rather than accepting it', async () => {
|
||||
await loadLegal();
|
||||
expect(adoptExternalLegal({ acceptedVersion: LEGAL_VERSION - 1, acceptedAt: 'old' })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isGateRequired()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { fakeBrowser } from 'wxt/testing';
|
||||
import { DEFAULT_SETTINGS } from '@/lib/browser/storage';
|
||||
import { getLocale } from '@/lib/i18n/index.svelte';
|
||||
import {
|
||||
adoptExternalSettings,
|
||||
applyTheme,
|
||||
flushSettings,
|
||||
getSettings,
|
||||
@@ -200,3 +201,72 @@ describe('settings store', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Cross-tab adoption — docs/03 §4.
|
||||
*
|
||||
* Two Manager tabs used to silently overwrite each other, because `save()`
|
||||
* writes the whole settings object rather than a patch: a tab holding a stale
|
||||
* locale reverted the other tab's language change the moment its own theme
|
||||
* toggle fired. From the user's side that is "I changed it and it didn't
|
||||
* stick", which is unfalsifiable and reads as a bug in the extension.
|
||||
*/
|
||||
describe('adoptExternalSettings', () => {
|
||||
it('applies a change from another tab, including locale and theme', async () => {
|
||||
await updateSettings({ theme: 'light' });
|
||||
const changed = adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'dark', locale: 'vi' });
|
||||
|
||||
expect(changed).toBe(true);
|
||||
expect(getSettings().theme).toBe('dark');
|
||||
expect(document.documentElement.getAttribute('data-theme')).toBe('dark');
|
||||
expect(getLocale()).toBe('vi');
|
||||
});
|
||||
|
||||
it('mutates in place, so a component that captured the object still sees it', () => {
|
||||
const captured = getSettings();
|
||||
adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'dark' });
|
||||
expect(getSettings()).toBe(captured);
|
||||
expect(captured.theme).toBe('dark');
|
||||
});
|
||||
|
||||
it('ignores an identical value — which is what our own write looks like', () => {
|
||||
// Echo suppression falls out of field equality: no snapshot to keep in step,
|
||||
// and no dependence on key order.
|
||||
expect(adoptExternalSettings({ ...getSettings() })).toBe(false);
|
||||
});
|
||||
|
||||
it('does NOT clobber an edit this tab has not persisted yet', async () => {
|
||||
// The hazard the whole design exists for. Writes are debounced 200 ms; a
|
||||
// change arriving inside that window must lose, because this tab is about
|
||||
// to write its entire object over it anyway — adopting first would revert
|
||||
// the user's choice in the UI *and* in what gets saved.
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
void updateSettings({ theme: 'dark' });
|
||||
const changed = adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'light' });
|
||||
|
||||
expect(changed).toBe(false);
|
||||
expect(getSettings().theme).toBe('dark');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
const stored = await fakeBrowser.storage.local.get('settings');
|
||||
expect((stored.settings as { theme: string }).theme).toBe('dark');
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('adopts again once the pending write has flushed', async () => {
|
||||
await updateSettings({ theme: 'dark' });
|
||||
await flushSettings();
|
||||
expect(adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'light' })).toBe(true);
|
||||
});
|
||||
|
||||
it('does not write back what it just adopted', async () => {
|
||||
// Otherwise two tabs ping-pong the same value forever.
|
||||
const spy = vi.spyOn(fakeBrowser.storage.local, 'set');
|
||||
adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'dark' });
|
||||
await flushSettings();
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user