Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): scope the replay outbox per project (PRD-8314) (#3897)
Andrew Mikofalvyb2f057c4f627
diff --git a/.changeset/project-scoped-replay-outbox.md b/.changeset/project-scoped-replay-outbox.mdnew file mode 100644index 000000000..4916f5ba3--- /dev/null+++ b/.changeset/project-scoped-replay-outbox.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++An unsynced edit can no longer cross between two open projects. When a window reconnects to a server that has restarted, it parks any edit that had not yet reached the server in browser storage and replays it once the connection is healthy again. That parking spot was named after the branch and the document path, but not after the project, and every project window in the desktop app is served from a single origin. So two projects that are worktrees of the same repository, open on the same branch, addressed one parking spot for a document at the same path. Whichever window replayed first consumed the record, which meant a project could receive text that was typed in a different project, while the window that lost the race stood down and dropped its own edit. Because the payload is document content rather than a claim about state, this crossed edits silently instead of raising an error. The parking spot is now named per project as well, so a window only ever contends with other windows of the same project.diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsxindex 1554e20c2..35bbc8937 100644--- a/packages/app/src/editor/DocumentContext.tsx+++ b/packages/app/src/editor/DocumentContext.tsx@@ -468,10 +468,11 @@ let pool: ProviderPool | null = null;export function getPool(collabUrl: string): ProviderPool {if (!pool) {- // Scope the pool's localStorage keys to THIS project — `scopedStorageKey`- // carries the why. `resolveSyncWorkspace()` is the right resolver here+ // Scope the pool's localStorage keys AND the replay-outbox's IndexedDB+ // database name to THIS project — see `lib/storage-scope.ts` for the+ // shared-origin why. `resolveSyncWorkspace()` is the right resolver here// because it answers synchronously on Electron, the host where the- // collision exists, so the very first key this pool touches is scoped.+ // collision exists, so the very first name this pool touches is scoped.pool = new ProviderPool(MAX_POOL, collabUrl, {storageNamespace: resolveSyncWorkspace()?.contentDir ?? null,});diff --git a/packages/app/src/editor/provider-pool-cross-tab-replay.test.ts b/packages/app/src/editor/provider-pool-cross-tab-replay.test.tsindex 577146e17..03e10f165 100644--- a/packages/app/src/editor/provider-pool-cross-tab-replay.test.ts+++ b/packages/app/src/editor/provider-pool-cross-tab-replay.test.ts@@ -1,11 +1,11 @@/*** Cross-tab exactly-once for the durable replay outbox.*- * The outbox record is keyed `(branch, docName)` with no tab component, so- * every same-origin tab (a browser preview and the desktop shell both sit on- * `127.0.0.1:PORT`) sees ONE record. That record is therefore the cross-tab- * claim token: whichever tab consumes it owns the replay and the others must- * stand down.+ * The outbox record is keyed `(namespace, branch, docName)` with no tab+ * component, so every tab of one project (a browser preview and the desktop+ * shell both sit on `127.0.0.1:PORT`) sees ONE record. That record is+ * therefore the cross-tab claim token: whichever tab consumes it owns the+ * replay and the others must stand down.** They must stand down because `replayBufferedContent` is not re-entrant. It* decides which CRDT surface holds the un-delivered edit by asking which@@ -80,7 +80,10 @@ describe('ProviderPool cross-tab replay claim', () => {// durable mirror has committed, exactly as `handleServerInstanceMismatch`// leaves things.expect(- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, { delta, fullState }),+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ { delta, fullState },+ ),).toBe(true);const tabA = newPool();const entryA = tabA.open(docName);@@ -102,7 +105,13 @@ describe('ProviderPool cross-tab replay claim', () => {expect(await waitFor(() => entryB.provider.document.getText('source').toString() === marker),).toBe(true);- expect(await readReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName)).toBeNull();+ expect(+ await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: null,+ }),+ ).toBeNull();// The recovered content reaches tab A the ordinary way (server → peers).entryA.provider.document.getText('source').insert(0, marker);@@ -126,7 +135,10 @@ describe('ProviderPool cross-tab replay claim', () => {const docName = uniqueDocName();const marker = `race-${randomUUID()}`;const { delta, fullState } = buildSourceOnlyState(marker);- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, { delta, fullState });+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ { delta, fullState },+ );// Neither tab has a RAM buffer: both are post-crash reopens racing the one// durable record.@@ -160,7 +172,13 @@ describe('ProviderPool cross-tab replay claim', () => {// would show up as the marker landing on both.expect([textA, textB].filter((t) => t === marker)).toHaveLength(1);expect([textA, textB].filter((t) => t === '')).toHaveLength(1);- expect(await readReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName)).toBeNull();+ expect(+ await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: null,+ }),+ ).toBeNull();});it('a RAM-only buffer (no durable mirror) still replays', async () => {diff --git a/packages/app/src/editor/provider-pool-durable-replay.test.ts b/packages/app/src/editor/provider-pool-durable-replay.test.tsindex 140802c3a..d46fc9252 100644--- a/packages/app/src/editor/provider-pool-durable-replay.test.ts+++ b/packages/app/src/editor/provider-pool-durable-replay.test.ts@@ -16,6 +16,7 @@ import { randomUUID } from 'node:crypto';import { setTimeout as wait } from 'node:timers/promises';import { afterEach, describe, expect, it, vi } from 'vitest';import * as Y from 'yjs';+import { projectDigest, scopedStorageKey } from '../lib/storage-scope';import { UNKNOWN_BRANCH_SENTINEL } from './client-persistence';import { ProviderPool } from './provider-pool';import { readReplayOutboxEntry, writeReplayOutboxEntry } from './replay-outbox';@@ -74,7 +75,10 @@ describe('ProviderPool durable replay outbox', () => {const docName = uniqueDocName();const marker = `durable-recovered-${randomUUID()}`;const { delta, fullState } = buildSourceOnlyState(marker);- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, { delta, fullState });+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ { delta, fullState },+ );pool = new ProviderPool(3, DUMMY_WS);const entry = pool.open(docName);@@ -87,14 +91,23 @@ describe('ProviderPool durable replay outbox', () => {);expect(recovered).toBe(true);// Consume-first: the durable outbox is gone after recovery.- expect(await readReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName)).toBeNull();+ expect(+ await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: null,+ }),+ ).toBeNull();});it('does not re-apply after a completed recovery (exactly-once across reopen)', async () => {const docName = uniqueDocName();const marker = `once-only-${randomUUID()}`;const { delta, fullState } = buildSourceOnlyState(marker);- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, { delta, fullState });+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ { delta, fullState },+ );pool = new ProviderPool(3, DUMMY_WS);const entry = pool.open(docName);@@ -113,14 +126,23 @@ describe('ProviderPool durable replay outbox', () => {entry2.provider.emit('synced', { state: true });await wait(80);expect(entry2.provider.document.getText('source').toString()).toBe('');- expect(await readReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName)).toBeNull();+ expect(+ await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: null,+ }),+ ).toBeNull();});it('a second `synced` never re-enters the replay', async () => {const docName = uniqueDocName();const marker = `single-fire-${randomUUID()}`;const { delta, fullState } = buildSourceOnlyState(marker);- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, { delta, fullState });+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ { delta, fullState },+ );pool = new ProviderPool(3, DUMMY_WS);const entry = pool.open(docName);@@ -155,10 +177,13 @@ describe('ProviderPool durable replay outbox', () => {// attempted (consume-first) so it can never re-fire.const real = buildSourceOnlyState('some real content that will be truncated');const truncated = real.fullState.slice(0, 4);- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, {- delta: truncated,- fullState: truncated,- });+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ {+ delta: truncated,+ fullState: truncated,+ },+ );pool = new ProviderPool(3, DUMMY_WS);const entry = pool.open(docName);@@ -169,7 +194,12 @@ describe('ProviderPool durable replay outbox', () => {// The outbox is consumed regardless of the apply outcome (consume-first).let consumed = false;for (let i = 0; i < 60 && !consumed; i += 1) {- consumed = (await readReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName)) === null;+ consumed =+ (await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: null,+ })) === null;if (!consumed) await wait(10);}expect(consumed).toBe(true);@@ -177,3 +207,206 @@ describe('ProviderPool durable replay outbox', () => {expect(entry.provider.document.getText('source').toString()).toBe('');});});++/**+ * Wiring tests: the pool must hand its project identity to every outbox call.+ *+ * The outbox module's own tests prove a namespaced database name isolates+ * projects. These prove the pool actually SUPPLIES that namespace — a call+ * site that passed `null` (or another project's value) would leave those+ * module tests green while restoring the collision.+ */+describe('ProviderPool durable replay outbox project scoping', () => {+ const PROJECT_A = '/Users/dev/repo/.worktrees/a';+ const PROJECT_B = '/Users/dev/repo/.worktrees/b';++ it("recovers an edit written under the pool's own project namespace", async () => {+ const docName = uniqueDocName();+ const marker = `scoped-recovered-${randomUUID()}`;+ const { delta, fullState } = buildSourceOnlyState(marker);+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: PROJECT_A },+ { delta, fullState },+ );++ pool = new ProviderPool(3, DUMMY_WS, { storageNamespace: PROJECT_A });+ const entry = pool.open(docName);+ if (!entry) throw new Error('expected entry');+ entry.observerCleanup = () => {};+ entry.provider.emit('synced', { state: true });++ const recovered = await waitFor(() =>+ entry.provider.document.getText('source').toString().includes(marker),+ );+ expect(recovered).toBe(true);+ });++ it("never touches a sibling project's buffered edit", async () => {+ const docName = uniqueDocName();+ const marker = `sibling-only-${randomUUID()}`;+ const { delta, fullState } = buildSourceOnlyState(marker);+ // Project A has an unsynced edit parked in its outbox. A window of+ // project B opens the same repo-relative path on the same branch.+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: PROJECT_A },+ { delta, fullState },+ );++ pool = new ProviderPool(3, DUMMY_WS, { storageNamespace: PROJECT_B });+ const entry = pool.open(docName);+ if (!entry) throw new Error('expected entry');+ entry.observerCleanup = () => {};+ vi.mocked(readReplayOutboxEntry).mockClear();+ entry.provider.emit('synced', { state: true });++ // Wait on a POSITIVE signal that B's replay actually ran — its first act+ // is the outbox read. Waiting only for "no leak yet" would also pass for a+ // replay that is merely slow, which is the bug wearing a stopwatch.+ const replayRan = await waitFor(() =>+ vi+ .mocked(readReplayOutboxEntry)+ .mock.calls.some(([key]) => key.docName === docName && key.namespace === PROJECT_B),+ );+ expect(replayRan).toBe(true);++ // Having run, B found nothing of its own: it neither applied A's content...+ expect(entry.provider.document.getText('source').toString()).not.toContain(marker);+ // ...nor consumed A's record, which A still needs on its next open.+ expect(+ await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: PROJECT_A,+ }),+ ).not.toBeNull();+ });++ it('writes the outbox under the pool project namespace on a mismatch recycle', async () => {+ // Covers the WRITE site, the only one that plants content. The tests above+ // cover the read and the RECOVERY-path consume; the discard-path consume+ // is a distinct site covered by its own test below.+ pool = new ProviderPool(3, DUMMY_WS, { storageNamespace: PROJECT_A });+ pool.setExpectedServerInstanceId('durable-scoped-epoch');+ const docName = uniqueDocName();+ const entry = pool.open(docName);+ if (!entry) throw new Error('expected entry');+ entry.observerCleanup = () => {};+ pool.setActive(docName);+ // `synced` is what captures the baseline state vector. The edit has to+ // land AFTER it, or the delta is empty and the recycle skips the capture+ // as unreplayable ("no-disk-ack-or-server-sync-vector").+ entry.provider.emit('synced', { state: true });+ entry.provider.document.getText('source').insert(0, `parked-${randomUUID()}`);++ entry.provider.emit('authenticationFailed', { reason: 'server-instance-mismatch' });+ await pool.awaitMismatchSettled();++ // The record lands under THIS project's name...+ expect(+ await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: PROJECT_A,+ }),+ ).not.toBeNull();+ // ...and NOT under the app-wide name that a `null` at the call site would+ // produce. This assertion is what makes the write site's namespace+ // load-bearing rather than merely present.+ expect(+ await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: null,+ }),+ ).toBeNull();+ });++ it('discards the outbox under the pool project namespace on close()', async () => {+ // The fourth call site: `discardBufferedUpdate`'s consume. A `null` here+ // targets the unscoped database, finds nothing, and leaves the REAL record+ // in place — so the next open resurrects an edit the user discarded. That+ // is silent content resurrection, the same class this scoping closes.+ const docName = uniqueDocName();+ const marker = `discard-scoped-${randomUUID()}`;+ const { delta, fullState } = buildSourceOnlyState(marker);+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: PROJECT_A },+ { delta, fullState },+ );++ pool = new ProviderPool(3, DUMMY_WS, { storageNamespace: PROJECT_A });+ const entry = pool.open(docName);+ if (!entry) throw new Error('expected entry');+ entry.observerCleanup = () => {};+ pool.__test_seedBufferedUpdate(docName, delta, {+ fullState,+ durable: true,+ branch: UNKNOWN_BRANCH_SENTINEL,+ });++ pool.close(docName);++ await vi.waitFor(async () => {+ expect(+ await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: PROJECT_A,+ }),+ ).toBeNull();+ });+ });++ it('emits recovery telemetry carrying the project as a digest, not a path', async () => {+ // Two properties in one: the field is PRESENT (so a cross-project report+ // has something to correlate on), and it is the DIGEST. Dropping the+ // digest call still type-checks, and these events reach `~/.ok/logs` and+ // bug-report bundles, so a raw namespace here would ship home-directory+ // paths. The value must also equal the segment `scopedStorageKey` embeds,+ // or correlating an event to its database silently matches nothing.+ pool = new ProviderPool(3, DUMMY_WS, { storageNamespace: PROJECT_A });+ pool.setExpectedServerInstanceId('telemetry-scoped-epoch');+ const docName = uniqueDocName();+ const entry = pool.open(docName);+ if (!entry) throw new Error('expected entry');+ entry.observerCleanup = () => {};+ pool.setActive(docName);++ // `spyOn` + `finally` rather than a raw reassign: this stub window+ // contains an `await`, so a rejection would otherwise leave `console.warn`+ // pointed at a dead spy for the rest of the worker. Accumulate into a+ // local rather than reading `mock.calls` afterwards — `mockRestore` clears+ // the call history along with the implementation.+ const warned: string[] = [];+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation((line: unknown) => {+ if (typeof line === 'string') warned.push(line);+ });+ try {+ // No `synced`, so no baseline vector: the recycle takes the+ // skipped-no-baseline arm, which emits through `recoveryTelemetryBase`.+ entry.provider.emit('authenticationFailed', { reason: 'server-instance-mismatch' });+ await pool.awaitMismatchSettled();+ } finally {+ warnSpy.mockRestore();+ }++ const events = warned+ .filter((line) => line.includes('ok-buffer-replay-skipped'))+ .map((line) => JSON.parse(line) as Record<string, string>);+ expect(events.length).toBeGreaterThan(0);++ const event = events[0] as Record<string, string>;+ expect(event.project).toBe(projectDigest(PROJECT_A));+ // Belt and braces on the privacy half: a digest carries no path separator.+ expect(event.project).not.toContain('/');+ expect(event.project).not.toBe(PROJECT_A);+ // The correlation half, which sharing `projectDigest` alone does NOT buy:+ // the callers agree by construction, but the COMPOSITION that turns a+ // digest into a name segment lives in `scopedStorageKey`. Change it (a+ // salt, a truncation, a version prefix) and the assertions above still+ // pass while correlating an event to its database matches nothing.+ expect(scopedStorageKey('ok-replay-outbox', PROJECT_A)).toBe(+ `ok-replay-outbox:${event.project}`,+ );+ });+});diff --git a/packages/app/src/editor/provider-pool-replay-discard.test.ts b/packages/app/src/editor/provider-pool-replay-discard.test.tsindex 41ca2a11f..75558fe23 100644--- a/packages/app/src/editor/provider-pool-replay-discard.test.ts+++ b/packages/app/src/editor/provider-pool-replay-discard.test.ts@@ -55,7 +55,10 @@ describe('ProviderPool replay-buffer discard reaches the durable mirror', () =>const docName = uniqueDocName();const marker = `closed-${randomUUID()}`;const { delta, fullState } = buildSourceOnlyState(marker);- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, { delta, fullState });+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ { delta, fullState },+ );pool = new ProviderPool(3, DUMMY_WS);const entry = pool.open(docName);@@ -72,7 +75,13 @@ describe('ProviderPool replay-buffer discard reaches the durable mirror', () =>expect(pool.__test_hasBufferedUpdate(docName)).toBe(false);// The durable half has to go too, or the next open resurrects the edit.await vi.waitFor(async () => {- expect(await readReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName)).toBeNull();+ expect(+ await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: null,+ }),+ ).toBeNull();});// End-to-end: reopening replays nothing.@@ -88,7 +97,10 @@ describe('ProviderPool replay-buffer discard reaches the durable mirror', () =>const docName = uniqueDocName();const authoringBranch = `feature-${randomUUID()}`;const { delta, fullState } = buildSourceOnlyState('branch-a edit');- await writeReplayOutboxEntry(authoringBranch, docName, { delta, fullState });+ await writeReplayOutboxEntry(+ { branch: authoringBranch, docName, namespace: null },+ { delta, fullState },+ );pool = new ProviderPool(3, DUMMY_WS);// The branch-switch flow runs AFTER the observed branch has already moved,@@ -104,7 +116,9 @@ describe('ProviderPool replay-buffer discard reaches the durable mirror', () =>expect(pool.__test_bufferedUpdatesSize()).toBe(0);await vi.waitFor(async () => {- expect(await readReplayOutboxEntry(authoringBranch, docName)).toBeNull();+ expect(+ await readReplayOutboxEntry({ branch: authoringBranch, docName, namespace: null }),+ ).toBeNull();});});@@ -136,7 +150,10 @@ describe('ProviderPool replay-buffer discard reaches the durable mirror', () =>it('reports the in-process loss when the entry is replaced mid-consume', async () => {const docName = uniqueDocName();const { delta, fullState } = buildSourceOnlyState(`abandoned-${randomUUID()}`);- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, { delta, fullState });+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ { delta, fullState },+ );pool = new ProviderPool(3, DUMMY_WS);const entry = pool.open(docName);diff --git a/packages/app/src/editor/provider-pool.ts b/packages/app/src/editor/provider-pool.tsindex bfb85f184..2b41a93b8 100644--- a/packages/app/src/editor/provider-pool.ts+++ b/packages/app/src/editor/provider-pool.ts@@ -2,7 +2,6 @@ import { HocuspocusProvider } from '@hocuspocus/provider';import {addsBlankLines,composeWithDerivedBody,- fnv1aDigest,LINEAGE_EPOCH_KEY,MarkdownManager,normalizeBridge,@@ -17,6 +16,7 @@ import { buildAuthToken } from '../lib/auth-token';import { readNumericOverride } from '../lib/perf/env-override';import { mark } from '../lib/perf/mark';import { emitColdMountChild } from '../lib/perf/otel-spans';+import { projectDigest, scopedStorageKey } from '../lib/storage-scope';import {type ClientPersistenceProvider,captureStateVector,@@ -379,46 +379,6 @@ class StoredEpochPeekTimeoutError extends Error {*/const LAST_OBSERVED_BRANCH_KEY = 'ok-last-observed-branch';-/**- * Scope a client-persistence storage key to a single project.- *- * A packaged desktop window loads the renderer through `loadFile`, so every- * project window shares the one `file://` origin (`webPreferences.partition`- * is set only for slides windows). One key per origin therefore means one key- * for EVERY open project, and whichever window wrote last decides what the- * next cold boot reads back. For the branch claim that is load-bearing: a- * window seeds `lastObservedBranch` from the shared key, claims a sibling- * project's branch, and the server correctly rejects it — the doc wedges and- * the red branch-mismatch banner goes up.- *- * `namespace` is the project's content dir, digested so no absolute home path- * lands in localStorage. Nothing prunes: the pre-scoping unscoped keys are- * left behind once, and one scoped pair accrues per project ever opened.- * Both are bounded and inert, which is why this ships without a migration —- * adopting the old value would import the sibling-project claim it removes. A null namespace returns the bare key, which is- * correct for web hosts: those are served per project on- * `http://127.0.0.1:<port>`, so the origin already isolates them.- *- * **This origin is shared by more than these two keys.** The same cause has- * now been mitigated three times independently — `localTabSessionKeyForMode`- * in `editor-tabs.ts` opts note windows out of tab persistence, and- * `dock-session-persistence.ts` routes through the main process — so a new- * storage surface should scope itself here rather than rediscover the bug.- * Scoping the ORIGIN instead (a per-project `webPreferences.partition`) was- * considered and rejected: it silently bypasses the `defaultSession`-only- * `webRequest` hooks and spellchecker config, forks genuinely app-global- * prefs such as theme and language, and orphans every existing `ok-ydoc:*`- * store.- */-function scopedStorageKey(baseKey: string, namespace: string | null): string {- // `null` only — an empty string is a broken Electron config, not a web- // host, and it must not fall through to the shared app-wide key. It- // digests to a fixed non-bare suffix, so such windows share with each- // other rather than with correctly-configured ones.- if (namespace === null) return baseKey;- return `${baseKey}:${fnv1aDigest(namespace)}`;-}-/*** localStorage key for the persisted per-doc lineage-epoch records.* Scoped per project by `scopedStorageKey`, for the same reason the branch@@ -715,6 +675,13 @@ export class ProviderPool {private readonly lastObservedBranchKey: string;private readonly docLineageEpochsKey: string;+ /**+ * Project identity handed to every replay-outbox call. Held raw rather than+ * pre-scoped because the outbox composes its own database name around the+ * digest; see `outboxDbName`.+ */+ private readonly storageNamespace: string | null;+constructor(maxSize: number,wsUrl: string,@@ -750,6 +717,7 @@ export class ProviderPool {typeof globalThis.localStorage !== 'undefined' ? globalThis.localStorage : null;}const storageNamespace = options?.storageNamespace ?? null;+ this.storageNamespace = storageNamespace;this.lastObservedBranchKey = scopedStorageKey(LAST_OBSERVED_BRANCH_KEY, storageNamespace);this.docLineageEpochsKey = scopedStorageKey(DOC_LINEAGE_EPOCHS_KEY, storageNamespace);}@@ -1431,9 +1399,9 @@ export class ProviderPool {private recoveryTelemetryBase(docName: string,staleClaimOverride?: string | undefined,- ): { docName: string; branch: string; serverInstanceId?: string } {+ ): { docName: string; branch: string; serverInstanceId?: string; project?: string } {const branch = this.normalizedObservedBranch();- const base: { docName: string; branch: string; serverInstanceId?: string } = {+ const base: { docName: string; branch: string; serverInstanceId?: string; project?: string } = {docName,branch,};@@ -1442,6 +1410,18 @@ export class ProviderPool {if (stale !== undefined && stale.length > 0) {base.serverInstanceId = stale;}+ // `docName` + `branch` are exactly the key two projects legitimately+ // share, so without this a cross-project report has nothing to correlate+ // on and a project-specific storage fault reads as a global one. Carries+ // the DIGEST, not the path: these events go through `console.warn` into+ // diagnostic bundles, and the raw namespace is an absolute path that can+ // contain the OS username. Routed through `projectDigest` — the same step+ // `scopedStorageKey` embeds — so the value stays comparable to the+ // database name's project segment by construction rather than because two+ // call sites happen to hash alike.+ if (this.storageNamespace !== null) {+ base.project = projectDigest(this.storageNamespace);+ }return base;}@@ -2457,7 +2437,11 @@ export class ProviderPool {tokenBacked = buffered.durable;} else {try {- const durable = await readReplayOutboxEntry(branch, docName);+ const durable = await readReplayOutboxEntry({+ branch,+ docName,+ namespace: this.storageNamespace,+ });if (durable === null) return;source = durable;tokenBacked = true;@@ -2478,11 +2462,13 @@ export class ProviderPool {// At-most-once in the tiny [consumed → server-synced] tail (matching the// RAM buffer, and past the crash window the outbox exists to close).//- // The consume is also the CROSS-TAB claim: same-origin tabs share one- // `(branch, docName)` record, so losing the claim means another tab- // already replayed this edit and this one must stand down. That covers- // both orders — the other tab consuming before we read (we never see a- // record) and after (we see one but cannot claim it).+ // The consume is also the CROSS-TAB claim: tabs of the SAME project+ // share one `(namespace, branch, docName)` record, so losing the claim+ // means another tab of this project already replayed this edit and this+ // one must stand down. A window of a DIFFERENT project never contends+ // for it. That covers both orders — the other tab consuming before we+ // read (we never see a record) and after (we see one but cannot claim+ // it).//// Only attempt it when a durable record actually backs this replay. An// unconditional consume would, on a RAM-only buffer, throw its way into@@ -2492,7 +2478,11 @@ export class ProviderPool {if (tokenBacked) {let claimed: boolean;try {- claimed = await consumeReplayOutboxEntry(tokenBranch, docName);+ claimed = await consumeReplayOutboxEntry({+ branch: tokenBranch,+ docName,+ namespace: this.storageNamespace,+ });} catch (err: unknown) {// Bail rather than apply: the record is still there, so a later// clean open recovers the edit instead of risking a double-apply.@@ -2561,13 +2551,17 @@ export class ProviderPool {// on an UNEXPECTED throw — which, once a carrier has been consumed, is a// silent in-process loss. Emit it (like this file's other fire-and-forget// recovery paths) rather than swallow, while still keeping the rejection- // out of the `synced` emitter. Kept minimal (no telemetry-base helper) so- // the fallback itself can never throw its way back out.+ // out of the `synced` emitter. It carries the full telemetry base: this+ // is the highest-value event on the buffer-replay path for a+ // cross-project incident, so omitting `branch` and `project` here is+ // exactly the wrong place to economize. Safe to call — the base's only+ // fallible step (storage read) already swallows, and the digest is a+ // pure function.provider.off('synced', onSyncedReplay);void runReplay().catch((err: unknown) => {this.emitStructuredClientRecoveryEvent({event: 'ok-buffer-replay-unexpected-error',- docName,+ ...this.recoveryTelemetryBase(docName),errorName: err instanceof Error ? err.name : 'non-error-throw',errorMessage: err instanceof Error ? err.message : String(err),});@@ -2819,10 +2813,10 @@ export class ProviderPool {// for a live token.if (fullStateForBuffer !== null) {outboxWrites.push(- writeReplayOutboxEntry(recoveryBranch, docName, {- delta: unsynced,- fullState: fullStateForBuffer,- })+ writeReplayOutboxEntry(+ { branch: recoveryBranch, docName, namespace: this.storageNamespace },+ { delta: unsynced, fullState: fullStateForBuffer },+ ).then((persisted) => {if (persisted) buffered.durable = true;else {@@ -3406,7 +3400,11 @@ export class ProviderPool {const buffered = this.bufferedUpdates.get(docName);this.bufferedUpdates.delete(docName);if (buffered === undefined || !buffered.durable) return;- void consumeReplayOutboxEntry(buffered.branch, docName).catch((err: unknown) => {+ void consumeReplayOutboxEntry({+ branch: buffered.branch,+ docName,+ namespace: this.storageNamespace,+ }).catch((err: unknown) => {this.emitStructuredClientRecoveryEvent({event: 'ok-buffer-replay-outbox-discard-failed',...this.recoveryTelemetryBase(docName),diff --git a/packages/app/src/editor/qa-001-crash-window.test.ts b/packages/app/src/editor/qa-001-crash-window.test.tsindex 6f2e0ed24..d6217ef20 100644--- a/packages/app/src/editor/qa-001-crash-window.test.ts+++ b/packages/app/src/editor/qa-001-crash-window.test.ts@@ -62,7 +62,10 @@ describe('QA-001 crash-window sweep (occurrence-count oracle, ratified consume-fconst docName = `qa001-${randomUUID()}`;const marker = `crash-before-consume-${randomUUID()}`;const { delta, fullState } = buildSourceOnlyState(marker);- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, { delta, fullState });+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ { delta, fullState },+ );// Reopen (fresh tab, no in-memory buffer): the durable read path fires.pool = new ProviderPool(3, DUMMY_WS);@@ -74,17 +77,26 @@ describe('QA-001 crash-window sweep (occurrence-count oracle, ratified consume-fawait waitFor(() => entry.provider.document.getText('source').toString().includes(marker));const src = entry.provider.document.getText('source').toString();expect(count(src, marker)).toBe(1); // EXACTLY once, not merely present- expect(await readReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName)).toBeNull(); // consumed+ expect(+ await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: null,+ }),+ ).toBeNull(); // consumed});it('WINDOW: consume happens but apply fails (corrupt = the between-consume-and-apply tail) -> content ABSENT (count 0), entry gone, NEVER doubled', async () => {const docName = `qa001-${randomUUID()}`;const real = buildSourceOnlyState('real content that will be truncated');const truncated = real.fullState.slice(0, 4);- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, {- delta: truncated,- fullState: truncated,- });+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ {+ delta: truncated,+ fullState: truncated,+ },+ );pool = new ProviderPool(3, DUMMY_WS);const entry = pool.open(docName);@@ -97,7 +109,12 @@ describe('QA-001 crash-window sweep (occurrence-count oracle, ratified consume-f// returns a truthy Promise and would pass vacuously).let consumed = false;for (let i = 0; i < 60 && !consumed; i += 1) {- consumed = (await readReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName)) === null;+ consumed =+ (await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: null,+ })) === null;if (!consumed) await wait(10);}expect(consumed).toBe(true);@@ -110,7 +127,10 @@ describe('QA-001 crash-window sweep (occurrence-count oracle, ratified consume-fconst docName = `qa001-${randomUUID()}`;const marker = `double-fire-${randomUUID()}`;const { delta, fullState } = buildSourceOnlyState(marker);- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, { delta, fullState });+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ { delta, fullState },+ );pool = new ProviderPool(3, DUMMY_WS);const entry = pool.open(docName);@@ -130,7 +150,10 @@ describe('QA-001 crash-window sweep (occurrence-count oracle, ratified consume-fconst docName = `qa001-${randomUUID()}`;const marker = `reopen-once-${randomUUID()}`;const { delta, fullState } = buildSourceOnlyState(marker);- await writeReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName, { delta, fullState });+ await writeReplayOutboxEntry(+ { branch: UNKNOWN_BRANCH_SENTINEL, docName, namespace: null },+ { delta, fullState },+ );pool = new ProviderPool(3, DUMMY_WS);const e1 = pool.open(docName);@@ -149,6 +172,12 @@ describe('QA-001 crash-window sweep (occurrence-count oracle, ratified consume-fe2.provider.emit('synced', { state: true });await wait(80);expect(count(e2.provider.document.getText('source').toString(), marker)).toBe(0);- expect(await readReplayOutboxEntry(UNKNOWN_BRANCH_SENTINEL, docName)).toBeNull();+ expect(+ await readReplayOutboxEntry({+ branch: UNKNOWN_BRANCH_SENTINEL,+ docName,+ namespace: null,+ }),+ ).toBeNull();});});diff --git a/packages/app/src/editor/replay-outbox.test.ts b/packages/app/src/editor/replay-outbox.test.tsindex bb5bc36fd..91f23817d 100644--- a/packages/app/src/editor/replay-outbox.test.ts+++ b/packages/app/src/editor/replay-outbox.test.ts@@ -43,70 +43,115 @@ afterEach(() => {describe('replay-outbox', () => {it('round-trips a written entry byte-for-byte', async () => {- await writeReplayOutboxEntry('main', 'doc-a', {- delta: bytes(1, 2, 3),- fullState: bytes(9, 8, 7, 6),- });- const read = await readReplayOutboxEntry('main', 'doc-a');+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'doc-a', namespace: null },+ {+ delta: bytes(1, 2, 3),+ fullState: bytes(9, 8, 7, 6),+ },+ );+ const read = await readReplayOutboxEntry({ branch: 'main', docName: 'doc-a', namespace: null });expect(read).not.toBeNull();expect(Array.from(read?.delta ?? [])).toEqual([1, 2, 3]);expect(Array.from(read?.fullState ?? [])).toEqual([9, 8, 7, 6]);});it('returns null and creates no database when no outbox exists', async () => {- const read = await readReplayOutboxEntry('main', 'never-written');+ const read = await readReplayOutboxEntry({+ branch: 'main',+ docName: 'never-written',+ namespace: null,+ });expect(read).toBeNull();// A normal doc open must not litter an empty outbox database.expect(await hasOutboxDb('ok-replay-outbox:main:never-written')).toBe(false);});it('a consumed entry reads back as null', async () => {- await writeReplayOutboxEntry('main', 'doc-b', { delta: bytes(1), fullState: bytes(2) });- await consumeReplayOutboxEntry('main', 'doc-b');- expect(await readReplayOutboxEntry('main', 'doc-b')).toBeNull();+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'doc-b', namespace: null },+ { delta: bytes(1), fullState: bytes(2) },+ );+ await consumeReplayOutboxEntry({ branch: 'main', docName: 'doc-b', namespace: null });+ expect(+ await readReplayOutboxEntry({ branch: 'main', docName: 'doc-b', namespace: null }),+ ).toBeNull();});it('consume reports whether IT removed a live record', async () => {- await writeReplayOutboxEntry('main', 'doc-claim', { delta: bytes(1), fullState: bytes(2) });+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'doc-claim', namespace: null },+ { delta: bytes(1), fullState: bytes(2) },+ );// The claim: first consumer takes the record, every later consumer of the// same record is told it lost.- expect(await consumeReplayOutboxEntry('main', 'doc-claim')).toBe(true);- expect(await consumeReplayOutboxEntry('main', 'doc-claim')).toBe(false);+ expect(+ await consumeReplayOutboxEntry({ branch: 'main', docName: 'doc-claim', namespace: null }),+ ).toBe(true);+ expect(+ await consumeReplayOutboxEntry({ branch: 'main', docName: 'doc-claim', namespace: null }),+ ).toBe(false);// Never written at all reads the same as already-claimed.- expect(await consumeReplayOutboxEntry('main', 'doc-claim-absent')).toBe(false);+ expect(+ await consumeReplayOutboxEntry({+ branch: 'main',+ docName: 'doc-claim-absent',+ namespace: null,+ }),+ ).toBe(false);});it('concurrent consumers of one record: exactly one claims it', async () => {- await writeReplayOutboxEntry('main', 'doc-race', { delta: bytes(7), fullState: bytes(8) });+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'doc-race', namespace: null },+ { delta: bytes(7), fullState: bytes(8) },+ );- // Two same-origin tabs racing the same `(branch, docName)` token. The- // count+delete pair runs inside ONE readwrite transaction, and IndexedDB- // serializes overlapping readwrite transactions across connections, so- // this is an atomic compare-and-claim rather than a check-then-act that- // both callers could win.+ // Two tabs of one project racing the same `(namespace, branch, docName)`+ // token. The count+delete pair runs inside ONE readwrite transaction, and+ // IndexedDB serializes overlapping readwrite transactions across+ // connections, so this is an atomic compare-and-claim rather than a+ // check-then-act that both callers could win.const results = await Promise.all([- consumeReplayOutboxEntry('main', 'doc-race'),- consumeReplayOutboxEntry('main', 'doc-race'),- consumeReplayOutboxEntry('main', 'doc-race'),+ consumeReplayOutboxEntry({ branch: 'main', docName: 'doc-race', namespace: null }),+ consumeReplayOutboxEntry({ branch: 'main', docName: 'doc-race', namespace: null }),+ consumeReplayOutboxEntry({ branch: 'main', docName: 'doc-race', namespace: null }),]);expect(results.filter(Boolean)).toHaveLength(1);- expect(await readReplayOutboxEntry('main', 'doc-race')).toBeNull();+ expect(+ await readReplayOutboxEntry({ branch: 'main', docName: 'doc-race', namespace: null }),+ ).toBeNull();});it('a later write overwrites an existing entry', async () => {- await writeReplayOutboxEntry('main', 'doc-c', { delta: bytes(1), fullState: bytes(1) });- await writeReplayOutboxEntry('main', 'doc-c', { delta: bytes(5, 5), fullState: bytes(6, 6) });- const read = await readReplayOutboxEntry('main', 'doc-c');+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'doc-c', namespace: null },+ { delta: bytes(1), fullState: bytes(1) },+ );+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'doc-c', namespace: null },+ { delta: bytes(5, 5), fullState: bytes(6, 6) },+ );+ const read = await readReplayOutboxEntry({ branch: 'main', docName: 'doc-c', namespace: null });expect(Array.from(read?.delta ?? [])).toEqual([5, 5]);expect(Array.from(read?.fullState ?? [])).toEqual([6, 6]);});it('scopes entries by branch and docName', async () => {- await writeReplayOutboxEntry('main', 'shared', { delta: bytes(1), fullState: bytes(1) });- expect(await readReplayOutboxEntry('feature', 'shared')).toBeNull();- expect(await readReplayOutboxEntry('main', 'other')).toBeNull();- expect(await readReplayOutboxEntry('main', 'shared')).not.toBeNull();+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'shared', namespace: null },+ { delta: bytes(1), fullState: bytes(1) },+ );+ expect(+ await readReplayOutboxEntry({ branch: 'feature', docName: 'shared', namespace: null }),+ ).toBeNull();+ expect(+ await readReplayOutboxEntry({ branch: 'main', docName: 'other', namespace: null }),+ ).toBeNull();+ expect(+ await readReplayOutboxEntry({ branch: 'main', docName: 'shared', namespace: null }),+ ).not.toBeNull();});it('reads null for a foreign/truncated record rather than returning garbage', async () => {@@ -128,11 +173,15 @@ describe('replay-outbox', () => {};req.onerror = () => reject(req.error);});- expect(await readReplayOutboxEntry('main', 'garbage')).toBeNull();+ expect(+ await readReplayOutboxEntry({ branch: 'main', docName: 'garbage', namespace: null }),+ ).toBeNull();});it('consuming an absent outbox is a no-op', async () => {- await expect(consumeReplayOutboxEntry('main', 'absent')).resolves.toBe(false);+ await expect(+ consumeReplayOutboxEntry({ branch: 'main', docName: 'absent', namespace: null }),+ ).resolves.toBe(false);expect(await hasOutboxDb('ok-replay-outbox:main:absent')).toBe(false);});@@ -142,15 +191,20 @@ describe('replay-outbox', () => {// can consume or reclaim. The write must decline and SAY it declined, so// the caller knows its buffer is RAM-only.await withoutDatabasesApi(async () => {- const persisted = await writeReplayOutboxEntry('main', 'no-databases-api', {- delta: bytes(1, 2, 3),- fullState: bytes(4, 5, 6),- });+ const persisted = await writeReplayOutboxEntry(+ { branch: 'main', docName: 'no-databases-api', namespace: null },+ {+ delta: bytes(1, 2, 3),+ fullState: bytes(4, 5, 6),+ },+ );expect(persisted).toBe(false);});expect(await hasOutboxDb('ok-replay-outbox:main:no-databases-api')).toBe(false);- expect(await readReplayOutboxEntry('main', 'no-databases-api')).toBeNull();+ expect(+ await readReplayOutboxEntry({ branch: 'main', docName: 'no-databases-api', namespace: null }),+ ).toBeNull();});it('rejects with a timeout rather than hanging when IndexedDB stalls', async () => {@@ -162,19 +216,28 @@ describe('replay-outbox', () => {vi.useFakeTimers();vi.spyOn(indexedDB, 'databases').mockReturnValue(new Promise(() => {}));- const stalled = consumeReplayOutboxEntry('main', 'doc-stalled');+ const stalled = consumeReplayOutboxEntry({+ branch: 'main',+ docName: 'doc-stalled',+ namespace: null,+ });const assertion = expect(stalled).rejects.toBeInstanceOf(ReplayOutboxTimeoutError);await vi.advanceTimersByTimeAsync(10_000);await assertion;});it('reports a committed write so the caller can trust the durable copy', async () => {- const persisted = await writeReplayOutboxEntry('main', 'doc-persisted', {- delta: bytes(1),- fullState: bytes(2),- });+ const persisted = await writeReplayOutboxEntry(+ { branch: 'main', docName: 'doc-persisted', namespace: null },+ {+ delta: bytes(1),+ fullState: bytes(2),+ },+ );expect(persisted).toBe(true);- expect(await readReplayOutboxEntry('main', 'doc-persisted')).not.toBeNull();+ expect(+ await readReplayOutboxEntry({ branch: 'main', docName: 'doc-persisted', namespace: null }),+ ).not.toBeNull();});it('commits the write transaction explicitly and still stores the entry', async () => {@@ -184,10 +247,13 @@ describe('replay-outbox', () => {// call on the prototype during it is attributable to that path.const commitSpy = vi.spyOn(IDBTransaction.prototype, 'commit');try {- const persisted = await writeReplayOutboxEntry('main', 'doc-explicit-commit', {- delta: bytes(7),- fullState: bytes(8),- });+ const persisted = await writeReplayOutboxEntry(+ { branch: 'main', docName: 'doc-explicit-commit', namespace: null },+ {+ delta: bytes(7),+ fullState: bytes(8),+ },+ );expect(persisted).toBe(true);expect(commitSpy).toHaveBeenCalled();} finally {@@ -195,9 +261,118 @@ describe('replay-outbox', () => {}// Committing early must not cost durability: the entry is readable back.- const entry = await readReplayOutboxEntry('main', 'doc-explicit-commit');+ const entry = await readReplayOutboxEntry({+ branch: 'main',+ docName: 'doc-explicit-commit',+ namespace: null,+ });expect(entry).not.toBeNull();expect(Array.from(entry?.delta ?? [])).toEqual([7]);expect(Array.from(entry?.fullState ?? [])).toEqual([8]);});});++/**+ * The outbox database name must carry a project component.+ *+ * `docName` is repo-root-relative and branch names repeat, so two worktrees of+ * one repository checked out on the same branch address the same doc path.+ * Every packaged project window loads the renderer through `loadFile`, so they+ * also share one `file://` origin — same-origin means same-app, not+ * same-project. Without a project component those two windows share one outbox+ * database, and the payload is buffered document content: a collision crosses+ * edits between projects instead of raising an error.+ */+describe('replay-outbox project scoping', () => {+ const PROJECT_A = '/Users/dev/repo/.worktrees/a';+ const PROJECT_B = '/Users/dev/repo/.worktrees/b';++ it('isolates two projects sharing one branch and docName', async () => {+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'notes/todo.md', namespace: PROJECT_A },+ { delta: bytes(1), fullState: bytes(0xaa) },+ );+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'notes/todo.md', namespace: PROJECT_B },+ { delta: bytes(2), fullState: bytes(0xbb) },+ );++ // Each project reads back its OWN bytes. Unscoped, B's write lands on A's+ // record and both reads return 0xbb.+ const fromA = await readReplayOutboxEntry({+ branch: 'main',+ docName: 'notes/todo.md',+ namespace: PROJECT_A,+ });+ const fromB = await readReplayOutboxEntry({+ branch: 'main',+ docName: 'notes/todo.md',+ namespace: PROJECT_B,+ });+ expect(Array.from(fromA?.fullState ?? [])).toEqual([0xaa]);+ expect(Array.from(fromB?.fullState ?? [])).toEqual([0xbb]);+ });++ it("consuming one project's record leaves the sibling project's intact", async () => {+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'notes/todo.md', namespace: PROJECT_A },+ { delta: bytes(1), fullState: bytes(0xaa) },+ );+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'notes/todo.md', namespace: PROJECT_B },+ { delta: bytes(2), fullState: bytes(0xbb) },+ );++ // The cross-tab exactly-once claim is per PROJECT, not per app. A window+ // in project A replaying its edit must not stand down a window in+ // project B, whose edit is a different document entirely.+ expect(+ await consumeReplayOutboxEntry({+ branch: 'main',+ docName: 'notes/todo.md',+ namespace: PROJECT_A,+ }),+ ).toBe(true);+ expect(+ await consumeReplayOutboxEntry({+ branch: 'main',+ docName: 'notes/todo.md',+ namespace: PROJECT_B,+ }),+ ).toBe(true);+ });++ it('keeps the cross-tab claim shared between tabs of the SAME project', async () => {+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'notes/todo.md', namespace: PROJECT_A },+ { delta: bytes(1), fullState: bytes(0xaa) },+ );+ // Two tabs of one project still contend for one record: the second must+ // lose the claim, or the edit replays twice.+ expect(+ await consumeReplayOutboxEntry({+ branch: 'main',+ docName: 'notes/todo.md',+ namespace: PROJECT_A,+ }),+ ).toBe(true);+ expect(+ await consumeReplayOutboxEntry({+ branch: 'main',+ docName: 'notes/todo.md',+ namespace: PROJECT_A,+ }),+ ).toBe(false);+ });++ it('leaves the database name unchanged when there is no project namespace', async () => {+ // Web hosts are served per project on `http://127.0.0.1:<port>`, so the+ // origin already isolates them and the bare name stays correct. Holding+ // the name steady there also means no existing record is orphaned.+ await writeReplayOutboxEntry(+ { branch: 'main', docName: 'doc-unscoped', namespace: null },+ { delta: bytes(1), fullState: bytes(2) },+ );+ expect(await hasOutboxDb('ok-replay-outbox:main:doc-unscoped')).toBe(true);+ });+});diff --git a/packages/app/src/editor/replay-outbox.ts b/packages/app/src/editor/replay-outbox.tsindex a5f2f98b3..e990b721e 100644--- a/packages/app/src/editor/replay-outbox.ts+++ b/packages/app/src/editor/replay-outbox.ts@@ -9,18 +9,71 @@* store, and read back on the next open of the doc — surviving a tab crash at* any point up to the replay.*- * It is a SEPARATE IndexedDB database (`ok-replay-outbox:<branch>:<docName>`),- * NEVER the y-indexeddb `updates` store: hydrating the pre-recycle bytes back- * into the fresh Y.Doc is exactly the content-duplication class `clearData`- * exists to prevent. The reopen path reads this store explicitly and feeds the- * bytes through the CONTENT-level replay (rebuild a replica, splice the- * recovered string) rather than a Y.Doc merge.+ * It is a SEPARATE IndexedDB database+ * (`ok-replay-outbox[:<project digest>]:<branch>:<docName>` — the project+ * segment is absent on a null namespace), NEVER the y-indexeddb+ * `updates` store: hydrating the pre-recycle bytes back into the fresh Y.Doc+ * is exactly the content-duplication class `clearData` exists to prevent. The+ * reopen path reads this store explicitly and feeds the bytes through the+ * CONTENT-level replay (rebuild a replica, splice the recovered string) rather+ * than a Y.Doc merge.*- * The db name is branch+docName scoped (not epoch-scoped): the post-recycle- * `serverInstanceId` is unknown when the buffer is captured (the client nulls- * its cached id and only relearns it from the reconnect handshake), so the- * epoch cannot be part of the key. Branch isolation mirrors the y-indexeddb- * naming.+ * The db name is project+branch+docName scoped (not epoch-scoped): the+ * post-recycle `serverInstanceId` is unknown when the buffer is captured (the+ * client nulls its cached id and only relearns it from the reconnect+ * handshake), so the epoch cannot be part of the key.+ *+ * The project component is REQUIRED for every packaged window, and omitted+ * only for a null namespace, where the origin already isolates — that is+ * `precedent #59`, applied here through `scopedStorageKey`+ * (`lib/storage-scope.ts`), not re-derived. What is specific to THIS+ * store: `docName` is repo-root-relative and branch names repeat, so two+ * worktrees of one repository on the same branch address the same doc path,+ * and the payload here is buffered document content — so a collision crosses+ * edits between projects rather than raising an error. The sibling+ * y-indexeddb store in `client-persistence.ts` is safe without a project+ * component only because its name carries the per-process `serverInstanceId`,+ * which this one cannot have; the omission of the epoch does not license+ * omitting project identity.+ *+ * `namespace` is threaded in from the caller rather than resolved in here, and+ * travels in a NAMED field (`ReplayOutboxKey`) rather than a positional slot.+ * Requiredness only forces a value to be supplied; naming is what stops a+ * wrong one — three bare strings in a row compile in any order.+ *+ * A namespace change renames the database, so an entry written under a+ * different one is not read back. That has three causes, all accepted:+ *+ * 1. The one-time upgrade from the pre-scoping name. Deliberately NOT+ * migrated: adopting an unscoped record would import the cross-project+ * content this scoping removes, which is the bug. Electron only, since a+ * null namespace reproduces the old name exactly. The stranded set is+ * every LIVE pre-scoping record, not just one caught mid-recycle. Every+ * consume path runs INSIDE a live session: a reopen's replay (from the RAM+ * buffer when one survived, straight from the outbox when the tab died and+ * none did), or an intentional discard through `discardBufferedUpdate`+ * (explicit close, LRU eviction, cross-branch invalidation) — that second+ * family is the one gated on the RAM buffer's `durable` flag. Ordinary app+ * termination — quit, force-quit, `quitAndInstall` — runs none of them. So+ * a doc not reopened between its write and the upgrade keeps an+ * unreachable record. Stranding is also silent: a null read is+ * indistinguishable from "nothing to recover".+ * 2. Ongoing: the namespace is the project path AS THE USER PICKED IT, not+ * its realpath (`window-manager.ts` keeps `projectPath` and `canonicalKey`+ * deliberately distinct, and the renderer is handed the former). So+ * reopening one project under a different spelling of the same path+ * (`/tmp` vs `/private/tmp`, a symlinked cwd, Windows drive-letter case)+ * reads a different name and misses its own parked edit.+ * 3. A revert of this change orphans records written under the NEW name, for+ * the same reason as (1) — the desktop updater rolls forward only, so a+ * rollback ships as a revert.+ *+ * Case 2 costs a missed recovery on a best-effort mechanism; the collision it+ * replaces silently applied ANOTHER project's content. Canonicalizing is+ * additive rather than blocked — `window-manager.ts` already computes+ * `canonicalKey`, and identity reaches the renderer as independently-parsed+ * spawn args — but it touches the desktop spawn surface and every+ * editor-window path, so it is deferred rather than bundled here.** Durable recovery requires `indexedDB.databases()` (Baseline). On engines* without it EVERY operation no-ops (degrade to RAM-only): the read/consume@@ -30,12 +83,13 @@* reports that with a `false` return so the caller knows the buffer is* RAM-only.*- * The single `(branch, docName)` record is also the CROSS-TAB exactly-once- * token: same-origin tabs share it, so `consumeReplayOutboxEntry` reports- * whether THIS caller was the one that removed a live record. Its count+delete- * run in one `readwrite` transaction, and IndexedDB serializes overlapping- * readwrite transactions across connections, which makes the pair an atomic- * compare-and-claim rather than a check-then-act.+ * The single `(namespace, branch, docName)` record is also the CROSS-TAB+ * exactly-once token: tabs of the same project share it, so+ * `consumeReplayOutboxEntry` reports whether THIS caller was the one that+ * removed a live record. Its count+delete run in one `readwrite` transaction,+ * and IndexedDB serializes overlapping readwrite transactions across+ * connections, which makes the pair an atomic compare-and-claim rather than a+ * check-then-act.** Consumed entries leave an empty outbox database behind (record deleted, DB* kept) rather than racing a `deleteDatabase` against a concurrent reopen —@@ -52,6 +106,8 @@* covers the general stall, not a version-change block.*/+import { scopedStorageKey } from '@/lib/storage-scope';+const REPLAY_OUTBOX_DB_PREFIX = 'ok-replay-outbox';const ENTRY_STORE_NAME = 'entry';const ENTRY_KEY = 'buffer';@@ -116,8 +172,32 @@ export interface ReplayOutboxEntry {readonly fullState: Uint8Array;}-function outboxDbName(branch: string, docName: string): string {- return `${REPLAY_OUTBOX_DB_PREFIX}:${branch}:${docName}`;+/**+ * Addresses ONE outbox record. Object-literal form for the reason+ * `CreateClientPersistenceArgs` in `client-persistence.ts` gives for the+ * sibling IDB name: the fields are indistinguishable to the type system, so+ * positionally a swap compiles cleanly and silently produces the wrong+ * database name — here defeating the cross-project defense.+ */+export interface ReplayOutboxKey {+ readonly branch: string;+ readonly docName: string;+ /** See the module header. `null` only on hosts the origin already isolates. */+ readonly namespace: string | null;+}++/**+ * `<prefix>[:<project digest>]:<branch>:<docName>`. The project segment is+ * ABSENT for a null namespace, which is what keeps the web-host name+ * byte-identical to its pre-scoping form.+ *+ * The project component is what keeps two windows of DIFFERENT projects off+ * one database — see the `namespace` note in the module header. It is applied+ * by `scopedStorageKey` to the PREFIX rather than appended to the whole name,+ * so no web-host record is orphaned by this change.+ */+function outboxDbName({ branch, docName, namespace }: ReplayOutboxKey): string {+ return `${scopedStorageKey(REPLAY_OUTBOX_DB_PREFIX, namespace)}:${branch}:${docName}`;}function openOutboxDb(dbName: string): Promise<IDBDatabase> {@@ -146,11 +226,14 @@ function openOutboxDb(dbName: string): Promise<IDBDatabase> {* `databases()` enumerates ALL origin databases and runs on the first `synced`* of a doc open (via `readReplayOutboxEntry`), so its cost scales with the* origin's total database count, not just outbox DBs. The consumed-but-kept- * empty outboxes (see the module note) add to that count only per recycled- * `(branch, docName)` — a bounded subset dwarfed by the per-epoch y-indexeddb- * stores this call already lists — so retaining them is a storage-hygiene cost,- * not an enumeration-cost regression that would justify racing a `deleteDatabase`- * against a concurrent reopen.+ * empty outboxes (see the module note) add to that count per recycled+ * `(namespace, branch, docName)`, so it scales with projects opened as well as+ * docs recycled — N worktrees sharing a branch and a doc path leave N orphans+ * where they once left one. Still dwarfed by the per-epoch y-indexeddb stores+ * this call already lists, so retaining them remains a storage-hygiene cost+ * rather than an enumeration-cost regression that would justify racing a+ * `deleteDatabase` against a concurrent reopen — but the project multiplier is+ * the term to re-check if that ever stops holding.*/async function outboxDbExists(dbName: string): Promise<boolean> {if (!isReplayOutboxSupported()) return false;@@ -168,15 +251,15 @@ async function outboxDbExists(dbName: string): Promise<boolean> {* caller uses that to decide whether a durable copy backs its RAM buffer.*/export async function writeReplayOutboxEntry(- branch: string,- docName: string,+ key: ReplayOutboxKey,entry: ReplayOutboxEntry,): Promise<boolean> {// No `databases()` means no reader will ever find this record: writing it// would strand a full doc-state payload in storage with nothing able to// consume or reclaim it. Report RAM-only instead.if (!isReplayOutboxSupported()) return false;- const dbName = outboxDbName(branch, docName);+ const { docName } = key;+ const dbName = outboxDbName(key);return withOutboxTimeout('write',docName,@@ -214,11 +297,11 @@ export async function writeReplayOutboxEntry(* consumed outbox). Never creates a DB for a doc that has no outbox.*/export async function readReplayOutboxEntry(- branch: string,- docName: string,+ key: ReplayOutboxKey,): Promise<ReplayOutboxEntry | null> {if (!isReplayOutboxSupported()) return null;- const dbName = outboxDbName(branch, docName);+ const { docName } = key;+ const dbName = outboxDbName(key);return withOutboxTimeout('read',docName,@@ -251,20 +334,26 @@ export async function readReplayOutboxEntry(* Consume a doc's buffer by deleting its record, and report whether THIS* caller was the one that removed a live record.*- * That boolean is the cross-tab exactly-once claim. Same-origin tabs share one- * `(branch, docName)` record, so a `false` return means another tab already- * consumed it and owns the replay — re-applying on top would not be idempotent- * (see `replayBufferedContent`'s surface attribution). The count and the delete- * run in ONE `readwrite` transaction and IndexedDB serializes overlapping- * readwrite transactions across connections, so the pair is an atomic- * compare-and-claim, not a check-then-act.+ * That boolean is the cross-tab exactly-once claim. Tabs of the SAME project+ * share one `(namespace, branch, docName)` record, so a `false` return means+ * another such tab already consumed it and owns the replay — re-applying on+ * top would not be idempotent (see `replayBufferedContent`'s surface+ * attribution). The count and the delete run in ONE `readwrite` transaction+ * and IndexedDB serializes overlapping readwrite transactions across+ * connections, so the pair is an atomic compare-and-claim, not a+ * check-then-act.+ *+ * A window of a DIFFERENT project must never lose this claim: its buffered+ * edit belongs to a different document that merely shares a path and a branch+ * name. That is what the `namespace` component guarantees.** Idempotent for callers that only want the record gone (consuming an absent* record resolves `false` rather than throwing).*/-export async function consumeReplayOutboxEntry(branch: string, docName: string): Promise<boolean> {+export async function consumeReplayOutboxEntry(key: ReplayOutboxKey): Promise<boolean> {if (!isReplayOutboxSupported()) return false;- const dbName = outboxDbName(branch, docName);+ const { docName } = key;+ const dbName = outboxDbName(key);return withOutboxTimeout('consume',docName,diff --git a/packages/app/src/lib/storage-scope.ts b/packages/app/src/lib/storage-scope.tsnew file mode 100644index 000000000..06493a6e8--- /dev/null+++ b/packages/app/src/lib/storage-scope.ts@@ -0,0 +1,88 @@+/**+ * Project scoping for the renderer's persistent storage names — the+ * implementation of `precedent #59`, which is the citable statement of the+ * rule. Home of the one thing every client storage surface has to obey, so a+ * new one adopts it instead of rediscovering the bug (`provider-pool.ts` used+ * to own this privately, which is why `replay-outbox.ts` shipped without it).+ */+import { fnv1aDigest } from '@inkeep/open-knowledge-core';++/**+ * Scope a client storage name to a single project.+ *+ * A packaged desktop window loads the renderer through `loadFile`, so every+ * project window shares the one `file://` origin (`webPreferences.partition`+ * is set only for slides windows). One name per origin therefore means one+ * name for EVERY open project, and whichever window wrote last decides what+ * the next cold boot reads back. For the branch claim that is load-bearing: a+ * window seeds `lastObservedBranch` from the shared key, claims a sibling+ * project's branch, and the server correctly rejects it — the doc wedges and+ * the red branch-mismatch banner goes up.+ *+ * `namespace` is the project's content dir, digested so no absolute home path+ * lands in storage. Nothing prunes: the pre-scoping unscoped names are left+ * behind once, and one scoped name accrues per project ever opened. Both are+ * bounded, which is why this ships without a migration — adopting the old+ * value would import the sibling-project state it removes. A null namespace+ * returns the bare name, which is correct for web hosts: those are served per+ * project on `http://127.0.0.1:<port>`, so the origin already isolates them.+ *+ * **The origin is shared by more than one surface, and this list is not a+ * gate.** The same cause has been mitigated independently several times over —+ * `localTabSessionKeyForMode` in `editor-tabs.ts` returns null for BOTH+ * editor and note windows so neither writes the shared key (editor tab state+ * persists through the desktop bridge instead, keyed per project; note+ * persists nothing), `dock-session-persistence.ts` routes through the main+ * process,+ * the pool's two localStorage keys route through here, and `replay-outbox.ts`+ * names its IndexedDB database through here. Others are still unscoped at the+ * time of writing (`ok-omnibar-recents-v1`, `ok-ask-ai-draft-v2`), which is+ * the point: a hand-kept list drifts, so treat this as illustrative and the+ * RULE above as the contract. A sweep test classifying every persistent+ * storage name as app-global-by-intent or project-scoped would make it a real+ * gate; until then a new surface is only as safe as its author's diligence.+ *+ * Scoping the ORIGIN instead (a per-project `webPreferences.partition`) was+ * considered and rejected: it silently bypasses the `defaultSession`-only+ * `webRequest` hooks and spellchecker config, forks genuinely app-global+ * prefs such as theme and language, and orphans every existing `ok-ydoc:*`+ * store.+ *+ * Applies to any name whose collision domain is the ORIGIN. The y-indexeddb+ * store in `client-persistence.ts` is deliberately not routed through here:+ * its name already carries the per-process `serverInstanceId`, and each+ * project runs its own Hocuspocus process, so that name cannot collide across+ * projects even without a project component.+ *+ * Named "key" from its localStorage origin; it now also composes IndexedDB+ * database NAMES (`replay-outbox.ts`). Read `baseKey` as "base storage name".+ */+export function scopedStorageKey(baseKey: string, namespace: string | null): string {+ // `null` only. An empty string is NOT a web host: it is what a window+ // opened without a project reports (the preload defaults `projectPath` to+ // `''`, and the navigator passes `--ok-project-path=` outright). Letting it+ // fall through to the bare key would put those windows on the shared+ // app-wide name; digesting it instead keeps them sharing only with each+ // other, which is the safe direction if one ever reaches a document store.+ if (namespace === null) return baseKey;+ return `${baseKey}:${projectDigest(namespace)}`;+}++/**+ * The project segment `scopedStorageKey` embeds.+ *+ * Exported so anything that has to be COMPARABLE to a scoped storage name —+ * telemetry correlating an event to a database, a test recomposing one —+ * derives it here rather than calling `fnv1aDigest` again. A second+ * derivation is equal only by coincidence: a salt, a truncation or a+ * different hash added here would silently stop matching it. Digesting is+ * also the privacy step (a raw namespace is an absolute path that can carry+ * the OS username), so keeping one definition keeps one place to audit.+ *+ * Note this is the SEGMENT, not the composition: `scopedStorageKey` above+ * decides how it is joined to a base name, and a caller reconstructing a full+ * name must go through that rather than concatenating this itself.+ */+export function projectDigest(namespace: string): string {+ return fnv1aDigest(namespace);+}diff --git a/packages/app/tests/integration/replay-outbox-durable.test.ts b/packages/app/tests/integration/replay-outbox-durable.test.tsindex 963aff73b..2b6094d99 100644--- a/packages/app/tests/integration/replay-outbox-durable.test.ts+++ b/packages/app/tests/integration/replay-outbox-durable.test.ts@@ -127,9 +127,24 @@ describe('durable replay outbox across server-instance-mismatch', () => {const outboxDbs = await outboxDbsForDoc(docName);expect(outboxDbs.length).toBeGreaterThanOrEqual(1);for (const dbName of outboxDbs) {- const segments = dbName.split(':');- const branch = segments[1] ?? '';- expect(await readReplayOutboxEntry(branch, docName)).toBeNull();+ // The name is `ok-replay-outbox[:<project digest>]:<branch>:<docName>`.+ // This harness builds its pool with no `storageNamespace`, so the+ // project segment is absent and the recomposed key below must pass+ // `namespace: null` to address the same database. PIN that rather than+ // parse around it: a harness that grows a namespace would otherwise+ // recompose an unscoped name, read a database that does not exist, and+ // pass this `toBeNull()` vacuously — reporting "consumed" for a record+ // it never looked at.+ // Strip the docName by LENGTH so a colon inside it cannot shift the+ // parse (`validateDocName` permits one, and `:` is a legal POSIX+ // filename byte), then strip the known prefix. What remains is the+ // branch alone for an unscoped name and `<digest>:<branch>` for a+ // scoped one — so the colonless assert IS the unscoped check, and git+ // refnames can never contain a colon to false-trip it.+ const withoutDoc = dbName.slice(0, -(docName.length + 1));+ const branch = withoutDoc.slice('ok-replay-outbox:'.length);+ expect(branch).not.toContain(':');+ expect(await readReplayOutboxEntry({ branch, docName, namespace: null })).toBeNull();}const finalOnDisk = readFileSync(join(server.contentDir, `${docName}.md`), 'utf-8');