Skip to content

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

Go

feat(docs): live co-editing for people and agents (MUL-9743) (#11092)

Jiayuan Zhang1f119972fc43
diff --git a/.github/ci-paths.json b/.github/ci-paths.json
index 5f2e995a6a..f10952d29d 100644
--- a/.github/ci-paths.json
+++ b/.github/ci-paths.json
@@ -3,6 +3,7 @@
".github/actions/frontend-quality/**",
"apps/web/**",
"apps/desktop/**",
+ "apps/collab/**",
"packages/**",
"server/internal/handler/testdata/quick_action_bodies.json",
"package.json",
diff --git a/apps/collab/package.json b/apps/collab/package.json
new file mode 100644
index 0000000000..1ac0fac774
--- /dev/null
+++ b/apps/collab/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "@multica/collab",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "tsx watch src/index.ts",
+ "start": "tsx src/index.ts",
+ "typecheck": "tsc --noEmit",
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "@hocuspocus/server": "^4.9.0",
+ "@multica/views": "workspace:*",
+ "happy-dom": "^21.0.4",
+ "node-diff3": "^4.0.0",
+ "tsx": "^4.21.0",
+ "y-protocols": "catalog:",
+ "yjs": "catalog:"
+ },
+ "devDependencies": {
+ "@hocuspocus/provider": "catalog:",
+ "@multica/tsconfig": "workspace:*",
+ "@types/node": "catalog:",
+ "@typescript/native": "catalog:",
+ "vitest": "catalog:"
+ }
+}
diff --git a/apps/collab/src/api.ts b/apps/collab/src/api.ts
new file mode 100644
index 0000000000..c6224ad800
--- /dev/null
+++ b/apps/collab/src/api.ts
@@ -0,0 +1,84 @@
+import type { Actor } from "./ticket";
+
+/** A stored document as the Go API holds it. */
+export interface StoredDocument {
+ workspace_id: string;
+ title: string;
+ content: string;
+ revision: number;
+ /** Last persisted Yjs state, base64, and the revision it was saved with. */
+ ystate: string | null;
+ ystate_revision: number | null;
+}
+
+export interface StoreRequest {
+ base_revision: number;
+ content: string;
+ ystate: string;
+ /** Everyone whose changes this write carries; the first is the author. */
+ contributors: Pick<Actor, "type" | "id">[];
+ title?: string;
+ message?: string;
+ action?: "edit" | "restore";
+ action_ref?: number;
+ task_id?: string;
+ /** Save only the Yjs state for the current revision; the doc is untouched. */
+ state_only?: boolean;
+}
+
+export type StoreResult =
+ | { status: "stored"; revision: number; title: string }
+ | { status: "conflict"; revision: number; content: string }
+ | { status: "gone" };
+
+export class ApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ }
+}
+
+/** Client for the Go API's internal collaboration endpoints
+ * (server/internal/handler/collab.go). */
+export class CollabApi {
+ constructor(
+ private readonly baseUrl: string,
+ private readonly secret: string,
+ ) {}
+
+ private async request(path: string, init: RequestInit = {}): Promise<Response> {
+ return fetch(`${this.baseUrl}${path}`, {
+ ...init,
+ headers: {
+ "Content-Type": "application/json",
+ "X-Collab-Secret": this.secret,
+ ...init.headers,
+ },
+ signal: AbortSignal.timeout(15_000),
+ });
+ }
+
+ async loadDoc(id: string): Promise<StoredDocument | null> {
+ const res = await this.request(`/internal/collab/docs/${encodeURIComponent(id)}`);
+ if (res.status === 404) return null;
+ if (!res.ok) throw new ApiError(`load doc ${id}: ${res.status} ${await res.text()}`, res.status);
+ return (await res.json()) as StoredDocument;
+ }
+
+ async storeDoc(id: string, body: StoreRequest): Promise<StoreResult> {
+ const res = await this.request(`/internal/collab/docs/${encodeURIComponent(id)}/store`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+ if (res.status === 404) return { status: "gone" };
+ if (res.status === 409) {
+ const data = (await res.json()) as { revision: number; content: string };
+ return { status: "conflict", revision: data.revision, content: data.content };
+ }
+ if (!res.ok) throw new ApiError(`store doc ${id}: ${res.status} ${await res.text()}`, res.status);
+ const data = (await res.json()) as { revision: number; title: string };
+ return { status: "stored", revision: data.revision, title: data.title };
+ }
+}
diff --git a/apps/collab/src/collab.test.ts b/apps/collab/src/collab.test.ts
new file mode 100644
index 0000000000..4603563ef5
--- /dev/null
+++ b/apps/collab/src/collab.test.ts
@@ -0,0 +1,432 @@
+import "./dom";
+import { createServer, type Server as HttpServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import * as Y from "yjs";
+import { HocuspocusProvider } from "@hocuspocus/provider";
+import { COLLAB_FIELD, createDocumentCodec } from "@multica/views/editor/schema/codec";
+import { COMPACT_STATE_MIN_BYTES } from "./documents";
+import { createCollabServer } from "./server";
+import { signTicket, type Actor } from "./ticket";
+
+const SECRET = "test-secret";
+const DOC_ID = "0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b";
+const NAME = `doc:${DOC_ID}`;
+const ada: Actor = { type: "member", id: "11111111-1111-1111-1111-111111111111", name: "Ada" };
+const bob: Actor = { type: "member", id: "22222222-2222-2222-2222-222222222222", name: "Bob" };
+const agent: Actor = { type: "agent", id: "33333333-3333-3333-3333-333333333333", name: "Lambda" };
+
+/** In-memory stand-in for the Go API's internal endpoints. */
+interface FakeDoc {
+ content: string;
+ revision: number;
+ ystate: string | null;
+ ystateRevision: number | null;
+ stores: { contributors: string[]; content: string; message?: string }[];
+}
+let fake: FakeDoc;
+/** When set, stores wait for it before answering. */
+let storeGate: { requested: number; release: Promise<void> } | null = null;
+let apiServer: HttpServer;
+let apiUrl = "";
+
+const codec = createDocumentCodec();
+const silent = { info() {}, warn() {}, error() {} };
+let collab: ReturnType<typeof createCollabServer>;
+let collabUrl = "";
+const providers: HocuspocusProvider[] = [];
+
+beforeAll(async () => {
+ apiServer = createServer(async (req, res) => {
+ if (req.headers["x-collab-secret"] !== SECRET) {
+ res.writeHead(401).end();
+ return;
+ }
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) chunks.push(chunk as Buffer);
+ const send = (status: number, body: unknown) => {
+ res.writeHead(status, { "Content-Type": "application/json" });
+ res.end(JSON.stringify(body));
+ };
+ if (req.method === "GET" && req.url === `/internal/collab/docs/${DOC_ID}`) {
+ return send(200, {
+ workspace_id: "ws",
+ title: "T",
+ content: fake.content,
+ revision: fake.revision,
+ ystate: fake.ystate,
+ ystate_revision: fake.ystateRevision,
+ });
+ }
+ if (req.method === "POST" && req.url === `/internal/collab/docs/${DOC_ID}/store`) {
+ const body = JSON.parse(Buffer.concat(chunks).toString());
+ if (storeGate && !body.state_only) {
+ storeGate.requested += 1;
+ await storeGate.release;
+ }
+ if (body.base_revision !== fake.revision) {
+ return send(409, { revision: fake.revision, content: fake.content });
+ }
+ if (body.state_only) {
+ fake.ystate = body.ystate;
+ fake.ystateRevision = fake.revision;
+ return send(200, { revision: fake.revision, title: "T" });
+ }
+ fake.revision += 1;
+ fake.content = body.content;
+ fake.ystate = body.ystate;
+ fake.ystateRevision = fake.revision;
+ fake.stores.push({
+ contributors: body.contributors.map((c: Actor) => c.id),
+ content: body.content,
+ message: body.message,
+ });
+ return send(200, { revision: fake.revision, title: "T" });
+ }
+ send(404, {});
+ });
+ await new Promise<void>((resolve) => apiServer.listen(0, resolve));
+ apiUrl = `http://127.0.0.1:${(apiServer.address() as AddressInfo).port}`;
+
+ collab = createCollabServer(
+ { port: 0, secret: SECRET, apiUrl, cdnDomain: "", storeDebounceMs: 100, storeMaxDebounceMs: 400 },
+ codec,
+ silent,
+ );
+ await collab.server.listen(0);
+ collabUrl = `ws://127.0.0.1:${collab.server.address.port}`;
+});
+
+afterAll(async () => {
+ await collab.server.destroy();
+ await new Promise((resolve) => apiServer.close(resolve));
+});
+
+afterEach(async () => {
+ for (const provider of providers.splice(0)) provider.destroy();
+ // Let the documents unload so every test starts from the fake API.
+ await waitFor(() => collab.server.hocuspocus.getDocumentsCount() === 0, 3000);
+});
+
+function resetDoc(content: string) {
+ fake = { content, revision: 1, ystate: null, ystateRevision: null, stores: [] };
+ storeGate = null;
+}
+
+function ticket(actor: Actor) {
+ return signTicket(
+ { document: NAME, workspaceId: "ws", actor, readOnly: false, expiresAt: Math.floor(Date.now() / 1000) + 60 },
+ SECRET,
+ );
+}
+
+async function connect(actor: Actor, opts: { document?: Y.Doc; epoch?: string } = {}) {
+ const document = opts.document ?? new Y.Doc();
+ const provider = new HocuspocusProvider({
+ url: collabUrl,
+ name: NAME,
+ document,
+ token: () => JSON.stringify({ ticket: ticket(actor), epoch: opts.epoch }),
+ });
+ providers.push(provider);
+ await waitFor(() => provider.isSynced, 3000);
+ return { provider, document };
+}
+
+async function waitFor(check: () => boolean, timeout = 3000) {
+ const start = Date.now();
+ while (!check()) {
+ if (Date.now() - start > timeout) throw new Error("timed out");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+}
+
+const markdown = (doc: Y.Doc) => codec.ydocToMarkdown(doc);
+/** Types into the text of the n-th top-level block. */
+function typeInto(doc: Y.Doc, block: number, offset: number, text: string) {
+ const element = doc.getXmlFragment(COLLAB_FIELD).get(block) as Y.XmlElement;
+ (element.get(0) as Y.XmlText).insert(offset, text);
+}
+
+async function internal(path: "write" | "edit" | "flush", body: unknown) {
+ const res = await fetch(`http://127.0.0.1:${collab.server.address.port}/internal/documents/${NAME}/${path}`, {
+ method: "POST",
+ headers: { "X-Collab-Secret": SECRET, "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ return { status: res.status, body: (await res.json()) as Record<string, any> };
+}
+
+describe("collaboration server", () => {
+ it("syncs two editors typing in the same paragraph and credits both", async () => {
+ resetDoc("Hello world\n\nSecond");
+ const a = await connect(ada);
+ const b = await connect(bob);
+ typeInto(a.document, 0, 5, ", Ada");
+ typeInto(b.document, 0, 11, "!");
+ await waitFor(() => markdown(a.document) === markdown(b.document) && markdown(a.document).includes("!"));
+ expect(markdown(a.document)).toBe("Hello, Ada world!\n\nSecond");
+ await waitFor(() => fake.stores.length > 0, 2000);
+ expect(fake.content).toBe("Hello, Ada world!\n\nSecond");
+ expect(fake.stores.at(-1)!.contributors.sort()).toEqual([ada.id, bob.id].sort());
+ });
+
+ it("applies an agent's find-and-replace edit live, as its own version", async () => {
+ resetDoc("Intro\n\nStatus: draft\n\nOutro");
+ const a = await connect(ada);
+ typeInto(a.document, 0, 5, " (Ada)");
+ const result = await internal("edit", {
+ actor: agent,
+ edits: [{ old_text: "Status: draft", new_text: "Status: approved" }],
+ message: "approve",
+ });
+ expect(result.status).toBe(200);
+ await waitFor(() => markdown(a.document).includes("approved"));
+ expect(markdown(a.document)).toBe("Intro (Ada)\n\nStatus: approved\n\nOutro");
+ // Ada's pending typing is stored first, under her name; the agent's edit
+ // is a version of its own.
+ const [human, agentStore] = fake.stores.slice(-2);
+ expect(human!.contributors).toEqual([ada.id]);
+ expect(human!.content).toBe("Intro (Ada)\n\nStatus: draft\n\nOutro");
+ expect(agentStore!.contributors).toEqual([agent.id]);
+ expect(agentStore!.message).toBe("approve");
+ // Editors see the agent in their presence list while it writes.
+ const users = () => [...a.provider.awareness!.getStates().values()].map((s) => s.user?.name);
+ await waitFor(() => users().includes(agent.name));
+ });
+
+ it("credits whoever typed while a save was in flight in the next save", async () => {
+ resetDoc("Alpha\n\nBeta");
+ let release!: () => void;
+ storeGate = { requested: 0, release: new Promise<void>((resolve) => (release = resolve)) };
+ const gate = storeGate;
+ const a = await connect(ada);
+ const b = await connect(bob);
+ typeInto(a.document, 0, 5, " by Ada");
+ await waitFor(() => gate.requested === 1, 2000);
+ typeInto(b.document, 1, 4, " by Bob");
+ await waitFor(() => markdown(a.document).includes("by Bob"));
+ release();
+ await waitFor(() => fake.stores.some((store) => store.content.includes("by Bob")), 3000);
+ const bobsSave = fake.stores.find((store) => store.content.includes("by Bob"))!;
+ expect(fake.stores[0]!.contributors).toEqual([ada.id]);
+ expect(bobsSave.contributors).toContain(bob.id);
+ });
+
+ it("refuses an edit that would make the doc too large, leaving the live copy alone", async () => {
+ resetDoc("Short");
+ const a = await connect(ada);
+ const result = await internal("edit", {
+ actor: agent,
+ edits: [{ old_text: "Short", new_text: "x".repeat((2 << 20) + 1) }],
+ });
+ expect(result.status).toBe(413);
+ expect(result.body.status).toBe("too_large");
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ expect(markdown(a.document)).toBe("Short");
+ expect(fake.content).toBe("Short");
+ expect(fake.stores).toEqual([]);
+ });
+
+ it("rejects an edit whose quoted text someone else already changed", async () => {
+ resetDoc("Status: draft");
+ const a = await connect(ada);
+ typeInto(a.document, 0, 13, " v2");
+ await waitFor(() => markdown(a.document) === "Status: draft v2");
+ const result = await internal("edit", {
+ actor: agent,
+ edits: [{ old_text: "Status: draft\n", new_text: "x" }],
+ });
+ expect(result.status).toBe(409);
+ expect(result.body.error).toBe("edit_failed");
+ expect(result.body.failure.reason).toBe("not_found");
+ expect(result.body.content).toBe("Status: draft v2");
+ });
+
+ it("merges a whole-document write from a stale base around live edits", async () => {
+ resetDoc("One\n\nTwo\n\nThree");
+ const a = await connect(ada);
+ typeInto(a.document, 2, 5, " (live)");
+ await waitFor(() => markdown(a.document).includes("live"));
+ const result = await internal("write", {
+ actor: agent,
+ base_revision: 1,
+ base_content: "One\n\nTwo\n\nThree",
+ content: "One (agent)\n\nTwo\n\nThree",
+ });
+ expect(result.status).toBe(200);
+ expect(result.body.merged).toBe(true);
+ await waitFor(() => markdown(a.document).includes("agent"));
+ expect(markdown(a.document)).toBe("One (agent)\n\nTwo\n\nThree (live)");
+ expect(fake.content).toBe("One (agent)\n\nTwo\n\nThree (live)");
+ });
+
+ it("merges a stale write to formatted text nobody else touched", async () => {
+ const original = "**Name check**: see [Kaon AI](https://kaon.ai)\n\nTwo\n\nThree";
+ resetDoc(original);
+ const a = await connect(ada);
+ typeInto(a.document, 2, 5, " (live)");
+ await waitFor(() => markdown(a.document).includes("live"));
+ const result = await internal("write", {
+ actor: agent,
+ base_revision: 1,
+ base_content: original,
+ content: original.replace("**Name check**", "**Name check (done)**"),
+ });
+ expect(result.status).toBe(200);
+ expect(result.body.merged).toBe(true);
+ expect(fake.content).toBe("**Name check (done)**: see [Kaon AI](https://kaon.ai)\n\nTwo\n\nThree (live)");
+ });
+
+ it("refuses a whole-document write that collides with a live edit", async () => {
+ resetDoc("One\n\nTwo");
+ const a = await connect(ada);
+ typeInto(a.document, 1, 3, " (Ada)");
+ await waitFor(() => markdown(a.document).includes("Ada"));
+ const result = await internal("write", {
+ actor: agent,
+ base_revision: 1,
+ base_content: "One\n\nTwo",
+ content: "One\n\nTwo (agent)",
+ });
+ expect(result.status).toBe(409);
+ expect(result.body.error).toBe("merge_conflict");
+ expect(result.body.conflicts).toEqual([{ current: "Two (Ada)", incoming: "Two (agent)" }]);
+ expect(markdown(a.document)).toBe("One\n\nTwo (Ada)");
+ });
+
+ it("serializes concurrent agent edits so neither is lost", async () => {
+ resetDoc("Alpha\n\nBeta\n\nGamma");
+ const [first, second] = await Promise.all([
+ internal("edit", { actor: agent, edits: [{ old_text: "Alpha", new_text: "Alpha 1" }] }),
+ internal("edit", { actor: { ...agent, id: "44444444-4444-4444-4444-444444444444", name: "Kappa" }, edits: [{ old_text: "Gamma", new_text: "Gamma 2" }] }),
+ ]);
+ expect(first.status).toBe(200);
+ expect(second.status).toBe(200);
+ expect(fake.content).toBe("Alpha 1\n\nBeta\n\nGamma 2");
+ expect(fake.stores.map((s) => s.contributors)).toEqual([
+ [agent.id],
+ ["44444444-4444-4444-4444-444444444444"],
+ ]);
+ });
+
+ it("reuses the saved state on reload instead of rebuilding", async () => {
+ resetDoc("Saved text");
+ const a = await connect(ada);
+ typeInto(a.document, 0, 10, " more");
+ await waitFor(() => fake.content === "Saved text more", 2000);
+ const epoch = a.document.getMap("meta").get("epoch");
+ a.provider.destroy();
+ await waitFor(() => collab.server.hocuspocus.getDocumentsCount() === 0);
+
+ // Same Y.Doc reconnects: no duplicated blocks, same epoch.
+ const again = await connect(ada, { document: a.document, epoch: epoch as string });
+ expect(markdown(again.document)).toBe("Saved text more");
+ expect(again.document.getMap("meta").get("epoch")).toBe(epoch);
+ });
+
+ it("catches up on a write made while it was down and keeps edits made offline", async () => {
+ resetDoc("First\n\nSecond");
+ const a = await connect(ada);
+ const epoch = a.document.getMap("meta").get("epoch") as string;
+ a.provider.destroy();
+ await waitFor(() => collab.server.hocuspocus.getDocumentsCount() === 0);
+
+ // While the service is unavailable an agent's write lands directly in the
+ // stored doc, and Ada keeps typing in her open editor.
+ fake.content = "First (agent)\n\nSecond";
+ fake.revision += 1;
+ typeInto(a.document, 1, 6, " (Ada offline)");
+
+ const back = await connect(ada, { document: a.document, epoch });
+ const watcher = await connect(bob);
+ const expected = "First (agent)\n\nSecond (Ada offline)";
+ await waitFor(() => markdown(back.document) === expected && markdown(watcher.document) === expected);
+ expect(back.document.getMap("meta").get("epoch")).toBe(epoch);
+ await waitFor(() => fake.content === expected, 2000);
+
+ // The caught-up state was saved, so a later load does not replay it.
+ back.provider.destroy();
+ watcher.provider.destroy();
+ await waitFor(() => collab.server.hocuspocus.getDocumentsCount() === 0);
+ const again = await connect(ada, { document: a.document, epoch });
+ expect(markdown(again.document)).toBe(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);
+ const epoch = a.document.getMap("meta").get("epoch") as string;
+ a.provider.destroy();
+ await waitFor(() => collab.server.hocuspocus.getDocumentsCount() === 0);
+
+ // The saved state is gone (restored from a backup without it), so the
+ // service rebuilds from Markdown under a new epoch.
+ fake.content = "Rewritten elsewhere";
+ fake.revision += 1;
+ fake.ystate = null;
+ fake.ystateRevision = null;
+
+ const reasons: string[] = [];
+ const stale = new HocuspocusProvider({
+ url: collabUrl,
+ name: NAME,
+ document: a.document,
+ token: () => JSON.stringify({ ticket: ticket(ada), epoch }),
+ // A per-document close on a shared socket arrives with the server's
+ // reason; the close code stays 1000.
+ onClose: ({ event }) => reasons.push(event.reason),
+ });
+ providers.push(stale);
+ await waitFor(() => reasons.includes("document-reset"));
+ stale.destroy();
+ expect(fake.content).toBe("Rewritten elsewhere");
+
+ const fresh = await connect(ada);
+ expect(markdown(fresh.document)).toBe("Rewritten elsewhere");
+ });
+
+ it("flushes pending edits so a reader sees the live text", async () => {
+ resetDoc("Before");
+ const a = await connect(ada);
+ typeInto(a.document, 0, 6, " after");
+ await waitFor(() => collab.store !== undefined);
+ const result = await internal("flush", {});
+ expect(result.body.loaded).toBe(true);
+ expect(fake.content).toBe("Before after");
+ });
+
+ it("does not serialize or store a document nobody changed since its last save", async () => {
+ resetDoc("Quiet");
+ const a = await connect(ada);
+ typeInto(a.document, 0, 5, " doc");
+ await internal("flush", {});
+ const stores = fake.stores.length;
+ const serialize = vi.spyOn(codec, "ydocToMarkdown");
+ try {
+ await internal("flush", {});
+ await internal("flush", {});
+ expect(serialize).not.toHaveBeenCalled();
+ expect(fake.stores.length).toBe(stores);
+ } finally {
+ serialize.mockRestore();
+ }
+ typeInto(a.document, 0, 9, "!");
+ await internal("flush", {});
+ expect(fake.content).toBe("Quiet doc!");
+ });
+
+ it("rebuilds an oversized saved state from Markdown on load", async () => {
+ resetDoc("Small doc");
+ const bloated = codec.createYDoc("Small doc");
+ bloated.getMap("meta").set("epoch", "old-epoch");
+ bloated.getMap("history").set("weight", "x".repeat(COMPACT_STATE_MIN_BYTES + 1));
+ fake.ystate = Buffer.from(Y.encodeStateAsUpdate(bloated)).toString("base64");
+ fake.ystateRevision = fake.revision;
+
+ const a = await connect(ada);
+ expect(markdown(a.document)).toBe("Small doc");
+ expect(a.document.getMap("meta").get("epoch")).not.toBe("old-epoch");
+ expect(Buffer.from(fake.ystate!, "base64").byteLength).toBeLessThan(10_000);
+ });
+});
diff --git a/apps/collab/src/config.ts b/apps/collab/src/config.ts
new file mode 100644
index 0000000000..c01afacfe0
--- /dev/null
+++ b/apps/collab/src/config.ts
@@ -0,0 +1,33 @@
+/** Each live doc lives in this process's memory, so the service runs as one
+ * replica: a second one would hold its own copy of the same doc. Scaling out
+ * needs Hocuspocus's Redis extension or routing by doc id first. */
+export interface CollabConfig {
+ port: number;
+ /** Shared with the Go API: signs editor tickets and authenticates the
+ * internal calls in both directions. */
+ secret: string;
+ /** Base URL of the Go API's internal collaboration endpoints. */
+ apiUrl: string;
+ cdnDomain: string;
+ /** Quiet period before a changed document is written back. Every store
+ * rewrites the doc, its version and a revision in Postgres. Agents' reads
+ * and every API write flush the live doc first, so they never wait on it. */
+ storeDebounceMs: number;
+ /** Longest a continuously edited document goes unsaved. */
+ storeMaxDebounceMs: number;
+}
+
+export function loadConfig(env: NodeJS.ProcessEnv = process.env): CollabConfig {
+ const secret = env.COLLAB_SECRET?.trim() ?? "";
+ const apiUrl = env.MULTICA_API_URL?.trim().replace(/\/+$/, "") ?? "";
+ if (!secret) throw new Error("COLLAB_SECRET is required");
+ if (!apiUrl) throw new Error("MULTICA_API_URL is required");
+ return {
+ port: Number(env.COLLAB_PORT || 8095),
+ secret,
+ apiUrl,
+ cdnDomain: env.MULTICA_CDN_DOMAIN?.trim() ?? "",
+ storeDebounceMs: Number(env.COLLAB_STORE_DEBOUNCE_MS || 5000),
+ storeMaxDebounceMs: Number(env.COLLAB_STORE_MAX_DEBOUNCE_MS || 30000),
+ };
+}
diff --git a/apps/collab/src/documents.ts b/apps/collab/src/documents.ts
new file mode 100644
index 0000000000..1c5cfa5310
--- /dev/null
+++ b/apps/collab/src/documents.ts
@@ -0,0 +1,417 @@
+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 { CollabApi, StoreRequest } from "./api";
+import { applyTextEdits, type EditFailure, type TextEdit } from "./edits";
+import { mergeDocuments, type MergeConflict } from "./merge";
+import type { Actor } from "./ticket";
+
+/** Close code telling a client its local copy belongs to a document the
+ * server has since rebuilt from Markdown: it must start over from the
+ * server's copy, because merging the two histories would duplicate every
+ * block. */
+export const RESET_CLOSE_CODE = 4409;
+const EPOCH_KEY = "epoch";
+/** The API refuses to store more Markdown than this (docContentMaxSize). */
+export const MAX_CONTENT_BYTES = 2 << 20;
+const META_MAP = "meta";
+/** A saved Yjs state keeps the id of everything ever typed, so it outgrows
+ * the Markdown it holds. Past both limits it is rebuilt from the Markdown on
+ * load, before it nears what the API accepts in one store. */
+export const COMPACT_STATE_MIN_BYTES = 1 << 20;
+export const COMPACT_STATE_RATIO = 4;
+
+export function parseDocumentName(name: string): { type: "doc"; id: string } | null {
+ const match = /^doc:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.exec(name);
+ return match ? { type: "doc", id: match[1]!.toLowerCase() } : null;
+}
+
+export function documentEpoch(doc: Y.Doc): string | undefined {
+ return doc.getMap(META_MAP).get(EPOCH_KEY) as string | undefined;
+}
+
+/** Transaction origin for changes the server makes itself. Hocuspocus does
+ * not schedule a store for it; the caller persists explicitly. */
+const serverOrigin = (actor: Actor) => ({ source: "local" as const, skipStoreHooks: true, context: { actor } });
+
+interface DocState {
+ id: string;
+ /** Stored revision the live document was last persisted as. */
+ revision: number;
+ /** Canonical Markdown of that revision. */
+ persisted: string;
+ /** The stored Markdown exactly as loaded, until the first change: agents
+ * quote text from it, and it can differ from the canonical form. */
+ loadedRaw: string | null;
+ /** Editors whose changes are not persisted yet. */
+ contributors: Map<string, Actor>;
+ /** Changed since the last store. Serializing the document is the costly
+ * part of a store, and reads flush documents nobody has touched. */
+ dirty: boolean;
+ /** Serializes persistence and server-side writes per document. */
+ queue: Promise<unknown>;
+}
+
+export interface WriteRequest {
+ actor: Actor;
+ /** Stored revision and content the writer based `content` on. */
+ base_revision?: number;
+ base_content?: string;
+ content?: string;
+ title?: string;
+ message?: string;
+ action?: "edit" | "restore";
+ action_ref?: number;
+ task_id?: string;
+}
+
+export interface EditRequest {
+ actor: Actor;
+ edits: TextEdit[];
+ message?: string;
+ task_id?: string;
+}
+
+export type WriteResult =
+ | { status: "ok"; revision: number; content: string; title: string; merged: boolean }
+ | { status: "conflict"; revision: number; content: string; conflicts: MergeConflict[] }
+ | { status: "edit_failed"; revision: number; content: string; failure: EditFailure }
+ | { status: "too_large"; revision: number }
+ | { status: "gone" };
+
+class GoneError extends Error {}
+
+interface Logger {
+ info(msg: string, fields?: Record<string, unknown>): void;
+ warn(msg: string, fields?: Record<string, unknown>): void;
+}
+
+export class DocumentStore {
+ private readonly states = new Map<string, DocState>();
+ private readonly agentPresence = new Map<string, NodeJS.Timeout>();
+ hocuspocus!: Hocuspocus;
+
+ constructor(
+ private readonly api: CollabApi,
+ private readonly codec: DocumentCodec,
+ private readonly log: Logger,
+ ) {}
+
+ // ---- Hocuspocus hooks ----------------------------------------------------
+
+ /** Builds the live document from the saved Yjs state, bringing it up to
+ * the stored Markdown when the doc was written without this service (it
+ * was down, or an older API instance wrote during a deploy). Clients that
+ * kept editing offline still share that state's history, so their edits
+ * merge in. Only without a usable saved state is the document rebuilt
+ * from Markdown under a new epoch, which resets every client; that is also
+ * how an oversized state is compacted. */
+ async load(name: string): Promise<Uint8Array> {
+ const parsed = parseDocumentName(name);
+ if (!parsed) throw new Error(`unknown document ${name}`);
+ const stored = await this.api.loadDoc(parsed.id);
+ if (!stored) throw new GoneError(`doc ${parsed.id} not found`);
+
+ let ydoc: Y.Doc | null = null;
+ let from = "markdown";
+ const state = stored.ystate ? Buffer.from(stored.ystate, "base64") : null;
+ const oversized =
+ state !== null &&
+ state.byteLength > COMPACT_STATE_MIN_BYTES &&
+ state.byteLength > COMPACT_STATE_RATIO * Buffer.byteLength(stored.content, "utf8");
+ if (oversized) from = "compacted";
+ if (state && !oversized && stored.ystate_revision !== null && stored.ystate_revision <= stored.revision) {
+ const candidate = new Y.Doc();
+ Y.applyUpdate(candidate, state);
+ if (documentEpoch(candidate)) {
+ ydoc = candidate;
+ from = "state";
+ // A state saved with this revision is the doc; re-parsing its Markdown
+ // 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: "" }));
+ from = "state+catch-up";
+ }
+ }
+ }
+ if (!ydoc) {
+ ydoc = this.codec.createYDoc(stored.content);
+ ydoc.getMap(META_MAP).set(EPOCH_KEY, randomUUID());
+ }
+ if (from !== "state" || stored.ystate_revision !== stored.revision) {
+ // Save the state now: loading again would otherwise redo the catch-up
+ // or rebuild with new Yjs items and duplicate text for clients that
+ // already hold this one.
+ const saved = await this.api.storeDoc(parsed.id, {
+ base_revision: stored.revision,
+ content: stored.content,
+ ystate: Buffer.from(Y.encodeStateAsUpdate(ydoc)).toString("base64"),
+ contributors: [],
+ state_only: true,
+ });
+ if (saved.status === "gone") throw new GoneError(`doc ${parsed.id} not found`);
+ if (saved.status === "conflict") throw new Error(`doc ${parsed.id} changed while loading`);
+ }
+ this.states.set(name, {
+ id: parsed.id,
+ revision: stored.revision,
+ persisted: this.codec.ydocToMarkdown(ydoc),
+ loadedRaw: stored.content,
+ contributors: new Map(),
+ dirty: false,
+ queue: Promise.resolve(),
+ });
+ this.log.info("loaded", { doc: parsed.id, revision: stored.revision, from, state_bytes: state?.byteLength ?? 0 });
+ return Y.encodeStateAsUpdate(ydoc);
+ }
+
+ noteChange(name: string, actor: Actor | undefined) {
+ const state = this.states.get(name);
+ if (!state || !actor) return;
+ state.contributors.set(`${actor.type}:${actor.id}`, actor);
+ state.loadedRaw = null;
+ state.dirty = true;
+ }
+
+ async autosave(name: string, document: Document): Promise<void> {
+ if (!this.states.has(name)) return;
+ await this.exclusive(name, () => this.persist(name, document, {}));
+ }
+
+ forget(name: string) {
+ this.states.delete(name);
+ this.lastTitle.delete(name);
+ clearTimeout(this.agentPresence.get(name));
+ this.agentPresence.delete(name);
+ }
+
+ // ---- Server-side writes (agents, CLI, API) -------------------------------
+
+ /** Persists pending editor changes now, so a reader sees the live text. */
+ async flush(name: string): Promise<{ loaded: boolean; revision?: number }> {
+ const document = this.hocuspocus.documents.get(name);
+ if (!document || document.isLoading || !this.states.has(name)) return { loaded: false };
+ const revision = await this.exclusive(name, () => this.persist(name, document, {}));
+ return { loaded: true, revision };
+ }
+
+ /** Whole-document write: three-way merged into the live document. */
+ write(name: string, req: WriteRequest): Promise<WriteResult> {
+ return this.withDocument(name, req.actor, async (document, state) => {
+ let merged = false;
+ if (req.content !== undefined) {
+ const current = this.codec.ydocToJSON(document);
+ const incoming = this.codec.parse(req.content);
+ let next = incoming;
+ if (req.action !== "restore" && req.base_content !== undefined) {
+ const base = this.codec.parse(req.base_content);
+ if (this.codec.serialize(base) !== this.codec.serialize(current)) {
+ const result = mergeDocuments(this.codec, base, current, incoming);
+ if (!result.ok) {
+ return {
+ status: "conflict",
+ revision: state.revision,
+ content: this.codec.serialize(current),
+ conflicts: result.conflicts,
+ };
+ }
+ next = result.doc;
+ merged = true;
+ }
+ }
+ if (tooLarge(this.codec.serialize(next))) return { status: "too_large", revision: state.revision };
+ this.codec.applyJSON(document, next, serverOrigin(req.actor));
+ }
+ return this.commit(name, document, state, req, merged);
+ });
+ }
+
+ /** Find-and-replace edits applied against the live text. */
+ edit(name: string, req: EditRequest): Promise<WriteResult> {
+ return this.withDocument(name, req.actor, async (document, state) => {
+ const current = this.codec.ydocToMarkdown(document);
+ let result = applyTextEdits(current, req.edits);
+ // Nothing changed since load, and the agent quoted the stored text
+ // verbatim where it differs from the canonical form.
+ if (!result.ok && state.loadedRaw !== null && current === state.persisted) {
+ const raw = applyTextEdits(state.loadedRaw, req.edits);
+ if (raw.ok) result = raw;
+ }
+ if (!result.ok) {
+ const { ok: _ok, ...failure } = result;
+ return { status: "edit_failed", revision: state.revision, content: current, failure };
+ }
+ 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));
+ return this.commit(name, document, state, req, false);
+ });
+ }
+
+ // ---- internals -----------------------------------------------------------
+
+ private async commit(
+ name: string,
+ document: Document,
+ state: DocState,
+ req: { actor: Actor; title?: string; message?: string; action?: "edit" | "restore"; action_ref?: number; task_id?: string },
+ merged: boolean,
+ ): Promise<WriteResult> {
+ this.showAgentPresence(name, document, req.actor);
+ const stored = await this.persist(name, document, req);
+ return {
+ status: "ok",
+ revision: stored,
+ content: state.persisted,
+ title: this.lastTitle.get(name) ?? "",
+ merged,
+ };
+ }
+
+ private readonly lastTitle = new Map<string, string>();
+
+ /** Runs `fn` on the loaded document with its queue held. Pending editor
+ * changes are persisted first, so the write gets a version of its own. */
+ private async withDocument(
+ name: string,
+ actor: Actor,
+ fn: (document: Document, state: DocState) => Promise<WriteResult>,
+ ): Promise<WriteResult> {
+ let connection;
+ try {
+ connection = await this.hocuspocus.openDirectConnection(name, { actor });
+ } catch (error) {
+ if (error instanceof GoneError) return { status: "gone" };
+ throw error;
+ }
+ try {
+ const document = connection.document!;
+ return await this.exclusive(name, async () => {
+ const state = this.states.get(name)!;
+ await this.persist(name, document, {});
+ return fn(document, state);
+ });
+ } catch (error) {
+ if (error instanceof GoneError) return { status: "gone" };
+ throw error;
+ } finally {
+ // Outside the queue: disconnecting runs the store hook, which queues.
+ await connection.disconnect();
+ }
+ }
+
+ private exclusive<T>(name: string, fn: () => Promise<T>): Promise<T> {
+ const state = this.states.get(name);
+ if (!state) return fn();
+ const run = state.queue.then(fn, fn);
+ state.queue = run.catch(() => undefined);
+ return run;
+ }
+
+ /** Writes the live document back to the API when it changed, or when the
+ * request carries a title, message or action of its own. */
+ private async persist(
+ name: string,
+ document: Document,
+ req: { actor?: Actor; title?: string; message?: string; action?: "edit" | "restore"; action_ref?: number; task_id?: string },
+ attempt = 0,
+ ): Promise<number> {
+ const state = this.states.get(name);
+ if (!state) throw new GoneError(name);
+ const explicit = req.actor !== undefined;
+ const own = req.title !== undefined || !!req.action || !!req.message;
+ if (!explicit && !own && !state.dirty) return state.revision;
+ state.dirty = false;
+ const content = this.codec.ydocToMarkdown(document);
+ if (content === state.persisted && !own) return state.revision;
+ // Taken now, not cleared after the store: someone typing while it is in
+ // flight must be credited in the next one.
+ const taken = explicit ? null : state.contributors;
+ if (taken) state.contributors = new Map();
+ const giveBack = () => {
+ if (!taken) return;
+ for (const [key, actor] of taken) if (!state.contributors.has(key)) state.contributors.set(key, actor);
+ };
+ const contributors = explicit ? [req.actor!] : [...taken!.values()];
+ const body: StoreRequest = {
+ base_revision: state.revision,
+ content,
+ ystate: Buffer.from(Y.encodeStateAsUpdate(document)).toString("base64"),
+ contributors: contributors.map(({ type, id }) => ({ type, id })),
+ ...(req.title !== undefined ? { title: req.title } : {}),
+ ...(req.message ? { message: req.message } : {}),
+ ...(req.action ? { action: req.action } : {}),
+ ...(req.action_ref ? { action_ref: req.action_ref } : {}),
+ ...(req.task_id ? { task_id: req.task_id } : {}),
+ };
+ let result;
+ try {
+ result = await this.api.storeDoc(state.id, body);
+ } catch (error) {
+ giveBack();
+ state.dirty = true;
+ throw error;
+ }
+ if (result.status === "gone") {
+ this.hocuspocus.closeConnections(name);
+ throw new GoneError(name);
+ }
+ if (result.status === "conflict") {
+ // The stored doc moved without this service (an older API instance
+ // during a deploy, or a write while the service was down). Fold that
+ // change into the live document and try again.
+ giveBack();
+ state.dirty = true;
+ if (attempt >= 2) throw new Error(`doc ${state.id}: store kept conflicting`);
+ this.reconcile(name, document, state, result.content);
+ state.revision = result.revision;
+ return this.persist(name, document, req, attempt + 1);
+ }
+ state.revision = result.revision;
+ state.persisted = content;
+ state.loadedRaw = null;
+ this.lastTitle.set(name, result.title);
+ this.log.info("stored", {
+ doc: state.id,
+ revision: result.revision,
+ contributors: body.contributors.map((c) => `${c.type}:${c.id}`),
+ });
+ return result.revision;
+ }
+
+ private reconcile(name: string, document: Document, state: DocState, storedContent: string) {
+ 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);
+ if (result.ok) {
+ this.codec.applyJSON(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 });
+ }
+ state.persisted = this.codec.serialize(stored);
+ }
+
+ /** Shows the writing agent in everyone's presence list for a moment. */
+ private showAgentPresence(name: string, document: Document, actor: Actor) {
+ if (actor.type !== "agent") return;
+ // Not setLocalStateField: it is a no-op while the local state is null,
+ // which is how Hocuspocus leaves the server's own awareness.
+ document.awareness.setLocalState({
+ user: { name: actor.name, color: "#7c3aed", kind: "agent", id: actor.id },
+ });
+ clearTimeout(this.agentPresence.get(name));
+ this.agentPresence.set(
+ name,
+ setTimeout(() => {
+ this.agentPresence.delete(name);
+ if (!document.isDestroyed) document.awareness.setLocalState(null);
+ }, 5000),
+ );
+ }
+}
+
+const tooLarge = (markdown: string) => Buffer.byteLength(markdown, "utf8") > MAX_CONTENT_BYTES;
diff --git a/apps/collab/src/dom.ts b/apps/collab/src/dom.ts
new file mode 100644
index 0000000000..0eee4c9b65
--- /dev/null
+++ b/apps/collab/src/dom.ts
@@ -0,0 +1,24 @@
+/**
+ * A DOM for the Markdown codec. @tiptap/markdown parses HTML found in
+ * Markdown (raw HTML, and the file-card divs preprocessMarkdown emits) only
+ * when `window.DOMParser` exists, and otherwise keeps it as literal text — so
+ * without this the server would build a different document than a browser
+ * does from the same Markdown. Import before anything that touches Tiptap.
+ */
+import { Window } from "happy-dom";
+
+const win = new Window();
+const globals = globalThis as Record<string, unknown>;
+for (const key of [
+ "DOMParser",
+ "Node",
+ "Element",
+ "HTMLElement",
+ "Text",
+ "DocumentFragment",
+ "XMLSerializer",
+] as const) {
+ globals[key] ??= win[key];
+}
+globals.window ??= win;
+globals.document ??= win.document;
diff --git a/apps/collab/src/edits.ts b/apps/collab/src/edits.ts
new file mode 100644
index 0000000000..b1ec291dde
--- /dev/null
+++ b/apps/collab/src/edits.ts
@@ -0,0 +1,43 @@
+export interface TextEdit {
+ old_text: string;
+ new_text: string;
+ replace_all?: boolean;
+}
+
+export type EditFailure =
+ | { reason: "not_found"; index: number }
+ | { reason: "ambiguous"; index: number; matches: number }
+ | { reason: "empty"; index: number };
+
+export type EditResult = { ok: true; text: string } | ({ ok: false } & EditFailure);
+
+function countOccurrences(text: string, needle: string): number {
+ let count = 0;
+ for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + needle.length)) {
+ count++;
+ }
+ return count;
+}
+
+/**
+ * Applies find-and-replace edits in order. Each `old_text` must occur exactly
+ * once (or at least once with `replace_all`) in the text as the previous
+ * edits left it. This is what lets an agent edit a document others are
+ * changing: the quoted text is the base, so the edit lands wherever that text
+ * now is and fails only when someone changed that very text.
+ */
+export function applyTextEdits(text: string, edits: TextEdit[]): EditResult {
+ let result = text;
+ for (const [index, edit] of edits.entries()) {
+ if (!edit.old_text) return { ok: false, reason: "empty", index };
+ const matches = countOccurrences(result, edit.old_text);
+ if (matches === 0) return { ok: false, reason: "not_found", index };
+ if (matches > 1 && !edit.replace_all) {
+ return { ok: false, reason: "ambiguous", index, matches };
+ }
+ result = edit.replace_all
+ ? result.split(edit.old_text).join(edit.new_text)
+ : result.replace(edit.old_text, () => edit.new_text);
+ }
+ return { ok: true, text: result };
+}
diff --git a/apps/collab/src/index.ts b/apps/collab/src/index.ts
new file mode 100644
index 0000000000..6713190da6
--- /dev/null
+++ b/apps/collab/src/index.ts
@@ -0,0 +1,42 @@
+import "./dom";
+import { createDocumentCodec } from "@multica/views/editor/schema/codec";
+import { loadConfig } from "./config";
+import { createCollabServer, type Logger } from "./server";
+
+const write =
+ (level: string) =>
+ (msg: string, fields: Record<string, unknown> = {}) =>
+ console.log(JSON.stringify({ time: new Date().toISOString(), level, msg, ...fields }));
+const log: Logger = { info: write("info"), warn: write("warn"), error: write("error") };
+
+const config = loadConfig();
+const { server } = createCollabServer(
+ config,
+ createDocumentCodec({ cdnDomain: config.cdnDomain }),
+ log,
+);
+await server.listen();
+log.info("collab listening", { port: config.port, api: config.apiUrl });
+
+/** Long enough to store every open doc; a stuck store must not block a deploy. */
+const SHUTDOWN_TIMEOUT_MS = 15_000;
+let stopping = false;
+for (const signal of ["SIGTERM", "SIGINT"] as const) {
+ process.on(signal, () => {
+ if (stopping) return;
+ stopping = true;
+ log.info("collab stopping", { signal, documents: server.hocuspocus.getDocumentsCount() });
+ setTimeout(() => {
+ log.warn("collab stop timed out", { documents: server.hocuspocus.getDocumentsCount() });
+ process.exit(1);
+ }, SHUTDOWN_TIMEOUT_MS).unref();
+ // Closes every connection and stores what editors typed before exiting.
+ server.destroy().then(
+ () => process.exit(0),
+ (error: unknown) => {
+ log.error("collab stop failed", { error: String(error) });
+ process.exit(1);
+ },
+ );
+ });
+}
diff --git a/apps/collab/src/merge.ts b/apps/collab/src/merge.ts
new file mode 100644
index 0000000000..b2c1aad571
--- /dev/null
+++ b/apps/collab/src/merge.ts
@@ -0,0 +1,56 @@
+import { diff3Merge } from "node-diff3";
+import type { DocumentCodec, JSONContent } from "@multica/views/editor/schema/codec";
+
+export interface MergeConflict {
+ /** The live document's version of the contested blocks, as Markdown. */
+ current: string;
+ /** The writer's version of the same blocks, as Markdown. */
+ incoming: string;
+}
+
+export type MergeResult =
+ | { ok: true; doc: JSONContent }
+ | { ok: false; conflicts: MergeConflict[] };
+
+/**
+ * Three-way merge of whole documents at top-level block granularity.
+ *
+ * `base` is what the writer read, `current` is the live document, `incoming`
+ * is what the writer wants. Blocks only one side changed are taken from that
+ * side; a block both sides changed differently is a conflict, and the writer
+ * has to re-read and retry. Each block is compared by its own serialized
+ * Markdown, not line by line: the live document and freshly parsed Markdown
+ * describe the same block with different field order and default attributes,
+ * and formatting the serializer normalizes away is not a change.
+ */
+export function mergeDocuments(
+ codec: DocumentCodec,
+ base: JSONContent,
+ current: JSONContent,
+ incoming: JSONContent,
+): MergeResult {
+ const blocks = new Map<string, JSONContent>();
+ const keys = (doc: JSONContent) =>
+ (doc.content ?? []).map((block) => {
+ const key = codec.serialize({ type: "doc", content: [block] });
+ blocks.set(key, block);
+ return key;
+ });
+ 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)!) });
+ 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),
+ });
+ }
+ }
+ if (conflicts.length > 0) return { ok: false, conflicts };
+ return { ok: true, doc: { type: "doc", content: merged } };
+}
diff --git a/apps/collab/src/server.ts b/apps/collab/src/server.ts
new file mode 100644
index 0000000000..9fd156a8ca
--- /dev/null
+++ b/apps/collab/src/server.ts
@@ -0,0 +1,166 @@
+import { timingSafeEqual } from "node:crypto";
+import type { IncomingMessage, ServerResponse } from "node:http";
+import { isTransactionOrigin, Server } from "@hocuspocus/server";
+import type { DocumentCodec } from "@multica/views/editor/schema/codec";
+import { CollabApi } from "./api";
+import type { CollabConfig } from "./config";
+import {
+ DocumentStore,
+ documentEpoch,
+ parseDocumentName,
+ RESET_CLOSE_CODE,
+ type EditRequest,
+ type WriteRequest,
+ type WriteResult,
+} from "./documents";
+import { verifyTicket, type Actor } from "./ticket";
+
+export interface ConnectionContext {
+ actor: Actor;
+ workspaceId: string;
+ /** The document epoch this client's local copy came from, if it has one. */
+ epoch?: string;
+}
+
+export interface Logger {
+ info(msg: string, fields?: Record<string, unknown>): void;
+ warn(msg: string, fields?: Record<string, unknown>): void;
+ error(msg: string, fields?: Record<string, unknown>): void;
+}
+
+const MAX_BODY_BYTES = 8 << 20;
+
+/** The provider token is `{"ticket": "...", "epoch": "..."}` so a
+ * reconnecting client can say which copy of the document it holds. A bare
+ * ticket is accepted too. */
+function parseToken(token: string): { ticket: string; epoch?: string } {
+ if (!token.startsWith("{")) return { ticket: token };
+ const parsed = JSON.parse(token) as { ticket?: unknown; epoch?: unknown };
+ if (typeof parsed.ticket !== "string") throw new Error("malformed token");
+ return { ticket: parsed.ticket, epoch: typeof parsed.epoch === "string" ? parsed.epoch : undefined };
+}
+
+export function createCollabServer(config: CollabConfig, codec: DocumentCodec, log: Logger) {
+ const api = new CollabApi(config.apiUrl, config.secret);
+ const store = new DocumentStore(api, codec, log);
+
+ const server = new Server<ConnectionContext>({
+ port: config.port,
+ quiet: true,
+ debounce: config.storeDebounceMs,
+ maxDebounce: config.storeMaxDebounceMs,
+ // Keep the doc warm for the debounce window after the last editor leaves,
+ // so a quick reconnect does not reload it.
+ unloadImmediately: false,
+
+ async onAuthenticate({ token, documentName, connectionConfig }) {
+ const { ticket, epoch } = parseToken(token);
+ const verified = verifyTicket(ticket, config.secret);
+ if (verified.document !== documentName) throw new Error("ticket is for another document");
+ if (!parseDocumentName(documentName)) throw new Error("unknown document");
+ if (verified.readOnly) connectionConfig.readOnly = true;
+ return { actor: verified.actor, workspaceId: verified.workspaceId, epoch };
+ },
+
+ async onLoadDocument({ documentName }) {
+ return store.load(documentName);
+ },
+
+ async beforeHandleMessage({ context, document }) {
+ if (context.epoch && context.epoch !== documentEpoch(document)) {
+ throw Object.assign(new Error("document was rebuilt"), {
+ code: RESET_CLOSE_CODE,
+ reason: "document-reset",
+ });
+ }
+ },
+
+ async onChange({ documentName, transactionOrigin, context }) {
+ if (isTransactionOrigin(transactionOrigin) && transactionOrigin.source === "connection") {
+ store.noteChange(documentName, context?.actor);
+ }
+ },
+
+ async onStoreDocument({ documentName, document }) {
+ await store.autosave(documentName, document);
+ },
+
+ async afterUnloadDocument({ documentName }) {
+ store.forget(documentName);
+ },
+
+ async onRequest({ request, response }) {
+ if (await handleRequest(request, response)) {
+ // Rejecting with a falsy value stops Hocuspocus's default response.
+ throw null;
+ }
+ },
+ });
+ store.hocuspocus = server.hocuspocus;
+
+ const authorized = (request: IncomingMessage) => {
+ const given = Buffer.from(String(request.headers["x-collab-secret"] ?? ""));
+ const expected = Buffer.from(config.secret);
+ return given.length === expected.length && timingSafeEqual(given, expected);
+ };
+
+ async function handleRequest(request: IncomingMessage, response: ServerResponse): Promise<boolean> {
+ const url = new URL(request.url ?? "/", "http://collab");
+ if (url.pathname === "/health") {
+ send(response, 200, { ok: true, documents: server.hocuspocus.getDocumentsCount() });
+ return true;
+ }
+ const match = /^\/internal\/documents\/([^/]+)\/(write|edit|flush)$/.exec(url.pathname);
+ if (!match) return false;
+ if (request.method !== "POST") return send(response, 405, { error: "method not allowed" });
+ if (!authorized(request)) return send(response, 401, { error: "unauthorized" });
+ const name = decodeURIComponent(match[1]!);
+ if (!parseDocumentName(name)) return send(response, 400, { error: "unknown document" });
+ try {
+ if (match[2] === "flush") return send(response, 200, await store.flush(name));
+ const body = await readJson(request);
+ const result =
+ match[2] === "write"
+ ? await store.write(name, body as WriteRequest)
+ : await store.edit(name, body as EditRequest);
+ return sendResult(response, result);
+ } catch (error) {
+ log.error("internal request failed", { path: url.pathname, error: String(error) });
+ return send(response, 500, { error: "internal error" });
+ }
+ }
+
+ return { server, store };
+}
+
+function sendResult(response: ServerResponse, result: WriteResult): boolean {
+ switch (result.status) {
+ case "ok":
+ return send(response, 200, result);
+ case "gone":
+ return send(response, 404, { error: "document not found" });
+ case "conflict":
+ return send(response, 409, { error: "merge_conflict", ...result });
+ case "edit_failed":
+ return send(response, 409, { error: "edit_failed", ...result });
+ case "too_large":
+ return send(response, 413, { error: "content_too_large", ...result });
+ }
+}
+
+function send(response: ServerResponse, status: number, body: unknown): true {
+ response.writeHead(status, { "Content-Type": "application/json" });
+ response.end(JSON.stringify(body));
+ return true;
+}
+
+async function readJson(request: IncomingMessage): Promise<unknown> {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ for await (const chunk of request) {
+ size += (chunk as Buffer).length;
+ if (size > MAX_BODY_BYTES) throw new Error("request body too large");
+ chunks.push(chunk as Buffer);
+ }
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
+}
diff --git a/apps/collab/src/ticket.ts b/apps/collab/src/ticket.ts
new file mode 100644
index 0000000000..792f409272
--- /dev/null
+++ b/apps/collab/src/ticket.ts
@@ -0,0 +1,67 @@
+import { createHmac, timingSafeEqual } from "node:crypto";
+
+export interface Actor {
+ type: "member" | "agent";
+ id: string;
+ name: string;
+}
+
+/** What the Go API vouches for when it hands an editor a ticket. */
+export interface Ticket {
+ document: string;
+ workspaceId: string;
+ actor: Actor;
+ readOnly: boolean;
+ expiresAt: number;
+}
+
+interface TicketPayload {
+ d: string;
+ w: string;
+ t: "member" | "agent";
+ i: string;
+ n: string;
+ ro: boolean;
+ exp: number;
+}
+
+const sign = (secret: string, payload: string) =>
+ createHmac("sha256", secret).update(payload).digest("base64url");
+
+/** Format: `<base64url JSON payload>.<base64url HMAC-SHA256>`, minted by
+ * server/internal/collab/ticket.go. */
+export function verifyTicket(token: string, secret: string, now = Date.now()): Ticket {
+ const [payload, signature, extra] = token.split(".");
+ if (!payload || !signature || extra !== undefined) throw new Error("malformed ticket");
+ const expected = Buffer.from(sign(secret, payload));
+ const actual = Buffer.from(signature);
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {
+ throw new Error("bad ticket signature");
+ }
+ const data = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as TicketPayload;
+ if (typeof data.exp !== "number" || data.exp * 1000 < now) throw new Error("ticket expired");
+ if (data.t !== "member" && data.t !== "agent") throw new Error("bad ticket actor");
+ return {
+ document: data.d,
+ workspaceId: data.w,
+ actor: { type: data.t, id: data.i, name: data.n },
+ readOnly: data.ro === true,
+ expiresAt: data.exp,
+ };
+}
+
+/** Test helper; production tickets come from the Go API. */
+export function signTicket(ticket: Ticket, secret: string): string {
+ const payload = Buffer.from(
+ JSON.stringify({
+ d: ticket.document,
+ w: ticket.workspaceId,
+ t: ticket.actor.type,
+ i: ticket.actor.id,
+ n: ticket.actor.name,
+ ro: ticket.readOnly,
+ exp: ticket.expiresAt,
+ } satisfies TicketPayload),
+ ).toString("base64url");
+ return `${payload}.${sign(secret, payload)}`;
+}
diff --git a/apps/collab/tsconfig.json b/apps/collab/tsconfig.json
new file mode 100644
index 0000000000..a8bc645d57
--- /dev/null
+++ b/apps/collab/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "@multica/tsconfig/base.json",
+ "compilerOptions": {
+ "noEmit": true,
+ "types": ["node"],
+ "lib": ["ESNext", "DOM"]
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/apps/web/config/runtime-urls.test.ts b/apps/web/config/runtime-urls.test.ts
index 8b7064f4ee..8953dcc467 100644
--- a/apps/web/config/runtime-urls.test.ts
+++ b/apps/web/config/runtime-urls.test.ts
@@ -313,6 +313,11 @@ describe("runtimeRewriteDestination", () => {
REMOTE_API_URL: "http://backend:8080",
}),
).toBe("http://backend:8080/ws");
+ expect(
+ runtimeRewriteDestination("/collab", {
+ REMOTE_API_URL: "http://backend:8080",
+ }),
+ ).toBe("http://backend:8080/collab");
});
});
diff --git a/apps/web/config/runtime-urls.ts b/apps/web/config/runtime-urls.ts
index c4d6b9ffb9..fbf7c0af46 100644
--- a/apps/web/config/runtime-urls.ts
+++ b/apps/web/config/runtime-urls.ts
@@ -128,8 +128,8 @@ export function runtimeRewriteDestination(
if (pathname === "/api" || pathname.startsWith("/api/")) {
return appendPath(remoteApiUrl, pathname);
}
- if (pathname === "/ws") {
- return appendPath(remoteApiUrl, "/ws");
+ if (pathname === "/ws" || pathname === "/collab") {
+ return appendPath(remoteApiUrl, pathname);
}
// `multica setup self-host` probes `{server-url}/health` and treats any
// non-200 as "Server not reachable". The backend serves it, but a
diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts
index cbf67acda8..b402d199bf 100644
--- a/apps/web/next.config.ts
+++ b/apps/web/next.config.ts
@@ -89,6 +89,10 @@ const nextConfig: NextConfig = {
source: "/ws",
destination: `${remoteApiUrl}/ws`,
},
+ {
+ source: "/collab",
+ destination: `${remoteApiUrl}/collab`,
+ },
{
source: "/health",
destination: `${remoteApiUrl}/health`,
diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts
index e6c1615621..d60b082e8a 100644
--- a/apps/web/proxy.ts
+++ b/apps/web/proxy.ts
@@ -170,6 +170,7 @@ export const config = {
"/auth/:path*",
"/docs/:path*",
"/ws",
+ "/collab",
"/((?!api|v1|_next/static|_next/image|favicon.ico|.*\\.).*)",
],
};
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 1ef92892c6..980fe2f84f 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -10,6 +10,7 @@ import {
DocSearchResponseSchema,
DocCommentSchema,
DocCommentListSchema,
+ DocCollabTicketSchema,
} from "../docs/schemas";
import type {
Doc,
@@ -20,6 +21,7 @@ import type {
CreateDocCommentRequest,
DocTree,
DocVersion,
+ DocCollabTicket,
CreateDocRequest,
UpdateDocRequest,
CreateDocFolderRequest,
@@ -1094,6 +1096,14 @@ export class ApiClient {
{ endpoint: "GET /api/docs/{id}/versions" },
).versions;
}
+ async createDocCollabTicket(id: string): Promise<DocCollabTicket> {
+ return parseWithFallback<DocCollabTicket>(
+ await this.fetch<unknown>(`/api/docs/${id}/collab-ticket`, { method: "POST" }),
+ DocCollabTicketSchema,
+ { enabled: false },
+ { endpoint: "POST /api/docs/{id}/collab-ticket" },
+ );
+ }
async getDocVersion(id: string, number: number): Promise<DocVersion | null> {
return parseWithFallback<DocVersion | null>(
await this.fetch<unknown>(`/api/docs/${id}/versions/${number}`),
diff --git a/packages/core/docs/client.test.ts b/packages/core/docs/client.test.ts
index 3e54625fd6..95459c229f 100644
--- a/packages/core/docs/client.test.ts
+++ b/packages/core/docs/client.test.ts
@@ -101,6 +101,17 @@ describe("knowledge base client", () => {
).toBe(false);
});
+ it("treats a stale save that could not be merged as a revision conflict", async () => {
+ respond(
+ { error: "the doc changed in the same place", code: "doc_merge_conflict", actual_revision: 5 },
+ 409,
+ );
+ const error = await new ApiClient("https://api.example.test")
+ .updateDoc("d1", { baseRevision: 3, content: "x" })
+ .catch((e: unknown) => e);
+ expect(isDocRevisionConflict(error)).toBe(true);
+ });
+
it("searches docs and keeps the hits it can read", async () => {
const { content: _content, ...summary } = validDoc;
const fetchMock = respond({
diff --git a/packages/core/docs/index.ts b/packages/core/docs/index.ts
index 7cccf70c79..be16bec0e6 100644
--- a/packages/core/docs/index.ts
+++ b/packages/core/docs/index.ts
@@ -3,3 +3,4 @@ export * from "./mutations";
export * from "./tree";
export * from "./draft-store";
export * from "./deletion-permissions";
+export * from "./realtime";
diff --git a/packages/core/docs/queries.ts b/packages/core/docs/queries.ts
index 699561a580..0025ea59c2 100644
--- a/packages/core/docs/queries.ts
+++ b/packages/core/docs/queries.ts
@@ -54,8 +54,11 @@ export function docVersionOptions(wsId: string, id: string, number: number) {
export function isDocNotFound(error: unknown): boolean {
return error instanceof ApiError && error.status === 404;
}
+/** A save based on a stale revision that the server could not apply: refused
+ * outright, or refused because the stale draft and a newer edit changed the
+ * same block. Either way the draft must be reconciled with the latest doc. */
export function isDocRevisionConflict(error: unknown): boolean {
if (!(error instanceof ApiError) || error.status !== 409) return false;
const body = error.body as { code?: unknown } | undefined;
- return body?.code === "revision_conflict";
+ return body?.code === "revision_conflict" || body?.code === "doc_merge_conflict";
}
diff --git a/packages/core/docs/realtime.test.ts b/packages/core/docs/realtime.test.ts
new file mode 100644
index 0000000000..bb241b71ba
--- /dev/null
+++ b/packages/core/docs/realtime.test.ts
@@ -0,0 +1,96 @@
+import { QueryClient } from "@tanstack/react-query";
+import { describe, expect, it } from "vitest";
+import type { Doc, DocTree } from "../types";
+import { docKeys } from "./queries";
+import { applyDocUpdated, holdLiveDoc } from "./realtime";
+
+const WS = "ws-1";
+const summary = (revision: number, title = "Plan") => ({
+ id: "doc-1",
+ workspace_id: WS,
+ folder_id: null,
+ title,
+ revision,
+ version_count: 2,
+ created_by_type: "member",
+ created_by_id: "u1",
+ updated_by_type: "member",
+ updated_by_id: "u2",
+ created_at: "2026-11-21T00:00:00Z",
+ updated_at: "2026-11-21T00:00:05Z",
+});
+const doc = (revision: number, content: string): Doc => ({
+ id: "doc-1",
+ workspaceId: WS,
+ folderId: null,
+ title: "Plan",
+ revision,
+ versionCount: 1,
+ createdByType: "member",
+ createdById: "u1",
+ updatedByType: "member",
+ updatedById: "u1",
+ createdAt: "2026-11-21T00:00:00Z",
+ updatedAt: "2026-11-21T00:00:00Z",
+ content,
+});
+
+function setup() {
+ const qc = new QueryClient();
+ const { content: _content, ...listed } = doc(1, "");
+ qc.setQueryData<DocTree>(docKeys.tree(WS), { folders: [], docs: [listed] });
+ qc.setQueryData<Doc>(docKeys.detail(WS, "doc-1"), doc(1, "old body"));
+ qc.setQueryData(docKeys.comments(WS, "doc-1"), []);
+ qc.setQueryData(docKeys.versions(WS, "doc-1"), []);
+ return qc;
+}
+const invalidated = (qc: QueryClient, key: readonly unknown[]) => qc.getQueryState(key)?.isInvalidated;
+
+describe("applyDocUpdated", () => {
+ it("patches a live doc in place without refetching its body or comments", () => {
+ const qc = setup();
+ const release = holdLiveDoc("doc-1");
+ applyDocUpdated(qc, WS, { doc: summary(5, "Plan v2"), version: 2 });
+ release();
+
+ expect(qc.getQueryData<DocTree>(docKeys.tree(WS))!.docs[0]).toMatchObject({ title: "Plan v2", revision: 5 });
+ expect(invalidated(qc, docKeys.tree(WS))).toBe(false);
+ expect(qc.getQueryData<Doc>(docKeys.detail(WS, "doc-1"))).toMatchObject({ title: "Plan v2", revision: 5, versionCount: 2 });
+ // Marked for the next open, but not fetched while the live session holds the body.
+ expect(invalidated(qc, docKeys.detail(WS, "doc-1"))).toBe(true);
+ expect(qc.getQueryState(docKeys.detail(WS, "doc-1"))!.fetchStatus).toBe("idle");
+ expect(invalidated(qc, docKeys.comments(WS, "doc-1"))).toBe(false);
+ expect(invalidated(qc, docKeys.versions(WS, "doc-1"))).toBe(true);
+ });
+
+ it("refetches the body of a doc that is not edited live", () => {
+ const qc = setup();
+ applyDocUpdated(qc, WS, { doc: summary(5) });
+ expect(invalidated(qc, docKeys.detail(WS, "doc-1"))).toBe(true);
+ expect(qc.getQueryData<Doc>(docKeys.detail(WS, "doc-1"))!.revision).toBe(1);
+ });
+
+ it("applies a metadata change at the same revision, such as a move", () => {
+ const qc = setup();
+ applyDocUpdated(qc, WS, { doc: { ...summary(1), folder_id: "f1" } });
+ expect(qc.getQueryData<Doc>(docKeys.detail(WS, "doc-1"))).toMatchObject({ folderId: "f1", content: "old body" });
+ expect(invalidated(qc, docKeys.detail(WS, "doc-1"))).toBe(false);
+ expect(qc.getQueryData<DocTree>(docKeys.tree(WS))!.docs[0]!.folderId).toBe("f1");
+ expect(invalidated(qc, docKeys.versions(WS, "doc-1"))).toBe(false);
+ });
+
+ it("ignores an event older than the cache", () => {
+ const qc = setup();
+ qc.setQueryData<Doc>(docKeys.detail(WS, "doc-1"), doc(7, "newer"));
+ applyDocUpdated(qc, WS, { doc: summary(5, "stale") });
+ expect(qc.getQueryData<Doc>(docKeys.detail(WS, "doc-1"))).toMatchObject({ revision: 7, title: "Plan" });
+ expect(invalidated(qc, docKeys.detail(WS, "doc-1"))).toBe(false);
+ });
+
+ it("falls back to refetching everything on a payload it cannot read", () => {
+ const qc = setup();
+ applyDocUpdated(qc, WS, { doc: { id: "doc-1" } });
+ expect(invalidated(qc, docKeys.tree(WS))).toBe(true);
+ expect(invalidated(qc, docKeys.comments(WS, "doc-1"))).toBe(true);
+ });
+});
diff --git a/packages/core/docs/realtime.ts b/packages/core/docs/realtime.ts
new file mode 100644
index 0000000000..68f584c581
--- /dev/null
+++ b/packages/core/docs/realtime.ts
@@ -0,0 +1,71 @@
+import type { QueryClient } from "@tanstack/react-query";
+import type { Doc, DocTree } from "../types";
+import { docKeys } from "./queries";
+import { DocSummarySchema } from "./schemas";
+
+const liveDocs = new Map<string, number>();
+
+/**
+ * Marks a doc as edited live in this tab until the returned function runs.
+ * Its body then comes from the live session, so another save does not need
+ * to download it again.
+ */
+export function holdLiveDoc(id: string): () => void {
+ liveDocs.set(id, (liveDocs.get(id) ?? 0) + 1);
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ const count = (liveDocs.get(id) ?? 1) - 1;
+ if (count > 0) liveDocs.set(id, count);
+ else liveDocs.delete(id);
+ };
+}
+
+/**
+ * Applies a `doc:updated` event to the cache. Every live save broadcasts one
+ * to the whole workspace every few seconds, so it patches the tree and the
+ * doc's metadata in place instead of refetching every doc query: the body is
+ * fetched again only by a tab that shows it outside a live session.
+ */
+export function applyDocUpdated(qc: QueryClient, wsId: string, payload: unknown) {
+ const event = payload as { doc?: unknown; version?: unknown } | undefined;
+ const parsed = DocSummarySchema.safeParse(event?.doc);
+ if (!parsed.success) {
+ void qc.invalidateQueries({ queryKey: docKeys.all(wsId) });
+ return;
+ }
+ const summary = parsed.data;
+
+ const tree = qc.getQueryData<DocTree>(docKeys.tree(wsId));
+ if (tree) {
+ const known = tree.docs.find((doc) => doc.id === summary.id);
+ if (!known) void qc.invalidateQueries({ queryKey: docKeys.tree(wsId) });
+ else if (summary.revision >= known.revision) {
+ qc.setQueryData<DocTree>(docKeys.tree(wsId), {
+ ...tree,
+ docs: tree.docs.map((doc) => (doc.id === summary.id ? summary : doc)),
+ });
+ }
+ }
+
+ const detailKey = docKeys.detail(wsId, summary.id);
+ const detail = qc.getQueryData<Doc>(detailKey);
+ if (detail && summary.revision >= detail.revision) {
+ if (summary.revision === detail.revision) {
+ qc.setQueryData<Doc>(detailKey, { ...detail, ...summary });
+ } else if (liveDocs.has(summary.id)) {
+ qc.setQueryData<Doc>(detailKey, { ...detail, ...summary });
+ // The cached body is now behind its revision: fetch it on next use.
+ void qc.invalidateQueries({ queryKey: detailKey, refetchType: "none" });
+ } else {
+ void qc.invalidateQueries({ queryKey: detailKey });
+ }
+ }
+
+ // Every write that adds or extends a version names it; a move does not.
+ if (typeof event?.version === "number") {
+ void qc.invalidateQueries({ queryKey: docKeys.versions(wsId, summary.id) });
+ void qc.invalidateQueries({ queryKey: docKeys.version(wsId, summary.id, event.version) });
+ }
+}
diff --git a/packages/core/docs/schemas.ts b/packages/core/docs/schemas.ts
index 46d3b55de9..8b0225f542 100644
--- a/packages/core/docs/schemas.ts
+++ b/packages/core/docs/schemas.ts
@@ -135,6 +135,10 @@ export const DocVersionSchema = z
action_ref: z.number().nullable().default(null),
task_id: z.string().nullable().default(null),
issue_id: z.string().nullable().default(null),
+ contributors: z
+ .array(z.object({ type: actor, id: z.string() }))
+ .catch([])
+ .default([]),
created_at: z.string(),
updated_at: z.string(),
content: z.string().optional(),
@@ -150,6 +154,7 @@ export const DocVersionSchema = z
actionRef: d.action_ref,
taskId: d.task_id,
issueId: d.issue_id,
+ contributors: d.contributors,
createdAt: d.created_at,
updatedAt: d.updated_at,
content: d.content,
@@ -157,3 +162,15 @@ export const DocVersionSchema = z
export const DocVersionListSchema = z.object({
versions: z.array(DocVersionSchema),
});
+export const DocCollabTicketSchema = z
+ .object({
+ enabled: z.boolean(),
+ token: z.string().optional(),
+ document: z.string().optional(),
+ expires_at: z.string().optional(),
+ })
+ .transform((t) =>
+ t.enabled && t.token && t.document
+ ? { enabled: true as const, token: t.token, document: t.document, expiresAt: t.expires_at ?? "" }
+ : { enabled: false as const },
+ );
diff --git a/packages/core/paths/reserved-slugs.ts b/packages/core/paths/reserved-slugs.ts
index 4c653f8ff2..a0d7c9c913 100644
--- a/packages/core/paths/reserved-slugs.ts
+++ b/packages/core/paths/reserved-slugs.ts
@@ -339,6 +339,7 @@ export const RESERVED_SLUGS: ReadonlySet<string> = new Set([
"readyz",
"healthz",
"ws",
+ "collab",
"metrics",
"ping",
diff --git a/packages/core/realtime/collab-url.test.ts b/packages/core/realtime/collab-url.test.ts
new file mode 100644
index 0000000000..b00b7e0d7d
--- /dev/null
+++ b/packages/core/realtime/collab-url.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vitest";
+import { collabUrlFromWsUrl } from "./provider";
+
+describe("collabUrlFromWsUrl", () => {
+ it("serves co-editing next to realtime", () => {
+ expect(collabUrlFromWsUrl("ws://localhost:8080/ws")).toBe("ws://localhost:8080/collab");
+ expect(collabUrlFromWsUrl("wss://api.example.com/base/ws?x=1")).toBe("wss://api.example.com/base/collab");
+ });
+
+ it("resolves a same-origin URL", () => {
+ expect(collabUrlFromWsUrl("https://app.example.com/ws")).toBe("wss://app.example.com/collab");
+ });
+});
diff --git a/packages/core/realtime/index.ts b/packages/core/realtime/index.ts
index d4b3334758..e5e0dc18b7 100644
--- a/packages/core/realtime/index.ts
+++ b/packages/core/realtime/index.ts
@@ -1,4 +1,4 @@
-export { WSProvider, useWS } from "./provider";
+export { WSProvider, useWS, collabUrlFromWsUrl } from "./provider";
export type { WSProviderProps, WSStatus } from "./provider";
export { useWSEvent, useWSReconnect, useWSStatus } from "./hooks";
export { useRealtimeSync, removeChatMessageFromCaches } from "./use-realtime-sync";
diff --git a/packages/core/realtime/provider.tsx b/packages/core/realtime/provider.tsx
index 3c80f020a2..817569a24e 100644
--- a/packages/core/realtime/provider.tsx
+++ b/packages/core/realtime/provider.tsx
@@ -4,6 +4,7 @@ import {
createContext,
use,
useEffect,
+ useMemo,
useState,
useCallback,
useSyncExternalStore,
@@ -34,6 +35,8 @@ type EventHandler = (payload: unknown, actorId?: string, actorType?: string) =>
export type WSStatus = WSConnectionStatus | "offline";
interface WSContextValue {
+ /** WebSocket URL of the live doc co-editing service. */
+ collabUrl: string;
subscribe: (event: WSEventType, handler: EventHandler) => () => void;
onReconnect: (callback: () => void) => () => void;
subscribeStatus: (listener: () => void) => () => void;
@@ -42,6 +45,16 @@ interface WSContextValue {
const WSContext = createContext<WSContextValue | null>(null);
+/** The co-editing service is served next to realtime: `…/ws` → `…/collab`. */
+export function collabUrlFromWsUrl(wsUrl: string): string {
+ const url = new URL(wsUrl, globalThis.location?.href ?? "http://localhost");
+ if (url.protocol === "http:") url.protocol = "ws:";
+ if (url.protocol === "https:") url.protocol = "wss:";
+ url.pathname = url.pathname.replace(/\/ws\/?$/, "") + "/collab";
+ url.search = "";
+ return url.toString();
+}
+
export interface WSProviderProps {
children: ReactNode;
/** WebSocket server URL (e.g. "ws://localhost:8080/ws") */
@@ -186,9 +199,11 @@ export function WSProvider({
[wsClient],
);
+ const collabUrl = useMemo(() => collabUrlFromWsUrl(wsUrl), [wsUrl]);
+
return (
<WSContext.Provider
- value={{ subscribe, onReconnect: onReconnectCb, subscribeStatus, getStatus }}
+ value={{ collabUrl, subscribe, onReconnect: onReconnectCb, subscribeStatus, getStatus }}
>
{children}
</WSContext.Provider>
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 635c4eb45c..fa14483d39 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -1,5 +1,6 @@
"use client";
import { docKeys } from "../docs/queries";
+import { applyDocUpdated } from "../docs/realtime";
import { weixinKeys } from "../weixin/queries";
@@ -1423,12 +1424,24 @@ export function useRealtimeSync(
qc.invalidateQueries({ queryKey: issueKeys.attachments(issueId) });
};
+ // Only the tree lists docs and folders; an open doc's body and comments
+ // are not touched by these.
const docUnsubs = ([
- "doc:created", "doc:updated", "doc:deleted",
- "doc_folder:created", "doc_folder:updated", "doc_folder:deleted",
+ "doc:created", "doc_folder:created", "doc_folder:updated", "doc_folder:deleted",
] as const).map((event) => ws.on(event, () => {
const wsId = getCurrentWsId();
- if (wsId) void qc.invalidateQueries({ queryKey: docKeys.all(wsId) });
+ if (wsId) void qc.invalidateQueries({ queryKey: docKeys.tree(wsId) });
+ }));
+ docUnsubs.push(ws.on("doc:updated", (p) => {
+ const wsId = getCurrentWsId();
+ if (wsId) applyDocUpdated(qc, wsId, p);
+ }));
+ docUnsubs.push(ws.on("doc:deleted", (p) => {
+ const wsId = getCurrentWsId();
+ if (!wsId) return;
+ void qc.invalidateQueries({ queryKey: docKeys.tree(wsId) });
+ const docId = (p as { doc_id?: string } | undefined)?.doc_id;
+ if (docId) void qc.invalidateQueries({ queryKey: docKeys.detail(wsId, docId) });
}));
// A discussion changed on one doc: refetch that doc's comments only.
docUnsubs.push(ws.on("doc_comment:changed", (p) => {
diff --git a/packages/core/types/doc.ts b/packages/core/types/doc.ts
index dabd84d2fa..7b083afbd1 100644
--- a/packages/core/types/doc.ts
+++ b/packages/core/types/doc.ts
@@ -77,10 +77,18 @@ export interface DocVersion {
actionRef: number | null;
taskId: string | null;
issueId: string | null;
+ /** Everyone whose edits the version carries. Empty for versions saved
+ * before live co-editing; the author is the one then. */
+ contributors: { type: DocAuthorType; id: string }[];
createdAt: string;
updatedAt: string;
content?: string;
}
+/** Lets an editor join a doc's live session; `enabled: false` when the
+ * server runs without the collaboration service. */
+export type DocCollabTicket =
+ | { enabled: true; token: string; document: string; expiresAt: string }
+ | { enabled: false };
export interface CreateDocRequest {
title: string;
content?: string;
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 10c30fcbe3..344bbbed6a 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -16,6 +16,8 @@
"./markdown/*": "./markdown/*.tsx",
"./markdown/linkify": "./markdown/linkify.ts",
"./markdown/mentions": "./markdown/mentions.ts",
+ "./markdown/file-cards": "./markdown/file-cards.ts",
+ "./markdown/issue-identifiers": "./markdown/issue-identifiers.ts",
"./hooks/*": "./hooks/*.ts",
"./lib/utils": "./lib/utils.ts",
"./lib/avatar-size": "./lib/avatar-size.ts",
diff --git a/packages/views/docs/components/doc-comment-anchors.ts b/packages/views/docs/components/doc-comment-anchors.ts
index 31efc2aebc..6e89043ede 100644
--- a/packages/views/docs/components/doc-comment-anchors.ts
+++ b/packages/views/docs/components/doc-comment-anchors.ts
@@ -73,9 +73,14 @@ function sharedPrefix(a: string, b: string): number {
return n;
}
-/** A DOM range over `anchor` in `root`, or null when the quote is gone. */
-export function docAnchorRange(root: HTMLElement, anchor: DocAnchor): Range | null {
- const { text, nodes } = indexCommentText(root, true);
+/** A DOM range over `anchor` in `root`, or null when the quote is gone. Pass
+ * `index` to locate several anchors with one walk over the doc. */
+export function docAnchorRange(
+ root: HTMLElement,
+ anchor: DocAnchor,
+ index: ReturnType<typeof indexCommentText> = indexCommentText(root, true),
+): Range | null {
+ const { text, nodes } = index;
const start = locateDocAnchor(text, anchor);
if (start === null) return null;
const end = start + anchor.quote.length;
diff --git a/packages/views/docs/components/doc-history-page.tsx b/packages/views/docs/components/doc-history-page.tsx
index b5e5a42b72..5af61057d6 100644
--- a/packages/views/docs/components/doc-history-page.tsx
+++ b/packages/views/docs/components/doc-history-page.tsx
@@ -97,8 +97,18 @@ function DocHistoryPageContent({ docId }: { docId: string }) {
: ""}
</span>
<span className="mt-1 block truncate text-caption">
- {getActorName(v.authorType, v.authorId)}
+ {(v.contributors.length > 1
+ ? v.contributors
+ : [{ type: v.authorType, id: v.authorId }]
+ )
+ .map((c) => getActorName(c.type, c.id))
+ .join(", ")}
</span>
+ {v.message && (
+ <span className="block truncate text-caption text-muted-foreground">
+ {v.message}
+ </span>
+ )}
<span className="block text-caption text-muted-foreground">
{new Date(v.updatedAt).toLocaleString()}
</span>
diff --git a/packages/views/docs/components/doc-not-found.test.tsx b/packages/views/docs/components/doc-not-found.test.tsx
index 51b20a8a42..f2cbd1fa26 100644
--- a/packages/views/docs/components/doc-not-found.test.tsx
+++ b/packages/views/docs/components/doc-not-found.test.tsx
@@ -67,6 +67,7 @@ vi.mock("../../editor", () => ({
ReadonlyContent: ({ content }: { content: string }) => <div>{content}</div>,
useEditorUpload: () => ({ uploadWithToast: vi.fn() }),
}));
+vi.mock("./use-doc-collab", () => ({ useDocCollab: () => ({ mode: "solo" }) }));
vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
vi.mock("../../layout/breadcrumb-header", () => ({
BreadcrumbHeader: ({ actions }: { actions?: React.ReactNode }) => <header>{actions}</header>,
diff --git a/packages/views/docs/components/doc-outline.tsx b/packages/views/docs/components/doc-outline.tsx
index 348038d0af..9335d6ba70 100644
--- a/packages/views/docs/components/doc-outline.tsx
+++ b/packages/views/docs/components/doc-outline.tsx
@@ -2,6 +2,7 @@
import { useEffect, useState, type RefObject } from "react";
import { cn } from "@multica/ui/lib/utils";
import { useT } from "../../i18n";
+import { watchDom } from "./dom-throttle";
export interface OutlineHeading {
level: number;
@@ -57,23 +58,12 @@ export function useDocOutline(
useEffect(() => {
const root = rootRef.current;
if (!root) return;
- let frame = 0;
- const refresh = () => {
- cancelAnimationFrame(frame);
- frame = requestAnimationFrame(() => {
- const next = readOutline(root);
- setHeadings((prev) => (sameOutline(prev, next) ? prev : next));
- });
- };
- refresh();
// The editor mounts after first paint and re-renders headings in place, so
// watch the DOM rather than the Markdown.
- const observer = new MutationObserver(refresh);
- observer.observe(root, { childList: true, subtree: true, characterData: true });
- return () => {
- observer.disconnect();
- cancelAnimationFrame(frame);
- };
+ return watchDom(root, () => {
+ const next = readOutline(root);
+ setHeadings((prev) => (sameOutline(prev, next) ? prev : next));
+ });
}, [rootRef]);
useEffect(() => {
diff --git a/packages/views/docs/components/doc-page.tsx b/packages/views/docs/components/doc-page.tsx
index 520e985c55..62ba5bd928 100644
--- a/packages/views/docs/components/doc-page.tsx
+++ b/packages/views/docs/components/doc-page.tsx
@@ -29,18 +29,21 @@ import {
docTreeOptions,
docCommentsOptions,
folderAncestry,
+ holdLiveDoc,
isDocNotFound,
} from "@multica/core/docs";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
import type { Doc } from "@multica/core/types";
-import { ContentEditor, useEditorUpload } from "../../editor";
+import { ContentEditor, ReadonlyContent, useEditorUpload } from "../../editor";
import { ActorAvatar } from "../../common/actor-avatar";
import { BreadcrumbHeader } from "../../layout/breadcrumb-header";
import { AppLink, useNavigation } from "../../navigation";
import { useT, useTimeAgo } from "../../i18n";
import { useDocDraft } from "./use-doc-draft";
+import { useDocCollab, type DocCollaborator } from "./use-doc-collab";
+import { useLiveDocTitle } from "./use-live-doc-title";
import { DocOutline, MIN_OUTLINE_HEADINGS, useDocOutline } from "./doc-outline";
import { DocCommentsPanel, groupDocThreads } from "./doc-comments-panel";
import { captureDocAnchor, type DocAnchor } from "./doc-comment-anchors";
@@ -148,7 +151,27 @@ function DocEditor({ doc }: { doc: Doc }) {
const { data: tree } = useQuery(docTreeOptions(wsId));
const { getActorName } = useActorName();
const timeAgo = useTimeAgo();
- const { draft, status, dirty, change, retry, reload } = useDocDraft(doc);
+ // With live editing on, the shared document holds the body and saves
+ // itself; only the title goes through the API. Until the page knows which
+ // mode it is in, nothing is saved: the body is shown read-only and a typed
+ // title is held.
+ const collab = useDocCollab(doc.id);
+ const live = collab.mode === "live" ? collab : null;
+ const solo = collab.mode === "solo";
+ const { draft, status, dirty, change, retry, reload, setAside } = useDocDraft(doc, solo);
+ const liveTitle = useLiveDocTitle(doc, !!live);
+ useEffect(() => {
+ if (solo) {
+ const title = liveTitle.take();
+ if (title !== null) change({ title });
+ } else if (live) {
+ setAside();
+ }
+ // Once per mode change: the handlers are recreated every render.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [solo, !!live]);
+ const liveSynced = !!live?.synced;
+ useEffect(() => (liveSynced ? holdLiveDoc(doc.id) : undefined), [liveSynced, doc.id]);
const [moving, setMoving] = useState(false);
const [deleting, setDeleting] = useState(false);
const canDelete = useCanDeleteDoc()(doc);
@@ -238,6 +261,15 @@ function DocEditor({ doc }: { doc: Doc }) {
}
actions={
<>
+ {live ? (
+ <LiveStatus
+ connected={live.connected}
+ synced={live.synced}
+ collaborators={live.collaborators}
+ titleFailed={liveTitle.failed}
+ onRetryTitle={liveTitle.retry}
+ />
+ ) : collab.mode === "checking" ? null : (
<span role="status" className="px-1 text-caption text-muted-foreground">
{status === "error" ? (
<Button size="xs" variant="ghost" onClick={() => void retry()}>
@@ -249,6 +281,7 @@ function DocEditor({ doc }: { doc: Doc }) {
t(($) => $.editor.saved)
) : null}
</span>
+ )}
<Button
size="icon-sm"
variant="ghost"
@@ -309,7 +342,7 @@ function DocEditor({ doc }: { doc: Doc }) {
</>
}
/>
- {status === "conflict" && (
+ {solo && status === "conflict" && (
<div
role="alert"
className="flex flex-wrap items-center gap-2 border-b bg-warning/10 px-6 py-2 text-body"
@@ -342,12 +375,15 @@ function DocEditor({ doc }: { doc: Doc }) {
)}
<input
aria-label={t(($) => $.editor.title_label)}
- value={draft.title}
+ value={solo ? draft.title : liveTitle.value}
// A doc just created from the tree is blank: start in its title.
autoFocus={!doc.title && !doc.content}
maxLength={300}
placeholder={t(($) => $.untitled)}
- onChange={(e) => change({ title: e.target.value })}
+ onChange={(e) =>
+ solo ? change({ title: e.target.value }) : liveTitle.change(e.target.value)
+ }
+ onBlur={solo ? undefined : liveTitle.blur}
className="w-full bg-transparent text-display-sm font-semibold outline-none"
/>
<div className="mt-3 mb-8 flex items-center gap-2 text-caption text-muted-foreground">
@@ -370,6 +406,21 @@ function DocEditor({ doc }: { doc: Doc }) {
</Tooltip>
</div>
<div ref={bodyRef} onClick={onBodyClick}>
+ {collab.mode === "checking" || (live && !live.synced) ? (
+ <ReadonlyContent content={doc.content} className="min-h-80" />
+ ) : live ? (
+ <ContentEditor
+ key={live.generation}
+ collaboration={live.collaboration}
+ selectionAction={commentAction}
+ placeholder={t(($) => $.editor.placeholder)}
+ enableSlashCommands
+ slashCommandMode="blocks"
+ showBlockHandles
+ onUploadFile={uploadFile}
+ className="min-h-80"
+ />
+ ) : (
<ContentEditor
selectionAction={commentAction}
value={draft.content}
@@ -383,6 +434,7 @@ function DocEditor({ doc }: { doc: Doc }) {
onUploadFile={uploadFile}
className="min-h-80"
/>
+ )}
</div>
</div>
</div>
@@ -429,3 +481,75 @@ function DocEditor({ doc }: { doc: Doc }) {
</div>
);
}
+
+function LiveStatus({
+ connected,
+ synced,
+ collaborators,
+ titleFailed,
+ onRetryTitle,
+}: {
+ connected: boolean;
+ synced: boolean;
+ collaborators: DocCollaborator[];
+ titleFailed: boolean;
+ onRetryTitle: () => void;
+}) {
+ const { t } = useT("docs");
+ return (
+ <span role="status" className="flex items-center gap-2 px-1 text-caption text-muted-foreground">
+ {collaborators.length > 0 && (
+ <span className="flex -space-x-1" aria-label={t(($) => $.editor.editing_now)}>
+ {collaborators.slice(0, 5).map((c) => (
+ <Tooltip key={c.key}>
+ <TooltipTrigger
+ render={
+ <span
+ data-collaborator={c.name}
+ className="rounded-full ring-2"
+ style={{ ["--tw-ring-color" as string]: c.color }}
+ />
+ }
+ >
+ <ActorAvatar actorType={c.kind} actorId={c.id} size="xs" />
+ </TooltipTrigger>
+ <TooltipContent>{c.name}</TooltipContent>
+ </Tooltip>
+ ))}
+ {collaborators.length > 5 && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ data-collaborators-more
+ className="flex h-5 min-w-5 items-center justify-center rounded-full bg-muted px-1 text-caption ring-2 ring-background"
+ />
+ }
+ >
+ +{collaborators.length - 5}
+ </TooltipTrigger>
+ <TooltipContent>
+ {collaborators
+ .slice(5)
+ .map((c) => c.name)
+ .join(", ")}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </span>
+ )}
+ {titleFailed ? (
+ <Button size="xs" variant="ghost" onClick={onRetryTitle}>
+ {t(($) => $.editor.title_save_failed)}
+ </Button>
+ ) : connected && synced ? (
+ <span className="flex items-center gap-1">
+ <span aria-hidden className="size-1.5 rounded-full bg-success" />
+ {t(($) => $.editor.live)}
+ </span>
+ ) : (
+ t(($) => (synced ? $.editor.reconnecting : $.editor.connecting))
+ )}
+ </span>
+ );
+}
diff --git a/packages/views/docs/components/dom-throttle.ts b/packages/views/docs/components/dom-throttle.ts
new file mode 100644
index 0000000000..ee8b95c6ac
--- /dev/null
+++ b/packages/views/docs/components/dom-throttle.ts
@@ -0,0 +1,23 @@
+/**
+ * Runs `fn` once now and then at most once per `intervalMs` while `target`'s
+ * subtree keeps changing. A live doc changes on every keystroke and caret
+ * move of every collaborator, so per-frame work would run sixty times a
+ * second; the last change is always picked up within `intervalMs`.
+ */
+export function watchDom(target: Node, fn: () => void, intervalMs = 200): () => void {
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const schedule = () => {
+ if (timer) return;
+ timer = setTimeout(() => {
+ timer = null;
+ fn();
+ }, intervalMs);
+ };
+ fn();
+ const observer = new MutationObserver(schedule);
+ observer.observe(target, { childList: true, subtree: true, characterData: true });
+ return () => {
+ observer.disconnect();
+ if (timer) clearTimeout(timer);
+ };
+}
diff --git a/packages/views/docs/components/use-doc-collab.ts b/packages/views/docs/components/use-doc-collab.ts
new file mode 100644
index 0000000000..d82fd447fd
--- /dev/null
+++ b/packages/views/docs/components/use-doc-collab.ts
@@ -0,0 +1,171 @@
+"use client";
+import { useEffect, useMemo, useState } from "react";
+import * as Y from "yjs";
+import { HocuspocusProvider } from "@hocuspocus/provider";
+import { api } from "@multica/core/api";
+import { useAuthStore } from "@multica/core/auth";
+import { useWS } from "@multica/core/realtime";
+import type { EditorCollaboration } from "../../editor/extensions";
+
+/** How long a first connection may take before the page edits without the
+ * live session. Saves then go through the API, which merges them in. */
+const CONNECT_TIMEOUT_MS = 8000;
+
+/** Servers that answered that live editing is off. That is server
+ * configuration, so later docs open for solo editing without asking again. */
+const liveEditingOff = new Set<string>();
+
+const COLORS = ["#2563eb", "#db2777", "#059669", "#d97706", "#7c3aed", "#0891b2", "#dc2626", "#4f46e5"];
+
+function colorFor(id: string): string {
+ let hash = 0;
+ for (const char of id) hash = (hash * 31 + char.charCodeAt(0)) | 0;
+ return COLORS[Math.abs(hash) % COLORS.length]!;
+}
+
+/** Someone else in the session: a person, or an agent writing through the API. */
+export interface DocCollaborator {
+ key: number;
+ id: string;
+ name: string;
+ color: string;
+ kind: "member" | "agent";
+}
+
+export type DocCollabState =
+ /** Asking the server whether live editing is on. */
+ | { mode: "checking" }
+ /** Live editing is off or unreachable: edit through the API. */
+ | { mode: "solo" }
+ | {
+ mode: "live";
+ /** False until the first sync; the editor waits for it. */
+ synced: boolean;
+ connected: boolean;
+ collaboration: EditorCollaboration;
+ collaborators: DocCollaborator[];
+ /** Changes the editor's key when the session starts over. */
+ generation: number;
+ };
+
+interface Session {
+ ydoc: Y.Doc;
+ provider: HocuspocusProvider;
+ generation: number;
+}
+
+export function useDocCollab(docId: string): DocCollabState {
+ const { collabUrl } = useWS();
+ const user = useAuthStore((s) => s.user);
+ const [mode, setMode] = useState<"checking" | "solo" | "live">(() =>
+ liveEditingOff.has(collabUrl) ? "solo" : "checking",
+ );
+ const [document, setDocument] = useState<string | null>(null);
+ const [generation, setGeneration] = useState(0);
+ const [session, setSession] = useState<Session | null>(null);
+ const [synced, setSynced] = useState(false);
+ const [connected, setConnected] = useState(false);
+ const [collaborators, setCollaborators] = useState<DocCollaborator[]>([]);
+
+ useEffect(() => {
+ if (liveEditingOff.has(collabUrl)) {
+ setMode("solo");
+ return;
+ }
+ let cancelled = false;
+ setMode("checking");
+ api
+ .createDocCollabTicket(docId)
+ .then((ticket) => {
+ if (ticket.enabled) liveEditingOff.delete(collabUrl);
+ else liveEditingOff.add(collabUrl);
+ if (cancelled) return;
+ setDocument(ticket.enabled ? ticket.document : null);
+ setMode(ticket.enabled ? "live" : "solo");
+ })
+ .catch(() => {
+ if (!cancelled) setMode("solo");
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [docId, collabUrl]);
+
+ useEffect(() => {
+ if (mode !== "live" || !document) return;
+ const ydoc = new Y.Doc();
+ let everSynced = false;
+ const provider = new HocuspocusProvider({
+ url: collabUrl,
+ name: document,
+ document: ydoc,
+ // Asked on every (re)connect. The epoch names the copy this tab holds,
+ // so the server can tell it to start over if the doc was rebuilt.
+ token: async () => {
+ const ticket = await api.createDocCollabTicket(docId);
+ if (!ticket.enabled) throw new Error("live editing is off");
+ const epoch = ydoc.getMap("meta").get("epoch");
+ return JSON.stringify({ ticket: ticket.token, epoch: typeof epoch === "string" ? epoch : undefined });
+ },
+ onSynced: ({ state }) => {
+ if (!state) return;
+ everSynced = true;
+ setSynced(true);
+ },
+ onStatus: ({ status }) => setConnected(status === "connected"),
+ onClose: ({ event }) => {
+ if (event.reason === "document-reset") setGeneration((g) => g + 1);
+ },
+ });
+ // Awareness changes on every caret move of every editor; only re-render
+ // when who is here changes.
+ let signature = "";
+ const updateCollaborators = () => {
+ const seen = new Set<string>();
+ const next: DocCollaborator[] = [];
+ for (const [key, state] of provider.awareness?.getStates() ?? []) {
+ if (key === ydoc.clientID) continue;
+ const u = (state as { user?: Partial<DocCollaborator> }).user;
+ if (!u?.name || !u.id) continue;
+ const dedupe = `${u.kind}:${u.id}`;
+ if (seen.has(dedupe)) continue;
+ seen.add(dedupe);
+ next.push({ key, id: u.id, name: u.name, color: u.color ?? colorFor(u.id), kind: u.kind === "agent" ? "agent" : "member" });
+ }
+ const nextSignature = next.map((c) => `${c.key}:${c.kind}:${c.id}:${c.name}:${c.color}`).join("|");
+ if (nextSignature === signature) return;
+ signature = nextSignature;
+ setCollaborators(next);
+ };
+ provider.awareness?.on("change", updateCollaborators);
+ const timeout = setTimeout(() => {
+ if (!everSynced) setMode("solo");
+ }, CONNECT_TIMEOUT_MS);
+ setSession({ ydoc, provider, generation });
+ return () => {
+ clearTimeout(timeout);
+ provider.awareness?.off("change", updateCollaborators);
+ provider.destroy();
+ ydoc.destroy();
+ setSession(null);
+ setSynced(false);
+ setConnected(false);
+ setCollaborators([]);
+ };
+ }, [mode, document, docId, collabUrl, generation]);
+
+ const collaboration = useMemo<EditorCollaboration | null>(() => {
+ if (!session || !user) return null;
+ return {
+ document: session.ydoc,
+ provider: session.provider,
+ user: { name: user.name || user.email, color: colorFor(user.id), id: user.id, kind: "member" },
+ };
+ }, [session, user]);
+
+ if (mode === "checking") return { mode };
+ if (mode === "solo" || !collaboration || !session) {
+ return mode === "solo" ? { mode } : { mode: "checking" };
+ }
+ return { mode: "live", synced, connected, collaboration, collaborators, generation: session.generation };
+}
diff --git a/packages/views/docs/components/use-doc-comment-highlights.ts b/packages/views/docs/components/use-doc-comment-highlights.ts
index 88bcabdf13..1baffd9886 100644
--- a/packages/views/docs/components/use-doc-comment-highlights.ts
+++ b/packages/views/docs/components/use-doc-comment-highlights.ts
@@ -1,6 +1,8 @@
"use client";
import { useEffect, useRef, useState, type RefObject } from "react";
+import { indexCommentText } from "../../issues/components/comment-annotation-selection";
import { docAnchorRange, type DocAnchor } from "./doc-comment-anchors";
+import { watchDom } from "./dom-throttle";
export interface AnchoredThread extends DocAnchor {
id: string;
@@ -34,14 +36,14 @@ export function useDocCommentHighlights(
useEffect(() => {
const host = rootRef.current;
if (!host) return;
- let frame = 0;
const paint = () => {
const root = host.querySelector<HTMLElement>(".ProseMirror");
if (!root) return;
const ranges = new Map<string, Range>();
const gone = new Set<string>();
+ const index = indexCommentText(root, true);
for (const thread of threadsRef.current) {
- const range = docAnchorRange(root, thread);
+ const range = docAnchorRange(root, thread, index);
if (range) ranges.set(thread.id, range);
else gone.add(thread.id);
}
@@ -56,16 +58,9 @@ export function useDocCommentHighlights(
else CSS.highlights.delete(ACTIVE_HIGHLIGHT);
}
};
- const schedule = () => {
- cancelAnimationFrame(frame);
- frame = requestAnimationFrame(paint);
- };
- schedule();
- const observer = new MutationObserver(schedule);
- observer.observe(host, { childList: true, subtree: true, characterData: true });
+ const stop = watchDom(host, paint);
return () => {
- observer.disconnect();
- cancelAnimationFrame(frame);
+ stop();
if (canHighlight()) {
CSS.highlights.delete(HIGHLIGHT);
CSS.highlights.delete(ACTIVE_HIGHLIGHT);
diff --git a/packages/views/docs/components/use-doc-draft.test.tsx b/packages/views/docs/components/use-doc-draft.test.tsx
index f5116d6a6c..e6d983a0c1 100644
--- a/packages/views/docs/components/use-doc-draft.test.tsx
+++ b/packages/views/docs/components/use-doc-draft.test.tsx
@@ -432,3 +432,42 @@ it("keeps a space typed at the end of the title after the server saves it trimme
});
expect(view.result.current.draft.title).toBe("Release notes");
});
+
+it("sends nothing while the doc is edited live, not even on exit", async () => {
+ const client = new QueryClient();
+ setDocDraft("ws-review:doc-review", {
+ title: doc.title,
+ content: "Left over from an earlier solo session",
+ baseTitle: doc.title,
+ baseContent: doc.content,
+ baseRevision: 1,
+ });
+ const view = renderHook(() => useDocDraft(doc, false), {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000);
+ });
+ view.unmount();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000);
+ });
+ expect(api.updateDoc).not.toHaveBeenCalled();
+});
+
+it("sets unsaved edits aside as a backup instead of saving them", async () => {
+ const view = mount();
+ act(() => view.result.current.change({ content: "Stale edit" }));
+ act(() => view.result.current.setAside());
+ expect(view.result.current.dirty).toBe(false);
+ expect(useDocDraftStore.getState().draft.entries["ws-review:doc-review"]).toMatchObject({
+ content: doc.content,
+ backup: { title: doc.title, content: "Stale edit" },
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000);
+ });
+ expect(api.updateDoc).not.toHaveBeenCalled();
+});
diff --git a/packages/views/docs/components/use-doc-draft.ts b/packages/views/docs/components/use-doc-draft.ts
index b7351bf0fb..39b9f85e7d 100644
--- a/packages/views/docs/components/use-doc-draft.ts
+++ b/packages/views/docs/components/use-doc-draft.ts
@@ -22,7 +22,12 @@ const fromDoc = (doc: Doc): DocDraft => ({
baseContent: doc.content,
baseRevision: doc.revision,
});
-export function useDocDraft(doc: Doc) {
+/**
+ * The doc as edited through the API: a local draft, saved after a pause and
+ * when the page goes away. `enabled` is false while the doc is (or may be)
+ * edited live, when the shared document saves the body: nothing is sent then.
+ */
+export function useDocDraft(doc: Doc, enabled = true) {
const wsId = useWorkspaceId();
const key = `${wsId}:${doc.id}`;
const draft = useDocDraftStore((s) => s.draft.entries[key]);
@@ -39,6 +44,8 @@ export function useDocDraft(doc: Doc) {
// before the parent passes the refreshed `doc`, so falling back to the prop
// would briefly hand the editor the pre-save content and reset its caret.
const savedDoc = useRef<Doc | null>(null);
+ const enabledRef = useRef(enabled);
+ enabledRef.current = enabled;
// The server trims titles. Keep what was typed in the field, so a pause
// after a space does not join the next word to the previous one.
const typedTitle = useRef<{ typed: string; saved: string } | null>(null);
@@ -59,7 +66,7 @@ export function useDocDraft(doc: Doc) {
// Child editor cleanup can still publish its final pending update.
// StrictMode's effect replay remounts before this microtask runs.
queueMicrotask(() => {
- if (!alive.current && statusRef.current === "saved")
+ if (!alive.current && enabledRef.current && statusRef.current === "saved")
void saveRef.current();
});
};
@@ -141,17 +148,17 @@ export function useDocDraft(doc: Doc) {
} finally {
saving.current = false;
// Edits made during the request still need saving after navigation.
- if (saved && !alive.current) void save();
+ if (saved && !alive.current && enabledRef.current) void save();
}
};
saveRef.current = save;
useEffect(() => {
- if (!draft || !dirty || status !== "saved") return;
+ if (!enabled || !draft || !dirty || status !== "saved") return;
const timer = setTimeout(() => {
void saveRef.current();
}, 1500);
return () => clearTimeout(timer);
- }, [draft, dirty, status]);
+ }, [enabled, draft, dirty, status]);
const change = (patch: Partial<Pick<DocDraft, "title" | "content">>) => {
if (!inScope()) return;
const current =
@@ -176,5 +183,16 @@ export function useDocDraft(doc: Doc) {
if (inScope()) updateStatus("error");
}
};
- return { draft: value, status, dirty, change, retry: save, reload };
+ /** Keeps unsaved edits as a read-only backup instead of saving them: they
+ * were made against an older copy, and the live document has moved on. */
+ const setAside = () => {
+ const current = useDocDraftStore.getState().draft.entries[key];
+ if (!current || !inScope()) return;
+ if (current.title === current.baseTitle && current.content === current.baseContent) return;
+ setDocDraft(key, {
+ ...fromDoc(latestDoc),
+ backup: { title: current.title, content: current.content },
+ });
+ };
+ return { draft: value, status, dirty, change, retry: save, reload, setAside };
}
diff --git a/packages/views/docs/components/use-live-doc-title.test.tsx b/packages/views/docs/components/use-live-doc-title.test.tsx
new file mode 100644
index 0000000000..1fa271a46c
--- /dev/null
+++ b/packages/views/docs/components/use-live-doc-title.test.tsx
@@ -0,0 +1,123 @@
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { ReactNode } from "react";
+import type { Doc } from "@multica/core/types";
+import { api } from "@multica/core/api";
+import { useLiveDocTitle } from "./use-live-doc-title";
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));
+vi.mock("@multica/core/api", () => ({ api: { updateDoc: vi.fn() } }));
+
+const doc: Doc = {
+ id: "doc",
+ workspaceId: "ws",
+ folderId: null,
+ title: "Runbook",
+ content: "Body",
+ revision: 1,
+ versionCount: 1,
+ createdByType: "member",
+ createdById: "u1",
+ updatedByType: "member",
+ updatedById: "u1",
+ createdAt: "2026-11-09T00:00:00Z",
+ updatedAt: "2026-11-09T00:00:00Z",
+};
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ vi.mocked(api.updateDoc).mockImplementation(async (_id, data) => ({
+ ...doc,
+ title: (data.title ?? doc.title).trim(),
+ revision: data.baseRevision + 1,
+ }));
+});
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+function mount(initial: { doc: Doc; enabled: boolean }) {
+ const client = new QueryClient();
+ return renderHook((props: { doc: Doc; enabled: boolean }) => useLiveDocTitle(props.doc, props.enabled), {
+ initialProps: initial,
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ });
+}
+
+it("saves after a pause, even while collaborators keep bumping the revision", async () => {
+ const view = mount({ doc, enabled: true });
+ act(() => view.result.current.change("Release runbook"));
+ for (let revision = 2; revision <= 4; revision++) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(200);
+ });
+ view.rerender({ doc: { ...doc, revision }, enabled: true });
+ }
+ expect(api.updateDoc).not.toHaveBeenCalled();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(200);
+ });
+ expect(api.updateDoc).toHaveBeenCalledExactlyOnceWith(doc.id, { baseRevision: 4, title: "Release runbook" });
+});
+
+it("saves a title typed just before leaving the page", async () => {
+ const view = mount({ doc, enabled: true });
+ act(() => view.result.current.change("Renamed"));
+ view.unmount();
+ expect(api.updateDoc).toHaveBeenCalledExactlyOnceWith(doc.id, { baseRevision: 1, title: "Renamed" });
+});
+
+it("saves at once when the field loses focus", async () => {
+ const view = mount({ doc, enabled: true });
+ act(() => view.result.current.change("Renamed"));
+ act(() => view.result.current.blur());
+ expect(api.updateDoc).toHaveBeenCalledExactlyOnceWith(doc.id, { baseRevision: 1, title: "Renamed" });
+});
+
+it("offers a retry after a failed save", async () => {
+ vi.mocked(api.updateDoc).mockRejectedValueOnce(new Error("Offline"));
+ const view = mount({ doc, enabled: true });
+ act(() => view.result.current.change("Renamed"));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(900);
+ });
+ expect(view.result.current.failed).toBe(true);
+ await act(async () => {
+ view.result.current.retry();
+ });
+ expect(api.updateDoc).toHaveBeenCalledTimes(2);
+ expect(view.result.current.failed).toBe(false);
+});
+
+it("holds a title typed while connecting and saves it once live", async () => {
+ const view = mount({ doc, enabled: false });
+ act(() => view.result.current.change("Typed early"));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+ expect(api.updateDoc).not.toHaveBeenCalled();
+ expect(view.result.current.value).toBe("Typed early");
+ view.rerender({ doc, enabled: true });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(900);
+ });
+ expect(api.updateDoc).toHaveBeenCalledExactlyOnceWith(doc.id, { baseRevision: 1, title: "Typed early" });
+});
+
+it("hands a title typed while connecting to the solo draft", () => {
+ const view = mount({ doc, enabled: false });
+ act(() => view.result.current.change("Typed early"));
+ let taken: string | null = null;
+ act(() => {
+ taken = view.result.current.take();
+ });
+ expect(taken).toBe("Typed early");
+ expect(view.result.current.value).toBe(doc.title);
+ view.unmount();
+ expect(api.updateDoc).not.toHaveBeenCalled();
+});
diff --git a/packages/views/docs/components/use-live-doc-title.ts b/packages/views/docs/components/use-live-doc-title.ts
new file mode 100644
index 0000000000..a705e19712
--- /dev/null
+++ b/packages/views/docs/components/use-live-doc-title.ts
@@ -0,0 +1,90 @@
+"use client";
+import { useEffect, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { api } from "@multica/core/api";
+import { docKeys } from "@multica/core/docs";
+import { useWorkspaceId } from "@multica/core/hooks";
+import type { Doc } from "@multica/core/types";
+
+const SAVE_DELAY_MS = 800;
+
+/**
+ * The title of a doc being edited live. The body syncs through the shared
+ * document; the title is saved on its own, last write wins, so a rename never
+ * touches what people are typing. Until `enabled`, typing is only held, so a
+ * title typed while the page is still connecting is not lost.
+ */
+export function useLiveDocTitle(doc: Doc, enabled: boolean) {
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ // What was typed, kept until the field loses focus so a pause after a space
+ // does not lose the space to the server's trim.
+ const [typed, setTyped] = useState<string | null>(null);
+ const [failed, setFailed] = useState(false);
+ const saved = useRef<string | null>(null);
+ // Read when sending, not watched: live body edits bump the revision every
+ // few seconds and must not keep restarting the title's debounce.
+ const latest = useRef({ doc, enabled, typed });
+ latest.current = { doc, enabled, typed };
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const sequence = useRef(0);
+
+ const pending = () => {
+ const { doc: current, typed: title } = latest.current;
+ return title !== null && title.trim() !== (saved.current ?? current.title) ? title : null;
+ };
+ const send = () => {
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = null;
+ const title = pending();
+ if (!latest.current.enabled || title === null) return;
+ const { doc: current } = latest.current;
+ const attempt = ++sequence.current;
+ api
+ .updateDoc(current.id, { baseRevision: current.revision, title })
+ .then((updated) => {
+ if (attempt !== sequence.current) return;
+ saved.current = updated.title;
+ setFailed(false);
+ qc.setQueryData(docKeys.detail(wsId, current.id), updated);
+ })
+ .catch(() => {
+ if (attempt === sequence.current) setFailed(true);
+ });
+ };
+
+ useEffect(() => {
+ if (!enabled || pending() === null) return;
+ timer.current = setTimeout(send, SAVE_DELAY_MS);
+ return () => {
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = null;
+ };
+ // `send` reads everything else through `latest`.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [enabled, typed, doc.title]);
+
+ // Leaving the page within the debounce still saves the title.
+ useEffect(() => () => send(), []); // eslint-disable-line react-hooks/exhaustive-deps
+
+ return {
+ value: typed ?? doc.title,
+ failed,
+ change: (title: string) => setTyped(title),
+ blur: () => {
+ send();
+ if (typed !== null && typed.trim() === (saved.current ?? doc.title)) {
+ setTyped(null);
+ saved.current = null;
+ }
+ },
+ retry: send,
+ /** Hands over a title typed before live editing turned out to be off. */
+ take: (): string | null => {
+ const title = typed;
+ setTyped(null);
+ saved.current = null;
+ return title;
+ },
+ };
+}
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 63d0846077..81f410508b 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -57,7 +57,7 @@ import {
import type { MentionItem } from "./extensions/mention-suggestion";
import type { IssueIdentifierResolver } from "./extensions/issue-identifier-autolink";
import type { BuiltinCommandSuggestionOptions } from "./extensions/slash-command-suggestion";
-import { createEditorExtensions } from "./extensions";
+import { createEditorExtensions, type EditorCollaboration } from "./extensions";
import {
uploadAndInsertFile,
insertUploadPlaceholder,
@@ -251,6 +251,14 @@ interface ContentEditorBaseProps {
* signal to swap their static shell for the live editor.
*/
onReady?: () => void;
+ /**
+ * Edit a shared Yjs document with other people and agents. The document is
+ * the source of truth: `value` / `defaultValue` are ignored, there is no
+ * local history to adopt external content into, and `onUpdate` only reports
+ * what the shared document now holds. The host remounts the editor (`key`)
+ * to switch documents.
+ */
+ collaboration?: EditorCollaboration;
}
type ContentEditorValueProps =
@@ -413,6 +421,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
attachments,
flushPendingOnUnmount = false,
onReady,
+ collaboration,
},
ref,
) {
@@ -589,7 +598,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
return issue ? { id: issue.id, identifier: issue.identifier } : null;
};
- const initialMarkdown = value ?? defaultValue ?? "";
+ const initialMarkdown = collaboration ? "" : (value ?? defaultValue ?? "");
const initialContent = initialMarkdown
? // One-shot read: the editor preprocesses its initial document once at
// load. Unlike the readonly renderer it does not need to re-run when
@@ -674,6 +683,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
quickActionMenuRef.current?.getQuickActionContent?.(id) ?? "",
},
resolveIssueIdentifierRef,
+ collaboration,
}),
onUpdate: ({ editor: ed }) => {
if (!onUpdateRef.current) return;
@@ -901,7 +911,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
// without this effect, a WS-driven description update keeps the editor
// showing stale content until the issue is closed and reopened.
useEffect(() => {
- if (!editor || editor.isDestroyed || value === undefined) return;
+ if (!editor || editor.isDestroyed || value === undefined || collaboration) return;
const previousValue = lastSyncedValueRef.current;
lastSyncedValueRef.current = value;
@@ -949,7 +959,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
if (isDirty) return;
applyExternalContent(value);
- }, [value, editor, applyExternalContent]);
+ }, [value, editor, applyExternalContent, collaboration]);
// Sync external `placeholder` changes into the mounted editor.
// The Placeholder extension is configured with a getter over `placeholderRef`
diff --git a/packages/views/editor/extensions/coalesced-awareness.test.ts b/packages/views/editor/extensions/coalesced-awareness.test.ts
new file mode 100644
index 0000000000..2b21e8f193
--- /dev/null
+++ b/packages/views/editor/extensions/coalesced-awareness.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import * as Y from "yjs";
+import { Awareness } from "y-protocols/awareness";
+import { coalesceAwarenessChanges } from "./coalesced-awareness";
+
+describe("coalesceAwarenessChanges", () => {
+ let awareness: Awareness;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ awareness = new Awareness(new Y.Doc());
+ });
+
+ afterEach(() => {
+ awareness.destroy();
+ vi.useRealTimers();
+ });
+
+ it("delivers a burst of changes as one call", () => {
+ const view = coalesceAwarenessChanges(awareness, 50);
+ const listener = vi.fn();
+ view.on("change", listener);
+
+ for (let i = 0; i < 10; i++) view.setLocalStateField("cursor", i);
+ expect(listener).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(50);
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect(awareness.getLocalState()?.cursor).toBe(9);
+ });
+
+ it("passes other events and reads straight through", () => {
+ const view = coalesceAwarenessChanges(awareness, 50);
+ const onUpdate = vi.fn();
+ view.on("update", onUpdate);
+
+ view.setLocalStateField("user", { name: "Ada" });
+ expect(onUpdate).toHaveBeenCalledTimes(1);
+ expect(view.clientID).toBe(awareness.clientID);
+ expect(view.getStates().get(awareness.clientID)?.user).toEqual({ name: "Ada" });
+ });
+
+ it("drops a pending call once the listener is removed", () => {
+ const view = coalesceAwarenessChanges(awareness, 50);
+ const listener = vi.fn();
+ view.on("change", listener);
+
+ view.setLocalStateField("cursor", 1);
+ view.off("change", listener);
+ vi.advanceTimersByTime(50);
+ view.setLocalStateField("cursor", 2);
+ vi.advanceTimersByTime(50);
+
+ expect(listener).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/editor/extensions/coalesced-awareness.ts b/packages/views/editor/extensions/coalesced-awareness.ts
new file mode 100644
index 0000000000..7a0640b81a
--- /dev/null
+++ b/packages/views/editor/extensions/coalesced-awareness.ts
@@ -0,0 +1,57 @@
+import type { Awareness } from "y-protocols/awareness";
+
+type Listener = (...args: unknown[]) => void;
+
+/**
+ * A view of `awareness` whose "change" listeners fire at most once per
+ * `intervalMs`. The caret plugin redraws every collaborator's caret on each
+ * change, and every caret move of every collaborator is a change, so with
+ * dozens of people typing it would redraw hundreds of times a second.
+ * Everything else, including "update" and all writes, passes straight through.
+ */
+export function coalesceAwarenessChanges(awareness: Awareness, intervalMs = 50): Awareness {
+ const wrapped = new Map<Listener, { listener: Listener; cancel: () => void }>();
+
+ const coalesce = (listener: Listener) => {
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let lastArgs: unknown[] = [];
+ return {
+ listener: (...args: unknown[]) => {
+ lastArgs = args;
+ if (timer) return;
+ timer = setTimeout(() => {
+ timer = null;
+ listener(...lastArgs);
+ }, intervalMs);
+ },
+ cancel: () => {
+ if (timer) clearTimeout(timer);
+ timer = null;
+ },
+ };
+ };
+
+ return new Proxy(awareness, {
+ get(target, prop) {
+ if (prop === "on") {
+ return (event: string, listener: Listener) => {
+ if (event !== "change") return target.on(event as "change", listener);
+ const coalesced = coalesce(listener);
+ wrapped.set(listener, coalesced);
+ target.on("change", coalesced.listener);
+ };
+ }
+ if (prop === "off") {
+ return (event: string, listener: Listener) => {
+ const coalesced = event === "change" ? wrapped.get(listener) : undefined;
+ if (!coalesced) return target.off(event as "change", listener);
+ coalesced.cancel();
+ wrapped.delete(listener);
+ target.off("change", coalesced.listener);
+ };
+ }
+ const value = Reflect.get(target, prop, target);
+ return typeof value === "function" ? value.bind(target) : value;
+ },
+ });
+}
diff --git a/packages/views/editor/extensions/code-block.test.ts b/packages/views/editor/extensions/code-block.test.ts
index fca8d5bc36..33e8a41cae 100644
--- a/packages/views/editor/extensions/code-block.test.ts
+++ b/packages/views/editor/extensions/code-block.test.ts
@@ -1,7 +1,12 @@
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { Editor } from "@tiptap/core";
+import type { DecorationSet } from "@tiptap/pm/view";
import { createEditorExtensions } from ".";
import { preprocessMarkdown } from "../utils/preprocess";
+import StarterKit from "@tiptap/starter-kit";
+import { Markdown } from "@tiptap/markdown";
+import { codeLowlight } from "../syntax-highlight";
+import { CodeBlockExtension } from "./code-block";
import {
MARKDOWN_CHUNK_THRESHOLD,
parseMarkdownChunked,
@@ -146,3 +151,43 @@ describe("production preprocessing and large-document loading", () => {
},
);
});
+
+describe("syntax highlighting", () => {
+ const markdown = "Intro\n\n```ts\nconst a = 1;\n```\n\n```ts\nlet b = 2;\n```";
+ const highlightPlugins = (editor: Editor) =>
+ editor.state.plugins.filter((p) => /^(lowlight|codeHighlight)\$/.test((p as unknown as { key: string }).key));
+ const highlighted = (editor: Editor) =>
+ (highlightPlugins(editor)[0]!.getState(editor.state) as DecorationSet)
+ .find()
+ .filter((d) => (d as unknown as { type: { attrs: { class: string } } }).type.attrs.class === "hljs-keyword")
+ .map((d) => editor.state.doc.textBetween(d.from, d.to));
+
+ it("highlights each code block", () => {
+ const editor = load(markdown);
+ expect(highlighted(editor)).toEqual(["const", "let"]);
+ expect(highlightPlugins(editor)).toHaveLength(1);
+ });
+
+ it("highlights again only the code block that changed", () => {
+ const highlight = vi.fn(codeLowlight.highlight);
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ const editor = new Editor({
+ element,
+ extensions: [StarterKit.configure({ codeBlock: false }), CodeBlockExtension.configure({ lowlight: { ...codeLowlight, highlight } }), Markdown],
+ content: markdown,
+ contentType: "markdown",
+ });
+ editors.push(editor);
+ expect(highlight).toHaveBeenCalledTimes(2);
+ editor.commands.insertContentAt(2, "x");
+ expect(highlight).toHaveBeenCalledTimes(2);
+ let second = 0;
+ editor.state.doc.descendants((node, pos) => {
+ if (node.type.name === "codeBlock") second = pos;
+ });
+ editor.commands.insertContentAt(second + 1, "var c;\n");
+ expect(highlight).toHaveBeenCalledTimes(3);
+ expect(highlighted(editor)).toEqual(["const", "var", "let"]);
+ });
+});
diff --git a/packages/views/editor/extensions/code-block.ts b/packages/views/editor/extensions/code-block.ts
index ff36b3b6a7..000c3b9b2e 100644
--- a/packages/views/editor/extensions/code-block.ts
+++ b/packages/views/editor/extensions/code-block.ts
@@ -1,4 +1,81 @@
import CodeBlockLowlight from "@tiptap/extension-code-block-lowlight";
+import type { Node as PMNode } from "@tiptap/pm/model";
+import { Plugin, PluginKey } from "@tiptap/pm/state";
+import { Decoration, DecorationSet } from "@tiptap/pm/view";
+import type { createLowlight } from "lowlight";
+
+type Lowlight = ReturnType<typeof createLowlight>;
+interface HighlightSpan {
+ from: number;
+ to: number;
+ className: string;
+}
+interface HastNode {
+ value?: string;
+ children?: HastNode[];
+ properties?: { className?: string[] };
+}
+
+function highlightSpans(node: PMNode, lowlight: Lowlight, defaultLanguage: string | null): HighlightSpan[] {
+ const language = node.attrs.language || defaultLanguage;
+ const text = node.textContent;
+ const tree = language && lowlight.registered(language) ? lowlight.highlight(language, text) : lowlight.highlightAuto(text);
+ const spans: HighlightSpan[] = [];
+ let at = 0;
+ const walk = (nodes: HastNode[], classes: string[]) => {
+ for (const child of nodes) {
+ const className = [...classes, ...(child.properties?.className ?? [])];
+ if (child.children) {
+ walk(child.children, className);
+ continue;
+ }
+ const length = child.value?.length ?? 0;
+ if (className.length && length) spans.push({ from: at, to: at + length, className: className.join(" ") });
+ at += length;
+ }
+ };
+ walk(tree.children as HastNode[], []);
+ return spans;
+}
+
+/**
+ * Syntax highlighting that stays cheap on a long, live doc. The stock lowlight
+ * plugin walks every node of the doc twice on each transaction, and
+ * re-highlights every code block whenever a step spans one, which is every
+ * change a collaborator makes (they arrive as a whole-document replace).
+ * Here a code block is highlighted once per version of its node, and the walk
+ * skips inline content.
+ */
+function codeHighlightPlugin(name: string, lowlight: Lowlight, defaultLanguage: string | null) {
+ const highlighted = new WeakMap<PMNode, HighlightSpan[]>();
+ const decorate = (doc: PMNode) => {
+ const decorations: Decoration[] = [];
+ doc.descendants((node, pos) => {
+ if (node.type.name !== name) return !node.isTextblock;
+ let spans = highlighted.get(node);
+ if (!spans) {
+ spans = highlightSpans(node, lowlight, defaultLanguage);
+ highlighted.set(node, spans);
+ }
+ for (const span of spans) {
+ decorations.push(Decoration.inline(pos + 1 + span.from, pos + 1 + span.to, { class: span.className }));
+ }
+ return false;
+ });
+ return DecorationSet.create(doc, decorations);
+ };
+ const plugin: Plugin<DecorationSet> = new Plugin<DecorationSet>({
+ key: new PluginKey("codeHighlight"),
+ state: {
+ init: (_, { doc }) => decorate(doc),
+ apply: (tr, set) => (tr.docChanged ? decorate(tr.doc) : set),
+ },
+ props: {
+ decorations: (state) => plugin.getState(state),
+ },
+ });
+ return plugin;
+}
/**
* Splits a fence info string into its language (the first word) and the rest,
@@ -22,6 +99,18 @@ export function splitFenceInfo(info: string | null | undefined): {
}
export const CodeBlockExtension = CodeBlockLowlight.extend({
+ addProseMirrorPlugins() {
+ // Drops the stock plugin, and ours when an extension of this one calls
+ // back into it. Plugin keys are runtime strings ProseMirror leaves out of
+ // its types.
+ const inherited = (this.parent?.() ?? []).filter(
+ (plugin) => !/^(lowlight|codeHighlight)\$/.test((plugin as unknown as { key: string }).key),
+ );
+ return [
+ ...inherited,
+ codeHighlightPlugin(this.name, this.options.lowlight as Lowlight, this.options.defaultLanguage ?? null),
+ ];
+ },
addAttributes() {
return {
...this.parent?.(),
diff --git a/packages/views/editor/extensions/collaboration-selection.test.ts b/packages/views/editor/extensions/collaboration-selection.test.ts
new file mode 100644
index 0000000000..f203935244
--- /dev/null
+++ b/packages/views/editor/extensions/collaboration-selection.test.ts
@@ -0,0 +1,63 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { Editor } from "@tiptap/core";
+import StarterKit from "@tiptap/starter-kit";
+import Collaboration from "@tiptap/extension-collaboration";
+import * as Y from "yjs";
+import { CollaborationSelectionSync } from "./collaboration-selection";
+
+let editor: Editor | null = null;
+afterEach(() => {
+ editor?.destroy();
+ editor = null;
+ document.body.innerHTML = "";
+});
+
+function setup(withSync: boolean) {
+ const shared = new Y.Doc();
+ const fragment = shared.getXmlFragment("default");
+ const paragraph = (text: string) => {
+ const p = new Y.XmlElement("paragraph");
+ p.insert(0, [new Y.XmlText(text)]);
+ return p;
+ };
+ fragment.insert(0, [paragraph("First"), paragraph("Second"), paragraph("Third")]);
+ const local = new Y.Doc();
+ Y.applyUpdate(local, Y.encodeStateAsUpdate(shared));
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ editor = new Editor({
+ element,
+ extensions: [
+ StarterKit.configure({ undoRedo: false }),
+ Collaboration.configure({ document: local }),
+ ...(withSync ? [CollaborationSelectionSync.configure({ document: local })] : []),
+ ],
+ });
+ const view = editor.view;
+ view.focus();
+ // A click into "Second" that ProseMirror has not read yet: the browser has
+ // moved the selection, the selectionchange event is still queued.
+ const second = view.dom.querySelectorAll("p")[1]!.firstChild!;
+ window.getSelection()!.collapse(second, 3);
+ // A collaborator types in "Third" before that event runs.
+ const remote = new Y.Doc();
+ Y.applyUpdate(remote, Y.encodeStateAsUpdate(local));
+ const before = Y.encodeStateVector(remote);
+ ((remote.getXmlFragment("default").get(2) as Y.XmlElement).get(0) as Y.XmlText).insert(5, "!");
+ Y.applyUpdate(local, Y.encodeStateAsUpdate(remote, before), "remote");
+ return view;
+}
+
+describe("CollaborationSelectionSync", () => {
+ it("keeps a selection the editor has not read yet when a collaborator's change arrives", () => {
+ const view = setup(true);
+ expect(view.state.doc.child(2).textContent).toBe("Third!");
+ expect(view.state.selection.$from.parent.textContent).toBe("Second");
+ expect(view.state.selection.$from.parentOffset).toBe(3);
+ });
+
+ it("without it, the sync plugin puts the old selection back", () => {
+ const view = setup(false);
+ expect(view.state.selection.$from.parent.textContent).toBe("First");
+ });
+});
diff --git a/packages/views/editor/extensions/collaboration-selection.ts b/packages/views/editor/extensions/collaboration-selection.ts
new file mode 100644
index 0000000000..f299afea77
--- /dev/null
+++ b/packages/views/editor/extensions/collaboration-selection.ts
@@ -0,0 +1,59 @@
+import { Extension } from "@tiptap/core";
+import { Plugin, TextSelection } from "@tiptap/pm/state";
+import type { EditorView } from "@tiptap/pm/view";
+import type * as Y from "yjs";
+
+/**
+ * Keeps a click or an arrow key from being undone by a collaborator's change.
+ *
+ * ProseMirror reads a selection the browser made on the next `selectionchange`
+ * event. A collaborator's change applied before that makes the sync plugin
+ * save the old selection and put it back, so with people typing a click could
+ * leave the caret at the top of the doc. Before a remote change applies, this
+ * reads the browser's selection into the editor so the sync plugin keeps it.
+ * It must run before the Collaboration extension's own handler, hence the
+ * higher priority.
+ */
+export const CollaborationSelectionSync = Extension.create<{ document: Y.Doc | null }>({
+ name: "collaborationSelectionSync",
+ priority: 1001,
+
+ addOptions() {
+ return { document: null };
+ },
+
+ addProseMirrorPlugins() {
+ const ydoc = this.options.document;
+ if (!ydoc) return [];
+ return [
+ new Plugin({
+ view(view) {
+ const sync = () => {
+ if ((ydoc as unknown as { _transaction: Y.Transaction | null })._transaction?.local !== false) return;
+ readDOMSelection(view);
+ };
+ ydoc.on("beforeAllTransactions", sync);
+ return { destroy: () => ydoc.off("beforeAllTransactions", sync) };
+ },
+ }),
+ ];
+ },
+});
+
+function readDOMSelection(view: EditorView) {
+ if (view.composing || !view.hasFocus() || !(view.state.selection instanceof TextSelection)) return;
+ const selection = view.dom.ownerDocument.getSelection();
+ if (!selection?.anchorNode || !selection.focusNode || !view.dom.contains(selection.anchorNode)) return;
+ let anchor: number;
+ let head: number;
+ try {
+ anchor = view.posAtDOM(selection.anchorNode, selection.anchorOffset);
+ head = view.posAtDOM(selection.focusNode, selection.focusOffset);
+ } catch {
+ return;
+ }
+ const { doc } = view.state;
+ const next = TextSelection.between(doc.resolve(anchor), doc.resolve(head));
+ if (next.eq(view.state.selection)) return;
+ view.dispatch(view.state.tr.setSelection(next));
+}
diff --git a/packages/views/editor/extensions/file-card.tsx b/packages/views/editor/extensions/file-card.tsx
index e0b28dec98..182dd32af8 100644
--- a/packages/views/editor/extensions/file-card.tsx
+++ b/packages/views/editor/extensions/file-card.tsx
@@ -4,30 +4,20 @@
* FileCard — Tiptap node extension for rendering uploaded non-image files
* as styled cards instead of plain markdown links.
*
- * Markdown serialization: `!file[filename](href)` — custom syntax that is
- * unambiguous (standard `[name](url)` is indistinguishable from regular links).
+ * The schema and Markdown codec live in ../schema/file-card.ts so the
+ * collaboration server can load them without React.
*
* Loading pipeline: preprocessFileCards in preprocess.ts converts both the
* new `!file[name](url)` syntax AND legacy `[name](cdnUrl)` lines into HTML
* divs BEFORE @tiptap/markdown parses the content. The markdownTokenizer
- * below acts as a fallback for any direct markdown parsing that bypasses
+ * acts as a fallback for any direct markdown parsing that bypasses
* preprocessing.
*/
-import { Node, mergeAttributes } from "@tiptap/core";
import { ReactNodeViewRenderer, NodeViewWrapper } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
-import { FILE_CARD_URL_PATTERN } from "@multica/ui/markdown";
-import { escapeMarkdownLabel } from "../utils/escape-markdown-label";
import { Attachment } from "../attachment";
-
-// Backslash is excluded from the label char class so "\x" runs can only be
-// consumed by \\. — overlapping alternatives backtrack in 2^n ways (ReDoS,
-// GitHub #4881).
-const FILE_CARD_MARKDOWN_RE = new RegExp(
- `^!file\\[((?:\\\\.|[^\\]\\\\])*)\\]\\((${FILE_CARD_URL_PATTERN.source})\\)`,
-);
-
+import { FileCardSchema } from "../schema/file-card";
// React NodeView — thin wrapper, all rendering lives in <Attachment>
@@ -50,96 +40,7 @@ export function FileCardView({ node, editor, deleteNode }: NodeViewProps) {
);
}
-// Tiptap Node Extension
-
-export const FileCardExtension = Node.create({
- name: "fileCard",
- group: "block",
- atom: true,
-
- addAttributes() {
- return {
- href: {
- default: "",
- rendered: false, // Don't put href on DOM — prevents link behavior
- },
- filename: {
- default: "",
- rendered: false,
- },
- fileSize: {
- default: 0,
- rendered: false,
- },
- uploading: {
- default: false,
- rendered: false,
- },
- uploadId: {
- default: null,
- rendered: false,
- },
- };
- },
-
- parseHTML() {
- return [
- {
- tag: 'div[data-type="fileCard"]',
- getAttrs: (el) => ({
- href: (el as HTMLElement).getAttribute("data-href"),
- filename: (el as HTMLElement).getAttribute("data-filename"),
- }),
- },
- ];
- },
-
- renderHTML({ node, HTMLAttributes }) {
- return [
- "div",
- mergeAttributes(HTMLAttributes, {
- "data-type": "fileCard",
- "data-href": node.attrs.href,
- "data-filename": node.attrs.filename,
- }),
- ];
- },
-
- // Markdown: custom !file[name](url) syntax for unambiguous roundtrip.
- // Standard [name](url) is indistinguishable from regular links — the old
- // regex-based CDN hostname matching in preprocessFileCards was fragile.
- markdownTokenizer: {
- name: "fileCard",
- level: "block" as const,
- start(src: string) {
- return src.search(/^!file\[/m);
- },
- tokenize(src: string) {
- const match = src.match(FILE_CARD_MARKDOWN_RE);
- if (!match) return undefined;
- const filename = (match[1] ?? "").replace(/\\([[\]\\()])/g, "$1");
- return {
- type: "fileCard",
- raw: match[0],
- attributes: { filename, href: match[2] },
- };
- },
- },
- parseMarkdown: (token: any, helpers: any) => {
- return helpers.createNode("fileCard", token.attributes);
- },
- renderMarkdown: (node: any) => {
- const { href, filename, uploading } = node.attrs || {};
- // An in-flight placeholder is not content. The document IS the draft body
- // (getMarkdown → setDraft), so serialising it would persist `!file[x](
- // )` — a line the tokenizer above cannot parse back, leaving dead literal
- // text in the draft that outlives the upload and ships with the comment.
- // Emitting nothing is the whole guarantee: the card becomes content the
- // moment it has a real href, and never before.
- if (uploading === true || !href) return "";
- return `!file[${escapeMarkdownLabel(filename || "file")}](${href})`;
- },
-
+export const FileCardExtension = FileCardSchema.extend({
addNodeView() {
return ReactNodeViewRenderer(FileCardView);
},
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index 34411f2a86..942b6cdf1b 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -25,19 +25,29 @@ import { CodeBlockExtension } from "./code-block";
import Placeholder from "@tiptap/extension-placeholder";
import Link from "@tiptap/extension-link";
import Typography from "@tiptap/extension-typography";
-import Image from "@tiptap/extension-image";
import TableRow from "@tiptap/extension-table-row";
import TableHeader from "@tiptap/extension-table-header";
import TableCell from "@tiptap/extension-table-cell";
import { Table } from "@tiptap/extension-table";
import { TaskList } from "@tiptap/extension-list";
import { Markdown } from "@tiptap/markdown";
-import { Marked, type marked } from "marked";
+import Collaboration from "@tiptap/extension-collaboration";
+import CollaborationCaret from "@tiptap/extension-collaboration-caret";
+import { CollaborationSelectionSync } from "./collaboration-selection";
+import type * as Y from "yjs";
+import type { Awareness } from "y-protocols/awareness";
+import { coalesceAwarenessChanges } from "./coalesced-awareness";
+import {
+ COLLAB_FIELD,
+ createMarkedInstance,
+ ImageSchema,
+ MARKDOWN_OPTIONS,
+ STARTER_KIT_OPTIONS,
+} from "../schema";
import { ReactNodeViewRenderer } from "@tiptap/react";
import type { AnyExtension } from "@tiptap/core";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
import { shouldAutoLink } from "@multica/ui/markdown";
-import { escapeMarkdownLabel } from "../utils/escape-markdown-label";
import { BaseMentionExtension } from "./mention-extension";
import { createMentionSuggestion, type MentionItem } from "./mention-suggestion";
import {
@@ -52,7 +62,7 @@ import { SuggestionTriggerArmingExtension } from "./suggestion-trigger-arming";
import { CodeBlockView } from "./code-block-view";
import { TableView } from "./table-view";
import { RICH_TABLE_CHROME_ATTRIBUTE } from "../../rich-content/rich-table";
-import { PatchedListItem, PatchedTaskItem } from "./list-item";
+import { PatchedListItem, PatchedOrderedList, PatchedTaskItem } from "./list-item";
import { createMarkdownPasteExtension } from "./markdown-paste";
import { createMarkdownCopyExtension } from "./markdown-copy";
import { createBlurShortcutExtension } from "./blur-shortcut";
@@ -72,72 +82,19 @@ const LinkExtension = Link.extend({ inclusive: false }).configure({
shouldAutoLink,
});
-export const ImageExtension = Image.extend({
- addAttributes() {
- return {
- ...this.parent?.(),
- uploading: {
- default: false,
- renderHTML: (attrs: Record<string, unknown>) =>
- attrs.uploading ? { "data-uploading": "" } : {},
- parseHTML: (el: HTMLElement) => el.hasAttribute("data-uploading"),
- },
- // The upload this placeholder belongs to — the same value the draft
- // store knows as `clientUploadId`. Lets a settle arriving at a mount
- // that did not start the upload find the node to replace. Render-only,
- // and cleared once the node holds a real URL.
- uploadId: {
- default: null,
- rendered: false,
- },
- // Intrinsic pixel dimensions, captured on upload (file-upload.ts). The
- // browser uses width/height on <img> to compute aspect-ratio and reserve
- // the box before the image decodes, so inserting an image causes no
- // layout shift (and the post-insert scrollIntoView stays correct). Not
- // serialized to markdown — `renderMarkdown` only emits src/alt/title — so
- // round-trips stay clean.
- width: {
- default: null,
- renderHTML: (attrs: Record<string, unknown>) =>
- attrs.width ? { width: attrs.width as number } : {},
- parseHTML: (el: HTMLElement) => {
- const w = parseInt(el.getAttribute("width") || "", 10);
- return Number.isFinite(w) ? w : null;
- },
- },
- height: {
- default: null,
- renderHTML: (attrs: Record<string, unknown>) =>
- attrs.height ? { height: attrs.height as number } : {},
- parseHTML: (el: HTMLElement) => {
- const h = parseInt(el.getAttribute("height") || "", 10);
- return Number.isFinite(h) ? h : null;
- },
- },
- };
- },
+export const ImageExtension = ImageSchema.extend({
addNodeView() {
return ReactNodeViewRenderer(ImageView);
},
- renderMarkdown: (node: any) => {
- const src = node.attrs?.src || "";
- // Same rule as fileCard: an in-flight placeholder is not content. Its src
- // is a process-local `blob:` URL that expires on reload, so emitting it
- // would put a dead link in the persisted draft. This replaces the
- // after-the-fact regex scrub ContentEditor used to run on every serialise.
- if (node.attrs?.uploading === true || !src) return "";
- const alt = escapeMarkdownLabel(node.attrs?.alt || "");
- const title = node.attrs?.title;
- if (title) {
- return `![${alt}](${src} "${title}")`;
- }
- return `![${alt}](${src})`;
- },
-}).configure({
- inline: false,
- allowBase64: false,
});
+export interface EditorCollaboration {
+ document: Y.Doc;
+ provider: { awareness: Awareness | null };
+ /** Shared with everyone in the session; the caret label shows `name`. */
+ user: { name: string; color: string; [field: string]: unknown };
+}
+
export interface EditorExtensionsOptions {
/**
* Placeholder text, or a getter for it. Prefer a getter when the value can
@@ -195,6 +152,12 @@ export interface EditorExtensionsOptions {
* context; the setup layer owns React Query + workspace access.
*/
resolveIssueIdentifierRef?: RefObject<IssueIdentifierResolver | undefined>;
+ /**
+ * Bind the editor to a shared Yjs document instead of its own content.
+ * The document, not the `content` option, is then the source of truth, and
+ * history comes from Yjs so undo only reverts this user's changes.
+ */
+ collaboration?: EditorCollaboration;
}
export function createEditorExtensions(
@@ -204,30 +167,13 @@ export function createEditorExtensions(
return [
StarterKit.configure({
- // Every level Markdown can express. The Markdown parser keeps the source
- // depth of `#`…`######`, but Heading.renderHTML falls back to `levels[0]`
- // for any level it was not configured with — so `levels: [1, 2, 3]` made
- // the editor draw every H4–H6 as an H1 (MUL-6060). The same list drives
- // parseHTML, so it also decides whether a pasted `<h4>` survives as a
- // heading. This is about rendering headings the content already has; the
- // bubble menu still offers only H1–H3 as authoring choices.
- heading: { levels: [1, 2, 3, 4, 5, 6] },
- link: false,
- codeBlock: false,
- // Underline has no Markdown representation. Tiptap's extension serializes
- // the mark as `++text++`, which is not CommonMark or GFM, so ReadonlyContent
- // (react-markdown + remark-gfm) renders the delimiters literally. Disabling
- // the extension drops the mark at parse time instead: pasted `<u>` /
- // `text-decoration: underline` keep their text, and Cmd+U becomes a no-op
- // rather than a way to produce content the display layer cannot render.
- underline: false,
- // Disable StarterKit's stock ListItem — its Enter keybind binds only
- // `splitListItem`, which leaves the user stuck inside an empty top-level
- // list item (see list-item.ts). PatchedListItem below restores the
- // standard split → lift fallback chain.
- listItem: false,
+ ...STARTER_KIT_OPTIONS,
+ // Yjs owns history in a collaborative document: its undo only reverts
+ // this user's own changes, never a collaborator's or an agent's.
+ ...(options.collaboration ? { undoRedo: false } : {}),
}),
PatchedListItem,
+ PatchedOrderedList,
// Checkbox task lists: `- [ ]` / `- [x]`. TaskList + TaskItem ship their own
// markdown tokenizer / renderMarkdown, an input rule (typing `[] ` / `[x] `),
// and a checkbox NodeView. The taskList tokenizer is consulted before
@@ -268,19 +214,7 @@ export function createEditorExtensions(
BlockMathExtension,
InlineMathExtension,
HighlightExtension,
- // 3-space indent so nested ordered lists survive CommonMark in ReadonlyContent.
- // Each editor gets its own marked instance. Without one, @tiptap/markdown
- // registers every editor's tokenizers on the global `marked` with `use()`
- // and never removes them: the list grows by one editor's worth per mount,
- // every inline parse runs all of them, and each tokenizer keeps its editor,
- // the React refs its extensions close over and the unmounted DOM alive
- // (MUL-9634: ~1,000 DOM nodes retained per issue opened).
- Markdown.configure({
- indentation: { style: "space", size: 3 },
- // A Marked instance has every member MarkdownManager uses (use, Lexer,
- // defaults, lexer, setOptions); the option is typed as the global's.
- marked: new Marked() as unknown as typeof marked,
- }),
+ Markdown.configure({ ...MARKDOWN_OPTIONS, marked: createMarkedInstance() }),
// Make Cmd+C / Cmd+X / drag write Markdown source to clipboard text/plain
// so users can copy rich content out as the original Markdown.
createMarkdownCopyExtension(),
@@ -329,5 +263,39 @@ export function createEditorExtensions(
}, () => options.onEnterRef?.current),
createBlurShortcutExtension(),
createFileUploadExtension(options.onUploadFileRef!, options.pasteAsFileThresholdRef),
+ ...(options.collaboration
+ ? [
+ Collaboration.configure({
+ document: options.collaboration.document,
+ field: COLLAB_FIELD,
+ }),
+ CollaborationSelectionSync.configure({ document: options.collaboration.document }),
+ CollaborationCaret.configure({
+ provider: {
+ awareness:
+ options.collaboration.provider.awareness &&
+ coalesceAwarenessChanges(options.collaboration.provider.awareness),
+ },
+ user: options.collaboration.user,
+ render: renderCaret,
+ }),
+ ]
+ : []),
];
}
+
+/** A collaborator's caret, as the extension draws it but hidden from the text
+ * index: comment anchors read the editor's text, and a caret label sitting
+ * inside quoted text would otherwise put a name in the middle of it. */
+function renderCaret(user: Record<string, string>): HTMLElement {
+ const caret = document.createElement("span");
+ caret.classList.add("collaboration-carets__caret");
+ caret.setAttribute("aria-hidden", "true");
+ caret.style.borderColor = user.color ?? "";
+ const label = document.createElement("div");
+ label.classList.add("collaboration-carets__label");
+ label.style.backgroundColor = user.color ?? "";
+ label.textContent = user.name ?? "";
+ caret.append(label);
+ return caret;
+}
diff --git a/packages/views/editor/extensions/issue-identifier-autolink.test.ts b/packages/views/editor/extensions/issue-identifier-autolink.test.ts
index 0a86400cc3..2e056a1e06 100644
--- a/packages/views/editor/extensions/issue-identifier-autolink.test.ts
+++ b/packages/views/editor/extensions/issue-identifier-autolink.test.ts
@@ -4,6 +4,7 @@ import StarterKit from "@tiptap/starter-kit";
import Link from "@tiptap/extension-link";
import { Markdown } from "@tiptap/markdown";
import type { RefObject } from "react";
+import { ySyncPluginKey } from "@tiptap/y-tiptap";
import { BaseMentionExtension } from "./mention-extension";
import { createMarkdownPasteExtension } from "./markdown-paste";
import {
@@ -152,6 +153,19 @@ describe("createIssueIdentifierAutolinkExtension", () => {
expect(editor.getMarkdown()).not.toContain("mention://issue");
});
+ it("does not convert an identifier a collaborator typed", async () => {
+ resolveMock.mockResolvedValue({ id: "uuid-3", identifier: "MUL-3" });
+ editor = makeEditor();
+
+ editor.view.dispatch(
+ editor.state.tr.insertText("MUL-3 ", 1).setMeta(ySyncPluginKey, { isChangeOrigin: true }),
+ );
+ await flush();
+
+ expect(resolveMock).not.toHaveBeenCalled();
+ expect(editor.getMarkdown()).not.toContain("mention://issue");
+ });
+
it("does not convert an identifier inside inline code", async () => {
resolveMock.mockResolvedValue({ id: "uuid-4", identifier: "MUL-4" });
editor = makeEditor();
diff --git a/packages/views/editor/extensions/issue-identifier-autolink.ts b/packages/views/editor/extensions/issue-identifier-autolink.ts
index 6013dd9a9e..5969ac0935 100644
--- a/packages/views/editor/extensions/issue-identifier-autolink.ts
+++ b/packages/views/editor/extensions/issue-identifier-autolink.ts
@@ -31,6 +31,7 @@ import type { EditorState, Transaction } from "@tiptap/pm/state";
import type { EditorView } from "@tiptap/pm/view";
import type { Mark, Node as PMNode, NodeType } from "@tiptap/pm/model";
import type { RefObject } from "react";
+import { ySyncPluginKey } from "@tiptap/y-tiptap";
export interface ResolvedIssueRef {
/** Issue UUID. */
@@ -101,7 +102,8 @@ function collectCandidates(
rangeTo = Number.POSITIVE_INFINITY,
): Candidate[] {
const out: Candidate[] = [];
- state.doc.descendants((node, pos, parent) => {
+ const size = state.doc.content.size;
+ state.doc.nodesBetween(Math.max(0, rangeFrom), Math.min(rangeTo, size), (node, pos, parent) => {
if (!node.isText || !node.text) return;
if (isSkippedTextNode(node.marks, parent)) return;
const text = node.text;
@@ -154,8 +156,8 @@ function candidatesFromUserTransaction(
return collectCandidates(state, range.from, range.to);
}
- const caret = state.selection.from;
- const target = collectCandidates(state).find((c) => c.to === caret - 1);
+ const caret = state.selection.$from;
+ const target = collectCandidates(state, caret.start(), caret.end()).find((c) => c.to === caret.pos - 1);
return target ? [target] : [];
}
@@ -229,9 +231,13 @@ export function createIssueIdentifierAutolinkExtension(
}
// 3. Capture new candidates from a genuine user edit only (never
- // programmatic setContent or our own replacement).
+ // programmatic setContent, our own replacement, or a
+ // collaborator's change arriving).
const isUserEdit =
- tr.docChanged && !tr.getMeta("preventUpdate") && !remove;
+ tr.docChanged &&
+ !tr.getMeta("preventUpdate") &&
+ !remove &&
+ !tr.getMeta(ySyncPluginKey)?.isChangeOrigin;
if (isUserEdit) {
const fresh = candidatesFromUserTransaction(tr, newState);
if (fresh.length > 0) {
diff --git a/packages/views/editor/extensions/list-item.ts b/packages/views/editor/extensions/list-item.ts
index 33623fa69f..e932234258 100644
--- a/packages/views/editor/extensions/list-item.ts
+++ b/packages/views/editor/extensions/list-item.ts
@@ -1,5 +1,5 @@
-import { type Editor, InputRule } from "@tiptap/core";
-import { ListItem, TaskItem } from "@tiptap/extension-list";
+import { type Editor, InputRule, type JSONContent } from "@tiptap/core";
+import { ListItem, OrderedList, TaskItem } from "@tiptap/extension-list";
import { sinkListItem as pmSinkListItem } from "@tiptap/pm/schema-list";
import { type Command, TextSelection } from "@tiptap/pm/state";
import type { NodeType } from "@tiptap/pm/model";
@@ -120,10 +120,42 @@ function listItemKeymap(editor: Editor, name: string) {
};
}
+/**
+ * Drops indentation that leaked into the start of a list item's paragraphs.
+ * Children are written 3 spaces deep, but Tiptap's list tokenizers strip only
+ * the marker's width (2 for `- `, and 2 for `8. ` as they skip the period), so
+ * a paragraph after a nested list kept a space, and every save added another
+ * until the paragraph turned into a code block. Leading spaces of a Markdown
+ * paragraph are never content.
+ */
+function trimItemParagraphs<T>(item: T): T {
+ if (!item || typeof item !== "object" || Array.isArray(item)) return item;
+ const node = item as JSONContent;
+ const content = node.content?.map((child) => {
+ const first = child.content?.[0];
+ if (child.type !== "paragraph" || first?.type !== "text" || !/^[ \t]/.test(first.text ?? "")) return child;
+ const text = first.text!.replace(/^[ \t]+/, "");
+ const rest = child.content!.slice(1);
+ return { ...child, content: text ? [{ ...first, text }, ...rest] : rest };
+ });
+ return (content ? { ...node, content } : node) as T;
+}
+
export const PatchedListItem = ListItem.extend({
addKeyboardShortcuts() {
return listItemKeymap(this.editor, this.name);
},
+ parseMarkdown: (token, helpers) => trimItemParagraphs(ListItem.config.parseMarkdown!(token, helpers)),
+});
+
+/** Ordered lists build their items without ListItem's parser, so they get the
+ * same trim here. */
+export const PatchedOrderedList = OrderedList.extend({
+ parseMarkdown: (token, helpers) => {
+ const list = OrderedList.config.parseMarkdown!(token, helpers);
+ if (!list || typeof list !== "object" || Array.isArray(list) || !list.content) return list;
+ return { ...list, content: list.content.map((item) => trimItemParagraphs(item)) };
+ },
});
/**
diff --git a/packages/views/editor/extensions/math.tsx b/packages/views/editor/extensions/math.tsx
index b24d6d2179..270ed970f4 100644
--- a/packages/views/editor/extensions/math.tsx
+++ b/packages/views/editor/extensions/math.tsx
@@ -1,9 +1,9 @@
"use client";
import katex from "katex";
-import { Node, mergeAttributes } from "@tiptap/core";
import { ReactNodeViewRenderer, NodeViewWrapper } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
+import { BlockMathSchema, InlineMathSchema } from "../schema/math";
function renderMath(expression: string, displayMode: boolean): string {
return katex.renderToString(expression, {
@@ -44,124 +44,13 @@ function BlockMathView({ node }: NodeViewProps) {
);
}
-export const InlineMathExtension = Node.create({
- name: "inlineMath",
- group: "inline",
- inline: true,
- atom: true,
- selectable: true,
-
- addAttributes() {
- return {
- expression: {
- default: "",
- rendered: false,
- },
- };
- },
-
- parseHTML() {
- return [
- {
- tag: 'span[data-type="inline-math"]',
- getAttrs: (el) => ({
- expression: (el as HTMLElement).getAttribute("data-expression") ?? "",
- }),
- },
- ];
- },
-
- renderHTML({ node, HTMLAttributes }) {
- return [
- "span",
- mergeAttributes(HTMLAttributes, {
- "data-type": "inline-math",
- "data-expression": node.attrs.expression,
- }),
- node.attrs.expression,
- ];
- },
-
- // Single-dollar inline math is intentionally not parsed from Markdown and has
- // no typing input rule. Dollar amounts like `$100~$120` must stay literal;
- // users should write explicit `$$...$$` blocks for math.
- renderMarkdown: (node: any) => {
- const expression = String(node.attrs?.expression ?? "");
- return `$${expression}$`;
- },
-
+export const InlineMathExtension = InlineMathSchema.extend({
addNodeView() {
return ReactNodeViewRenderer(InlineMathView);
},
});
-export const BlockMathExtension = Node.create({
- name: "blockMath",
- group: "block",
- atom: true,
- code: true,
- defining: true,
- isolating: true,
- selectable: true,
-
- addAttributes() {
- return {
- expression: {
- default: "",
- rendered: false,
- },
- };
- },
-
- parseHTML() {
- return [
- {
- tag: 'div[data-type="block-math"]',
- getAttrs: (el) => ({
- expression: (el as HTMLElement).getAttribute("data-expression") ?? "",
- }),
- },
- ];
- },
-
- renderHTML({ node, HTMLAttributes }) {
- return [
- "div",
- mergeAttributes(HTMLAttributes, {
- "data-type": "block-math",
- "data-expression": node.attrs.expression,
- }),
- node.attrs.expression,
- ];
- },
-
- markdownTokenizer: {
- name: "blockMath",
- level: "block" as const,
- start(src: string) {
- return src.search(/^\$\$/m);
- },
- tokenize(src: string) {
- if (!src.startsWith("$$")) return undefined;
- const match = src.match(/^\$\$[ \t]*\n?([\s\S]+?)\n?\$\$(?:\n|$)/);
- if (!match) return undefined;
- return {
- type: "blockMath",
- raw: match[0],
- attributes: { expression: match[1] ?? "" },
- };
- },
- },
-
- parseMarkdown: (token: any, helpers: any) => {
- return helpers.createNode("blockMath", token.attributes);
- },
-
- renderMarkdown: (node: any) => {
- const expression = String(node.attrs?.expression ?? "");
- return `$$\n${expression}\n$$`;
- },
-
+export const BlockMathExtension = BlockMathSchema.extend({
addNodeView() {
return ReactNodeViewRenderer(BlockMathView);
},
diff --git a/packages/views/editor/extensions/mention-extension.ts b/packages/views/editor/extensions/mention-extension.ts
index 6176c315ac..2083d485e7 100644
--- a/packages/views/editor/extensions/mention-extension.ts
+++ b/packages/views/editor/extensions/mention-extension.ts
@@ -1,123 +1,11 @@
-import Mention from "@tiptap/extension-mention";
-import { mergeAttributes } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react";
import { MentionView } from "./mention-view";
-import { escapeMarkdownLabel } from "../utils/escape-markdown-label";
+import { MentionSchema } from "../schema/mention";
-const MENTION_LINK_MARKER = "](mention://";
+export { mentionText } from "../schema/mention";
-function isEscaped(text: string, index: number): boolean {
- let slashCount = 0;
- for (let i = index - 1; i >= 0 && text[i] === "\\"; i--) {
- slashCount++;
- }
- return slashCount % 2 === 1;
-}
-
-function findUnescapedMentionMarker(src: string, from = 0): number {
- let marker = src.indexOf(MENTION_LINK_MARKER, from);
-
- while (marker !== -1) {
- if (!isEscaped(src, marker)) return marker;
- marker = src.indexOf(MENTION_LINK_MARKER, marker + MENTION_LINK_MARKER.length);
- }
-
- return -1;
-}
-
-function findMentionStart(src: string): number {
- let marker = findUnescapedMentionMarker(src);
-
- while (marker !== -1) {
- for (let i = marker - 1; i >= 0; i--) {
- const char = src[i];
- if (char === "\n" || char === "\r") break;
- if (char === "[" && !isEscaped(src, i)) return i;
- }
-
- marker = findUnescapedMentionMarker(src, marker + MENTION_LINK_MARKER.length);
- }
-
- return -1;
-}
-
-/** A mention as text, the way its pill reads: issues and projects by name. */
-export function mentionText(attrs: Record<string, unknown>): string {
- const type = attrs.type ?? "member";
- const prefix = type === "issue" || type === "project" || type === "doc" ? "" : "@";
- return `${prefix}${String(attrs.label ?? attrs.id ?? "")}`;
-}
-
-export const BaseMentionExtension = Mention.extend({
+export const BaseMentionExtension = MentionSchema.extend({
addNodeView() {
return ReactNodeViewRenderer(MentionView);
},
- renderHTML({ node, HTMLAttributes }) {
- return [
- "span",
- mergeAttributes(
- { "data-type": "mention" },
- this.options.HTMLAttributes,
- HTMLAttributes,
- {
- "data-mention-type": node.attrs.type ?? "member",
- "data-mention-id": node.attrs.id,
- },
- ),
- mentionText(node.attrs),
- ];
- },
- addAttributes() {
- return {
- ...this.parent?.(),
- type: {
- default: "member",
- parseHTML: (el: HTMLElement) =>
- el.getAttribute("data-mention-type") ?? "member",
- renderHTML: () => ({}),
- },
- };
- },
- markdownTokenizer: {
- name: "mention",
- level: "inline" as const,
- start(src: string) {
- // Anchor on Multica's mention href first. Scanning forward from every
- // "[" backtracks badly on escaped stacktrace markers like \~\[...\].
- return findMentionStart(src);
- },
- tokenize(src: string) {
- // Label accepts escaped chars (\\[ \\]) or any non-] non-backslash
- // character. Excluding backslash from the char class keeps the two
- // alternatives disjoint — otherwise "\x" runs backtrack in 2^n ways
- // (ReDoS, GitHub #4881) — while still supporting bracket-containing
- // names like "David\[TF\]".
- const match = src.match(
- /^\[@?((?:\\.|[^\]\\])+)\]\(mention:\/\/(\w+)\/([^)]+)\)/,
- );
- if (!match) return undefined;
- // Reverse escapeMarkdownLabel: unescape \[ \] \\ \( \) that
- // renderMarkdown produced. Must mirror the escaped set exactly, or a
- // label containing "\" fails to round-trip through the linear tokenizer.
- const rawLabel = match[1]?.replace(/\\([[\]\\()])/g, "$1");
- return {
- type: "mention",
- raw: match[0],
- attributes: { label: rawLabel, type: match[2] ?? "member", id: match[3] },
- };
- },
- },
- parseMarkdown: (token: any, helpers: any) => {
- return helpers.createNode("mention", token.attributes);
- },
- renderMarkdown: (node: any) => {
- const { id, label, type = "member" } = node.attrs || {};
- const prefix = type === "issue" || type === "project" || type === "doc" ? "" : "@";
- // Escape [ ] \ ( ) in the label so the markdown link syntax is not broken
- // and the label survives the linear tokenizer (which now treats "\" as an
- // escape lead, not an ordinary char). Must stay in sync with the unescape
- // in tokenize() above. Shared with file-card/slash via escapeMarkdownLabel.
- const safeLabel = escapeMarkdownLabel(label ?? id);
- return `[${prefix}${safeLabel}](mention://${type}/${id})`;
- },
});
diff --git a/packages/views/editor/extensions/slash-command-extension.ts b/packages/views/editor/extensions/slash-command-extension.ts
index b232d1892a..6cb5865e88 100644
--- a/packages/views/editor/extensions/slash-command-extension.ts
+++ b/packages/views/editor/extensions/slash-command-extension.ts
@@ -1,72 +1,9 @@
-import Mention from "@tiptap/extension-mention";
-import { mergeAttributes } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react";
import { SlashCommandView } from "./slash-command-view";
-import { formatSlashCommandLabel } from "./slash-command-utils";
-import { escapeMarkdownLabel } from "../utils/escape-markdown-label";
-
-export const SlashCommandExtension = Mention.extend({
- name: "slashCommand",
+import { SlashCommandSchema } from "../schema/slash-command";
+export const SlashCommandExtension = SlashCommandSchema.extend({
addNodeView() {
return ReactNodeViewRenderer(SlashCommandView);
},
-
- renderHTML({ node, HTMLAttributes }) {
- return [
- "span",
- mergeAttributes(
- { "data-type": "slash-command" },
- this.options.HTMLAttributes,
- HTMLAttributes,
- ),
- `/${formatSlashCommandLabel(node.attrs.label)}`,
- ];
- },
-
- addAttributes() {
- return { ...this.parent?.() };
- },
-
- parseHTML() {
- return [{ tag: 'span[data-type="slash-command"]' }];
- },
-
- markdownTokenizer: {
- name: "slashCommand",
- level: "inline" as const,
- start(src: string) {
- // Backslash is excluded from the char class so "\x" runs can only be
- // consumed by \\. — overlapping alternatives backtrack in 2^n ways
- // (ReDoS, GitHub #4881).
- return src.search(/\[\/(?:\\.|[^\]\\])+\]\(slash:\/\/skill\//);
- },
- tokenize(src: string) {
- const match = src.match(
- /^\[\/((?:\\.|[^\]\\])+)\]\(slash:\/\/skill\/([^)]+)\)/,
- );
- if (!match) return undefined;
- // Reverse escapeMarkdownLabel: unescape \[ \] \\ \( \). Must mirror the
- // escaped set exactly, or a label containing "\" fails to round-trip
- // through the linear tokenizer.
- const rawLabel = match[1]?.replace(/\\([[\]\\()])/g, "$1");
- return {
- type: "slashCommand",
- raw: match[0],
- attributes: { label: rawLabel, id: match[2] },
- };
- },
- },
-
- parseMarkdown: (token: any, helpers: any) => {
- return helpers.createNode("slashCommand", token.attributes);
- },
-
- renderMarkdown: (node: any) => {
- const { id, label } = node.attrs || {};
- // Escape [ ] \ ( ) so the label survives the linear tokenizer; must stay in
- // sync with the unescape in tokenize() above.
- const safeLabel = escapeMarkdownLabel(formatSlashCommandLabel(label));
- return `[/${safeLabel}](slash://skill/${id})`;
- },
});
diff --git a/packages/views/editor/schema/codec.ts b/packages/views/editor/schema/codec.ts
new file mode 100644
index 0000000000..d88b10a1fd
--- /dev/null
+++ b/packages/views/editor/schema/codec.ts
@@ -0,0 +1,108 @@
+/**
+ * Markdown ⇄ collaborative document conversion, for the collaboration server.
+ *
+ * Markdown stays the canonical stored format; the Yjs document is the live
+ * editing state. Every conversion here goes through the same schema and
+ * Markdown codec the editor uses, so a document loaded on the server is the
+ * one a browser would have built from the same Markdown.
+ *
+ * HTML inside Markdown (including the file-card divs preprocessMarkdown
+ * produces) is only parsed when a DOM is available; the server installs one
+ * before using the codec.
+ */
+import { createDocument, getSchema, type JSONContent } from "@tiptap/core";
+import { MarkdownManager } from "@tiptap/markdown";
+import type { Node as PMNode, Schema } from "@tiptap/pm/model";
+import * as Y from "yjs";
+import {
+ prosemirrorJSONToYXmlFragment,
+ updateYFragment,
+ yXmlFragmentToProseMirrorRootNode,
+} from "@tiptap/y-tiptap";
+import { preprocessMarkdown } from "../utils/preprocess";
+import {
+ MARKDOWN_CHUNK_THRESHOLD,
+ parseMarkdownChunked,
+} from "../utils/parse-markdown-chunked";
+import {
+ COLLAB_FIELD,
+ createMarkdownSchemaExtensions,
+ createMarkedInstance,
+ MARKDOWN_OPTIONS,
+} from "./index";
+
+export { COLLAB_FIELD };
+export type { JSONContent };
+
+export interface DocumentCodec {
+ schema: Schema;
+ /** Stored Markdown → ProseMirror JSON, with the editor's preprocessing. */
+ parse(markdown: string): JSONContent;
+ /** ProseMirror JSON → Markdown, normalized the way the editor saves it. */
+ serialize(json: JSONContent): string;
+ /** JSON → schema-checked node; content the schema rejects is dropped. */
+ toNode(json: JSONContent): PMNode;
+ /** A fresh Y.Doc holding `markdown`. */
+ createYDoc(markdown: string): Y.Doc;
+ ydocToJSON(ydoc: Y.Doc): JSONContent;
+ ydocToMarkdown(ydoc: Y.Doc): string;
+ /** Rewrites the live document to `json` as a structural diff in one
+ * transaction: unchanged blocks keep their Yjs identity, so collaborators'
+ * carets and concurrent edits elsewhere are left alone. */
+ applyJSON(ydoc: Y.Doc, json: JSONContent, origin?: unknown): void;
+}
+
+export function createDocumentCodec(opts: { cdnDomain?: string } = {}): DocumentCodec {
+ const extensions = createMarkdownSchemaExtensions();
+ const schema = getSchema(extensions);
+ const manager = new MarkdownManager({ ...MARKDOWN_OPTIONS, marked: createMarkedInstance(), extensions });
+ const cdnDomain = opts.cdnDomain ?? "";
+
+ const parse = (markdown: string): JSONContent => {
+ const source = preprocessMarkdown(markdown, { cdnDomain });
+ if (!source.trim()) return { type: "doc", content: [{ type: "paragraph" }] };
+ return source.length > MARKDOWN_CHUNK_THRESHOLD
+ ? parseMarkdownChunked(manager, source)
+ : manager.parse(source);
+ };
+ const toNode = (json: JSONContent): PMNode =>
+ createDocument(json, schema, undefined, { errorOnInvalidContent: false });
+ const serialize = (json: JSONContent): string => manager.serialize(json).trim();
+ // The editor keeps an empty paragraph after a final list, table or code
+ // block, and every connected editor adds its own when it is missing: a
+ // server-side rewrite without one would come back with one per editor,
+ // saved as `&nbsp;` lines. A single one saves as nothing.
+ const withTrailingParagraph = (json: JSONContent): JSONContent =>
+ json.content?.at(-1)?.type === "paragraph"
+ ? json
+ : { ...json, content: [...(json.content ?? []), { type: "paragraph" }] };
+ const ydocToJSON = (ydoc: Y.Doc): JSONContent =>
+ yXmlFragmentToProseMirrorRootNode(ydoc.getXmlFragment(COLLAB_FIELD), schema).toJSON();
+
+ return {
+ schema,
+ parse,
+ serialize,
+ toNode,
+ createYDoc(markdown) {
+ const ydoc = new Y.Doc();
+ prosemirrorJSONToYXmlFragment(
+ schema,
+ toNode(withTrailingParagraph(parse(markdown))).toJSON(),
+ ydoc.getXmlFragment(COLLAB_FIELD),
+ );
+ return ydoc;
+ },
+ ydocToJSON,
+ ydocToMarkdown: (ydoc) => serialize(ydocToJSON(ydoc)),
+ applyJSON(ydoc, json, origin) {
+ const node = toNode(withTrailingParagraph(json));
+ ydoc.transact(() => {
+ updateYFragment(ydoc, ydoc.getXmlFragment(COLLAB_FIELD), node, {
+ mapping: new Map(),
+ isOMark: new Map(),
+ });
+ }, origin);
+ },
+ };
+}
diff --git a/packages/views/editor/schema/file-card.ts b/packages/views/editor/schema/file-card.ts
new file mode 100644
index 0000000000..ab00df161e
--- /dev/null
+++ b/packages/views/editor/schema/file-card.ts
@@ -0,0 +1,106 @@
+/**
+ * fileCard node schema and Markdown codec, without the React NodeView, so the
+ * collaboration server can parse and serialize documents in Node.
+ *
+ * Markdown serialization: `!file[filename](href)` — custom syntax that is
+ * unambiguous (standard `[name](url)` is indistinguishable from regular links).
+ */
+import { Node, mergeAttributes } from "@tiptap/core";
+import { FILE_CARD_URL_PATTERN } from "@multica/ui/markdown/file-cards";
+import { escapeMarkdownLabel } from "../utils/escape-markdown-label";
+
+// Backslash is excluded from the label char class so "\x" runs can only be
+// consumed by \\. — overlapping alternatives backtrack in 2^n ways (ReDoS,
+// GitHub #4881).
+const FILE_CARD_MARKDOWN_RE = new RegExp(
+ `^!file\\[((?:\\\\.|[^\\]\\\\])*)\\]\\((${FILE_CARD_URL_PATTERN.source})\\)`,
+);
+
+export const FileCardSchema = Node.create({
+ name: "fileCard",
+ group: "block",
+ atom: true,
+
+ addAttributes() {
+ return {
+ href: {
+ default: "",
+ rendered: false, // Don't put href on DOM — prevents link behavior
+ },
+ filename: {
+ default: "",
+ rendered: false,
+ },
+ fileSize: {
+ default: 0,
+ rendered: false,
+ },
+ uploading: {
+ default: false,
+ rendered: false,
+ },
+ uploadId: {
+ default: null,
+ rendered: false,
+ },
+ };
+ },
+
+ parseHTML() {
+ return [
+ {
+ tag: 'div[data-type="fileCard"]',
+ getAttrs: (el) => ({
+ href: (el as HTMLElement).getAttribute("data-href"),
+ filename: (el as HTMLElement).getAttribute("data-filename"),
+ }),
+ },
+ ];
+ },
+
+ renderHTML({ node, HTMLAttributes }) {
+ return [
+ "div",
+ mergeAttributes(HTMLAttributes, {
+ "data-type": "fileCard",
+ "data-href": node.attrs.href,
+ "data-filename": node.attrs.filename,
+ }),
+ ];
+ },
+
+ // Markdown: custom !file[name](url) syntax for unambiguous roundtrip.
+ // Standard [name](url) is indistinguishable from regular links — the old
+ // regex-based CDN hostname matching in preprocessFileCards was fragile.
+ markdownTokenizer: {
+ name: "fileCard",
+ level: "block" as const,
+ start(src: string) {
+ return src.search(/^!file\[/m);
+ },
+ tokenize(src: string) {
+ const match = src.match(FILE_CARD_MARKDOWN_RE);
+ if (!match) return undefined;
+ const filename = (match[1] ?? "").replace(/\\([[\]\\()])/g, "$1");
+ return {
+ type: "fileCard",
+ raw: match[0],
+ attributes: { filename, href: match[2] },
+ };
+ },
+ },
+ parseMarkdown: (token: any, helpers: any) => {
+ return helpers.createNode("fileCard", token.attributes);
+ },
+ renderMarkdown: (node: any) => {
+ const { href, filename, uploading } = node.attrs || {};
+ // An in-flight placeholder is not content. The document IS the draft body
+ // (getMarkdown → setDraft), so serialising it would persist `!file[x](
+ // )` — a line the tokenizer above cannot parse back, leaving dead literal
+ // text in the draft that outlives the upload and ships with the comment.
+ // Emitting nothing is the whole guarantee: the card becomes content the
+ // moment it has a real href, and never before.
+ if (uploading === true || !href) return "";
+ return `!file[${escapeMarkdownLabel(filename || "file")}](${href})`;
+ },
+});
diff --git a/packages/views/editor/schema/formats.test.ts b/packages/views/editor/schema/formats.test.ts
new file mode 100644
index 0000000000..083b905d7c
--- /dev/null
+++ b/packages/views/editor/schema/formats.test.ts
@@ -0,0 +1,200 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { Editor } from "@tiptap/core";
+import * as Y from "yjs";
+import { Awareness } from "y-protocols/awareness";
+import { createEditorExtensions } from "../extensions";
+import { preprocessMarkdown } from "../utils/preprocess";
+import {
+ MARKDOWN_CHUNK_THRESHOLD,
+ parseMarkdownChunked,
+ type MarkdownManagerLike,
+} from "../utils/parse-markdown-chunked";
+import { createDocumentCodec } from "./codec";
+
+const CDN = "cdn.multica.test";
+
+// Every format the docs editor can hold, written the way users and agents
+// write it, including the legacy forms still stored in older documents.
+const ALL_FORMATS = [
+ "# Heading 1",
+ "## Heading 2",
+ "### Heading 3",
+ "#### Heading 4",
+ "##### Heading 5",
+ "###### Heading 6",
+ "",
+ "Plain text with **bold**, *italic*, ***both***, ~~strike~~, `inline code`, ==highlight==, **==bold highlight==** and an escaped \\*star\\*.",
+ "",
+ "A [link](https://example.com \"title\"), a bare URL https://multica.ai/docs and a mailto <[email protected]>.",
+ "",
+ "Mentions: [@Ada](mention://member/11111111-1111-4111-8111-111111111111), [@Bot\\[TF\\]](mention://agent/22222222-2222-4222-8222-222222222222), [MUL-42](mention://issue/33333333-3333-4333-8333-333333333333), and a legacy [@ id=\"44444444-4444-4444-8444-444444444444\" label=\"Grace\"].",
+ "",
+ "A skill [/deploy](slash://skill/55555555-5555-4555-8555-555555555555) and a price of $100~$120 that is not math.",
+ "",
+ "中文段落,混排 English 与 emoji 🚀,以及全角标点:「引号」。",
+ "",
+ "Line one with a hard break ",
+ "line two.",
+ "",
+ "- bullet",
+ " - nested bullet",
+ " - deeper",
+ "- second **bold** bullet",
+ "",
+ "1. first",
+ "2. second",
+ " 1. nested ordered",
+ " 2. another",
+ "3. third",
+ "",
+ "- [ ] open task",
+ "- [x] done task",
+ " - [ ] nested task",
+ "- [ ] [MUL-42](mention://issue/33333333-3333-4333-8333-333333333333) task with a mention",
+ "",
+ "> A quote with **bold**",
+ ">",
+ "> - and a list",
+ "> > nested quote",
+ "",
+ "---",
+ "",
+ "```ts",
+ "const a: number = 1; // **not bold**",
+ "if (a == 1) console.log(\"==no highlight==\");",
+ "```",
+ "",
+ "```",
+ "plain fence with <tag> and $$ not math $$",
+ "```",
+ "",
+ "```mermaid",
+ "graph TD; A-->B;",
+ "```",
+ "",
+ "$$",
+ "\\int_0^1 x^2 \\, dx = \\frac{1}{3}",
+ "$$",
+ "",
+ "| Left | Center | Right |",
+ "| :--- | :---: | ---: |",
+ "| **bold** | `code` | [link](https://example.com) |",
+ "| [@Ada](mention://member/11111111-1111-4111-8111-111111111111) | ==hi== | 中文 |",
+ "",
+ "![A screenshot](https://cdn.multica.test/images/shot.png \"Shot title\")",
+ "",
+ "![attachment](/api/attachments/66666666-6666-4666-8666-666666666666/download)",
+ "",
+ "!file[report \\[v2\\].pdf](https://cdn.multica.test/files/report.pdf)",
+ "",
+ "[legacy.zip](https://cdn.multica.test/files/legacy.zip)",
+ "",
+ "Last paragraph.",
+].join("\n");
+
+const editors: Editor[] = [];
+afterEach(() => {
+ editors.splice(0).forEach((editor) => editor.destroy());
+ document.body.innerHTML = "";
+});
+
+function mountEditor(collaboration?: { document: Y.Doc }) {
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ const editor = new Editor({
+ element,
+ extensions: createEditorExtensions({
+ placeholder: "",
+ enableSlashCommands: false,
+ onUploadFileRef: { current: undefined },
+ ...(collaboration
+ ? {
+ collaboration: {
+ document: collaboration.document,
+ provider: { awareness: new Awareness(collaboration.document) },
+ user: { name: "Ada", color: "#3b82f6" },
+ },
+ }
+ : {}),
+ }),
+ });
+ editors.push(editor);
+ return editor;
+}
+
+/** How the doc page loads a document when it is edited alone (ContentEditor). */
+function openSolo(markdown: string) {
+ const editor = mountEditor();
+ const source = preprocessMarkdown(markdown, { cdnDomain: CDN });
+ if (source.length > MARKDOWN_CHUNK_THRESHOLD) {
+ const manager = (editor.storage as { markdown: { manager: MarkdownManagerLike } }).markdown.manager;
+ editor.commands.setContent(parseMarkdownChunked(manager, source), { emitUpdate: false });
+ } else {
+ editor.commands.setContent(source, { emitUpdate: false, contentType: "markdown" });
+ }
+ return editor;
+}
+
+/** How it loads in a live session: the collaboration server builds the Yjs
+ * document from the stored Markdown and the browser binds to a copy of it. */
+function openLive(markdown: string) {
+ const server = createDocumentCodec({ cdnDomain: CDN }).createYDoc(markdown);
+ const client = new Y.Doc();
+ Y.applyUpdate(client, Y.encodeStateAsUpdate(server));
+ return { editor: mountEditor({ document: client }), server };
+}
+
+describe.each([
+ ["every format", ALL_FORMATS],
+ ["every format in a document long enough to parse in chunks", Array(8).fill(ALL_FORMATS).join("\n\n")],
+])("a live document with %s", (_name, markdown) => {
+ it("is the document the solo editor builds", () => {
+ const solo = openSolo(markdown);
+ const { editor: live } = openLive(markdown);
+ expect(live.getJSON()).toEqual(solo.getJSON());
+ expect(live.getHTML()).toBe(solo.getHTML());
+ });
+
+ it("saves the Markdown the solo editor saves", () => {
+ const solo = openSolo(markdown);
+ const { editor: live, server } = openLive(markdown);
+ const codec = createDocumentCodec({ cdnDomain: CDN });
+ expect(codec.ydocToMarkdown(server)).toBe(solo.getMarkdown().trim());
+ expect(live.getMarkdown().trim()).toBe(solo.getMarkdown().trim());
+ });
+
+ it("is stable when the saved Markdown is loaded again", () => {
+ const codec = createDocumentCodec({ cdnDomain: CDN });
+ const saved = codec.ydocToMarkdown(codec.createYDoc(markdown));
+ expect(codec.ydocToMarkdown(codec.createYDoc(saved))).toBe(saved);
+ });
+});
+
+describe("formats made in the browser", () => {
+ it("reach the other editor and the saved Markdown unchanged", () => {
+ const codec = createDocumentCodec({ cdnDomain: CDN });
+ const server = codec.createYDoc("Start");
+ const ada = new Y.Doc();
+ const bob = new Y.Doc();
+ for (const doc of [ada, bob]) Y.applyUpdate(doc, Y.encodeStateAsUpdate(server));
+ // Relay every update the way the collaboration server does.
+ const peers = [server, ada, bob];
+ for (const doc of peers) {
+ doc.on("update", (update: Uint8Array, origin: unknown) => {
+ if (origin === "relay") return;
+ for (const peer of peers) if (peer !== doc) Y.applyUpdate(peer, update, "relay");
+ });
+ }
+
+ const adaEditor = mountEditor({ document: ada });
+ const bobEditor = mountEditor({ document: bob });
+ adaEditor.commands.setContent(preprocessMarkdown(ALL_FORMATS, { cdnDomain: CDN }), {
+ contentType: "markdown",
+ });
+
+ expect(bobEditor.getJSON()).toEqual(adaEditor.getJSON());
+ expect(bobEditor.getHTML()).toBe(adaEditor.getHTML());
+ expect(codec.ydocToMarkdown(server)).toBe(adaEditor.getMarkdown().trim());
+ expect(codec.ydocToMarkdown(server)).toBe(openSolo(ALL_FORMATS).getMarkdown().trim());
+ });
+});
diff --git a/packages/views/editor/schema/image.ts b/packages/views/editor/schema/image.ts
new file mode 100644
index 0000000000..617c400e1f
--- /dev/null
+++ b/packages/views/editor/schema/image.ts
@@ -0,0 +1,69 @@
+/**
+ * image node schema and Markdown codec, without the React NodeView, so the
+ * collaboration server can parse and serialize documents in Node.
+ */
+import Image from "@tiptap/extension-image";
+import { escapeMarkdownLabel } from "../utils/escape-markdown-label";
+
+export const ImageSchema = Image.extend({
+ addAttributes() {
+ return {
+ ...this.parent?.(),
+ uploading: {
+ default: false,
+ renderHTML: (attrs: Record<string, unknown>) =>
+ attrs.uploading ? { "data-uploading": "" } : {},
+ parseHTML: (el: HTMLElement) => el.hasAttribute("data-uploading"),
+ },
+ // The upload this placeholder belongs to — the same value the draft
+ // store knows as `clientUploadId`. Lets a settle arriving at a mount
+ // that did not start the upload find the node to replace. Render-only,
+ // and cleared once the node holds a real URL.
+ uploadId: {
+ default: null,
+ rendered: false,
+ },
+ // Intrinsic pixel dimensions, captured on upload (file-upload.ts). The
+ // browser uses width/height on <img> to compute aspect-ratio and reserve
+ // the box before the image decodes, so inserting an image causes no
+ // layout shift (and the post-insert scrollIntoView stays correct). Not
+ // serialized to markdown — `renderMarkdown` only emits src/alt/title — so
+ // round-trips stay clean.
+ width: {
+ default: null,
+ renderHTML: (attrs: Record<string, unknown>) =>
+ attrs.width ? { width: attrs.width as number } : {},
+ parseHTML: (el: HTMLElement) => {
+ const w = parseInt(el.getAttribute("width") || "", 10);
+ return Number.isFinite(w) ? w : null;
+ },
+ },
+ height: {
+ default: null,
+ renderHTML: (attrs: Record<string, unknown>) =>
+ attrs.height ? { height: attrs.height as number } : {},
+ parseHTML: (el: HTMLElement) => {
+ const h = parseInt(el.getAttribute("height") || "", 10);
+ return Number.isFinite(h) ? h : null;
+ },
+ },
+ };
+ },
+ renderMarkdown: (node: any) => {
+ const src = node.attrs?.src || "";
+ // Same rule as fileCard: an in-flight placeholder is not content. Its src
+ // is a process-local `blob:` URL that expires on reload, so emitting it
+ // would put a dead link in the persisted draft. This replaces the
+ // after-the-fact regex scrub ContentEditor used to run on every serialise.
+ if (node.attrs?.uploading === true || !src) return "";
+ const alt = escapeMarkdownLabel(node.attrs?.alt || "");
+ const title = node.attrs?.title;
+ if (title) {
+ return `![${alt}](${src} "${title}")`;
+ }
+ return `![${alt}](${src})`;
+ },
+}).configure({
+ inline: false,
+ allowBase64: false,
+});
diff --git a/packages/views/editor/schema/index.ts b/packages/views/editor/schema/index.ts
new file mode 100644
index 0000000000..5171d93cd9
--- /dev/null
+++ b/packages/views/editor/schema/index.ts
@@ -0,0 +1,107 @@
+/**
+ * The document schema and Markdown codec shared by the editor and the
+ * collaboration server.
+ *
+ * Nothing here may import React, CSS or browser-only modules: the
+ * collaboration server loads this file in Node to turn stored Markdown into
+ * the collaborative document and back. The editor builds its extension array
+ * from the same pieces and adds NodeViews, pickers and input behaviour on top
+ * (../extensions/index.ts); schema.test.ts fails when the two drift apart.
+ */
+import StarterKit, { type StarterKitOptions } from "@tiptap/starter-kit";
+import Link from "@tiptap/extension-link";
+import TableRow from "@tiptap/extension-table-row";
+import TableHeader from "@tiptap/extension-table-header";
+import TableCell from "@tiptap/extension-table-cell";
+import { Table } from "@tiptap/extension-table";
+import { TaskList } from "@tiptap/extension-list";
+import { Markdown } from "@tiptap/markdown";
+import { Marked, type marked } from "marked";
+import type { AnyExtension } from "@tiptap/core";
+import { CodeBlockExtension } from "../extensions/code-block";
+import { PatchedListItem, PatchedOrderedList, PatchedTaskItem } from "../extensions/list-item";
+import { HighlightExtension } from "../extensions/highlight";
+import { FileCardSchema } from "./file-card";
+import { MentionSchema } from "./mention";
+import { BlockMathSchema, InlineMathSchema } from "./math";
+import { ImageSchema } from "./image";
+import { SlashCommandSchema } from "./slash-command";
+
+export { FileCardSchema } from "./file-card";
+export { MentionSchema, mentionText } from "./mention";
+export { BlockMathSchema, InlineMathSchema } from "./math";
+export { ImageSchema } from "./image";
+export { SlashCommandSchema } from "./slash-command";
+
+export const STARTER_KIT_OPTIONS: Partial<StarterKitOptions> = {
+ // Every level Markdown can express. The Markdown parser keeps the source
+ // depth of `#`…`######`, but Heading.renderHTML falls back to `levels[0]`
+ // for any level it was not configured with — so `levels: [1, 2, 3]` made
+ // the editor draw every H4–H6 as an H1 (MUL-6060). The same list drives
+ // parseHTML, so it also decides whether a pasted `<h4>` survives as a
+ // heading. This is about rendering headings the content already has; the
+ // bubble menu still offers only H1–H3 as authoring choices.
+ heading: { levels: [1, 2, 3, 4, 5, 6] },
+ link: false,
+ codeBlock: false,
+ // Underline has no Markdown representation. Tiptap's extension serializes
+ // the mark as `++text++`, which is not CommonMark or GFM, so ReadonlyContent
+ // (react-markdown + remark-gfm) renders the delimiters literally. Disabling
+ // the extension drops the mark at parse time instead: pasted `<u>` /
+ // `text-decoration: underline` keep their text, and Cmd+U becomes a no-op
+ // rather than a way to produce content the display layer cannot render.
+ underline: false,
+ // Disable StarterKit's stock ListItem — its Enter keybind binds only
+ // `splitListItem`, which leaves the user stuck inside an empty top-level
+ // list item (see list-item.ts). PatchedListItem restores the standard
+ // split → lift fallback chain.
+ listItem: false,
+ // PatchedOrderedList drops indentation the stock parser leaks into items.
+ orderedList: false,
+};
+
+/** The Y.XmlFragment the Collaboration extension binds. */
+export const COLLAB_FIELD = "default";
+
+// 3-space indent so nested ordered lists survive CommonMark in ReadonlyContent.
+export const MARKDOWN_OPTIONS = { indentation: { style: "space" as const, size: 3 } };
+
+/**
+ * A private marked instance for one editor or codec. Without one,
+ * @tiptap/markdown registers every editor's tokenizers on the global `marked`
+ * with `use()` and never removes them: the list grows by one editor's worth
+ * per mount, every inline parse runs all of them, and each tokenizer keeps its
+ * editor, the React refs its extensions close over and the unmounted DOM alive
+ * (MUL-9634: ~1,000 DOM nodes retained per issue opened).
+ */
+export function createMarkedInstance(): typeof marked {
+ // A Marked instance has every member MarkdownManager uses (use, Lexer,
+ // defaults, lexer, setOptions); the option is typed as the global's.
+ return new Marked() as unknown as typeof marked;
+}
+
+/** Schema-only extensions: every node and mark the editor can hold, with
+ * their Markdown codecs, and no views, plugins that need a DOM, or pickers. */
+export function createMarkdownSchemaExtensions(): AnyExtension[] {
+ return [
+ StarterKit.configure({ ...STARTER_KIT_OPTIONS, undoRedo: false }),
+ PatchedListItem,
+ PatchedOrderedList,
+ TaskList,
+ PatchedTaskItem,
+ CodeBlockExtension,
+ Link.extend({ inclusive: false }).configure({ openOnClick: false, autolink: false }),
+ ImageSchema,
+ Table.configure({ resizable: false, renderWrapper: true }),
+ TableRow,
+ TableHeader,
+ TableCell,
+ BlockMathSchema,
+ InlineMathSchema,
+ HighlightExtension,
+ Markdown.configure({ ...MARKDOWN_OPTIONS, marked: createMarkedInstance() }),
+ FileCardSchema,
+ MentionSchema,
+ SlashCommandSchema,
+ ];
+}
diff --git a/packages/views/editor/schema/math.ts b/packages/views/editor/schema/math.ts
new file mode 100644
index 0000000000..88231f6545
--- /dev/null
+++ b/packages/views/editor/schema/math.ts
@@ -0,0 +1,120 @@
+/**
+ * Math node schemas and Markdown codecs, without the KaTeX NodeViews, so the
+ * collaboration server can parse and serialize documents in Node.
+ */
+import { Node, mergeAttributes } from "@tiptap/core";
+
+export const InlineMathSchema = Node.create({
+ name: "inlineMath",
+ group: "inline",
+ inline: true,
+ atom: true,
+ selectable: true,
+
+ addAttributes() {
+ return {
+ expression: {
+ default: "",
+ rendered: false,
+ },
+ };
+ },
+
+ parseHTML() {
+ return [
+ {
+ tag: 'span[data-type="inline-math"]',
+ getAttrs: (el) => ({
+ expression: (el as HTMLElement).getAttribute("data-expression") ?? "",
+ }),
+ },
+ ];
+ },
+
+ renderHTML({ node, HTMLAttributes }) {
+ return [
+ "span",
+ mergeAttributes(HTMLAttributes, {
+ "data-type": "inline-math",
+ "data-expression": node.attrs.expression,
+ }),
+ node.attrs.expression,
+ ];
+ },
+
+ // Single-dollar inline math is intentionally not parsed from Markdown and has
+ // no typing input rule. Dollar amounts like `$100~$120` must stay literal;
+ // users should write explicit `$$...$$` blocks for math.
+ renderMarkdown: (node: any) => {
+ const expression = String(node.attrs?.expression ?? "");
+ return `$${expression}$`;
+ },
+});
+
+export const BlockMathSchema = Node.create({
+ name: "blockMath",
+ group: "block",
+ atom: true,
+ code: true,
+ defining: true,
+ isolating: true,
+ selectable: true,
+
+ addAttributes() {
+ return {
+ expression: {
+ default: "",
+ rendered: false,
+ },
+ };
+ },
+
+ parseHTML() {
+ return [
+ {
+ tag: 'div[data-type="block-math"]',
+ getAttrs: (el) => ({
+ expression: (el as HTMLElement).getAttribute("data-expression") ?? "",
+ }),
+ },
+ ];
+ },
+
+ renderHTML({ node, HTMLAttributes }) {
+ return [
+ "div",
+ mergeAttributes(HTMLAttributes, {
+ "data-type": "block-math",
+ "data-expression": node.attrs.expression,
+ }),
+ node.attrs.expression,
+ ];
+ },
+
+ markdownTokenizer: {
+ name: "blockMath",
+ level: "block" as const,
+ start(src: string) {
+ return src.search(/^\$\$/m);
+ },
+ tokenize(src: string) {
+ if (!src.startsWith("$$")) return undefined;
+ const match = src.match(/^\$\$[ \t]*\n?([\s\S]+?)\n?\$\$(?:\n|$)/);
+ if (!match) return undefined;
+ return {
+ type: "blockMath",
+ raw: match[0],
+ attributes: { expression: match[1] ?? "" },
+ };
+ },
+ },
+
+ parseMarkdown: (token: any, helpers: any) => {
+ return helpers.createNode("blockMath", token.attributes);
+ },
+
+ renderMarkdown: (node: any) => {
+ const expression = String(node.attrs?.expression ?? "");
+ return `$$\n${expression}\n$$`;
+ },
+});
diff --git a/packages/views/editor/schema/mention.ts b/packages/views/editor/schema/mention.ts
new file mode 100644
index 0000000000..90c5ee6304
--- /dev/null
+++ b/packages/views/editor/schema/mention.ts
@@ -0,0 +1,122 @@
+/**
+ * mention node schema and Markdown codec, without the React NodeView, so the
+ * collaboration server can parse and serialize documents in Node.
+ */
+import Mention from "@tiptap/extension-mention";
+import { mergeAttributes } from "@tiptap/core";
+import { escapeMarkdownLabel } from "../utils/escape-markdown-label";
+
+const MENTION_LINK_MARKER = "](mention://";
+
+function isEscaped(text: string, index: number): boolean {
+ let slashCount = 0;
+ for (let i = index - 1; i >= 0 && text[i] === "\\"; i--) {
+ slashCount++;
+ }
+ return slashCount % 2 === 1;
+}
+
+function findUnescapedMentionMarker(src: string, from = 0): number {
+ let marker = src.indexOf(MENTION_LINK_MARKER, from);
+
+ while (marker !== -1) {
+ if (!isEscaped(src, marker)) return marker;
+ marker = src.indexOf(MENTION_LINK_MARKER, marker + MENTION_LINK_MARKER.length);
+ }
+
+ return -1;
+}
+
+function findMentionStart(src: string): number {
+ let marker = findUnescapedMentionMarker(src);
+
+ while (marker !== -1) {
+ for (let i = marker - 1; i >= 0; i--) {
+ const char = src[i];
+ if (char === "\n" || char === "\r") break;
+ if (char === "[" && !isEscaped(src, i)) return i;
+ }
+
+ marker = findUnescapedMentionMarker(src, marker + MENTION_LINK_MARKER.length);
+ }
+
+ return -1;
+}
+
+/** A mention as text, the way its pill reads: issues and projects by name. */
+export function mentionText(attrs: Record<string, unknown>): string {
+ const type = attrs.type ?? "member";
+ const prefix = type === "issue" || type === "project" || type === "doc" ? "" : "@";
+ return `${prefix}${String(attrs.label ?? attrs.id ?? "")}`;
+}
+
+export const MentionSchema = Mention.extend({
+ renderHTML({ node, HTMLAttributes }) {
+ return [
+ "span",
+ mergeAttributes(
+ { "data-type": "mention" },
+ this.options.HTMLAttributes,
+ HTMLAttributes,
+ {
+ "data-mention-type": node.attrs.type ?? "member",
+ "data-mention-id": node.attrs.id,
+ },
+ ),
+ mentionText(node.attrs),
+ ];
+ },
+ addAttributes() {
+ return {
+ ...this.parent?.(),
+ type: {
+ default: "member",
+ parseHTML: (el: HTMLElement) =>
+ el.getAttribute("data-mention-type") ?? "member",
+ renderHTML: () => ({}),
+ },
+ };
+ },
+ markdownTokenizer: {
+ name: "mention",
+ level: "inline" as const,
+ start(src: string) {
+ // Anchor on Multica's mention href first. Scanning forward from every
+ // "[" backtracks badly on escaped stacktrace markers like \~\[...\].
+ return findMentionStart(src);
+ },
+ tokenize(src: string) {
+ // Label accepts escaped chars (\\[ \\]) or any non-] non-backslash
+ // character. Excluding backslash from the char class keeps the two
+ // alternatives disjoint — otherwise "\x" runs backtrack in 2^n ways
+ // (ReDoS, GitHub #4881) — while still supporting bracket-containing
+ // names like "David\[TF\]".
+ const match = src.match(
+ /^\[@?((?:\\.|[^\]\\])+)\]\(mention:\/\/(\w+)\/([^)]+)\)/,
+ );
+ if (!match) return undefined;
+ // Reverse escapeMarkdownLabel: unescape \[ \] \\ \( \) that
+ // renderMarkdown produced. Must mirror the escaped set exactly, or a
+ // label containing "\" fails to round-trip through the linear tokenizer.
+ const rawLabel = match[1]?.replace(/\\([[\]\\()])/g, "$1");
+ return {
+ type: "mention",
+ raw: match[0],
+ attributes: { label: rawLabel, type: match[2] ?? "member", id: match[3] },
+ };
+ },
+ },
+ parseMarkdown: (token: any, helpers: any) => {
+ return helpers.createNode("mention", token.attributes);
+ },
+ renderMarkdown: (node: any) => {
+ const { id, label, type = "member" } = node.attrs || {};
+ const prefix = type === "issue" || type === "project" || type === "doc" ? "" : "@";
+ // Escape [ ] \ ( ) in the label so the markdown link syntax is not broken
+ // and the label survives the linear tokenizer (which now treats "\" as an
+ // escape lead, not an ordinary char). Must stay in sync with the unescape
+ // in tokenize() above. Shared with file-card/slash via escapeMarkdownLabel.
+ const safeLabel = escapeMarkdownLabel(label ?? id);
+ return `[${prefix}${safeLabel}](mention://${type}/${id})`;
+ },
+});
diff --git a/packages/views/editor/schema/schema.test.ts b/packages/views/editor/schema/schema.test.ts
new file mode 100644
index 0000000000..77726b34f7
--- /dev/null
+++ b/packages/views/editor/schema/schema.test.ts
@@ -0,0 +1,146 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { Editor, getSchema } from "@tiptap/core";
+import type { Schema } from "@tiptap/pm/model";
+import * as Y from "yjs";
+import { createEditorExtensions } from "../extensions";
+import { createMarkdownSchemaExtensions } from ".";
+import { COLLAB_FIELD, createDocumentCodec } from "./codec";
+
+const editorExtensions = () =>
+ createEditorExtensions({
+ placeholder: "",
+ enableSlashCommands: false,
+ onUploadFileRef: { current: undefined },
+ });
+
+function describeSchema(schema: Schema) {
+ const nodes = Object.fromEntries(
+ Object.entries(schema.nodes).map(([name, type]) => [
+ name,
+ { attrs: Object.keys(type.spec.attrs ?? {}).sort(), group: type.spec.group ?? null, content: type.spec.content ?? null },
+ ]),
+ );
+ const marks = Object.fromEntries(
+ Object.entries(schema.marks).map(([name, type]) => [
+ name,
+ { attrs: Object.keys(type.spec.attrs ?? {}).sort(), inclusive: type.spec.inclusive ?? null },
+ ]),
+ );
+ return { nodes, marks };
+}
+
+let editor: Editor | null = null;
+afterEach(() => {
+ editor?.destroy();
+ editor = null;
+ document.body.innerHTML = "";
+});
+
+describe("schema-only extensions", () => {
+ // The collaboration server builds documents from this list. A node or mark
+ // the editor knows but the server does not would be dropped from every
+ // collaborative document the server touches.
+ it("describe the same schema as the editor", () => {
+ expect(describeSchema(getSchema(createMarkdownSchemaExtensions()))).toEqual(
+ describeSchema(getSchema(editorExtensions())),
+ );
+ });
+
+ it("serialize Markdown the way the editor does", () => {
+ const markdown = [
+ "# Title",
+ "",
+ "Some **bold** and ==highlight== with [@Ada](mention://member/u1) and [MUL-1](mention://issue/i1).",
+ "",
+ "- [ ] task",
+ "- [x] done",
+ "",
+ "1. one",
+ " 1. nested",
+ "",
+ "```ts title=\"x\"",
+ "const a = 1;",
+ "```",
+ "",
+ "$$",
+ "e=mc^2",
+ "$$",
+ "",
+ "| a | b |",
+ "| --- | --- |",
+ "| 1 | 2 |",
+ "",
+ "![alt](https://example.com/a.png)",
+ "",
+ "!file[report.pdf](https://example.com/report.pdf)",
+ ].join("\n");
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ editor = new Editor({ element, extensions: editorExtensions() });
+ const codec = createDocumentCodec();
+ editor.commands.setContent(codec.parse(markdown));
+ expect(codec.serialize(codec.parse(markdown))).toBe(editor.getMarkdown().trim());
+ });
+});
+
+describe("document codec", () => {
+ const codec = createDocumentCodec();
+
+ it("round-trips Markdown through a Y.Doc", () => {
+ const markdown = "# Plan\n\nFirst paragraph.\n\n- a\n- b";
+ expect(codec.ydocToMarkdown(codec.createYDoc(markdown))).toBe(markdown);
+ });
+
+ it("keeps the editor's trailing paragraph after a final list, through rewrites", () => {
+ const ydoc = codec.createYDoc("Intro\n\n- a");
+ const last = () => ydoc.getXmlFragment(COLLAB_FIELD).toArray().at(-1) as Y.XmlElement;
+ expect(last().nodeName).toBe("paragraph");
+ expect(codec.ydocToMarkdown(ydoc)).toBe("Intro\n\n- a");
+ codec.applyJSON(ydoc, codec.parse("Intro\n\n- a\n- b"));
+ expect(last().nodeName).toBe("paragraph");
+ expect(ydoc.getXmlFragment(COLLAB_FIELD).length).toBe(3);
+ expect(codec.ydocToMarkdown(ydoc)).toBe("Intro\n\n- a\n- b");
+ });
+
+ it.each([
+ ["ordered", "8. **Keep**:\n - a\n - b\n\n **Drop**:\n - c\n\n Closing note."],
+ ["bullet", "- a\n- b:\n - x\n - y\n\n [tag]"],
+ ])("keeps a %s item's paragraph after a nested list stable across saves", (_kind, markdown) => {
+ const saved = codec.serialize(codec.parse(markdown));
+ expect(codec.serialize(codec.parse(saved))).toBe(saved);
+ expect(saved).not.toMatch(/^ {4,}\S/m);
+ expect(JSON.stringify(codec.parse(markdown))).not.toMatch(/"text":" /);
+ });
+
+ it("keeps an empty document editable", () => {
+ const ydoc = codec.createYDoc("");
+ expect(ydoc.getXmlFragment(COLLAB_FIELD).length).toBe(1);
+ expect(codec.ydocToMarkdown(ydoc)).toBe("");
+ });
+
+ it("applies new Markdown as a diff that keeps untouched blocks", () => {
+ const ydoc = codec.createYDoc("Alpha\n\nBeta\n\nGamma");
+ const fragment = ydoc.getXmlFragment(COLLAB_FIELD);
+ const [alpha, , gamma] = fragment.toArray();
+ codec.applyJSON(ydoc, codec.parse("Alpha\n\nBeta edited\n\nGamma"), "agent");
+ expect(codec.ydocToMarkdown(ydoc)).toBe("Alpha\n\nBeta edited\n\nGamma");
+ expect(fragment.get(0)).toBe(alpha);
+ expect(fragment.get(2)).toBe(gamma);
+ });
+
+ it("merges a server-side rewrite with a concurrent client edit", () => {
+ const server = codec.createYDoc("Alpha\n\nBeta\n\nGamma");
+ const client = new Y.Doc();
+ Y.applyUpdate(client, Y.encodeStateAsUpdate(server));
+
+ // The client types into Gamma while the server rewrites Alpha.
+ const gammaText = client.getXmlFragment(COLLAB_FIELD).get(2) as Y.XmlElement;
+ (gammaText.get(0) as Y.XmlText).insert(5, " ray");
+ codec.applyJSON(server, codec.parse("Alpha changed\n\nBeta\n\nGamma"), "agent");
+
+ Y.applyUpdate(server, Y.encodeStateAsUpdate(client));
+ Y.applyUpdate(client, Y.encodeStateAsUpdate(server));
+ expect(codec.ydocToMarkdown(server)).toBe("Alpha changed\n\nBeta\n\nGamma ray");
+ expect(codec.ydocToMarkdown(client)).toBe(codec.ydocToMarkdown(server));
+ });
+});
diff --git a/packages/views/editor/schema/slash-command.ts b/packages/views/editor/schema/slash-command.ts
new file mode 100644
index 0000000000..6fff1437ea
--- /dev/null
+++ b/packages/views/editor/schema/slash-command.ts
@@ -0,0 +1,70 @@
+/**
+ * slashCommand node schema and Markdown codec, without the React NodeView, so
+ * the collaboration server can parse and serialize documents in Node.
+ */
+import Mention from "@tiptap/extension-mention";
+import { mergeAttributes } from "@tiptap/core";
+import { formatSlashCommandLabel } from "../extensions/slash-command-utils";
+import { escapeMarkdownLabel } from "../utils/escape-markdown-label";
+
+export const SlashCommandSchema = Mention.extend({
+ name: "slashCommand",
+
+ renderHTML({ node, HTMLAttributes }) {
+ return [
+ "span",
+ mergeAttributes(
+ { "data-type": "slash-command" },
+ this.options.HTMLAttributes,
+ HTMLAttributes,
+ ),
+ `/${formatSlashCommandLabel(node.attrs.label)}`,
+ ];
+ },
+
+ addAttributes() {
+ return { ...this.parent?.() };
+ },
+
+ parseHTML() {
+ return [{ tag: 'span[data-type="slash-command"]' }];
+ },
+
+ markdownTokenizer: {
+ name: "slashCommand",
+ level: "inline" as const,
+ start(src: string) {
+ // Backslash is excluded from the char class so "\x" runs can only be
+ // consumed by \\. — overlapping alternatives backtrack in 2^n ways
+ // (ReDoS, GitHub #4881).
+ return src.search(/\[\/(?:\\.|[^\]\\])+\]\(slash:\/\/skill\//);
+ },
+ tokenize(src: string) {
+ const match = src.match(
+ /^\[\/((?:\\.|[^\]\\])+)\]\(slash:\/\/skill\/([^)]+)\)/,
+ );
+ if (!match) return undefined;
+ // Reverse escapeMarkdownLabel: unescape \[ \] \\ \( \). Must mirror the
+ // escaped set exactly, or a label containing "\" fails to round-trip
+ // through the linear tokenizer.
+ const rawLabel = match[1]?.replace(/\\([[\]\\()])/g, "$1");
+ return {
+ type: "slashCommand",
+ raw: match[0],
+ attributes: { label: rawLabel, id: match[2] },
+ };
+ },
+ },
+
+ parseMarkdown: (token: any, helpers: any) => {
+ return helpers.createNode("slashCommand", token.attributes);
+ },
+
+ renderMarkdown: (node: any) => {
+ const { id, label } = node.attrs || {};
+ // Escape [ ] \ ( ) so the label survives the linear tokenizer; must stay in
+ // sync with the unescape in tokenize() above.
+ const safeLabel = escapeMarkdownLabel(formatSlashCommandLabel(label));
+ return `[/${safeLabel}](slash://skill/${id})`;
+ },
+});
diff --git a/packages/views/editor/styles/shell.css b/packages/views/editor/styles/shell.css
index 3ed074e8da..23de28897f 100644
--- a/packages/views/editor/styles/shell.css
+++ b/packages/views/editor/styles/shell.css
@@ -94,3 +94,29 @@
max-width: min(360px, calc(100vw - 2rem));
white-space: nowrap;
}
+
+/* Collaborators' carets (CollaborationCaret). The colour comes inline from
+ each collaborator's awareness state. */
+.rich-text-editor .collaboration-carets__caret {
+ position: relative;
+ margin-left: -1px;
+ margin-right: -1px;
+ border-left: 1px solid;
+ border-right: 1px solid;
+ word-break: normal;
+ pointer-events: none;
+}
+
+.rich-text-editor .collaboration-carets__label {
+ position: absolute;
+ top: -1.4em;
+ left: -1px;
+ border-radius: 3px 3px 3px 0;
+ padding: 0.1rem 0.3rem;
+ color: white;
+ font-size: 0.6875rem;
+ font-weight: 600;
+ line-height: normal;
+ white-space: nowrap;
+ user-select: none;
+}
diff --git a/packages/views/editor/utils/preprocess.ts b/packages/views/editor/utils/preprocess.ts
index 66738a1068..b45293f5c7 100644
--- a/packages/views/editor/utils/preprocess.ts
+++ b/packages/views/editor/utils/preprocess.ts
@@ -1,10 +1,10 @@
-import {
- preprocessLinks,
- preprocessMentionShortcodes,
- preprocessFileCards,
- preprocessIssueIdentifiers,
-} from "@multica/ui/markdown";
-import { stripChannelMediaMarkers } from "@multica/core/types";
+// Submodule imports, not the `@multica/ui/markdown` barrel: the collaboration
+// server runs this in Node, and the barrel pulls in React renderers and CSS.
+import { preprocessLinks } from "@multica/ui/markdown/linkify";
+import { preprocessMentionShortcodes } from "@multica/ui/markdown/mentions";
+import { preprocessFileCards } from "@multica/ui/markdown/file-cards";
+import { preprocessIssueIdentifiers } from "@multica/ui/markdown/issue-identifiers";
+import { stripChannelMediaMarkers } from "@multica/core/types/attachment-url";
/**
* Preprocess a markdown string before loading into Tiptap via contentType: 'markdown'.
diff --git a/packages/views/issues/components/comment-annotation-selection.ts b/packages/views/issues/components/comment-annotation-selection.ts
index d8679a5e9f..365d9ccd2a 100644
--- a/packages/views/issues/components/comment-annotation-selection.ts
+++ b/packages/views/issues/components/comment-annotation-selection.ts
@@ -8,16 +8,20 @@ const BLOCKS = new Set(["P", "DIV", "LI", "PRE", "BLOCKQUOTE", "H1", "H2", "H3",
*/
export function indexCommentText(root: HTMLElement, editable = false) {
let text = "";
+ // Reading the end of `text` would flatten it on every block, which is
+ // quadratic on a long doc.
+ let last = "";
const nodes: { node: Text; start: number; end: number }[] = [];
- const newline = () => { if (text && !text.endsWith("\n")) text += "\n"; };
+ const newline = () => { if (text && last !== "\n") { text += "\n"; last = "\n"; } };
function visit(node: Node) {
if (node.nodeType === Node.TEXT_NODE) {
const value = node.textContent ?? "";
nodes.push({ node: node as Text, start: text.length, end: text.length + value.length });
text += value;
+ if (value) last = value[value.length - 1]!;
} else if (node instanceof HTMLElement) {
if (node.matches(EXCLUDED) || (!editable && node.matches('[contenteditable="true"]'))) return;
- if (node.tagName === "BR") { text += "\n"; return; }
+ if (node.tagName === "BR") { text += "\n"; last = "\n"; return; }
const block = BLOCKS.has(node.tagName);
if (block) newline();
node.childNodes.forEach(visit);
diff --git a/packages/views/locales/en/docs.json b/packages/views/locales/en/docs.json
index 5bc2f02653..9290bd0bba 100644
--- a/packages/views/locales/en/docs.json
+++ b/packages/views/locales/en/docs.json
@@ -48,7 +48,12 @@
"conflict": "Updated by {{name}}. Your draft is kept. Reload to continue.",
"reload": "Reload latest",
"draft": "Your saved draft",
- "unsaved_changes": "Unsaved changes"
+ "unsaved_changes": "Unsaved changes",
+ "live": "Live",
+ "reconnecting": "Reconnecting...",
+ "connecting": "Connecting...",
+ "title_save_failed": "Title not saved",
+ "editing_now": "Editing now"
},
"history": {
"title": "History",
diff --git a/packages/views/locales/es/docs.json b/packages/views/locales/es/docs.json
index 04b3c0b562..60b03a820b 100644
--- a/packages/views/locales/es/docs.json
+++ b/packages/views/locales/es/docs.json
@@ -48,7 +48,12 @@
"conflict": "{{name}} actualizó el documento. Tu borrador se conserva. Recarga para continuar.",
"reload": "Cargar última versión",
"draft": "Tu borrador guardado",
- "unsaved_changes": "Cambios sin guardar"
+ "unsaved_changes": "Cambios sin guardar",
+ "live": "En vivo",
+ "reconnecting": "Reconectando...",
+ "connecting": "Conectando...",
+ "title_save_failed": "No se guardó el título",
+ "editing_now": "Editando ahora"
},
"history": {
"title": "Historial",
diff --git a/packages/views/locales/fr/docs.json b/packages/views/locales/fr/docs.json
index 677af7d4ed..fbe14370b3 100644
--- a/packages/views/locales/fr/docs.json
+++ b/packages/views/locales/fr/docs.json
@@ -48,7 +48,12 @@
"conflict": "{{name}} a modifié le document. Votre brouillon est conservé. Rechargez pour continuer.",
"reload": "Recharger la dernière version",
"draft": "Votre brouillon conservé",
- "unsaved_changes": "Modifications non enregistrées"
+ "unsaved_changes": "Modifications non enregistrées",
+ "live": "En direct",
+ "reconnecting": "Reconnexion...",
+ "connecting": "Connexion...",
+ "title_save_failed": "Titre non enregistré",
+ "editing_now": "En train de modifier"
},
"history": {
"title": "Historique",
diff --git a/packages/views/locales/ja/docs.json b/packages/views/locales/ja/docs.json
index 0af9def227..e8c62d67a1 100644
--- a/packages/views/locales/ja/docs.json
+++ b/packages/views/locales/ja/docs.json
@@ -48,7 +48,12 @@
"conflict": "{{name}} が更新しました。下書きを保持しています。再読み込みして続けてください。",
"reload": "最新版を読み込む",
"draft": "保存した下書き",
- "unsaved_changes": "保存していない変更"
+ "unsaved_changes": "保存していない変更",
+ "live": "ライブ",
+ "reconnecting": "再接続中...",
+ "connecting": "接続中...",
+ "title_save_failed": "タイトルを保存できませんでした",
+ "editing_now": "編集中"
},
"history": {
"title": "履歴",
diff --git a/packages/views/locales/ko/docs.json b/packages/views/locales/ko/docs.json
index 5b701d6fa5..8d3597f4f5 100644
--- a/packages/views/locales/ko/docs.json
+++ b/packages/views/locales/ko/docs.json
@@ -48,7 +48,12 @@
"conflict": "{{name}}님이 수정했습니다. 초안이 보존됩니다. 다시 불러와 계속하세요.",
"reload": "최신 버전 불러오기",
"draft": "보존된 초안",
- "unsaved_changes": "저장하지 않은 변경사항"
+ "unsaved_changes": "저장하지 않은 변경사항",
+ "live": "실시간",
+ "reconnecting": "다시 연결하는 중...",
+ "connecting": "연결하는 중...",
+ "title_save_failed": "제목을 저장하지 못했습니다",
+ "editing_now": "편집 중"
},
"history": {
"title": "기록",
diff --git a/packages/views/locales/ru/docs.json b/packages/views/locales/ru/docs.json
index a1fac7be26..1013342d4b 100644
--- a/packages/views/locales/ru/docs.json
+++ b/packages/views/locales/ru/docs.json
@@ -48,7 +48,12 @@
"conflict": "{{name}} обновил документ. Черновик сохранён. Загрузите последнюю версию.",
"reload": "Загрузить последнюю версию",
"draft": "Сохранённый черновик",
- "unsaved_changes": "Несохранённые изменения"
+ "unsaved_changes": "Несохранённые изменения",
+ "live": "Совместно",
+ "reconnecting": "Переподключение...",
+ "connecting": "Подключение...",
+ "title_save_failed": "Название не сохранено",
+ "editing_now": "Редактируют сейчас"
},
"history": {
"title": "История",
diff --git a/packages/views/locales/zh-Hans/docs.json b/packages/views/locales/zh-Hans/docs.json
index c158187df3..a71cd7ad68 100644
--- a/packages/views/locales/zh-Hans/docs.json
+++ b/packages/views/locales/zh-Hans/docs.json
@@ -48,7 +48,12 @@
"conflict": "{{name}} 已更新文档。草稿已保留,刷新后继续编辑。",
"reload": "刷新最新版本",
"draft": "保留的草稿",
- "unsaved_changes": "未保存的修改"
+ "unsaved_changes": "未保存的修改",
+ "live": "实时协作",
+ "reconnecting": "正在重新连接...",
+ "connecting": "正在连接...",
+ "title_save_failed": "标题未保存",
+ "editing_now": "正在编辑"
},
"history": {
"title": "历史",
diff --git a/packages/views/locales/zh-Hant/docs.json b/packages/views/locales/zh-Hant/docs.json
index 71d6801f0b..1206efc5c4 100644
--- a/packages/views/locales/zh-Hant/docs.json
+++ b/packages/views/locales/zh-Hant/docs.json
@@ -48,7 +48,12 @@
"conflict": "{{name}} 已更新文件。草稿已保留,重新載入後繼續編輯。",
"reload": "載入最新版本",
"draft": "保留的草稿",
- "unsaved_changes": "未儲存的修改"
+ "unsaved_changes": "未儲存的修改",
+ "live": "即時協作",
+ "reconnecting": "正在重新連線...",
+ "connecting": "正在連線...",
+ "title_save_failed": "標題未儲存",
+ "editing_now": "正在編輯"
},
"history": {
"title": "歷史",
diff --git a/packages/views/package.json b/packages/views/package.json
index 06f4aff215..e5c687857f 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -18,6 +18,8 @@
"./common/menu-primitives": "./common/menu-primitives.ts",
"./common/shortcut-keycaps": "./common/shortcut-keycaps.tsx",
"./editor": "./editor/index.ts",
+ "./editor/schema": "./editor/schema/index.ts",
+ "./editor/schema/codec": "./editor/schema/codec.ts",
"./issue-views": "./issue-views/index.ts",
"./issues/components": "./issues/components/index.ts",
"./issues/components/status-icon": "./issues/components/status-icon.tsx",
@@ -97,11 +99,14 @@
"@dnd-kit/sortable": "catalog:",
"@dnd-kit/utilities": "catalog:",
"@floating-ui/dom": "^1.7.6",
+ "@hocuspocus/provider": "catalog:",
"@multica/core": "workspace:*",
"@multica/ui": "workspace:*",
"@tanstack/react-virtual": "catalog:",
"@tiptap/core": "3.31.3",
"@tiptap/extension-code-block-lowlight": "3.31.3",
+ "@tiptap/extension-collaboration": "3.31.3",
+ "@tiptap/extension-collaboration-caret": "3.31.3",
"@tiptap/extension-document": "3.31.3",
"@tiptap/extension-highlight": "3.31.3",
"@tiptap/extension-image": "3.31.3",
@@ -121,6 +126,7 @@
"@tiptap/react": "3.31.3",
"@tiptap/starter-kit": "3.31.3",
"@tiptap/suggestion": "3.31.3",
+ "@tiptap/y-tiptap": "^3.3.1",
"cmdk": "catalog:",
"hast-util-to-html": "^9.0.5",
"katex": "catalog:",
@@ -149,7 +155,9 @@
"remark-math": "catalog:",
"sonner": "catalog:",
"unist-util-visit": "^5.1.0",
- "yaml": "catalog:"
+ "y-protocols": "catalog:",
+ "yaml": "catalog:",
+ "yjs": "catalog:"
},
"peerDependencies": {
"@tanstack/react-query": "catalog:",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5483a13f21..a463c9efe2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -27,6 +27,9 @@ catalogs:
'@formatjs/intl-localematcher':
specifier: ^0.8.4
version: 0.8.4
+ '@hocuspocus/provider':
+ specifier: ^4.9.0
+ version: 4.9.0
'@tailwindcss/postcss':
specifier: ^4
version: 4.2.2
@@ -192,9 +195,15 @@ catalogs:
vitest:
specifier: ^4.1.0
version: 4.1.0
+ y-protocols:
+ specifier: ^1.0.7
+ version: 1.0.7
yaml:
specifier: ^2.6.0
version: 2.9.0
+ yjs:
+ specifier: ^13.6.33
+ version: 13.6.33
zod:
specifier: ^4.1.5
version: 4.3.6
@@ -255,6 +264,46 @@ importers:
specifier: 'catalog:'
version: 2.9.0
+ apps/collab:
+ dependencies:
+ '@hocuspocus/server':
+ specifier: ^4.9.0
+ '@multica/views':
+ specifier: workspace:*
+ version: link:../../packages/views
+ happy-dom:
+ specifier: ^21.0.4
+ version: 21.0.4
+ node-diff3:
+ specifier: ^4.0.0
+ version: 4.0.0
+ tsx:
+ specifier: ^4.21.0
+ version: 4.23.15
+ y-protocols:
+ specifier: 'catalog:'
+ version: 1.0.7([email protected])
+ yjs:
+ specifier: 'catalog:'
+ version: 13.6.33
+ devDependencies:
+ '@hocuspocus/provider':
+ specifier: 'catalog:'
+ '@multica/tsconfig':
+ specifier: workspace:*
+ version: link:../../packages/tsconfig
+ '@types/node':
+ specifier: 'catalog:'
+ version: 25.5.0
+ '@typescript/native':
+ specifier: 'catalog:'
+ vitest:
+ specifier: 'catalog:'
+
apps/desktop:
dependencies:
'@dnd-kit/core':
@@ -347,7 +396,7 @@ importers:
version: link:../../packages/vitest-setup
'@tailwindcss/vite':
specifier: 'catalog:'
'@testing-library/jest-dom':
specifier: 'catalog:'
version: 6.9.1
@@ -368,7 +417,7 @@ importers:
'@vitejs/plugin-react':
specifier: ^5.1.1
electron:
specifier: ^44.9.3
version: 44.9.3
@@ -377,7 +426,7 @@ importers:
version: 26.8.1([email protected])
electron-vite:
specifier: ^5.0.0
globals:
specifier: ^16.0.0
version: 16.5.0
@@ -395,7 +444,7 @@ importers:
version: '@typescript/[email protected]'
vitest:
specifier: 'catalog:'
apps/docs:
dependencies:
@@ -407,7 +456,7 @@ importers:
fumadocs-mdx:
specifier: 'catalog:'
fumadocs-ui:
specifier: 'catalog:'
@@ -462,7 +511,7 @@ importers:
version: 11.0.5
vitest:
specifier: 'catalog:'
apps/mobile:
dependencies:
@@ -597,7 +646,7 @@ importers:
version: 2.0.1
nativewind:
specifier: ^4.1.23
react:
specifier: 19.2.3
version: 19.2.3
@@ -651,10 +700,10 @@ importers:
version: 2.6.1
tailwindcss:
specifier: ^3.4.17
- version: 3.4.19([email protected])
tailwindcss-animate:
specifier: ^1.0.7
zod:
specifier: ^4.1.5
version: 4.3.6
@@ -682,7 +731,7 @@ importers:
version: 6.0.3
vitest:
specifier: 'catalog:'
apps/storybook:
dependencies:
@@ -713,10 +762,10 @@ importers:
version: link:../../packages/tsconfig
'@storybook/react-vite':
specifier: ^10.6.7
'@tailwindcss/vite':
specifier: 'catalog:'
'@types/react':
specifier: ^19.2.0
version: 19.2.14
@@ -728,7 +777,7 @@ importers:
'@vitejs/plugin-react':
specifier: 'catalog:'
storybook:
specifier: ^10.6.7
version: 10.6.7(@types/[email protected])([email protected])
@@ -740,7 +789,7 @@ importers:
version: '@typescript/[email protected]'
vite:
specifier: ^8.0.1
apps/web:
dependencies:
@@ -767,7 +816,7 @@ importers:
fumadocs-mdx:
specifier: 'catalog:'
next:
specifier: 'catalog:'
@@ -816,7 +865,7 @@ importers:
'@vitejs/plugin-react':
specifier: 'catalog:'
jsdom:
specifier: 'catalog:'
version: 29.0.1(@noble/[email protected])
@@ -831,7 +880,7 @@ importers:
version: '@typescript/[email protected]'
vitest:
specifier: 'catalog:'
packages/core:
dependencies:
@@ -901,7 +950,7 @@ importers:
version: '@typescript/[email protected]'
vitest:
specifier: 'catalog:'
packages/ee:
dependencies:
@@ -968,7 +1017,7 @@ importers:
'@vitejs/plugin-react':
specifier: 'catalog:'
eslint:
specifier: 'catalog:'
version: 9.39.4([email protected])
@@ -983,7 +1032,7 @@ importers:
version: '@typescript/[email protected]'
vitest:
specifier: 'catalog:'
packages/eslint-config:
dependencies:
@@ -1160,7 +1209,7 @@ importers:
'@vitejs/plugin-react':
specifier: 'catalog:'
esbuild:
specifier: ^0.25.12
version: 0.25.12
@@ -1172,7 +1221,7 @@ importers:
version: '@typescript/[email protected]'
vitest:
specifier: 'catalog:'
packages/views:
dependencies:
@@ -1194,6 +1243,9 @@ importers:
'@floating-ui/dom':
specifier: ^1.7.6
version: 1.7.6
+ '@hocuspocus/provider':
+ specifier: 'catalog:'
'@multica/core':
specifier: workspace:*
version: link:../core
@@ -1215,6 +1267,12 @@ importers:
'@tiptap/extension-code-block-lowlight':
specifier: 3.31.3
+ '@tiptap/extension-collaboration':
+ specifier: 3.31.3
+ '@tiptap/extension-collaboration-caret':
+ specifier: 3.31.3
'@tiptap/extension-document':
specifier: 3.31.3
version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))
@@ -1272,6 +1330,9 @@ importers:
'@tiptap/suggestion':
specifier: 3.31.3
version: 3.31.3(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
+ '@tiptap/y-tiptap':
+ specifier: ^3.3.1
cmdk:
specifier: 'catalog:'
@@ -1368,9 +1429,15 @@ importers:
unist-util-visit:
specifier: ^5.1.0
version: 5.1.0
+ y-protocols:
+ specifier: 'catalog:'
+ version: 1.0.7([email protected])
yaml:
specifier: 'catalog:'
version: 2.9.0
+ yjs:
+ specifier: 'catalog:'
+ version: 13.6.33
zustand:
specifier: 'catalog:'
@@ -1416,7 +1483,7 @@ importers:
'@vitejs/plugin-react':
specifier: 'catalog:'
eslint:
specifier: 'catalog:'
version: 9.39.4([email protected])
@@ -1431,7 +1498,7 @@ importers:
version: '@typescript/[email protected]'
vitest:
specifier: 'catalog:'
packages/vitest-setup: {}
@@ -2677,6 +2744,22 @@ packages:
'@fumari/[email protected]':
resolution: {integrity: sha512-iaiV2wyzJ4mW358NX4CX3yGit+WjKYzpaQ+rldK9BjL/5jFpeV6ruWnZVq7MEyMn3Gd0DLi8g/79NZAAQaGscw==}
+ '@hocuspocus/[email protected]':
+ resolution: {integrity: sha512-lrp5gtT8kvLt9/MuRRQPKaveihv5emSsP9+sMCq2rx8xVGn33PZIv0haSGyb37CbAIlVaHb/yG22VKKMx+clYg==}
+
+ '@hocuspocus/[email protected]':
+ resolution: {integrity: sha512-I+B/bJs8SRCBZRRevdNkMGtCAE6S13hsTFX2SZ33iSSJC/4IZcsl5+St9/OYYxxkETfvelJKsmhtwdyIwXnsEg==}
+ peerDependencies:
+ y-protocols: ^1.0.6
+ yjs: ^13.6.8
+
+ '@hocuspocus/[email protected]':
+ resolution: {integrity: sha512-8qRkIcFpcz4cw2WHLgUdwZGAqiUUdueh9iCdhujYfExHsnGnJ3iTiowGOs25HsNfUhxQRj6HJBGi4M2lP3rEpg==}
+ engines: {node: '>=22'}
+ peerDependencies:
+ y-protocols: ^1.0.6
+ yjs: ^13.6.8
+
resolution: {integrity: sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g==}
engines: {node: '>=18.14.1'}
@@ -2953,6 +3036,9 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
+ '@lifeomic/[email protected]':
+ resolution: {integrity: sha512-QZqem4QuAnAyzfz+Gj5/+SLxqwCAw2qmt7732ZXodr6VDWGeYLG6w1i/vYLa55JQM9wRuBKLmXmiZ2P0LtE5rw==}
+
'@malept/[email protected]':
resolution: {integrity: sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==}
engines: {node: '>= 12.13.0'}
@@ -5165,6 +5251,21 @@ packages:
peerDependencies:
'@tiptap/core': 3.31.3
+ '@tiptap/[email protected]':
+ resolution: {integrity: sha512-ub2SsYwmEcmTbqk4aC55M6AnU5/jJcr85lk0jQTqoo1h4ADGYcVXKaJY/CgDCxJgPxr6e/+IiNSYTLjW0nOEgg==}
+ peerDependencies:
+ '@tiptap/core': 3.31.3
+ '@tiptap/pm': 3.31.3
+ '@tiptap/y-tiptap': ^3.0.7
+
+ '@tiptap/[email protected]':
+ resolution: {integrity: sha512-JAwOXjeeDYghrPcK57dtvxwn06zcz50mxSSk4PaSdLxM8tkw8+udx+51ewqKKd3WlFof4zyMwUEbO/DGaUdEvw==}
+ peerDependencies:
+ '@tiptap/core': 3.31.3
+ '@tiptap/pm': 3.31.3
+ '@tiptap/y-tiptap': ^3.0.7
+ yjs: ^13
+
'@tiptap/[email protected]':
resolution: {integrity: sha512-EexgmqnyDNyGlISxo7SMrp5MygpJYmqD+0cY5jB6L1U6L4CpKKRWUt8OO1sWzEHDE1+TTvwt+WIFoIWAziOtEA==}
peerDependencies:
@@ -5338,6 +5439,15 @@ packages:
'@tiptap/core': 3.31.3
'@tiptap/pm': 3.31.3
+ '@tiptap/[email protected]':
+ resolution: {integrity: sha512-QbjDWZUWwgu22HyohKVVVZJnhkqGru+iibQR1yvN4+YnwEeTbRouCDGXOT93QqxpoEek+I9JM14zDkh9nq1/Aw==}
+ peerDependencies:
+ prosemirror-model: ^1.7.1
+ prosemirror-state: ^1.2.3
+ prosemirror-view: ^1.9.10
+ y-protocols: ^1.0.1
+ yjs: ^13.6.13
+
'@ts-morph/[email protected]':
resolution: {integrity: sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ==}
@@ -5604,6 +5714,12 @@ packages:
resolution: {integrity: sha512-RlDm9K7+o5stv0Co8i8ZRGxDbrTxhJtgjqjFyVh/tXQyl/rYtTKlnTvZ88oSTeYREWurwx20Js4kTuKCsFkUtg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==}
+
resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==}
@@ -6292,6 +6408,9 @@ packages:
resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==}
+
resolution: {integrity: sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==}
@@ -6430,6 +6549,10 @@ packages:
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
+ resolution: {integrity: sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==}
+ engines: {node: '>=4.0'}
+
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
@@ -6803,6 +6926,14 @@ packages:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-YG2kyfafNXKmu7e6k64yrj6whrw7m5sBIsOSXOlJ/72X3TQWRQuw8DhvXFDcBk8HF77PnTSygnm7xpYCTnFpow==}
+ peerDependencies:
+ srvx: '>=0.11.5'
+ peerDependenciesMeta:
+ srvx:
+ optional: true
+
resolution: {integrity: sha512-fJAcud6B3rRu+KHYk+Bwf+WFL2MDCJJ1XG9x137tJQ0xYxor7XziQtuGFbWNdqrvF4Tk26O3H73nfVqXt/fW1A==}
@@ -7319,6 +7450,10 @@ packages:
resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
engines: {node: '>=0.12'}
+ resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
+ engines: {node: '>=0.12'}
+
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
engines: {node: '>=6'}
@@ -8343,6 +8478,10 @@ packages:
resolution: {integrity: sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==}
+ resolution: {integrity: sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw==}
+ engines: {node: '>=20.0.0'}
+
resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==}
engines: {node: '>= 0.4'}
@@ -8831,6 +8970,9 @@ packages:
resolution: {integrity: sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==}
+
resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==}
engines: {node: '>= 0.4'}
@@ -8992,6 +9134,11 @@ packages:
resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}
engines: {node: '>= 0.8.0'}
+ resolution: {integrity: sha512-/a2eRImR8sZbmMVKe2we1/KukDQkuPyPf8yol6epvCu2PH6hurjcRI3mdGFFAi0uGoRJGyns99JquZgxwW1tQg==}
+ engines: {node: '>=16'}
+ hasBin: true
+
resolution: {integrity: sha512-gPWxznF6TKmUHrOQjlVo2UbaL2EJ71mb2CCeRs/2qBpi4L/g4LUVc9+3lKQ6DTUZwJswfM7ainGrLO1+fOqa2g==}
@@ -9873,6 +10020,10 @@ packages:
resolution: {integrity: sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==}
+ resolution: {integrity: sha512-U6ROYD85/70rtvHRa3mmB2PUHNT9R+K3Oo5WLnCtVl3aZ2GPY+lgB+vrIfwy5P/fr+Avng+loYDgk+MglPgwMQ==}
+ engines: {bun: '>=1.3.10'}
+
resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}
engines: {node: '>=10.5.0'}
@@ -11734,6 +11885,11 @@ packages:
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
+ resolution: {integrity: sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==}
+ engines: {node: '>=18.0.0'}
+ hasBin: true
+
resolution: {integrity: sha512-JXNkRe6H6MjSlk5UQRTjyoKX5YN2zlc2632xcSlSFBao5yvbMWTpv9SNolOZlZmUlcDOHuszPLItbKrvcXnnZA==}
hasBin: true
@@ -12131,6 +12287,10 @@ packages:
resolution: {integrity: sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg==}
+ resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==}
engines: {node: '>=20'}
@@ -12212,18 +12372,6 @@ packages:
utf-8-validate:
optional: true
- resolution: {integrity: sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==}
- engines: {node: '>=10.0.0'}
- peerDependencies:
- bufferutil: ^4.0.1
- utf-8-validate: '>=5.0.2'
- peerDependenciesMeta:
- bufferutil:
- optional: true
- utf-8-validate:
- optional: true
-
resolution: {integrity: sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==}
engines: {node: '>=10.0.0'}
@@ -12271,6 +12419,12 @@ packages:
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
engines: {node: '>=0.4'}
+ resolution: {integrity: sha512-YSVsLoXxO67J6eE/nV4AtFtT3QEotZf5sK5BHxFBXso7VDUT3Tx07IfA6hsu5Q5OmBdMkQVmFZ9QOA7fikWvnw==}
+ engines: {node: '>=16.0.0', npm: '>=8.0.0'}
+ peerDependencies:
+ yjs: ^13.0.0
+
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
engines: {node: '>=10'}
@@ -12303,6 +12457,10 @@ packages:
resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==}
+ engines: {node: '>=16.0.0', npm: '>=8.0.0'}
+
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
engines: {node: '>=10'}
@@ -13424,7 +13582,7 @@ snapshots:
'@expo/schema-utils': 57.0.2
'@expo/spawn-async': 1.8.0
- '@expo/ws-tunnel': 2.0.1([email protected])
+ '@expo/ws-tunnel': 2.0.1([email protected])
'@expo/xcpretty': 4.4.4
'@react-native/dev-middleware': 0.86.3
accepts: 1.3.8
@@ -13462,7 +13620,7 @@ snapshots:
terminal-link: 2.1.1
toqr: 0.1.1
wrap-ansi: 7.0.0
- ws: 8.20.1
+ ws: 8.23.0
zod: 3.25.76
optionalDependencies:
expo-router: 57.0.25(8a20a4667a541f38b33c8305b447f6bf)
@@ -13777,9 +13935,9 @@ snapshots:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
- ws: 8.20.1
+ ws: 8.23.0
dependencies:
@@ -13831,6 +13989,30 @@ snapshots:
'@fumari/[email protected]': {}
+ '@hocuspocus/[email protected]':
+ dependencies:
+ lib0: 0.2.120
+
+ dependencies:
+ '@hocuspocus/common': 4.9.0
+ '@lifeomic/attempt': 3.1.0
+ lib0: 0.2.120
+ y-protocols: 1.0.7([email protected])
+ yjs: 13.6.33
+
+ dependencies:
+ '@hocuspocus/common': 4.9.0
+ async-mutex: 0.5.0
+ crossws: 0.4.17
+ kleur: 4.1.5
+ lib0: 0.2.120
+ y-protocols: 1.0.7([email protected])
+ yjs: 13.6.33
+ transitivePeerDependencies:
+ - srvx
+
dependencies:
hono: 4.12.8
@@ -14017,11 +14199,11 @@ snapshots:
'@types/yargs': 17.0.35
chalk: 4.1.2
dependencies:
glob: 13.0.6
react-docgen-typescript: 2.4.0(@typescript/[email protected])
optionalDependencies:
typescript: '@typescript/[email protected]'
@@ -14051,6 +14233,8 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5
+ '@lifeomic/[email protected]': {}
+
'@malept/[email protected]':
dependencies:
cross-spawn: 7.0.6
@@ -15815,11 +15999,11 @@ snapshots:
'@standard-schema/[email protected]': {}
dependencies:
storybook: 10.6.7(@types/[email protected])([email protected])
ts-dedent: 2.2.0
'@storybook/[email protected]': {}
@@ -15836,11 +16020,11 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
dependencies:
- '@joshwooding/vite-plugin-react-docgen-typescript': 0.7.0(@typescript/[email protected])([email protected](@emnapi/[email protected])(@emnapi/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))
+ '@joshwooding/vite-plugin-react-docgen-typescript': 0.7.0(@typescript/[email protected])([email protected](@emnapi/[email protected])(@emnapi/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))
'@rollup/pluginutils': 5.5.1
empathic: 2.1.0
magic-string: 1.4.3
@@ -15850,7 +16034,7 @@ snapshots:
resolve: 1.22.12
storybook: 10.6.7(@types/[email protected])([email protected])
tsconfig-paths: 4.2.0
optionalDependencies:
typescript: '@typescript/[email protected]'
transitivePeerDependencies:
@@ -15954,12 +16138,12 @@ snapshots:
postcss: 8.5.26
tailwindcss: 4.2.2
dependencies:
'@tailwindcss/node': 4.2.2
'@tailwindcss/oxide': 4.2.2
tailwindcss: 4.2.2
'@tanstack/[email protected]': {}
@@ -16063,6 +16247,19 @@ snapshots:
dependencies:
'@tiptap/core': 3.31.3(@tiptap/[email protected])
+ dependencies:
+ '@tiptap/core': 3.31.3(@tiptap/[email protected])
+ '@tiptap/pm': 3.31.3
+
+ dependencies:
+ '@tiptap/core': 3.31.3(@tiptap/[email protected])
+ '@tiptap/pm': 3.31.3
+ yjs: 13.6.33
+
dependencies:
'@tiptap/core': 3.31.3(@tiptap/[email protected])
@@ -16254,6 +16451,16 @@ snapshots:
'@tiptap/core': 3.31.3(@tiptap/[email protected])
'@tiptap/pm': 3.31.3
+ dependencies:
+ lib0: 0.2.120
+ prosemirror-model: 1.25.12
+ prosemirror-state: 1.4.4
+ prosemirror-transform: 1.12.0
+ prosemirror-view: 1.42.6
+ y-protocols: 1.0.7([email protected])
+ yjs: 13.6.33
+
'@ts-morph/[email protected]':
dependencies:
fast-glob: 3.3.3
@@ -16551,6 +16758,12 @@ snapshots:
optional: true
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 25.5.0
+
'@types/[email protected]': {}
@@ -16926,7 +17139,7 @@ snapshots:
d3-selection: 3.0.0
d3-transition: 3.0.1([email protected])
dependencies:
'@babel/core': 7.29.0
'@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/[email protected])
@@ -16934,21 +17147,21 @@ snapshots:
'@rolldown/pluginutils': 1.0.0-rc.3
'@types/babel__core': 7.20.5
react-refresh: 0.18.0
transitivePeerDependencies:
- supports-color
dependencies:
'@rolldown/pluginutils': 1.0.0-rc.7
optionalDependencies:
babel-plugin-react-compiler: 1.0.0
dependencies:
'@rolldown/pluginutils': 1.0.0-rc.7
optionalDependencies:
babel-plugin-react-compiler: 1.0.0
@@ -16969,41 +17182,50 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.0
dependencies:
'@vitest/spy': 4.1.0
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
msw: 2.12.14(@types/[email protected])(@typescript/[email protected])
dependencies:
'@vitest/spy': 4.1.0
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
msw: 2.12.14(@types/[email protected])(@typescript/[email protected])
dependencies:
'@vitest/spy': 4.1.0
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
msw: 2.12.14(@types/[email protected])(@typescript/[email protected])
dependencies:
'@vitest/spy': 4.1.0
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
msw: 2.12.14(@types/[email protected])([email protected])
+
+ dependencies:
+ '@vitest/spy': 4.1.0
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+ msw: 2.12.14(@types/[email protected])([email protected])
'@vitest/[email protected]':
dependencies:
@@ -17312,6 +17534,10 @@ snapshots:
+ dependencies:
+ tslib: 2.8.1
+
@@ -17504,6 +17730,10 @@ snapshots:
+ dependencies:
+ '@types/node': 25.5.0
+
dependencies:
base64-js: 1.5.1
@@ -17906,6 +18136,8 @@ snapshots:
shebang-command: 2.0.0
which: 2.0.2
+
dependencies:
hyphenate-style-name: 1.1.0
@@ -18404,7 +18636,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@babel/core': 7.29.0
'@babel/plugin-transform-arrow-functions': 7.27.1(@babel/[email protected])
@@ -18412,7 +18644,7 @@ snapshots:
esbuild: 0.25.12
magic-string: 0.30.21
picocolors: 1.1.1
transitivePeerDependencies:
- supports-color
@@ -18468,6 +18700,8 @@ snapshots:
+
@@ -19697,7 +19931,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@mdx-js/mdx': 3.1.1
'@standard-schema/spec': 1.1.0
@@ -19724,11 +19958,11 @@ snapshots:
'@types/react': 19.2.14
react: 19.2.3
transitivePeerDependencies:
- supports-color
dependencies:
'@mdx-js/mdx': 3.1.1
'@standard-schema/spec': 1.1.0
@@ -19755,7 +19989,7 @@ snapshots:
'@types/react': 19.2.14
react: 19.2.3
transitivePeerDependencies:
- supports-color
@@ -19939,6 +20173,19 @@ snapshots:
+ dependencies:
+ '@types/node': 25.5.0
+ '@types/whatwg-mimetype': 3.0.2
+ '@types/ws': 8.18.2
+ buffer-image-size: 0.6.4
+ entities: 7.0.1
+ whatwg-mimetype: 3.0.0
+ ws: 8.23.0
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+
@@ -20472,6 +20719,8 @@ snapshots:
+
dependencies:
define-data-property: 1.1.4
@@ -20660,6 +20909,10 @@ snapshots:
prelude-ls: 1.2.1
type-check: 0.4.0
+ dependencies:
+ isomorphic.js: 0.2.5
+
dependencies:
debug: 2.6.9
@@ -21973,6 +22226,32 @@ snapshots:
- '@types/node'
optional: true
+ dependencies:
+ '@inquirer/confirm': 5.1.21(@types/[email protected])
+ '@mswjs/interceptors': 0.41.3
+ '@open-draft/deferred-promise': 2.2.0
+ '@types/statuses': 2.0.6
+ cookie: 1.1.1
+ graphql: 16.13.1
+ headers-polyfill: 4.0.3
+ is-node-process: 1.2.0
+ outvariant: 1.4.3
+ path-to-regexp: 6.3.0
+ picocolors: 1.1.1
+ rettime: 0.10.1
+ statuses: 2.0.2
+ strict-event-emitter: 0.5.1
+ tough-cookie: 6.0.1
+ type-fest: 5.5.0
+ until-async: 3.0.2
+ yargs: 17.7.2
+ optionalDependencies:
+ typescript: 7.0.2
+ transitivePeerDependencies:
+ - '@types/node'
+ optional: true
+
@@ -21987,12 +22266,12 @@ snapshots:
dependencies:
comment-json: 4.6.2
debug: 4.4.3
- tailwindcss: 3.4.19([email protected])
+ tailwindcss: 3.4.19([email protected])([email protected])
transitivePeerDependencies:
- react
- react-native
@@ -22053,6 +22332,8 @@ snapshots:
dependencies:
semver: 7.8.5
+
@@ -22580,12 +22861,13 @@ snapshots:
camelcase-css: 2.0.1
postcss: 8.5.26
dependencies:
lilconfig: 3.1.3
optionalDependencies:
jiti: 1.21.7
postcss: 8.5.26
+ tsx: 4.23.15
yaml: 2.9.1
@@ -22932,7 +23214,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@babel/helper-module-imports': 7.28.6
'@babel/traverse': 7.29.0
@@ -22943,7 +23225,7 @@ snapshots:
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
semver: 7.7.4
- tailwindcss: 3.4.19([email protected])
+ tailwindcss: 3.4.19([email protected])([email protected])
optionalDependencies:
react-native-safe-area-context: 5.7.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
@@ -24196,11 +24478,11 @@ snapshots:
dependencies:
- tailwindcss: 3.4.19([email protected])
+ tailwindcss: 3.4.19([email protected])([email protected])
dependencies:
'@alloc/quick-lru': 5.2.0
arg: 5.0.2
@@ -24219,7 +24501,7 @@ snapshots:
postcss: 8.5.26
postcss-import: 15.1.0([email protected])
postcss-js: 4.1.0([email protected])
postcss-nested: 6.2.0([email protected])
postcss-selector-parser: 6.1.2
resolve: 1.22.12
@@ -24374,6 +24656,12 @@ snapshots:
+ dependencies:
+ esbuild: 0.28.2
+ optionalDependencies:
+ fsevents: 2.3.3
+
optionalDependencies:
'@turbo/darwin-64': 2.9.5
@@ -24692,7 +24980,7 @@ snapshots:
d3-time: 3.1.0
d3-timer: 3.0.1
dependencies:
lightningcss: 1.32.0
picomatch: 4.0.7
@@ -24705,12 +24993,13 @@ snapshots:
fsevents: 2.3.3
jiti: 2.7.0
terser: 5.47.1
+ tsx: 4.23.15
yaml: 2.9.1
transitivePeerDependencies:
- '@emnapi/core'
- '@emnapi/runtime'
dependencies:
lightningcss: 1.32.0
picomatch: 4.0.7
@@ -24722,12 +25011,13 @@ snapshots:
fsevents: 2.3.3
jiti: 1.21.7
terser: 5.47.1
+ tsx: 4.23.15
yaml: 2.9.1
transitivePeerDependencies:
- '@emnapi/core'
- '@emnapi/runtime'
dependencies:
lightningcss: 1.32.0
picomatch: 4.0.7
@@ -24739,15 +25029,16 @@ snapshots:
fsevents: 2.3.3
jiti: 2.7.0
terser: 5.47.1
+ tsx: 4.23.15
yaml: 2.9.0
transitivePeerDependencies:
- '@emnapi/core'
- '@emnapi/runtime'
dependencies:
'@vitest/expect': 4.1.0
'@vitest/pretty-format': 4.1.0
'@vitest/runner': 4.1.0
'@vitest/snapshot': 4.1.0
@@ -24764,19 +25055,20 @@ snapshots:
tinyexec: 1.0.4
tinyglobby: 0.2.15
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.1
'@types/node': 25.5.0
+ happy-dom: 21.0.4
jsdom: 29.0.1(@noble/[email protected])
transitivePeerDependencies:
- msw
dependencies:
'@vitest/expect': 4.1.0
'@vitest/pretty-format': 4.1.0
'@vitest/runner': 4.1.0
'@vitest/snapshot': 4.1.0
@@ -24793,19 +25085,20 @@ snapshots:
tinyexec: 1.0.4
tinyglobby: 0.2.15
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.1
'@types/node': 25.5.0
+ happy-dom: 21.0.4
jsdom: 29.0.1(@noble/[email protected])
transitivePeerDependencies:
- msw
dependencies:
'@vitest/expect': 4.1.0
'@vitest/pretty-format': 4.1.0
'@vitest/runner': 4.1.0
'@vitest/snapshot': 4.1.0
@@ -24822,19 +25115,20 @@ snapshots:
tinyexec: 1.0.4
tinyglobby: 0.2.15
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.1
'@types/node': 25.5.0
+ happy-dom: 21.0.4
jsdom: 29.0.1(@noble/[email protected])
transitivePeerDependencies:
- msw
dependencies:
'@vitest/expect': 4.1.0
'@vitest/pretty-format': 4.1.0
'@vitest/runner': 4.1.0
'@vitest/snapshot': 4.1.0
@@ -24851,11 +25145,42 @@ snapshots:
tinyexec: 1.0.4
tinyglobby: 0.2.15
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.1
'@types/node': 25.5.0
+ happy-dom: 21.0.4
+ jsdom: 29.0.1(@noble/[email protected])
+ transitivePeerDependencies:
+ - msw
+
+ dependencies:
+ '@vitest/expect': 4.1.0
+ '@vitest/pretty-format': 4.1.0
+ '@vitest/runner': 4.1.0
+ '@vitest/snapshot': 4.1.0
+ '@vitest/spy': 4.1.0
+ '@vitest/utils': 4.1.0
+ es-module-lexer: 2.0.0
+ expect-type: 1.3.0
+ magic-string: 0.30.21
+ obug: 2.1.1
+ pathe: 2.0.3
+ picomatch: 4.0.3
+ std-env: 4.0.0
+ tinybench: 2.9.0
+ tinyexec: 1.0.4
+ tinyglobby: 0.2.15
+ tinyrainbow: 3.1.0
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.1
+ '@types/node': 25.5.0
+ happy-dom: 21.0.4
jsdom: 29.0.1(@noble/[email protected])
transitivePeerDependencies:
- msw
@@ -24911,6 +25236,8 @@ snapshots:
+
@@ -25010,8 +25337,6 @@ snapshots:
-
@@ -25043,6 +25368,11 @@ snapshots:
+ dependencies:
+ lib0: 0.2.120
+ yjs: 13.6.33
+
@@ -25067,6 +25397,10 @@ snapshots:
y18n: 5.0.8
yargs-parser: 21.1.1
+ dependencies:
+ lib0: 0.2.120
+
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 4980337a34..7bf54fdad3 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -10,6 +10,7 @@ catalog:
'@dnd-kit/utilities': ^3.2.2
'@fontsource-variable/inter': ^5.2.5
'@formatjs/intl-localematcher': ^0.8.4
+ '@hocuspocus/provider': ^4.9.0
'@tailwindcss/postcss': ^4
'@tailwindcss/vite': ^4
'@tanstack/react-query': ^5.96.2
@@ -37,8 +38,8 @@ catalog:
jsdom: ^29.0.1
katex: ^0.16.45
mdast-util-from-markdown: ^2.0.3
- micromark-util-sanitize-uri: ^2.0.1
mermaid: ^11.14.0
+ micromark-util-sanitize-uri: ^2.0.1
motion: ^12.38.0
next: ^16.4.5
next-themes: ^0.4.6
@@ -65,10 +66,11 @@ catalog:
tailwind-merge: ^3.4.0
tailwindcss: ^4
tw-animate-css: ^1.4.0
- # Keep the compiler API for ESLint, Next.js, and repository scripts; tsc uses @typescript/native.
typescript: npm:@typescript/[email protected]
unified: ^11.0.5
vitest: ^4.1.0
+ y-protocols: ^1.0.7
yaml: ^2.6.0
+ yjs: ^13.6.33
zod: ^4.1.5
zustand: ^5.0.0
diff --git a/scripts/ci-scope.test.mjs b/scripts/ci-scope.test.mjs
index 65c0ccf2db..b47f8241cf 100644
--- a/scripts/ci-scope.test.mjs
+++ b/scripts/ci-scope.test.mjs
@@ -24,6 +24,7 @@ for (const [name, files, selected] of [
["docs test", ["apps/docs/lib/unrendered-bold.test.ts"], ["quality", "docs"]],
["web changelog", ["apps/web/features/landing/i18n/en.ts"], ["frontend", "quality"]],
["mobile UI", ["apps/mobile/app/index.tsx"], ["quality"]],
+ ["collaboration service", ["apps/collab/src/documents.ts"], ["frontend", "quality"]],
["migration only", ["server/migrations/999_example.up.sql"], ["backend", "sqlc"]],
["agent process code", ["server/pkg/agent/cursor_background.go"], ["backend", "runtime"]],
["daemon dependency", ["server/internal/skill/service.go"], ["backend", "runtime"]],
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 04eba6bd4a..43451fe8c4 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -160,6 +160,8 @@ var concurrentIndexCleanups = map[string]string{
"707_doc_comment_workspace_idx": "doc_comment_workspace_idx",
"708_attachment_workspace_size_idx": "idx_attachment_workspace_size",
"712_dashboard_range_view_scope_idx": "uq_dashboard_range_view_scope",
+ "714_doc_collab_state_pkey_index": "doc_collab_state_pkey_idx",
+ "716_doc_revision_pkey_index": "doc_revision_pkey_idx",
"671_weixin_account_state_unique_index": "weixin_account_state_pkey",
"669_weixin_login_session_unique_index": "weixin_login_session_pkey",
"666_weixin_login_expiry_idx": "weixin_login_expiry_idx",
diff --git a/server/cmd/multica/cmd_doc.go b/server/cmd/multica/cmd_doc.go
index 8968afd721..f91cf909cc 100644
--- a/server/cmd/multica/cmd_doc.go
+++ b/server/cmd/multica/cmd_doc.go
@@ -18,15 +18,19 @@ import (
// Doc commands — the workspace knowledge base (MUL-8370).
//
// Writes are optimistic: `doc update` must name the revision it edited
-// (`--base-revision`, from `doc get`). When someone else saved in between the
-// server answers 409 and nothing is written; re-read, merge, retry.
+// (`--base-revision`, from `doc get`). When someone else saved in between,
+// the server merges the change into theirs, or answers 409 when both changed
+// the same paragraph. `doc edit` replaces quoted text and needs no revision.
var docCmd = &cobra.Command{
Use: "doc",
Short: "Work with knowledge base docs",
Long: "Read and write docs in the workspace knowledge base.\n\n" +
- "Every update needs --base-revision: the revision you read with `multica doc get`. " +
- "If the doc changed since then the update is refused; re-read it, merge your change, and retry. " +
+ "People may be editing a doc while you work on it. For targeted changes prefer " +
+ "`multica doc edit`: it replaces text you quote and lands wherever that text now is. " +
+ "`multica doc update` replaces the whole doc and needs --base-revision, the revision you read " +
+ "with `multica doc get`; edits made since then are merged in, and the update is refused only " +
+ "when you and someone else changed the same paragraph. " +
"Pass --message to say what changed and why — it shows in the doc's history.",
}
@@ -79,8 +83,20 @@ var docUpdateCmd = &cobra.Command{
RunE: runDocUpdate,
}
+var docEditCmd = &cobra.Command{
+ Use: "edit <doc-id>",
+ Short: "Replace quoted text in a doc",
+ Long: "Replace text in a doc without rewriting the rest of it.\n\n" +
+ "--old must match the doc's current Markdown exactly once (copy it from `multica doc get --output content`, " +
+ "with enough surrounding text to be unique), or at least once with --replace-all. " +
+ "The edit applies to the live doc, so it is safe while people are editing; " +
+ "it fails only when the quoted text is no longer there.",
+ Args: exactArgs(1),
+ RunE: runDocEdit,
+}
+
func init() {
- docCmd.AddCommand(docListCmd, docSearchCmd, docGetCmd, docCreateCmd, docUpdateCmd, docMoveCmd)
+ docCmd.AddCommand(docListCmd, docSearchCmd, docGetCmd, docCreateCmd, docUpdateCmd, docEditCmd, docMoveCmd)
docMoveCmd.Flags().String("folder", "", "Destination folder id, or `root` for the top level (required)")
docMoveCmd.Flags().String("output", "json", "Output format: table or json")
docListCmd.Flags().String("output", "table", "Output format: table or json")
@@ -97,6 +113,13 @@ func init() {
}
docCreateCmd.Flags().String("folder", "", "Folder id (default: root)")
docUpdateCmd.Flags().Int64("base-revision", 0, "Revision from doc get (required)")
+ docEditCmd.Flags().String("old", "", "Exact text to replace (required)")
+ docEditCmd.Flags().String("old-file", "", "Read the text to replace from a UTF-8 file")
+ docEditCmd.Flags().String("new", "", "Replacement text")
+ docEditCmd.Flags().String("new-file", "", "Read the replacement from a UTF-8 file")
+ docEditCmd.Flags().Bool("replace-all", false, "Replace every occurrence of --old")
+ docEditCmd.Flags().String("message", "", "Change summary for history")
+ docEditCmd.Flags().String("output", "json", "Output format: table or json")
}
type docTree struct {
@@ -153,10 +176,21 @@ func resolveDocFolderTarget(ctx context.Context, client *cli.APIClient, ref stri
// docWriteError turns a stale-revision 409 into instructions an agent can act on.
func docWriteError(action string, base int64, err error) error {
var httpErr *cli.HTTPError
- if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusConflict && strings.Contains(httpErr.Body, "revision_conflict") {
- return fmt.Errorf("%s: the doc changed since revision %d, so nothing was written. "+
- "Run `multica doc get` for the latest content and revision, merge your change into it, and retry with the new --base-revision (%s)",
- action, base, httpErr.Body)
+ if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusConflict {
+ switch {
+ case strings.Contains(httpErr.Body, "revision_conflict"):
+ return fmt.Errorf("%s: the doc changed since revision %d, so nothing was written. "+
+ "Run `multica doc get` for the latest content and revision, merge your change into it, and retry with the new --base-revision (%s)",
+ action, base, httpErr.Body)
+ case strings.Contains(httpErr.Body, "doc_merge_conflict"):
+ return fmt.Errorf("%s: someone changed the same paragraphs since revision %d, so nothing was written. "+
+ "The conflicts list both versions; run `multica doc get`, then apply your change with `multica doc edit` "+
+ "or retry the update from the new revision (%s)", action, base, httpErr.Body)
+ case strings.Contains(httpErr.Body, "doc_edit_failed"):
+ return fmt.Errorf("%s: nothing was written because --old does not match the doc exactly once. "+
+ "Run `multica doc get --output content`, quote the current text (with more context if it repeats), and retry (%s)",
+ action, httpErr.Body)
+ }
}
return fmt.Errorf("%s: %w", action, err)
}
@@ -325,7 +359,7 @@ func runDocGet(cmd *cobra.Command, args []string) error {
return err
}
var doc map[string]any
- if err := client.GetJSON(ctx, "/api/docs/"+id, &doc); err != nil {
+ if err := client.GetJSON(ctx, "/api/docs/"+id+"?flush=true", &doc); err != nil {
return fmt.Errorf("get doc: %w", err)
}
if output, _ := cmd.Flags().GetString("output"); output == "content" {
@@ -414,3 +448,61 @@ func runDocUpdate(cmd *cobra.Command, args []string) error {
output, _ := cmd.Flags().GetString("output")
return printDocSummary(doc, output)
}
+
+func readEditText(cmd *cobra.Command, flag string) (string, bool, error) {
+ if path, _ := cmd.Flags().GetString(flag + "-file"); path != "" {
+ if cmd.Flags().Changed(flag) {
+ return "", false, fmt.Errorf("pass only one of --%s and --%s-file", flag, flag)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return "", false, fmt.Errorf("read --%s-file: %w", flag, err)
+ }
+ return string(data), true, nil
+ }
+ v, _ := cmd.Flags().GetString(flag)
+ return v, cmd.Flags().Changed(flag), nil
+}
+
+func runDocEdit(cmd *cobra.Command, args []string) error {
+ oldText, hasOld, err := readEditText(cmd, "old")
+ if err != nil {
+ return err
+ }
+ if !hasOld || oldText == "" {
+ return fmt.Errorf("--old (or --old-file) is required: the exact text to replace")
+ }
+ newText, hasNew, err := readEditText(cmd, "new")
+ if err != nil {
+ return err
+ }
+ if !hasNew {
+ return fmt.Errorf("--new (or --new-file) is required; pass --new \"\" to delete the text")
+ }
+ replaceAll, _ := cmd.Flags().GetBool("replace-all")
+ body := map[string]any{
+ "edits": []map[string]any{{"old_text": oldText, "new_text": newText, "replace_all": replaceAll}},
+ }
+ if v, _ := cmd.Flags().GetString("message"); v != "" {
+ body["message"] = v
+ }
+
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ id, err := resolveDocRef(ctx, client, args[0], false)
+ if err != nil {
+ return err
+ }
+ var doc map[string]any
+ if err := client.PostJSON(ctx, "/api/docs/"+id+"/edits", body, &doc); err != nil {
+ return docWriteError("edit doc", 0, err)
+ }
+ delete(doc, "content")
+ output, _ := cmd.Flags().GetString("output")
+ return printDocSummary(doc, output)
+}
diff --git a/server/cmd/multica/cmd_doc_test.go b/server/cmd/multica/cmd_doc_test.go
index 29732da22e..93c5688249 100644
--- a/server/cmd/multica/cmd_doc_test.go
+++ b/server/cmd/multica/cmd_doc_test.go
@@ -13,7 +13,7 @@ import (
)
func TestDocCommandsExposeOnlyAgentReadWrite(t *testing.T) {
- expected := map[string]bool{"list": true, "search": true, "get": true, "create": true, "update": true, "move": true}
+ expected := map[string]bool{"list": true, "search": true, "get": true, "create": true, "edit": true, "update": true, "move": true}
for _, command := range docCmd.Commands() {
if !expected[command.Name()] {
t.Fatalf("unexpected doc command: %s", command.Name())
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index c7786e78fd..c6c22bb615 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -24,6 +24,7 @@ import (
"github.com/multica-ai/multica/server/internal/attachmentpreview"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/cloudruntime"
+ "github.com/multica-ai/multica/server/internal/collab"
"github.com/multica-ai/multica/server/internal/connectedapps"
"github.com/multica-ai/multica/server/internal/daemonws"
"github.com/multica-ai/multica/server/internal/entitlement"
@@ -469,6 +470,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
h.Metrics = opts.BusinessMetrics
h.InboxReads.Metrics = opts.InboxReadMetrics
h.FeatureFlags = opts.FeatureFlags
+ collabClient, err := collab.NewClient(os.Getenv("COLLAB_INTERNAL_URL"), os.Getenv("COLLAB_SECRET"))
+ if err != nil {
+ slog.Error("live doc editing disabled", "error", err)
+ }
+ h.Collab = collabClient
h.ThemeStore = themeStoreFromEnv()
h.TaskService.FeatureFlags = opts.FeatureFlags
h.TaskService.Metrics = opts.BusinessMetrics
@@ -1599,6 +1605,18 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
realtime.HandleWebSocket(hub, mc, pr, slugResolver, w, r)
})
+ // Live doc editing. Editors authenticate with a ticket from
+ // POST /api/docs/{id}/collab-ticket; the service calls back with the
+ // shared secret.
+ if h.Collab != nil {
+ r.Get("/collab", h.Collab.Proxy().ServeHTTP)
+ r.Route("/internal/collab/docs/{id}", func(r chi.Router) {
+ r.Use(h.RequireCollabSecret)
+ r.Get("/", h.GetCollabDoc)
+ r.Post("/store", h.StoreCollabDoc)
+ })
+ }
+
// Capability-authenticated attachment download (MUL-5292). Public by
// necessity: a native download (Electron's webContents.downloadURL, a
// cross-site webview <img>) carries neither Authorization nor a session
@@ -2361,6 +2379,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Route("/{id}", func(r chi.Router) {
r.Get("/", h.GetDoc)
r.Patch("/", h.UpdateDoc)
+ r.Post("/edits", h.EditDoc)
+ r.Post("/collab-ticket", h.CreateDocCollabTicket)
r.With(handler.RequireHumanActor).Delete("/", h.DeleteDoc)
r.Post("/move", h.MoveDoc)
r.Get("/versions", h.ListDocVersions)
diff --git a/server/internal/collab/client.go b/server/internal/collab/client.go
new file mode 100644
index 0000000000..046d762bbf
--- /dev/null
+++ b/server/internal/collab/client.go
@@ -0,0 +1,180 @@
+package collab
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+ "strings"
+ "time"
+)
+
+// SecretHeader authenticates the API and the collaboration service to each
+// other.
+const SecretHeader = "X-Collab-Secret"
+
+// ErrUnavailable means the service could not be reached or failed; callers
+// fall back to writing the stored doc directly.
+var ErrUnavailable = errors.New("collaboration service unavailable")
+
+// Client talks to the collaboration service's internal endpoints.
+type Client struct {
+ baseURL *url.URL
+ secret string
+ http *http.Client
+}
+
+// NewClient returns nil when either setting is empty: collaboration is off.
+func NewClient(internalURL, secret string) (*Client, error) {
+ internalURL, secret = strings.TrimSpace(internalURL), strings.TrimSpace(secret)
+ if internalURL == "" || secret == "" {
+ return nil, nil
+ }
+ u, err := url.Parse(strings.TrimRight(internalURL, "/"))
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
+ return nil, fmt.Errorf("invalid COLLAB_INTERNAL_URL %q", internalURL)
+ }
+ return &Client{baseURL: u, secret: secret, http: &http.Client{Timeout: 30 * time.Second}}, nil
+}
+
+// Secret is the shared secret, for verifying the service's calls back.
+func (c *Client) Secret() string { return c.secret }
+
+// WriteRequest is a whole-document write. BaseContent is the stored content
+// at BaseRevision, the common ancestor for the three-way merge.
+type WriteRequest struct {
+ Actor Actor `json:"actor"`
+ BaseRevision int64 `json:"base_revision,omitempty"`
+ BaseContent *string `json:"base_content,omitempty"`
+ Content *string `json:"content,omitempty"`
+ Title *string `json:"title,omitempty"`
+ Message string `json:"message,omitempty"`
+ Action string `json:"action,omitempty"`
+ ActionRef *int32 `json:"action_ref,omitempty"`
+ TaskID string `json:"task_id,omitempty"`
+}
+
+// EditRequest is a list of find-and-replace edits against the live text.
+type EditRequest struct {
+ Actor Actor `json:"actor"`
+ Edits []TextEdit `json:"edits"`
+ Message string `json:"message,omitempty"`
+ TaskID string `json:"task_id,omitempty"`
+}
+
+// MergeConflict is a block both sides changed differently.
+type MergeConflict struct {
+ Current string `json:"current"`
+ Incoming string `json:"incoming"`
+}
+
+// Result statuses.
+const (
+ StatusOK = "ok"
+ StatusConflict = "conflict"
+ StatusEditFailed = "edit_failed"
+ StatusGone = "gone"
+ // StatusTooLarge: the write would make the doc larger than the API stores.
+ // The live document is left as it was.
+ StatusTooLarge = "too_large"
+)
+
+// Result of a write or edit. Content is the live text after the write, or at
+// the time of a conflict or failed edit.
+type Result struct {
+ Status string `json:"status"`
+ Revision int64 `json:"revision"`
+ Content string `json:"content"`
+ Merged bool `json:"merged"`
+ Conflicts []MergeConflict `json:"conflicts,omitempty"`
+ Failure *EditFailure `json:"failure,omitempty"`
+}
+
+func (c *Client) Write(ctx context.Context, docID string, req WriteRequest) (Result, error) {
+ return c.call(ctx, docID, "write", req)
+}
+
+func (c *Client) Edit(ctx context.Context, docID string, req EditRequest) (Result, error) {
+ return c.call(ctx, docID, "edit", req)
+}
+
+// Flush persists pending editor changes of a loaded doc, so a read sees what
+// people have typed. Docs nobody has open return immediately.
+func (c *Client) Flush(ctx context.Context, docID string) error {
+ _, err := c.call(ctx, docID, "flush", struct{}{})
+ return err
+}
+
+func (c *Client) call(ctx context.Context, docID, op string, body any) (Result, error) {
+ raw, err := json.Marshal(body)
+ if err != nil {
+ return Result{}, err
+ }
+ endpoint := c.baseURL.JoinPath("internal", "documents", DocumentName(docID), op)
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), bytes.NewReader(raw))
+ if err != nil {
+ return Result{}, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set(SecretHeader, c.secret)
+ resp, err := c.http.Do(req)
+ if err != nil {
+ return Result{}, fmt.Errorf("%w: %v", ErrUnavailable, err)
+ }
+ defer resp.Body.Close()
+ data, _ := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
+ switch resp.StatusCode {
+ case http.StatusOK, http.StatusConflict, http.StatusRequestEntityTooLarge:
+ var result Result
+ if err := json.Unmarshal(data, &result); err != nil {
+ return Result{}, fmt.Errorf("%w: decode %s response: %v", ErrUnavailable, op, err)
+ }
+ if op == "flush" {
+ result.Status = StatusOK
+ }
+ return result, nil
+ case http.StatusNotFound:
+ return Result{Status: StatusGone}, nil
+ }
+ err = fmt.Errorf("%s returned %d: %s", op, resp.StatusCode, strings.TrimSpace(string(data)))
+ // Only a service that cannot answer is worked around by writing to the
+ // database directly. A request it refused would be refused again, and
+ // writing around a running service would leave its live copy behind.
+ if resp.StatusCode >= 500 {
+ return Result{}, fmt.Errorf("%w: %v", ErrUnavailable, err)
+ }
+ return Result{}, err
+}
+
+// Proxy forwards editor WebSockets to the service. The ticket in the first
+// message authenticates them, so the route needs no session.
+func (c *Client) Proxy() http.Handler {
+ target := *c.baseURL
+ proxy := &httputil.ReverseProxy{
+ Rewrite: func(r *httputil.ProxyRequest) {
+ r.SetURL(&target)
+ r.Out.URL.Path = "/"
+ r.Out.URL.RawPath = ""
+ // Browsers send cookies along; the service has no use for them.
+ r.Out.Header.Del("Cookie")
+ r.Out.Header.Del("Authorization")
+ },
+ ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) {
+ slog.Warn("collab proxy failed", "error", err)
+ w.WriteHeader(http.StatusBadGateway)
+ },
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
+ http.Error(w, "websocket upgrade required", http.StatusBadRequest)
+ return
+ }
+ proxy.ServeHTTP(w, r)
+ })
+}
diff --git a/server/internal/collab/collab_test.go b/server/internal/collab/collab_test.go
new file mode 100644
index 0000000000..42550796a9
--- /dev/null
+++ b/server/internal/collab/collab_test.go
@@ -0,0 +1,124 @@
+package collab
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+)
+
+func TestSignTicketMatchesCollabService(t *testing.T) {
+ // Signed by apps/collab/src/ticket.ts signTicket with the same inputs.
+ const want = "eyJkIjoiZG9jOjAxOTNhMWIyLWMzZDQtN2U1Zi04YTliLTBjMWQyZTNmNGE1YiIsInciOiJ3cy0xIiwidCI6Im1lbWJlciIsImkiOiIxMTExMTExMS0xMTExLTExMTEtMTExMS0xMTExMTExMTExMTEiLCJuIjoiQWRhIiwicm8iOmZhbHNlLCJleHAiOjQxMDI0NDQ4MDB9.4GoYej7TRhHnGZD6EdDcUlZ64JITKjEe94E_7h_okKY"
+ got := SignTicket("s3cret", Ticket{
+ Document: DocumentName("0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b"),
+ WorkspaceID: "ws-1",
+ Actor: Actor{Type: "member", ID: "11111111-1111-1111-1111-111111111111", Name: "Ada"},
+ ExpiresAt: time.Unix(4102444800, 0),
+ })
+ if got != want {
+ t.Fatalf("ticket mismatch:\n got %s\nwant %s", got, want)
+ }
+}
+
+func TestApplyTextEdits(t *testing.T) {
+ cases := []struct {
+ name string
+ text string
+ edits []TextEdit
+ want string
+ failure *EditFailure
+ }{
+ {"single", "Status: draft", []TextEdit{{OldText: "draft", NewText: "approved"}}, "Status: approved", nil},
+ {"sequential", "a b", []TextEdit{{OldText: "a", NewText: "c"}, {OldText: "c b", NewText: "done"}}, "done", nil},
+ {"replace all", "x x x", []TextEdit{{OldText: "x", NewText: "y", ReplaceAll: true}}, "y y y", nil},
+ {"not found", "abc", []TextEdit{{OldText: "zzz", NewText: "y"}}, "", &EditFailure{Reason: "not_found"}},
+ {"ambiguous", "x x", []TextEdit{{OldText: "x", NewText: "y"}}, "", &EditFailure{Reason: "ambiguous", Matches: 2}},
+ {"empty", "abc", []TextEdit{{OldText: "a", NewText: "b"}, {OldText: "", NewText: "y"}}, "", &EditFailure{Reason: "empty", Index: 1}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, failure := ApplyTextEdits(tc.text, tc.edits)
+ if (failure == nil) != (tc.failure == nil) || (failure != nil && *failure != *tc.failure) {
+ t.Fatalf("failure = %+v, want %+v", failure, tc.failure)
+ }
+ if got != tc.want {
+ t.Fatalf("text = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestNewClientDisabledWithoutSettings(t *testing.T) {
+ for _, c := range [][2]string{{"", "s"}, {"http://x", ""}, {"", ""}} {
+ client, err := NewClient(c[0], c[1])
+ if client != nil || err != nil {
+ t.Fatalf("NewClient(%q, %q) = %v, %v; want nil, nil", c[0], c[1], client, err)
+ }
+ }
+ if _, err := NewClient("ftp://x", "s"); err == nil {
+ t.Fatal("expected an error for a non-http URL")
+ }
+}
+
+func TestClientMapsServiceResponses(t *testing.T) {
+ var gotPath, gotSecret string
+ var gotBody map[string]any
+ status, body := http.StatusOK, `{"status":"ok","revision":7,"content":"x","merged":true}`
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotPath, gotSecret = r.URL.Path, r.Header.Get(SecretHeader)
+ _ = json.NewDecoder(r.Body).Decode(&gotBody)
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(body))
+ }))
+ defer srv.Close()
+ client, err := NewClient(srv.URL, "s3cret")
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+
+ content := "new"
+ result, err := client.Write(ctx, "abc", WriteRequest{Actor: Actor{Type: "agent", ID: "a"}, Content: &content})
+ if err != nil || result.Status != StatusOK || result.Revision != 7 || !result.Merged {
+ t.Fatalf("write = %+v, %v", result, err)
+ }
+ if gotPath != "/internal/documents/doc:abc/write" || gotSecret != "s3cret" || gotBody["content"] != "new" {
+ t.Fatalf("request = %s %q %v", gotPath, gotSecret, gotBody)
+ }
+
+ status, body = http.StatusConflict, `{"error":"edit_failed","status":"edit_failed","revision":3,"content":"c","failure":{"reason":"ambiguous","index":0,"matches":2}}`
+ result, err = client.Edit(ctx, "abc", EditRequest{Edits: []TextEdit{{OldText: "x", NewText: "y"}}})
+ if err != nil || result.Status != StatusEditFailed || result.Failure == nil || result.Failure.Matches != 2 {
+ t.Fatalf("edit = %+v, %v", result, err)
+ }
+
+ status, body = http.StatusNotFound, `{}`
+ if result, err = client.Write(ctx, "abc", WriteRequest{}); err != nil || result.Status != StatusGone {
+ t.Fatalf("gone = %+v, %v", result, err)
+ }
+
+ status, body = http.StatusRequestEntityTooLarge, `{"error":"content_too_large","status":"too_large","revision":3}`
+ if result, err = client.Edit(ctx, "abc", EditRequest{}); err != nil || result.Status != StatusTooLarge {
+ t.Fatalf("too large = %+v, %v", result, err)
+ }
+
+ // A refused request must not be written around the running service.
+ status, body = http.StatusBadRequest, `{"error":"bad"}`
+ if _, err = client.Write(ctx, "abc", WriteRequest{}); err == nil || errors.Is(err, ErrUnavailable) {
+ t.Fatalf("400 err = %v, want an error other than ErrUnavailable", err)
+ }
+
+ status, body = http.StatusInternalServerError, `{"error":"boom"}`
+ if _, err = client.Write(ctx, "abc", WriteRequest{}); !errors.Is(err, ErrUnavailable) {
+ t.Fatalf("500 err = %v, want ErrUnavailable", err)
+ }
+
+ srv.Close()
+ if err = client.Flush(ctx, "abc"); !errors.Is(err, ErrUnavailable) {
+ t.Fatalf("unreachable err = %v, want ErrUnavailable", err)
+ }
+}
diff --git a/server/internal/collab/edits.go b/server/internal/collab/edits.go
new file mode 100644
index 0000000000..e881d9b5e5
--- /dev/null
+++ b/server/internal/collab/edits.go
@@ -0,0 +1,44 @@
+package collab
+
+import "strings"
+
+// TextEdit replaces OldText with NewText. OldText must occur exactly once, or
+// at least once with ReplaceAll.
+type TextEdit struct {
+ OldText string `json:"old_text"`
+ NewText string `json:"new_text"`
+ ReplaceAll bool `json:"replace_all,omitempty"`
+}
+
+// EditFailure says which edit could not be applied and why: "not_found",
+// "ambiguous" (with Matches) or "empty".
+type EditFailure struct {
+ Reason string `json:"reason"`
+ Index int `json:"index"`
+ Matches int `json:"matches,omitempty"`
+}
+
+// ApplyTextEdits applies edits in order, each against the text the previous
+// ones left. It mirrors apps/collab/src/edits.ts, which applies the same
+// edits to the live document; this copy serves docs nobody has open when the
+// collaboration service is not configured.
+func ApplyTextEdits(text string, edits []TextEdit) (string, *EditFailure) {
+ for i, edit := range edits {
+ if edit.OldText == "" {
+ return "", &EditFailure{Reason: "empty", Index: i}
+ }
+ matches := strings.Count(text, edit.OldText)
+ if matches == 0 {
+ return "", &EditFailure{Reason: "not_found", Index: i}
+ }
+ if matches > 1 && !edit.ReplaceAll {
+ return "", &EditFailure{Reason: "ambiguous", Index: i, Matches: matches}
+ }
+ if edit.ReplaceAll {
+ text = strings.ReplaceAll(text, edit.OldText, edit.NewText)
+ } else {
+ text = strings.Replace(text, edit.OldText, edit.NewText, 1)
+ }
+ }
+ return text, nil
+}
diff --git a/server/internal/collab/ticket.go b/server/internal/collab/ticket.go
new file mode 100644
index 0000000000..cda5465c05
--- /dev/null
+++ b/server/internal/collab/ticket.go
@@ -0,0 +1,57 @@
+// Package collab connects the API to the live co-editing service
+// (apps/collab): it mints the tickets editors connect with, sends server-side
+// writes through the service so they merge into what people are typing, and
+// proxies editor WebSockets to it.
+package collab
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "time"
+)
+
+// Actor is who a ticket or a write speaks for.
+type Actor struct {
+ Type string `json:"type"`
+ ID string `json:"id"`
+ Name string `json:"name"`
+}
+
+// Ticket is what the API vouches for when it lets an editor connect to a
+// document. It is verified by apps/collab/src/ticket.ts.
+type Ticket struct {
+ Document string
+ WorkspaceID string
+ Actor Actor
+ ReadOnly bool
+ ExpiresAt time.Time
+}
+
+type ticketPayload struct {
+ D string `json:"d"`
+ W string `json:"w"`
+ T string `json:"t"`
+ I string `json:"i"`
+ N string `json:"n"`
+ RO bool `json:"ro"`
+ Exp int64 `json:"exp"`
+}
+
+// SignTicket returns `<base64url JSON payload>.<base64url HMAC-SHA256>`.
+func SignTicket(secret string, t Ticket) string {
+ raw, _ := json.Marshal(ticketPayload{
+ D: t.Document, W: t.WorkspaceID, T: t.Actor.Type, I: t.Actor.ID, N: t.Actor.Name,
+ RO: t.ReadOnly, Exp: t.ExpiresAt.Unix(),
+ })
+ payload := base64.RawURLEncoding.EncodeToString(raw)
+ mac := hmac.New(sha256.New, []byte(secret))
+ mac.Write([]byte(payload))
+ return payload + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
+}
+
+// DocumentName is the collaboration service's name for a doc.
+func DocumentName(docID string) string {
+ return "doc:" + docID
+}
diff --git a/server/internal/daemon/execenv/runtime_config_kind_test.go b/server/internal/daemon/execenv/runtime_config_kind_test.go
index c6bdf9b10a..ad585b2156 100644
--- a/server/internal/daemon/execenv/runtime_config_kind_test.go
+++ b/server/internal/daemon/execenv/runtime_config_kind_test.go
@@ -84,7 +84,7 @@ func TestBuildMetaSkillContentDocsFollowFlag(t *testing.T) {
for _, enabled := range []bool{false, true} {
out := buildMetaSkillContent("claude", TaskContextForEnv{IssueID: "issue-1", DocsEnabled: enabled})
- for _, line := range []string{"`multica doc list|search|get|create|update|move`", "mention://doc/<doc-id>"} {
+ for _, line := range []string{"`multica doc list|search|get|create|edit|update|move`", "mention://doc/<doc-id>"} {
if got := strings.Contains(out, line); got != enabled {
t.Errorf("DocsEnabled=%v: brief contains %q = %v\n---\n%s", enabled, line, got, out)
}
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index c88f0a561a..58ba9f10da 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -282,7 +282,7 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("- `multica issue wakeup <create|list|get|update|disable|trigger|delete|runs|events>` — persist an event, condition or time wakeup on this issue, then finish the current run. When the platform can check the fact itself, use one `--until-*` condition so no run starts before it holds; check the rule's `last_error` for missing PR links or snapshots, which are retried automatically. Conditions, PR rules and actor filters: `multica issue wakeup create --help` and the multica-platform issues reference.\n")
b.WriteString("- `multica issue children <id> [--output json]` — list a parent's sub-issues grouped by stage.\n")
if ctx.DocsEnabled {
- b.WriteString("- `multica doc list|search|get|create|update|move` — workspace docs; `doc search <query>` matches titles and content; `doc update` needs `--base-revision` from `multica doc get` (details: `multica doc --help`).\n")
+ b.WriteString("- `multica doc list|search|get|create|edit|update|move` — workspace docs; `doc search <query>` matches titles and content; people may be editing a doc live, so change part of it with `doc edit <id> --old <exact text> --new <text>`; `doc update` rewrites the whole doc and needs `--base-revision` from `multica doc get` (details: `multica doc --help`).\n")
}
b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-file <path> | --content-stdin] [--parent <comment-id>] [--attachment <path>]` — post a comment. Agent-authored bodies MUST use `--content-file` with a file inside your working directory; full flags: `multica issue comment add --help`.\n")
b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>] [--fresh]` — repository checkout on a dedicated branch; re-running it keeps a checkout that has uncommitted or unpushed work, or is already on this task's branch, and only fetches; a clean, fully pushed checkout on another branch starts over on a new branch. `--fresh` discards uncommitted and untracked files for a new branch; commits stay on the old branch, so push any you still need first.\n\n")
diff --git a/server/internal/handler/doc.go b/server/internal/handler/doc.go
index c3139deb84..bd8c7c05ea 100644
--- a/server/internal/handler/doc.go
+++ b/server/internal/handler/doc.go
@@ -87,9 +87,12 @@ type DocVersionResponse struct {
ActionRef *int32 `json:"action_ref"`
TaskID *string `json:"task_id"`
IssueID *string `json:"issue_id"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
- Content *string `json:"content,omitempty"`
+ // Contributors lists everyone whose edits the version carries. Versions
+ // saved before live co-editing have none; their author is the one.
+ Contributors []DocContributor `json:"contributors"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+ Content *string `json:"content,omitempty"`
}
func docToSummary(d db.Doc) DocSummaryResponse {
@@ -141,18 +144,19 @@ func docFolderToResponse(f db.DocFolder) DocFolderResponse {
func docVersionToResponse(v db.DocVersion, withContent bool) DocVersionResponse {
resp := DocVersionResponse{
- DocID: uuidToString(v.DocID),
- Number: v.Number,
- Title: v.Title,
- AuthorType: v.AuthorType,
- AuthorID: uuidToString(v.AuthorID),
- Message: v.Message,
- Action: v.Action,
- ActionRef: int4ToPtr(v.ActionRef),
- TaskID: uuidToPtr(v.TaskID),
- IssueID: uuidToPtr(v.IssueID),
- CreatedAt: timestampToString(v.CreatedAt),
- UpdatedAt: timestampToString(v.UpdatedAt),
+ DocID: uuidToString(v.DocID),
+ Number: v.Number,
+ Title: v.Title,
+ AuthorType: v.AuthorType,
+ AuthorID: uuidToString(v.AuthorID),
+ Message: v.Message,
+ Action: v.Action,
+ ActionRef: int4ToPtr(v.ActionRef),
+ TaskID: uuidToPtr(v.TaskID),
+ IssueID: uuidToPtr(v.IssueID),
+ Contributors: parseDocContributors(v.Contributors),
+ CreatedAt: timestampToString(v.CreatedAt),
+ UpdatedAt: timestampToString(v.UpdatedAt),
}
if withContent {
content := v.Content
@@ -163,18 +167,19 @@ func docVersionToResponse(v db.DocVersion, withContent bool) DocVersionResponse
func docVersionRowToResponse(v db.ListDocVersionsRow) DocVersionResponse {
return DocVersionResponse{
- DocID: uuidToString(v.DocID),
- Number: v.Number,
- Title: v.Title,
- AuthorType: v.AuthorType,
- AuthorID: uuidToString(v.AuthorID),
- Message: v.Message,
- Action: v.Action,
- ActionRef: int4ToPtr(v.ActionRef),
- TaskID: uuidToPtr(v.TaskID),
- IssueID: uuidToPtr(v.IssueID),
- CreatedAt: timestampToString(v.CreatedAt),
- UpdatedAt: timestampToString(v.UpdatedAt),
+ DocID: uuidToString(v.DocID),
+ Number: v.Number,
+ Title: v.Title,
+ AuthorType: v.AuthorType,
+ AuthorID: uuidToString(v.AuthorID),
+ Message: v.Message,
+ Action: v.Action,
+ ActionRef: int4ToPtr(v.ActionRef),
+ TaskID: uuidToPtr(v.TaskID),
+ IssueID: uuidToPtr(v.IssueID),
+ Contributors: parseDocContributors(v.Contributors),
+ CreatedAt: timestampToString(v.CreatedAt),
+ UpdatedAt: timestampToString(v.UpdatedAt),
}
}
@@ -303,7 +308,7 @@ func (h *Handler) ListDocTree(w http.ResponseWriter, r *http.Request) {
}
func (h *Handler) GetDoc(w http.ResponseWriter, r *http.Request) {
- _, wsUUID, _, ok := h.docWorkspace(w, r)
+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)
if !ok {
return
}
@@ -311,6 +316,17 @@ func (h *Handler) GetDoc(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // Agents and the CLI read what people have typed so far. Editors in the
+ // app already see it live, and refetch on every save.
+ if h.Collab != nil {
+ actorType, _ := h.resolveActor(r, userID, workspaceID)
+ if actorType == "agent" || r.URL.Query().Get("flush") == "true" {
+ h.flushDocCollab(r.Context(), doc.ID)
+ if doc, ok = h.loadDoc(w, r, wsUUID); !ok {
+ return
+ }
+ }
+ }
writeJSON(w, http.StatusOK, DocResponse{DocSummaryResponse: docToSummary(doc), Content: doc.Content})
}
@@ -372,21 +388,26 @@ func (h *Handler) CreateDoc(w http.ResponseWriter, r *http.Request) {
return
}
if _, err := qtx.InsertDocVersion(ctx, db.InsertDocVersionParams{
- DocID: doc.ID,
- WorkspaceID: wsUUID,
- Number: 1,
- Title: doc.Title,
- Content: doc.Content,
- AuthorType: actorType,
- AuthorID: parseUUID(actorID),
- Message: req.Message,
- Action: "create",
- TaskID: taskID,
- IssueID: issueID,
+ DocID: doc.ID,
+ WorkspaceID: wsUUID,
+ Number: 1,
+ Title: doc.Title,
+ Content: doc.Content,
+ AuthorType: actorType,
+ AuthorID: parseUUID(actorID),
+ Message: req.Message,
+ Action: "create",
+ TaskID: taskID,
+ IssueID: issueID,
+ Contributors: docContributorsJSON([]DocContributor{{Type: actorType, ID: actorID}}),
}); err != nil {
writeError(w, http.StatusInternalServerError, "failed to create doc")
return
}
+ if err := recordDocRevision(ctx, qtx, doc); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to create doc")
+ return
+ }
if err := tx.Commit(ctx); err != nil {
writeError(w, http.StatusInternalServerError, "failed to create doc")
return
@@ -459,6 +480,12 @@ func (h *Handler) UpdateDoc(w http.ResponseWriter, r *http.Request) {
taskID, issueID := h.docTaskContext(r, actorType)
ctx := r.Context()
+ if h.Collab != nil {
+ actor := h.collabActor(ctx, actorType, actorID)
+ if h.updateDocViaCollab(w, r, wsUUID, docUUID, req, actor, taskID) {
+ return
+ }
+ }
tx, err := h.TxStarter.Begin(ctx)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to update doc")
@@ -507,42 +534,10 @@ func (h *Handler) UpdateDoc(w http.ResponseWriter, r *http.Request) {
}
// Autosave writes every pause; keep one snapshot per editing stretch
// instead of one per pause.
- merged := false
- if req.Action == "edit" && req.Message == "" {
- rows, err := qtx.MergeDocEditIntoVersion(ctx, db.MergeDocEditIntoVersionParams{
- Title: title, Content: content, DocID: doc.ID, Number: doc.VersionCount,
- AuthorType: actorType, AuthorID: parseUUID(actorID), TaskID: taskID,
- })
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to save version")
- return
- }
- merged = rows == 1
- }
- number := doc.VersionCount
- if !merged {
- number++
- var actionRef pgtype.Int4
- if req.Action == "restore" {
- actionRef = pgtype.Int4{Int32: *req.ActionRef, Valid: true}
- }
- if _, err := qtx.InsertDocVersion(ctx, db.InsertDocVersionParams{
- DocID: doc.ID, WorkspaceID: wsUUID, Number: number, Title: title, Content: content,
- AuthorType: actorType, AuthorID: parseUUID(actorID), Message: req.Message,
- Action: req.Action, ActionRef: actionRef, TaskID: taskID, IssueID: issueID,
- }); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to save version")
- return
- }
- }
- updated, err := qtx.UpdateDocContent(ctx, db.UpdateDocContentParams{
- Title: title,
- Content: content,
- VersionCount: number,
- UpdatedByType: actorType,
- UpdatedByID: parseUUID(actorID),
- ID: doc.ID,
- WorkspaceID: wsUUID,
+ updated, number, err := commitDocWrite(ctx, qtx, doc, docWrite{
+ title: title, content: content, actorType: actorType, actorID: actorID,
+ message: req.Message, action: req.Action, actionRef: req.ActionRef,
+ taskID: taskID, issueID: issueID,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to update doc")
diff --git a/server/internal/handler/doc_collab.go b/server/internal/handler/doc_collab.go
new file mode 100644
index 0000000000..5243042990
--- /dev/null
+++ b/server/internal/handler/doc_collab.go
@@ -0,0 +1,623 @@
+package handler
+
+import (
+ "context"
+ "crypto/subtle"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/collab"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+const (
+ docCollabTicketTTL = 5 * time.Minute
+ docCollabFlushTimeout = 2 * time.Second
+ docCollabBodyMaxBytes = 16 << 20
+ docEditsMax = 100
+ // Live editing saves every 5 to 30 seconds while someone types, each save
+ // a full copy of the doc. A writer whose base is more than this many
+ // revisions old gets a revision conflict instead of a merge.
+ docRevisionsKept = 50
+)
+
+// DocContributor is someone whose edits a version carries.
+type DocContributor struct {
+ Type string `json:"type"`
+ ID string `json:"id"`
+}
+
+func docContributorsJSON(contributors []DocContributor) []byte {
+ if len(contributors) == 0 {
+ return []byte("[]")
+ }
+ raw, _ := json.Marshal(contributors)
+ return raw
+}
+
+func parseDocContributors(raw []byte) []DocContributor {
+ contributors := []DocContributor{}
+ if len(raw) > 0 {
+ _ = json.Unmarshal(raw, &contributors)
+ }
+ return contributors
+}
+
+// docWrite is one change to a doc's title or content, committed by
+// commitDocWrite inside the caller's transaction.
+type docWrite struct {
+ title, content string
+ actorType, actorID string
+ contributors []DocContributor
+ message, action string
+ actionRef *int32
+ taskID, issueID pgtype.UUID
+}
+
+// commitDocWrite snapshots a write into the version history and updates the
+// doc. Unlabeled edits fold into the latest snapshot while the same editing
+// stretch lasts: the same author and task, or, for people co-editing live,
+// any member, with everyone added as a contributor.
+func commitDocWrite(ctx context.Context, qtx *db.Queries, doc db.Doc, wr docWrite) (db.Doc, int32, error) {
+ if len(wr.contributors) == 0 {
+ wr.contributors = []DocContributor{{Type: wr.actorType, ID: wr.actorID}}
+ }
+ merged := false
+ if wr.action == "edit" && wr.message == "" {
+ var rows int64
+ var err error
+ if wr.actorType == "member" && !wr.taskID.Valid {
+ rows, err = qtx.MergeCollabEditIntoVersion(ctx, db.MergeCollabEditIntoVersionParams{
+ Title: wr.title, Content: wr.content, Contributors: docContributorsJSON(wr.contributors),
+ DocID: doc.ID, Number: doc.VersionCount,
+ })
+ } else {
+ rows, err = qtx.MergeDocEditIntoVersion(ctx, db.MergeDocEditIntoVersionParams{
+ Title: wr.title, Content: wr.content, DocID: doc.ID, Number: doc.VersionCount,
+ AuthorType: wr.actorType, AuthorID: parseUUID(wr.actorID), TaskID: wr.taskID,
+ })
+ }
+ if err != nil {
+ return db.Doc{}, 0, err
+ }
+ merged = rows == 1
+ }
+ number := doc.VersionCount
+ if !merged {
+ number++
+ var actionRef pgtype.Int4
+ if wr.action == "restore" && wr.actionRef != nil {
+ actionRef = pgtype.Int4{Int32: *wr.actionRef, Valid: true}
+ }
+ if _, err := qtx.InsertDocVersion(ctx, db.InsertDocVersionParams{
+ DocID: doc.ID, WorkspaceID: doc.WorkspaceID, Number: number, Title: wr.title, Content: wr.content,
+ AuthorType: wr.actorType, AuthorID: parseUUID(wr.actorID), Message: wr.message,
+ Action: wr.action, ActionRef: actionRef, TaskID: wr.taskID, IssueID: wr.issueID,
+ Contributors: docContributorsJSON(wr.contributors),
+ }); err != nil {
+ return db.Doc{}, 0, err
+ }
+ }
+ updated, err := qtx.UpdateDocContent(ctx, db.UpdateDocContentParams{
+ Title: wr.title, Content: wr.content, VersionCount: number,
+ UpdatedByType: wr.actorType, UpdatedByID: parseUUID(wr.actorID),
+ ID: doc.ID, WorkspaceID: doc.WorkspaceID,
+ })
+ if err != nil {
+ return db.Doc{}, 0, err
+ }
+ if err := recordDocRevision(ctx, qtx, updated); err != nil {
+ return db.Doc{}, 0, err
+ }
+ return updated, number, nil
+}
+
+// recordDocRevision keeps the content of recent revisions, the merge base for
+// a write that started from one of them.
+func recordDocRevision(ctx context.Context, qtx *db.Queries, doc db.Doc) error {
+ if err := qtx.InsertDocRevision(ctx, db.InsertDocRevisionParams{DocID: doc.ID, Revision: doc.Revision, Content: doc.Content}); err != nil {
+ return err
+ }
+ return qtx.PruneDocRevisions(ctx, db.PruneDocRevisionsParams{DocID: doc.ID, KeepFrom: doc.Revision - docRevisionsKept})
+}
+
+func (h *Handler) collabActor(ctx context.Context, actorType, actorID string) collab.Actor {
+ actor := collab.Actor{Type: actorType, ID: actorID}
+ switch actorType {
+ case "agent":
+ if agent, err := h.Queries.GetAgent(ctx, parseUUID(actorID)); err == nil {
+ actor.Name = agent.Name
+ }
+ case "member":
+ if user, err := h.Queries.GetUser(ctx, parseUUID(actorID)); err == nil {
+ actor.Name = user.Name
+ }
+ }
+ return actor
+}
+
+// flushDocCollab persists what people have typed into a doc that is open for
+// live editing, so a read returns it. Best effort: a slow or absent service
+// leaves the last save in place.
+func (h *Handler) flushDocCollab(ctx context.Context, docID pgtype.UUID) {
+ if h.Collab == nil {
+ return
+ }
+ ctx, cancel := context.WithTimeout(ctx, docCollabFlushTimeout)
+ defer cancel()
+ if err := h.Collab.Flush(ctx, uuidToString(docID)); err != nil {
+ slog.Warn("doc collab flush failed", "doc_id", uuidToString(docID), "error", err)
+ }
+}
+
+type DocCollabTicketResponse struct {
+ Enabled bool `json:"enabled"`
+ Token string `json:"token,omitempty"`
+ Document string `json:"document,omitempty"`
+ ExpiresAt string `json:"expires_at,omitempty"`
+}
+
+// CreateDocCollabTicket lets an editor join a doc's live session. Editors ask
+// again on every reconnect, so tickets are short-lived.
+func (h *Handler) CreateDocCollabTicket(w http.ResponseWriter, r *http.Request) {
+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)
+ if !ok {
+ return
+ }
+ doc, ok := h.loadDoc(w, r, wsUUID)
+ if !ok {
+ return
+ }
+ if h.Collab == nil {
+ writeJSON(w, http.StatusOK, DocCollabTicketResponse{Enabled: false})
+ return
+ }
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ expires := time.Now().Add(docCollabTicketTTL)
+ document := collab.DocumentName(uuidToString(doc.ID))
+ token := collab.SignTicket(h.Collab.Secret(), collab.Ticket{
+ Document: document,
+ WorkspaceID: workspaceID,
+ Actor: h.collabActor(r.Context(), actorType, actorID),
+ ExpiresAt: expires,
+ })
+ writeJSON(w, http.StatusOK, DocCollabTicketResponse{
+ Enabled: true, Token: token, Document: document, ExpiresAt: expires.UTC().Format(time.RFC3339),
+ })
+}
+
+type DocWriteResponse struct {
+ DocResponse
+ // Merged is true when the write was based on an older revision and was
+ // merged with the changes made since.
+ Merged bool `json:"merged"`
+}
+
+func writeDocMergeConflict(w http.ResponseWriter, result collab.Result) {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "the change overlaps edits made since its base revision",
+ "code": "doc_merge_conflict",
+ "conflicts": result.Conflicts,
+ "actual_revision": result.Revision,
+ "content": result.Content,
+ })
+}
+
+func writeDocEditFailed(w http.ResponseWriter, failure *collab.EditFailure, revision int64, content string) {
+ msg := "old_text was not found in the doc"
+ switch failure.Reason {
+ case "ambiguous":
+ msg = "old_text matches more than once; quote more context or set replace_all"
+ case "empty":
+ msg = "old_text must not be empty"
+ }
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": msg,
+ "code": "doc_edit_failed",
+ "failure": failure,
+ "actual_revision": revision,
+ "content": content,
+ })
+}
+
+// updateDocViaCollab sends a write through the live session, so it merges
+// into what people are typing instead of overwriting it. It reports false
+// when the service is unreachable and the caller should write directly.
+func (h *Handler) updateDocViaCollab(w http.ResponseWriter, r *http.Request, wsUUID pgtype.UUID, docUUID pgtype.UUID, req UpdateDocRequest, actor collab.Actor, taskID pgtype.UUID) bool {
+ ctx := r.Context()
+ doc, err := h.Queries.GetDoc(ctx, db.GetDocParams{ID: docUUID, WorkspaceID: wsUUID})
+ if err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusNotFound, "doc not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to update doc")
+ }
+ return true
+ }
+ write := collab.WriteRequest{
+ Actor: actor, Message: req.Message, Action: req.Action, ActionRef: req.ActionRef,
+ }
+ if taskID.Valid {
+ write.TaskID = uuidToString(taskID)
+ }
+ switch {
+ case req.Action == "restore":
+ source, err := h.Queries.GetDocVersion(ctx, db.GetDocVersionParams{DocID: doc.ID, Number: *req.ActionRef})
+ if err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusBadRequest, "version not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to update doc")
+ }
+ return true
+ }
+ write.Title, write.Content = &source.Title, &source.Content
+ case req.Content != nil:
+ // The content the writer started from is the merge base.
+ var base string
+ if req.BaseRevision == doc.Revision {
+ base = doc.Content
+ } else if req.BaseRevision < doc.Revision {
+ base, err = h.Queries.GetDocRevisionContent(ctx, db.GetDocRevisionContentParams{DocID: doc.ID, Revision: req.BaseRevision})
+ if err != nil {
+ if isNotFound(err) {
+ writeRevisionConflict(w, "doc", doc.ID, req.BaseRevision, doc.Revision)
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to update doc")
+ }
+ return true
+ }
+ } else {
+ writeRevisionConflict(w, "doc", doc.ID, req.BaseRevision, doc.Revision)
+ return true
+ }
+ write.BaseRevision, write.BaseContent, write.Content, write.Title = req.BaseRevision, &base, req.Content, req.Title
+ default:
+ // Title only: last write wins, the content is untouched.
+ write.Title = req.Title
+ }
+
+ result, err := h.Collab.Write(ctx, uuidToString(doc.ID), write)
+ if err != nil {
+ if errors.Is(err, collab.ErrUnavailable) {
+ slog.Warn("doc collab write failed; writing directly", "doc_id", uuidToString(doc.ID), "error", err)
+ return false
+ }
+ writeError(w, http.StatusInternalServerError, "failed to update doc")
+ return true
+ }
+ h.writeCollabResult(w, r, wsUUID, doc.ID, result)
+ return true
+}
+
+func (h *Handler) writeCollabResult(w http.ResponseWriter, r *http.Request, wsUUID, docID pgtype.UUID, result collab.Result) {
+ switch result.Status {
+ case collab.StatusOK:
+ updated, err := h.Queries.GetDoc(r.Context(), db.GetDocParams{ID: docID, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load doc")
+ return
+ }
+ writeJSON(w, http.StatusOK, DocWriteResponse{
+ DocResponse: DocResponse{DocSummaryResponse: docToSummary(updated), Content: updated.Content},
+ Merged: result.Merged,
+ })
+ case collab.StatusConflict:
+ writeDocMergeConflict(w, result)
+ case collab.StatusEditFailed:
+ failure := result.Failure
+ if failure == nil {
+ failure = &collab.EditFailure{Reason: "not_found"}
+ }
+ writeDocEditFailed(w, failure, result.Revision, result.Content)
+ case collab.StatusGone:
+ writeError(w, http.StatusNotFound, "doc not found")
+ case collab.StatusTooLarge:
+ writeError(w, http.StatusRequestEntityTooLarge, "content must be at most 2 MB")
+ default:
+ writeError(w, http.StatusInternalServerError, "failed to update doc")
+ }
+}
+
+type EditDocRequest struct {
+ Edits []collab.TextEdit `json:"edits"`
+ Message string `json:"message"`
+}
+
+// EditDoc applies find-and-replace edits. Each edit quotes the text it
+// changes, so it lands wherever that text now is, even while others are
+// editing, and fails only when someone changed that very text.
+func (h *Handler) EditDoc(w http.ResponseWriter, r *http.Request) {
+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)
+ if !ok {
+ return
+ }
+ docUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "doc id")
+ if !ok {
+ return
+ }
+ var req EditDocRequest
+ r.Body = http.MaxBytesReader(w, r.Body, docBodyMaxBytes)
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if len(req.Edits) == 0 || len(req.Edits) > docEditsMax {
+ writeError(w, http.StatusBadRequest, "edits must contain between 1 and 100 edits")
+ return
+ }
+ for i := range req.Edits {
+ req.Edits[i].OldText = sanitizeNullBytes(req.Edits[i].OldText)
+ req.Edits[i].NewText = sanitizeNullBytes(req.Edits[i].NewText)
+ if !utf8.ValidString(req.Edits[i].OldText) || !utf8.ValidString(req.Edits[i].NewText) {
+ writeError(w, http.StatusBadRequest, "edits must be valid UTF-8")
+ return
+ }
+ }
+ req.Message = sanitizeNullBytes(req.Message)
+ if !validateDocMessage(w, req.Message) {
+ return
+ }
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ taskID, issueID := h.docTaskContext(r, actorType)
+
+ ctx := r.Context()
+ if h.Collab != nil {
+ if _, err := h.Queries.GetDoc(ctx, db.GetDocParams{ID: docUUID, WorkspaceID: wsUUID}); err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusNotFound, "doc not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to edit doc")
+ }
+ return
+ }
+ edit := collab.EditRequest{Actor: h.collabActor(ctx, actorType, actorID), Edits: req.Edits, Message: req.Message}
+ if taskID.Valid {
+ edit.TaskID = uuidToString(taskID)
+ }
+ result, err := h.Collab.Edit(ctx, uuidToString(docUUID), edit)
+ if err == nil {
+ h.writeCollabResult(w, r, wsUUID, docUUID, result)
+ return
+ }
+ if !errors.Is(err, collab.ErrUnavailable) {
+ writeError(w, http.StatusInternalServerError, "failed to edit doc")
+ return
+ }
+ slog.Warn("doc collab edit failed; editing directly", "doc_id", uuidToString(docUUID), "error", err)
+ }
+
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to edit doc")
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ doc, err := qtx.GetDocForUpdate(ctx, db.GetDocForUpdateParams{ID: docUUID, WorkspaceID: wsUUID})
+ if err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusNotFound, "doc not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to edit doc")
+ }
+ return
+ }
+ content, failure := collab.ApplyTextEdits(doc.Content, req.Edits)
+ if failure != nil {
+ writeDocEditFailed(w, failure, doc.Revision, doc.Content)
+ return
+ }
+ if !validateDocContent(w, content) {
+ return
+ }
+ if content == doc.Content {
+ writeJSON(w, http.StatusOK, DocWriteResponse{DocResponse: DocResponse{DocSummaryResponse: docToSummary(doc), Content: doc.Content}})
+ return
+ }
+ updated, number, err := commitDocWrite(ctx, qtx, doc, docWrite{
+ title: doc.Title, content: content, actorType: actorType, actorID: actorID,
+ message: req.Message, action: "edit", taskID: taskID, issueID: issueID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to edit doc")
+ return
+ }
+ if err := tx.Commit(ctx); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to edit doc")
+ return
+ }
+ h.publish(protocol.EventDocUpdated, workspaceID, actorType, actorID, map[string]any{
+ "doc": docToSummary(updated), "version": number,
+ })
+ writeJSON(w, http.StatusOK, DocWriteResponse{DocResponse: DocResponse{DocSummaryResponse: docToSummary(updated), Content: updated.Content}})
+}
+
+// --- Internal endpoints called by the collaboration service ---
+
+// RequireCollabSecret admits only the collaboration service.
+func (h *Handler) RequireCollabSecret(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ given := r.Header.Get(collab.SecretHeader)
+ if h.Collab == nil || subtle.ConstantTimeCompare([]byte(given), []byte(h.Collab.Secret())) != 1 {
+ writeError(w, http.StatusUnauthorized, "unauthorized")
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+type collabDocResponse struct {
+ WorkspaceID string `json:"workspace_id"`
+ Title string `json:"title"`
+ Content string `json:"content"`
+ Revision int64 `json:"revision"`
+ YState *string `json:"ystate"`
+ YStateRevision *int64 `json:"ystate_revision"`
+}
+
+func (h *Handler) GetCollabDoc(w http.ResponseWriter, r *http.Request) {
+ docUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "doc id")
+ if !ok {
+ return
+ }
+ row, err := h.Queries.GetDocForCollab(r.Context(), docUUID)
+ if err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusNotFound, "doc not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to load doc")
+ }
+ return
+ }
+ resp := collabDocResponse{
+ WorkspaceID: uuidToString(row.WorkspaceID), Title: row.Title, Content: row.Content, Revision: row.Revision,
+ }
+ if row.Ystate != nil && row.YstateRevision.Valid {
+ state := base64.StdEncoding.EncodeToString(row.Ystate)
+ resp.YState, resp.YStateRevision = &state, &row.YstateRevision.Int64
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
+
+type collabStoreRequest struct {
+ BaseRevision int64 `json:"base_revision"`
+ Content string `json:"content"`
+ YState string `json:"ystate"`
+ Contributors []DocContributor `json:"contributors"`
+ Title *string `json:"title"`
+ Message string `json:"message"`
+ Action string `json:"action"`
+ ActionRef *int32 `json:"action_ref"`
+ TaskID string `json:"task_id"`
+ // StateOnly saves the Yjs state for the current revision and leaves the
+ // doc itself untouched.
+ StateOnly bool `json:"state_only"`
+}
+
+// StoreCollabDoc saves the live document: a version crediting everyone whose
+// edits it carries, the new content, and the Yjs state behind it.
+func (h *Handler) StoreCollabDoc(w http.ResponseWriter, r *http.Request) {
+ docUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "doc id")
+ if !ok {
+ return
+ }
+ var req collabStoreRequest
+ r.Body = http.MaxBytesReader(w, r.Body, docCollabBodyMaxBytes)
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ req.Content = sanitizeNullBytes(req.Content)
+ req.Message = sanitizeNullBytes(req.Message)
+ if !validateDocContent(w, req.Content) || !validateDocMessage(w, req.Message) {
+ return
+ }
+ if req.Title != nil {
+ title := strings.TrimSpace(sanitizeNullBytes(*req.Title))
+ if !validateDocTitle(w, title) {
+ return
+ }
+ req.Title = &title
+ }
+ if req.Action == "" {
+ req.Action = "edit"
+ }
+ if !contains(validDocActions, req.Action) || (req.Action == "restore" && (req.ActionRef == nil || *req.ActionRef <= 0)) {
+ writeError(w, http.StatusBadRequest, "invalid action")
+ return
+ }
+ ystate, err := base64.StdEncoding.DecodeString(req.YState)
+ if err != nil || len(ystate) == 0 {
+ writeError(w, http.StatusBadRequest, "ystate must be base64")
+ return
+ }
+ contributors := make([]DocContributor, 0, len(req.Contributors))
+ for _, c := range req.Contributors {
+ if _, err := util.ParseUUID(c.ID); err != nil || (c.Type != "member" && c.Type != "agent") {
+ writeError(w, http.StatusBadRequest, "invalid contributor")
+ return
+ }
+ contributors = append(contributors, c)
+ }
+
+ ctx := r.Context()
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to store doc")
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ doc, err := qtx.GetDocByIDForUpdate(ctx, docUUID)
+ if err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusNotFound, "doc not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to store doc")
+ }
+ return
+ }
+ if doc.Revision != req.BaseRevision {
+ writeJSON(w, http.StatusConflict, map[string]any{"revision": doc.Revision, "content": doc.Content})
+ return
+ }
+ title := doc.Title
+ if req.Title != nil {
+ title = *req.Title
+ }
+
+ updated, number := doc, int32(0)
+ actorType, actorID := doc.UpdatedByType, uuidToString(doc.UpdatedByID)
+ if len(contributors) > 0 {
+ actorType, actorID = contributors[0].Type, contributors[0].ID
+ }
+ changed := !req.StateOnly && (req.Action != "edit" || req.Message != "" || title != doc.Title || req.Content != doc.Content)
+ if changed {
+ var taskID, issueID pgtype.UUID
+ if actorType == "agent" {
+ if parsed, err := util.ParseUUID(req.TaskID); err == nil {
+ taskID = parsed
+ if task, err := qtx.GetAgentTask(ctx, parsed); err == nil {
+ issueID = task.IssueID
+ }
+ }
+ }
+ updated, number, err = commitDocWrite(ctx, qtx, doc, docWrite{
+ title: title, content: req.Content, actorType: actorType, actorID: actorID,
+ contributors: contributors, message: req.Message, action: req.Action, actionRef: req.ActionRef,
+ taskID: taskID, issueID: issueID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to store doc")
+ return
+ }
+ }
+ if err := qtx.UpsertDocCollabState(ctx, db.UpsertDocCollabStateParams{
+ DocID: updated.ID, WorkspaceID: updated.WorkspaceID, Ystate: ystate, Revision: updated.Revision,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to store doc")
+ return
+ }
+ if err := tx.Commit(ctx); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to store doc")
+ return
+ }
+ if changed {
+ h.publish(protocol.EventDocUpdated, uuidToString(updated.WorkspaceID), actorType, actorID, map[string]any{
+ "doc": docToSummary(updated), "version": number,
+ })
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"revision": updated.Revision, "title": updated.Title})
+}
diff --git a/server/internal/handler/doc_collab_test.go b/server/internal/handler/doc_collab_test.go
new file mode 100644
index 0000000000..82d11f43a6
--- /dev/null
+++ b/server/internal/handler/doc_collab_test.go
@@ -0,0 +1,173 @@
+package handler
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/collab"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func useCollab(t *testing.T, url string) {
+ t.Helper()
+ client, err := collab.NewClient(url, "test-collab-secret")
+ if err != nil {
+ t.Fatal(err)
+ }
+ previous := testHandler.Collab
+ testHandler.Collab = client
+ t.Cleanup(func() { testHandler.Collab = previous })
+}
+
+func docHistory(t *testing.T, docID string) []DocVersionResponse {
+ t.Helper()
+ var history struct {
+ Versions []DocVersionResponse `json:"versions"`
+ }
+ testutil.Call(t, testHandler.ListDocVersions, withURLParam(newRequest("GET", "/api/docs/versions", nil), "id", docID)).Want(http.StatusOK).JSON(&history)
+ return history.Versions
+}
+
+func TestEditDocWithoutCollabService(t *testing.T) {
+ doc := createDocForTest(t)
+ edit := func(edits ...collab.TextEdit) *http.Request {
+ return withURLParam(newRequest("POST", "/api/docs/"+doc.ID+"/edits", map[string]any{"edits": edits, "message": "fix"}), "id", doc.ID)
+ }
+ var updated DocWriteResponse
+ testutil.Call(t, testHandler.EditDoc, edit(collab.TextEdit{OldText: "Original", NewText: "Edited"})).Want(http.StatusOK).JSON(&updated)
+ if updated.Content != "# First\n\nEdited" || updated.Revision != 2 {
+ t.Fatalf("edit not applied: %+v", updated)
+ }
+ var failed map[string]any
+ testutil.Call(t, testHandler.EditDoc, edit(collab.TextEdit{OldText: "Original", NewText: "x"})).Want(http.StatusConflict).JSON(&failed)
+ if failed["code"] != "doc_edit_failed" || failed["content"] != "# First\n\nEdited" {
+ t.Fatalf("stale quote must fail with the current text: %v", failed)
+ }
+ testutil.Call(t, testHandler.EditDoc, edit()).Want(http.StatusBadRequest)
+
+ versions := docHistory(t, doc.ID)
+ if len(versions) != 2 || versions[0].Message != "fix" || len(versions[0].Contributors) != 1 || versions[0].Contributors[0].ID != testUserID {
+ t.Fatalf("edit must be its own credited version: %+v", versions)
+ }
+}
+
+func TestStoreCollabDocCreditsEveryoneAndFoldsTheSession(t *testing.T) {
+ doc := createDocForTest(t)
+ const bob = "00000000-0000-4000-8000-0000000000b0"
+ state := base64.StdEncoding.EncodeToString([]byte{1, 2, 3})
+ store := func(body map[string]any) *http.Request {
+ body["ystate"] = state
+ return withURLParam(newRequest("POST", "/internal/collab/docs/"+doc.ID+"/store", body), "id", doc.ID)
+ }
+ var stored struct {
+ Revision int64 `json:"revision"`
+ }
+ testutil.Call(t, testHandler.StoreCollabDoc, store(map[string]any{
+ "base_revision": 1, "content": "Together",
+ "contributors": []DocContributor{{Type: "member", ID: testUserID}, {Type: "member", ID: bob}},
+ })).Want(http.StatusOK).JSON(&stored)
+ testutil.Call(t, testHandler.StoreCollabDoc, store(map[string]any{
+ "base_revision": stored.Revision, "content": "Together again",
+ "contributors": []DocContributor{{Type: "member", ID: bob}},
+ })).Want(http.StatusOK).JSON(&stored)
+
+ versions := docHistory(t, doc.ID)
+ if len(versions) != 2 || len(versions[0].Contributors) != 2 {
+ t.Fatalf("a co-editing session must fold into one version crediting both: %+v", versions)
+ }
+
+ // An agent's write stands alone.
+ agentID := "00000000-0000-4000-8000-0000000000a1"
+ testutil.Call(t, testHandler.StoreCollabDoc, store(map[string]any{
+ "base_revision": stored.Revision, "content": "Together again, agent",
+ "contributors": []DocContributor{{Type: "agent", ID: agentID}}, "message": "polish",
+ })).Want(http.StatusOK).JSON(&stored)
+ versions = docHistory(t, doc.ID)
+ if len(versions) != 3 || versions[0].AuthorType != "agent" || versions[0].Message != "polish" {
+ t.Fatalf("agent write must be its own version: %+v", versions)
+ }
+
+ var conflict struct {
+ Revision int64 `json:"revision"`
+ Content string `json:"content"`
+ }
+ testutil.Call(t, testHandler.StoreCollabDoc, store(map[string]any{
+ "base_revision": 1, "content": "stale", "contributors": []DocContributor{},
+ })).Want(http.StatusConflict).JSON(&conflict)
+ if conflict.Revision != stored.Revision || conflict.Content != "Together again, agent" {
+ t.Fatalf("stale store must report the stored doc: %+v", conflict)
+ }
+
+ var loaded collabDocResponse
+ testutil.Call(t, testHandler.GetCollabDoc, withURLParam(newRequest("GET", "/internal/collab/docs/"+doc.ID, nil), "id", doc.ID)).Want(http.StatusOK).JSON(&loaded)
+ if loaded.YState == nil || *loaded.YState != state || loaded.YStateRevision == nil || *loaded.YStateRevision != stored.Revision {
+ t.Fatalf("saved state must come back with its revision: %+v", loaded)
+ }
+
+ // A state-only store saves the Yjs state and leaves the doc alone.
+ caughtUp := base64.StdEncoding.EncodeToString([]byte{4, 5, 6})
+ var same struct {
+ Revision int64 `json:"revision"`
+ }
+ testutil.Call(t, testHandler.StoreCollabDoc, withURLParam(newRequest("POST", "/internal/collab/docs/"+doc.ID+"/store", map[string]any{
+ "base_revision": stored.Revision, "content": "ignored", "ystate": caughtUp,
+ "contributors": []DocContributor{}, "state_only": true,
+ }), "id", doc.ID)).Want(http.StatusOK).JSON(&same)
+ testutil.Call(t, testHandler.GetCollabDoc, withURLParam(newRequest("GET", "/internal/collab/docs/"+doc.ID, nil), "id", doc.ID)).Want(http.StatusOK).JSON(&loaded)
+ if same.Revision != stored.Revision || loaded.Content != "Together again, agent" || *loaded.YState != caughtUp || len(docHistory(t, doc.ID)) != 3 {
+ t.Fatalf("state-only store must not touch the doc: revision %d, %+v", same.Revision, loaded)
+ }
+}
+
+func TestUpdateDocGoesThroughCollabWithItsMergeBase(t *testing.T) {
+ doc := createDocForTest(t)
+ // Revision 2 is someone else's edit; the writer still holds revision 1.
+ testutil.Call(t, testHandler.UpdateDoc, withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, map[string]any{"base_revision": 1, "content": "# First\n\nTheirs"}), "id", doc.ID)).Want(http.StatusOK)
+
+ var got collab.WriteRequest
+ service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/internal/documents/doc:"+doc.ID+"/flush" {
+ _, _ = w.Write([]byte(`{"loaded":false}`))
+ return
+ }
+ _ = json.NewDecoder(r.Body).Decode(&got)
+ w.WriteHeader(http.StatusConflict)
+ _, _ = w.Write([]byte(`{"error":"merge_conflict","status":"conflict","revision":2,"content":"# First\n\nTheirs","conflicts":[{"current":"Theirs","incoming":"Mine"}]}`))
+ }))
+ defer service.Close()
+ useCollab(t, service.URL)
+
+ var conflict map[string]any
+ testutil.Call(t, testHandler.UpdateDoc, withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, map[string]any{"base_revision": 1, "content": "# First\n\nMine"}), "id", doc.ID)).Want(http.StatusConflict).JSON(&conflict)
+ if got.BaseContent == nil || *got.BaseContent != doc.Content || got.BaseRevision != 1 || got.Actor.ID != testUserID {
+ t.Fatalf("write must carry the content at its base revision: %+v", got)
+ }
+ if conflict["code"] != "doc_merge_conflict" {
+ t.Fatalf("unexpected response: %v", conflict)
+ }
+
+ // A base older than the kept revisions cannot be merged.
+ testutil.Call(t, testHandler.UpdateDoc, withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, map[string]any{"base_revision": 9, "content": "x"}), "id", doc.ID)).Want(http.StatusConflict)
+}
+
+func TestDocWritesFallBackWhenCollabIsDown(t *testing.T) {
+ doc := createDocForTest(t)
+ service := httptest.NewServer(http.NotFoundHandler())
+ url := service.URL
+ service.Close()
+ useCollab(t, url)
+
+ var updated DocWriteResponse
+ testutil.Call(t, testHandler.UpdateDoc, withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, map[string]any{"base_revision": 1, "content": "Direct"}), "id", doc.ID)).Want(http.StatusOK).JSON(&updated)
+ if updated.Content != "Direct" {
+ t.Fatalf("write must land directly: %+v", updated)
+ }
+ testutil.Call(t, testHandler.EditDoc, withURLParam(newRequest("POST", "/api/docs/"+doc.ID+"/edits", map[string]any{"edits": []collab.TextEdit{{OldText: "Direct", NewText: "Edited"}}}), "id", doc.ID)).Want(http.StatusOK).JSON(&updated)
+ if updated.Content != "Edited" {
+ t.Fatalf("edit must land directly: %+v", updated)
+ }
+ testutil.Call(t, testHandler.GetDoc, withURLParam(newRequest("GET", "/api/docs/"+doc.ID, nil), "id", doc.ID)).Want(http.StatusOK)
+}
diff --git a/server/internal/handler/doc_test.go b/server/internal/handler/doc_test.go
index 1bb256913d..3b8f99de8b 100644
--- a/server/internal/handler/doc_test.go
+++ b/server/internal/handler/doc_test.go
@@ -17,6 +17,8 @@ func createDocForTest(t *testing.T) DocResponse {
testutil.Call(t, testHandler.CreateDoc, newRequest("POST", "/api/docs", map[string]any{"title": "Runbook", "content": "# First\n\nOriginal"})).Want(http.StatusCreated).JSON(&doc)
t.Cleanup(func() {
testPool.Exec(context.Background(), "DELETE FROM doc_version WHERE doc_id = $1", doc.ID)
+ testPool.Exec(context.Background(), "DELETE FROM doc_revision WHERE doc_id = $1", doc.ID)
+ testPool.Exec(context.Background(), "DELETE FROM doc_collab_state WHERE doc_id = $1", doc.ID)
testPool.Exec(context.Background(), "DELETE FROM doc WHERE id = $1", doc.ID)
})
return doc
@@ -159,6 +161,8 @@ func TestDocTextDropsNULBytes(t *testing.T) {
})).Want(http.StatusCreated).JSON(&doc)
t.Cleanup(func() {
testPool.Exec(context.Background(), "DELETE FROM doc_version WHERE doc_id = $1", doc.ID)
+ testPool.Exec(context.Background(), "DELETE FROM doc_revision WHERE doc_id = $1", doc.ID)
+ testPool.Exec(context.Background(), "DELETE FROM doc_collab_state WHERE doc_id = $1", doc.ID)
testPool.Exec(context.Background(), "DELETE FROM doc WHERE id = $1", doc.ID)
})
if doc.Title != "Runbook" || doc.Content != "Step one" {
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 0efa616fe3..385be24c2d 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -21,6 +21,7 @@ import (
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/cloudruntime"
+ "github.com/multica-ai/multica/server/internal/collab"
"github.com/multica-ai/multica/server/internal/connectedapps"
"github.com/multica-ai/multica/server/internal/daemonws"
"github.com/multica-ai/multica/server/internal/dbreader"
@@ -255,6 +256,9 @@ type Handler struct {
LocalSkillListStore LocalSkillListStore
LocalSkillImportStore LocalSkillImportStore
FeatureFlags *featureflag.Service
+ // Collab is the live co-editing service for docs. Nil turns live editing
+ // off: docs save through the REST autosave path.
+ Collab *collab.Client
// ThemeStore serves the community theme registry. Nil only when
// MULTICA_THEME_REGISTRY_URL is invalid: its routes return 404 and
// /api/config omits it.
diff --git a/server/internal/handler/reserved_slugs.json b/server/internal/handler/reserved_slugs.json
index 7445ad5f81..4706c72a7e 100644
--- a/server/internal/handler/reserved_slugs.json
+++ b/server/internal/handler/reserved_slugs.json
@@ -333,6 +333,7 @@
"readyz",
"healthz",
"ws",
+ "collab",
"metrics",
"ping"
]
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 7a116ceb94..6a8266b144 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -67,8 +67,10 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"dingtalk_bot_identity": workspaceDelete,
"dingtalk_group_route": workspaceDelete,
"doc": workspaceDelete,
+ "doc_collab_state": workspaceDelete,
"doc_comment": workspaceDelete,
"doc_folder": workspaceDelete,
+ "doc_revision": workspaceDelete,
"doc_version": workspaceDelete,
"entitlement_feature_attempt": workspaceDelete,
"entitlement_limit_overage": workspaceDelete,
diff --git a/server/migrations/713_doc_collab.down.sql b/server/migrations/713_doc_collab.down.sql
new file mode 100644
index 0000000000..12eb8117eb
--- /dev/null
+++ b/server/migrations/713_doc_collab.down.sql
@@ -0,0 +1,3 @@
+ALTER TABLE doc_version DROP COLUMN IF EXISTS contributors;
+DROP TABLE IF EXISTS doc_revision;
+DROP TABLE IF EXISTS doc_collab_state;
diff --git a/server/migrations/713_doc_collab.up.sql b/server/migrations/713_doc_collab.up.sql
new file mode 100644
index 0000000000..0093b2d81d
--- /dev/null
+++ b/server/migrations/713_doc_collab.up.sql
@@ -0,0 +1,20 @@
+-- Live co-editing of docs: the Yjs state behind a doc's stored content, the
+-- content of recent revisions (so a write based on an older revision can be
+-- merged instead of refused), and everyone whose edits a snapshot carries.
+-- Primary keys are built concurrently in 714–717.
+CREATE TABLE IF NOT EXISTS doc_collab_state (
+ doc_id UUID NOT NULL,
+ workspace_id UUID NOT NULL,
+ ystate BYTEA NOT NULL,
+ revision BIGINT NOT NULL,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE TABLE IF NOT EXISTS doc_revision (
+ doc_id UUID NOT NULL,
+ revision BIGINT NOT NULL,
+ content TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+ALTER TABLE doc_version ADD COLUMN IF NOT EXISTS contributors JSONB NOT NULL DEFAULT '[]'::jsonb;
diff --git a/server/migrations/714_doc_collab_state_pkey_index.down.sql b/server/migrations/714_doc_collab_state_pkey_index.down.sql
new file mode 100644
index 0000000000..282bac4565
--- /dev/null
+++ b/server/migrations/714_doc_collab_state_pkey_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS doc_collab_state_pkey_idx;
diff --git a/server/migrations/714_doc_collab_state_pkey_index.up.sql b/server/migrations/714_doc_collab_state_pkey_index.up.sql
new file mode 100644
index 0000000000..614d91fe3e
--- /dev/null
+++ b/server/migrations/714_doc_collab_state_pkey_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS doc_collab_state_pkey_idx ON doc_collab_state (doc_id);
diff --git a/server/migrations/715_doc_collab_state_pkey.down.sql b/server/migrations/715_doc_collab_state_pkey.down.sql
new file mode 100644
index 0000000000..53b49038b9
--- /dev/null
+++ b/server/migrations/715_doc_collab_state_pkey.down.sql
@@ -0,0 +1 @@
+ALTER TABLE doc_collab_state DROP CONSTRAINT IF EXISTS doc_collab_state_pkey;
diff --git a/server/migrations/715_doc_collab_state_pkey.up.sql b/server/migrations/715_doc_collab_state_pkey.up.sql
new file mode 100644
index 0000000000..0514a100a3
--- /dev/null
+++ b/server/migrations/715_doc_collab_state_pkey.up.sql
@@ -0,0 +1 @@
+ALTER TABLE doc_collab_state ADD CONSTRAINT doc_collab_state_pkey PRIMARY KEY USING INDEX doc_collab_state_pkey_idx;
diff --git a/server/migrations/716_doc_revision_pkey_index.down.sql b/server/migrations/716_doc_revision_pkey_index.down.sql
new file mode 100644
index 0000000000..e88f4389ed
--- /dev/null
+++ b/server/migrations/716_doc_revision_pkey_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS doc_revision_pkey_idx;
diff --git a/server/migrations/716_doc_revision_pkey_index.up.sql b/server/migrations/716_doc_revision_pkey_index.up.sql
new file mode 100644
index 0000000000..8e5da45b99
--- /dev/null
+++ b/server/migrations/716_doc_revision_pkey_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS doc_revision_pkey_idx ON doc_revision (doc_id, revision);
diff --git a/server/migrations/717_doc_revision_pkey.down.sql b/server/migrations/717_doc_revision_pkey.down.sql
new file mode 100644
index 0000000000..62c7f620c8
--- /dev/null
+++ b/server/migrations/717_doc_revision_pkey.down.sql
@@ -0,0 +1 @@
+ALTER TABLE doc_revision DROP CONSTRAINT IF EXISTS doc_revision_pkey;
diff --git a/server/migrations/717_doc_revision_pkey.up.sql b/server/migrations/717_doc_revision_pkey.up.sql
new file mode 100644
index 0000000000..6ae5b06d23
--- /dev/null
+++ b/server/migrations/717_doc_revision_pkey.up.sql
@@ -0,0 +1 @@
+ALTER TABLE doc_revision ADD CONSTRAINT doc_revision_pkey PRIMARY KEY USING INDEX doc_revision_pkey_idx;
diff --git a/server/pkg/db/generated/doc.sql.go b/server/pkg/db/generated/doc.sql.go
index 5d2aa71885..ae6c703393 100644
--- a/server/pkg/db/generated/doc.sql.go
+++ b/server/pkg/db/generated/doc.sql.go
@@ -174,7 +174,9 @@ func (q *Queries) CreateDocFolder(ctx context.Context, arg CreateDocFolderParams
const deleteDoc = `-- name: DeleteDoc :exec
WITH v AS (DELETE FROM doc_version WHERE doc_version.doc_id = $1 AND doc_version.workspace_id = $2),
-c AS (DELETE FROM doc_comment WHERE doc_comment.doc_id = $1 AND doc_comment.workspace_id = $2)
+c AS (DELETE FROM doc_comment WHERE doc_comment.doc_id = $1 AND doc_comment.workspace_id = $2),
+s AS (DELETE FROM doc_collab_state WHERE doc_collab_state.doc_id = $1 AND doc_collab_state.workspace_id = $2),
+r AS (DELETE FROM doc_revision WHERE doc_revision.doc_id = $1)
DELETE FROM doc WHERE doc.id = $1 AND doc.workspace_id = $2
`
@@ -222,6 +224,8 @@ func (q *Queries) DeleteDocFolder(ctx context.Context, arg DeleteDocFolderParams
const deleteWorkspaceDocs = `-- name: DeleteWorkspaceDocs :exec
WITH v AS (DELETE FROM doc_version WHERE doc_version.workspace_id = $1),
+s AS (DELETE FROM doc_collab_state WHERE doc_collab_state.doc_id IN (SELECT id FROM doc WHERE doc.workspace_id = $1)),
+r AS (DELETE FROM doc_revision WHERE doc_revision.doc_id IN (SELECT id FROM doc WHERE doc.workspace_id = $1)),
c AS (DELETE FROM doc_comment WHERE doc_comment.workspace_id = $1),
f AS (DELETE FROM doc_folder WHERE doc_folder.workspace_id = $1)
DELETE FROM doc WHERE doc.workspace_id = $1
@@ -263,6 +267,31 @@ func (q *Queries) GetDoc(ctx context.Context, arg GetDocParams) (Doc, error) {
return i, err
}
+const getDocByIDForUpdate = `-- name: GetDocByIDForUpdate :one
+SELECT id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at FROM doc WHERE id = $1 FOR UPDATE
+`
+
+func (q *Queries) GetDocByIDForUpdate(ctx context.Context, id pgtype.UUID) (Doc, error) {
+ row := q.db.QueryRow(ctx, getDocByIDForUpdate, id)
+ var i Doc
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.FolderID,
+ &i.Title,
+ &i.Content,
+ &i.Revision,
+ &i.VersionCount,
+ &i.CreatedByType,
+ &i.CreatedByID,
+ &i.UpdatedByType,
+ &i.UpdatedByID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
const getDocComment = `-- name: GetDocComment :one
SELECT id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at FROM doc_comment
WHERE id = $1 AND doc_id = $2 AND workspace_id = $3
@@ -323,6 +352,39 @@ func (q *Queries) GetDocFolder(ctx context.Context, arg GetDocFolderParams) (Doc
return i, err
}
+const getDocForCollab = `-- name: GetDocForCollab :one
+SELECT d.workspace_id, d.title, d.content, d.revision,
+ s.ystate AS ystate, s.revision AS ystate_revision
+FROM doc d
+LEFT JOIN doc_collab_state s ON s.doc_id = d.id
+WHERE d.id = $1
+`
+
+type GetDocForCollabRow struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Title string `json:"title"`
+ Content string `json:"content"`
+ Revision int64 `json:"revision"`
+ Ystate []byte `json:"ystate"`
+ YstateRevision pgtype.Int8 `json:"ystate_revision"`
+}
+
+// The collaboration service's view of a doc: stored content plus the Yjs
+// state last saved with it, which is only reusable at the same revision.
+func (q *Queries) GetDocForCollab(ctx context.Context, id pgtype.UUID) (GetDocForCollabRow, error) {
+ row := q.db.QueryRow(ctx, getDocForCollab, id)
+ var i GetDocForCollabRow
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Content,
+ &i.Revision,
+ &i.Ystate,
+ &i.YstateRevision,
+ )
+ return i, err
+}
+
const getDocForUpdate = `-- name: GetDocForUpdate :one
SELECT id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at FROM doc
WHERE id = $1 AND workspace_id = $2
@@ -355,8 +417,25 @@ func (q *Queries) GetDocForUpdate(ctx context.Context, arg GetDocForUpdateParams
return i, err
}
+const getDocRevisionContent = `-- name: GetDocRevisionContent :one
+SELECT content FROM doc_revision
+WHERE doc_id = $1 AND revision = $2
+`
+
+type GetDocRevisionContentParams struct {
+ DocID pgtype.UUID `json:"doc_id"`
+ Revision int64 `json:"revision"`
+}
+
+func (q *Queries) GetDocRevisionContent(ctx context.Context, arg GetDocRevisionContentParams) (string, error) {
+ row := q.db.QueryRow(ctx, getDocRevisionContent, arg.DocID, arg.Revision)
+ var content string
+ err := row.Scan(&content)
+ return content, err
+}
+
const getDocVersion = `-- name: GetDocVersion :one
-SELECT doc_id, workspace_id, number, title, content, author_type, author_id, message, action, action_ref, task_id, issue_id, created_at, updated_at FROM doc_version
+SELECT doc_id, workspace_id, number, title, content, author_type, author_id, message, action, action_ref, task_id, issue_id, created_at, updated_at, contributors FROM doc_version
WHERE doc_id = $1 AND number = $2
`
@@ -383,34 +462,54 @@ func (q *Queries) GetDocVersion(ctx context.Context, arg GetDocVersionParams) (D
&i.IssueID,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Contributors,
)
return i, err
}
+const insertDocRevision = `-- name: InsertDocRevision :exec
+INSERT INTO doc_revision (doc_id, revision, content)
+VALUES ($1, $2, $3)
+ON CONFLICT (doc_id, revision) DO UPDATE SET content = EXCLUDED.content
+`
+
+type InsertDocRevisionParams struct {
+ DocID pgtype.UUID `json:"doc_id"`
+ Revision int64 `json:"revision"`
+ Content string `json:"content"`
+}
+
+func (q *Queries) InsertDocRevision(ctx context.Context, arg InsertDocRevisionParams) error {
+ _, err := q.db.Exec(ctx, insertDocRevision, arg.DocID, arg.Revision, arg.Content)
+ return err
+}
+
const insertDocVersion = `-- name: InsertDocVersion :one
INSERT INTO doc_version (
doc_id, workspace_id, number, title, content, author_type, author_id,
- message, action, action_ref, task_id, issue_id
+ message, action, action_ref, task_id, issue_id, contributors
) VALUES (
$1, $2, $3, $4, $5, $6, $7,
- $8, $9, $10, $11, $12
+ $8, $9, $10, $11, $12,
+ $13::jsonb
)
-RETURNING doc_id, workspace_id, number, title, content, author_type, author_id, message, action, action_ref, task_id, issue_id, created_at, updated_at
+RETURNING doc_id, workspace_id, number, title, content, author_type, author_id, message, action, action_ref, task_id, issue_id, created_at, updated_at, contributors
`
type InsertDocVersionParams struct {
- DocID pgtype.UUID `json:"doc_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Number int32 `json:"number"`
- Title string `json:"title"`
- Content string `json:"content"`
- AuthorType string `json:"author_type"`
- AuthorID pgtype.UUID `json:"author_id"`
- Message string `json:"message"`
- Action string `json:"action"`
- ActionRef pgtype.Int4 `json:"action_ref"`
- TaskID pgtype.UUID `json:"task_id"`
- IssueID pgtype.UUID `json:"issue_id"`
+ DocID pgtype.UUID `json:"doc_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Number int32 `json:"number"`
+ Title string `json:"title"`
+ Content string `json:"content"`
+ AuthorType string `json:"author_type"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ Message string `json:"message"`
+ Action string `json:"action"`
+ ActionRef pgtype.Int4 `json:"action_ref"`
+ TaskID pgtype.UUID `json:"task_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Contributors []byte `json:"contributors"`
}
func (q *Queries) InsertDocVersion(ctx context.Context, arg InsertDocVersionParams) (DocVersion, error) {
@@ -427,6 +526,7 @@ func (q *Queries) InsertDocVersion(ctx context.Context, arg InsertDocVersionPara
arg.ActionRef,
arg.TaskID,
arg.IssueID,
+ arg.Contributors,
)
var i DocVersion
err := row.Scan(
@@ -444,6 +544,7 @@ func (q *Queries) InsertDocVersion(ctx context.Context, arg InsertDocVersionPara
&i.IssueID,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Contributors,
)
return i, err
}
@@ -567,7 +668,7 @@ func (q *Queries) ListDocThreadParticipants(ctx context.Context, arg ListDocThre
const listDocVersions = `-- name: ListDocVersions :many
SELECT
doc_id, workspace_id, number, title, author_type, author_id, message, action,
- action_ref, task_id, issue_id, created_at, updated_at
+ action_ref, task_id, issue_id, contributors, created_at, updated_at
FROM doc_version
WHERE doc_id = $1
ORDER BY number DESC
@@ -580,19 +681,20 @@ type ListDocVersionsParams struct {
}
type ListDocVersionsRow struct {
- DocID pgtype.UUID `json:"doc_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Number int32 `json:"number"`
- Title string `json:"title"`
- AuthorType string `json:"author_type"`
- AuthorID pgtype.UUID `json:"author_id"`
- Message string `json:"message"`
- Action string `json:"action"`
- ActionRef pgtype.Int4 `json:"action_ref"`
- TaskID pgtype.UUID `json:"task_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ DocID pgtype.UUID `json:"doc_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Number int32 `json:"number"`
+ Title string `json:"title"`
+ AuthorType string `json:"author_type"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ Message string `json:"message"`
+ Action string `json:"action"`
+ ActionRef pgtype.Int4 `json:"action_ref"`
+ TaskID pgtype.UUID `json:"task_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Contributors []byte `json:"contributors"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
func (q *Queries) ListDocVersions(ctx context.Context, arg ListDocVersionsParams) ([]ListDocVersionsRow, error) {
@@ -616,6 +718,7 @@ func (q *Queries) ListDocVersions(ctx context.Context, arg ListDocVersionsParams
&i.ActionRef,
&i.TaskID,
&i.IssueID,
+ &i.Contributors,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
@@ -696,6 +799,49 @@ func (q *Queries) LockDocTree(ctx context.Context, workspaceID pgtype.UUID) erro
return err
}
+const mergeCollabEditIntoVersion = `-- name: MergeCollabEditIntoVersion :execrows
+UPDATE doc_version SET
+ title = $1,
+ content = $2,
+ contributors = (
+ SELECT COALESCE(jsonb_agg(DISTINCT e), '[]'::jsonb)
+ FROM jsonb_array_elements(doc_version.contributors || $3::jsonb) AS e
+ ),
+ updated_at = now()
+WHERE doc_id = $4
+ AND number = $5
+ AND action = 'edit'
+ AND message = ''
+ AND author_type = 'member'
+ AND task_id IS NULL
+ AND created_at > now() - interval '30 minutes'
+`
+
+type MergeCollabEditIntoVersionParams struct {
+ Title string `json:"title"`
+ Content string `json:"content"`
+ Contributors []byte `json:"contributors"`
+ DocID pgtype.UUID `json:"doc_id"`
+ Number int32 `json:"number"`
+}
+
+// Folds a save from people editing together into the latest snapshot while
+// the session lasts: an unlabeled member edit within 30 minutes of the
+// snapshot's start. Everyone who joined is added to its contributors.
+func (q *Queries) MergeCollabEditIntoVersion(ctx context.Context, arg MergeCollabEditIntoVersionParams) (int64, error) {
+ result, err := q.db.Exec(ctx, mergeCollabEditIntoVersion,
+ arg.Title,
+ arg.Content,
+ arg.Contributors,
+ arg.DocID,
+ arg.Number,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const mergeDocEditIntoVersion = `-- name: MergeDocEditIntoVersion :execrows
UPDATE doc_version SET
title = $1,
@@ -803,6 +949,21 @@ func (q *Queries) MoveDocFolder(ctx context.Context, arg MoveDocFolderParams) (D
return i, err
}
+const pruneDocRevisions = `-- name: PruneDocRevisions :exec
+DELETE FROM doc_revision
+WHERE doc_id = $1 AND revision < $2
+`
+
+type PruneDocRevisionsParams struct {
+ DocID pgtype.UUID `json:"doc_id"`
+ KeepFrom int64 `json:"keep_from"`
+}
+
+func (q *Queries) PruneDocRevisions(ctx context.Context, arg PruneDocRevisionsParams) error {
+ _, err := q.db.Exec(ctx, pruneDocRevisions, arg.DocID, arg.KeepFrom)
+ return err
+}
+
const renameDocFolder = `-- name: RenameDocFolder :one
UPDATE doc_folder SET title = $1, updated_at = now()
WHERE id = $2 AND workspace_id = $3
@@ -932,3 +1093,29 @@ func (q *Queries) UpdateDocContent(ctx context.Context, arg UpdateDocContentPara
)
return i, err
}
+
+const upsertDocCollabState = `-- name: UpsertDocCollabState :exec
+INSERT INTO doc_collab_state (doc_id, workspace_id, ystate, revision)
+VALUES ($1, $2, $3, $4)
+ON CONFLICT (doc_id) DO UPDATE SET
+ ystate = EXCLUDED.ystate,
+ revision = EXCLUDED.revision,
+ updated_at = now()
+`
+
+type UpsertDocCollabStateParams struct {
+ DocID pgtype.UUID `json:"doc_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Ystate []byte `json:"ystate"`
+ Revision int64 `json:"revision"`
+}
+
+func (q *Queries) UpsertDocCollabState(ctx context.Context, arg UpsertDocCollabStateParams) error {
+ _, err := q.db.Exec(ctx, upsertDocCollabState,
+ arg.DocID,
+ arg.WorkspaceID,
+ arg.Ystate,
+ arg.Revision,
+ )
+ return err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 417e1cf513..c5af52b107 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -879,6 +879,14 @@ type Doc struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
+type DocCollabState struct {
+ DocID pgtype.UUID `json:"doc_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Ystate []byte `json:"ystate"`
+ Revision int64 `json:"revision"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type DocComment struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
@@ -908,21 +916,29 @@ type DocFolder struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
+type DocRevision struct {
+ DocID pgtype.UUID `json:"doc_id"`
+ Revision int64 `json:"revision"`
+ Content string `json:"content"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type DocVersion struct {
- DocID pgtype.UUID `json:"doc_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Number int32 `json:"number"`
- Title string `json:"title"`
- Content string `json:"content"`
- AuthorType string `json:"author_type"`
- AuthorID pgtype.UUID `json:"author_id"`
- Message string `json:"message"`
- Action string `json:"action"`
- ActionRef pgtype.Int4 `json:"action_ref"`
- TaskID pgtype.UUID `json:"task_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ DocID pgtype.UUID `json:"doc_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Number int32 `json:"number"`
+ Title string `json:"title"`
+ Content string `json:"content"`
+ AuthorType string `json:"author_type"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ Message string `json:"message"`
+ Action string `json:"action"`
+ ActionRef pgtype.Int4 `json:"action_ref"`
+ TaskID pgtype.UUID `json:"task_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ Contributors []byte `json:"contributors"`
}
type EntitlementFeatureAttempt struct {
diff --git a/server/pkg/db/queries/doc.sql b/server/pkg/db/queries/doc.sql
index 10fbe6b8fd..10096a24af 100644
--- a/server/pkg/db/queries/doc.sql
+++ b/server/pkg/db/queries/doc.sql
@@ -83,7 +83,9 @@ RETURNING *;
-- name: DeleteDoc :exec
WITH v AS (DELETE FROM doc_version WHERE doc_version.doc_id = @id AND doc_version.workspace_id = @workspace_id),
-c AS (DELETE FROM doc_comment WHERE doc_comment.doc_id = @id AND doc_comment.workspace_id = @workspace_id)
+c AS (DELETE FROM doc_comment WHERE doc_comment.doc_id = @id AND doc_comment.workspace_id = @workspace_id),
+s AS (DELETE FROM doc_collab_state WHERE doc_collab_state.doc_id = @id AND doc_collab_state.workspace_id = @workspace_id),
+r AS (DELETE FROM doc_revision WHERE doc_revision.doc_id = @id)
DELETE FROM doc WHERE doc.id = @id AND doc.workspace_id = @workspace_id;
-- name: GetDocVersion :one
@@ -93,7 +95,7 @@ WHERE doc_id = $1 AND number = $2;
-- name: ListDocVersions :many
SELECT
doc_id, workspace_id, number, title, author_type, author_id, message, action,
- action_ref, task_id, issue_id, created_at, updated_at
+ action_ref, task_id, issue_id, contributors, created_at, updated_at
FROM doc_version
WHERE doc_id = $1
ORDER BY number DESC
@@ -119,15 +121,18 @@ WHERE doc_id = @doc_id
-- name: InsertDocVersion :one
INSERT INTO doc_version (
doc_id, workspace_id, number, title, content, author_type, author_id,
- message, action, action_ref, task_id, issue_id
+ message, action, action_ref, task_id, issue_id, contributors
) VALUES (
@doc_id, @workspace_id, @number, @title, @content, @author_type, @author_id,
- @message, @action, sqlc.narg('action_ref'), sqlc.narg('task_id'), sqlc.narg('issue_id')
+ @message, @action, sqlc.narg('action_ref'), sqlc.narg('task_id'), sqlc.narg('issue_id'),
+ @contributors::jsonb
)
RETURNING *;
-- name: DeleteWorkspaceDocs :exec
WITH v AS (DELETE FROM doc_version WHERE doc_version.workspace_id = @workspace_id),
+s AS (DELETE FROM doc_collab_state WHERE doc_collab_state.doc_id IN (SELECT id FROM doc WHERE doc.workspace_id = @workspace_id)),
+r AS (DELETE FROM doc_revision WHERE doc_revision.doc_id IN (SELECT id FROM doc WHERE doc.workspace_id = @workspace_id)),
c AS (DELETE FROM doc_comment WHERE doc_comment.workspace_id = @workspace_id),
f AS (DELETE FROM doc_folder WHERE doc_folder.workspace_id = @workspace_id)
DELETE FROM doc WHERE doc.workspace_id = @workspace_id;
@@ -173,3 +178,56 @@ SELECT DISTINCT author_id FROM doc_comment
WHERE workspace_id = @workspace_id AND doc_id = @doc_id
AND (id = @root_id OR parent_id = @root_id)
AND author_type = 'member';
+
+-- name: GetDocForCollab :one
+-- The collaboration service's view of a doc: stored content plus the Yjs
+-- state last saved with it, which is only reusable at the same revision.
+SELECT d.workspace_id, d.title, d.content, d.revision,
+ s.ystate AS ystate, s.revision AS ystate_revision
+FROM doc d
+LEFT JOIN doc_collab_state s ON s.doc_id = d.id
+WHERE d.id = $1;
+
+-- name: GetDocByIDForUpdate :one
+SELECT * FROM doc WHERE id = $1 FOR UPDATE;
+
+-- name: UpsertDocCollabState :exec
+INSERT INTO doc_collab_state (doc_id, workspace_id, ystate, revision)
+VALUES (@doc_id, @workspace_id, @ystate, @revision)
+ON CONFLICT (doc_id) DO UPDATE SET
+ ystate = EXCLUDED.ystate,
+ revision = EXCLUDED.revision,
+ updated_at = now();
+
+-- name: InsertDocRevision :exec
+INSERT INTO doc_revision (doc_id, revision, content)
+VALUES (@doc_id, @revision, @content)
+ON CONFLICT (doc_id, revision) DO UPDATE SET content = EXCLUDED.content;
+
+-- name: PruneDocRevisions :exec
+DELETE FROM doc_revision
+WHERE doc_id = @doc_id AND revision < @keep_from;
+
+-- name: GetDocRevisionContent :one
+SELECT content FROM doc_revision
+WHERE doc_id = @doc_id AND revision = @revision;
+
+-- name: MergeCollabEditIntoVersion :execrows
+-- Folds a save from people editing together into the latest snapshot while
+-- the session lasts: an unlabeled member edit within 30 minutes of the
+-- snapshot's start. Everyone who joined is added to its contributors.
+UPDATE doc_version SET
+ title = @title,
+ content = @content,
+ contributors = (
+ SELECT COALESCE(jsonb_agg(DISTINCT e), '[]'::jsonb)
+ FROM jsonb_array_elements(doc_version.contributors || @contributors::jsonb) AS e
+ ),
+ updated_at = now()
+WHERE doc_id = @doc_id
+ AND number = @number
+ AND action = 'edit'
+ AND message = ''
+ AND author_type = 'member'
+ AND task_id IS NULL
+ AND created_at > now() - interval '30 minutes';