Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

fix(web): prevent document recovery tabs from acknowledging each other (#751)

I'm Groot 🌳e86102b8f338
diff --git a/apps/web/src/features/documents/hooks/useDocumentCollaboration.test.tsx b/apps/web/src/features/documents/hooks/useDocumentCollaboration.test.tsx
index 6627a00d..e9433855 100644
--- a/apps/web/src/features/documents/hooks/useDocumentCollaboration.test.tsx
+++ b/apps/web/src/features/documents/hooks/useDocumentCollaboration.test.tsx
@@ -6,6 +6,7 @@ import { Editor } from '@tiptap/core';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { JSDOM } from 'jsdom';
import type { ProjectDocument } from '@/lib/api/endpoints/documents';
+import { sendableSteps } from 'prosemirror-collab';
import { documentEditorExtensions } from '../components/DocumentMarkdownEditor';
type UseDocumentCollaboration =
@@ -148,6 +149,73 @@ afterEach(() => {
}
});
+const recoveryKey = 'document-steps:user-1:SEKTA:42';
+
+function storedRecovery(text = '!') {
+ const base = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ attrs: { blockId: 'saved' },
+ content: [{ type: 'text', text: 'Saved' }],
+ },
+ ],
+ };
+ const step = {
+ stepType: 'replace',
+ from: 6,
+ to: 6,
+ slice: { content: [{ type: 'text', text }] },
+ };
+ window.sessionStorage.setItem(
+ recoveryKey,
+ JSON.stringify({ epoch: 'e1', version: 0, clientId: 'restored-client', base, steps: [step] }),
+ );
+ return step;
+}
+
+type SavedStep = { clientId: string; step: Record<string, unknown> };
+
+function stepServer(existing: SavedStep[] = [], gate = Promise.resolve(), content = 'Saved!') {
+ const fallback = globalThis.fetch;
+ const accepted = [...existing];
+ const writes: { clientId: string; steps: Record<string, unknown>[] }[] = [];
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = new URL(String(input));
+ if (url.pathname.endsWith('/steps')) {
+ if (init?.method === 'POST') {
+ const body = JSON.parse(String(init.body)) as (typeof writes)[number];
+ writes.push(body);
+ await gate;
+ accepted.push(...body.steps.map((step) => ({ step, clientId: body.clientId })));
+ return Response.json(projectDocument(3, content));
+ }
+ const version = Number(url.searchParams.get('version') ?? 0);
+ return Response.json({
+ epoch: 'e1',
+ version: accepted.length,
+ steps: accepted.slice(version),
+ hasMore: false,
+ documentVersion: accepted.length ? 3 : 2,
+ });
+ }
+ if (url.pathname.endsWith('/documents/42')) return Response.json(projectDocument(3, content));
+ return fallback(input, init);
+ }) as typeof fetch;
+ return writes;
+}
+
+async function mountDocument() {
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <Probe document={projectDocument(2, 'Saved')} />
+ </QueryClientProvider>,
+ );
+ });
+}
+
describe('useDocumentCollaboration', () => {
it('seeds a session from the document Markdown, not from a stale editor body', async () => {
await act(async () => {
@@ -228,4 +296,73 @@ describe('useDocumentCollaboration', () => {
assert.equal(collaboration.status, 'conflict');
assert.equal(editor.getText(), 'Saved!');
});
+ it('keeps a restored client read-only until its old steps are acknowledged', async () => {
+ storedRecovery();
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const writes = stepServer([], gate);
+ await mountDocument();
+ assert.equal(collaboration.ready, false);
+ assert.equal(writes[0].clientId, 'restored-client');
+ assert.ok(window.sessionStorage.getItem(recoveryKey));
+ await act(async () => {
+ release();
+ await collaboration.flush();
+ });
+ assert.equal(collaboration.ready, true);
+ assert.equal(editor.getText(), 'Saved!');
+ act(() => {
+ editor.commands.insertContentAt(editor.state.doc.content.size - 1, '?');
+ });
+ assert.notEqual(sendableSteps(editor.state)?.clientID, 'restored-client');
+ });
+
+ it('reconciles an accepted batch without resending it and includes the source tabs later steps', async () => {
+ const step = storedRecovery();
+ const later = {
+ stepType: 'replace',
+ from: 7,
+ to: 7,
+ slice: { content: [{ type: 'text', text: 'A' }] },
+ };
+ const writes = stepServer(
+ [
+ { clientId: 'restored-client', step },
+ { clientId: 'restored-client', step: later },
+ ],
+ Promise.resolve(),
+ 'Saved!A',
+ );
+ await mountDocument();
+ assert.equal(collaboration.ready, true);
+ assert.equal(editor.getText(), 'Saved!A');
+ assert.equal(writes.length, 0);
+ assert.equal(window.sessionStorage.getItem(recoveryKey), null);
+ assert.equal(editor.commands.undo(), false);
+ act(() => {
+ editor.commands.insertContentAt(editor.state.doc.content.size - 1, 'B');
+ });
+ assert.notEqual(sendableSteps(editor.state)?.clientID, 'restored-client');
+ });
+
+ it('keeps divergent legacy recovery for export instead of acknowledging another tabs text', async () => {
+ storedRecovery('B');
+ const step = {
+ stepType: 'replace',
+ from: 6,
+ to: 6,
+ slice: { content: [{ type: 'text', text: 'A' }] },
+ };
+ const writes = stepServer([{ clientId: 'restored-client', step }], Promise.resolve(), 'SavedA');
+ await mountDocument();
+ assert.equal(collaboration.ready, false);
+ assert.equal(collaboration.recoveryConflict, true);
+ assert.equal(collaboration.status, 'conflict');
+ assert.equal(editor.getText(), 'SavedB');
+ assert.equal(writes.length, 0);
+ assert.ok(window.sessionStorage.getItem(recoveryKey));
+ assert.equal(sendableSteps(editor.state)?.steps.length, 1);
+ });
});
diff --git a/apps/web/src/features/documents/hooks/useDocumentCollaboration.ts b/apps/web/src/features/documents/hooks/useDocumentCollaboration.ts
index ce003945..050e6920 100644
--- a/apps/web/src/features/documents/hooks/useDocumentCollaboration.ts
+++ b/apps/web/src/features/documents/hooks/useDocumentCollaboration.ts
@@ -42,7 +42,7 @@ export function useDocumentCollaboration({
const qc = useQueryClient();
const [status, setStatus] = useState<DocumentSyncState>('connecting');
const [ready, setReady] = useState(false);
- const state = useRef<DocumentSessionState | null>(null);
+ const state = useRef<(DocumentSessionState & { recovering: boolean }) | null>(null);
const saving = useRef<Promise<ProjectDocument | null> | null>(null);
const latest = useRef({ document, onSaved });
latest.current = { document, onSaved };
@@ -68,8 +68,20 @@ export function useDocumentCollaboration({
getVersion(editor.state),
);
if (editor.isDestroyed || state.current !== activeSession) return;
- confirmedVersion.current = result.documentVersion;
const steps = result.steps.map((item) => Step.fromJSON(editor.schema, item.step));
+ const pending = sendableSteps(editor.state);
+ // A cloned recovery can share an id, but different steps are never our acknowledgement.
+ for (
+ let i = 0;
+ i < steps.length && result.steps[i].clientId === activeSession.clientId;
+ i++
+ ) {
+ const expected = pending?.steps[i];
+ if (!expected && activeSession.recovering) continue;
+ if (!expected || !sameStepJson(expected.toJSON(), steps[i].toJSON()))
+ throw new ApiError(409, 'Document acknowledgement does not match the local changes');
+ }
+ confirmedVersion.current = result.documentVersion;
for (const step of steps) {
const applied = step.apply(state.current.confirmed);
if (!applied.doc) throw new Error('Invalid remote document change');
@@ -222,12 +234,41 @@ export function useDocumentCollaboration({
editor.registerPlugin(
collab({ version: recovery?.version ?? session.version, clientID: clientId }),
);
- state.current = { epoch: session.epoch, clientId, confirmed: base, snapshot: editor.state };
+ state.current = {
+ epoch: session.epoch,
+ clientId,
+ confirmed: base,
+ snapshot: editor.state,
+ recovering: Boolean(recovery),
+ };
if (recovery) {
editor.view.dispatch(tr);
state.current.snapshot = editor.state;
}
setRecoveryConflict(false);
+ if (recovery) {
+ const activeSession = state.current;
+ const saved = await flush();
+ if (cancelled || editor.isDestroyed || state.current !== activeSession || !saved) return;
+ if (sendableSteps(editor.state)) {
+ setStatus('error');
+ return;
+ }
+ // Drain the restored identity before accepting edits under a fresh one.
+ const version = getVersion(editor.state);
+ editor.unregisterPlugin('collab');
+ editor
+ .chain()
+ .setContent(activeSession.confirmed.toJSON(), { emitUpdate: false })
+ .setMeta('addToHistory', false)
+ .run();
+ editor.unregisterPlugin('history');
+ editor.registerPlugin(history());
+ activeSession.clientId = uuid();
+ activeSession.recovering = false;
+ editor.registerPlugin(collab({ version, clientID: activeSession.clientId }));
+ activeSession.snapshot = editor.state;
+ }
setReady(true);
setStatus('saved');
} catch (error) {
@@ -244,7 +285,7 @@ export function useDocumentCollaboration({
setReady(false);
if (!editor.isDestroyed) editor.unregisterPlugin('collab');
};
- }, [attempt, document.id, editor, enabled, persist, projectKey, storageKey, userId]);
+ }, [attempt, document.id, editor, enabled, flush, persist, projectKey, storageKey, userId]);
useEffect(() => {
if (!editor || !ready) return;
@@ -317,3 +358,22 @@ export function useDocumentCollaboration({
},
};
}
+
+function sameStepJson(left: unknown, right: unknown): boolean {
+ if (left === right) return true;
+ if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object')
+ return false;
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
+ const keys = Object.keys(left);
+ return (
+ keys.length === Object.keys(right).length &&
+ keys.every(
+ (key) =>
+ Object.hasOwn(right, key) &&
+ sameStepJson(
+ (left as Record<string, unknown>)[key],
+ (right as Record<string, unknown>)[key],
+ ),
+ )
+ );
+}