Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions pkgs/id/web/src/collab-step-budget.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Packr } from "msgpackr";

/**
* Per-message step bound, mirroring MAX_STEPS_PER_MESSAGE in
* pkgs/id/src/web/collab.rs. A transaction may exceed this count, so the
* client flushes remainder steps as the server confirms each batch.
*/
export const MAX_STEPS_PER_MESSAGE = 1000;

/**
* Wire-size budget for one Steps message, mirroring the server frame cap
* MAX_FRAME_BYTES (1 MiB, pkgs/id/src/frames.rs) minus a reserve for the
* MessagePack envelope. Both editor-side splitting and outbound batching
* use this shared bound.
*/
export const MAX_STEPS_MESSAGE_BYTES = 1024 * 1024 - 4096;

const packr = new Packr({ useRecords: false, structuredClone: true });

/** Encoded size of one step on the wire (MessagePack, same config as collab.ts). */
export function stepWireSize(step: unknown): number {
return packr.pack(step).byteLength;
}
64 changes: 63 additions & 1 deletion pkgs/id/web/src/collab.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { Packr, Unpackr } from "msgpackr";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MAX_STEPS_MESSAGE_BYTES, MAX_STEPS_PER_MESSAGE, buildCollabWsUrl, initCollab, stepBatch } from "./collab";
import {
MAX_STEPS_MESSAGE_BYTES,
MAX_STEPS_PER_MESSAGE,
buildCollabWsUrl,
initCollab,
stepBatch,
stepWireSize,
} from "./collab";
import { getSendableSteps, getVersion } from "./editor";

// Same MessagePack configuration as collab.ts
const packr = new Packr({ useRecords: false, structuredClone: true });
Expand Down Expand Up @@ -269,6 +277,60 @@ describe("stepBatch (client side of the server step cap, #1965)", () => {
});
});

describe("large text insertion collaboration (#4119)", () => {
beforeEach(() => {
vi.useFakeTimers();
FakeWebSocket.instances = [];
vi.stubGlobal("WebSocket", FakeWebSocket);
});

afterEach(() => {
while (liveConnections.length > 0) liveConnections.pop()?.disconnect();
vi.unstubAllGlobals();
vi.useRealTimers();
document.body.innerHTML = "";
});

it("sends and confirms all bounded steps from a single oversized paste", () => {
const { conn, socket } = openCollab();
socket.deliver([MSG_INIT, 0, { type: "doc", content: [{ type: "code_block" }] }, "raw"]);
expect(conn.editor).not.toBeNull();

const view = conn.editor!.view;
const text = "x".repeat(1_100_000);
view.dispatch(view.state.tr.insertText(text, 1));

let confirmed = 0;
for (let frameIndex = 0; frameIndex < 100; frameIndex++) {
const frames = socket.sent.map((data) => unpackr.unpack(data as Uint8Array) as unknown[]);
const stepFrames = frames.filter((frame) => frame[0] === 1);
const frame = stepFrames[frameIndex];
if (!frame) break;

const steps = frame[2] as unknown[];
const clientID = frame[3] as number;
expect(steps.length).toBeGreaterThan(0);
expect(steps.length).toBeLessThanOrEqual(MAX_STEPS_PER_MESSAGE);
expect(steps.every((step) => stepWireSize(step) <= MAX_STEPS_MESSAGE_BYTES)).toBe(true);

confirmed += steps.length;
socket.deliver([2, steps, steps.map(() => clientID)]);
}

const allFrames = socket.sent.map((data) => unpackr.unpack(data as Uint8Array) as unknown[]);
const stepFrameData = socket.sent.filter((data) => (unpackr.unpack(data as Uint8Array) as unknown[])[0] === 1);
const sentSteps = allFrames.filter((frame) => frame[0] === 1).flatMap((frame) => frame[2] as unknown[]);
expect(stepFrameData.every((data) => (data as Uint8Array).byteLength <= 1024 * 1024)).toBe(true);
expect(sentSteps.length).toBeGreaterThan(1);
expect(sentSteps.map((step) => (step as { slice: { content: Array<{ text?: string }> } }).slice.content
.map((node) => node.text ?? "").join("")).join("")).toBe(text);
expect(confirmed).toBe(sentSteps.length);
expect(getSendableSteps(view)).toBeNull();
expect(getVersion(view.state)).toBe(confirmed);
expect(view.state.doc.textContent).toBe(text);
});
});

describe("buildCollabWsUrl (#2830)", () => {
// [docId, expected single path segment] — the segment must decode
// back to the exact docId, and plain names must be untouched.
Expand Down
25 changes: 3 additions & 22 deletions pkgs/id/web/src/collab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ import { Step } from "prosemirror-transform";
import { markCursorFresh, onInitReceived, removeCursor, setConnectionState, updateCursor } from "./cursors";
import { type ContentMode, type EditorInstance, getSendableSteps, initEditor } from "./editor";
import { closeImageBrowser } from "./image-browser";
import { MAX_STEPS_MESSAGE_BYTES, MAX_STEPS_PER_MESSAGE, stepWireSize } from "./collab-step-budget";

export { MAX_STEPS_MESSAGE_BYTES, MAX_STEPS_PER_MESSAGE, stepWireSize } from "./collab-step-budget";

// Message type tags
const MSG = {
Expand All @@ -60,28 +63,6 @@ const MSG = {
const packr = new Packr({ useRecords: false, structuredClone: true });
const unpackr = new Unpackr({ useRecords: false, structuredClone: true });

/** Per-message step bound, mirroring the server MAX_STEPS_PER_MESSAGE
* (pkgs/id/src/web/collab.rs). A single editor transaction can legitimately
* exceed it - indenting N lines produces N steps (web/src/indent.ts) - so
* the client sends at most this many steps per Steps message and flushes
* the remainder as the server confirms each batch (see the Update handler),
* instead of wedging the session on a rejected oversized batch. */
export const MAX_STEPS_PER_MESSAGE = 1000;

/** Wire-size budget for one Steps message, mirroring the server frame cap
* MAX_FRAME_BYTES (1 MiB, pkgs/id/src/frames.rs) minus a reserve for the
* MessagePack envelope ([tag, version, steps, clientID]). The step-count
* cap alone cannot bound the wire size: 1,000 medium steps encode to far
* more than 1 MiB, and the server refuses an over-limit message before
* applying any of it (Codex P2 on PR #4051). */
export const MAX_STEPS_MESSAGE_BYTES = 1024 * 1024 - 4096;

/** Encoded size of one step on the wire (MessagePack, same Packr config
* as the send path). */
export function stepWireSize(step: unknown): number {
return packr.pack(step).byteLength;
}

/** The next batch of pending steps to send: at most MAX_STEPS_PER_MESSAGE
* steps and at most MAX_STEPS_MESSAGE_BYTES of encoded steps, in order.
* Remaining steps stay unconfirmed and are sent by later flushes.
Expand Down
45 changes: 45 additions & 0 deletions pkgs/id/web/src/editor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* Tests the content mode types, schema selection, and editor initialization.
*/

import { redo, undo } from "prosemirror-history";
import type { EditorView } from "prosemirror-view";
import { afterEach, describe, expect, it } from "vitest";
import {
Expand All @@ -17,7 +18,9 @@ import {
parseOrderedListStart,
rawSchema,
richSchema,
splitOversizedTextInsertion,
} from "./editor";
import { MAX_STEPS_MESSAGE_BYTES, stepWireSize } from "./collab-step-budget";

// ============================================================================
// Content Mode Type Tests
Expand Down Expand Up @@ -662,6 +665,48 @@ describe("getSendableSteps", () => {
});
});

describe("oversized text insertion dispatch (#4119)", () => {
const views: EditorView[] = [];

afterEach(() => {
for (const view of views) view.destroy();
views.length = 0;
});

it("leaves an under-budget insertion on the original transaction path", () => {
const container = document.createElement("div");
const { view } = initEditor(container, undefined, 0, "raw");
views.push(view);
const transaction = view.state.tr.insertText("small paste", 1);

expect(stepWireSize(transaction.steps[0])).toBeLessThanOrEqual(MAX_STEPS_MESSAGE_BYTES);
expect(splitOversizedTextInsertion(view.state, transaction)).toBe(transaction);
});

it("splits a large text insertion into bounded steps in one undoable transaction", () => {
const container = document.createElement("div");
const { view } = initEditor(container, undefined, 0, "raw");
views.push(view);
const text = "a😀".repeat(250_000);
const transaction = view.state.tr.insertText(text, 1);
const rewritten = splitOversizedTextInsertion(view.state, transaction);

expect(rewritten).not.toBe(transaction);
expect(rewritten.steps.length).toBeGreaterThan(1);
expect(rewritten.steps.every((step) => stepWireSize(step) <= MAX_STEPS_MESSAGE_BYTES)).toBe(true);
expect(rewritten.doc.eq(transaction.doc)).toBe(true);

view.dispatch(transaction);
expect(view.state.doc.textContent).toBe(text);
expect(view.state.selection.head).toBe(text.length + 1);

expect(undo(view.state, (tr) => view.dispatch(tr))).toBe(true);
expect(view.state.doc.textContent).toBe("");
expect(redo(view.state, (tr) => view.dispatch(tr))).toBe(true);
expect(view.state.doc.textContent).toBe(text);
});
});

// ============================================================================
// #2010: image parseDOM width/height parsing — only plain non-negative
// safe integers survive; everything else is dropped to null at parse time
Expand Down
104 changes: 102 additions & 2 deletions pkgs/id/web/src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ import { gapCursor } from "prosemirror-gapcursor";
import { history } from "prosemirror-history";
import { keymap } from "prosemirror-keymap";
import { MenuItem, blockTypeItem, liftItem, redoItem, selectParentNodeItem, undoItem } from "prosemirror-menu";
import { type MarkType, Node, Schema } from "prosemirror-model";
import { Fragment, type Mark, type MarkType, Node, Schema, Slice } from "prosemirror-model";
import { schema as basicSchema } from "prosemirror-schema-basic";
import { addListNodes } from "prosemirror-schema-list";
import { EditorState, type Plugin, TextSelection, type Transaction } from "prosemirror-state";
import { EditorState, type Plugin, Selection, TextSelection, type Transaction } from "prosemirror-state";
import { ReplaceStep } from "prosemirror-transform";
import { EditorView } from "prosemirror-view";
import { createActiveLinePlugin } from "./active-line";
import { createCursorPlugin, type SendCursorFn } from "./cursors";
Expand All @@ -31,6 +32,7 @@ import { createImageUploadPlugin } from "./image-upload";
import { createIndentPlugin } from "./indent";
import { createSearchPlugins } from "./search-panel";
import { createWrapPlugins } from "./wrap";
import { MAX_STEPS_MESSAGE_BYTES, stepWireSize } from "./collab-step-budget";

/**
* Content mode types matching server-side enum.
Expand Down Expand Up @@ -481,6 +483,103 @@ function markMenuItem(markType: MarkType, options: { title: string; label: strin
});
}

type TextRun = { text: string; marks: readonly Mark[] };

/**
* Turn a single oversized, closed text replacement into smaller replace
* steps before the collab plugin sees it. Keeping these steps in one
* transaction preserves normal history grouping and selection mapping.
*/
export function splitOversizedTextInsertion(state: EditorState, transaction: Transaction): Transaction {
if (transaction.steps.length !== 1 || transaction.getMeta("addToHistory") === false) return transaction;

const step = transaction.steps[0];
if (!(step instanceof ReplaceStep) || step.slice.openStart !== 0 || step.slice.openEnd !== 0) return transaction;
if (!(transaction.selection instanceof TextSelection)) return transaction;
if (stepWireSize(step.toJSON()) <= MAX_STEPS_MESSAGE_BYTES) return transaction;

const runs: TextRun[] = [];
let textLength = 0;
let textOnly = step.slice.content.childCount > 0;
step.slice.content.forEach((node) => {
if (!node.isText || typeof node.text !== "string") {
textOnly = false;
return;
}
runs.push({ text: node.text, marks: node.marks });
textLength += node.text.length;
});
if (!textOnly || textLength === 0) return transaction;

const text = runs.map((run) => run.text).join("");
const sliceBetween = (from: number, to: number): Slice => {
const nodes: Node[] = [];
let offset = 0;
for (const run of runs) {
const runEnd = offset + run.text.length;
const start = Math.max(from, offset);
const end = Math.min(to, runEnd);
if (start < end) nodes.push(state.schema.text(run.text.slice(start - offset, end - offset), run.marks));
offset = runEnd;
if (offset >= to) break;
}
return new Slice(Fragment.fromArray(nodes), 0, 0);
};
const safeBoundary = (position: number): number => {
if (position > 0 && position < text.length) {
const before = text.charCodeAt(position - 1);
const after = text.charCodeAt(position);
if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) return position - 1;
}
return position;
};

const replacement = state.tr;
let start = 0;
while (start < text.length) {
let low = start + 1;
let high = text.length;
let best = start;
while (low <= high) {
const end = safeBoundary(Math.floor((low + high) / 2));
if (end <= start) {
low = Math.floor((low + high) / 2) + 1;
continue;
}
const from = step.from + start;
const to = start === 0 ? step.to : from;
const candidate = new ReplaceStep(from, to, sliceBetween(start, end));
if (stepWireSize(candidate.toJSON()) <= MAX_STEPS_MESSAGE_BYTES) {
best = end;
low = Math.floor((low + high) / 2) + 1;
} else {
high = Math.floor((low + high) / 2) - 1;
}
}
if (best === start) return transaction;

const from = step.from + start;
const to = start === 0 ? step.to : from;
replacement.step(new ReplaceStep(from, to, sliceBetween(start, best)));
start = best;
}

// Fail closed if the narrow rewrite did not produce precisely the same
// document. All generated steps must be within the shared outbound budget.
if (!replacement.doc.eq(transaction.doc)) return transaction;
if (replacement.steps.some((candidate) => stepWireSize(candidate.toJSON()) > MAX_STEPS_MESSAGE_BYTES)) {
return transaction;
}

replacement.setSelection(Selection.fromJSON(replacement.doc, transaction.selection.toJSON()));
const transactionMeta = (transaction as unknown as { meta: Record<string, unknown> }).meta;
for (const [key, value] of Object.entries(transactionMeta)) replacement.setMeta(key, value);
if (transaction.storedMarksSet) replacement.setStoredMarks(transaction.storedMarks);
replacement.setTime(transaction.time);
if (transaction.scrolledIntoView) replacement.scrollIntoView();
return replacement;
}

/**
* Initialize a ProseMirror editor in the given container.
*
Expand Down Expand Up @@ -729,6 +828,7 @@ export function initEditor(
},
},
dispatchTransaction(transaction: Transaction) {
transaction = splitOversizedTextInsertion(view.state, transaction);
const newState = view.state.apply(transaction);
view.updateState(newState);

Expand Down
Loading