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
This commit is contained in:
bunker-admin 2026-03-27 13:46:35 -06:00
parent 078bb6e313
commit a436c494fd

View File

@ -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