Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): stop no-op pool notifies re-rendering the app shell (#2979)

Andrew Mikofalvyb7932b780be1
diff --git a/.changeset/pool-snapshot-render-loop.md b/.changeset/pool-snapshot-render-loop.md
new file mode 100644
index 000000000..b7b572903
--- /dev/null
+++ b/.changeset/pool-snapshot-render-loop.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Fixed a crash that could take the whole editor down to the "Something went wrong" screen during navigation — most visibly right after creating a new file, and also when a document was renamed, deleted, or moved out from under an open tab. The editor tracked its open-document pool with a value that was rebuilt from scratch on every pool change, including changes that altered nothing you could see, such as re-opening a document that was already open. Each rebuild re-rendered the app shell and handed the navigation layer a fresh set of callbacks, which prompted it to re-open the document again. When a document's identity changed underneath that cycle, it fed itself until React aborted the render with "Maximum update depth exceeded". The pool value is now reused when nothing observable has changed, so the cycle can no longer close.
diff --git a/packages/app/src/editor/DocumentContext.snapshot-stability.dom.test.tsx b/packages/app/src/editor/DocumentContext.snapshot-stability.dom.test.tsx
new file mode 100644
index 000000000..1728e686f
--- /dev/null
+++ b/packages/app/src/editor/DocumentContext.snapshot-stability.dom.test.tsx
@@ -0,0 +1,141 @@
+import { act, cleanup, render, screen } from '@testing-library/react';
+import { type ReactNode, useEffect } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+// Dummy ws URL: the pool constructs real providers but they never reach the
+// wire, matching `DocumentContext.branch-fanout.dom.test.tsx`.
+vi.doMock('@/lib/use-collab-url', () => ({
+ useCollabUrl: () => ({
+ collabUrl: 'ws://localhost:1/collab',
+ attempts: 0,
+ terminal: false,
+ lastError: null,
+ retry: () => {},
+ }),
+}));
+
+const { DocumentProvider, useDocumentContext, useDocumentTransition } = await import(
+ './DocumentContext'
+);
+
+const originalFetch = globalThis.fetch;
+
+/**
+ * Past this many runs the effect stops feeding the cycle, so a regression
+ * fails the assertion below instead of spinning until React's own
+ * nested-update limit trips (which surfaces as an opaque minified #185).
+ */
+const EFFECT_RUN_CAP = 25;
+
+let effectRuns = 0;
+let consumerCommits = 0;
+
+/**
+ * Mirrors `NavigationHandler` in `App.tsx`: the effect calls the navigation
+ * entry point in its body AND lists that same callback as a dependency.
+ *
+ * That pairing is only safe while a pool notify which changes nothing
+ * observable leaves the provider's snapshot state untouched. If every notify
+ * allocates a fresh snapshot, the callback gets a new identity per commit and
+ * the pairing closes into a cycle: effect → `openTargetTransition` →
+ * `pool.open()` → notify → re-render → new callback identity → effect.
+ */
+function NavigationEffectShape({ docName }: { docName: string }) {
+ const { openTargetTransition } = useDocumentTransition();
+ useEffect(() => {
+ effectRuns += 1;
+ if (effectRuns > EFFECT_RUN_CAP) return;
+ openTargetTransition({ kind: 'doc', target: docName, docName });
+ }, [openTargetTransition, docName]);
+ return null;
+}
+
+function SnapshotConsumer() {
+ const { poolEntries } = useDocumentContext();
+ // Depless effect runs once per commit — counts re-renders without the
+ // impurity of mutating a counter during render.
+ useEffect(() => {
+ consumerCommits += 1;
+ });
+ return <span data-testid="pool-size">{poolEntries.length}</span>;
+}
+
+function ProviderHarness({ children }: { children: ReactNode }) {
+ return <DocumentProvider>{children}</DocumentProvider>;
+}
+
+function getPool(): { open(docName: string): unknown } {
+ const pool = (window as unknown as { __providerPool?: { open(docName: string): unknown } })
+ .__providerPool;
+ if (!pool) throw new Error('__providerPool not exposed');
+ return pool;
+}
+
+async function settle(): Promise<void> {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
+
+describe('DocumentContext pool-snapshot stability', () => {
+ afterEach(() => {
+ cleanup();
+ effectRuns = 0;
+ consumerCommits = 0;
+ globalThis.fetch = originalFetch;
+ window.localStorage.clear();
+ window.location.hash = '';
+ });
+
+ test('a navigation effect that re-opens its own target settles instead of looping', async () => {
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
+
+ render(<NavigationEffectShape docName="Loop.md" />, { wrapper: ProviderHarness });
+ await settle();
+ const runsAtQuiescence = effectRuns;
+
+ // Admitting the doc and marking it active are real transitions, so a
+ // handful of re-runs is expected. The defect is unbounded re-running, so
+ // assert well clear of the cap rather than pinning an exact count.
+ expect(runsAtQuiescence).toBeLessThan(EFFECT_RUN_CAP / 2);
+
+ // ...and it must have converged, not merely been throttled: further
+ // draining adds no runs.
+ await settle();
+ await settle();
+ expect(effectRuns).toBe(runsAtQuiescence);
+ });
+
+ test('re-opening an already-pooled doc does not re-render snapshot consumers', async () => {
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
+
+ render(<SnapshotConsumer />, { wrapper: ProviderHarness });
+ await settle();
+
+ // The pool is cached per collab URL at module scope, so it can carry
+ // entries admitted by an earlier test. Assert on deltas, not absolutes.
+ const pool = getPool();
+ const sizeBefore = Number(screen.getByTestId('pool-size').textContent);
+ const commitsBeforeAdmission = consumerCommits;
+
+ await act(async () => {
+ pool.open('Warm.md');
+ });
+ await settle();
+
+ // Admitting a new doc is a real change: it must reach consumers.
+ expect(Number(screen.getByTestId('pool-size').textContent)).toBe(sizeBefore + 1);
+ expect(consumerCommits).toBeGreaterThan(commitsBeforeAdmission);
+
+ // A warm hit only bumps `lastAccessedAt` and re-touches the LRU order.
+ // Neither reaches the DOM, so no consumer should re-render.
+ const commitsAfterAdmission = consumerCommits;
+ await act(async () => {
+ pool.open('Warm.md');
+ pool.open('Warm.md');
+ });
+ await settle();
+
+ expect(consumerCommits).toBe(commitsAfterAdmission);
+ });
+});
diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsx
index c82069179..5a4ec7954 100644
--- a/packages/app/src/editor/DocumentContext.tsx
+++ b/packages/app/src/editor/DocumentContext.tsx
@@ -567,6 +567,45 @@ function sameNavigationTarget(
return navigationTargetKey(a) === navigationTargetKey(b);
}
+/**
+ * Structural equality for two pool snapshots, so a notify that changes nothing
+ * a consumer can observe does not re-render the provider.
+ *
+ * `lastAccessedAt` is deliberately excluded. It never reaches the DOM — its
+ * only job is to order `poolEntries`, and that ordering is already encoded in
+ * the array itself (`takeSnapshot` sorts MRU-first, and `computeActivityMountList`
+ * re-sorts by the same key). Comparing it would defeat the bailout entirely,
+ * because `ProviderPool.open()` bumps it on every cache hit.
+ *
+ * Without this guard the provider re-renders on every pool mutation, which
+ * hands every context consumer a fresh callback identity. An effect that both
+ * calls one of those callbacks and depends on it — `NavigationHandler` in
+ * `App.tsx` is the load-bearing one — then closes into a self-feeding cycle
+ * that terminates only at React's nested-update limit.
+ */
+function sameSnapshot(a: Snapshot, b: Snapshot): boolean {
+ if (a === b) return true;
+ if (
+ a.activeDocName !== b.activeDocName ||
+ a.activeProvider !== b.activeProvider ||
+ a.syncState !== b.syncState ||
+ // Reference comparison is sufficient: the pool only reassigns
+ // `serverRestartRecoveryState` on an actual transition.
+ a.serverRestartRecovery !== b.serverRestartRecovery ||
+ a.poolEntries.length !== b.poolEntries.length
+ ) {
+ return false;
+ }
+ return a.poolEntries.every((entry, index) => {
+ const other = b.poolEntries[index];
+ return (
+ entry.docName === other.docName &&
+ entry.provider === other.provider &&
+ entry.poolEventId === other.poolEventId
+ );
+ });
+}
+
function takeSnapshot(p: ProviderPool): Snapshot {
const active = p.getActive();
// Project mutable pool entries to immutable read-only snapshots, sorted MRU-first.
@@ -1022,8 +1061,17 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
setTabIdentityResolved(false);
const p = getPool(collabUrl);
+ // Reuses the previous snapshot when nothing observable changed, so a pool
+ // notify that only touched LRU bookkeeping doesn't re-render the shell.
+ const commitSnapshot = () => {
+ setSnapshot((current) => {
+ const next = takeSnapshot(p);
+ return sameSnapshot(current, next) ? current : next;
+ });
+ };
+
// Sync initial state
- setSnapshot(takeSnapshot(p));
+ commitSnapshot();
// Late-join branch backstop. Auth-token `expectedBranch` claim
// mismatch (server is on branch B, client claims branch A) routes
@@ -1120,7 +1168,7 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
});
// Subscribe to pool changes
- p.setOnChange(() => setSnapshot(takeSnapshot(p)));
+ p.setOnChange(commitSnapshot);
// Fetch principal and wire tab identity so HocuspocusProvider includes
// {principalId, tabSessionId} in its auth token. The server's