Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(collab): keep image size and in-flight uploads when a Markdown write lands (MUL-9786) (#11132)

Jiayuan Zhang8031fd73349a
diff --git a/apps/collab/src/collab.test.ts b/apps/collab/src/collab.test.ts
index 4603563ef5..9992ea44ac 100644
--- a/apps/collab/src/collab.test.ts
+++ b/apps/collab/src/collab.test.ts
@@ -295,6 +295,55 @@ describe("collaboration server", () => {
expect(markdown(a.document)).toBe("One\n\nTwo (Ada)");
});
+ describe("keeps what Markdown cannot express", () => {
+ const image = { type: "image", attrs: { src: "https://cdn.example.com/a.png", alt: "a", width: 800, height: 600 } };
+ const file = { type: "fileCard", attrs: { href: "https://cdn.example.com/f.pdf", filename: "f.pdf", fileSize: 12345 } };
+ const uploading = { type: "image", attrs: { src: "blob:http://local/1", uploading: true, uploadId: "u1" } };
+ const paragraph = (text: string) => ({ type: "paragraph", content: [{ type: "text", text }] });
+
+ /** Ada's editor holds media whose size and upload state live only in the
+ * Yjs document; the server's copy has caught up with it. */
+ async function editorWithMedia() {
+ resetDoc("First.\n\nLast.");
+ const a = await connect(ada);
+ codec.applyJSON(a.document, {
+ type: "doc",
+ content: [paragraph("First."), image, file, uploading, paragraph("Last.")],
+ });
+ const live = () => codec.ydocToJSON(collab.server.hocuspocus.documents.get(NAME)!);
+ await waitFor(() => JSON.stringify(live()).includes('"uploadId":"u1"'));
+ return a;
+ }
+ const blocks = (doc: Y.Doc) =>
+ codec.ydocToJSON(doc).content!.filter((block) => block.type !== "paragraph").map((block) => block.attrs);
+
+ it("in blocks an agent's edit did not touch", async () => {
+ const a = await editorWithMedia();
+ const before = markdown(a.document);
+ const result = await internal("edit", {
+ actor: agent,
+ edits: [{ old_text: "First.", new_text: "First, edited." }],
+ });
+ expect(result.status).toBe(200);
+ await waitFor(() => markdown(a.document).includes("edited"));
+ expect(blocks(a.document)).toMatchObject([image.attrs, file.attrs, uploading.attrs]);
+ expect(markdown(a.document)).toBe(before.replace("First.", "First, edited."));
+ });
+
+ it("in blocks a whole-document write did not touch", async () => {
+ const a = await editorWithMedia();
+ const result = await internal("write", {
+ actor: agent,
+ base_revision: 1,
+ base_content: markdown(a.document),
+ content: markdown(a.document).replace("Last.", "Last, rewritten."),
+ });
+ expect(result.status).toBe(200);
+ await waitFor(() => markdown(a.document).includes("rewritten"));
+ expect(blocks(a.document)).toMatchObject([image.attrs, file.attrs, uploading.attrs]);
+ });
+ });
+
it("serializes concurrent agent edits so neither is lost", async () => {
resetDoc("Alpha\n\nBeta\n\nGamma");
const [first, second] = await Promise.all([
diff --git a/apps/collab/src/documents.ts b/apps/collab/src/documents.ts
index 1c5cfa5310..be4a7b85e0 100644
--- a/apps/collab/src/documents.ts
+++ b/apps/collab/src/documents.ts
@@ -1,10 +1,10 @@
import { randomUUID } from "node:crypto";
import * as Y from "yjs";
import type { Document, Hocuspocus } from "@hocuspocus/server";
-import type { DocumentCodec } from "@multica/views/editor/schema/codec";
+import type { DocumentCodec, JSONContent } from "@multica/views/editor/schema/codec";
import type { CollabApi, StoreRequest } from "./api";
import { applyTextEdits, type EditFailure, type TextEdit } from "./edits";
-import { mergeDocuments, type MergeConflict } from "./merge";
+import { keepLiveBlocks, mergeDocuments, type MergeConflict } from "./merge";
import type { Actor } from "./ticket";
/** Close code telling a client its local copy belongs to a document the
@@ -131,7 +131,7 @@ export class DocumentStore {
// only risks the round trip changing something.
const target = stored.ystate_revision < stored.revision ? this.codec.parse(stored.content) : null;
if (target && this.codec.ydocToMarkdown(candidate) !== this.codec.serialize(target)) {
- this.codec.applyJSON(candidate, target, serverOrigin({ type: "member", id: "", name: "" }));
+ this.applyParsed(candidate, target, serverOrigin({ type: "member", id: "", name: "" }));
from = "state+catch-up";
}
}
@@ -222,7 +222,7 @@ export class DocumentStore {
}
}
if (tooLarge(this.codec.serialize(next))) return { status: "too_large", revision: state.revision };
- this.codec.applyJSON(document, next, serverOrigin(req.actor));
+ this.applyParsed(document, next, serverOrigin(req.actor));
}
return this.commit(name, document, state, req, merged);
});
@@ -245,13 +245,19 @@ export class DocumentStore {
}
const next = this.codec.parse(result.text);
if (tooLarge(this.codec.serialize(next))) return { status: "too_large", revision: state.revision };
- this.codec.applyJSON(document, next, serverOrigin(req.actor));
+ this.applyParsed(document, next, serverOrigin(req.actor));
return this.commit(name, document, state, req, false);
});
}
// ---- internals -----------------------------------------------------------
+ /** Every server-side write of content parsed from Markdown goes through
+ * here, so it keeps what Markdown cannot express (see keepLiveBlocks). */
+ private applyParsed(ydoc: Y.Doc, next: JSONContent, origin: unknown) {
+ this.codec.applyJSON(ydoc, keepLiveBlocks(this.codec, this.codec.ydocToJSON(ydoc), next), origin);
+ }
+
private async commit(
name: string,
document: Document,
@@ -387,7 +393,7 @@ export class DocumentStore {
const live = this.codec.ydocToJSON(document);
const result = mergeDocuments(this.codec, base, live, stored);
if (result.ok) {
- this.codec.applyJSON(document, result.doc, serverOrigin({ type: "member", id: "", name: "" }));
+ this.applyParsed(document, result.doc, serverOrigin({ type: "member", id: "", name: "" }));
} else {
// Keep what people are typing; the next store overwrites the stray write.
this.log.warn("stored change conflicts with live edits; keeping live", { doc: state.id, name });
diff --git a/apps/collab/src/merge.test.ts b/apps/collab/src/merge.test.ts
new file mode 100644
index 0000000000..892f6bef57
--- /dev/null
+++ b/apps/collab/src/merge.test.ts
@@ -0,0 +1,49 @@
+import "./dom";
+import { describe, expect, it } from "vitest";
+import { createDocumentCodec, type JSONContent } from "@multica/views/editor/schema/codec";
+import { keepLiveBlocks } from "./merge";
+
+const codec = createDocumentCodec();
+const p = (text: string): JSONContent => ({ type: "paragraph", content: [{ type: "text", text }] });
+const upload = (id: string): JSONContent => ({ type: "fileCard", attrs: { href: "", filename: id, uploading: true, uploadId: id } });
+const doc = (...content: JSONContent[]): JSONContent => ({ type: "doc", content });
+const names = (json: JSONContent) =>
+ json.content!.map((block) => (block.attrs?.uploading ? `upload:${block.attrs.uploadId}` : codec.serialize(doc(block))));
+
+describe("keepLiveBlocks", () => {
+ it("keeps each upload placeholder after the live block it followed", () => {
+ const live = doc(upload("u0"), p("A"), upload("u1"), p("B"), upload("u2"), upload("u3"), p("C"));
+ const next = doc(p("A"), p("B2"), p("C"), p("D"));
+ expect(names(keepLiveBlocks(codec, live, next))).toEqual([
+ "upload:u0",
+ "A",
+ "upload:u1",
+ "B2",
+ "upload:u2",
+ "upload:u3",
+ "C",
+ "D",
+ ]);
+ });
+
+ it("pairs a placeholder with the empty paragraph its Markdown parses back into", () => {
+ const live = doc(p("A"), upload("u1"), p("B"));
+ const next = codec.parse(codec.serialize(live).replace("A", "A2"));
+ expect(names(keepLiveBlocks(codec, live, next))).toEqual(["A2", "upload:u1", "B"]);
+ });
+
+ it("keeps a placeholder whose live block the writer deleted", () => {
+ const live = doc(p("A"), p("B"), upload("u1"), p("C"));
+ expect(names(keepLiveBlocks(codec, live, doc(p("A"), p("C"))))).toEqual(["A", "upload:u1", "C"]);
+ });
+
+ it("keeps the live copy of an unchanged block and takes the writer's copy of a changed one", () => {
+ const sized = (src: string): JSONContent => ({ type: "image", attrs: { src, alt: "", width: 800, height: 600 } });
+ const live = doc(sized("https://cdn.example.com/a.png"), sized("https://cdn.example.com/b.png"));
+ const next = codec.parse("![](https://cdn.example.com/a.png)\n\n![](https://cdn.example.com/c.png)");
+ const [kept, replaced] = keepLiveBlocks(codec, live, next).content!;
+ expect(kept!.attrs).toMatchObject({ src: "https://cdn.example.com/a.png", width: 800, height: 600 });
+ expect(replaced!.attrs?.src).toBe("https://cdn.example.com/c.png");
+ expect(replaced!.attrs?.width ?? null).toBeNull();
+ });
+});
diff --git a/apps/collab/src/merge.ts b/apps/collab/src/merge.ts
index b2c1aad571..969e0e695c 100644
--- a/apps/collab/src/merge.ts
+++ b/apps/collab/src/merge.ts
@@ -1,4 +1,4 @@
-import { diff3Merge } from "node-diff3";
+import { diff3Merge, diffIndices } from "node-diff3";
import type { DocumentCodec, JSONContent } from "@multica/views/editor/schema/codec";
export interface MergeConflict {
@@ -54,3 +54,35 @@ export function mergeDocuments(
if (conflicts.length > 0) return { ok: false, conflicts };
return { ok: true, doc: { type: "doc", content: merged } };
}
+
+const isPendingUpload = (block: JSONContent) =>
+ (block.type === "image" || block.type === "fileCard") && block.attrs?.uploading === true;
+
+/**
+ * Prepares a document parsed from Markdown to replace the live one.
+ *
+ * Markdown does not carry everything the live document holds: image size,
+ * file size, and placeholders for uploads still in flight. A writer working
+ * from Markdown never saw them, so its write must not remove them. Every
+ * top-level block whose Markdown is unchanged keeps its live copy. A
+ * placeholder serializes like an empty paragraph, so it pairs with the one
+ * its gap parses back into; inside a region the writer changed it is kept,
+ * on the side of the changed blocks it was on.
+ */
+export function keepLiveBlocks(codec: DocumentCodec, live: JSONContent, next: JSONContent): JSONContent {
+ const key = (block: JSONContent) => codec.serialize({ type: "doc", content: [block] });
+ const current = live.content ?? [];
+ const incoming = next.content ?? [];
+ const content: JSONContent[] = [];
+ let i = 0;
+ for (const { buffer1: [start, length], buffer2: [from, count] } of diffIndices(current.map(key), incoming.map(key))) {
+ content.push(...current.slice(i, start));
+ const replaced = current.slice(start, start + length);
+ const firstContent = replaced.findIndex((block) => !isPendingUpload(block));
+ const before = firstContent === -1 ? replaced : replaced.slice(0, firstContent);
+ content.push(...before, ...incoming.slice(from, from + count), ...replaced.slice(before.length).filter(isPendingUpload));
+ i = start + length;
+ }
+ content.push(...current.slice(i));
+ return { ...next, content };
+}