diff --git a/.agents/FEATURES.md b/.agents/FEATURES.md
index 00ad827..7ad66c2 100644
--- a/.agents/FEATURES.md
+++ b/.agents/FEATURES.md
@@ -8,6 +8,7 @@ One row per feature, with its analysis document (CLAUDE.md §5.1). Gaps live in
| Workspace, contracts, gates, PWA shell | 0 | Merged to `main` 2026-11-01 (`d11d242`); built, not deployed. Phase 0 gate still open | [phase0-workspace.md](features/phase0-workspace.md) | [feature-phase0-workspace.md](reviews/feature-phase0-workspace.md) |
| Roadmap and gameplay docs, read against the code | 0 | Merged 2026-11-01; Q1–Q7 answered by the author | — | [docs-roadmap-gameplay.md](reviews/docs-roadmap-gameplay.md) |
| The Letter slot: page at `#letter`, empty `docs/LETTER.md` | 0 | Merged to `main`; built, not deployed. Invisible until the author writes | [letter-slot.md](features/letter-slot.md) | [feature-letter-slot.md](reviews/feature-letter-slot.md) |
+| Two tabs, one garden: what one tab writes, the others see | 1 | Merged to `main`; built, not deployed | [two-tabs.md](features/two-tabs.md) | [fix-two-tabs.md](reviews/fix-two-tabs.md) |
| Thorns: touch her; a rush of taps, and she says she has thorns | 1 | Merged to `main`; built, not deployed | [thorns.md](features/thorns.md) | [feature-thorns.md](reviews/feature-thorns.md) |
| The day's sentence: her folded petal, one a day, never lost, best at sunset; candidates and `library:verify` | 1 | Merged to `main`; built, not deployed. Invisible until the author verifies sentences | [day-sentence.md](features/day-sentence.md) | [feature-day-sentence.md](reviews/feature-day-sentence.md) |
| The in-game sunset: move the chair, half a minute of silence, then the real sunset's time | 1 | Merged to `main`; built, not deployed | [chair-sunset.md](features/chair-sunset.md) | [feature-chair-sunset.md](reviews/feature-chair-sunset.md) |
diff --git a/.agents/GAP_ANALYSIS.md b/.agents/GAP_ANALYSIS.md
index 6acd0e5..65a42bb 100644
--- a/.agents/GAP_ANALYSIS.md
+++ b/.agents/GAP_ANALYSIS.md
@@ -59,6 +59,7 @@ sentences). Nothing in Phase 1 is visible to the player yet.
| ~~G1.5~~ | ~~The day's sentence and the folded petal~~ | Closed 2026-11-02 on `feature/day-sentence`, for the code: `engine/petal` (5 properties: never lost, verified-later never swaps it, one a day, no repeat until all opened), the `sentence-opened` event, the rose file v2, the petal in the garden; e2e opens one in a fixture build and reloads. 9 of 9 put-back bugs caught. **The shipped app shows no petal until the author verifies sentences (G0.18).** |
| ~~G1.6~~ | ~~The in-game sunset: move the chair, watch it again~~ | Closed 2026-11-02 on `feature/chair-sunset`: half a minute with nothing to press, then the real sunset's time; Escape and a tap leave; the offline suite watches one with the server gone. 4 of 4 put-back bugs caught. |
| ~~G1.7~~ | ~~Thorns were on the roadmap but undesigned~~ | Closed 2026-11-02 on `feature/thorns`, as the author chose: thorns teach gentleness. `engine/touch` (2 properties: spaced taps are never a rush; one blush a visit); a tremor is one touch; nothing recorded. 6 of 6 put-back bugs caught. |
+| ~~G1.8~~ | ~~Two tabs (CLAUDE.md §8, predicted)~~ | Closed 2026-11-07 on `fix/two-tabs`. Measured first: two e2e tests failed (an open tab saw neither care nor a town from the other). Storage announces committed writes on a `BroadcastChannel`; the rose and the garden read again, adding to what they show. No lock needed: nothing stored drifts. 7 of 7 put-back bugs caught. |
| G1.3 | Towns have no Czech names (*Vídeň*) | Open. Natural Earth has none; arrives with Czech copy. |
## Design questions — answered
diff --git a/.agents/features/two-tabs.md b/.agents/features/two-tabs.md
new file mode 100644
index 0000000..a2480a8
--- /dev/null
+++ b/.agents/features/two-tabs.md
@@ -0,0 +1,64 @@
+# Two tabs, one garden
+
+Status: built on `fix/two-tabs`. CLAUDE.md §8, *Two tabs, one database (predicted): two event streams
+into one store; derived state drifts. Use a `BroadcastChannel` lock.* Review:
+[`fix-two-tabs.md`](../reviews/fix-two-tabs.md).
+
+## 1. Why and what, in the player's terms
+
+A player may have the garden open twice: two browser tabs, or the installed app and a tab. Whatever
+they do in one is now seen in the other within a moment, without a reload: care given, a petal opened,
+a rose brought back from a file, a town chosen.
+
+**Measured first (2026-11-07).** Two e2e tests, written before the fix, failed: a tab already open did
+not see care given in the other, nor a town chosen there. The prediction was half right:
+
+- **No stored state drifts.** There is no `derived` store yet; the log is append-only and every write
+ is its own IndexedDB transaction (auto-increment ids), so two writers cannot overwrite each other.
+ The identity's first write already wins in a transaction (rose.md). **No lock is needed.**
+- **The views drift.** Each tab read the log once, at start. The harm: she is watered in one tab, the
+ other still shows her thirsty, the player waters again, and she is too full — a mistake the game
+ made, blamed on her care.
+
+## 2. Technical architecture
+
+```mermaid
+flowchart LR
+ a["tab A
packages/storage: appendCare"] -->|"IndexedDB write, then post 'log'"| bc(("BroadcastChannel
rosea-changes"))
+ bc -->|"'log' | 'place'"| b["tab B
packages/storage: onChange"]
+ b --> app["apps/rosea wiring"] --> ui["packages/ui
Rose / Shell reload from storage"]
+```
+
+| # | Decision | Why |
+|:--|:--|:--|
+| W1 | **`packages/storage` announces its own writes** on a `BroadcastChannel` named after the database, *after* the write commits: `'log'` (care, a petal, a rose brought back) or `'place'` (the town). | One module owns every write, so no write path can forget to announce. After the commit, so the other tab reads what was written. |
+| W2 | **The message is only what changed**, never the data. The other tab reads storage again. | Storage stays the truth; a message can be lost or arrive twice and nothing breaks. |
+| W3 | A tab does not hear itself (a `BroadcastChannel` never delivers to the object that posted). | No double reload. |
+| W4 | **No lock.** | §1: nothing a lock would protect exists yet. When a `derived` store arrives, its feature doc decides again. |
+| W5 | Where `BroadcastChannel` does not exist, nothing is announced and each tab is as before. | Safari has it since 15.4; an older browser loses only the live update, never data. |
+| W6 | Nothing on screen says another tab acted. The garden simply is as it is. | Calm; no "updated elsewhere" notices. |
+
+## 3. Risk analysis
+
+| Risk | Answer |
+|:--|:--|
+| **Blame for the game's mistake** (watered twice, too full). | The fix itself. |
+| **Privacy**: a message leaves the tab. | A `BroadcastChannel` reaches only this origin's own tabs and workers in this browser profile; it carries one word, never data. Nothing leaves the device. |
+| A message from another origin or a malformed one. | The channel is same-origin by definition; anything but `'log'` or `'place'` is ignored. |
+| Reachability, offline | Not affected; works offline. |
+
+## 4. Gap analysis
+
+Closes CLAUDE.md §8's two-tabs trap (measured, answered) and the review checklist's *two tabs open*
+for the log and the town. Not covered: a tab that is mid-pour when the other tab's care arrives keeps
+pouring against the new water level (that is the correct level).
+
+## 5. Verification matrix
+
+| Case | Kind | Where |
+|:--|:--|:--|
+| Each write announces after it commits: care, petal, rose brought back → `'log'`; town → `'place'` | unit | `storage/test/changes.test.ts` |
+| A failed write announces nothing; a tab does not hear itself; a malformed message is ignored; unsubscribe stops it; `close()` closes the channel | unit | same |
+| Without `BroadcastChannel`, storage still works | unit | same |
+| The rose reloads her log on `'log'`; the shell reloads the town on `'place'` | unit | `ui/test/two-tabs.test.ts` |
+| Built app, two tabs: care in A seen in B without reload; a town chosen in A shown in B | e2e | `e2e/shell.spec.ts` (failed before the fix: the measurement) |
diff --git a/.agents/lessons/README.md b/.agents/lessons/README.md
index e6a188f..2ab1769 100644
--- a/.agents/lessons/README.md
+++ b/.agents/lessons/README.md
@@ -11,7 +11,7 @@ and **how to apply it**.
| `design.md` | none yet | Wording, silence, empty states. |
| [`art.md`](art.md) | 2 | The image pipeline. |
| [`code.md`](code.md) | 3 | TypeScript, Svelte, async ordering, Rust. |
-| [`technical.md`](technical.md) | 5 | The browser and the build as platforms. |
+| [`technical.md`](technical.md) | 6 | The browser and the build as platforms. |
| [`testing.md`](testing.md) | 10 | What makes a test worth having, and how a passing test lies. |
| `privacy.md` | none yet | What could leave the device or make a person findable. (The geocell finding is in the review, not here: it was caught before it cost anything.) |
| [`process.md`](process.md) | 4 | Workflow, commits, credentials, honesty about what shipped. |
diff --git a/.agents/lessons/technical.md b/.agents/lessons/technical.md
index 492feb8..8f2173f 100644
--- a/.agents/lessons/technical.md
+++ b/.agents/lessons/technical.md
@@ -70,3 +70,16 @@ listening. This machine runs many projects.
**How to apply it.** Before starting a preview, check that the port is free
(`netstat -ano | grep :`). After it starts, check the page title before you trust
anything the page says.
+
+## A predicted trap can name the right place and the wrong harm
+
+**What happened.** CLAUDE.md §8 predicted that two tabs would make stored derived state drift and
+prescribed a lock. On 2026-11-07 two e2e tests, written before any fix, showed the real harm was
+elsewhere: there was no derived store and the append-only log could not conflict, but each tab's
+view went stale, so a player could water the rose twice. A lock would have fixed nothing.
+
+**Why it bit.** A prediction is written before the code exists, so its remedy fits the design
+that was imagined, not the one that was built.
+
+**How to apply it.** Before acting on a predicted trap, write the test that would show it, run it
+against the built app, and fix what fails. Then rewrite the trap's row with what was measured.
diff --git a/.agents/reviews/fix-two-tabs.md b/.agents/reviews/fix-two-tabs.md
new file mode 100644
index 0000000..218a62e
--- /dev/null
+++ b/.agents/reviews/fix-two-tabs.md
@@ -0,0 +1,53 @@
+# Review — `fix/two-tabs`
+
+Adversarial self-review (CLAUDE.md §5.3). Analysis: [`features/two-tabs.md`](../features/two-tabs.md).
+Reviewed 2026-11-07 on Node 22.11.0, Windows 10. There is no PR: the only remote is Gitea.
+
+## The measurement
+
+CLAUDE.md §8 predicted *derived state drifts; use a BroadcastChannel lock*. Two e2e tests were
+written first and run against the built app: both **failed** (a tab already open saw neither care
+nor a town chosen in another tab). Reading the code explained why, and showed what the
+prediction got wrong: there is no `derived` store and the log is append-only, so nothing stored
+can drift and no lock is needed. What drifted was each tab's view, which can make the player water
+her twice. Both tests pass after the fix.
+
+## Gates
+
+Counts are on the merge; HANDOVER repeats them. New: storage +7, ui +3, e2e +2 (the measurement).
+
+**The app changed** (CLAUDE.md §5.4), invisibly in one tab: another open tab now follows it.
+Rebuilt by the e2e and offline runs; **not deployed** (G0.13).
+
+## Bug drills
+
+| Put back | Result |
+|:--|:--|
+| Care is announced before it is written | CAUGHT |
+| A petal is never announced | CAUGHT |
+| A town is never announced | CAUGHT |
+| Any message counts as a change | CAUGHT |
+| The rose replaces her view with a stale read | CAUGHT |
+| The rose does not listen | CAUGHT |
+| The garden ignores a town from another tab | CAUGHT |
+
+## Findings
+
+| # | Area | Finding | Resolution |
+|:--|:--|:--|:--|
+| 1 | Correctness | A tab's own care can still be on its way to IndexedDB when another tab's news makes it read; a plain replace would drop that care from view, and nothing would bring it back. | The read is added to what the tab shows, never replaces it (the log only grows); drilled. |
+| 2 | Correctness | Two reads overlapping, finishing out of order. | Same answer: each only adds, so order does not matter. |
+| 3 | Correctness | Announcing before the commit would make the other tab read too early. | Announced after `add` / after the transaction resolves; drilled. |
+| 4 | Correctness | A tab mid-pour when the other tab's care arrives: the can now measures against the new level. | Accepted: that is the true level. |
+| 5 | Design | A town arriving while this tab is searching for one: the search closes and the new town shows. | Accepted: the player's choice in the other tab is the newer one. A tab in the middle of *Change town* keeps its open search (only the shown town updates). |
+| 6 | Privacy | A `BroadcastChannel` message. | Same origin, same browser profile only; one word (`log`, `place`), no data. Nothing leaves the device. |
+| 7 | Compatibility | Browsers without `BroadcastChannel` (Safari before 15.4). | Each tab keeps its own view, as before; no data is affected; tested with it removed. |
+| 8 | Process | The measurement commit would have been red on its own. | The branch was regrouped before pushing so every commit is green: the tests land with the fix. |
+| 9 | Process | On 2026-11-07 the root `node_modules` was missing (cause unknown; the code and history were intact). | Restored with `pnpm install --frozen-lockfile`, which also reinstalled the hooks. |
+| — | Soul, reachability, offline | Looked; the fix removes a way the game could blame her care for its own mistake. Nothing new is shown or sent; works offline. | — |
+
+## What was not verified
+
+- Safari and Firefox (BroadcastChannel across an installed app and a tab); a phone.
+- The KeepSafe path across tabs end to end (bringing her back in one tab, seen in the other):
+ covered by the storage test that a brought-back rose announces `log`, not by an e2e.
diff --git a/CLAUDE.md b/CLAUDE.md
index 57854ca..27c8dc4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -509,7 +509,7 @@ No timestamp finer than a day, no precise location, no free text, no link to the
| **Medical claims in a store listing** | One word like *heal* in marketing copy can pull the product toward medical-device rules. `lint:copy` also runs on store text kept in the repo. |
| **IndexedDB is evictable** *(predicted; answered by `keep-her-safe.md`)* | WebKit can discard origin storage after seven days without interaction — exactly the shape of a player who drifted away and comes back. Call `navigator.storage.persist()` where it exists, prompt iOS players to install, and make export-my-rose a first-class feature. A player returning to find their rose gone is the cruellest bug this product could have. |
| **The stale service worker** *(answered by `calm-refresh.md`)* | A precached shell keeps serving old JS to a player who has "updated". Detect a waiting worker and offer an explicit, calm *refresh* control. |
-| **Two tabs, one database** *(predicted)* | Two event streams into one store; derived state drifts. Use a `BroadcastChannel` lock. |
+| **Two tabs, one database** *(measured 2026-11-07; answered by `two-tabs.md`)* | Predicted: derived state drifts, use a lock. Measured: nothing stored drifts (the log is append-only, there is no `derived` store yet), so no lock — but each tab's **view** went stale, and a player could water her twice. `packages/storage` announces each committed write on a `BroadcastChannel`; the other tabs read again, keeping what they already show. When a `derived` store arrives, decide the lock again. |
| **GitHub Pages serves under a sub-path** *(predicted)* | A project site lives at `//`, not `/`. Vite `base`, the web manifest `start_url` and `scope`, and the service worker scope must all agree, or the installed app opens a 404 or never updates. The offline suite runs against the same base path. |
| **GitHub Pages cannot set response headers** *(predicted)* | No custom CSP or cache headers. The content-security policy goes in a `` tag; caching is controlled by the service worker and hashed filenames. |
| **Pages hosts files, not services** | `services/lucerna` cannot live on Pages. It runs on Mark's own server (Phase 4), and the app must work fully without it. |
diff --git a/HANDOVER.md b/HANDOVER.md
index 6b42c24..6e302c8 100644
--- a/HANDOVER.md
+++ b/HANDOVER.md
@@ -12,8 +12,8 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
Gitea hashes match. Analysis: [`.agents/features/phase0-workspace.md`](.agents/features/phase0-workspace.md).
Review, with counts and the mutation results:
[`.agents/reviews/feature-phase0-workspace.md`](.agents/reviews/feature-phase0-workspace.md).
-- **Gates:** all pass on this machine. Unit tests: 458 (cpu-guard 13, identity 5, schema 19,
- content 80, storage 58, art-prep 56, engine 168, ui 59). E2E: 19. Offline: 1. `lint:copy`: 21 files, 0 problems.
+- **Gates:** all pass on this machine. Unit tests: 468 (cpu-guard 13, identity 5, schema 19,
+ content 80, storage 65, art-prep 56, engine 168, ui 62). E2E: 21. Offline: 1. `lint:copy`: 21 files, 0 problems.
`validate:library`: 13 of 13 fixtures rejected; 78 candidates pass.
- **Built, not deployed:** there is no host yet.
- **Roadmap and gameplay docs:** `docs/ROADMAP.md` and `docs/GAMEPLAY.md` are on
@@ -93,6 +93,11 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
says *Gently. I have thorns.* and rests four seconds. A tremor's taps count as one. Nothing is
recorded. Tuning in `TOUCH` (`packages/engine/src/touch/touch.ts`). Review:
[`.agents/reviews/feature-thorns.md`](.agents/reviews/feature-thorns.md).
+- **Two tabs (2026-11-07):** merged to `main`. Measured first: an open tab did not see care or a
+ town from another tab, so a player could water her twice. Storage now announces each committed
+ write on a `BroadcastChannel`; the other tabs read again. No lock: nothing stored can drift.
+ On this date the root `node_modules` was found missing; `pnpm install --frozen-lockfile`
+ restored it. Review: [`.agents/reviews/fix-two-tabs.md`](.agents/reviews/fix-two-tabs.md).
- **Phase 1 is built in code.** What remains of it is the author's: verified sentences (the petal
appears with them), hosting (G0.13), and the gate itself — two weeks of daily play on a phone.
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/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([]);
+ });
+});
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 @@