From 102ac4467590d516cc1210f9aef32f894d4186dc Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:06:43 +0100 Subject: [PATCH 1/3] [storage] TwoTabs: Announce each write to the other tabs after it commits --- packages/storage/src/index.ts | 55 +++++++++++- packages/storage/test/changes.test.ts | 120 ++++++++++++++++++++++++++ 2 files changed, 172 insertions(+), 3 deletions(-) create mode 100644 packages/storage/test/changes.test.ts diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index 2bb3f9c..7b31263 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -79,6 +79,11 @@ export interface Storage { * here is appended. Nothing is edited or removed. Rejects a file that is not a rose. */ importRose(file: unknown, currentKey: string): Promise<{ readonly added: number; readonly petals: number }>; + /** + * Hears what another tab of the garden wrote (two-tabs.md): `'log'` or `'place'`, + * after it committed. Read storage again on it. Returns the way to stop hearing. + */ + onChange(listener: (what: Change) => void): () => void; close(): void; } @@ -188,12 +193,44 @@ class RoseaDatabase extends Dexie { } } +/** What another tab changed (two-tabs.md W2): only which part, never the data. */ +export type Change = 'log' | 'place'; + +/** The channel every tab of the garden announces its writes on (two-tabs.md W1). */ +export const CHANGES_CHANNEL = `${DATABASE_NAME}-changes`; + /** * Opens the player's database. `options` lets a test pass fake-indexeddb; the app - * passes nothing and gets the browser's IndexedDB. + * passes nothing and gets the browser's IndexedDB. `settings.channel` names the + * channel writes are announced on (null: none), so tests can keep theirs apart. */ -export function openStorage(options?: DexieOptions): Storage { +export function openStorage(options?: DexieOptions, settings: { readonly channel?: string | null } = {}): Storage { const db = new RoseaDatabase(options); + const channelName = settings.channel === undefined ? CHANGES_CHANNEL : settings.channel; + // Where BroadcastChannel does not exist, each tab simply keeps its own view (W5). + const channel = channelName !== null && typeof BroadcastChannel === 'function' ? new BroadcastChannel(channelName) : null; + const listeners = new Set<(what: Change) => void>(); + if (channel) { + channel.onmessage = (message: MessageEvent) => { + const what = message.data; + if (what !== 'log' && what !== 'place') return; + for (const listener of listeners) { + try { + listener(what); + } catch (error) { + console.error('storage: a listener for changes in another tab failed', error); + } + } + }; + } + /** Called only after a write committed, so the other tab reads what was written. A tab never hears itself (W3). */ + const announce = (what: Change): void => { + try { + channel?.postMessage(what); + } catch (error) { + console.warn('storage: could not tell the other tabs about a change; they will see it on their next load', error); + } + }; const asIdentity = (row: KeyRow | undefined): Identity | null => { const id = row ? { publicKey: row.publicKey, privateKey: row.privateKey } : null; return id && isIdentity(id) ? id : null; @@ -211,11 +248,13 @@ export function openStorage(options?: DexieOptions): Storage { const plain = asSunsetPlace(place); if (plain === null) throw new TypeError('storage: refusing to save a sunset place of an unknown shape'); await db.profile.put({ key: SUNSET_PLACE, value: plain }); + announce('place'); }, async appendCare(event) { const plain = asCareEvent(event); if (plain === null) throw new TypeError('storage: refusing to append a care event of an unknown shape'); await db.events.add({ event: plain }); + announce('log'); }, async loadCare() { const rows = await db.events.orderBy('id').toArray(); @@ -233,6 +272,7 @@ export function openStorage(options?: DexieOptions): Storage { const plain = asSentenceOpened(event); if (plain === null) throw new TypeError('storage: refusing to append an opened petal of an unknown shape'); await db.events.add({ event: plain }); + announce('log'); }, async loadOpened() { const rows = await db.events.orderBy('id').toArray(); @@ -276,7 +316,7 @@ export function openStorage(options?: DexieOptions): Storage { async importRose(file, currentKey) { const rose = asRoseFile(file); if (rose === null) throw new TypeError('storage: this file does not hold a rose'); - return db.transaction('rw', db.events, db.profile, async () => { + const result = await db.transaction('rw', db.events, db.profile, async () => { const row = await db.profile.get(PAST_KEYS); const past = isKeyList(row?.value) ? row.value : []; const keys = [...new Set([...past, ...rose.keys])].filter((k) => k !== currentKey); @@ -289,8 +329,17 @@ export function openStorage(options?: DexieOptions): Storage { await db.events.bulkAdd([...added, ...petals].map((event) => ({ event }))); return { added: added.length, petals: petals.length }; }); + // After the commit: her keys and her log both changed for the other tabs. + announce('log'); + return result; + }, + onChange(listener) { + listeners.add(listener); + return () => listeners.delete(listener); }, close() { + listeners.clear(); + channel?.close(); db.close(); } }; diff --git a/packages/storage/test/changes.test.ts b/packages/storage/test/changes.test.ts new file mode 100644 index 0000000..0dbfe47 --- /dev/null +++ b/packages/storage/test/changes.test.ts @@ -0,0 +1,120 @@ +import type { CareEvent, SentenceOpened } from '@rosea/schema'; +import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { openStorage, ROSE_FILE_FORMAT, type Change, type Storage } from '../src/index.js'; + +const KEY = 'K'.repeat(87); +const OLD = 'O'.repeat(87); +const weed: CareEvent = { kind: 'care', ts: 1774944060000, localDay: '2026-03-31', from: KEY, to: KEY, act: 'weed', trace: 'petal:rose', messageId: null, clientVersion: '0.1.0' }; +const petal: SentenceOpened = { kind: 'sentence-opened', ts: 1774944000000, localDay: '2026-03-31', from: KEY, messageId: 'ps-118-24', clientVersion: '0.1.0' }; +const brno = { kind: 'town', town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } } as const; + +let channels = 0; +const opened: Storage[] = []; +/** Two tabs of one garden: one database, one channel, their own for this test. */ +function twoTabs(): [Storage, Storage] { + const indexedDB = new IDBFactory(); + const channel = `rosea-test-${++channels}`; + const tabs = [openStorage({ indexedDB, IDBKeyRange }, { channel }), openStorage({ indexedDB, IDBKeyRange }, { channel })] as [Storage, Storage]; + opened.push(...tabs); + return tabs; +} +afterEach(() => { + for (const s of opened.splice(0)) s.close(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +/** Everything `tab` hears in the next `ms`. */ +function hears(tab: Storage, ms = 150): Promise { + const heard: Change[] = []; + const stop = tab.onChange((what) => heard.push(what)); + return new Promise((resolve) => + setTimeout(() => { + stop(); + resolve(heard); + }, ms) + ); +} + +describe('a write is announced to the other tabs (two-tabs.md W1)', () => { + it('care: the other tab hears "log", and reading then finds it', async () => { + const [a, b] = twoTabs(); + let found: CareEvent[] = []; + const read = new Promise((resolve) => + b.onChange(async () => { + found = await b.loadCare(); + resolve(); + }) + ); + await a.appendCare(weed); + await read; + expect(found).toEqual([weed]); + }); + + it('a petal and a rose brought back are "log"; a town is "place"', async () => { + const [a, b] = twoTabs(); + const heard = hears(b); + await a.appendOpened(petal); + await a.importRose({ format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [], opened: [] }, KEY); + await a.saveSunsetPlace(brno); + expect(await heard).toEqual(['log', 'log', 'place']); + }); + + it('a tab does not hear itself (W3)', async () => { + const [a] = twoTabs(); + const heard = hears(a); + await a.appendCare(weed); + expect(await heard).toEqual([]); + }); + + it('a refused write announces nothing', async () => { + const [a, b] = twoTabs(); + const heard = hears(b); + await expect(a.appendCare({ ...weed, note: 'x' } as CareEvent)).rejects.toThrow(); + await expect(a.importRose('not a rose', KEY)).rejects.toThrow(); + expect(await heard).toEqual([]); + }); + + it('a malformed message is ignored; a listener that throws does not stop the others', async () => { + const [, b] = twoTabs(); + const raw = new BroadcastChannel(`rosea-test-${channels}`); + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined); + b.onChange(() => { + throw new Error('a broken listener'); + }); + const heard = hears(b); + raw.postMessage({ what: 'log', data: 'anything' }); + raw.postMessage('care'); + raw.postMessage('place'); + expect(await heard).toEqual(['place']); + expect(error).toHaveBeenCalledOnce(); + raw.close(); + }); + + it('after unsubscribing, or after close, nothing more is heard', async () => { + const [a, b] = twoTabs(); + const calls: Change[] = []; + const stop = b.onChange((w) => calls.push(w)); + stop(); + await a.appendCare(weed); + b.close(); + await a.appendCare({ ...weed, ts: weed.ts + 1 }); + await new Promise((r) => setTimeout(r, 100)); + expect(calls).toEqual([]); + }); +}); + +describe('without a channel (W5)', () => { + it('storage works as before, and simply hears nothing', async () => { + vi.stubGlobal('BroadcastChannel', undefined); + const indexedDB = new IDBFactory(); + const a = openStorage({ indexedDB, IDBKeyRange }); + const b = openStorage({ indexedDB, IDBKeyRange }); + opened.push(a, b); + const heard = hears(b); + await a.appendCare(weed); + expect(await b.loadCare()).toEqual([weed]); + expect(await heard).toEqual([]); + }); +}); From b67fa3603ddaa778270dcc1832b30146a2f8eb78 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:06:44 +0100 Subject: [PATCH 2/3] [ui] TwoTabs: The rose and the garden read again when another tab wrote, keeping their own --- apps/rosea/src/App.svelte | 6 +- e2e/shell.spec.ts | 39 +++++++++++ packages/ui/src/Shell.svelte | 16 +++++ packages/ui/src/rose/Rose.svelte | 22 +++--- packages/ui/src/rose/types.ts | 2 + packages/ui/src/sunset/types.ts | 2 + packages/ui/test/two-tabs.test.ts | 107 ++++++++++++++++++++++++++++++ 7 files changed, 185 insertions(+), 9 deletions(-) create mode 100644 packages/ui/test/two-tabs.test.ts diff --git a/apps/rosea/src/App.svelte b/apps/rosea/src/App.svelte index cdbb75d..ab70679 100644 --- a/apps/rosea/src/App.svelte +++ b/apps/rosea/src/App.svelte @@ -29,7 +29,9 @@ search: async (query) => (await loadTowns()).searchTowns(query), load: () => storage.loadSunsetPlace(), save: (choice) => storage.saveSunsetPlace(choice), - now: () => Date.now() + now: () => Date.now(), + // Another tab of the garden chose a town (two-tabs.md). + changes: (listener) => storage.onChange((what) => what === 'place' && listener()) }; // The player's key names their rose (rose.md). Kept once; if the device will not @@ -97,6 +99,8 @@ sentences, loadOpened: () => storage.loadOpened(), appendOpened: (event) => storage.appendOpened(event), + // Another tab gave care, opened a petal or brought her back (two-tabs.md). + changes: (listener) => storage.onChange((what) => what === 'log' && listener()), clientVersion: version, deviceZone, now: () => Date.now(), diff --git a/e2e/shell.spec.ts b/e2e/shell.spec.ts index 034ac5e..763ab09 100644 --- a/e2e/shell.spec.ts +++ b/e2e/shell.spec.ts @@ -241,6 +241,45 @@ test.describe('the rose, in Prague at 08:00 on 1 March 2026', () => { }); }); +// --- Two tabs, one garden (.agents/features/two-tabs.md) ---------------------- +test.describe('two tabs of the garden, in Prague at 08:00 on 1 March 2026', () => { + test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' }); + const MORNING = Date.parse('2026-03-01T08:00:00+01:00'); + + test('care given in one tab is seen in the other without a reload, so she is not watered twice', async ({ page, context }) => { + const other = await context.newPage(); + for (const p of [page, other]) { + await p.clock.setFixedTime(MORNING); + await open(p); + await expect(p.getByText(en.rose.says.dry)).toBeVisible(); + } + await page.getByRole('button', { name: en.rose.water }).hover(); + await page.mouse.down(); + await page.waitForTimeout(1500); + await page.mouse.up(); + await expect(page.getByText(en.rose.says.thanks)).toBeVisible(); + await storedCare(page, 1); + + // The other tab, untouched and not reloaded, knows she was watered. + await expect(other.getByText(en.rose.says.thanks)).toBeVisible({ timeout: 3_000 }); + await other.getByRole('button', { name: en.rose.numbers }).click(); + await expect(other.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`); + }); + + test('a town chosen in one tab is the town in the other', async ({ page, context }) => { + const other = await context.newPage(); + for (const p of [page, other]) { + await p.clock.setFixedTime(MORNING); + await open(p); + await expect(p.getByRole('heading', { level: 2, name: en.sunset.question })).toBeVisible(); + } + await page.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno'); + await page.getByRole('button', { name: /^Brno/ }).first().click(); + await storedTown(page, 'Brno'); + await expect(other.locator('.sun p').first()).toHaveText(/in Brno\.$/, { timeout: 3_000 }); + }); +}); + // --- Keeping her (.agents/features/keep-her-safe.md) -------------------------- test.describe('keep her safe, in Prague at 08:00 on 1 March 2026', () => { test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' }); diff --git a/packages/ui/src/Shell.svelte b/packages/ui/src/Shell.svelte index d11e73b..6996b68 100644 --- a/packages/ui/src/Shell.svelte +++ b/packages/ui/src/Shell.svelte @@ -72,6 +72,22 @@ return () => clearInterval(timer); }); + // A town chosen in another tab becomes the town here too (two-tabs.md). + $effect(() => { + const wiring = sunset; + return wiring?.changes?.(() => { + wiring.load().then( + (saved) => { + if (saved === null) return; + choice = saved; + status = 'set'; + now = wiring.now(); + }, + (error: unknown) => console.error('sunset: could not read the town another tab chose', error) + ); + }); + }); + async function choose(next: SunsetChoice): Promise { if (!sunset) return; choice = next; diff --git a/packages/ui/src/rose/Rose.svelte b/packages/ui/src/rose/Rose.svelte index 7be3f8e..0118dde 100644 --- a/packages/ui/src/rose/Rose.svelte +++ b/packages/ui/src/rose/Rose.svelte @@ -1,6 +1,6 @@