From a436c494fd326d07655ba4a213a0228c2b6d0fe4 Mon Sep 17 00:00:00 2001 From: bunker-admin Date: Fri, 27 Mar 2026 13:46:35 -0600 Subject: [PATCH] Add duplication guard in collab onChange to detect and auto-fix doubled content Y.js CRDT merges can duplicate content when a client reconnects after external file modifications (e.g., API PUT while collab is active). The guard detects when content is exactly doubled and auto-trims it. Bunker Admin --- api/src/modules/docs/docs-collab.service.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/api/src/modules/docs/docs-collab.service.ts b/api/src/modules/docs/docs-collab.service.ts index 0d61ca72..48215044 100644 --- a/api/src/modules/docs/docs-collab.service.ts +++ b/api/src/modules/docs/docs-collab.service.ts @@ -257,8 +257,23 @@ const docsExtension: Extension = { return; } - // Write plaintext to disk (debounced by Hocuspocus's built-in debounce) + // Duplication guard: detect and fix content that appears to be doubled const content = yText.toString(); + if (content.length > 20) { + const half = Math.floor(content.length / 2); + const firstHalf = content.substring(0, half); + const secondHalf = content.substring(half); + if (firstHalf === secondHalf) { + logger.warn(`Docs collab: detected duplicated content in ${documentName} (${content.length} chars), fixing`); + // Replace the Y.Text with just the first half + document.transact(() => { + yText.delete(half, content.length - half); + }); + return; // The deletion triggers another onChange with the fixed content + } + } + + // Write plaintext to disk (debounced by Hocuspocus's built-in debounce) try { await docsFilesService.writeFileContent(documentName, content); // Invalidate Redis file cache