Skip to content

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

Go

fix(collab): keep both sides when a direct write conflicts with live edits (MUL-9793) (#11137)

Jiayuan Zhang9264f8614486
diff --git a/apps/collab/src/collab.test.ts b/apps/collab/src/collab.test.ts
index 9992ea44ac..f8e36fcb61 100644
--- a/apps/collab/src/collab.test.ts
+++ b/apps/collab/src/collab.test.ts
@@ -402,6 +402,38 @@ describe("collaboration server", () => {
expect(markdown(again.document)).toBe(expected);
});
+ describe("folds in a write stored while the API could not reach it", () => {
+ /** Ada has the doc open and the service holds it; an agent's write lands
+ * in the stored doc directly, before Ada's typing is saved. */
+ async function directWriteDuringLiveEdit(stored: string) {
+ resetDoc("One\n\nTwo");
+ const a = await connect(ada);
+ fake.content = stored;
+ fake.revision += 1;
+ typeInto(a.document, 1, 3, " (Ada)");
+ await waitFor(() => fake.stores.length > 0, 2000);
+ return a;
+ }
+
+ it("merging it when it changed other blocks", async () => {
+ const a = await directWriteDuringLiveEdit("One (agent)\n\nTwo");
+ const expected = "One (agent)\n\nTwo (Ada)";
+ expect(fake.content).toBe(expected);
+ expect(fake.stores.at(-1)!.message).toBeUndefined();
+ await waitFor(() => markdown(a.document) === expected);
+ });
+
+ it("keeping both copies of a block both sides changed, in a labeled version", async () => {
+ const a = await directWriteDuringLiveEdit("One\n\nTwo (agent)");
+ const expected = "One\n\nTwo (Ada)\n\nTwo (agent)";
+ expect(fake.content).toBe(expected);
+ const store = fake.stores.at(-1)!;
+ expect(store.contributors).toEqual([ada.id]);
+ expect(store.message).toMatch(/^Kept both sides of 1 conflicting edit:/);
+ await waitFor(() => markdown(a.document) === expected);
+ });
+ });
+
it("tells a client to start over when no saved state is left to merge with", async () => {
resetDoc("Original");
const a = await connect(ada);
diff --git a/apps/collab/src/documents.ts b/apps/collab/src/documents.ts
index be4a7b85e0..85638126ea 100644
--- a/apps/collab/src/documents.ts
+++ b/apps/collab/src/documents.ts
@@ -371,9 +371,9 @@ export class DocumentStore {
giveBack();
state.dirty = true;
if (attempt >= 2) throw new Error(`doc ${state.id}: store kept conflicting`);
- this.reconcile(name, document, state, result.content);
+ const note = this.reconcile(name, document, state, result.content);
state.revision = result.revision;
- return this.persist(name, document, req, attempt + 1);
+ return this.persist(name, document, note && !req.message ? { ...req, message: note } : req, attempt + 1);
}
state.revision = result.revision;
state.persisted = content;
@@ -387,18 +387,25 @@ export class DocumentStore {
return result.revision;
}
- private reconcile(name: string, document: Document, state: DocState, storedContent: string) {
+ /** Folds a change stored without this service into the live document.
+ * Its writer was already told it succeeded, so a block both sides changed
+ * keeps both copies, live first, and the returned note labels the version
+ * that saves them. */
+ private reconcile(name: string, document: Document, state: DocState, storedContent: string): string | null {
const base = this.codec.parse(state.persisted);
const stored = this.codec.parse(storedContent);
const live = this.codec.ydocToJSON(document);
const result = mergeDocuments(this.codec, base, live, stored);
+ const origin = serverOrigin({ type: "member", id: "", name: "" });
+ state.persisted = this.codec.serialize(stored);
if (result.ok) {
- 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 });
+ this.applyParsed(document, result.doc, origin);
+ return null;
}
- state.persisted = this.codec.serialize(stored);
+ this.applyParsed(document, result.both, origin);
+ const count = result.conflicts.length;
+ this.log.warn("stored change conflicts with live edits; keeping both", { doc: state.id, name, conflicts: count });
+ return `Kept both sides of ${count} conflicting edit${count === 1 ? "" : "s"}: live text first, then a change saved while live editing was unavailable`;
}
/** Shows the writing agent in everyone's presence list for a moment. */
diff --git a/apps/collab/src/merge.test.ts b/apps/collab/src/merge.test.ts
index 892f6bef57..6cbc62cb20 100644
--- a/apps/collab/src/merge.test.ts
+++ b/apps/collab/src/merge.test.ts
@@ -1,7 +1,7 @@
import "./dom";
import { describe, expect, it } from "vitest";
import { createDocumentCodec, type JSONContent } from "@multica/views/editor/schema/codec";
-import { keepLiveBlocks } from "./merge";
+import { keepLiveBlocks, mergeDocuments } from "./merge";
const codec = createDocumentCodec();
const p = (text: string): JSONContent => ({ type: "paragraph", content: [{ type: "text", text }] });
@@ -10,6 +10,31 @@ 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("mergeDocuments", () => {
+ it("merges edits to adjacent blocks", () => {
+ const result = mergeDocuments(codec, doc(p("A"), p("B"), p("C")), doc(p("A1"), p("B"), p("C")), doc(p("A"), p("B2"), p("C")));
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(names(result.doc)).toEqual(["A1", "B2", "C"]);
+ });
+
+ it("offers both sides of only the blocks both changed, current first", () => {
+ const base = doc(p("A"), p("B"), p("C"), p("D"));
+ const result = mergeDocuments(codec, base, doc(p("A1"), p("B"), p("C1"), p("D")), doc(p("A"), p("B2"), p("C2"), p("D")));
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.conflicts).toEqual([{ current: "C1", incoming: "C2" }]);
+ expect(names(result.both)).toEqual(["A1", "B2", "C1", "C2", "D"]);
+ });
+
+ it("offers both whole sides when blocks were added or removed", () => {
+ const result = mergeDocuments(codec, doc(p("A"), p("B")), doc(p("A"), p("B1")), doc(p("A"), p("B2"), p("X")));
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.conflicts).toEqual([{ current: "B1", incoming: "B2\n\nX" }]);
+ expect(names(result.both)).toEqual(["A", "B1", "B2", "X"]);
+ });
+});
+
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"));
diff --git a/apps/collab/src/merge.ts b/apps/collab/src/merge.ts
index 969e0e695c..152a0ed76d 100644
--- a/apps/collab/src/merge.ts
+++ b/apps/collab/src/merge.ts
@@ -10,7 +10,10 @@ export interface MergeConflict {
export type MergeResult =
| { ok: true; doc: JSONContent }
- | { ok: false; conflicts: MergeConflict[] };
+ /** `both` is the merge with each conflict resolved by keeping the current
+ * blocks followed by the incoming ones, for a write that cannot be sent
+ * back to its writer. */
+ | { ok: false; conflicts: MergeConflict[]; both: JSONContent };
/**
* Three-way merge of whole documents at top-level block granularity.
@@ -39,19 +42,32 @@ export function mergeDocuments(
const regions = diff3Merge(keys(current), keys(base), keys(incoming));
const merged: JSONContent[] = [];
const conflicts: MergeConflict[] = [];
- const toMarkdown = (part: string[]) =>
- codec.serialize({ type: "doc", content: part.map((key) => blocks.get(key)!) });
+ const toBlocks = (part: string[]) => part.map((key) => blocks.get(key)!);
+ const toMarkdown = (part: string[]) => codec.serialize({ type: "doc", content: toBlocks(part) });
+ const conflict = (a: string[], b: string[]) => {
+ conflicts.push({ current: toMarkdown(a), incoming: toMarkdown(b) });
+ merged.push(...toBlocks(a), ...toBlocks(b));
+ };
for (const region of regions) {
if (region.ok) {
- merged.push(...region.ok.map((key) => blocks.get(key)!));
- } else {
- conflicts.push({
- current: toMarkdown(region.conflict.a),
- incoming: toMarkdown(region.conflict.b),
- });
+ merged.push(...toBlocks(region.ok));
+ continue;
+ }
+ const { a, o, b } = region.conflict;
+ // diff3 also reports edits to adjacent blocks as one conflict. When no
+ // block was added or removed, the blocks line up and only those both
+ // sides changed differently conflict.
+ if (a.length !== o.length || b.length !== o.length) {
+ conflict(a, b);
+ continue;
+ }
+ for (let i = 0; i < o.length; i++) {
+ if (a[i] === o[i] || a[i] === b[i]) merged.push(...toBlocks([b[i]!]));
+ else if (b[i] === o[i]) merged.push(...toBlocks([a[i]!]));
+ else conflict([a[i]!], [b[i]!]);
}
}
- if (conflicts.length > 0) return { ok: false, conflicts };
+ if (conflicts.length > 0) return { ok: false, conflicts, both: { type: "doc", content: merged } };
return { ok: true, doc: { type: "doc", content: merged } };
}