Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): scope client-persistence storage keys per project (PRD-8303) (#3884)

Andrew Mikofalvy5200e3338723
diff --git a/.changeset/project-scoped-client-persistence-keys.md b/.changeset/project-scoped-client-persistence-keys.md
new file mode 100644
index 000000000..369e65a59
--- /dev/null
+++ b/.changeset/project-scoped-client-persistence-keys.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Opening two projects at once no longer wedges one of them behind a red "the project's server is on a different branch than this window" banner. Each window remembers the git branch it last saw so that a freshly restored window can prove to the server which branch its cached content belongs to. That memory was stored under a single key shared by every open project, because it was scoped to the app rather than to the project. Whichever window wrote last decided what the next window read, so a window could start up claiming a completely different project's branch. The server correctly rejected the mismatched claim, the document then failed to load for 30 seconds, and the banner blamed the server even though the server was on the right branch the whole time. This was most visible right after an update, when every window restarts and reads that memory at once. Each project now keeps its own copy, so one project can no longer answer for another. The per-document lineage records, which had the same app-wide scope, are now per project as well.
diff --git a/packages/app/src/editor/DocumentContext.getPool-namespace.dom.test.ts b/packages/app/src/editor/DocumentContext.getPool-namespace.dom.test.ts
new file mode 100644
index 000000000..6ddb3a703
--- /dev/null
+++ b/packages/app/src/editor/DocumentContext.getPool-namespace.dom.test.ts
@@ -0,0 +1,59 @@
+// The seam between `provider-pool.test.ts` (which verifies the key-scoping
+// MECHANISM, but hands `storageNamespace` in by hand) and production. This
+// file pins the one line that supplies it for real: a regression there —
+// `.contentDir` swapped for a sibling field, the `storageNamespace` option
+// dropped from the call, a fresh-per-launch fallback reintroduced — is
+// type-clean and silent, so it ships with a fully green suite and
+// reproduces the wedge the scoping exists to prevent.
+//
+// Lives in its own file on purpose. `pool` is a module-level singleton, so
+// whichever test constructs it first freezes it for the rest of the file;
+// `vi.resetModules()` plus a dynamic import gives each case a fresh one.
+import { fnv1aDigest } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+
+const WS_URL = 'ws://localhost:1/collab';
+
+function setDesktopBridge(projectPath: string): void {
+ window.okDesktop = {
+ config: { projectPath },
+ platform: 'darwin',
+ } as unknown as Window['okDesktop'];
+}
+
+beforeEach(() => {
+ vi.resetModules();
+});
+
+afterEach(() => {
+ delete window.okDesktop;
+ window.localStorage.clear();
+});
+
+describe('getPool storage-namespace wiring', () => {
+ test('scopes keys to the Electron project reported by resolveSyncWorkspace', async () => {
+ setDesktopBridge('/tmp/project-a');
+ const { getPool } = await import('./DocumentContext');
+ const pool = getPool(WS_URL);
+ try {
+ pool.setObservedBranch('main');
+ expect(window.localStorage.getItem('ok-last-observed-branch')).toBeNull();
+ expect(
+ window.localStorage.getItem(`ok-last-observed-branch:${fnv1aDigest('/tmp/project-a')}`),
+ ).toBe('main');
+ } finally {
+ pool.dispose();
+ }
+ });
+
+ test('web host with no bridge keeps the bare key — the per-port origin isolates it', async () => {
+ const { getPool } = await import('./DocumentContext');
+ const pool = getPool(WS_URL);
+ try {
+ pool.setObservedBranch('main');
+ expect(window.localStorage.getItem('ok-last-observed-branch')).toBe('main');
+ } finally {
+ pool.dispose();
+ }
+ });
+});
diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsx
index b0ae3ec0c..e83e00273 100644
--- a/packages/app/src/editor/DocumentContext.tsx
+++ b/packages/app/src/editor/DocumentContext.tsx
@@ -36,6 +36,7 @@ import {
shouldSuppressTabSessionRestore,
} from '@/lib/tab-session-restore-suppression';
import { useCollabUrl } from '@/lib/use-collab-url';
+import { resolveSyncWorkspace } from '@/lib/use-workspace';
import { getEditorForDoc } from './active-editor';
import { handleBranchSwitched } from './branch-invalidation';
import {
@@ -467,7 +468,13 @@ let pool: ProviderPool | null = null;
export function getPool(collabUrl: string): ProviderPool {
if (!pool) {
- pool = new ProviderPool(MAX_POOL, collabUrl);
+ // Scope the pool's localStorage keys to THIS project — `scopedStorageKey`
+ // carries the 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.
+ pool = new ProviderPool(MAX_POOL, collabUrl, {
+ storageNamespace: resolveSyncWorkspace()?.contentDir ?? null,
+ });
// Wire the editor cache to the pool's eviction events. Without this
// subscription, cached `Editor` / `EditorView` instances would
// outlive the Y.Doc they're bound to. Single subscription per pool
diff --git a/packages/app/src/editor/provider-pool.test.ts b/packages/app/src/editor/provider-pool.test.ts
index 5a30cfd77..b82985b90 100644
--- a/packages/app/src/editor/provider-pool.test.ts
+++ b/packages/app/src/editor/provider-pool.test.ts
@@ -1370,6 +1370,106 @@ describe('ProviderPool server-instance-ID claim (US-001)', () => {
});
});
+// Every project window in the packaged desktop app loads the
+// renderer through `loadFile` — a single `file://` origin — and
+// `webPreferences.partition` is set only for slides windows, so every open
+// project shares ONE localStorage. A storage key that is not scoped to the
+// project therefore lets a SIBLING project's window decide this window's
+// branch claim: the pool seeds `lastObservedBranch` from the shared key at
+// cold boot, claims the sibling's branch, and the server correctly rejects
+// it. That is the wedge behind the red "the project's server is on a
+// different branch" banner.
+describe('cross-project storage-key isolation', () => {
+ function makeStubStorage(): {
+ stub: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
+ store: Map<string, string>;
+ } {
+ const store = new Map<string, string>();
+ const stub = {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => {
+ store.set(k, v);
+ },
+ removeItem: (k: string) => {
+ store.delete(k);
+ },
+ };
+ return { stub, store };
+ }
+
+ test("a sibling project's persisted branch does not become this pool's claim", () => {
+ const { stub } = makeStubStorage();
+ // Window A — project A, on `main`, records its branch into the store
+ // both windows share.
+ const poolA = new ProviderPool(3, DUMMY_WS, {
+ storage: stub,
+ storageNamespace: '/Users/dev/code/project-a',
+ });
+ try {
+ poolA.setObservedBranch('main');
+
+ // Window B — a DIFFERENT project, cold boot (empty in-memory cache),
+ // reading that same shared localStorage.
+ const poolB = new ProviderPool(3, DUMMY_WS, {
+ storage: stub,
+ storageNamespace: '/Users/dev/code/project-b',
+ });
+ try {
+ const entry = poolB.open('doc1');
+ if (!entry) throw new Error('expected entry');
+ const parsed = parseHocuspocusAuthToken(entry.provider.configuration.token as string);
+ if (!parsed) throw new Error('expected valid token');
+ // B has never observed a branch of its own, so it must claim
+ // nothing. Claiming A's `main` is exactly what the server rejects.
+ expect(parsed.expectedBranch).toBeUndefined();
+ } finally {
+ poolB.dispose();
+ }
+ } finally {
+ poolA.dispose();
+ }
+ });
+
+ test('an empty namespace is scoped, not treated as a web host', () => {
+ // `''` reaches the pool when an Electron host resolves a workspace with
+ // no contentDir — a broken config. It must not fall through to the
+ // app-wide key that correctly-configured windows would then share.
+ const { stub, store } = makeStubStorage();
+ const broken = new ProviderPool(3, DUMMY_WS, { storage: stub, storageNamespace: '' });
+ try {
+ broken.setObservedBranch('main');
+ expect(store.has('ok-last-observed-branch')).toBe(false);
+ expect(store.get('ok-last-observed-branch:811c9dc5')).toBe('main');
+ } finally {
+ broken.dispose();
+ }
+ });
+
+ test('a project still reads back its OWN branch across a cold boot', () => {
+ // Namespacing must not cost us the fresh-tab defense the key exists for:
+ // same project, new pool, still claims what it persisted.
+ const { stub } = makeStubStorage();
+ const namespace = '/Users/dev/code/project-a';
+ const first = new ProviderPool(3, DUMMY_WS, { storage: stub, storageNamespace: namespace });
+ try {
+ first.setObservedBranch('feature/example');
+ } finally {
+ first.dispose();
+ }
+
+ const second = new ProviderPool(3, DUMMY_WS, { storage: stub, storageNamespace: namespace });
+ try {
+ const entry = second.open('doc1');
+ if (!entry) throw new Error('expected entry');
+ const parsed = parseHocuspocusAuthToken(entry.provider.configuration.token as string);
+ if (!parsed) throw new Error('expected valid token');
+ expect(parsed.expectedBranch).toBe('feature/example');
+ } finally {
+ second.dispose();
+ }
+ });
+});
+
// ---------------------------------------------------------------------------
// MECHANISM-ONLY tests for the per-doc lineage-epoch records (the doc-lineage
// fence's client half): claim derivation, envelope validation, record/drop
@@ -1657,6 +1757,61 @@ describe('ProviderPool doc-lineage epoch records', () => {
expect(envelope.epochs[renamedDoc]).toBeUndefined();
expect(envelope.epochs[deletedDoc]).toBeUndefined();
});
+
+ // Cross-project isolation for the envelope key. Both pools here share one
+ // storage stub, one document path and one server instance, and neither has
+ // observed a branch — so the project namespace is the ONLY thing that can
+ // separate them. Drop it and B reads back an epoch minted for A's document.
+ test("a sibling project cannot read back this project's lineage envelope", () => {
+ const { stub, store } = makeStubStorage();
+ const docName = uniqueDocName('pp-lineage-cross-project');
+
+ const projectA = new ProviderPool(3, DUMMY_WS, {
+ storage: stub,
+ storageNamespace: '/Users/dev/code/project-a',
+ persistenceFactory: vi.fn(makePersistenceStub),
+ });
+ try {
+ projectA.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
+ const entryA = projectA.open(docName);
+ if (!entryA) throw new Error('expected entry');
+ entryA.provider.document.getMap('lifecycle').set('epoch', 'epoch-project-a');
+ entryA.provider.emit('synced', { state: true });
+ // A's envelope went to its own scoped key, never the app-wide one.
+ expect(store.get(ENVELOPE_KEY)).toBeUndefined();
+ } finally {
+ projectA.dispose();
+ }
+
+ const projectB = new ProviderPool(3, DUMMY_WS, {
+ storage: stub,
+ storageNamespace: '/Users/dev/code/project-b',
+ persistenceFactory: vi.fn(makePersistenceStub),
+ });
+ try {
+ projectB.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
+ const entryB = projectB.open(docName);
+ if (!entryB) throw new Error('expected entry');
+ expect(tokenOf(entryB).expectedDocLineageEpoch).toBeUndefined();
+ } finally {
+ projectB.dispose();
+ }
+
+ // ...and the scoping must not cost A its own round-trip.
+ const projectAAgain = new ProviderPool(3, DUMMY_WS, {
+ storage: stub,
+ storageNamespace: '/Users/dev/code/project-a',
+ persistenceFactory: vi.fn(makePersistenceStub),
+ });
+ try {
+ projectAAgain.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
+ const entryA2 = projectAAgain.open(docName);
+ if (!entryA2) throw new Error('expected entry');
+ expect(tokenOf(entryA2).expectedDocLineageEpoch).toBe('epoch-project-a');
+ } finally {
+ projectAAgain.dispose();
+ }
+ });
});
// ---------------------------------------------------------------------------
diff --git a/packages/app/src/editor/provider-pool.ts b/packages/app/src/editor/provider-pool.ts
index 9542271ba..bfb85f184 100644
--- a/packages/app/src/editor/provider-pool.ts
+++ b/packages/app/src/editor/provider-pool.ts
@@ -2,6 +2,7 @@ import { HocuspocusProvider } from '@hocuspocus/provider';
import {
addsBlankLines,
composeWithDerivedBody,
+ fnv1aDigest,
LINEAGE_EPOCH_KEY,
MarkdownManager,
normalizeBridge,
@@ -373,14 +374,59 @@ class StoredEpochPeekTimeoutError extends Error {
* `ProviderPool` to seed the cross-branch defense's in-memory cache on
* a fresh tab so the very first auth-token claim is checked against
* the server's current branch (closes the fresh-tab-with-stale-IDB
- * gap). Single key per origin is fine — a single Hocuspocus server's
- * branch is global to the project.
+ * gap). Scoped per project by `scopedStorageKey` — see that helper for why
+ * one key per ORIGIN is not one key per project.
*/
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.
- * Single envelope per origin:
+ * Scoped per project by `scopedStorageKey`, for the same reason the branch
+ * key is: a sibling project's window shares this origin's localStorage, and
+ * its write would clobber this project's envelope. A clobbered read still
+ * fails safe via the validation below, but the fence it feeds goes silently
+ * dead until the next learned epoch.
+ * Single envelope per project:
* `{ branch, serverInstanceId, epochs: Record<docName, epoch> }` —
* validated against the current observed branch + live instance id on
* load, so a stale envelope (server restarted, branch switched) is
@@ -661,6 +707,14 @@ export class ProviderPool {
*/
private readonly storage: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | null;
+ /**
+ * Project-scoped storage keys, resolved once at construction from
+ * `options.storageNamespace`. See `scopedStorageKey` for why the bare
+ * constants cannot be used directly in a packaged desktop window.
+ */
+ private readonly lastObservedBranchKey: string;
+ private readonly docLineageEpochsKey: string;
+
constructor(
maxSize: number,
wsUrl: string,
@@ -668,6 +722,12 @@ export class ProviderPool {
recycleDebounceMs?: number;
clearDataTimeoutMs?: number;
storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | null;
+ /**
+ * Project identity (the content dir) that scopes this pool's storage
+ * keys. Omit / null on hosts where the origin already isolates
+ * projects. See `scopedStorageKey`.
+ */
+ storageNamespace?: string | null;
persistenceFactory?: ClientPersistenceFactory;
peekStoredLineageEpoch?: PeekStoredLineageEpoch;
},
@@ -689,6 +749,9 @@ export class ProviderPool {
this.storage =
typeof globalThis.localStorage !== 'undefined' ? globalThis.localStorage : null;
}
+ const storageNamespace = options?.storageNamespace ?? null;
+ this.lastObservedBranchKey = scopedStorageKey(LAST_OBSERVED_BRANCH_KEY, storageNamespace);
+ this.docLineageEpochsKey = scopedStorageKey(DOC_LINEAGE_EPOCHS_KEY, storageNamespace);
}
/**
@@ -1193,7 +1256,7 @@ export class ProviderPool {
if (this.lastObservedBranchInitialized) return this.lastObservedBranch;
this.lastObservedBranchInitialized = true;
try {
- const stored = this.storage?.getItem(LAST_OBSERVED_BRANCH_KEY) ?? null;
+ const stored = this.storage?.getItem(this.lastObservedBranchKey) ?? null;
if (stored !== null && stored.length > 0) {
this.lastObservedBranch = stored;
}
@@ -1214,9 +1277,9 @@ export class ProviderPool {
this.lastObservedBranchInitialized = true;
try {
if (branch === null || branch.length === 0) {
- this.storage?.removeItem(LAST_OBSERVED_BRANCH_KEY);
+ this.storage?.removeItem(this.lastObservedBranchKey);
} else {
- this.storage?.setItem(LAST_OBSERVED_BRANCH_KEY, branch);
+ this.storage?.setItem(this.lastObservedBranchKey, branch);
}
} catch {
// Storage write failures are non-fatal — see read-side comment.
@@ -1272,7 +1335,7 @@ export class ProviderPool {
if (instanceId === null || instanceId.length === 0) return;
this.docLineageEpochsEnvelopeConsumed = true;
try {
- const raw = this.storage?.getItem(DOC_LINEAGE_EPOCHS_KEY) ?? null;
+ const raw = this.storage?.getItem(this.docLineageEpochsKey) ?? null;
if (raw === null) return;
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== 'object' || parsed === null) return;
@@ -1323,7 +1386,7 @@ export class ProviderPool {
if (instanceId === null || instanceId.length === 0) return;
try {
this.storage?.setItem(
- DOC_LINEAGE_EPOCHS_KEY,
+ this.docLineageEpochsKey,
JSON.stringify({
branch: this.normalizedObservedBranch(),
serverInstanceId: instanceId,