Skip to content

[Prototype] [lexical][lexical-list][lexical-rich-text][lexical-react][lexical-yjs] Feature: Prototype block markers - #9386

Closed
zurfyx wants to merge 1 commit into
zurfyx/collab-v2-inline-format-layoutfrom
zurfyx/collab-v2-block-marker-layout
Closed

zurfyx wants to merge 1 commit into
zurfyx/collab-v2-inline-format-layoutfrom
zurfyx/collab-v2-block-marker-layout

Conversation

@zurfyx

@zurfyx zurfyx commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Note

Prototype, not for merge. Stacked on #9383 (option A), which is stacked on #9381. Review only the top commit. Opened to compare two collab v2 layouts side by side. A Yjs 14 version of this layout is being prototyped as a separate package; numbers here are Yjs 13.

TL;DR

Root cause The v2 binding mirrors the Lexical tree node for node in Yjs. When existing text changes parent (wrapping it in a link or mark, Enter, Backspace, paragraph → heading, list indent), Yjs can only delete and re-insert those characters, so a peer's concurrent edits to them are moved, lost or duplicated.
Option A (#9383) Keep the nesting, but store links and text formats as Yjs formats on the existing characters. Fixes the inline races.
Option B (this PR) A plus: a container's lines (paragraph, heading, quote, list item) share one Yjs sequence, each ending in a block marker that carries its type and properties. Fixes the block-level races too.
Cost of B Larger docs (about 1.2-1.7×) and slower fresh loads; some large-list operations still scale with the list length.

Why wrapping text loses edits

flowchart TB
  subgraph today["Today: link is its own element"]
    direction LR
    t1["XmlText<br/>'Revenue grew 4% in Q3.'"] -->|"link 'grew 4%'"| t2["'Revenue ' + link▸'grew 4%' + ' in Q3.'<br/>14 chars deleted and re-inserted"] --> t3["peer typing inside or after<br/>jumps to 'Revenue |' or is lost"]
  end
  subgraph fmt["A / B: link is a format"]
    direction LR
    f1["XmlText<br/>'Revenue grew 4% in Q3.'"] -->|"link 'grew 4%'"| f2["same characters<br/>+ 2 format markers"] --> f3["peer's text stays<br/>where it was typed"]
  end
  today ~~~ fmt
  style t3 fill:#ffe3e3,stroke:#c92a2a
  style f3 fill:#d3f9d8,stroke:#2b8a3e
Loading

The same mechanism explains the block races: Enter moves the tail into a new paragraph, Backspace moves the second paragraph's text into the first, paragraph → heading replaces the element. B extends "don't move characters" to those.

Option A vs option B (same Lexical tree, different Yjs layout)

A: nested nodes (#9383). One Yjs container per Lexical block; each block's text is its own sequence.

flowchart TB
  Ar["root"] --> Ap["paragraph"] --> Apt["'Revenue grew 4% in Q3.'<br/>(+ link format)"]
  Ar --> Ah["heading h2"] --> Aht["'Plan'"]
  Ar --> Al["list (bullet)"] --> Ali1["listitem"] --> Ali1t["'one'"]
  Al --> Ali2["listitem"] --> Ali2t["'two'"]
  Ar --> At["table → row → cell → paragraph → 'x'"]
Loading

B: block markers (this PR). A container's lines share one sequence; a ¶ marker ends each line and carries its attributes.

flowchart TB
  subgraph seq["root: ONE sequence, read in order"]
    direction TB
    subgraph r1[" "]
      direction LR
      s1["'Revenue grew 4% in Q3.'"] --- m1["¶ paragraph"]
    end
    subgraph r2[" "]
      direction LR
      s2["'Plan'"] --- m2["¶ heading h2"]
    end
    subgraph r3[" "]
      direction LR
      s3["'one'"] --- m3["¶ listitem L1"]
      s4["'two'"] --- m4["¶ listitem L1"]
    end
    subgraph r4[" "]
      direction LR
      e1["▣ table (nested): row → cell → its own sequence"]
    end
    r1 ~~~ r2 ~~~ r3 ~~~ r4
  end
  style m1 fill:#fff4e6,stroke:#e8590c
  style m2 fill:#fff4e6,stroke:#e8590c
  style m3 fill:#fff4e6,stroke:#e8590c
  style m4 fill:#fff4e6,stroke:#e8590c
  style e1 fill:#e5dbff,stroke:#7048e8
Loading

In B, Enter inserts one ¶, Backspace deletes one ¶, and heading/quote/indent/list type change only change ¶ attributes, so no characters move. Lists are not stored; they are rebuilt from consecutive list-item markers. Tables, cells, slots and any undeclared block stay nested exactly as in A.

Per kind of node (declared in $config; undeclared = nested, as in A)

Kind Examples A stores it as B stores it as
Inline annotation link, autolink, bold; comments via NodeState (#9380) formats on characters formats on characters
Line paragraph, heading, quote, list item own XmlElement + XmlText ¶ marker in the parent's sequence
Group list own XmlElement not stored; rebuilt from markers
Container table, row, cell, slots, custom blocks own XmlElement own XmlElement, embedded
Atomic image, mention, equation embed embed

Declarations: A adds collab: {inline: 'format'}; B adds collab: {block: 'line' | {mode: 'group', items, key, derived, nested}}. B is A plus the block field, so B can be adopted one node type at a time.

Concurrent races

Headless, 2 and 3 peers, pinned client ids in both orders, per-sender in-order delivery; PASS also requires a fresh reader to match.

xychart-beta
  title "Races passed (of 17)"
  x-axis ["main v2", "A (#9383)", "B (this PR)"]
  y-axis "passed" 0 --> 17
  bar [1, 6, 16]
Loading
Race (each while a peer types) main A B
Type inside a range ‖ peer links it; unlink; type after a link; undo own link ❌ ✅ ✅
Bold ‖ italic on overlapping text ❌ ✅ ✅
Paragraph → heading / quote ❌ ❌ ✅
Enter (split) with a peer typing in the tail ❌ ❌ ✅
Backspace (join) ❌ ❌ ✅
List indent; Enter in a list item ❌ ❌ ✅
List type change ✅ ✅ ✅
Rows inserted then a peer types; table cell ‖ cell ❌ ❌ ✅
Move ‖ type; move ‖ move ❌ ❌ ✅ ¹
Comment via MarkNode (not opted in; use #9380) ❌ ❌ ❌

¹ Text typed into a line while it is moved can land in its old neighbour; real moves still need a placement model.

Nested structures (collapsible > title + content, layouts, table cells with lists, slots, container directly inside container, 3-level nesting), 93 cases × 4 delivery orders:

pie showData
  title "B compared with A on nested cases"
  "B better" : 40
  "Same" : 51
  "B worse" : 2
Loading

Cost

Headless Node, 10k blocks, gc off, median; single runs on a shared Linux VM, p95 noisy.

main A B
Keystroke in a paragraph, incl. peer apply (ms) 54.3 59.7 50.3
Keystroke in a list item (ms) 59.9 58.9 50.5
Enter / Backspace (ms) 74.2 / 74.7 73.8 / 73.9 75.4 / 75.6
Paste a whole document into a live doc (ms) 894 974 1,260
Doc size (bytes) 872,754 1,006,407 1,391,890
Bytes added per typed char / Enter / Backspace 18 / 93 / 65 18 / 93 / 65 18 / 61 / 8
Fresh load (ms) 427 504 945
xychart-beta
  title "Doc size at 10k blocks (KB, gc off)"
  x-axis ["main v2", "A", "B"]
  y-axis "KB" 0 --> 1500
  bar [873, 1006, 1392]
Loading
  • About 80% of the keystroke time above is Lexical core walking the whole document's text twice per commit, in every configuration; with that walk skipped, paragraph keystrokes are about 7.1 (main), 8.2 (A) and 2.6 (B) ms. That is independent of collab and worth its own change.
  • Space is deterministic and matters most for deployments that never GC; a committed per-operation size test is planned for the Yjs 14 version.
  • B's remaining costs: very large lists (10k-item list: peer apply of Enter about 119 ms vs 68 ms on main, list type change about 332 ms vs 14 ms), list-heavy loads ~2× slower.
Known limits and follow-ups found by an audit of this prototype
  • A line switching to nested storage for one instance (e.g. a non-inline node inserted into a paragraph) can lose a peer's typing. Rule for the next version: storage kind follows the node class, never the instance.
  • Text directly inside a container before a block child is read as part of that block. Rule: always end a line with its marker, including leading text.
  • Leftover text can end up as a direct child of a block container. Rule: record a container's content kind when it is created.
  • Typing inside an inline element that is not a format (e.g. MarkNode) can drop non-text children on peers; a fix exists.
  • Subclasses with state outside their JSON schema lose it; the schema-completeness check must cover inline formats as well as lines.
  • Some import/format-all paths are quadratic in the number of containers or lines; fixes measured at roughly main's speed.
  • Decorators holding a nested editor (image captions) cannot be stored by any layout today.
  • A client from before this layout sees a B document as empty and can overwrite it; a version gate and a new root name are needed (planned for the Yjs 14 version, plus a converter for existing v1/v2 documents).

Open questions for maintainers

  • Block markers in a v2 option, or only in a new Yjs 14 binding?
  • The collab declaration shape in $config (inline, block: line, group with items / key / derived / nested).
  • Space budgets: which per-operation byte budgets should CI enforce?

Full commit message (design, decisions, test plan)

Description

PROTOTYPE, not for merge. Stacked on #9383 (opt-in v2 inline-format layout),
which is stacked on #9381. It exists so that the block-marker layout (option
B) can be compared side by side with the inline-format layout (option A) and
with the current v2 layout; it is opt-in and changes nothing for anyone who
does not ask for it.

Collab v2 stores every block as its own XmlElement holding its own XmlText.
Lexical expresses Enter, Backspace at the start of a block, a heading or
quote toggle and a list indent as node replacement and moves, so the binding
deletes characters from one shared type and re-creates them in another, and
whatever a collaborator typed concurrently in those characters moves to the
wrong block or is lost:

  • splitting a paragraph while a peer types in its tail leaves the typed text
    in the first half ("Revenue X" / "grew 4% in Q3.");
  • joining two paragraphs while a peer types in the second loses the typing;
  • turning a paragraph into a heading or a quote, indenting a list item, or
    pressing Enter inside a list item loses (or misplaces) concurrent typing in
    that block, and the same happens inside table cells and other containers.

This adds an opt-in layout for new documents, blockMarkers, on
createBindingV2__EXPERIMENTAL, useYjsCollaborationV2__EXPERIMENTAL and
CollaborationPluginV2__EXPERIMENTAL. It implies inlineFormats. In it:

  • Every shared element (the root, and every block that is not a line) holds
    exactly one Y.XmlText, its flow. A block declared
    $config({collab: {block: 'line'}}) is stored in its container's flow as
    its inline content (the [lexical][lexical-link][lexical-react][lexical-yjs] Feature: Opt-in v2 inline-format layout #9383 run: formats, links, "\n" line breaks, inline
    embeds) followed by a marker: one U+2029 character whose formatting
    attributes carry the line's type (bt), its serialization schema fields
    (b|<field>) and NodeState (b|s_<key>). A character and not an embed
    object, because formatting merges per key: a concurrent type change and
    indent of one line both apply, where replacing an immutable embed would
    duplicate the marker. A line is identified by its marker's Yjs id while
    that marker exists; a split gives the first part a new marker (the old one
    ends the second part), and a join keeps the second line's marker.
  • A block declared as a group ({mode: 'group', items, key, nested, derived}) is not stored. Its items' markers carry the group's type and
    key fields (bg, bg|<field>) and their nesting level (bl, always
    written, 0 included, so that a format boundary that a concurrent change
    drops next to an item cannot change the level of an item nobody edited).
    Readers rebuild the groups from consecutive items (equal key fields and
    level: one group; deeper level: a nested group in a wrapper item), and a
    node transform rebuilds locally edited groups in that same canonical shape.
    derived (an addition to the API first sketched for this prototype) names
    item fields that follow from the structure and are not stored: ListNode
    declares value and indent, since storing indent would make every read
    restructure the list.
  • Any other block (tables, rows, cells, code blocks, block decorators, a
    custom block) is an XmlElement embedded in its container's flow, with its
    own flow following the same rules, so a cell's paragraphs are lines in the
    cell's flow.
  • Writing diffs only what changed. Each flow keeps a cache of its units (the
    Yjs content of each line or embed) and an index from node key to unit, so
    the position of a line is a prefix sum recomputed lazily from the first
    unit that changed. A keystroke rewrites the one line it touched: one
    contiguous insert or delete found by diffing its content, then only the
    attributes that differ.
  • Structural changes are anchored on unit identity, never on characters
    alone. Units are matched by node key (the longest run in order). A matched
    line whose content did not change is an anchor no diff crosses; if only
    its marker changed (a type, list type, level or checked change) its marker
    is formatted. A line or embed that lost its key and whose content is not
    in the rewritten lines next to it (a removed line, a moved block) is
    deleted exactly: its own characters and marker, never a neighbour's. Only
    the units of a split, a join or a type change are diffed by characters
    together, so Enter inserts a marker into the line it splits, Backspace at
    the start of a line deletes one, and concurrent typing in the characters
    involved is kept. A moved block is a delete and reinsert of its content.
    Format operations of a structural change are applied as one delta, and
    large insertions (a paste) as one delta.
  • Reading locates a remote change from the items its transaction inserted
    and deleted in the flow (each belongs to the unit whose marker or embed
    follows it; a format reaches to the next format of its key; many items are
    located in one pass over the flow), without the event delta, which Yjs
    computes by walking the whole flow. Only the touched units are read back,
    with one walk that starts at the previous unit's marker. Line nodes are
    reused by marker id, then by order; a line whose content and marker did
    not change is left alone. A change that keeps the line count and the group
    structure updates the lines in place; otherwise only the changed units are
    read and the group items around them are regrouped from the cache. Groups
    rebuilt by a read are refreshed by one update so their own transforms
    (list numbering) run.
  • A U+2029 that arrives without a marker type (its formatting lost to a
    concurrent change) ends a paragraph in a container of lines, so U+2029
    never shows up in Lexical text there; U+2029 typed into text is written as
    U+2028 and the local text is changed to match.
  • Cursors: Lexical points map to positions in the flows and back.

Adoption follows #9383. initializeInlineFormatLayout__EXPERIMENTAL marks an
empty document with layout version 2 (and creates the root flow in the same
transaction) when the binding has blockMarkers; the React plugin calls it
after the provider's first sync. Unmarked documents keep their layout.
getInlineFormatLayoutState__EXPERIMENTAL returns 'blocks' for such a
document. Older clients: a client that only has #9383 sees version 2 as a
newer layout, makes the editor read-only, reports it through onWarn (and
its reader calls onError twice) and shows the document empty; a client
from before #9383 also shows it empty and stays editable, so documents in
this layout must only be opened by upgraded clients.

Core: CollabNodeConfig (the collab key of $config, from #9383) gets
block?: 'node' | 'line' | CollabBlockGroupConfig, inherited per key and
read with getDeclaredCollabConfig, which never throws. The hints are
validated where they are used, in @lexical/yjs and only in this layout: a
'line' or group must be an ElementNode, a line cannot declare slots, a
group needs key fields and its items must be lines; and the hint is only
honored for classes whose serialization is schema-complete (the declaring
class, and subclasses below it that declare their own $config() and do not
hand-write exportJSON or updateFromJSON), since a marker stores only
schema fields and NodeState. Anything else is stored as a node, with a
development warning; an instance whose children are not all inline, or that
hosts slots, is stored as a node too. Declarations: ParagraphNode,
HeadingNode, QuoteNode and ListItemNode are lines; ListNode is a group of
ListItemNode with key listType, start, nested, and value and indent
derived. Flow types are added for the new types and options. All of it is
@experimental.

Supported: split, join, partial joins (a delete across lines), heading,
quote and paragraph toggles, list type changes, list indent and outdent,
Enter inside list items, check state, alignment, indent and NodeState of
lines, removing lines and blocks, moving blocks (text a peer types into a
line while it is moved lands in the line's old neighbour, as in #9383), links
and formats (#9383),
tables and other containers recursively, block and inline decorators, undo,
cursors.

Falls back (stored as a node): a line that gets a block child or a slot, a
subclass that is not schema-complete, a group with a child that is not one
of its items or is empty. A container's inline children mixed with lines are
read without rebuilding their links.

Known limits:

  • Marker attributes merge per key. A split racing a type change leaves one
    half with the old type (the new marker carries the splitter's view); a
    list type change racing Enter splits the list in two; concurrent changes to
    one line can combine attributes from different clients.
  • Text typed into a line that a peer removes concurrently joins the next
    line (the removed marker is gone, so the text belongs to the next one); at
    the end of a container it becomes a paragraph.
  • A group's fields other than its key fields, and its NodeState, are not
    synchronized; derived item fields (list numbering) are recomputed by each
    client's transforms.
  • A structural change to a group (Enter, Backspace, indent, outdent in a
    list) costs time proportional to the group's size on both sides (Lexical's
    own list numbering already does on the local side); see the tables.
  • Documents are larger (1.1x to 1.6x the default layout in the benchmarks
    below) and fresh loads take up to 2x as long.
  • Version snapshots (DIFF_VERSIONS_COMMAND) are rendered without reusing
    nodes.
  • Only exercised in Node with in-memory providers: not in browsers, with
    IME, or against a real network provider.

Performance. Headless, Node, one shared Linux VM (load average 4 to 8), so
timings are approximate. Binding time only, median: "write" is
syncLexicalUpdateToYjsV2__EXPERIMENTAL, "read" is
syncYjsChangesToLexicalV2__EXPERIMENTAL including Lexical's own update and
the refresh update; a Lexical update alone costs about 10 ms at 10,000
blocks. Default and inline-format columns from the same harness on their
branches.

A list of 10,000 items (write / read, ms; "B before" is the first
version of this prototype):

                         default         inline formats  B before          B
keystroke                6.2 / 9.0       7.2 / 10.4      1.2 / 244         1.1 / 10.9
Enter                    333 / 68        386 / 67        141 / 459         43 / 119
Backspace join           333 / 72        392 / 74        137 / 452         43 / 123
indent                   386 / 62        452 / 60        143 / 565         46 / 172
outdent                  387 / 66        458 / 71        139 / 454         44 / 121
list type change         15 / 14         18 / 15         7751 / 4899       75 / 332
fresh load               663             709             1136              996

10,000 paragraphs:

                         default         inline formats  B before          B
keystroke                7.0 / 11.1      6.4 / 9.9       0.9 / 9.8         0.8 / 9.4
Enter                    7.6 / 23.2      7.0 / 21.3      4.9 / 11.4        8.6 / 12.2
Backspace join           6.9 / 22.8      7.1 / 21.6      4.3 / 11.7        7.2 / 11.9
fresh load               545             549             447               490
document size            740 KB          740 KB          919 KB            919 KB

At 1,000 list items, B's Enter is 4.8 / 11.7 ms and a list type change
9.5 / 35 ms. In a list, a structural change still costs time proportional
to the list on both sides: the local transforms (numbering, canonical
grouping) and, on the reader, the refresh update that reruns them; the list
type change also reads every item's marker.

Side-by-side benchmark (two peers, a mixed document of headings, paragraphs
with links and bold, bullet lists, quotes and a table; median ms per edit
including the synchronous peer apply, or ms for the operation):

N = 10,000               default         inline formats  B before          B
keystroke, paragraph     54.3            59.7            53.6              50.3
keystroke, list item     59.9            58.9            88.4              50.5
Enter                    74.2            73.8            75.2              75.4
Backspace                74.7            73.9            75.0              75.6
paste whole doc (1 upd)  894             974             128,885           1,260
document size (bytes)    872,754         1,006,407       1,686,157         1,391,890
fresh load               427             504             949               945
N = 2,000: keystroke in a list item 8.6 / 8.8 / 14.5 / 8.7 ms; pasting the
whole document 208 / 200 / 4,990 / 338 ms.

About 77 to 80% of the per-keystroke time at 10,000 blocks is Lexical core
computing the text content of the whole document twice per commit, in every
configuration; B's own Yjs write is about 1 ms there.

Test plan

New and changed tests:

  • lexical-yjs/src/__tests__/unit/BlockMarkerLayoutV2.test.ts (147
    tests): headless v2 peers with pinned client ids, edited offline then
    synced, with per-sender in-order delivery (senders delivered in reverse
    order, one update at a time) and causal delivery, two peers in both id
    orders and three peers:
    • split ‖ type in the tail, join ‖ type, heading ‖ type, quote ‖ type,
      list indent ‖ type, list type change ‖ type, Enter inside a list item ‖
      type, link ‖ type, table cell paragraphs ‖ type, undeclared custom block
      ‖ type;
    • removals, three peers in four orders: remove a line ‖ clear the next
      line, remove a list item ‖ clear the next item, remove a line ‖ type in
      or bold the next line, remove an empty line ‖ type in the next empty line
      ‖ retype the title, remove a duplicate line ‖ quote the next line,
      typing into a removed line (the documented limit), outdent ‖ indent of
      one item leaving its neighbours alone;
    • 40 randomized three-peer runs (remove, type, Enter, Backspace, heading
      and quote toggles, bold) that check after every round that all peers and
      a fresh reader show the same tree, that no Lexical text holds U+2029,
      that the tokens of removed lines never come back, and that a line whose
      type one peer set, with no other structural change to it, keeps it;
    • declarations: a slot-declaring ParagraphNode subclass works with
      inlineFormats and with blockMarkers (stored as a node), and a legacy
      ParagraphNode subclass with a property outside its schema keeps it;
    • the flow's content, a round trip of a document with every node kind, a
      keystroke's update size, Enter and Backspace as marker insert and delete,
      retyping, re-indenting and a list type change inserting no characters,
      undo, outdent and check state ‖ typing, a line with a block child, a
      newer layout version read-only, and cursors.
      Each scenario checks the text, the same tree (exported JSON) on every
      peer, a fresh reader's tree, and one flow in the root.
  • SyncV2DefaultLayoutBytes.test.ts: the scripted session also runs with
    blockMarkers: false (default digest, recorded on the parent of [lexical][lexical-link][lexical-react][lexical-yjs] Feature: Opt-in v2 inline-format layout #9383) and
    with inlineFormats: true and inlineFormats: true, blockMarkers: false
    (digest 349f7f4948556b91, recorded by running this file on [lexical][lexical-link][lexical-react][lexical-yjs] Feature: Opt-in v2 inline-format layout #9383's
    commit); a binding with blockMarkers writes nothing for an editor's
    existing content.
  • LexicalCollabNodeConfig.test.ts: block declarations, per-key
    inheritance, and that reading hints never throws.
  • InlineFormatLayoutV2.test.ts: its "newer layout version" test uses
    version 3, since 2 is now the block-marker layout.

Before

The new scenarios with #9383's layout instead of blockMarkers, causal
delivery, ids 1,2 (-t restricted to the concurrency scenarios):

$ npx vitest --project unit --no-watch BlockMarkerLayoutV2 (with inlineFormats)
 FAIL  split ‖ type in the tail
Expected: "paragraph("Revenue ") / paragraph("grew 4%X in Q3.")"
Received: "paragraph("Revenue X") / paragraph("grew 4% in Q3.")"
 FAIL  join ‖ type
Expected: "paragraph("HelloWorld!")"
Received: "paragraph("HelloWorld")"
 FAIL  heading ‖ type
Received: "heading[h2]("Revenue grew 4% in Q3.")"
 FAIL  list indent ‖ type
Received: "list[bullet](listitem("one") listitem(list[bullet](listitem("two"))))"
 FAIL  Enter inside a list item ‖ type
Received: "list[bullet](listitem("one !") listitem("two"))"
 FAIL  table cell paragraphs (nested container) ‖ type
Received: "table(tablerow(tablecell(paragraph("cell!") paragraph(" one")) ...
 FAIL  remove a duplicate line ‖ quote the next line
Received: "paragraph("same") / paragraph("same") / quote("same")"
 FAIL  randomized intent checks > seed 1
AssertionError: expected 'ab Ka1 ab\n\nxyab Lb2 abab Mc3 ab...' not to contain 'Mc3'
      Tests  69 failed | 63 passed | 15 skipped (147)

The same test file on the first version of this prototype:

 FAIL  removals > remove a line ‖ clear the next line
Expected: "paragraph("alpha") / paragraph()"
Received: "paragraph("alpha") / paragraph("b\u2029")"
 FAIL  removals > remove a list item ‖ clear the next item
Received: "list[bullet](listitem("one")) / paragraph("t\u2029")"
 FAIL  removals > remove an empty line ‖ type in the next empty line ‖ retype the title
Received: "heading[h3]("Title") / paragraph() / paragraph("#B#y")"
 FAIL  removals > remove a duplicate line ‖ quote the next line
Received: "paragraph("same") / paragraph("same")"
 FAIL  removals > outdent ‖ indent of one item leaves its neighbours alone
AssertionError: expected [ 'two\n\nthree', +0 ] to deeply equal [ 'three', +0 ]
 FAIL  randomized intent checks > seed 4
Expected: "heading"
Received: "paragraph"
 FAIL  declarations > a subclass that declares slots is stored as a node, and A is unaffected
Error: getDeclaredCollabConfig: SlotParagraph declares collab.block "line" and slots; a line cannot host slots
 FAIL  declarations > a legacy subclass with a property outside its schema is stored as a node
AssertionError: expected '' to be 'bar'
      Tests  28 failed | 119 passed (147)

After

$ npx vitest --project unit --no-watch packages/lexical-yjs/src/__tests__/unit/BlockMarkerLayoutV2.test.ts packages/lexical-yjs/src/__tests__/unit/SyncV2DefaultLayoutBytes.test.ts packages/lexical/src/__tests__/unit/LexicalCollabNodeConfig.test.ts
 Test Files  3 passed (3)
      Tests  161 passed (161)

$ npx vitest --project unit --no-watch packages/lexical-yjs packages/lexical-react/src/__tests__/unit/Collab packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin packages/lexical-link packages/lexical-list packages/lexical-rich-text packages/lexical-mark packages/lexical/src
 Test Files  172 passed (172)
      Tests  3861 passed (3861)

$ pnpm run tsc                 # exit 0
$ pnpm run flow                # Found 0 errors
$ npx vitest --project scripts-unit --no-watch scripts/__tests__/unit/treeShakingSource.test.ts
      Tests  341 passed (341)

Out-of-tree scratch harnesses, not part of this commit:

  • Randomized convergence runs (typing, deleting, Enter, Backspace, heading,
    quote and paragraph toggles, list wrap, indent, outdent and type change,
    links, bold and italic, removing blocks, inserting tables and block
    decorators, undo; random offline rounds), each checking convergence, the
    same tree on every peer, a fresh reader, no U+2029 in Lexical text and
    removed lines staying removed: 2000/2000 runs each for two and three
    peers, causal and per-sender delivery. A reviewer's probe with lines that
    share letters (remove, clear, type, split, join, bold) found U+2029 in the
    text in 40/400 runs on the first version and 0/400 now.
  • A three-peer adversarial matrix (44 scenarios, four orders): the
    remaining differences from the intended result are the documented limits
    (split ‖ type change, list type change ‖ Enter, typing into a removed
    line).
  • A React side-by-side harness (three clients on the collaboration plugin,
    17 races, both client id orders, plus a fresh fourth client): default 1/17,
    inline formats 6/17, B 16/17 (the remaining failure is a comment MarkNode,
    which declares no collab hint).

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Oct 20, 2026
@vercel

vercel Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
lexical Ready Ready Preview Oct 20, 2026 6:01pm UTC
lexical-playground Ready Ready Preview Oct 20, 2026 6:01pm UTC

Request Review

@etrepum

etrepum commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator

Measuring space (bytes added to the yjs doc) is probably at least as important as measuring the time and is not a noisy measurement. A lot of yjs configurations aren't going to do any sort of GC by default so this can matter very quickly.

@zurfyx
zurfyx marked this pull request as ready for review October 20, 2026 15:52
…] Feature: Prototype block markers

## Description

PROTOTYPE, not for merge. Stacked on #9383 (opt-in v2 inline-format layout),
which is stacked on #9381. It exists so that the block-marker layout (option
B) can be compared side by side with the inline-format layout (option A) and
with the current v2 layout; it is opt-in and changes nothing for anyone who
does not ask for it.

Collab v2 stores every block as its own XmlElement holding its own XmlText.
Lexical expresses Enter, Backspace at the start of a block, a heading or
quote toggle and a list indent as node replacement and moves, so the binding
deletes characters from one shared type and re-creates them in another, and
whatever a collaborator typed concurrently in those characters moves to the
wrong block or is lost:

- splitting a paragraph while a peer types in its tail leaves the typed text
  in the first half (`"Revenue X" / "grew 4% in Q3."`);
- joining two paragraphs while a peer types in the second loses the typing;
- turning a paragraph into a heading or a quote, indenting a list item, or
  pressing Enter inside a list item loses (or misplaces) concurrent typing in
  that block, and the same happens inside table cells and other containers.

This adds an opt-in layout for new documents, `blockMarkers`, on
`createBindingV2__EXPERIMENTAL`, `useYjsCollaborationV2__EXPERIMENTAL` and
`CollaborationPluginV2__EXPERIMENTAL`. It implies `inlineFormats`. In it:

- Every shared element (the root, and every block that is not a line) holds
  exactly one Y.XmlText, its flow. A block declared
  `$config({collab: {block: 'line'}})` is stored in its container's flow as
  its inline content (the #9383 run: formats, links, "\n" line breaks, inline
  embeds) followed by a marker: one U+2029 character whose formatting
  attributes carry the line's type (`bt`), its serialization schema fields
  (`b|<field>`) and NodeState (`b|s_<key>`). A character and not an embed
  object, because formatting merges per key: a concurrent type change and
  indent of one line both apply, where replacing an immutable embed would
  duplicate the marker. A line is identified by its marker's Yjs id while
  that marker exists; a split gives the first part a new marker (the old one
  ends the second part), and a join keeps the second line's marker.
- A block declared as a group (`{mode: 'group', items, key, nested,
  derived}`) is not stored. Its items' markers carry the group's type and
  `key` fields (`bg`, `bg|<field>`) and their nesting level (`bl`, always
  written, 0 included, so that a format boundary that a concurrent change
  drops next to an item cannot change the level of an item nobody edited).
  Readers rebuild the groups from consecutive items (equal key fields and
  level: one group; deeper level: a nested group in a wrapper item), and a
  node transform rebuilds locally edited groups in that same canonical shape.
  `derived` (an addition to the API first sketched for this prototype) names
  item fields that follow from the structure and are not stored: ListNode
  declares `value` and `indent`, since storing `indent` would make every read
  restructure the list.
- Any other block (tables, rows, cells, code blocks, block decorators, a
  custom block) is an XmlElement embedded in its container's flow, with its
  own flow following the same rules, so a cell's paragraphs are lines in the
  cell's flow.
- Writing diffs only what changed. Each flow keeps a cache of its units (the
  Yjs content of each line or embed) and an index from node key to unit, so
  the position of a line is a prefix sum recomputed lazily from the first
  unit that changed. A keystroke rewrites the one line it touched: one
  contiguous insert or delete found by diffing its content, then only the
  attributes that differ.
- Structural changes are anchored on unit identity, never on characters
  alone. Units are matched by node key (the longest run in order). A matched
  line whose content did not change is an anchor no diff crosses; if only
  its marker changed (a type, list type, level or checked change) its marker
  is formatted. A line or embed that lost its key and whose content is not
  in the rewritten lines next to it (a removed line, a moved block) is
  deleted exactly: its own characters and marker, never a neighbour's. Only
  the units of a split, a join or a type change are diffed by characters
  together, so Enter inserts a marker into the line it splits, Backspace at
  the start of a line deletes one, and concurrent typing in the characters
  involved is kept. A moved block is a delete and reinsert of its content.
  Format operations of a structural change are applied as one delta, and
  large insertions (a paste) as one delta.
- Reading locates a remote change from the items its transaction inserted
  and deleted in the flow (each belongs to the unit whose marker or embed
  follows it; a format reaches to the next format of its key; many items are
  located in one pass over the flow), without the event delta, which Yjs
  computes by walking the whole flow. Only the touched units are read back,
  with one walk that starts at the previous unit's marker. Line nodes are
  reused by marker id, then by order; a line whose content and marker did
  not change is left alone. A change that keeps the line count and the group
  structure updates the lines in place; otherwise only the changed units are
  read and the group items around them are regrouped from the cache. Groups
  rebuilt by a read are refreshed by one update so their own transforms
  (list numbering) run.
- A U+2029 that arrives without a marker type (its formatting lost to a
  concurrent change) ends a paragraph in a container of lines, so U+2029
  never shows up in Lexical text there; U+2029 typed into text is written as
  U+2028 and the local text is changed to match.
- Cursors: Lexical points map to positions in the flows and back.

Adoption follows #9383. `initializeInlineFormatLayout__EXPERIMENTAL` marks an
empty document with layout version 2 (and creates the root flow in the same
transaction) when the binding has `blockMarkers`; the React plugin calls it
after the provider's first sync. Unmarked documents keep their layout.
`getInlineFormatLayoutState__EXPERIMENTAL` returns `'blocks'` for such a
document. Older clients: a client that only has #9383 sees version 2 as a
newer layout, makes the editor read-only, reports it through `onWarn` (and
its reader calls `onError` twice) and shows the document empty; a client
from before #9383 also shows it empty and stays editable, so documents in
this layout must only be opened by upgraded clients.

Core: `CollabNodeConfig` (the `collab` key of `$config`, from #9383) gets
`block?: 'node' | 'line' | CollabBlockGroupConfig`, inherited per key and
read with `getDeclaredCollabConfig`, which never throws. The hints are
validated where they are used, in `@lexical/yjs` and only in this layout: a
`'line'` or group must be an ElementNode, a line cannot declare slots, a
group needs key fields and its items must be lines; and the hint is only
honored for classes whose serialization is schema-complete (the declaring
class, and subclasses below it that declare their own `$config()` and do not
hand-write `exportJSON` or `updateFromJSON`), since a marker stores only
schema fields and NodeState. Anything else is stored as a node, with a
development warning; an instance whose children are not all inline, or that
hosts slots, is stored as a node too. Declarations: ParagraphNode,
HeadingNode, QuoteNode and ListItemNode are lines; ListNode is a group of
ListItemNode with key `listType`, `start`, nested, and `value` and `indent`
derived. Flow types are added for the new types and options. All of it is
`@experimental`.

Supported: split, join, partial joins (a delete across lines), heading,
quote and paragraph toggles, list type changes, list indent and outdent,
Enter inside list items, check state, alignment, indent and NodeState of
lines, removing lines and blocks, moving blocks (text a peer types into a
line while it is moved lands in the line's old neighbour, as in #9383), links
and formats (#9383),
tables and other containers recursively, block and inline decorators, undo,
cursors.

Falls back (stored as a node): a line that gets a block child or a slot, a
subclass that is not schema-complete, a group with a child that is not one
of its items or is empty. A container's inline children mixed with lines are
read without rebuilding their links.

Known limits:
- Marker attributes merge per key. A split racing a type change leaves one
  half with the old type (the new marker carries the splitter's view); a
  list type change racing Enter splits the list in two; concurrent changes to
  one line can combine attributes from different clients.
- Text typed into a line that a peer removes concurrently joins the next
  line (the removed marker is gone, so the text belongs to the next one); at
  the end of a container it becomes a paragraph.
- A group's fields other than its key fields, and its NodeState, are not
  synchronized; derived item fields (list numbering) are recomputed by each
  client's transforms.
- A structural change to a group (Enter, Backspace, indent, outdent in a
  list) costs time proportional to the group's size on both sides (Lexical's
  own list numbering already does on the local side); see the tables.
- Documents are larger (1.1x to 1.6x the default layout in the benchmarks
  below) and fresh loads take up to 2x as long.
- Version snapshots (`DIFF_VERSIONS_COMMAND`) are rendered without reusing
  nodes.
- Only exercised in Node with in-memory providers: not in browsers, with
  IME, or against a real network provider.

Performance. Headless, Node, one shared Linux VM (load average 4 to 8), so
timings are approximate. Binding time only, median: "write" is
`syncLexicalUpdateToYjsV2__EXPERIMENTAL`, "read" is
`syncYjsChangesToLexicalV2__EXPERIMENTAL` including Lexical's own update and
the refresh update; a Lexical update alone costs about 10 ms at 10,000
blocks. Default and inline-format columns from the same harness on their
branches.

A list of 10,000 items (`write / read`, ms; "B before" is the first
version of this prototype):

```
                         default         inline formats  B before          B
keystroke                6.2 / 9.0       7.2 / 10.4      1.2 / 244         1.1 / 10.9
Enter                    333 / 68        386 / 67        141 / 459         43 / 119
Backspace join           333 / 72        392 / 74        137 / 452         43 / 123
indent                   386 / 62        452 / 60        143 / 565         46 / 172
outdent                  387 / 66        458 / 71        139 / 454         44 / 121
list type change         15 / 14         18 / 15         7751 / 4899       75 / 332
fresh load               663             709             1136              996
```

10,000 paragraphs:

```
                         default         inline formats  B before          B
keystroke                7.0 / 11.1      6.4 / 9.9       0.9 / 9.8         0.8 / 9.4
Enter                    7.6 / 23.2      7.0 / 21.3      4.9 / 11.4        8.6 / 12.2
Backspace join           6.9 / 22.8      7.1 / 21.6      4.3 / 11.7        7.2 / 11.9
fresh load               545             549             447               490
document size            740 KB          740 KB          919 KB            919 KB
```

At 1,000 list items, B's Enter is 4.8 / 11.7 ms and a list type change
9.5 / 35 ms. In a list, a structural change still costs time proportional
to the list on both sides: the local transforms (numbering, canonical
grouping) and, on the reader, the refresh update that reruns them; the list
type change also reads every item's marker.

Side-by-side benchmark (two peers, a mixed document of headings, paragraphs
with links and bold, bullet lists, quotes and a table; median ms per edit
including the synchronous peer apply, or ms for the operation):

```
N = 10,000               default         inline formats  B before          B
keystroke, paragraph     54.3            59.7            53.6              50.3
keystroke, list item     59.9            58.9            88.4              50.5
Enter                    74.2            73.8            75.2              75.4
Backspace                74.7            73.9            75.0              75.6
paste whole doc (1 upd)  894             974             128,885           1,260
document size (bytes)    872,754         1,006,407       1,686,157         1,391,890
fresh load               427             504             949               945
N = 2,000: keystroke in a list item 8.6 / 8.8 / 14.5 / 8.7 ms; pasting the
whole document 208 / 200 / 4,990 / 338 ms.
```

About 77 to 80% of the per-keystroke time at 10,000 blocks is Lexical core
computing the text content of the whole document twice per commit, in every
configuration; B's own Yjs write is about 1 ms there.

## Test plan

New and changed tests:
- `lexical-yjs/src/__tests__/unit/BlockMarkerLayoutV2.test.ts` (147
  tests): headless v2 peers with pinned client ids, edited offline then
  synced, with per-sender in-order delivery (senders delivered in reverse
  order, one update at a time) and causal delivery, two peers in both id
  orders and three peers:
  - split ‖ type in the tail, join ‖ type, heading ‖ type, quote ‖ type,
    list indent ‖ type, list type change ‖ type, Enter inside a list item ‖
    type, link ‖ type, table cell paragraphs ‖ type, undeclared custom block
    ‖ type;
  - removals, three peers in four orders: remove a line ‖ clear the next
    line, remove a list item ‖ clear the next item, remove a line ‖ type in
    or bold the next line, remove an empty line ‖ type in the next empty line
    ‖ retype the title, remove a duplicate line ‖ quote the next line,
    typing into a removed line (the documented limit), outdent ‖ indent of
    one item leaving its neighbours alone;
  - 40 randomized three-peer runs (remove, type, Enter, Backspace, heading
    and quote toggles, bold) that check after every round that all peers and
    a fresh reader show the same tree, that no Lexical text holds U+2029,
    that the tokens of removed lines never come back, and that a line whose
    type one peer set, with no other structural change to it, keeps it;
  - declarations: a slot-declaring ParagraphNode subclass works with
    `inlineFormats` and with `blockMarkers` (stored as a node), and a legacy
    ParagraphNode subclass with a property outside its schema keeps it;
  - the flow's content, a round trip of a document with every node kind, a
    keystroke's update size, Enter and Backspace as marker insert and delete,
    retyping, re-indenting and a list type change inserting no characters,
    undo, outdent and check state ‖ typing, a line with a block child, a
    newer layout version read-only, and cursors.
  Each scenario checks the text, the same tree (exported JSON) on every
  peer, a fresh reader's tree, and one flow in the root.
- `SyncV2DefaultLayoutBytes.test.ts`: the scripted session also runs with
  `blockMarkers: false` (default digest, recorded on the parent of #9383) and
  with `inlineFormats: true` and `inlineFormats: true, blockMarkers: false`
  (digest `349f7f4948556b91`, recorded by running this file on #9383's
  commit); a binding with `blockMarkers` writes nothing for an editor's
  existing content.
- `LexicalCollabNodeConfig.test.ts`: block declarations, per-key
  inheritance, and that reading hints never throws.
- `InlineFormatLayoutV2.test.ts`: its "newer layout version" test uses
  version 3, since 2 is now the block-marker layout.

### Before

The new scenarios with #9383's layout instead of `blockMarkers`, causal
delivery, ids 1,2 (`-t` restricted to the concurrency scenarios):

```
$ npx vitest --project unit --no-watch BlockMarkerLayoutV2 (with inlineFormats)
 FAIL  split ‖ type in the tail
Expected: "paragraph("Revenue ") / paragraph("grew 4%X in Q3.")"
Received: "paragraph("Revenue X") / paragraph("grew 4% in Q3.")"
 FAIL  join ‖ type
Expected: "paragraph("HelloWorld!")"
Received: "paragraph("HelloWorld")"
 FAIL  heading ‖ type
Received: "heading[h2]("Revenue grew 4% in Q3.")"
 FAIL  list indent ‖ type
Received: "list[bullet](listitem("one") listitem(list[bullet](listitem("two"))))"
 FAIL  Enter inside a list item ‖ type
Received: "list[bullet](listitem("one !") listitem("two"))"
 FAIL  table cell paragraphs (nested container) ‖ type
Received: "table(tablerow(tablecell(paragraph("cell!") paragraph(" one")) ...
 FAIL  remove a duplicate line ‖ quote the next line
Received: "paragraph("same") / paragraph("same") / quote("same")"
 FAIL  randomized intent checks > seed 1
AssertionError: expected 'ab Ka1 ab\n\nxyab Lb2 abab Mc3 ab...' not to contain 'Mc3'
      Tests  69 failed | 63 passed | 15 skipped (147)
```

The same test file on the first version of this prototype:

```
 FAIL  removals > remove a line ‖ clear the next line
Expected: "paragraph("alpha") / paragraph()"
Received: "paragraph("alpha") / paragraph("b\u2029")"
 FAIL  removals > remove a list item ‖ clear the next item
Received: "list[bullet](listitem("one")) / paragraph("t\u2029")"
 FAIL  removals > remove an empty line ‖ type in the next empty line ‖ retype the title
Received: "heading[h3]("Title") / paragraph() / paragraph("#B#y")"
 FAIL  removals > remove a duplicate line ‖ quote the next line
Received: "paragraph("same") / paragraph("same")"
 FAIL  removals > outdent ‖ indent of one item leaves its neighbours alone
AssertionError: expected [ 'two\n\nthree', +0 ] to deeply equal [ 'three', +0 ]
 FAIL  randomized intent checks > seed 4
Expected: "heading"
Received: "paragraph"
 FAIL  declarations > a subclass that declares slots is stored as a node, and A is unaffected
Error: getDeclaredCollabConfig: SlotParagraph declares collab.block "line" and slots; a line cannot host slots
 FAIL  declarations > a legacy subclass with a property outside its schema is stored as a node
AssertionError: expected '' to be 'bar'
      Tests  28 failed | 119 passed (147)
```

### After

```
$ npx vitest --project unit --no-watch packages/lexical-yjs/src/__tests__/unit/BlockMarkerLayoutV2.test.ts packages/lexical-yjs/src/__tests__/unit/SyncV2DefaultLayoutBytes.test.ts packages/lexical/src/__tests__/unit/LexicalCollabNodeConfig.test.ts
 Test Files  3 passed (3)
      Tests  161 passed (161)

$ npx vitest --project unit --no-watch packages/lexical-yjs packages/lexical-react/src/__tests__/unit/Collab packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin packages/lexical-link packages/lexical-list packages/lexical-rich-text packages/lexical-mark packages/lexical/src
 Test Files  172 passed (172)
      Tests  3861 passed (3861)

$ pnpm run tsc                 # exit 0
$ pnpm run flow                # Found 0 errors
$ npx vitest --project scripts-unit --no-watch scripts/__tests__/unit/treeShakingSource.test.ts
      Tests  341 passed (341)
```

Out-of-tree scratch harnesses, not part of this commit:
- Randomized convergence runs (typing, deleting, Enter, Backspace, heading,
  quote and paragraph toggles, list wrap, indent, outdent and type change,
  links, bold and italic, removing blocks, inserting tables and block
  decorators, undo; random offline rounds), each checking convergence, the
  same tree on every peer, a fresh reader, no U+2029 in Lexical text and
  removed lines staying removed: 2000/2000 runs each for two and three
  peers, causal and per-sender delivery. A reviewer's probe with lines that
  share letters (remove, clear, type, split, join, bold) found U+2029 in the
  text in 40/400 runs on the first version and 0/400 now.
- A three-peer adversarial matrix (44 scenarios, four orders): the
  remaining differences from the intended result are the documented limits
  (split ‖ type change, list type change ‖ Enter, typing into a removed
  line).
- A React side-by-side harness (three clients on the collaboration plugin,
  17 races, both client id orders, plus a fresh fourth client): default 1/17,
  inline formats 6/17, B 16/17 (the remaining failure is a comment MarkNode,
  which declares no `collab` hint).
@pkg-pr-new

pkg-pr-new Bot commented Oct 20, 2026

Copy link
Copy Markdown
lexical

npm i https://pkg.pr.new/lexical@9386
yarn add https://pkg.pr.new/[email protected]

@lexical/a11y

npm i https://pkg.pr.new/@lexical/a11y@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/clipboard

npm i https://pkg.pr.new/@lexical/clipboard@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/code

npm i https://pkg.pr.new/@lexical/code@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/code-core

npm i https://pkg.pr.new/@lexical/code-core@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/code-prism

npm i https://pkg.pr.new/@lexical/code-prism@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/code-shiki

npm i https://pkg.pr.new/@lexical/code-shiki@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/compiler

npm i https://pkg.pr.new/@lexical/compiler@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/devtools-core

npm i https://pkg.pr.new/@lexical/devtools-core@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/dragon

npm i https://pkg.pr.new/@lexical/dragon@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/eslint-plugin

npm i https://pkg.pr.new/@lexical/eslint-plugin@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/extension

npm i https://pkg.pr.new/@lexical/extension@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/fast-check

npm i https://pkg.pr.new/@lexical/fast-check@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/file

npm i https://pkg.pr.new/@lexical/file@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/hashtag

npm i https://pkg.pr.new/@lexical/hashtag@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/headless

npm i https://pkg.pr.new/@lexical/headless@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/history

npm i https://pkg.pr.new/@lexical/history@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/html

npm i https://pkg.pr.new/@lexical/html@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/internal

npm i https://pkg.pr.new/@lexical/internal@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/link

npm i https://pkg.pr.new/@lexical/link@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/list

npm i https://pkg.pr.new/@lexical/list@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/mark

npm i https://pkg.pr.new/@lexical/mark@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/markdown

npm i https://pkg.pr.new/@lexical/markdown@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/mdast

npm i https://pkg.pr.new/@lexical/mdast@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/offset

npm i https://pkg.pr.new/@lexical/offset@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/overflow

npm i https://pkg.pr.new/@lexical/overflow@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/plain-text

npm i https://pkg.pr.new/@lexical/plain-text@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/react

npm i https://pkg.pr.new/@lexical/react@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/rich-text

npm i https://pkg.pr.new/@lexical/rich-text@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/selection

npm i https://pkg.pr.new/@lexical/selection@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/table

npm i https://pkg.pr.new/@lexical/table@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/tailwind

npm i https://pkg.pr.new/@lexical/tailwind@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/text

npm i https://pkg.pr.new/@lexical/text@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/utils

npm i https://pkg.pr.new/@lexical/utils@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

@lexical/yjs

npm i https://pkg.pr.new/@lexical/yjs@9386
yarn add https://pkg.pr.new/@lexical/[email protected]

commit: 095ed3f

zurfyx added a commit that referenced this pull request Oct 20, 2026
…ding with block markers

## Description

PROTOTYPE, not for merge. Stacked on #9386 (block markers on Yjs 13), whose
`$config({collab})` declarations it reuses. It shows the block-marker data
model on Yjs 14 (`@y/y`), as a new experimental package, `@lexical/y`.
`@lexical/yjs` (Yjs 13) is unchanged: Yjs 14 is a different npm package, so
a Yjs 14 binding cannot replace it in place.

Entries (all `@experimental`):
- `@lexical/y`: `YBinding`, `YCollabExtension` (binding, collaborative undo,
  `status` signal; conflicts with the history extensions),
  `writeEditorToYDoc` (headless writer for converters), `createYDoc`,
  `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and the types `YBindingOptions`,
  `YBindingStatus`, `YCursor`, `YCollabConfig`, `ClientIDRange`. No React,
  no DOM requirement.
- `@lexical/y/server`: `inspectUpdateRoots`, `isUpdateForLayout`,
  `writeUpgradeNotice`, `UpdateRoots`. No editor dependencies.
- `@lexical/y/migrate` is reserved for a converter from the Yjs 13 layouts.

`@y/y` is a peer dependency pinned to 14.0.0-rc.28, the newest release the
repository's minimum release age (7 days) allowed when this was written
(npm's `latest` tag points at an older release candidate).

Core: `CollabNodeConfig.content?: 'block' | 'inline'` (what a block node
stored as its own node holds), declared `'inline'` on CodeNode.

Data model (the semantics of #9386):
- Shared root `doc.get('lexical-y')`, a new root name, with a layout version
  attribute. The editor stays read only until that record has been read; a
  newer version, or content without a version, stays read only.
- `initialize()` (after the provider's first sync) marks only an empty root.
  It refuses when an older layout's root (`root`, `root-v2`) has content
  other than an upgrade notice (convert it: `writeEditorToYDoc` writes the
  layout root next to the old one). The initial content is written with a
  client id hashed from the layout version and the content, so two clients
  initializing the same content at once write it once, and outside the undo
  history.
- Every container (the root and every node stored as its own Y.Node) holds
  one sequence of text, child nodes and line markers (Yjs 14 Y.Node children
  are unified, so no XmlText per container is needed).
- A line (declared `'line'`, schema-complete) is its inline content followed
  by a marker: a child `Y.Node` named `¶` whose map attributes hold the
  line's type (left out for a paragraph), schema fields (minus derived),
  NodeState, and for a group item the group type, key fields and level. Not
  a character with formats (#9386's U+2029) and not an embed:
  * map attributes merge per key (last writer wins), so a concurrent heading
    change and indent both apply, without format start/end items in the
    sequence;
  * the marker's identity (its item) never changes when its attributes do,
    where an immutable embed would have to be replaced (and could be
    duplicated by concurrent replacements);
  * block attributes never mix with inline formats, and text may contain
    any character.
- Groups (lists) are rebuilt from consecutive items; local groups are kept
  in the same canonical shape by a transform (adjacent equal groups and
  wrapper items merged, empty groups removed); derived fields (list
  numbering) are recomputed by a refresh update on every client. All of a
  group's synced fields (and NodeState) identify it; a nested item's marker
  also records its outer groups and their wrapper items' fields (`o`), so an
  indented first item keeps its outer list's type and the wrappers' fields
  sync.
- Storage follows the class, never the instance: a declared line stays a
  line even with a block child (the child is stored as a node inside its
  content). Undeclared or invalid blocks are `b:<type>` child nodes with the
  class's own (compact) JSON as attributes; inline elements that are not
  formats and inline decorators are `i:<type>` children.
- A container records what it holds (`c`: blocks or inline content) when it
  is created, from `collab.content` or its children, and never changes it:
  leftover inline content of a block container reads as a paragraph on every
  reader; inline content directly in a block container is always ended by a
  `¦` terminator.
- Inline wrappers declared `inline: 'format'` are one format key each
  (`w:link`, whose value holds the wrapper's fields); text formats are one
  key per format (`f:bold`), plus type, JSON fields, NodeState and, for text
  nodes Lexical would not merge, a segment key (`k`). Formats apply to any
  child, so a link can span a line break or an inline decorator; a line
  break's NodeState is a format of its `\n`. Two adjacent equal links keep an
  instance key (`#`) so they stay two links on every peer.
- NodeState equal to its default is not stored (setting it back deletes
  the key). Element `textFormat`/`textStyle` are always stored.
- Schema completeness (own `$config()`, no hand-written `exportJSON`,
  `updateFromJSON` or `afterCloneFrom` below the declaring class) is
  required for lines, groups and inline formats; anything else is a node.
- Editor instances (nested caption editors) are not synchronized; JSON
  snapshots of them are (members that JSON would drop are dropped).
- A class with a hand-written serialization is a node; an edit to one of its
  own fields alone is written (the whole node's JSON is compared) and read
  through `updateFromJSON`, then `importJSON` for fields it does not know.
- Unknown types fail closed: a client that meets a node, line, text or
  group type it does not register goes read only with a warning, so it never
  hides and later deletes content it cannot show.

Write path:
- Anchored edits: Y.Node#insert/delete/format walk the type from its start
  on every call in rc.28, so the binding edits the sequence from the item it
  knows (the previous line's marker) with a port of Yjs' text position
  algorithm. A test runs random operations through it and through
  Y.Node#applyDelta and requires identical documents (byte for byte).
- A keystroke (one text node of a line changed, same formats) diffs only
  that node's old and new text and writes at its offset: cost in the line's
  items, not its length (0.4 ms in a 200,000-character paragraph).
- Identity-anchored structure: units matched by node key (LIS); a line
  whose content did not change (node identity against the previous state,
  inline elements included) is never diffed; removed or moved units are
  deleted exactly; only split, join and type-change segments are diffed,
  as one sequence of the segment's items with the caret as the diff anchor:
  text that moved to another line keeps its items (no re-insert of a moved
  tail, so text a peer deleted is not resurrected). Diffs never split a
  surrogate pair. A Lexical node replaced in place by a new one of the same
  type keeps its shared node. Enter inserts a marker, Backspace deletes one, a type, indent
  or list type change only sets marker attributes.
- Structure is read from node links (the root is always marked dirty);
  attributes are written only for changed keys; inserted content carries its
  formats (no reformat after insert); format passes walk runs, not
  characters.
- Development self-check (default on outside production; `selfCheck` and
  `selfCheckSample` for production): every line a write touched is read back
  from Yjs, and every container a structural write touched is read whole
  into a fresh editor and compared with the editor's JSON (node types, list
  structure, wrapper fields, NodeState); mismatches go to the editor's
  `onWarn`. All tests run with it and fail on a warning.

Read path: a pending local `editor.update()` is committed before a remote
transaction is read; changed items are bucketed by container once per
transaction;
each changed item is located by walking to the next end item; text edits
update lines in place; structural changes re-parse only the touched units
(groups next to them are regrouped without re-reading untouched lines);
formats that span a marker propagate only while the value at the next unit's
start changes (re-reading the next unit as a region when it cannot be
updated in place); an inline element that cannot be empty is not shown when
peers deleted all its content; NodeState keys are read in sorted order. The local selection
is captured as relative positions before each remote transaction (a caret
anchored to the character on its left, a range to its edge characters) and
restored in the same update. While the local editor is composing (IME), remote
inserts into the composing line are applied to Yjs but not to that line's
nodes (the browser composes into their DOM); readers and writers of that
line skip those ids, and the line is read again when the composition ends
(deletions, formats and structure in the composing line are read at once).
A text diff with a run of equal characters places the change at the caret
(a space typed next to a space), and never splits a surrogate pair.
Follow-up updates (list renumbering, and
padding a table row that a concurrent column insert left short, done only by
the client that created the row) are kept out of the undo history.

Containers opt out of Yjs' remote formatting cleanup, which rescans every
type with formats after a remote format change (O(document) here): the
binding marks its containers as having no formats before Yjs decides. The
document's `cleanupFormatting` flag and the app's other types are untouched.

Servers on yrs before 0.28 read client ids as 32-bit numbers, while Yjs 14
draws 53-bit ones: such a server stores an author's content under a
truncated id, and the author receives its own content back as another
client's on reconnect, duplicating it (verified with ywasm 0.23.5; 0.28.0 is
fine). Opt-in compatibility: `clientIDRange: 'uint32'` (binding, extension,
`writeEditorToYDoc`) or `createYDoc({compat: 'yrs-0.23'})` keeps the
document's client id in 32 bits, including when Yjs draws a new one; the id
the binding uses for the initial content is always 32-bit. The default,
`'uint53'`, leaves Yjs 14's ids unchanged.

Undo: Yjs 14 UndoManager on the root, tracking only this binding's writes; a
container this client created that holds another client's content is kept
whole by undo (its fields and own content too).
Cursors: `getCursor()` / `$resolveCursor()` (relative positions on items;
no provider wiring or rendering).

`@y/y` internals used (all in rc.28; a bump must re-run the cursor
equivalence test): `new Item(...)`, `item.integrate`, `getItemCleanStart`,
`createID`, `Item.left/right/origin/rightOrigin/parent/content/deleted/
countable/length`, `YNode._start`, `_item`, `_map`, `_length`,
`_searchMarker`, `_hasFormatting`, `_legacyTypeRef` (upgrade notice), the
`beforeObserverCalls` event, `doc.store.getItem/getClock`,
`iterateStructsByIdSet`, `decodeUpdate`, `findRootTypeKey`.

Supported: split, join, partial joins, heading/quote/paragraph, list type,
indent/outdent, Enter in list items, checked state, alignment and NodeState
of lines, links and other inline formats (incl. property changes and spans
across line breaks), text formats, comments as NodeState, tables and any
nested containers (collapsible-like container > title + content, cell >
collapsible, box > box), block and inline decorators, inline elements
(MarkNode) with nested content, undo/redo, cursors, local selection across
remote edits.

Known limits:
- A move is a delete and a reinsert: text a peer types into a moved line
  lands in its old neighbour.
- MarkNode is an element with its own content: wrapping a range moves the
  text into it, and concurrent typing in that range stays outside. Comments
  should use per-id NodeState (MarkStateExtension).
- A split racing a type change gives the first half the splitter's type;
  text typed into a line a peer removed joins the next line.
- Slots are not synchronized; a link's fields merge as a whole (last
  writer wins).
- Yjs format semantics: bold ‖ bold on adjacent ranges of one line can leave
  part unformatted (the same on Yjs 13).
- A join ‖ removal of the joined line also joins the next line (nothing
  deleted comes back); unwrapping a container ‖ typing in it keeps the
  container; text typed inside a container a peer removed is lost (delete
  wins).
- Two clients initializing with different content at once both keep their
  content (converged); a row padded by its creator only if that client is
  still around (its client id).
- Several edits to one line in a single update are written as one replace
  (a peer's caret inside it moves to the edge).
- Structural edits in a large list cost time proportional to the list on
  both sides (regrouping and renumbering): about 4x main end to end at 10,000
  items. Enter at 10,000 blocks (core text walk skipped) is 26.4 ms against
  main's 19.6 ms.
- Relies on the @y/y internals listed above.
- Version gate: the layout version must be an integer from 1 to
  `LAYOUT_VERSION`; anything else is read only.
- With Yjs 14's default 53-bit client ids, servers on yrs before 0.28
  duplicate content on reconnect; use the opt-in 32-bit range for them.

Known open issues (being fixed, from randomized runs; see Fuzz below):
- A list item holding a paragraph (a list inserted inside a container):
  unlisting it or changing its type ‖ the same or typing in it can keep the
  paragraph twice or lose the typed text.
- Rare text fragments after a join racing a type change (a token split by
  a marker), and a few duplicated or lost tokens in seeds that mix block
  moves with other structure.
- Rare self-check mismatches of an element's `textFormat` after concurrent
  list edits, and a NodeState comment divergence in one gc seed.

## Test plan

### Before

The Yjs 13 layouts on the same scenarios, from their own branches: main v2,
#9383 and #9386 lose or misplace concurrent typing on split, join, retype,
indent and nested containers (#9386 fixes most of them on Yjs 13); bytes per
operation are in the table below.

### After

New tests in `packages/lexical-y/src/__tests__/unit` (headless peers with
pinned client ids, offline edits then sync, both id orders, causal and
per-sender delivery, two and three peers; every case checks every peer, a
fresh reader, no exception and no self-check warning):
- `BlockMarkers.test.ts`: split, join, heading, quote, list indent, list
  type, Enter in a list item, link, table cell, custom block, removals with
  three peers, and 40 randomized intent seeds;
- `Races.test.ts`: links, unlink, undo of a link, overlapping formats,
  heading/quote/split/join/indent/list type/Enter races, moves, table rows
  and cells, row insert ‖ column insert, MarkNode; moves and MarkNode are
  documented limits (converged, intent not kept);
- `Nested.test.ts`, `NestedFuzz.test.ts`: collapsible-like containers,
  collapsible in a table cell in a collapsible, box > box, six-level lists,
  mixed inline and block content, emptied containers, list numbering,
  content inside marks (links, equations, nested marks), comment state ‖
  link wrap, 20 randomized nested seeds;
- `Selection.test.ts`: carets and ranges across remote edits, link URL
  change, a space typed next to a space;
- `Composition.test.ts`: IME composition (composition key) with a peer
  inserting before, right before, after and inside the composed text, edits
  in other lines, structural edits and deletions in the composing line;
- `Init.test.ts`: undo after initialization, concurrent initializations
  (same and different content), legacy roots, upgrade notice, conversion in
  place, extension (status, undo state, history conflict);
- `Storage.test.ts`: layout, every node kind, keystroke/Enter/Backspace and
  attribute-only updates, block child in a line, schema-incomplete
  subclasses, newer layout read only, no write before initialization,
  headless writer, undo, cursors;
- `Cursor.test.ts`: write cursor ≡ Y.Node#applyDelta (60 random seeds);
- `Size.test.ts`: byte budgets per operation and for a 10,000-edit session;
- `YrsCompat.test.ts`: a relay on ywasm 0.23.5 duplicates a 53-bit
  author's content on reconnect, not with `clientIDRange: 'uint32'` or
  `createYDoc({compat: 'yrs-0.23'})`, ywasm 0.28.0 handles 53-bit ids, and
  the 32-bit range survives Yjs drawing a new id (ywasm 0.23.5 and 0.28.0
  are dev dependencies);
- Regression tests: `Concurrency.test.ts` (lists, links, moves, formats in
  every order), `BlocksAndLines.test.ts` (a block inserted before a line ‖
  typing at its start, undo of a container a peer typed into, nested list
  shapes), `Ranges.test.ts` (range deletes across lines, line break
  NodeState, adjacent equal links), `Links.test.ts`, `EmptyMarks.test.ts`,
  `Tabs.test.ts`, `NestedItems.test.ts`, `NodeStateDefaults.test.ts`,
  `Document.test.ts` (group fields, pending local update),
  `Surrogates.test.ts`, `Lifecycle.test.ts` (version gate, concurrent init,
  undo across peers), `OtherRoots.test.ts`, `Nodes.test.ts` (link fields,
  schema subclasses, hand-written classes, object values, unknown types read
  only);
- `Fuzz.test.ts`: 300 seeds plus 100 with gc (3 peers, every delivery mode,
  typing, formats, links, comments, lists, tables, containers, undo/redo;
  convergence, fresh reader, canonical shape, self-check, no lost or
  duplicated tokens), longer runs through `FUZZ_SEEDS`; 4 seeds with open
  findings are listed in the test. `FuzzReplay.test.ts` replays 18
  minimized scripts of fixed failures;
- `Server.test.ts`, `ServerScale.test.ts`, `Source.test.ts`: server helpers
  (old client's update, delete-only update, linear time on 8,000-paragraph
  updates, notice readable by a Yjs 13 client), fail-closed editability, no
  `process.env` but NODE_ENV in shipped source.
- Core: `LexicalCollabNodeConfig.test.ts` covers `content`.

Fuzz, differential (the same scripts on this binding, #9386 and main v2,
moves included; worse = more unique tokens lost or duplicated, or a
divergence, exception, fragment or hang the other two do not have): 9,981
seeds, @lexical/y worse than both on 55 (0.55%: loss 31, duplicate 22,
fragment 5; divergence and exceptions 0), and loses fewer tokens than #9386
on 8.6% and than main v2 on 48%; gc on, 2,496 seeds: worse than both on 14
(0.56%). Hangs: #9386 18, @lexical/y 1 (being investigated).

Real browsers (Chromium, Firefox, WebKit through Playwright; separate
contexts over a Yjs 14 WebSocket relay with a 200 ms delay; real key events;
convergence, fresh load, token checks, no console warnings, editor errors
or self-check warnings), last run before this round's correctness fixes:
Chromium 60/60, Firefox 53/53 and WebKit 53/53 (IME cases need CDP and are
skipped in Firefox and WebKit).

Performance (headless Node, shared VM, medians, ms):

```
                                N=2,000            N=10,000
keystroke (end to end, 2 peers) 9.0                55.1      (main 54.3, B 50.3)
  core text walk skipped        0.53               2.1       (main 7.1, B 2.6)
Enter / Backspace               13.7 / 13.6        75.7 / 75.8 (main 74.2 / 74.7)
  core text walk skipped        4.8 / 4.8          26.4 / 27.0 (main 19.6 / 19.4)
document size (bytes)           164,000            833,603   (main 872,754,
                                (main 171,110)      A 1,006,407, B 1,391,890)
fresh load                      90                 416       (main 427, B 945)
initial bulk write (1 update)   271                1,104     (main 894, B 1,260)
```

Stress shapes (local update + write + peer read): 400 nested sections
(collapsible > table > cell > collapsible > list, box) paste 300, load 130,
208 KB; 10x10 tables 100/200/400 paste 1,099/1,875/3,864, load
412/776/1,570; bold everything in a list of 5k/10k/20k items 302/548/1,170;
add a NodeState comment in a 10k/20k/40k list 37/77/237; indent in a flat
list of 2.5k/5k/10k items 81/134/271; keystroke in a 50k/200k-character
paragraph 0.34/0.43. All linear.

Bytes per operation (gc off, client ids in Yjs' random range; op / undo /
redo):

```
                         main v2        #9383 (A)      #9386 (B)      @lexical/y
type a char mid line     25/11/26       25/11/26       25/11/26       24/10/24
paste 1k chars           1025/12/1026   1025/12/1026   1025/12/1026   1024/11/1025
Enter mid line           86/57/88       86/57/88       78/11/81       26/10/26
Backspace join           70/107/78      70/107/78      10/76/11       10/26/10
heading toggle           124/108/126    124/108/126    122/48/127     48/10/38
indent list item         134/58/135     134/58/135     54/37/57       65/27/60
link a word              175/73/190     276/11/292     282/11/292     103/10/103
bold a range             131/11/143     131/11/143     137/11/143     59/10/59
add a comment            137/11/149     137/11/149     143/11/149     65/10/65
table row insert         146/11/153     146/11/153     335/11/335     189/10/188
delete a table           10/439/11      10/439/11      11/1089/11     11/563/10
10,000-edit session      2,839,497      3,124,314      404,571        210,029
```

A Yjs 14 document written by this binding, with concurrent updates relayed
through yrs (ywasm 0.28.0), reloads into a fresh client identically; on yrs
0.23 it does with `clientIDRange: 'uint32'`.

```
$ npx vitest --project unit --no-watch packages/lexical-y/src \
    packages/lexical/src/__tests__/unit/LexicalCollabNodeConfig.test.ts
$ pnpm run tsc; pnpm run tsc-test   # exit 0
$ pnpm run flow                     # Found 0 errors
$ npx vitest --project scripts-unit --no-watch \
    scripts/__tests__/unit/treeShakingSource.test.ts
$ pnpm run prepare-release           # release build, package and type checks
$ pnpm --filter lexical-playground run build-vercel
$ pnpm --filter @lexical/website run build
```
zurfyx added a commit that referenced this pull request Oct 20, 2026
…ding with block markers

## Description

PROTOTYPE, not for merge. Stacked on #9386 (block markers on Yjs 13), whose
`$config({collab})` declarations it reuses. It shows the block-marker data
model on Yjs 14 (`@y/y`), as a new experimental package, `@lexical/y`.
`@lexical/yjs` (Yjs 13) is unchanged: Yjs 14 is a different npm package, so
a Yjs 14 binding cannot replace it in place.

Entries (all `@experimental`):
- `@lexical/y`: `YBinding`, `YCollabExtension` (binding, collaborative undo,
  `status` signal; conflicts with the history extensions),
  `writeEditorToYDoc` (headless writer for converters), `createYDoc`,
  `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and the types `YBindingOptions`,
  `YBindingStatus`, `YCursor`, `YCollabConfig`, `ClientIDRange`. No React,
  no DOM requirement.
- `@lexical/y/server`: `inspectUpdateRoots`, `isUpdateForLayout`,
  `writeUpgradeNotice`, `UpdateRoots`. No editor dependencies.
- `@lexical/y/migrate` is reserved for a converter from the Yjs 13 layouts.

`@y/y` is a peer dependency pinned to 14.0.0-rc.28, the newest release the
repository's minimum release age (7 days) allowed when this was written
(npm's `latest` tag points at an older release candidate).

Core: `CollabNodeConfig.content?: 'block' | 'inline'` (what a block node
stored as its own node holds), declared `'inline'` on CodeNode.

Data model (the semantics of #9386):
- Shared root `doc.get('lexical-y')`, a new root name, with a layout version
  attribute. The editor stays read only until that record has been read; a
  newer version, or content without a version, stays read only.
- `initialize()` (after the provider's first sync) marks only an empty root.
  It refuses when an older layout's root (`root`, `root-v2`) has content
  other than an upgrade notice (convert it: `writeEditorToYDoc` writes the
  layout root next to the old one). The initial content is written with a
  client id hashed from the layout version and the content, so two clients
  initializing the same content at once write it once, and outside the undo
  history.
- Every container (the root and every node stored as its own Y.Node) holds
  one sequence of text, child nodes and line markers (Yjs 14 Y.Node children
  are unified, so no XmlText per container is needed).
- A line (declared `'line'`, schema-complete) is its inline content followed
  by a marker: a child `Y.Node` named `¶` whose map attributes hold the
  line's type (left out for a paragraph), schema fields (minus derived),
  NodeState, and for a group item the group type, key fields and level. Not
  a character with formats (#9386's U+2029) and not an embed:
  * map attributes merge per key (last writer wins), so a concurrent heading
    change and indent both apply, without format start/end items in the
    sequence;
  * the marker's identity (its item) never changes when its attributes do,
    where an immutable embed would have to be replaced (and could be
    duplicated by concurrent replacements);
  * block attributes never mix with inline formats, and text may contain
    any character.
- Groups (lists) are rebuilt from consecutive items; local groups are kept
  in the same canonical shape by a transform (adjacent equal groups and
  wrapper items merged, empty groups removed); derived fields (list
  numbering) are recomputed by a refresh update on every client. All of a
  group's synced fields (and NodeState) identify it; a nested item's marker
  also records its outer groups and their wrapper items' fields (`o`), so an
  indented first item keeps its outer list's type and the wrappers' fields
  sync.
- Storage follows the class, never the instance: a declared line stays a
  line even with a block child (the child is stored as a node inside its
  content). Undeclared or invalid blocks are `b:<type>` child nodes with the
  class's own (compact) JSON as attributes; inline elements that are not
  formats and inline decorators are `i:<type>` children.
- A container records what it holds (`c`: blocks or inline content) when it
  is created, from `collab.content` or its children, and never changes it:
  leftover inline content of a block container reads as a paragraph on every
  reader; inline content directly in a block container is always ended by a
  `¦` terminator.
- Inline wrappers declared `inline: 'format'` are one format key each
  (`w:link`, whose value holds the wrapper's fields); text formats are one
  key per format (`f:bold`), plus type, JSON fields, NodeState and, for text
  nodes Lexical would not merge, a segment key (`k`). Formats apply to any
  child, so a link can span a line break or an inline decorator; a line
  break's NodeState is a format of its `\n`. Two adjacent equal links keep an
  instance key (`#`) so they stay two links on every peer.
- NodeState equal to its default is not stored (setting it back deletes
  the key). Element `textFormat`/`textStyle` are always stored.
- Schema completeness (own `$config()`, no hand-written `exportJSON`,
  `updateFromJSON` or `afterCloneFrom` below the declaring class) is
  required for lines, groups and inline formats; anything else is a node.
- Editor instances (nested caption editors) are not synchronized; JSON
  snapshots of them are (members that JSON would drop are dropped).
- A class with a hand-written serialization is a node; an edit to one of its
  own fields alone is written (the whole node's JSON is compared) and read
  through `updateFromJSON`, then `importJSON` for fields it does not know.
- Unknown types fail closed: a client that meets a node, line, text or
  group type it does not register goes read only with a warning, so it never
  hides and later deletes content it cannot show.

Write path:
- Anchored edits: Y.Node#insert/delete/format walk the type from its start
  on every call in rc.28, so the binding edits the sequence from the item it
  knows (the previous line's marker) with a port of Yjs' text position
  algorithm. A test runs random operations through it and through
  Y.Node#applyDelta and requires identical documents (byte for byte).
- A keystroke (one text node of a line changed, same formats, every other
  child unchanged including inside links) diffs only that node's old and
  new text, anchored at the caret, and writes at its offset: cost in the line's
  items, not its length (0.4 ms in a 200,000-character paragraph).
- Identity-anchored structure: units matched by node key (LIS); a line
  whose content did not change (node identity against the previous state,
  inline elements included) is never diffed; removed or moved units are
  deleted exactly; only split, join and type-change segments are diffed,
  as one sequence of the segment's items with the caret as the diff anchor:
  text that moved to another line keeps its items (no re-insert of a moved
  tail, so text a peer deleted is not resurrected). Diffs never split a
  surrogate pair. A Lexical node replaced in place by a new one of the same
  type keeps its shared node. Enter inserts a marker, Backspace deletes one, a type, indent
  or list type change only sets marker attributes.
- Structure is read from node links (the root is always marked dirty);
  attributes are written only for changed keys; inserted content carries its
  formats (no reformat after insert); format passes walk runs, not
  characters.
- Development self-check (default on outside production; `selfCheck` and
  `selfCheckSample` for production): every line a write touched is read back
  from Yjs, and every container a structural write touched, or where a
  group item's marker changed, is read whole into a fresh editor and
  compared with the editor's JSON (node types, list structure, wrapper
  fields, NodeState); mismatches go to the editor's `onWarn`. All tests run
  with it and fail on a warning.

Read path: a pending local `editor.update()` is committed before a remote
transaction is read; changed items are bucketed by container once per
transaction;
each changed item is located by walking to the next end item; text edits
update lines in place; structural changes re-parse only the touched units
(groups next to them are regrouped without re-reading untouched lines);
formats that span a marker propagate only while the value at the next unit's
start changes (re-reading the next unit as a region when it cannot be
updated in place); an inline element that cannot be empty is not shown when
peers deleted all its content; NodeState keys are read in sorted order. The local selection
is captured as relative positions before each remote transaction (a caret
anchored to the character on its left, a range to its edge characters) and
restored in the same update. While the local editor is composing (IME), remote
inserts into the composing line are applied to Yjs but not to that line's
nodes (the browser composes into their DOM); readers and writers of that
line skip those ids, and the line is read again when the composition ends
(deletions, formats and structure in the composing line are read at once).
A text diff with a run of equal characters places the change at the caret
(a space typed next to a space), and never splits a surrogate pair.
Follow-up updates (list renumbering, and
padding a table row that a concurrent column insert left short, done only by
the client that created the row) are kept out of the undo history.

Containers opt out of Yjs' remote formatting cleanup, which rescans every
type with formats after a remote format change (O(document) here): the
binding marks its containers as having no formats before Yjs decides. The
document's `cleanupFormatting` flag and the app's other types are untouched.

Servers on yrs before 0.28 read client ids as 32-bit numbers, while Yjs 14
draws 53-bit ones: such a server stores an author's content under a
truncated id, and the author receives its own content back as another
client's on reconnect, duplicating it (verified with ywasm 0.23.5; 0.28.0 is
fine). Opt-in compatibility: `clientIDRange: 'uint32'` (binding, extension,
`writeEditorToYDoc`) or `createYDoc({compat: 'yrs-0.23'})` keeps the
document's client id in 32 bits, including when Yjs draws a new one; the id
the binding uses for the initial content is always 32-bit. The default,
`'uint53'`, leaves Yjs 14's ids unchanged.

Undo: Yjs 14 UndoManager on the root, tracking only this binding's writes; a
container this client created that holds another client's content is kept
whole by undo (its fields and own content too).
Cursors: `getCursor()` / `$resolveCursor()` (relative positions on items;
no provider wiring or rendering).

`@y/y` internals used (all in rc.28; a bump must re-run the cursor
equivalence test): `new Item(...)`, `item.integrate`, `getItemCleanStart`,
`createID`, `Item.left/right/origin/rightOrigin/parent/content/deleted/
countable/length`, `YNode._start`, `_item`, `_map`, `_length`,
`_searchMarker`, `_hasFormatting`, `_legacyTypeRef` (upgrade notice), the
`beforeObserverCalls` event, `doc.store.getItem/getClock`,
`iterateStructsByIdSet`, `decodeUpdate`, `findRootTypeKey`.

Supported: split, join, partial joins, heading/quote/paragraph, list type,
indent/outdent, Enter in list items, checked state, alignment and NodeState
of lines, links and other inline formats (incl. property changes and spans
across line breaks), text formats, comments as NodeState, tables and any
nested containers (collapsible-like container > title + content, cell >
collapsible, box > box), block and inline decorators, inline elements
(MarkNode) with nested content, undo/redo, cursors, local selection across
remote edits.

Known limits:
- A move is a delete and a reinsert: text a peer types into a moved line
  lands in its old neighbour.
- MarkNode is an element with its own content: wrapping a range moves the
  text into it, and concurrent typing in that range stays outside. Comments
  should use per-id NodeState (MarkStateExtension).
- A split racing a type change gives the first half the splitter's type;
  text typed into a line a peer removed joins the next line.
- Slots are not synchronized; a link's fields merge as a whole (last
  writer wins).
- Yjs format semantics: bold ‖ bold on adjacent ranges of one line can leave
  part unformatted (the same on Yjs 13).
- A join ‖ removal of the joined line also joins the next line (nothing
  deleted comes back); unwrapping a container is a removal and a
  reinsertion of its lines, so text a peer types inside it at the same time
  is lost, as is text typed inside a container a peer removed (delete
  wins).
- Two clients initializing with different content at once both keep their
  content (converged); a row padded by its creator only if that client is
  still around (its client id).
- Several edits to one line in a single update are written as one replace
  (a peer's caret inside it moves to the edge).
- Structural edits in a large list cost time proportional to the list on
  both sides (regrouping and renumbering): about 4x main end to end at 10,000
  items. Enter at 10,000 blocks (core text walk skipped) is 26.4 ms against
  main's 19.6 ms.
- Relies on the @y/y internals listed above.
- Version gate: the layout version must be an integer from 1 to
  `LAYOUT_VERSION`; anything else is read only.
- With Yjs 14's default 53-bit client ids, servers on yrs before 0.28
  duplicate content on reconnect; use the opt-in 32-bit range for them.

Known open issues (being fixed, from randomized runs; see Fuzz below):
- A list item holding a paragraph (a list inserted inside a container that
  is not a shadow root) stores the paragraph as a node in the line:
  unlisting it, changing its type or removing it ‖ the same or typing in it
  can keep the paragraph twice or lose the typed text.
- Text moved out of a removed node into a line is diffed by characters
  against that line's old text, so a concurrent edit can split a token
  ("fragment"; about 0.1% of seeds).
- Rare: a text NodeState (comment) on text typed next to a line a peer
  removed in a table cell is missing on one peer; a self-check mismatch of
  an element's `textFormat` after concurrent list edits.

## Test plan

### Before

The Yjs 13 layouts on the same scenarios, from their own branches: main v2,
#9383 and #9386 lose or misplace concurrent typing on split, join, retype,
indent and nested containers (#9386 fixes most of them on Yjs 13); bytes per
operation are in the table below.

### After

New tests in `packages/lexical-y/src/__tests__/unit` (headless peers with
pinned client ids, offline edits then sync, both id orders, causal and
per-sender delivery, two and three peers; every case checks every peer, a
fresh reader, no exception and no self-check warning):
- `BlockMarkers.test.ts`: split, join, heading, quote, list indent, list
  type, Enter in a list item, link, table cell, custom block, removals with
  three peers, and 40 randomized intent seeds;
- `Races.test.ts`: links, unlink, undo of a link, overlapping formats,
  heading/quote/split/join/indent/list type/Enter races, moves, table rows
  and cells, row insert ‖ column insert, MarkNode; moves and MarkNode are
  documented limits (converged, intent not kept);
- `Nested.test.ts`, `NestedFuzz.test.ts`: collapsible-like containers,
  collapsible in a table cell in a collapsible, box > box, six-level lists,
  mixed inline and block content, emptied containers, list numbering,
  content inside marks (links, equations, nested marks), comment state ‖
  link wrap, 20 randomized nested seeds;
- `Selection.test.ts`: carets and ranges across remote edits, link URL
  change, a space typed next to a space;
- `Composition.test.ts`: IME composition (composition key) with a peer
  inserting before, right before, after and inside the composed text, edits
  in other lines, structural edits and deletions in the composing line;
- `Init.test.ts`: undo after initialization, concurrent initializations
  (same and different content), legacy roots, upgrade notice, conversion in
  place, extension (status, undo state, history conflict);
- `Storage.test.ts`: layout, every node kind, keystroke/Enter/Backspace and
  attribute-only updates, block child in a line, schema-incomplete
  subclasses, newer layout read only, no write before initialization,
  headless writer, undo, cursors;
- `Cursor.test.ts`: write cursor ≡ Y.Node#applyDelta (60 random seeds);
- `Size.test.ts`: byte budgets per operation and for a 10,000-edit session;
- `YrsCompat.test.ts`: a relay on ywasm 0.23.5 duplicates a 53-bit
  author's content on reconnect, not with `clientIDRange: 'uint32'` or
  `createYDoc({compat: 'yrs-0.23'})`, ywasm 0.28.0 handles 53-bit ids, and
  the 32-bit range survives Yjs drawing a new id (ywasm 0.23.5 and 0.28.0
  are dev dependencies);
- Regression tests: `Concurrency.test.ts` (lists, links, moves, formats in
  every order), `BlocksAndLines.test.ts` (a block inserted before a line ‖
  typing at its start, undo of a container a peer typed into, nested list
  shapes), `Ranges.test.ts` (range deletes across lines, line break
  NodeState, adjacent equal links), `Links.test.ts`, `EmptyMarks.test.ts`,
  `Tabs.test.ts`, `NestedItems.test.ts`, `NodeStateDefaults.test.ts`,
  `Document.test.ts` (group fields, pending local update),
  `Surrogates.test.ts`, `Lifecycle.test.ts` (version gate, concurrent init,
  undo across peers), `OtherRoots.test.ts`, `Nodes.test.ts` (link fields,
  schema subclasses, hand-written classes, object values, unknown types read
  only);
- `Fuzz.test.ts`: 300 seeds plus 100 with gc (3 peers, every delivery mode,
  typing, formats, links, comments, lists, tables, containers, undo/redo;
  convergence, fresh reader, canonical shape, self-check, no lost or
  duplicated tokens), longer runs through `FUZZ_SEEDS`; 3 seeds with open
  findings are listed in the test. `FuzzReplay.test.ts` replays 23
  minimized scripts of fixed failures;
- `Server.test.ts`, `ServerScale.test.ts`, `Source.test.ts`: server helpers
  (old client's update, delete-only update, linear time on 8,000-paragraph
  updates, notice readable by a Yjs 13 client), fail-closed editability, no
  `process.env` but NODE_ENV in shipped source.
- Core: `LexicalCollabNodeConfig.test.ts` covers `content`.

Fuzz, differential: the same scripts run on this binding, on #9386 and on
main v2. "Worse" means @lexical/y loses or duplicates more unique tokens,
or diverges, throws, fragments or hangs where neither of the other two
does:
- 9,983 seeds with block moves: worse than both on 53 (0.53%; 19 of them
  only lose text typed into a container a peer removed). Divergence 1,
  exceptions 0. Fewer lost tokens than #9386 on 8.7% of seeds and than
  main v2 on 48%.
- 9,995 seeds without moves: worse than both on 30 (0.30%; 14 of them
  container loss).
- 2,496 seeds with gc on: worse than both on 13 (0.52%).
- Hangs, all three runs: #9386 26, @lexical/y 0.
Within a partition, the fuzz relays updates as a sync protocol would.
Otherwise two peers that lack a third peer's update rewrite derived fields
against each other forever (a test artifact; it caused the one hang seen
on @lexical/y before).

Real browsers (Chromium, Firefox, WebKit through Playwright; separate
contexts over a Yjs 14 WebSocket relay with a 200 ms delay; real key events;
convergence, fresh load, token checks, no console warnings, editor errors
or self-check warnings), after this round's fixes: Chromium 60/60, Firefox
53/53 and WebKit 53/53 (IME cases need CDP and are skipped in Firefox and
WebKit).

Performance (headless Node, shared VM, medians, ms):

```
                                N=2,000            N=10,000
keystroke (end to end, 2 peers) 9.0                55.1      (main 54.3, B 50.3)
  core text walk skipped        0.53               2.1       (main 7.1, B 2.6)
Enter / Backspace               13.7 / 13.6        75.7 / 75.8 (main 74.2 / 74.7)
  core text walk skipped        4.8 / 4.8          26.4 / 27.0 (main 19.6 / 19.4)
document size (bytes)           164,000            833,603   (main 872,754,
                                (main 171,110)      A 1,006,407, B 1,391,890)
fresh load                      90                 416       (main 427, B 945)
initial bulk write (1 update)   271                1,104     (main 894, B 1,260)
```

Stress shapes (local update + write + peer read): 400 nested sections
(collapsible > table > cell > collapsible > list, box) paste 300, load 130,
208 KB; 10x10 tables 100/200/400 paste 1,099/1,875/3,864, load
412/776/1,570; bold everything in a list of 5k/10k/20k items 302/548/1,170;
add a NodeState comment in a 10k/20k/40k list 37/77/237; indent in a flat
list of 2.5k/5k/10k items 81/134/271; keystroke in a 50k/200k-character
paragraph 0.34/0.43. All linear.

Bytes per operation (gc off, client ids in Yjs' random range; op / undo /
redo):

```
                         main v2        #9383 (A)      #9386 (B)      @lexical/y
type a char mid line     25/11/26       25/11/26       25/11/26       24/10/24
paste 1k chars           1025/12/1026   1025/12/1026   1025/12/1026   1024/11/1025
Enter mid line           86/57/88       86/57/88       78/11/81       26/10/26
Backspace join           70/107/78      70/107/78      10/76/11       10/26/10
heading toggle           124/108/126    124/108/126    122/48/127     48/10/38
indent list item         134/58/135     134/58/135     54/37/57       65/27/60
link a word              175/73/190     276/11/292     282/11/292     103/10/103
bold a range             131/11/143     131/11/143     137/11/143     59/10/59
add a comment            137/11/149     137/11/149     143/11/149     65/10/65
table row insert         146/11/153     146/11/153     335/11/335     189/10/188
delete a table           10/439/11      10/439/11      11/1089/11     11/563/10
10,000-edit session      2,839,497      3,124,314      404,571        210,029
```

A Yjs 14 document written by this binding, with concurrent updates relayed
through yrs (ywasm 0.28.0), reloads into a fresh client identically; on yrs
0.23 it does with `clientIDRange: 'uint32'`.

```
$ npx vitest --project unit --no-watch packages/lexical-y/src \
    packages/lexical/src/__tests__/unit/LexicalCollabNodeConfig.test.ts
$ pnpm run tsc; pnpm run tsc-test   # exit 0
$ pnpm run flow                     # Found 0 errors
$ npx vitest --project scripts-unit --no-watch \
    scripts/__tests__/unit/treeShakingSource.test.ts
$ pnpm run prepare-release           # release build, package and type checks
$ pnpm --filter lexical-playground run build-vercel
$ pnpm --filter @lexical/website run build
```
zurfyx added a commit that referenced this pull request Oct 21, 2026
…ding with block markers

## Description

PROTOTYPE, not for merge. Stacked on #9386 (block markers on Yjs 13), whose
`$config({collab})` declarations it reuses. It shows the block-marker data
model on Yjs 14 (`@y/y`), as a new experimental package, `@lexical/y`.
`@lexical/yjs` (Yjs 13) is unchanged: Yjs 14 is a different npm package, so
a Yjs 14 binding cannot replace it in place.

Entries (all `@experimental`):
- `@lexical/y`: `YBinding`, `YCollabExtension` (binding, collaborative undo,
  `status` signal; conflicts with the history extensions),
  `writeEditorToYDoc` (headless writer for converters), `createYDoc`,
  `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and the types `YBindingOptions`,
  `YBindingStatus`, `YCursor`, `YCollabConfig`, `ClientIDRange`. No React,
  no DOM requirement.
- `@lexical/y/server`: `inspectUpdateRoots`, `isUpdateForLayout`,
  `writeUpgradeNotice`, `UpdateRoots`. No editor dependencies.
- `@lexical/y/migrate` is reserved for a converter from the Yjs 13 layouts.

`@y/y` is a peer dependency pinned to 14.0.0-rc.28, the newest release the
repository's minimum release age (7 days) allowed when this was written
(npm's `latest` tag points at an older release candidate).

Core: `CollabNodeConfig.content?: 'block' | 'inline'` (what a block node
stored as its own node holds), declared `'inline'` on CodeNode.

Data model (the semantics of #9386):
- Shared root `doc.get('lexical-y')`, a new root name, with a layout version
  attribute. The editor stays read only until that record has been read; a
  newer version, or content without a version, stays read only.
- `initialize()` (after the provider's first sync) marks only an empty root.
  It refuses when an older layout's root (`root`, `root-v2`) has content
  other than an upgrade notice (convert it: `writeEditorToYDoc` writes the
  layout root next to the old one). The initial content is written with a
  client id hashed from the layout version and the content, so two clients
  initializing the same content at once write it once, and outside the undo
  history.
- Every container (the root and every node stored as its own Y.Node) holds
  one sequence of text, child nodes and line markers (Yjs 14 Y.Node children
  are unified, so no XmlText per container is needed).
- A line (declared `'line'`, schema-complete) is its inline content followed
  by a marker: a child `Y.Node` named `¶` whose map attributes hold the
  line's type (left out for a paragraph), schema fields (minus derived),
  NodeState, and for a group item the group type, key fields and level. Not
  a character with formats (#9386's U+2029) and not an embed:
  * map attributes merge per key (last writer wins), so a concurrent heading
    change and indent both apply, without format start/end items in the
    sequence;
  * the marker's identity (its item) never changes when its attributes do,
    where an immutable embed would have to be replaced (and could be
    duplicated by concurrent replacements);
  * block attributes never mix with inline formats, and text may contain
    any character.
- Groups (lists) are rebuilt from consecutive items; local groups are kept
  in the same canonical shape by a transform (adjacent equal groups and
  wrapper items merged, empty groups removed); derived fields (list
  numbering) are recomputed by a refresh update on every client. All of a
  group's synced fields (and NodeState) identify it; a nested item's marker
  also records its outer groups and their wrapper items' fields (`o`), so an
  indented first item keeps its outer list's type and the wrappers' fields
  sync.
- Storage follows the class, never the instance: a declared line stays a
  line even with a block child (the child is stored as a node inside its
  content). Undeclared or invalid blocks are `b:<type>` child nodes with the
  class's own (compact) JSON as attributes; inline elements that are not
  formats and inline decorators are `i:<type>` children.
- A container records what it holds (`c`: blocks or inline content) when it
  is created, from `collab.content` or its children, and never changes it:
  leftover inline content of a block container reads as a paragraph on every
  reader; inline content directly in a block container is always ended by a
  `¦` terminator.
- Inline wrappers declared `inline: 'format'` are one format key each
  (`w:link`, whose value holds the wrapper's fields); text formats are one
  key per format (`f:bold`), plus type, JSON fields, NodeState and, for text
  nodes Lexical would not merge, a segment key (`k`). Formats apply to any
  child, so a link can span a line break or an inline decorator; a line
  break's NodeState is a format of its `\n`. Two adjacent equal links keep an
  instance key (`#`) so they stay two links on every peer.
- NodeState equal to its default is not stored (setting it back deletes
  the key). Element `textFormat`/`textStyle` are always stored.
- Schema completeness (own `$config()`, no hand-written `exportJSON`,
  `updateFromJSON` or `afterCloneFrom` below the declaring class) is
  required for lines, groups and inline formats; anything else is a node.
- Editor instances (nested caption editors) are not synchronized; JSON
  snapshots of them are (members that JSON would drop are dropped).
- A class with a hand-written serialization is a node; an edit to one of its
  own fields alone is written (the whole node's JSON is compared) and read
  through `updateFromJSON`, then `importJSON` for fields it does not know.
- Unknown types fail closed: a client that meets a node, line, text or
  group type it does not register goes read only with a warning, so it never
  hides and later deletes content it cannot show.

Write path:
- Anchored edits: Y.Node#insert/delete/format walk the type from its start
  on every call in rc.28, so the binding edits the sequence from the item it
  knows (the previous line's marker) with a port of Yjs' text position
  algorithm. A test runs random operations through it and through
  Y.Node#applyDelta and requires identical documents (byte for byte).
- A keystroke (one text node of a line changed, same formats, every other
  child unchanged including inside links) diffs only that node's old and
  new text, anchored at the caret, and writes at its offset: cost in the line's
  items, not its length (0.4 ms in a 200,000-character paragraph).
- Identity-anchored structure: units matched by node key (a weighted
  longest increasing subsequence: as many blocks as possible stay in place,
  a list counting as one block; between equal counts a block node, whose
  rewrite copies its subtree, outweighs lines). A line whose content did not
  change (node identity against the previous state, inline elements
  included) is never diffed; removed or moved units are deleted exactly;
  only split, join and type-change segments are diffed, as one sequence of
  the segment's items with the caret as the diff anchor: text that moved to
  another line keeps its items (no re-insert of a moved tail, so text a peer
  deleted is not resurrected). Each character keeps its old item only
  if it comes from the same Lexical text node as before (text nodes merged
  by a join or an unlink are attributed using the caret at the join, else
  by common prefix and suffix), so text that moved between nodes or lines is
  written as new text, never built from equal old characters. Diffs never split a
  surrogate pair. A Lexical node replaced in place by a new one keeps its
  shared node and content: a different type is recorded in the node's `t`
  attribute (a paragraph held by a list item turned into a heading keeps a
  peer's concurrent typing). Enter inserts a marker, Backspace deletes one, a
  type, indent or list type change only sets marker attributes.
- Structure is read from node links (the root is always marked dirty);
  attributes are written only for changed keys; inserted content carries its
  formats (no reformat after insert); format passes walk runs, not
  characters.
- Development self-check (default on outside production; `selfCheck` and
  `selfCheckSample` for production): every line a write touched is read back
  from Yjs, and every container a structural write touched, or where a
  group item's marker changed, is read whole into a fresh editor and
  compared with the editor's JSON (node types, list structure, wrapper
  fields, NodeState); mismatches go to the editor's `onWarn`. All tests run
  with it and fail on a warning.

Read path: a pending local `editor.update()` is committed before a remote
transaction is read; changed items are bucketed by container once per
transaction; an inserted or deleted format item re-derives the start formats
of the following units (past block nodes too) until they agree again;
each changed item is located by walking to the next end item; text edits
update lines in place; structural changes re-parse only the touched units
(groups next to them are regrouped without re-reading untouched lines);
formats that span a marker propagate only while the value at the next unit's
start changes (re-reading the next unit as a region when it cannot be
updated in place); an inline element that cannot be empty is not shown when
peers deleted all its content; NodeState keys are read in sorted order. The local selection
is captured as relative positions before each remote transaction (a caret
anchored to the character on its left, a range to its edge characters) and
restored in the same update. While the local editor is composing (IME), remote
inserts into the composing line are applied to Yjs but not to that line's
nodes (the browser composes into their DOM); readers and writers of that
line skip those ids, and the line is read again when the composition ends
(deletions, formats and structure in the composing line are read at once).
A text diff with a run of equal characters places the change at the caret
(a space typed next to a space), and never splits a surrogate pair.
Follow-up updates (list renumbering, and
padding a table row that a concurrent column insert left short, done only by
the client that created the row) are kept out of the undo history.

Containers opt out of Yjs' remote formatting cleanup, which rescans every
type with formats after a remote format change (O(document) here): the
binding marks its containers as having no formats before Yjs decides. The
document's `cleanupFormatting` flag and the app's other types are untouched.

Servers on yrs before 0.28 read client ids as 32-bit numbers, while Yjs 14
draws 53-bit ones. With Yjs 14's default ids:
- a ywasm 0.23.5 relay stores an author's content under a truncated id, and
  the author receives its own content back as another client's on reconnect,
  duplicating it;
- a real yrs 0.23 server rejects the reconnect ("the awareness update is
  malformed"), and edits made offline are lost.
yrs/ywasm 0.28.0 is fine. Opt-in compatibility: `clientIDRange: 'uint32'`
(binding, extension, `writeEditorToYDoc`) or `createYDoc({compat:
'yrs-0.23'})` keeps the document's client id in 32 bits, including when Yjs
draws a new one; the id the binding uses for the initial content is always
32-bit. The default, `'uint53'`, leaves Yjs 14's ids unchanged. The binding
does not own the awareness, which takes the document's client id when it is
created; the README tells apps to create the awareness and provider from a
document that already has a 32-bit id. With 32-bit ids, a yrs 0.23 server
converges, including offline edits, reconnects and late joiners.

Undo: Yjs 14 UndoManager on the root, tracking only this binding's writes. A
container the undone change inserted that holds another client's content is
kept whole (its fields and own content too), unless the undo also restores
a container of the same type (the change was a move: keeping the copy
would duplicate it).
Cursors: `getCursor()` / `$resolveCursor()` (relative positions on items;
no provider wiring or rendering).

`@y/y` internals used (all in rc.28; a bump must re-run the cursor
equivalence test): `new Item(...)`, `item.integrate`, `getItemCleanStart`,
`createID`, `Item.left/right/origin/rightOrigin/parent/content/deleted/
countable/length`, `YNode._start`, `_item`, `_map`, `_length`,
`_searchMarker`, `_hasFormatting`, `_legacyTypeRef` (upgrade notice), the
`beforeObserverCalls` event, `doc.store.getItem/getClock`,
`iterateStructsByIdSet`, `decodeUpdate`, `findRootTypeKey`.

Supported: split, join, partial joins, heading/quote/paragraph, list type,
indent/outdent, Enter in list items, checked state, alignment and NodeState
of lines, links and other inline formats (incl. property changes and spans
across line breaks), text formats, comments as NodeState, tables and any
nested containers (collapsible-like container > title + content, cell >
collapsible, box > box), block and inline decorators, inline elements
(MarkNode) with nested content, undo/redo, cursors, local selection across
remote edits.

Known limits:
- A move is a delete and a reinsert: text a peer types into a moved line
  lands in its old neighbour.
- MarkNode is an element with its own content: wrapping a range moves the
  text into it, and concurrent typing in that range stays outside. Comments
  should use per-id NodeState (MarkStateExtension).
- A split racing a type change gives the first half the splitter's type;
  text typed into a line a peer removed joins the next line.
- Slots are not synchronized; a link's fields merge as a whole (last
  writer wins).
- Yjs format semantics: bold ‖ bold on adjacent ranges of one line can leave
  part unformatted (the same on Yjs 13).
- A join ‖ removal of the joined line also joins the next line (nothing
  deleted comes back); unwrapping a container is a removal and a
  reinsertion of its lines, so text a peer types inside it at the same time
  is lost, as is text typed inside a container a peer removed (delete
  wins).
- Two clients initializing with different content at once both keep their
  content (converged); a row padded by its creator only if that client is
  still around (its client id).
- Several edits to one line in a single update are written as one replace
  (a peer's caret inside it moves to the edge).
- Structural edits in a large list cost time proportional to the list on
  both sides (regrouping and renumbering): about 4x main end to end at 10,000
  items. Enter at 10,000 blocks (core text walk skipped) is 26.4 ms against
  main's 19.6 ms.
- Relies on the @y/y internals listed above.
- Version gate: the layout version must be an integer from 1 to
  `LAYOUT_VERSION`; anything else is read only.
- With Yjs 14's default 53-bit client ids, servers on yrs before 0.28
  duplicate content or lose offline edits on reconnect; use the opt-in
  32-bit range for them, and create the awareness from that document.

Known open issues (from randomized runs; see Fuzz below):
- Two peers moving the same blocks at once (move ‖ move): which of two
  swapped blocks gets rewritten is a guess (Lexical does not say which node
  moved), so a block can be duplicated or, if the other peer moved it into
  a container a third peer deleted, lost. 2 of 9,983 seeds are worse than
  both Yjs 13 layouts (see Fuzz).
- Rare self-check mismatches of an element's `textFormat` after concurrent
  list edits and a bold-then-undo (about 0.05% of seeds, converged).
- Not a binding issue: `$toggleLink(null)` on a range that ends at the edge
  of a link's text throws in `$splitLinkAtSelection` (empty
  `extractedChildren`), in any editor on main; the fuzz no longer generates
  it.

## Test plan

### Before

The Yjs 13 layouts on the same scenarios, from their own branches: main v2,
#9383 and #9386 lose or misplace concurrent typing on split, join, retype,
indent and nested containers (#9386 fixes most of them on Yjs 13); bytes per
operation are in the table below.

### After

New tests in `packages/lexical-y/src/__tests__/unit` (headless peers with
pinned client ids, offline edits then sync, both id orders, causal and
per-sender delivery, two and three peers; every case checks every peer, a
fresh reader, no exception and no self-check warning):
- `BlockMarkers.test.ts`: split, join, heading, quote, list indent, list
  type, Enter in a list item, link, table cell, custom block, removals with
  three peers, and 40 randomized intent seeds;
- `Races.test.ts`: links, unlink, undo of a link, overlapping formats,
  heading/quote/split/join/indent/list type/Enter races, moves, table rows
  and cells, row insert ‖ column insert, MarkNode; moves and MarkNode are
  documented limits (converged, intent not kept);
- `Nested.test.ts`, `NestedFuzz.test.ts`: collapsible-like containers,
  collapsible in a table cell in a collapsible, box > box, six-level lists,
  mixed inline and block content, emptied containers, list numbering,
  content inside marks (links, equations, nested marks), comment state ‖
  link wrap, 20 randomized nested seeds;
- `Selection.test.ts`: carets and ranges across remote edits, link URL
  change, a space typed next to a space;
- `Composition.test.ts`: IME composition (composition key) with a peer
  inserting before, right before, after and inside the composed text, edits
  in other lines, structural edits and deletions in the composing line;
- `Init.test.ts`: undo after initialization, concurrent initializations
  (same and different content), legacy roots, upgrade notice, conversion in
  place, extension (status, undo state, history conflict);
- `Storage.test.ts`: layout, every node kind, keystroke/Enter/Backspace and
  attribute-only updates, block child in a line, schema-incomplete
  subclasses, newer layout read only, no write before initialization,
  headless writer, undo, cursors;
- `Cursor.test.ts`: write cursor ≡ Y.Node#applyDelta (60 random seeds);
- `Size.test.ts`: byte budgets per operation and for a 10,000-edit session;
- `YrsCompat.test.ts`: a relay on ywasm 0.23.5 duplicates a 53-bit
  author's content on reconnect, not with `clientIDRange: 'uint32'` or
  `createYDoc({compat: 'yrs-0.23'})`, ywasm 0.28.0 handles 53-bit ids, and
  the 32-bit range survives Yjs drawing a new id (ywasm 0.23.5 and 0.28.0
  are dev dependencies);
- Regression tests: `Concurrency.test.ts` (lists, links, moves, formats in
  every order), `BlocksAndLines.test.ts` (a block inserted before a line ‖
  typing at its start, undo of a container a peer typed into, nested list
  shapes, paragraphs held by list items, moves past tables and their undo), `Ranges.test.ts` (range deletes across lines, line break
  NodeState, adjacent equal links), `Links.test.ts`, `EmptyMarks.test.ts`,
  `Tabs.test.ts`, `NestedItems.test.ts`, `NodeStateDefaults.test.ts`,
  `Document.test.ts` (group fields, pending local update),
  `Surrogates.test.ts`, `Lifecycle.test.ts` (version gate, concurrent init,
  undo across peers), `OtherRoots.test.ts`, `Nodes.test.ts` (link fields,
  schema subclasses, hand-written classes, object values, unknown types read
  only);
- `Fuzz.test.ts`: 300 seeds plus 100 with gc (3 peers, every delivery mode,
  typing, formats, links, comments, lists, tables, containers, undo/redo;
  convergence, fresh reader, canonical shape, self-check, no lost or
  duplicated tokens), longer runs through `FUZZ_SEEDS`, a differential run
  through `FUZZ_DIFF=1`; one seed where all three layouts lose the same
  token is listed in the test. `FuzzReplay.test.ts` replays 43 minimized
  scripts of fixed failures;
- `Server.test.ts`, `ServerScale.test.ts`, `Source.test.ts`: server helpers
  (old client's update, delete-only update, linear time on 8,000-paragraph
  updates, notice readable by a Yjs 13 client), fail-closed editability, no
  `process.env` but NODE_ENV in shipped source.
- Core: `LexicalCollabNodeConfig.test.ts` covers `content`.

Fuzz, differential: the same scripts run on this binding, on #9386 and on
main v2; each pair is compared on the script cut before the first op the
two runs resolved differently. "Worse than both" means @lexical/y loses or
duplicates more unique tokens, or diverges, throws, fragments or hangs,
than #9386 and than main v2:
- 9,983 seeds with block moves: 2 (one move ‖ swap of equal list items
  duplicates an item; one delete-wins container loss where both other
  layouts bring the deleted table back).
- 9,995 seeds without moves: 0.
- 2,496 seeds with gc on: 1 (delete-wins: both others resurrect deleted
  cells).
- @lexical/y diverged, threw or fragmented on 0 of the 22,474 seeds; it
  loses fewer tokens than #9386 on about 7% of seeds and than main v2 on
  about 38%. Hangs: #9386 26, @lexical/y 0.
Within a partition, the fuzz relays updates as a sync protocol would.

Real browsers (Chromium, Firefox, WebKit through Playwright; separate
contexts over a Yjs 14 WebSocket relay with a 200 ms delay; real key events;
convergence, fresh load, token checks, no console warnings, editor errors
or self-check warnings), after this round's fixes: Chromium 60/60, Firefox
53/53 and WebKit 53/53 (IME cases need CDP and are skipped in Firefox and
WebKit).

Performance (headless Node, shared VM, medians, ms):

```
                                N=2,000            N=10,000
keystroke (end to end, 2 peers) 9.0                55.1      (main 54.3, B 50.3)
  core text walk skipped        0.53               2.1       (main 7.1, B 2.6)
Enter / Backspace               13.7 / 13.6        75.7 / 75.8 (main 74.2 / 74.7)
  core text walk skipped        4.8 / 4.8          26.4 / 27.0 (main 19.6 / 19.4)
document size (bytes)           164,000            833,603   (main 872,754,
                                (main 171,110)      A 1,006,407, B 1,391,890)
fresh load                      90                 416       (main 427, B 945)
initial bulk write (1 update)   271                1,104     (main 894, B 1,260)
```

Stress shapes (local update + write + peer read): 400 nested sections
(collapsible > table > cell > collapsible > list, box) paste 300, load 130,
208 KB; 10x10 tables 100/200/400 paste 1,099/1,875/3,864, load
412/776/1,570; bold everything in a list of 5k/10k/20k items 302/548/1,170;
add a NodeState comment in a 10k/20k/40k list 37/77/237; indent in a flat
list of 2.5k/5k/10k items 81/134/271; keystroke in a 50k/200k-character
paragraph 0.34/0.43. All linear.

Bytes per operation (gc off, client ids in Yjs' random range; op / undo /
redo):

```
                         main v2        #9383 (A)      #9386 (B)      @lexical/y
type a char mid line     25/11/26       25/11/26       25/11/26       24/10/24
paste 1k chars           1025/12/1026   1025/12/1026   1025/12/1026   1024/11/1025
Enter mid line           86/57/88       86/57/88       78/11/81       26/10/26
Backspace join           70/107/78      70/107/78      10/76/11       10/26/10
heading toggle           124/108/126    124/108/126    122/48/127     48/10/38
indent list item         134/58/135     134/58/135     54/37/57       65/27/60
link a word              175/73/190     276/11/292     282/11/292     103/10/103
bold a range             131/11/143     131/11/143     137/11/143     59/10/59
add a comment            137/11/149     137/11/149     143/11/149     65/10/65
table row insert         146/11/153     146/11/153     335/11/335     189/10/188
delete a table           10/439/11      10/439/11      11/1089/11     11/563/10
10,000-edit session      2,839,497      3,124,314      404,571        210,029
```

A Yjs 14 document written by this binding, with concurrent updates relayed
through yrs (ywasm 0.28.0), reloads into a fresh client identically; on yrs
0.23 it does with `clientIDRange: 'uint32'`.

```
$ npx vitest --project unit --no-watch packages/lexical-y/src \
    packages/lexical/src/__tests__/unit/LexicalCollabNodeConfig.test.ts
$ pnpm run tsc; pnpm run tsc-test   # exit 0
$ pnpm run flow                     # Found 0 errors
$ npx vitest --project scripts-unit --no-watch \
    scripts/__tests__/unit/treeShakingSource.test.ts
$ pnpm run prepare-release           # release build, package and type checks
$ pnpm --filter lexical-playground run build-vercel
$ pnpm --filter @lexical/website run build
```
zurfyx added a commit that referenced this pull request Oct 21, 2026
…ding with block markers

## Description

PROTOTYPE, not for merge. Stacked on #9386 (block markers on Yjs 13), whose
`$config({collab})` declarations it reuses. It shows the block-marker data
model on Yjs 14 (`@y/y`), as a new experimental package, `@lexical/y`.
`@lexical/yjs` (Yjs 13) is unchanged: Yjs 14 is a different npm package, so
a Yjs 14 binding cannot replace it in place.

Entries (all `@experimental`):
- `@lexical/y`: `YBinding`, `YCollabExtension` (binding, collaborative undo,
  `status` signal; conflicts with the history extensions),
  `writeEditorToYDoc` (headless writer for converters), `createYDoc`,
  `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and the types `YBindingOptions`,
  `YBindingStatus`, `YCursor`, `YCollabConfig`, `ClientIDRange`. No React,
  no DOM requirement.
- `@lexical/y/server`: `inspectUpdateRoots`, `isUpdateForLayout`,
  `writeUpgradeNotice`, `UpdateRoots`. No editor dependencies.
- `@lexical/y/migrate` is reserved for a converter from the Yjs 13 layouts.

`@y/y` is a peer dependency pinned to 14.0.0-rc.28, the newest release the
repository's minimum release age (7 days) allowed when this was written
(npm's `latest` tag points at an older release candidate).

Core:
- `CollabNodeConfig.content?: 'block' | 'inline'` (what a block node stored
  as its own node holds), declared `'inline'` on CodeNode.
- Text normalization no longer merges text into or out of the node being
  composed (IME): merging rewrote its DOM text node and the browser's
  composition range took in the merged text; the nodes merge when the
  composition ends.
- `NodeState.updateFromKnown` drops the key's unknown value (read from JSON
  before the key's config was known): setting such a key back to its default
  left the stale value in exportJSON (a comment removed on a peer stayed).

Data model (the semantics of #9386):
- Shared root `doc.get('lexical-y')`, a new root name, with a layout version
  attribute. The editor stays read only until that record has been read; a
  newer version, or content without a version, stays read only.
- `initialize()` (after the provider's first sync) marks only an empty root.
  It refuses when an older layout's root (`root`, `root-v2`) has content
  other than an upgrade notice (convert it: `writeEditorToYDoc` writes the
  layout root next to the old one). The initial content is written with a
  client id hashed from the layout version and the content, so two clients
  initializing the same content at once write it once, and outside the undo
  history.
- Every container (the root and every node stored as its own Y.Node) holds
  one sequence of text, child nodes and line markers (Yjs 14 Y.Node children
  are unified, so no XmlText per container is needed).
- A line (declared `'line'`, schema-complete) is its inline content followed
  by a marker: a child `Y.Node` named `¶` whose map attributes hold the
  line's type (left out for a paragraph), schema fields (minus derived),
  NodeState, and for a group item the group type, key fields and level. Not
  a character with formats (#9386's U+2029) and not an embed:
  * map attributes merge per key (last writer wins), so a concurrent heading
    change and indent both apply, without format start/end items in the
    sequence;
  * the marker's identity (its item) never changes when its attributes do,
    where an immutable embed would have to be replaced (and could be
    duplicated by concurrent replacements);
  * block attributes never mix with inline formats, and text may contain
    any character.
- Groups (lists) are rebuilt from consecutive items; local groups are kept
  in the same canonical shape by a transform (adjacent equal groups and
  wrapper items merged, empty groups removed); derived fields (list
  numbering) are recomputed by a refresh update on every client. All of a
  group's synced fields (and NodeState) identify it; a nested item's marker
  also records its outer groups and their wrapper items' fields (`o`), so an
  indented first item keeps its outer list's type and the wrappers' fields
  sync.
- Storage follows the class, never the instance: a declared line stays a
  line even with a block child (the child is stored as a node inside its
  content). Undeclared or invalid blocks are `b:<type>` child nodes with the
  class's own (compact) JSON as attributes; inline elements that are not
  formats and inline decorators are `i:<type>` children.
- A container records what it holds (`c`: blocks or inline content) when it
  is created, from `collab.content` or its children, and never changes it:
  leftover inline content of a block container reads as a paragraph on every
  reader; inline content directly in a block container is always ended by a
  `¦` terminator.
- Inline wrappers declared `inline: 'format'` are one format key each
  (`w:link`, whose value holds the wrapper's fields); text formats are one
  key per format (`f:bold`), plus type, JSON fields, NodeState and, for text
  nodes Lexical would not merge, a segment key (`k`). Formats apply to any
  child, so a link can span a line break or an inline decorator; a line
  break's NodeState is a format of its `\n`. Two adjacent equal links keep an
  instance key (`#`) so they stay two links on every peer.
- NodeState equal to its default is not stored (setting it back deletes
  the key). Element `textFormat`/`textStyle` are always stored.
- Schema completeness (own `$config()`, no hand-written `exportJSON`,
  `updateFromJSON` or `afterCloneFrom` below the declaring class) is
  required for lines, groups and inline formats; anything else is a node.
- Editor instances (nested caption editors) are not synchronized; JSON
  snapshots of them are (members that JSON would drop are dropped).
- A class with a hand-written serialization is a node; an edit to one of its
  own fields alone is written (the whole node's JSON is compared) and read
  through `updateFromJSON`, then `importJSON` for fields it does not know.
- Unknown types fail closed: a client that meets a node, line, text or
  group type it does not register goes read only with a warning, so it never
  hides and later deletes content it cannot show.

Write path:
- Anchored edits: Y.Node#insert/delete/format walk the type from its start
  on every call in rc.28, so the binding edits the sequence from the item it
  knows (the previous line's marker) with a port of Yjs' text position
  algorithm. A test runs random operations through it and through
  Y.Node#applyDelta and requires identical documents (byte for byte).
- A keystroke (one text node of a line changed, same formats, every other
  child unchanged including inside links) diffs only that node's old and
  new text, anchored at the caret, and writes at its offset: cost in the line's
  items, not its length (0.4 ms in a 200,000-character paragraph).
- Identity-anchored structure: units matched by node key (a weighted
  longest increasing subsequence: as many blocks as possible stay in place,
  a list counting as one block; between equal counts a block node, whose
  rewrite copies its subtree, outweighs lines). A line whose content did not
  change (node identity against the previous state, inline elements
  included) is never diffed; removed or moved units are deleted exactly;
  only split, join and type-change segments are diffed, as one sequence of
  the segment's items with the caret as the diff anchor: text that moved to
  another line keeps its items (no re-insert of a moved tail, so text a peer
  deleted is not resurrected). Each character keeps its old item only
  if it comes from the same Lexical text node as before (text nodes merged
  by a join or an unlink are attributed using the caret at the join, else
  by common prefix and suffix), so text that moved between nodes or lines is
  written as new text, never built from equal old characters. Diffs never split a
  surrogate pair. A Lexical node replaced in place by a new one keeps its
  shared node and content: a different type is recorded in the node's `t`
  attribute (a paragraph held by a list item turned into a heading keeps a
  peer's concurrent typing). Enter inserts a marker, Backspace deletes one, a
  type, indent or list type change only sets marker attributes.
- Structure is read from node links (the root is always marked dirty);
  attributes are written only for changed keys; inserted content carries its
  formats (no reformat after insert); format passes walk runs, not
  characters.
- Development self-check (default on outside production; `selfCheck` and
  `selfCheckSample` for production, also options of `YCollabExtension`):
  every line a write touched is read back from Yjs (text, formats, line
  break NodeState, marker), and every container a structural write touched,
  or where a group item's marker changed, is read whole into a fresh editor
  and compared with the editor's JSON (node types, list structure, wrapper
  fields, NodeState); mismatches go to the editor's `onWarn`. The whole
  container read runs every time for containers of up to 256 units and is
  sampled in proportion above that (Enter in a 2,000-block document went
  from about 50 to about 12 ms in development). All tests run with it and
  fail on a warning.

Read path: a pending local `editor.update()` is committed before a remote
transaction is read; changed items are bucketed by container once per
transaction; an inserted or deleted format item re-derives the start formats
of the following units (past block nodes too) until they agree again;
each changed item is located by walking to the next end item; text edits
update lines in place; structural changes re-parse only the touched units
(groups next to them are regrouped without re-reading untouched lines);
formats that span a marker propagate only while the value at the next unit's
start changes (re-reading the next unit as a region when it cannot be
updated in place); an inline element that cannot be empty is not shown when
peers deleted all its content; NodeState keys are read in sorted order. The local selection
is captured as relative positions before each remote transaction (a caret
anchored to the character on its left, a range to its edge characters) and
restored in the same update (an end item a peer deleted is skipped when a
position is resolved). While the local editor is composing (IME), remote
inserts into the composing line are applied to Yjs but not to that line's
nodes (the browser composes into their DOM); readers and writers of that
line skip those ids, and the line is read again when the composition ends.
Deletions, formats and structure in the composing line are read at once,
keeping the composed text node (its key and text): text a peer joins into
the line goes into nodes of its own, and a composing line joined into the
next keeps its node for the merged line. Remote reads skip Lexical's
transforms, so every list whose children (or whose items' children) a read
changed is refreshed afterwards (list numbering is computed the same way on
every peer); a marker attribute a peer removed resets the field even when
exportJSON hides it (`checked` outside a check list).
A text diff with a run of equal characters places the change at the caret
(a space typed next to a space), and never splits a surrogate pair.
Follow-up updates (list renumbering, and
padding a table row that a concurrent column insert left short, done only by
the client that created the row) are kept out of the undo history.

Containers opt out of Yjs' remote formatting cleanup, which rescans every
type with formats after a remote format change (O(document) here): the
binding marks its containers as having no formats before Yjs decides. The
document's `cleanupFormatting` flag and the app's other types are untouched.

Servers on yrs before 0.28 read client ids as 32-bit numbers, while Yjs 14
draws 53-bit ones. With Yjs 14's default ids:
- a ywasm 0.23.5 relay stores an author's content under a truncated id, and
  the author receives its own content back as another client's on reconnect,
  duplicating it;
- a real yrs 0.23 server rejects the reconnect ("the awareness update is
  malformed"), and edits made offline are lost.
yrs/ywasm 0.28.0 is fine. Opt-in compatibility: `clientIDRange: 'uint32'`
(binding, extension, `writeEditorToYDoc`) or `createYDoc({compat:
'yrs-0.23'})` keeps the document's client id in 32 bits, including when Yjs
draws a new one; the id the binding uses for the initial content is always
32-bit. The default, `'uint53'`, leaves Yjs 14's ids unchanged. The binding
does not own the awareness, which takes the document's client id when it is
created; the README tells apps to create the awareness and provider from a
document that already has a 32-bit id. With 32-bit ids, a yrs 0.23 server
converges, including offline edits, reconnects and late joiners.

Undo: Yjs 14 UndoManager on the root, tracking only this binding's writes. A
container the undone change inserted that holds another client's content is
kept whole (its fields and own content too), unless the undo also restores
a container of the same type (the change was a move: keeping the copy
would duplicate it).
Cursors: `getCursor()` / `$resolveCursor()` (relative positions on items;
no provider wiring or rendering).

`@y/y` internals used (all in rc.28; a bump must re-run the cursor
equivalence test): `new Item(...)`, `item.integrate`, `getItemCleanStart`,
`createID`, `Item.left/right/origin/rightOrigin/parent/content/deleted/
countable/length`, `YNode._start`, `_item`, `_map`, `_length`,
`_searchMarker`, `_hasFormatting`, `_legacyTypeRef` (upgrade notice), the
`beforeObserverCalls` event, `doc.store.getItem/getClock`,
`iterateStructsByIdSet`, `decodeUpdate`, `findRootTypeKey`.

Supported: split, join, partial joins, heading/quote/paragraph, list type,
indent/outdent, Enter in list items, checked state, alignment and NodeState
of lines, links and other inline formats (incl. property changes and spans
across line breaks), text formats, comments as NodeState, tables and any
nested containers (collapsible-like container > title + content, cell >
collapsible, box > box), block and inline decorators, inline elements
(MarkNode) with nested content, undo/redo, cursors, local selection across
remote edits.

Known limits:
- A move is a delete and a reinsert: text a peer types into a moved line
  lands in its old neighbour. The moved block is the one rewritten (Lexical's
  record of explicit moves, `_recordNodeMoves`), not the blocks it passed.
- Lexical restructures written as moves lose a peer's concurrent typing in
  the moved paragraph: a list created from a paragraph inside a container
  that is not a shadow root (a box), indenting or pasting list items that
  hold blocks. Two peers pulling the same text across a container edge
  (range deletes from a list item into a collapsible title) both copy it.
- Properties a class keeps outside its `$config()` schema and NodeState are
  not synced; such classes are stored as nodes with a warning naming the
  properties.
- MarkNode is an element with its own content: wrapping a range moves the
  text into it, and concurrent typing in that range stays outside. Comments
  should use per-id NodeState (MarkStateExtension).
- A split racing a type change gives the first half the splitter's type;
  text typed into a line a peer removed joins the next line.
- Slots are not synchronized; a link's fields merge as a whole (last
  writer wins).
- Yjs format semantics: bold ‖ bold on adjacent ranges of one line can leave
  part unformatted (the same on Yjs 13).
- A join ‖ removal of the joined line also joins the next line (nothing
  deleted comes back); unwrapping a container is a removal and a
  reinsertion of its lines, so text a peer types inside it at the same time
  is lost, as is text typed inside a container a peer removed (delete
  wins).
- Two clients initializing with different content at once both keep their
  content (converged); a row padded by its creator only if that client is
  still around (its client id).
- Several edits to one line in a single update are written as one replace
  (a peer's caret inside it moves to the edge).
- Structural edits in a large list cost time proportional to the list on
  both sides (regrouping and renumbering): about 4x main end to end at 10,000
  items. Enter at 10,000 blocks (core text walk skipped) is 26.4 ms against
  main's 19.6 ms.
- Relies on the @y/y internals listed above.
- Version gate: the layout version must be an integer from 1 to
  `LAYOUT_VERSION`; anything else is read only.
- With Yjs 14's default 53-bit client ids, servers on yrs before 0.28
  duplicate content or lose offline edits on reconnect; use the opt-in
  32-bit range for them, and create the awareness from that document.

Known open issues (from randomized runs; see Fuzz below):
- Two peers moving the same blocks at once (move ‖ move) can duplicate or
  lose a block; 2 of 9,983 differential seeds are worse than both Yjs 13
  layouts (see Fuzz).
- Indent, outdent and paste storms in nested lists whose items hold blocks
  can leave a non-canonical list (a list with a non-item child) that fresh
  readers build differently, and duplicate items after an undo across a
  peer's indent (about 0.1% of seeds of a second, list-heavy generator).
- Rare self-check mismatches of an element's `textFormat` after concurrent
  list edits and a bold-then-undo (converged).
- Not a binding issue: `$toggleLink(null)` on a range that ends at the edge
  of a link's text throws in `$splitLinkAtSelection` (empty
  `extractedChildren`), in any editor on main; the fuzz no longer generates
  it.

## Test plan

### Before

The Yjs 13 layouts on the same scenarios, from their own branches: main v2,
#9383 and #9386 lose or misplace concurrent typing on split, join, retype,
indent and nested containers (#9386 fixes most of them on Yjs 13); bytes per
operation are in the table below.

### After

New tests in `packages/lexical-y/src/__tests__/unit` (headless peers with
pinned client ids, offline edits then sync, both id orders, causal and
per-sender delivery, two and three peers; every case checks every peer, a
fresh reader, no exception and no self-check warning):
- `BlockMarkers.test.ts`: split, join, heading, quote, list indent, list
  type, Enter in a list item, link, table cell, custom block, removals with
  three peers, and 40 randomized intent seeds;
- `Races.test.ts`: links, unlink, undo of a link, overlapping formats,
  heading/quote/split/join/indent/list type/Enter races, moves, table rows
  and cells, row insert ‖ column insert, MarkNode; moves and MarkNode are
  documented limits (converged, intent not kept);
- `Nested.test.ts`, `NestedFuzz.test.ts`: collapsible-like containers,
  collapsible in a table cell in a collapsible, box > box, six-level lists,
  mixed inline and block content, emptied containers, list numbering,
  content inside marks (links, equations, nested marks), comment state ‖
  link wrap, 20 randomized nested seeds;
- `Selection.test.ts`: carets and ranges across remote edits, link URL
  change, a space typed next to a space;
- `Composition.test.ts`: IME composition (composition key) with a peer
  inserting before, right before, after and inside the composed text, edits
  in other lines, structural edits and deletions in the composing line, a
  peer joining the lines while composing at the start of line 2 or the end
  of line 1;
- `NestedLists.test.ts`: a nested list in a table cell removed ‖ Enter in
  two of its items (3 peers), undo of a list type change after a peer
  checked an item, paste + indent + undo numbering, typing ‖ a paragraph
  turned into a list in the root, a cell and after a list;
- `LineBreakState.test.ts`: NodeState set, reset and combined with text on
  an existing line break;
- `Init.test.ts`: undo after initialization, concurrent initializations
  (same and different content), legacy roots, upgrade notice, conversion in
  place, extension (status, undo state, history conflict);
- `Storage.test.ts`: layout, every node kind, keystroke/Enter/Backspace and
  attribute-only updates, block child in a line, schema-incomplete
  subclasses, newer layout read only, no write before initialization,
  headless writer, undo, cursors;
- `Cursor.test.ts`: write cursor ≡ Y.Node#applyDelta (60 random seeds);
- `Size.test.ts`: byte budgets per operation and for a 10,000-edit session;
- `YrsCompat.test.ts`: a relay on ywasm 0.23.5 duplicates a 53-bit
  author's content on reconnect, not with `clientIDRange: 'uint32'` or
  `createYDoc({compat: 'yrs-0.23'})`, ywasm 0.28.0 handles 53-bit ids, and
  the 32-bit range survives Yjs drawing a new id (ywasm 0.23.5 and 0.28.0
  are dev dependencies);
- Regression tests: `Concurrency.test.ts` (lists, links, moves, formats in
  every order), `BlocksAndLines.test.ts` (a block inserted before a line ‖
  typing at its start, undo of a container a peer typed into, nested list
  shapes, paragraphs held by list items, moves past tables and their undo), `Ranges.test.ts` (range deletes across lines, line break
  NodeState, adjacent equal links), `Links.test.ts`, `EmptyMarks.test.ts`,
  `Tabs.test.ts`, `NestedItems.test.ts`, `NodeStateDefaults.test.ts`,
  `Document.test.ts` (group fields, pending local update),
  `Surrogates.test.ts`, `Lifecycle.test.ts` (version gate, concurrent init,
  undo across peers), `OtherRoots.test.ts`, `Nodes.test.ts` (link fields,
  schema subclasses, hand-written classes, object values, unknown types read
  only);
- `Fuzz.test.ts`: 300 seeds plus 100 with gc (3 peers, every delivery mode,
  typing, formats, links, comments, lists, tables, containers, undo/redo;
  convergence, fresh reader, canonical shape, self-check, no lost or
  duplicated tokens), longer runs through `FUZZ_SEEDS`, a differential run
  through `FUZZ_DIFF=1`; one seed where all three layouts lose the same
  token is listed in the test. `FuzzReplay.test.ts` replays 43 minimized
  scripts of fixed failures;
- `Server.test.ts`, `ServerScale.test.ts`, `Source.test.ts`: server helpers
  (old client's update, delete-only update, linear time on 8,000-paragraph
  updates, notice readable by a Yjs 13 client), fail-closed editability, no
  `process.env` but NODE_ENV in shipped source.
- Core: `LexicalCollabNodeConfig.test.ts` covers `content`.

Fuzz, differential: the same scripts run on this binding, on #9386 and on
main v2; each pair is compared on the script cut before the first op the
two runs resolved differently. "Worse than both" means @lexical/y loses or
duplicates more unique tokens, or diverges, throws, fragments or hangs,
than #9386 and than main v2:
- 9,983 seeds with block moves: 4, all move classes: two moves of the same
  list (move ‖ swap of two of its items) duplicate an item, a peer typing in
  a block another peer moved loses the typing (the moved block is the one
  rewritten; #9386 and v2 happen to rewrite the other block in these
  seeds), and one delete-wins loss where both other layouts bring a deleted
  table back.
- 9,995 seeds without moves: 0.
- 2,496 seeds with gc on: 1 (delete-wins: both others resurrect deleted
  cells).
- @lexical/y diverged, threw or fragmented on 0 of the 22,474 seeds; it
  loses fewer tokens than #9386 on about 7% of seeds and than main v2 on
  about 38%. Hangs: #9386 26, @lexical/y 0.
Within a partition, the fuzz relays updates as a sync protocol would.

A second, list-heavy generator (3-4 peers, partitions, gc on some seeds,
collapsible > table > cell > list shapes, deep lists in boxes, emoji, CJK
and Ext-B text, overlapping MarkStateExtension comments, links, line breaks,
rich paste into list items, indent storms, undo/redo; run locally, as it
needs MarkStateExtension, which is not in this stack), 6,000 seeds with
line breaks and 6,000 without: divergence 1 and 2 seeds (both
non-canonical nested lists), fresh-reader mismatches 4 and 5, element
textFormat self-check mismatches 27 and 27 (converged); most other findings
are delete-wins losses (550 and 509 seeds) and the restructure-as-move
limit above.

Real browsers (Chromium, Firefox, WebKit through Playwright; separate
contexts over a Yjs 14 WebSocket relay with a 200 ms delay; real key events;
convergence, fresh load, token checks, no console warnings, editor errors
or self-check warnings): Chromium 60/60, Firefox 53/53 and WebKit 53/53;
17 more cases (nested containers with 3 peers, lists in cells, emoji and
CJK, IME at a line boundary while a peer joins, drag and drop, comments,
reloads, a 2,000-block document): Chromium 17/17, Firefox and WebKit 13/13
(IME cases need CDP and are skipped in Firefox and WebKit). The WebKit
split + join race under load (4 workers, 100 runs): 98 passed, 2 lost to
browser crashes; an earlier caret
jump there was a position resolving across a deleted line marker.

Performance (headless Node, shared VM, medians, ms):

```
                                N=2,000            N=10,000
keystroke (end to end, 2 peers) 9.0                55.1      (main 54.3, B 50.3)
  core text walk skipped        0.53               2.1       (main 7.1, B 2.6)
Enter / Backspace               13.7 / 13.6        75.7 / 75.8 (main 74.2 / 74.7)
  core text walk skipped        4.8 / 4.8          26.4 / 27.0 (main 19.6 / 19.4)
document size (bytes)           164,000            833,603   (main 872,754,
                                (main 171,110)      A 1,006,407, B 1,391,890)
fresh load                      90                 416       (main 427, B 945)
initial bulk write (1 update)   271                1,104     (main 894, B 1,260)
```

Stress shapes (local update + write + peer read): 400 nested sections
(collapsible > table > cell > collapsible > list, box) paste 300, load 130,
208 KB; 10x10 tables 100/200/400 paste 1,099/1,875/3,864, load
412/776/1,570; bold everything in a list of 5k/10k/20k items 302/548/1,170;
add a NodeState comment in a 10k/20k/40k list 37/77/237; indent in a flat
list of 2.5k/5k/10k items 81/134/271; keystroke in a 50k/200k-character
paragraph 0.34/0.43. All linear.

Bytes per operation (gc off, client ids in Yjs' random range; op / undo /
redo):

```
                         main v2        #9383 (A)      #9386 (B)      @lexical/y
type a char mid line     25/11/26       25/11/26       25/11/26       24/10/24
paste 1k chars           1025/12/1026   1025/12/1026   1025/12/1026   1024/11/1025
Enter mid line           86/57/88       86/57/88       78/11/81       26/10/26
Backspace join           70/107/78      70/107/78      10/76/11       10/26/10
heading toggle           124/108/126    124/108/126    122/48/127     48/10/38
indent list item         134/58/135     134/58/135     54/37/57       65/27/60
link a word              175/73/190     276/11/292     282/11/292     103/10/103
bold a range             131/11/143     131/11/143     137/11/143     59/10/59
add a comment            137/11/149     137/11/149     143/11/149     65/10/65
table row insert         146/11/153     146/11/153     335/11/335     189/10/188
delete a table           10/439/11      10/439/11      11/1089/11     11/563/10
10,000-edit session      2,839,497      3,124,314      404,571        210,029
```

A Yjs 14 document written by this binding, with concurrent updates relayed
through yrs (ywasm 0.28.0), reloads into a fresh client identically; on yrs
0.23 it does with `clientIDRange: 'uint32'`.

```
$ npx vitest --project unit --no-watch packages/lexical-y/src \
    packages/lexical/src/__tests__/unit/LexicalCollabNodeConfig.test.ts
$ pnpm run tsc; pnpm run tsc-test   # exit 0
$ pnpm run flow                     # Found 0 errors
$ npx vitest --project scripts-unit --no-watch \
    scripts/__tests__/unit/treeShakingSource.test.ts
$ pnpm run prepare-release           # release build, package and type checks
$ pnpm --filter lexical-playground run build-vercel
$ pnpm --filter @lexical/website run build
```
zurfyx added a commit that referenced this pull request Oct 21, 2026
…ding with block markers

## Description

PROTOTYPE, not for merge. Stacked on #9386 (block markers on Yjs 13), whose
`$config({collab})` declarations it reuses. It shows the block-marker data
model on Yjs 14 (`@y/y`), as a new experimental package, `@lexical/y`.
`@lexical/yjs` (Yjs 13) is unchanged: Yjs 14 is a different npm package, so
a Yjs 14 binding cannot replace it in place.

Entries (all `@experimental`):
- `@lexical/y`: `YBinding`, `YCollabExtension` (binding, collaborative undo,
  `status` signal; conflicts with the history extensions),
  `writeEditorToYDoc` (headless writer for converters), `createYDoc`,
  `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and the types `YBindingOptions`,
  `YBindingStatus`, `YCursor`, `YCollabConfig`, `ClientIDRange`. No React,
  no DOM requirement.
- `@lexical/y/server`: `inspectUpdateRoots`, `isUpdateForLayout`,
  `writeUpgradeNotice`, `UpdateRoots`. No editor dependencies.
- `@lexical/y/migrate` is reserved for a converter from the Yjs 13 layouts.

`@y/y` is a peer dependency pinned to 14.0.0-rc.28, the newest release the
repository's minimum release age (7 days) allowed when this was written
(npm's `latest` tag points at an older release candidate).

Core:
- `CollabNodeConfig.content?: 'block' | 'inline'` (what a block node stored
  as its own node holds), declared `'inline'` on CodeNode.
- Text normalization no longer merges text into or out of the node being
  composed (IME): merging rewrote its DOM text node and the browser's
  composition range took in the merged text; the nodes merge when the
  composition ends.
  (Also proposed on its own against main.)

Data model (the semantics of #9386):
- Shared root `doc.get('lexical-y')`, a new root name, with a layout version
  attribute. The editor stays read only until that record has been read; a
  newer version, or content without a version, stays read only.
- `initialize()` (after the provider's first sync) marks only an empty root.
  It refuses when an older layout's root (`root`, `root-v2`) has content
  other than an upgrade notice (convert it: `writeEditorToYDoc` writes the
  layout root next to the old one). The initial content is written with a
  client id hashed from the layout version and the content, so two clients
  initializing the same content at once write it once, and outside the undo
  history.
- Every container (the root and every node stored as its own Y.Node) holds
  one sequence of text, child nodes and line markers (Yjs 14 Y.Node children
  are unified, so no XmlText per container is needed).
- A line (declared `'line'`, schema-complete) is its inline content followed
  by a marker: a child `Y.Node` named `¶` whose map attributes hold the
  line's type (left out for a paragraph), schema fields (minus derived),
  NodeState, and for a group item the group type, key fields and level. Not
  a character with formats (#9386's U+2029) and not an embed:
  * map attributes merge per key (last writer wins), so a concurrent heading
    change and indent both apply, without format start/end items in the
    sequence;
  * the marker's identity (its item) never changes when its attributes do,
    where an immutable embed would have to be replaced (and could be
    duplicated by concurrent replacements);
  * block attributes never mix with inline formats, and text may contain
    any character.
- Groups (lists) are rebuilt from consecutive items; local groups are kept
  in the same canonical shape by a transform (adjacent equal groups and
  wrapper items merged, empty groups removed); derived fields (list
  numbering) are recomputed by a refresh update on every client. All of a
  group's synced fields (and NodeState) identify it; a nested item's marker
  also records its outer groups and their wrapper items' fields (`o`), so an
  indented first item keeps its outer list's type and the wrappers' fields
  sync.
- Storage follows the class, never the instance: a declared line stays a
  line even with a block child (the child is stored as a node inside its
  content). Undeclared or invalid blocks are `b:<type>` child nodes with the
  class's own (compact) JSON as attributes; inline elements that are not
  formats and inline decorators are `i:<type>` children.
- A container records what it holds (`c`: blocks or inline content) when it
  is created, from `collab.content` or its children, and never changes it:
  leftover inline content of a block container reads as a paragraph on every
  reader; inline content directly in a block container is always ended by a
  `¦` terminator.
- Inline wrappers declared `inline: 'format'` are one format key each
  (`w:link`, whose value holds the wrapper's fields); text formats are one
  key per format (`f:bold`), plus type, JSON fields, NodeState and, for text
  nodes Lexical would not merge, a segment key (`k`). Formats apply to any
  child, so a link can span a line break or an inline decorator; a line
  break's NodeState is a format of its `\n`. Two adjacent equal links keep an
  instance key (`#`) so they stay two links on every peer.
- NodeState equal to its default is not stored (setting it back deletes
  the key). Element `textFormat`/`textStyle` are always stored.
- Schema completeness (own `$config()`, no hand-written `exportJSON`,
  `updateFromJSON` or `afterCloneFrom` below the declaring class) is
  required for lines, groups and inline formats; anything else is a node.
- Editor instances (nested caption editors) are not synchronized; JSON
  snapshots of them are (members that JSON would drop are dropped).
- A class with a hand-written serialization is a node; an edit to one of its
  own fields alone is written (the whole node's JSON is compared) and read
  through `updateFromJSON`, then `importJSON` for fields it does not know.
- Unknown types fail closed: a client that meets a node, line, text or
  group type it does not register goes read only with a warning, so it never
  hides and later deletes content it cannot show.

Write path:
- Anchored edits: Y.Node#insert/delete/format walk the type from its start
  on every call in rc.28, so the binding edits the sequence from the item it
  knows (the previous line's marker) with a port of Yjs' text position
  algorithm. A test runs random operations through it and through
  Y.Node#applyDelta and requires identical documents (byte for byte).
- A keystroke (one text node of a line changed, same formats, every other
  child unchanged including inside links) diffs only that node's old and
  new text, anchored at the caret, and writes at its offset: cost in the line's
  items, not its length (0.4 ms in a 200,000-character paragraph).
- Identity-anchored structure: units matched by node key (a weighted
  longest increasing subsequence: as many blocks as possible stay in place,
  a list counting as one block; between equal counts a block node, whose
  rewrite copies its subtree, outweighs lines). A line whose content did not
  change (node identity against the previous state, inline elements
  included) is never diffed; removed or moved units are deleted exactly;
  only split, join and type-change segments are diffed, as one sequence of
  the segment's items with the caret as the diff anchor: text that moved to
  another line keeps its items (no re-insert of a moved tail, so text a peer
  deleted is not resurrected). Each character keeps its old item only
  if it comes from the same Lexical text node as before (text nodes merged
  by a join or an unlink are attributed using the caret at the join, else
  by common prefix and suffix), so text that moved between nodes or lines is
  written as new text, never built from equal old characters. Diffs never split a
  surrogate pair. A Lexical node replaced in place by a new one keeps its
  shared node and content: a different type is recorded in the node's `t`
  attribute (a paragraph held by a list item turned into a heading keeps a
  peer's concurrent typing). Enter inserts a marker, Backspace deletes one, a
  type, indent or list type change only sets marker attributes.
- Structure is read from node links (the root is always marked dirty);
  attributes are written only for changed keys; inserted content carries its
  formats (no reformat after insert); format passes walk runs, not
  characters.
- Development self-check (default on outside production; `selfCheck` and
  `selfCheckSample` for production, also options of `YCollabExtension`):
  every line a write touched is read back from Yjs (text, formats, line
  break NodeState, marker), and every container a structural write touched,
  or where a group item's marker changed, is read whole into a fresh editor
  and compared with the editor's JSON (node types, list structure, wrapper
  fields, NodeState); mismatches go to the editor's `onWarn`. The whole
  container read runs every time for containers of up to 256 units and is
  sampled in proportion above that (Enter in a 2,000-block document went
  from about 50 to about 12 ms in development). All tests run with it and
  fail on a warning.

Read path: a pending local `editor.update()` is committed before a remote
transaction is read; changed items are bucketed by container once per
transaction; an inserted or deleted format item re-derives the start formats
of the following units (past block nodes too) until they agree again;
each changed item is located by walking to the next end item; text edits
update lines in place; structural changes re-parse only the touched units
(groups next to them are regrouped without re-reading untouched lines);
formats that span a marker propagate only while the value at the next unit's
start changes (re-reading the next unit as a region when it cannot be
updated in place); an inline element that cannot be empty is not shown when
peers deleted all its content; NodeState keys are read in sorted order. The local selection
is captured as relative positions before each remote transaction (a caret
anchored to the character on its left, a range to its edge characters) and
restored in the same update (an end item a peer deleted is skipped when a
position is resolved). While the local editor is composing (IME), remote
inserts into the composing line are applied to Yjs but not to that line's
nodes (the browser composes into their DOM); readers and writers of that
line skip those ids, and the line is read again when the composition ends.
Deletions, formats and structure in the composing line are read at once,
keeping the composed text node (its key and text): text a peer joins into
the line goes into nodes of its own, and a composing line joined into the
next keeps its node for the merged line. Remote reads skip Lexical's
transforms, so every list whose children a read changed, or whose items
gained or lost a nested list, is refreshed afterwards by running the list
class's own transforms with its siblings hidden (list numbering is computed
the same way on every peer, and a transform never merges two lists on one
peer only); groups are told apart by their declared key fields only (a list
by type and start, as Lexical merges lists), and a region read back empty
regroups its neighbours; a marker attribute a peer removed resets the field
even when exportJSON hides it (`checked` outside a check list). A NodeState
value read before its key's config was known is replaced by the known value
when the node is written (a reset comment is removed on every peer).

Recovery: a stored node a write deletes without giving it a new shared node
loses its mapping (no later write goes into a deleted node, where Yjs drops
what is inserted; this was the "cursor advanced past the end" exception on
paste); a write that throws part way is followed by a rewrite of every
container in a fresh transaction, reported through `onWarn`. (Re-reading a
container the self-check finds wrong was tried and dropped: only the
clients that sampled the check would change, so peers would diverge.)
A text diff with a run of equal characters places the change at the caret
(a space typed next to a space), and never splits a surrogate pair.
Follow-up updates (list renumbering, and
padding a table row that a concurrent column insert left short, done only by
the client that created the row) are kept out of the undo history.

Containers opt out of Yjs' remote formatting cleanup, which rescans every
type with formats after a remote format change (O(document) here): the
binding marks its containers as having no formats before Yjs decides. The
document's `cleanupFormatting` flag and the app's other types are untouched.

Servers on yrs before 0.28 read client ids as 32-bit numbers, while Yjs 14
draws 53-bit ones. With Yjs 14's default ids:
- a ywasm 0.23.5 relay stores an author's content under a truncated id, and
  the author receives its own content back as another client's on reconnect,
  duplicating it;
- a real yrs 0.23 server rejects the reconnect ("the awareness update is
  malformed"), and edits made offline are lost.
yrs/ywasm 0.28.0 is fine. Opt-in compatibility: `clientIDRange: 'uint32'`
(binding, extension, `writeEditorToYDoc`) or `createYDoc({compat:
'yrs-0.23'})` keeps the document's client id in 32 bits, including when Yjs
draws a new one; the id the binding uses for the initial content is always
32-bit. The default, `'uint53'`, leaves Yjs 14's ids unchanged. The binding
does not own the awareness, which takes the document's client id when it is
created; the README tells apps to create the awareness and provider from a
document that already has a 32-bit id. With 32-bit ids, a yrs 0.23 server
converges, including offline edits, reconnects and late joiners.

Undo: Yjs 14 UndoManager on the root, tracking only this binding's writes. A
container the undone change inserted that holds another client's content is
kept whole (its fields and own content too), unless the undo also restores
a container of the same type (the change was a move: keeping the copy
would duplicate it).
Cursors: `getCursor()` / `$resolveCursor()` (relative positions on items;
no provider wiring or rendering).

`@y/y` internals used (all in rc.28; a bump must re-run the cursor
equivalence test): `new Item(...)`, `item.integrate`, `getItemCleanStart`,
`createID`, `Item.left/right/origin/rightOrigin/parent/content/deleted/
countable/length`, `YNode._start`, `_item`, `_map`, `_length`,
`_searchMarker`, `_hasFormatting`, `_legacyTypeRef` (upgrade notice), the
`beforeObserverCalls` event, `doc.store.getItem/getClock`,
`iterateStructsByIdSet`, `decodeUpdate`, `findRootTypeKey`.

Supported: split, join, partial joins, heading/quote/paragraph, list type,
indent/outdent, Enter in list items, checked state, alignment and NodeState
of lines, links and other inline formats (incl. property changes and spans
across line breaks), text formats, comments as NodeState, tables and any
nested containers (collapsible-like container > title + content, cell >
collapsible, box > box), block and inline decorators, inline elements
(MarkNode) with nested content, undo/redo, cursors, local selection across
remote edits.

Known limits:
- A move is a delete and a reinsert: text a peer types into a moved line
  lands in its old neighbour. The cheaper side is rewritten: a long move
  rewrites the moved block, not every block it passed; in a swap the smaller
  block is re-created (a collapsible dragged past a box keeps a peer's
  typing inside it); between equal blocks the moved one (Lexical's record of
  explicit moves, `_recordNodeMoves`).
- Lexical restructures written as moves lose a peer's concurrent typing in
  the moved paragraph: a list created from a paragraph inside a container
  that is not a shadow root (a box), indenting or pasting list items that
  hold blocks. Two peers pulling the same text across a container edge
  (range deletes from a list item into a collapsible title) both copy it.
- Properties a class keeps outside its `$config()` schema and NodeState are
  not synced; such classes are stored as nodes with a warning naming the
  properties (Lexical itself drops them when it clones the node).
- MarkNode is an element with its own content: wrapping a range moves the
  text into it, and concurrent typing in that range stays outside. Comments
  should use per-id NodeState (MarkStateExtension).
- A split racing a type change gives the first half the splitter's type;
  text typed into a line a peer removed joins the next line.
- Slots are not synchronized; a link's fields merge as a whole (last
  writer wins).
- Yjs format semantics: bold ‖ bold on adjacent ranges of one line can leave
  part unformatted (the same on Yjs 13).
- A join ‖ removal of the joined line also joins the next line (nothing
  deleted comes back); unwrapping a container is a removal and a
  reinsertion of its lines, so text a peer types inside it at the same time
  is lost, as is text typed inside a container a peer removed (delete
  wins).
- Two clients initializing with different content at once both keep their
  content (converged); a row padded by its creator only if that client is
  still around (its client id).
- Several edits to one line in a single update are written as one replace
  (a peer's caret inside it moves to the edge).
- Structural edits in a large list cost time proportional to the list on
  both sides (regrouping and renumbering): about 4x main end to end at 10,000
  items. Enter at 10,000 blocks (core text walk skipped) is 26.4 ms against
  main's 19.6 ms.
- Relies on the @y/y internals listed above.
- Version gate: the layout version must be an integer from 1 to
  `LAYOUT_VERSION`; anything else is read only.
- With Yjs 14's default 53-bit client ids, servers on yrs before 0.28
  duplicate content or lose offline edits on reconnect; use the opt-in
  32-bit range for them, and create the awareness from that document.

Known open issues (from randomized runs; see Fuzz below):
- Two peers moving the same blocks at once (move ‖ move) can duplicate or
  lose a block; 2 of 9,983 differential seeds are worse than both Yjs 13
  layouts (see Fuzz).
- Lists stored as nodes inside a list item (Lexical's paste of blocks into a
  list item, or a list left directly inside a list by a join) can read back
  differently on a fresh reader after concurrent indents and undo, and
  adjacent ones of one type stay apart until the next local edit (about
  0.05% of seeds of a second, list-heavy generator).
- Rare self-check mismatches of an element's `textFormat` after concurrent
  list edits and a bold-then-undo (converged).
- Not a binding issue: `$toggleLink(null)` on a range that ends at the edge
  of a link's text throws in `$splitLinkAtSelection` (empty
  `extractedChildren`), in any editor on main; the fuzz no longer generates
  it.

## Test plan

### Before

The Yjs 13 layouts on the same scenarios, from their own branches: main v2,
#9383 and #9386 lose or misplace concurrent typing on split, join, retype,
indent and nested containers (#9386 fixes most of them on Yjs 13); bytes per
operation are in the table below.

### After

New tests in `packages/lexical-y/src/__tests__/unit` (headless peers with
pinned client ids, offline edits then sync, both id orders, causal and
per-sender delivery, two and three peers; every case checks every peer, a
fresh reader, no exception and no self-check warning):
- `BlockMarkers.test.ts`: split, join, heading, quote, list indent, list
  type, Enter in a list item, link, table cell, custom block, removals with
  three peers, and 40 randomized intent seeds;
- `Races.test.ts`: links, unlink, undo of a link, overlapping formats,
  heading/quote/split/join/indent/list type/Enter races, moves, table rows
  and cells, row insert ‖ column insert, MarkNode; moves and MarkNode are
  documented limits (converged, intent not kept);
- `Nested.test.ts`, `NestedFuzz.test.ts`: collapsible-like containers,
  collapsible in a table cell in a collapsible, box > box, six-level lists,
  mixed inline and block content, emptied containers, list numbering,
  content inside marks (links, equations, nested marks), comment state ‖
  link wrap, 20 randomized nested seeds;
- `Selection.test.ts`: carets and ranges across remote edits, link URL
  change, a space typed next to a space;
- `WriteRecovery.test.ts`: a write that throws part way is rewritten and
  reported; a nested list that becomes a level is not written into its old
  shared node;
- `Composition.test.ts`: IME composition (composition key) with a peer
  inserting before, right before, after and inside the composed text, edits
  in other lines, structural edits and deletions in the composing line, a
  peer joining the lines while composing at the start of line 2 or the end
  of line 1;
- `NestedLists.test.ts`: a nested list in a table cell removed ‖ Enter in
  two of its items (3 peers), undo of a list type change after a peer
  checked an item, paste + indent + undo numbering, typing ‖ a paragraph
  turned into a list in the root, a cell and after a list;
- `LineBreakState.test.ts`: NodeState set, reset and combined with text on
  an existing line break;
- `Init.test.ts`: undo after initialization, concurrent initializations
  (same and different content), legacy roots, upgrade notice, conversion in
  place, extension (status, undo state, history conflict);
- `Storage.test.ts`: layout, every node kind, keystroke/Enter/Backspace and
  attribute-only updates, block child in a line, schema-incomplete
  subclasses, newer layout read only, no write before initialization,
  headless writer, undo, cursors;
- `Cursor.test.ts`: write cursor ≡ Y.Node#applyDelta (60 random seeds);
- `Size.test.ts`: byte budgets per operation and for a 10,000-edit session;
- `YrsCompat.test.ts`: a relay on ywasm 0.23.5 duplicates a 53-bit
  author's content on reconnect, not with `clientIDRange: 'uint32'` or
  `createYDoc({compat: 'yrs-0.23'})`, ywasm 0.28.0 handles 53-bit ids, and
  the 32-bit range survives Yjs drawing a new id (ywasm 0.23.5 and 0.28.0
  are dev dependencies);
- Regression tests: `Concurrency.test.ts` (lists, links, moves, formats in
  every order), `BlocksAndLines.test.ts` (a block inserted before a line ‖
  typing at its start, undo of a container a peer typed into, nested list
  shapes, paragraphs held by list items, moves past tables and their undo), `Ranges.test.ts` (range deletes across lines, line break
  NodeState, adjacent equal links), `Links.test.ts`, `EmptyMarks.test.ts`,
  `Tabs.test.ts`, `NestedItems.test.ts`, `NodeStateDefaults.test.ts`,
  `Document.test.ts` (group fields, pending local update),
  `Surrogates.test.ts`, `Lifecycle.test.ts` (version gate, concurrent init,
  undo across peers), `OtherRoots.test.ts`, `Nodes.test.ts` (link fields,
  schema subclasses, hand-written classes, object values, unknown types read
  only);
- `Fuzz.test.ts`: 300 seeds plus 100 with gc (3 peers, every delivery mode,
  typing, formats, links, comments, lists, tables, containers, undo/redo;
  convergence, fresh reader, canonical shape, self-check, no lost or
  duplicated tokens), longer runs through `FUZZ_SEEDS`, a differential run
  through `FUZZ_DIFF=1`; one seed where all three layouts lose the same
  token is listed in the test. `FuzzReplay.test.ts` replays 43 minimized
  scripts of fixed failures;
- `Server.test.ts`, `ServerScale.test.ts`, `Source.test.ts`: server helpers
  (old client's update, delete-only update, linear time on 8,000-paragraph
  updates, notice readable by a Yjs 13 client), fail-closed editability, no
  `process.env` but NODE_ENV in shipped source.
- Core: `LexicalCollabNodeConfig.test.ts` covers `content`.

Fuzz, differential: the same scripts run on this binding, on #9386 and on
main v2; each pair is compared on the script cut before the first op the
two runs resolved differently. "Worse than both" means @lexical/y loses or
duplicates more unique tokens, or diverges, throws, fragments or hangs,
than #9386 and than main v2; text typed into a container a peer removed,
which the other layout keeps only by bringing back deleted content, is not
counted as lost (`resurrectionExcuse`):
- 9,983 seeds with block moves: 2, both move classes (a list moved ‖ two
  of its items swapped duplicates an item; a delete across a table ‖ a
  paragraph moved past it).
- 9,995 seeds without moves: 0.
- 2,496 seeds with gc on: 0.
- @lexical/y diverged, threw or fragmented on 0 of the 22,474 seeds; it
  loses fewer tokens than #9386 on about 7% of seeds and than main v2 on
  about 38%. Hangs: #9386 26, @lexical/y 0.
Within a partition, the fuzz relays updates as a sync protocol would.

A second, list-heavy generator (3-4 peers, partitions, gc on some seeds,
collapsible > table > cell > list shapes, deep lists in boxes, emoji, CJK
and Ext-B text, overlapping MarkStateExtension comments, links, line breaks,
rich paste into list items, indent storms, undo/redo; run locally, as it
needs MarkStateExtension, which is not in this stack): 6,000 seeds with
line breaks, 6,000 without and 3,000 with moves: divergence 1, 2 and 1
seeds, fresh-reader mismatches 3, 6 and 1 (node-stored lists inside list
items, from Lexical's paste of blocks into a list item), self-check
mismatches 12, 12 and 3 (mostly element textFormat, converged), adjacent
lists of one type stored as nodes inside a line 10, 3 and 5 (converged;
Lexical merges them on the next local edit); most other findings are
delete-wins losses and the restructure-as-move limit above.

Real browsers (Chromium, Firefox, WebKit through Playwright; separate
contexts over a Yjs 14 WebSocket relay with a 200 ms delay; real key events;
convergence, fresh load, token checks, no console warnings, editor errors
or self-check warnings): Chromium 60/60, Firefox 53/53 and WebKit 53/53;
17 more cases (nested containers with 3 peers, lists in cells, emoji and
CJK, IME at a line boundary while a peer joins, drag and drop, comments,
reloads, a 2,000-block document): Chromium 17/17, Firefox and WebKit 13/13
(IME cases need CDP and are skipped in Firefox and WebKit). The WebKit
split + join race under load (4 workers, 100 runs): 98 passed, 2 lost to
browser crashes; an earlier caret
jump there was a position resolving across a deleted line marker.

Performance (headless Node, shared VM, medians, ms):

```
                                N=2,000            N=10,000
keystroke (end to end, 2 peers) 9.0                55.1      (main 54.3, B 50.3)
  core text walk skipped        0.53               2.1       (main 7.1, B 2.6)
Enter / Backspace               13.7 / 13.6        75.7 / 75.8 (main 74.2 / 74.7)
  core text walk skipped        4.8 / 4.8          26.4 / 27.0 (main 19.6 / 19.4)
document size (bytes)           164,000            833,603   (main 872,754,
                                (main 171,110)      A 1,006,407, B 1,391,890)
fresh load                      90                 416       (main 427, B 945)
initial bulk write (1 update)   271                1,104     (main 894, B 1,260)
```

Stress shapes (local update + write + peer read): 400 nested sections
(collapsible > table > cell > collapsible > list, box) paste 300, load 130,
208 KB; 10x10 tables 100/200/400 paste 1,099/1,875/3,864, load
412/776/1,570; bold everything in a list of 5k/10k/20k items 302/548/1,170;
add a NodeState comment in a 10k/20k/40k list 37/77/237; indent in a flat
list of 2.5k/5k/10k items 81/134/271; keystroke in a 50k/200k-character
paragraph 0.34/0.43. All linear.

Bytes per operation (gc off, client ids in Yjs' random range; op / undo /
redo):

```
                         main v2        #9383 (A)      #9386 (B)      @lexical/y
type a char mid line     25/11/26       25/11/26       25/11/26       24/10/24
paste 1k chars           1025/12/1026   1025/12/1026   1025/12/1026   1024/11/1025
Enter mid line           86/57/88       86/57/88       78/11/81       26/10/26
Backspace join           70/107/78      70/107/78      10/76/11       10/26/10
heading toggle           124/108/126    124/108/126    122/48/127     48/10/38
indent list item         134/58/135     134/58/135     54/37/57       65/27/60
link a word              175/73/190     276/11/292     282/11/292     103/10/103
bold a range             131/11/143     131/11/143     137/11/143     59/10/59
add a comment            137/11/149     137/11/149     143/11/149     65/10/65
table row insert         146/11/153     146/11/153     335/11/335     189/10/188
delete a table           10/439/11      10/439/11      11/1089/11     11/563/10
10,000-edit session      2,839,497      3,124,314      404,571        210,029
```

A Yjs 14 document written by this binding, with concurrent updates relayed
through yrs (ywasm 0.28.0), reloads into a fresh client identically; on yrs
0.23 it does with `clientIDRange: 'uint32'`.

```
$ npx vitest --project unit --no-watch packages/lexical-y/src \
    packages/lexical/src/__tests__/unit/LexicalCollabNodeConfig.test.ts
$ pnpm run tsc; pnpm run tsc-test   # exit 0
$ pnpm run flow                     # Found 0 errors
$ npx vitest --project scripts-unit --no-watch \
    scripts/__tests__/unit/treeShakingSource.test.ts
$ pnpm run prepare-release           # release build, package and type checks
$ pnpm --filter lexical-playground run build-vercel
$ pnpm --filter @lexical/website run build
```
@zurfyx

zurfyx commented Oct 21, 2026

Copy link
Copy Markdown
Member Author

Agreed that space matters at least as much as time, so it's now a first-class, committed metric. The Yjs 14 version of this layout is up as #9400 (@lexical/y, stacked on this PR), with a Size.test.ts that fails if any operation's byte cost grows more than ~10% over its budget.

Bytes added per operation (gc off, client ids in Yjs' random range; op / undo / redo):

operation main v2 #9383 (A) #9386 (this PR) #9400 @lexical/y
type a char mid line 25/11/26 25/11/26 25/11/26 24/10/24
Enter mid line 86/57/88 86/57/88 78/11/81 26/10/26
Backspace join 70/107/78 70/107/78 10/76/11 10/26/10
heading toggle 124/108/126 124/108/126 122/48/127 48/10/38
indent list item 134/58/135 134/58/135 54/37/57 65/27/60
link a word 175/73/190 276/11/292 282/11/292 103/10/103
bold a range 131/11/143 131/11/143 137/11/143 59/10/59
add a comment (NodeState) 137/11/149 137/11/149 143/11/149 65/10/65
table row insert 146/11/153 146/11/153 335/11/335 189/10/188
10,000-edit scripted session 2,839,497 3,124,314 404,571 210,029

At 10k blocks the whole document is 834 KB with @lexical/y vs 873 KB on main v2 (this PR: 1.39 MB, because of the U+2029 marker plus formats). On time, nothing is superlinear in the stress shapes we tried (200 tables, bold-all on a 10k list, 20k comments, depth-40 nesting, a 200k-character paragraph). Keystroke cost at 10k blocks is about the same as main in every layout, and ~80% of it is Lexical core walking the whole document text on each commit, which is worth a separate core change. With @y/y rc.28, Y.Node#applyDelta walks a type from its start on every insert, which goes quadratic once a container is one sequence. So @lexical/y uses its own anchored write cursor (an equivalence test checks it against applyDelta), and it turns off cleanupFormatting because that rescans the whole type after every remote format.

zurfyx added a commit that referenced this pull request Oct 21, 2026
…ding with block markers

## Description

PROTOTYPE, not for merge. Stacked on #9386 (block markers on Yjs 13), whose
`$config({collab})` declarations it reuses. It shows the block-marker data
model on Yjs 14 (`@y/y`), as a new experimental package, `@lexical/y`.
`@lexical/yjs` (Yjs 13) is unchanged: Yjs 14 is a different npm package, so
a Yjs 14 binding cannot replace it in place.

Entries (all `@experimental`):
- `@lexical/y`: `YBinding`, `YCollabExtension` (binding, collaborative undo,
  `status` signal; conflicts with the history extensions),
  `writeEditorToYDoc` (headless writer for converters), `createYDoc`,
  `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and the types `YBindingOptions`,
  `YBindingStatus`, `YCursor`, `YCollabConfig`, `ClientIDRange`. No React,
  no DOM requirement.
- `@lexical/y/server`: `inspectUpdateRoots`, `isUpdateForLayout`,
  `writeUpgradeNotice`, `UpdateRoots`. No editor dependencies.
- `@lexical/y/migrate` is reserved for a converter from the Yjs 13 layouts.

`@y/y` is a peer dependency pinned to 14.0.0-rc.28, the newest release the
repository's minimum release age (7 days) allowed when this was written
(npm's `latest` tag points at an older release candidate).

Core:
- `CollabNodeConfig.content?: 'block' | 'inline'` (what a block node stored
  as its own node holds), declared `'inline'` on CodeNode.
- Text normalization no longer merges text into or out of the node being
  composed (IME): merging rewrote its DOM text node and the browser's
  composition range took in the merged text; the nodes merge when the
  composition ends.
  (Also proposed on its own against main.)

Data model (the semantics of #9386):
- Shared root `doc.get('lexical-y')`, a new root name, with a layout version
  attribute. The editor stays read only until that record has been read; a
  newer version, or content without a version, stays read only.
- `initialize()` (after the provider's first sync) marks only an empty root.
  It refuses when an older layout's root (`root`, `root-v2`) has content
  other than an upgrade notice (convert it: `writeEditorToYDoc` writes the
  layout root next to the old one). The initial content is written with a
  client id hashed from the layout version and the content, so two clients
  initializing the same content at once write it once, and outside the undo
  history.
- Every container (the root and every node stored as its own Y.Node) holds
  one sequence of text, child nodes and line markers (Yjs 14 Y.Node children
  are unified, so no XmlText per container is needed).
- A line (declared `'line'`, schema-complete) is its inline content followed
  by a marker: a child `Y.Node` named `¶` whose map attributes hold the
  line's type (left out for a paragraph), schema fields (minus derived),
  NodeState, and for a group item the group type, key fields and level. Not
  a character with formats (#9386's U+2029) and not an embed:
  * map attributes merge per key (last writer wins), so a concurrent heading
    change and indent both apply, without format start/end items in the
    sequence;
  * the marker's identity (its item) never changes when its attributes do,
    where an immutable embed would have to be replaced (and could be
    duplicated by concurrent replacements);
  * block attributes never mix with inline formats, and text may contain
    any character.
- Groups (lists) are rebuilt from consecutive items; local groups are kept
  in the same canonical shape by a transform (adjacent equal groups and
  wrapper items merged, empty groups removed); derived fields (list
  numbering) are recomputed by a refresh update on every client. All of a
  group's synced fields (and NodeState) identify it; a nested item's marker
  also records its outer groups and their wrapper items' fields (`o`), so an
  indented first item keeps its outer list's type and the wrappers' fields
  sync.
- Storage follows the class, never the instance: a declared line stays a
  line even with a block child (the child is stored as a node inside its
  content). Undeclared or invalid blocks are `b:<type>` child nodes with the
  class's own (compact) JSON as attributes; inline elements that are not
  formats and inline decorators are `i:<type>` children.
- A container records what it holds (`c`: blocks or inline content) when it
  is created, from `collab.content` or its children, and never changes it:
  leftover inline content of a block container reads as a paragraph on every
  reader; inline content directly in a block container is always ended by a
  `¦` terminator.
- Inline wrappers declared `inline: 'format'` are one format key each
  (`w:link`, whose value holds the wrapper's fields); text formats are one
  key per format (`f:bold`), plus type, JSON fields, NodeState and, for text
  nodes Lexical would not merge, a segment key (`k`). Formats apply to any
  child, so a link can span a line break or an inline decorator; a line
  break's NodeState is a format of its `\n`. Two adjacent equal links keep an
  instance key (`#`) so they stay two links on every peer.
- NodeState equal to its default is not stored (setting it back deletes
  the key). Element `textFormat`/`textStyle` are always stored.
- Schema completeness (own `$config()`, no hand-written `exportJSON`,
  `updateFromJSON` or `afterCloneFrom` below the declaring class) is
  required for lines, groups and inline formats; anything else is a node.
- Editor instances (nested caption editors) are not synchronized; JSON
  snapshots of them are (members that JSON would drop are dropped).
- A class with a hand-written serialization is a node; an edit to one of its
  own fields alone is written (the whole node's JSON is compared) and read
  through `updateFromJSON`, then `importJSON` for fields it does not know.
- Unknown types fail closed: a client that meets a node, line, text or
  group type it does not register goes read only with a warning, so it never
  hides and later deletes content it cannot show.

Write path:
- Anchored edits: Y.Node#insert/delete/format walk the type from its start
  on every call in rc.28, so the binding edits the sequence from the item it
  knows (the previous line's marker) with a port of Yjs' text position
  algorithm. A test runs random operations through it and through
  Y.Node#applyDelta and requires identical documents (byte for byte).
- A keystroke (one text node of a line changed, same formats, every other
  child unchanged including inside links) diffs only that node's old and
  new text, anchored at the caret, and writes at its offset: cost in the line's
  items, not its length (0.4 ms in a 200,000-character paragraph).
- Identity-anchored structure: units matched by node key (a weighted
  longest increasing subsequence: as many blocks as possible stay in place,
  a list counting as one block; between equal counts a block node, whose
  rewrite copies its subtree, outweighs lines). A line whose content did not
  change (node identity against the previous state, inline elements
  included) is never diffed; removed or moved units are deleted exactly;
  only split, join and type-change segments are diffed, as one sequence of
  the segment's items with the caret as the diff anchor: text that moved to
  another line keeps its items (no re-insert of a moved tail, so text a peer
  deleted is not resurrected). Each character keeps its old item only
  if it comes from the same Lexical text node as before (text nodes merged
  by a join or an unlink are attributed using the caret at the join, else
  by common prefix and suffix), so text that moved between nodes or lines is
  written as new text, never built from equal old characters. Diffs never split a
  surrogate pair. A Lexical node replaced in place by a new one keeps its
  shared node and content: a different type is recorded in the node's `t`
  attribute (a paragraph held by a list item turned into a heading keeps a
  peer's concurrent typing). Enter inserts a marker, Backspace deletes one, a
  type, indent or list type change only sets marker attributes.
- Structure is read from node links (the root is always marked dirty);
  attributes are written only for changed keys; inserted content carries its
  formats (no reformat after insert); format passes walk runs, not
  characters.
- Development self-check (default on outside production; `selfCheck` and
  `selfCheckSample` for production, also options of `YCollabExtension`):
  every line a write touched is read back from Yjs (text, formats, line
  break NodeState, marker), and every container a structural write touched,
  or where a group item's marker changed, is read whole into a fresh editor
  and compared with the editor's JSON (node types, list structure, wrapper
  fields, NodeState); mismatches go to the editor's `onWarn`. The whole
  container read runs every time for containers of up to 256 units and is
  sampled in proportion above that (Enter in a 2,000-block document went
  from about 50 to about 12 ms in development). All tests run with it and
  fail on a warning.

Read path: a pending local `editor.update()` is committed before a remote
transaction is read; changed items are bucketed by container once per
transaction; an inserted or deleted format item re-derives the start formats
of the following units (past block nodes too) until they agree again;
each changed item is located by walking to the next end item; text edits
update lines in place; structural changes re-parse only the touched units
(groups next to them are regrouped without re-reading untouched lines);
formats that span a marker propagate only while the value at the next unit's
start changes (re-reading the next unit as a region when it cannot be
updated in place); an inline element that cannot be empty is not shown when
peers deleted all its content; NodeState keys are read in sorted order. The local selection
is captured as relative positions before each remote transaction (a caret
anchored to the character on its left, a range to its edge characters) and
restored in the same update (an end item a peer deleted is skipped when a
position is resolved). While the local editor is composing (IME), remote
inserts into the composing line are applied to Yjs but not to that line's
nodes (the browser composes into their DOM); readers and writers of that
line skip those ids, and the line is read again when the composition ends.
Deletions, formats and structure in the composing line are read at once,
keeping the composed text node (its key and text): text a peer joins into
the line goes into nodes of its own, and a composing line joined into the
next keeps its node for the merged line. Remote reads skip Lexical's
transforms, so every list whose children a read changed, or whose items
gained or lost a nested list, is refreshed afterwards by running the list
class's own transforms with its siblings hidden (list numbering is computed
the same way on every peer, and a transform never merges two lists on one
peer only); groups are told apart by their first declared key field only (a
list by its type, as Lexical merges lists), and a region read back empty
regroups its neighbours. Groups and wrapper items carry their textFormat and
textStyle (Lexical serializes them only while an element has no text), and
each wrapper reads the fields its own group recorded. A list stored as a
node inside a line (Lexical keeps blocks pasted into a list item inside it)
reads text left without a marker as one of its items; an element that cannot
be empty is shown only while its content is not, on every reader; and two
such lists of one type that end up next to each other (added by two peers at
once) are merged by exactly one client, the one that created the second, in
an update kept out of the undo history. When the local tree joins two
wrapper items, the nested lists they hold are joined too, as a reader builds
them. A link's own textFormat is stored with its value. The character diff
of a line places a change at the caret only while the text after the caret
is unchanged (after a join the caret is before the new text). A marker
attribute a peer removed resets the field even when exportJSON hides it
(`checked` outside a check list). A NodeState value read before its key's
config was known is replaced by the known value when the node is written (a
reset comment is removed on every peer).

Recovery: a stored node a write deletes without giving it a new shared node
loses its mapping (no later write goes into a deleted node, where Yjs drops
what is inserted; this was the "cursor advanced past the end" exception on
paste); a write that throws part way is followed by a rewrite of every
container in a fresh transaction, reported through `onWarn`. (Re-reading a
container the self-check finds wrong was tried and dropped: only the
clients that sampled the check would change, so peers would diverge.)
A text diff with a run of equal characters places the change at the caret
(a space typed next to a space), and never splits a surrogate pair.
Follow-up updates (list renumbering, and
padding a table row that a concurrent column insert left short, done only by
the client that created the row) are kept out of the undo history.

Containers opt out of Yjs' remote formatting cleanup, which rescans every
type with formats after a remote format change (O(document) here): the
binding marks its containers as having no formats before Yjs decides. The
document's `cleanupFormatting` flag and the app's other types are untouched.

Servers on yrs before 0.28 read client ids as 32-bit numbers, while Yjs 14
draws 53-bit ones. With Yjs 14's default ids:
- a ywasm 0.23.5 relay stores an author's content under a truncated id, and
  the author receives its own content back as another client's on reconnect,
  duplicating it;
- a real yrs 0.23 server rejects the reconnect ("the awareness update is
  malformed"), and edits made offline are lost.
yrs/ywasm 0.28.0 is fine. Opt-in compatibility: `clientIDRange: 'uint32'`
(binding, extension, `writeEditorToYDoc`) or `createYDoc({compat:
'yrs-0.23'})` keeps the document's client id in 32 bits, including when Yjs
draws a new one; the id the binding uses for the initial content is always
32-bit. The default, `'uint53'`, leaves Yjs 14's ids unchanged. The binding
does not own the awareness, which takes the document's client id when it is
created; the README tells apps to create the awareness and provider from a
document that already has a 32-bit id. With 32-bit ids, a yrs 0.23 server
converges, including offline edits, reconnects and late joiners.

Undo: Yjs 14 UndoManager on the root, tracking only this binding's writes. A
container the undone change inserted that holds another client's content is
kept whole (its fields and own content too), unless the undo also restores
a container of the same type (the change was a move: keeping the copy
would duplicate it).
Cursors: `getCursor()` / `$resolveCursor()` (relative positions on items;
no provider wiring or rendering).

`@y/y` internals used (all in rc.28; a bump must re-run the cursor
equivalence test): `new Item(...)`, `item.integrate`, `getItemCleanStart`,
`createID`, `Item.left/right/origin/rightOrigin/parent/content/deleted/
countable/length`, `YNode._start`, `_item`, `_map`, `_length`,
`_searchMarker`, `_hasFormatting`, `_legacyTypeRef` (upgrade notice), the
`beforeObserverCalls` event, `doc.store.getItem/getClock`,
`iterateStructsByIdSet`, `decodeUpdate`, `findRootTypeKey`.

Supported: split, join, partial joins, heading/quote/paragraph, list type,
indent/outdent, Enter in list items, checked state, alignment and NodeState
of lines, links and other inline formats (incl. property changes and spans
across line breaks), text formats, comments as NodeState, tables and any
nested containers (collapsible-like container > title + content, cell >
collapsible, box > box), block and inline decorators, inline elements
(MarkNode) with nested content, undo/redo, cursors, local selection across
remote edits.

Known limits:
- A move is a delete and a reinsert: text a peer types into a moved line
  lands in its old neighbour. The cheaper side is rewritten: a long move
  rewrites the moved block, not every block it passed; in a swap the smaller
  block is re-created (a collapsible dragged past a box keeps a peer's
  typing inside it); between equal blocks the moved one (Lexical's record of
  explicit moves, `_recordNodeMoves`).
- Lexical restructures written as moves lose a peer's concurrent typing in
  the moved paragraph: a list created from a paragraph inside a container
  that is not a shadow root (a box), indenting or pasting list items that
  hold blocks. Two peers pulling the same text across a container edge
  (range deletes from a list item into a collapsible title) both copy it.
- Properties a class keeps outside its `$config()` schema and NodeState are
  not synced; such classes are stored as nodes with a warning naming the
  properties (Lexical itself drops them when it clones the node).
- MarkNode is an element with its own content: wrapping a range moves the
  text into it, and concurrent typing in that range stays outside. Comments
  should use per-id NodeState (MarkStateExtension).
- A split racing a type change gives the first half the splitter's type;
  text typed into a line a peer removed joins the next line.
- Slots are not synchronized; a link's fields merge as a whole (last
  writer wins).
- Yjs format semantics: bold ‖ bold on adjacent ranges of one line can leave
  part unformatted (the same on Yjs 13).
- A join ‖ removal of the joined line also joins the next line (nothing
  deleted comes back); unwrapping a container is a removal and a
  reinsertion of its lines, so text a peer types inside it at the same time
  is lost, as is text typed inside a container a peer removed (delete
  wins).
- Two clients initializing with different content at once both keep their
  content (converged); a row padded by its creator only if that client is
  still around (its client id).
- Several edits to one line in a single update are written as one replace
  (a peer's caret inside it moves to the edge).
- Structural edits in a large list cost time proportional to the list on
  both sides (regrouping and renumbering): about 4x main end to end at 10,000
  items. Enter at 10,000 blocks (core text walk skipped) is 26.4 ms against
  main's 19.6 ms.
- Relies on the @y/y internals listed above.
- Version gate: the layout version must be an integer from 1 to
  `LAYOUT_VERSION`; anything else is read only.
- With Yjs 14's default 53-bit client ids, servers on yrs before 0.28
  duplicate content or lose offline edits on reconnect; use the opt-in
  32-bit range for them, and create the awareness from that document.

Known open issues (from randomized runs; see Fuzz below):
- Two peers moving the same blocks at once (move ‖ move) can duplicate or
  lose a block; 2 of 9,983 differential seeds are worse than both Yjs 13
  layouts (see Fuzz).
- NodeState keys of a node keep the order of the author's local history in
  its own editor (values equal; other clients read them sorted).
- Not a binding issue: `$toggleLink(null)` on a range that ends at the edge
  of a link's text throws in `$splitLinkAtSelection` (empty
  `extractedChildren`), in any editor on main; the fuzz no longer generates
  it.

## Test plan

### Before

The Yjs 13 layouts on the same scenarios, from their own branches: main v2,
#9383 and #9386 lose or misplace concurrent typing on split, join, retype,
indent and nested containers (#9386 fixes most of them on Yjs 13); bytes per
operation are in the table below.

### After

New tests in `packages/lexical-y/src/__tests__/unit` (headless peers with
pinned client ids, offline edits then sync, both id orders, causal and
per-sender delivery, two and three peers; every case checks every peer, a
fresh reader, no exception and no self-check warning):
- `BlockMarkers.test.ts`: split, join, heading, quote, list indent, list
  type, Enter in a list item, link, table cell, custom block, removals with
  three peers, and 40 randomized intent seeds;
- `Races.test.ts`: links, unlink, undo of a link, overlapping formats,
  heading/quote/split/join/indent/list type/Enter races, moves, table rows
  and cells, row insert ‖ column insert, MarkNode; moves and MarkNode are
  documented limits (converged, intent not kept);
- `Nested.test.ts`, `NestedFuzz.test.ts`: collapsible-like containers,
  collapsible in a table cell in a collapsible, box > box, six-level lists,
  mixed inline and block content, emptied containers, list numbering,
  content inside marks (links, equations, nested marks), comment state ‖
  link wrap, 20 randomized nested seeds;
- `Selection.test.ts`: carets and ranges across remote edits, link URL
  change, a space typed next to a space;
- `WriteRecovery.test.ts`: a write that throws part way is rewritten and
  reported; a nested list that becomes a level is not written into its old
  shared node;
- `ListsInLines.test.ts`: lists inside a list item added by two peers merge
  once; text left in a removed item reads as an item; an emptied list is
  hidden on every reader; joined wrapper items join their lists; wrapper,
  group and link text formats; a join ‖ delete keeps the joined text whole;
- `Composition.test.ts`: IME composition (composition key) with a peer
  inserting before, right before, after and inside the composed text, edits
  in other lines, structural edits and deletions in the composing line, a
  peer joining the lines while composing at the start of line 2 or the end
  of line 1;
- `NestedLists.test.ts`: a nested list in a table cell removed ‖ Enter in
  two of its items (3 peers), undo of a list type change after a peer
  checked an item, paste + indent + undo numbering, typing ‖ a paragraph
  turned into a list in the root, a cell and after a list;
- `LineBreakState.test.ts`: NodeState set, reset and combined with text on
  an existing line break;
- `Init.test.ts`: undo after initialization, concurrent initializations
  (same and different content), legacy roots, upgrade notice, conversion in
  place, extension (status, undo state, history conflict);
- `Storage.test.ts`: layout, every node kind, keystroke/Enter/Backspace and
  attribute-only updates, block child in a line, schema-incomplete
  subclasses, newer layout read only, no write before initialization,
  headless writer, undo, cursors;
- `Cursor.test.ts`: write cursor ≡ Y.Node#applyDelta (60 random seeds);
- `Size.test.ts`: byte budgets per operation and for a 10,000-edit session;
- `YrsCompat.test.ts`: a relay on ywasm 0.23.5 duplicates a 53-bit
  author's content on reconnect, not with `clientIDRange: 'uint32'` or
  `createYDoc({compat: 'yrs-0.23'})`, ywasm 0.28.0 handles 53-bit ids, and
  the 32-bit range survives Yjs drawing a new id (ywasm 0.23.5 and 0.28.0
  are dev dependencies);
- Regression tests: `Concurrency.test.ts` (lists, links, moves, formats in
  every order), `BlocksAndLines.test.ts` (a block inserted before a line ‖
  typing at its start, undo of a container a peer typed into, nested list
  shapes, paragraphs held by list items, moves past tables and their undo), `Ranges.test.ts` (range deletes across lines, line break
  NodeState, adjacent equal links), `Links.test.ts`, `EmptyMarks.test.ts`,
  `Tabs.test.ts`, `NestedItems.test.ts`, `NodeStateDefaults.test.ts`,
  `Document.test.ts` (group fields, pending local update),
  `Surrogates.test.ts`, `Lifecycle.test.ts` (version gate, concurrent init,
  undo across peers), `OtherRoots.test.ts`, `Nodes.test.ts` (link fields,
  schema subclasses, hand-written classes, object values, unknown types read
  only);
- `Fuzz.test.ts`: 300 seeds plus 100 with gc (3 peers, every delivery mode,
  typing, formats, links, comments, lists, tables, containers, undo/redo;
  convergence, fresh reader, canonical shape, self-check, no lost or
  duplicated tokens), longer runs through `FUZZ_SEEDS`, a differential run
  through `FUZZ_DIFF=1`; one seed where all three layouts lose the same
  token is listed in the test. `FuzzReplay.test.ts` replays 43 minimized
  scripts of fixed failures;
- `Server.test.ts`, `ServerScale.test.ts`, `Source.test.ts`: server helpers
  (old client's update, delete-only update, linear time on 8,000-paragraph
  updates, notice readable by a Yjs 13 client), fail-closed editability, no
  `process.env` but NODE_ENV in shipped source.
- Core: `LexicalCollabNodeConfig.test.ts` covers `content`.

Fuzz, differential: the same scripts run on this binding, on #9386 and on
main v2; each pair is compared on the script cut before the first op the
two runs resolved differently. "Worse than both" means @lexical/y loses or
duplicates more unique tokens, or diverges, throws, fragments or hangs,
than #9386 and than main v2; text typed into a container a peer removed,
which the other layout keeps only by bringing back deleted content, is not
counted as lost (`resurrectionExcuse`):
- 9,983 seeds with block moves: 2, both move classes (a list moved ‖ two
  of its items swapped duplicates an item; a delete across a table ‖ a
  paragraph moved past it).
- 9,995 seeds without moves: 0.
- 2,496 seeds with gc on: 0.
- @lexical/y diverged, threw or fragmented on 0 of the 22,474 seeds; it
  loses fewer tokens than #9386 on about 7% of seeds and than main v2 on
  about 38%. Hangs: #9386 26, @lexical/y 0.
Within a partition, the fuzz relays updates as a sync protocol would.

A second, list-heavy generator (3-4 peers, partitions, gc on some seeds,
collapsible > table > cell > list shapes, deep lists in boxes, emoji, CJK
and Ext-B text, overlapping MarkStateExtension comments, links, line breaks,
rich paste into list items, indent storms, undo/redo; run locally, as it
needs MarkStateExtension, which is not in this stack): 6,000 seeds with line
breaks, 6,000 without and 3,000 with moves: 0 divergence, 0 fresh-reader
mismatches, 0 self-check warnings and 0 non-canonical shapes (adjacent equal
lists, empty lists, lists with other children); remaining findings are
delete-wins losses, the restructure-as-move limit above (1.2% of seeds
duplicate an item, 2.5% with moves) and NodeState key order in the author's
own editor.

Real browsers (Chromium, Firefox, WebKit through Playwright; separate
contexts over a Yjs 14 WebSocket relay with a 200 ms delay; real key events;
convergence, fresh load, token checks, no console warnings, editor errors
or self-check warnings): Chromium 60/60, Firefox 53/53 and WebKit 53/53;
17 more cases (nested containers with 3 peers, lists in cells, emoji and
CJK, IME at a line boundary while a peer joins, drag and drop, comments,
reloads, a 2,000-block document): Chromium 17/17, Firefox and WebKit 13/13
(IME cases need CDP and are skipped in Firefox and WebKit). The WebKit
split + join race under load (4 workers, 100 runs): 98 passed, 2 lost to
browser crashes; an earlier caret
jump there was a position resolving across a deleted line marker.

Performance (headless Node, shared VM, medians, ms):

```
                                N=2,000            N=10,000
keystroke (end to end, 2 peers) 9.0                55.1      (main 54.3, B 50.3)
  core text walk skipped        0.53               2.1       (main 7.1, B 2.6)
Enter / Backspace               13.7 / 13.6        75.7 / 75.8 (main 74.2 / 74.7)
  core text walk skipped        4.8 / 4.8          26.4 / 27.0 (main 19.6 / 19.4)
document size (bytes)           164,000            833,603   (main 872,754,
                                (main 171,110)      A 1,006,407, B 1,391,890)
fresh load                      90                 416       (main 427, B 945)
initial bulk write (1 update)   271                1,104     (main 894, B 1,260)
```

Stress shapes (local update + write + peer read): 400 nested sections
(collapsible > table > cell > collapsible > list, box) paste 300, load 130,
208 KB; 10x10 tables 100/200/400 paste 1,099/1,875/3,864, load
412/776/1,570; bold everything in a list of 5k/10k/20k items 302/548/1,170;
add a NodeState comment in a 10k/20k/40k list 37/77/237; indent in a flat
list of 2.5k/5k/10k items 81/134/271; keystroke in a 50k/200k-character
paragraph 0.34/0.43. All linear.

Bytes per operation (gc off, client ids in Yjs' random range; op / undo /
redo):

```
                         main v2        #9383 (A)      #9386 (B)      @lexical/y
type a char mid line     25/11/26       25/11/26       25/11/26       24/10/24
paste 1k chars           1025/12/1026   1025/12/1026   1025/12/1026   1024/11/1025
Enter mid line           86/57/88       86/57/88       78/11/81       26/10/26
Backspace join           70/107/78      70/107/78      10/76/11       10/26/10
heading toggle           124/108/126    124/108/126    122/48/127     48/10/38
indent list item         134/58/135     134/58/135     54/37/57       65/27/60
link a word              175/73/190     276/11/292     282/11/292     103/10/103
bold a range             131/11/143     131/11/143     137/11/143     59/10/59
add a comment            137/11/149     137/11/149     143/11/149     65/10/65
table row insert         146/11/153     146/11/153     335/11/335     189/10/188
delete a table           10/439/11      10/439/11      11/1089/11     11/563/10
10,000-edit session      2,839,497      3,124,314      404,571        210,029
```

A Yjs 14 document written by this binding, with concurrent updates relayed
through yrs (ywasm 0.28.0), reloads into a fresh client identically; on yrs
0.23 it does with `clientIDRange: 'uint32'`.

```
$ npx vitest --project unit --no-watch packages/lexical-y/src \
    packages/lexical/src/__tests__/unit/LexicalCollabNodeConfig.test.ts
$ pnpm run tsc; pnpm run tsc-test   # exit 0
$ pnpm run flow                     # Found 0 errors
$ npx vitest --project scripts-unit --no-watch \
    scripts/__tests__/unit/treeShakingSource.test.ts
$ pnpm run prepare-release           # release build, package and type checks
$ pnpm --filter lexical-playground run build-vercel
$ pnpm --filter @lexical/website run build
```
zurfyx added a commit that referenced this pull request Oct 21, 2026
…ding with block markers

## Description

PROTOTYPE, not for merge. Stacked on #9386 (block markers on Yjs 13), whose
`$config({collab})` declarations it reuses. It shows the block-marker data
model on Yjs 14 (`@y/y`), as a new experimental package, `@lexical/y`.
`@lexical/yjs` (Yjs 13) is unchanged: Yjs 14 is a different npm package, so
a Yjs 14 binding cannot replace it in place.

Entries (all `@experimental`):
- `@lexical/y`: `YBinding`, `YCollabExtension` (binding, collaborative undo,
  `status` signal; conflicts with the history extensions),
  `writeEditorToYDoc` (headless writer for converters), `createYDoc`,
  `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and the types `YBindingOptions`,
  `YBindingStatus`, `YCursor`, `YCollabConfig`, `ClientIDRange`. No React,
  no DOM requirement.
- `@lexical/y/server`: `inspectUpdateRoots`, `isUpdateForLayout`,
  `writeUpgradeNotice`, `UpdateRoots`. No editor dependencies.
- `@lexical/y/migrate` is reserved for a converter from the Yjs 13 layouts.

`@y/y` is a peer dependency pinned to 14.0.0-rc.28, the newest release the
repository's minimum release age (7 days) allowed when this was written
(npm's `latest` tag points at an older release candidate).

Core:
- `CollabNodeConfig.content?: 'block' | 'inline'` (what a block node stored
  as its own node holds), declared `'inline'` on CodeNode.
- Text normalization no longer merges text into or out of the node being
  composed (IME): merging rewrote its DOM text node and the browser's
  composition range took in the merged text; the nodes merge when the
  composition ends.
  (Also proposed on its own against main.)

Data model (the semantics of #9386):
- Shared root `doc.get('lexical-y')`, a new root name, with a layout version
  attribute. The editor stays read only until that record has been read; a
  newer version, or content without a version, stays read only.
- `initialize()` (after the provider's first sync) marks only an empty root.
  It refuses when an older layout's root (`root`, `root-v2`) has content
  other than an upgrade notice (convert it: `writeEditorToYDoc` writes the
  layout root next to the old one). The initial content is written with a
  client id hashed from the layout version, the target shared type (its
  top-level name or item id) and the exact items written (encoded from a
  scratch document), so two clients initializing the same content into the
  same root at once write it once, while different roots or content never
  share an id; outside the undo history.
- Every container (the root and every node stored as its own Y.Node) holds
  one sequence of text, child nodes and line markers (Yjs 14 Y.Node children
  are unified, so no XmlText per container is needed).
- A line (declared `'line'`, schema-complete) is its inline content followed
  by a marker: a child `Y.Node` named `¶` whose map attributes hold the
  line's type (left out for a paragraph), schema fields (minus derived),
  NodeState, and for a group item the group type, key fields and level. Not
  a character with formats (#9386's U+2029) and not an embed:
  * map attributes merge per key (last writer wins), so a concurrent heading
    change and indent both apply, without format start/end items in the
    sequence;
  * the marker's identity (its item) never changes when its attributes do,
    where an immutable embed would have to be replaced (and could be
    duplicated by concurrent replacements);
  * block attributes never mix with inline formats, and text may contain
    any character.
- Groups (lists) are rebuilt from consecutive items; local groups are kept
  in the same canonical shape by a transform (adjacent equal groups and
  wrapper items merged, empty groups removed); derived fields (list
  numbering) are recomputed by a refresh update on every client. All of a
  group's synced fields (and NodeState) identify it; a nested item's marker
  also records its outer groups and their wrapper items' fields (`o`), so an
  indented first item keeps its outer list's type and the wrappers' fields
  sync.
- Storage follows the class, never the instance: a declared line stays a
  line even with a block child (the child is stored as a node inside its
  content). Undeclared or invalid blocks are `b:<type>` child nodes with the
  class's own (compact) JSON as attributes; inline elements that are not
  formats and inline decorators are `i:<type>` children.
- A container records what it holds (`c`: blocks or inline content) when it
  is created, from `collab.content` or its children, and never changes it:
  leftover inline content of a block container reads as a paragraph on every
  reader; inline content directly in a block container is always ended by a
  `¦` terminator.
- Inline wrappers declared `inline: 'format'` are one format key each
  (`w:link`, whose value holds the wrapper's fields); text formats are one
  key per format (`f:bold`), plus type, JSON fields, NodeState and, for text
  nodes Lexical would not merge, a segment key (`k`). Formats apply to any
  child, so a link can span a line break or an inline decorator; a line
  break's NodeState is a format of its `\n`. Two adjacent equal links keep an
  instance key (`#`) so they stay two links on every peer.
- NodeState equal to its default is not stored (setting it back deletes
  the key). Element `textFormat`/`textStyle` are always stored.
- Schema completeness (own `$config()`, no hand-written `exportJSON`,
  `updateFromJSON` or `afterCloneFrom` below the declaring class) is
  required for lines, groups and inline formats; anything else is a node.
- Editor instances (nested caption editors) are not synchronized; JSON
  snapshots of them are (members that JSON would drop are dropped).
- A class with a hand-written serialization is a node; an edit to one of its
  own fields alone is written (the whole node's JSON is compared) and read
  through `updateFromJSON`, then `importJSON` for fields it does not know.
- Unknown types fail closed: a client that meets a node, line, text or
  group type it does not register goes read only with a warning, so it never
  hides and later deletes content it cannot show.

Write path:
- Anchored edits: Y.Node#insert/delete/format walk the type from its start
  on every call in rc.28, so the binding edits the sequence from the item it
  knows (the previous line's marker) with a port of Yjs' text position
  algorithm. A test runs random operations through it and through
  Y.Node#applyDelta and requires identical documents (byte for byte).
- A keystroke (one text node of a line changed, same formats, every other
  child unchanged including inside links) diffs only that node's old and
  new text, anchored at the caret, and writes at its offset: cost in the line's
  items, not its length (0.4 ms in a 200,000-character paragraph).
-  Identity-anchored structure: units matched by node key (a weighted
  longest increasing subsequence: as many blocks as possible stay in place,
  a list counting as one block; between equal counts a block node, whose
  rewrite copies its subtree, outweighs lines). A line whose content did not
  change (node identity against the previous state, inline elements
  included) is never diffed; removed or moved units are deleted exactly;
  only split, join and type-change segments are diffed, as one sequence of
  the segment's items with the caret as the diff anchor: text that moved to
  another line keeps its items (no re-insert of a moved tail, so text a peer
  deleted is not resurrected). Each character keeps its old item only if it
  comes from the same Lexical text node as before (text nodes merged by a
  join or an unlink are attributed using the caret at the join, else by
  common prefix and suffix, among the nodes removed from the content being
  rewritten; text merged from elsewhere is new), so text that moved between
  nodes or lines is written as new text, never built from equal old
  characters. Diffs never split a surrogate pair. A Lexical node replaced in
  place by a new one keeps its shared node and content: a different type is
  recorded in the node's `t` attribute (a paragraph held by a list item
  turned into a heading keeps a peer's concurrent typing). Enter inserts a
  marker, Backspace deletes one, a type, indent or list type change only
  sets marker attributes.
- Structure is read from node links (the root is always marked dirty);
  attributes are written only for changed keys; inserted content carries its
  formats (no reformat after insert); format passes walk runs, not
  characters.
- Development self-check (default on outside production; `selfCheck` and
  `selfCheckSample` for production, also options of `YCollabExtension`):
  every line a write touched is read back from Yjs (text, formats, line
  break NodeState, marker), and every container a structural write touched,
  or where a group item's marker changed, is read whole into a fresh editor
  and compared with the editor's JSON (node types, list structure, wrapper
  fields, NodeState); mismatches go to the editor's `onWarn`. The whole
  container read runs every time for containers of up to 256 units and is
  sampled in proportion above that (Enter in a 2,000-block document went
  from about 50 to about 12 ms in development). All tests run with it and
  fail on a warning.

Read path: a pending local `editor.update()` is committed before a remote
transaction is read; changed items are bucketed by container once per
transaction; an inserted or deleted format item re-derives the start formats
of the following units (past block nodes too) until they agree again; each
changed item is located by walking to the next end item; text edits update
lines in place; structural changes re-parse only the touched units (groups
next to them are regrouped without re-reading untouched lines); formats that
span a marker propagate only while the value at the next unit's start
changes (re-reading the next unit as a region when it cannot be updated in
place); an inline element that cannot be empty is not shown when peers
deleted all its content; NodeState keys are read in sorted order. The local
selection is captured as relative positions before each remote transaction
(a caret anchored to the character on its left, a range to its edge
characters) and restored in the same update (an end item a peer deleted is
skipped when a position is resolved). While the local editor is composing
(IME), remote inserts into the composing line are applied to Yjs but not to
that line's nodes (the browser composes into their DOM); readers and writers
of that line skip those ids, and the line is read again when the composition
ends. Deletions, formats and structure in the composing line are read at
once, keeping the composed text node (its key and text): text a peer joins
into the line goes into nodes of its own, and a composing line joined into
the next keeps its node for the merged line. Remote reads skip Lexical's
transforms, so every list whose children a read changed, or whose items
gained or lost a nested list, is refreshed afterwards by running the list
class's own transforms with its siblings hidden (list numbering is computed
the same way on every peer, and a transform never merges two lists on one
peer only); groups are told apart by their first declared key field only (a
list by its type, as Lexical merges lists), and a region read back empty
regroups its neighbours. Groups and wrapper items carry their textFormat and
textStyle (Lexical serializes them only while an element has no text), and
each wrapper reads the fields its own group recorded. A list stored as a
node inside a line (Lexical keeps blocks pasted into a list item inside it)
reads text left without a marker as one of its items; an element that cannot
be empty is shown only while its content is not, on every reader; and two
such lists of one type that end up next to each other (added by two peers at
once) are merged (see Repairs). When the local tree joins two wrapper items,
the nested lists they hold are joined too, as a reader builds them. A link's
own textFormat is stored with its value. The character diff of a line places
a change at the caret only while the text after the caret is unchanged
(after a join the caret is before the new text). A marker attribute a peer
removed resets the field even when exportJSON hides it (`checked` outside a
check list). A NodeState value read before its key's config was known is
replaced by the known value when the node is written (a reset comment is
removed on every peer).

Recovery: a stored node a write deletes without giving it a new shared node
loses its mapping (no later write goes into a deleted node, where Yjs drops
what is inserted; this was the "cursor advanced past the end" exception on
paste). A write that throws part way is followed by a rewrite of every
container in a fresh transaction; a remote read that throws is followed by a
rebuild of the editor from the shared content (what every fresh reader
shows) in a fresh update; both are reported through `onWarn`. When the
self-check finds the editor different from the shared content after a
remote change (the shared content is right, the editor is not), those
containers are read again. (After a local write the editor is the intent,
so a mismatch there is only reported.)
A text diff with a run of equal characters places the change at the caret
(a space typed next to a space), and never splits a surrogate pair.
Repairs: concurrent edits can leave shapes Lexical would normalize, which
remote reads do not (they skip transforms): a ragged table (row insert ‖
column insert) and two equal lists side by side inside a list item. Every
client that sees one repairs it with the same write, run under a client id
derived from the shared subtree it depends on (every item id and deleted
flag), so the repair is one write whoever is online, and no particular client
(or session) has to be around. Cells added to pad a row carry a padding mark
in the same transaction; an empty padding cell at the end of a row wider than
the table is removed again (an undo of the column insert), and undo of a row
insert removes its padding with it. Repairs and list renumbering are kept
out of the undo history.

Containers opt out of Yjs' remote formatting cleanup, which rescans every
type with formats after a remote format change (O(document) here): the
binding marks its containers as having no formats before Yjs decides. The
document's `cleanupFormatting` flag and the app's other types are untouched.

Servers on yrs before 0.28 read client ids as 32-bit numbers, while Yjs 14
draws 53-bit ones. With Yjs 14's default ids:
- a ywasm 0.23.5 relay stores an author's content under a truncated id, and
  the author receives its own content back as another client's on reconnect,
  duplicating it;
- a real yrs 0.23 server rejects the reconnect ("the awareness update is
  malformed"), and edits made offline are lost.
yrs/ywasm 0.28.0 is fine. Opt-in compatibility: `clientIDRange: 'uint32'`
(binding, extension, `writeEditorToYDoc`) or `createYDoc({compat:
'yrs-0.23'})` keeps the document's client id in 32 bits, including when Yjs
draws a new one; the id the binding uses for the initial content is always
32-bit. The default, `'uint53'`, leaves Yjs 14's ids unchanged. The binding
does not own the awareness, which takes the document's client id when it is
created; the README tells apps to create the awareness and provider from a
document that already has a 32-bit id. With 32-bit ids, a yrs 0.23 server
converges, including offline edits, reconnects and late joiners.

Undo: Yjs 14 UndoManager on the root, tracking only this binding's writes. A
container the undone change inserted that holds another client's content is
kept whole (its fields and own content too), unless the undo also restores
a container of the same type (the change was a move: keeping the copy
would duplicate it).
Cursors: `getCursor()` / `$resolveCursor()` (relative positions on items;
no provider wiring or rendering).

`@y/y` internals used (all in rc.28; a bump must re-run the cursor
equivalence test): `new Item(...)`, `item.integrate`, `getItemCleanStart`,
`createID`, `Item.left/right/origin/rightOrigin/parent/content/deleted/
countable/length`, `YNode._start`, `_item`, `_map`, `_length`,
`_searchMarker`, `_hasFormatting`, `_legacyTypeRef` (upgrade notice), the
`beforeObserverCalls` event, `doc.store.getItem/getClock`,
`iterateStructsByIdSet`, `decodeUpdate`, `findRootTypeKey`.

Supported: split, join, partial joins, heading/quote/paragraph, list type,
indent/outdent, Enter in list items, checked state, alignment and NodeState
of lines, links and other inline formats (incl. property changes and spans
across line breaks), text formats, comments as NodeState, tables and any
nested containers (collapsible-like container > title + content, cell >
collapsible, box > box), block and inline decorators, inline elements
(MarkNode) with nested content, undo/redo, cursors, local selection across
remote edits.

Known limits:
- A move is a delete and a reinsert: text a peer types into a moved line
  lands in its old neighbour. The cheaper side is rewritten: a long move
  rewrites the moved block, not every block it passed; in a swap the smaller
  block is re-created (a collapsible dragged past a box keeps a peer's
  typing inside it); between equal blocks the moved one (Lexical's record of
  explicit moves, `_recordNodeMoves`).
- Lexical restructures written as moves lose a peer's concurrent typing in
  the moved paragraph: a list created from a paragraph inside a container
  that is not a shadow root (a box), indenting or pasting list items that
  hold blocks. Two peers pulling the same text across a container edge
  (range deletes from a list item into a collapsible title) both copy it.
- Properties a class keeps outside its `$config()` schema and NodeState are
  not synced; such classes are stored as nodes with a warning naming the
  properties (Lexical itself drops them when it clones the node).
- MarkNode is an element with its own content: wrapping a range moves the
  text into it, and concurrent typing in that range stays outside. Comments
  should use per-id NodeState (MarkStateExtension).
- A split racing a type change gives the first half the splitter's type;
  text typed into a line a peer removed joins the next line.
- Slots are not synchronized; a link's fields merge as a whole (last
  writer wins).
- Yjs format semantics: bold ‖ bold on adjacent ranges of one line can leave
  part unformatted (the same on Yjs 13).
- A join ‖ removal of the joined line also joins the next line (nothing
  deleted comes back); unwrapping a container is a removal and a
  reinsertion of its lines, so text a peer types inside it at the same time
  is lost, as is text typed inside a container a peer removed (delete
  wins).
- Two clients initializing with different content at once both keep their
  content (converged).
- Undo never deletes a container another client has put content in (it is
  kept whole): after two peers' lists inside one list item are merged,
  undoing either addition keeps the merged list. If two clients repair the
  same list pair from different versions of the line, its items show twice.
- Several edits to one line in a single update are written as one replace
  (a peer's caret inside it moves to the edge).
- Structural edits in a large list cost time proportional to the list on
  both sides (regrouping and renumbering): about 4x main end to end at 10,000
  items. Enter at 10,000 blocks (core text walk skipped) is 26.4 ms against
  main's 19.6 ms.
- Relies on the @y/y internals listed above.
- Version gate: the layout version must be an integer from 1 to
  `LAYOUT_VERSION`; anything else is read only.
- With Yjs 14's default 53-bit client ids, servers on yrs before 0.28
  duplicate content or lose offline edits on reconnect; use the opt-in
  32-bit range for them, and create the awareness from that document.

Known open issues (from randomized runs; see Fuzz below):
- Two peers moving the same blocks at once (move ‖ move) can duplicate or
  lose a block; 2 of 9,983 differential seeds are worse than both Yjs 13
  layouts (see Fuzz).
- NodeState keys of a node keep the order of the author's local history in
  its own editor (values equal; other clients read them sorted).
- Not a binding issue: `$toggleLink(null)` on a range that ends at the edge
  of a link's text throws in `$splitLinkAtSelection` (empty
  `extractedChildren`), in any editor on main; the fuzz no longer generates
  it.

## Test plan

### Before

The Yjs 13 layouts on the same scenarios, from their own branches: main v2,
#9383 and #9386 lose or misplace concurrent typing on split, join, retype,
indent and nested containers (#9386 fixes most of them on Yjs 13); bytes per
operation are in the table below.

### After

New tests in `packages/lexical-y/src/__tests__/unit` (headless peers with
pinned client ids, offline edits then sync, both id orders, causal and
per-sender delivery, two and three peers; every case checks every peer, a
fresh reader, no exception and no self-check warning):
- `BlockMarkers.test.ts`: split, join, heading, quote, list indent, list
  type, Enter in a list item, link, table cell, custom block, removals with
  three peers, and 40 randomized intent seeds;
- `Races.test.ts`: links, unlink, undo of a link, overlapping formats,
  heading/quote/split/join/indent/list type/Enter races, moves, table rows
  and cells, row insert ‖ column insert, MarkNode; moves and MarkNode are
  documented limits (converged, intent not kept);
- `Nested.test.ts`, `NestedFuzz.test.ts`: collapsible-like containers,
  collapsible in a table cell in a collapsible, box > box, six-level lists,
  mixed inline and block content, emptied containers, list numbering,
  content inside marks (links, equations, nested marks), comment state ‖
  link wrap, 20 randomized nested seeds;
- `Selection.test.ts`: carets and ranges across remote edits, link URL
  change, a space typed next to a space;
- `WriteRecovery.test.ts`: a write that throws part way is rewritten and
  reported; a remote read that throws rebuilds the editor, reported, and
  later edits converge; a nested list that becomes a level is not written
  into its old shared node;
- `Repairs.test.ts`: row ‖ column insert then either inserter undoes (the
  table stays rectangular, both id orders); two lists added to one item
  merge whether or not the second list's author has reloaded (fresh reader
  agrees); undo after a merge keeps the merged list (documented);
- `BulkScale.test.ts`: select all + remove bold and join every pair of lines
  at 5,000 and 20,000 lines (linear; 20,000 lines in about 2 s);
- `ListsInLines.test.ts`: lists inside a list item added by two peers merge
  once; text left in a removed item reads as an item; an emptied list is
  hidden on every reader; joined wrapper items join their lists; wrapper,
  group and link text formats; a join ‖ delete keeps the joined text whole;
  a marker-only write on a line holding a list peers emptied;
- `Composition.test.ts`: IME composition (composition key) with a peer
  inserting before, right before, after and inside the composed text, edits
  in other lines, structural edits and deletions in the composing line, a
  peer joining the lines while composing at the start of line 2 or the end
  of line 1;
- `NestedLists.test.ts`: a nested list in a table cell removed ‖ Enter in
  two of its items (3 peers), undo of a list type change after a peer
  checked an item, paste + indent + undo numbering, typing ‖ a paragraph
  turned into a list in the root, a cell and after a list;
- `LineBreakState.test.ts`: NodeState set, reset and combined with text on
  an existing line break;
- `Init.test.ts`: undo after initialization, concurrent initializations
  (same and different content, two different roots with equal content),
  legacy roots, upgrade notice, conversion in
  place, extension (status, undo state, history conflict);
- `Storage.test.ts`: layout, every node kind, keystroke/Enter/Backspace and
  attribute-only updates, block child in a line, schema-incomplete
  subclasses, newer layout read only, no write before initialization,
  headless writer, undo, cursors;
- `Cursor.test.ts`: write cursor ≡ Y.Node#applyDelta (60 random seeds);
- `Size.test.ts`: byte budgets per operation and for a 10,000-edit session;
- `YrsCompat.test.ts`: a relay on ywasm 0.23.5 duplicates a 53-bit
  author's content on reconnect, not with `clientIDRange: 'uint32'` or
  `createYDoc({compat: 'yrs-0.23'})`, ywasm 0.28.0 handles 53-bit ids, and
  the 32-bit range survives Yjs drawing a new id (ywasm 0.23.5 and 0.28.0
  are dev dependencies);
- Regression tests: `Concurrency.test.ts` (lists, links, moves, formats in
  every order), `BlocksAndLines.test.ts` (a block inserted before a line ‖
  typing at its start, undo of a container a peer typed into, nested list
  shapes, paragraphs held by list items, moves past tables and their undo),
  `Ranges.test.ts` (range deletes across lines, line break NodeState,
  adjacent equal links), `Links.test.ts`, `EmptyMarks.test.ts`,
  `Tabs.test.ts`, `NestedItems.test.ts`, `NodeStateDefaults.test.ts`,
  `Document.test.ts` (group fields, pending local update),
  `Surrogates.test.ts`, `Lifecycle.test.ts` (version gate, concurrent init,
  undo across peers, dispose of a read-only binding restores editability),
  `OtherRoots.test.ts`, `Nodes.test.ts` (link fields, schema subclasses,
  hand-written classes, object values, unknown types read only);
- `Fuzz.test.ts`: 300 seeds plus 100 with gc (3 peers, every delivery mode,
  typing, formats, links, comments, lists, tables, containers, undo/redo;
  convergence, fresh reader, canonical shape, self-check, no lost or
  duplicated tokens), longer runs through `FUZZ_SEEDS`, a differential run
  through `FUZZ_DIFF=1` (absolute checks on @lexical/y's full script, and
  worse-than-both on cut scripts); one seed where all three layouts lose the
  same token is listed in the test. `FuzzReplay.test.ts` replays 46
  minimized scripts of fixed failures;
- `Server.test.ts`, `ServerScale.test.ts`, `Source.test.ts`: server helpers
  (old client's update, delete-only update, linear time on 8,000-paragraph
  updates, notice readable by a Yjs 13 client), fail-closed editability, no
  `process.env` but NODE_ENV in shipped source.
- Core: `LexicalCollabNodeConfig.test.ts` covers `content`.

Fuzz, differential: the same scripts run on this binding, on #9386 and on
the default v2 layout of @lexical/yjs as it is in this stack (origin/main's
v2 plus the stack's fix that writes only changed text attributes; on the
duplicate seeds origin/main behaves the same). Two checks per seed:
- absolute, on @lexical/y's full script: divergence, an exception, a
  fragmented token, a self-check warning or a fresh-reader mismatch: 0 of
  the 22,474 seeds below (9,983 with moves, 9,995 without, 2,496 with gc);
- relative, "worse than both": each pair is compared on the script cut
  before the first op the two runs resolved differently, and @lexical/y
  loses or duplicates more unique tokens, or diverges, throws, fragments or
  hangs, than #9386 and than v2; text typed into a container a peer
  removed, which the other layout keeps only by bringing back deleted
  content, is not counted as lost (`resurrectionExcuse`). With moves: 2,
  both move classes (a list moved ‖ two of its items swapped duplicates an
  item; a delete across a table ‖ a paragraph moved past it). Without
  moves: 0. With gc: 0.
@lexical/y loses fewer tokens than #9386 on about 7% of seeds and than v2 on
about 38%. Hangs: #9386 26, @lexical/y 0.
Within a partition, the fuzz relays updates as a sync protocol would.

A second, list-heavy generator (3-4 peers, partitions, gc on some seeds,
collapsible > table > cell > list shapes, deep lists in boxes, emoji, CJK
and Ext-B text, overlapping MarkStateExtension comments, links, line breaks,
rich paste into list items, indent storms, undo/redo; run locally, as it
needs MarkStateExtension, which is not in this stack), full scripts: 6,000
seeds with line breaks, 6,000 without and 3,000 with moves: 0 divergence, 0
fresh-reader mismatches, 0 self-check warnings and 0 non-canonical shapes
(adjacent equal lists, empty lists, lists with other children); remaining
findings are delete-wins losses, the restructure-as-move limit above (1.2%,
1.3% and 2.5% of seeds duplicate an item), fragmented tokens in 4, 6 and 2
seeds (the one examined: a container removed while a peer pastes into
it) and NodeState key order in the author's own editor.

Real browsers (Chromium, Firefox, WebKit through Playwright; separate
contexts over a Yjs 14 WebSocket relay with a 200 ms delay; real key events;
convergence, fresh load, token checks, no console warnings, editor errors
or self-check warnings): Chromium 60/60, Firefox 53/53 and WebKit 53/53;
17 more cases (nested containers with 3 peers, lists in cells, emoji and
CJK, IME at a line boundary while a peer joins, drag and drop, comments,
reloads, a 2,000-block document): Chromium 17/17, Firefox and WebKit 13/13
(IME cases need CDP and are skipped in Firefox and WebKit). The WebKit
split + join race under load (4 workers, 100 runs): 98 passed, 2 lost to
browser crashes; an earlier caret
jump there was a position resolving across a deleted line marker.

Performance (headless Node, shared VM, medians, ms):

```
                                N=2,000            N=10,000
keystroke (end to end, 2 peers) 9.0                55.1      (main 54.3, B 50.3)
  core text walk skipped        0.53               2.1       (main 7.1, B 2.6)
Enter / Backspace               13.7 / 13.6        75.7 / 75.8 (main 74.2 / 74.7)
  core text walk skipped        4.8 / 4.8          26.4 / 27.0 (main 19.6 / 19.4)
document size (bytes)           164,000            833,603   (main 872,754,
                                (main 171,110)      A 1,006,407, B 1,391,890)
fresh load                      90                 416       (main 427, B 945)
initial bulk write (1 update)   271                1,104     (main 894, B 1,260)
```

Stress shapes (local update + write + peer read): 400 nested sections
(collapsible > table > cell > collapsible > list, box) paste 300, load 130,
208 KB; 10x10 tables 100/200/400 paste 1,099/1,875/3,864, load
412/776/1,570; bold everything in a list of 5k/10k/20k items 302/548/1,170;
add a NodeState comment in a 10k/20k/40k list 37/77/237; indent in a flat
list of 2.5k/5k/10k items 81/134/271; keystroke in a 50k/200k-character
paragraph 0.34/0.43. All linear.

Bytes per operation (gc off, client ids in Yjs' random range; op / undo /
redo):

```
                         main v2        #9383 (A)      #9386 (B)      @lexical/y
type a char mid line     25/11/26       25/11/26       25/11/26       24/10/24
paste 1k chars           1025/12/1026   1025/12/1026   1025/12/1026   1024/11/1025
Enter mid line           86/57/88       86/57/88       78/11/81       26/10/26
Backspace join           70/107/78      70/107/78      10/76/11       10/26/10
heading toggle           124/108/126    124/108/126    122/48/127     48/10/38
indent list item         134/58/135     134/58/135     54/37/57       65/27/60
link a word              175/73/190     276/11/292     282/11/292     103/10/103
bold a range             131/11/143     131/11/143     137/11/143     59/10/59
add a comment            137/11/149     137/11/149     143/11/149     65/10/65
table row insert         146/11/153     146/11/153     335/11/335     189/10/188
delete a table           10/439/11      10/439/11      11/1089/11     11/563/10
10,000-edit session      2,839,497      3,124,314      404,571        210,029
```

A Yjs 14 document written by this binding, with concurrent updates relayed
through yrs (ywasm 0.28.0), reloads into a fresh client identically; on yrs
0.23 it does with `clientIDRange: 'uint32'`.

```
$ npx vitest --project unit --no-watch packages/lexical-y/src \
    packages/lexical/src/__tests__/unit/LexicalCollabNodeConfig.test.ts
$ pnpm run tsc; pnpm run tsc-test   # exit 0
$ pnpm run flow                     # Found 0 errors
$ npx vitest --project scripts-unit --no-watch \
    scripts/__tests__/unit/treeShakingSource.test.ts
$ pnpm run prepare-release           # release build, package and type checks
$ pnpm --filter lexical-playground run build-vercel
$ pnpm --filter @lexical/website run build
```
zurfyx added a commit that referenced this pull request Oct 21, 2026
…ding with block markers

## Description

PROTOTYPE, not for merge. Stacked on #9386 (block markers on Yjs 13), whose
`$config({collab})` declarations it reuses. It shows the block-marker data
model on Yjs 14 (`@y/y`), as a new experimental package, `@lexical/y`.
`@lexical/yjs` (Yjs 13) is unchanged: Yjs 14 is a different npm package, so
a Yjs 14 binding cannot replace it in place.

Entries (all `@experimental`):
- `@lexical/y`: `YBinding`, `YCollabExtension` (binding, collaborative undo,
  `status` signal; conflicts with the history extensions),
  `writeEditorToYDoc` (headless writer for converters), `createYDoc`,
  `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and the types `YBindingOptions`,
  `YBindingStatus`, `YCursor`, `YCollabConfig`, `ClientIDRange`. No React,
  no DOM requirement.
- `@lexical/y/server`: `inspectUpdateRoots`, `isUpdateForLayout`,
  `writeUpgradeNotice`, `UpdateRoots`. No editor dependencies.
- `@lexical/y/migrate` is reserved for a converter from the Yjs 13 layouts.

`@y/y` is a peer dependency pinned to 14.0.0-rc.28, the newest release the
repository's minimum release age (7 days) allowed when this was written
(npm's `latest` tag points at an older release candidate).

Core:
- `CollabNodeConfig.content?: 'block' | 'inline'` (what a block node stored
  as its own node holds), declared `'inline'` on CodeNode.
- Text normalization no longer merges text into or out of the node being
  composed (IME): merging rewrote its DOM text node and the browser's
  composition range took in the merged text; the nodes merge when the
  composition ends.
  (Also proposed on its own against main.)

Data model (the semantics of #9386):
- Shared root `doc.get('lexical-y')`, a new root name, with a layout version
  attribute. The editor stays read only until that record has been read; a
  newer version, or content without a version, stays read only.
- `initialize()` (after the provider's first sync) marks only an empty root.
  It refuses when an older layout's root (`root`, `root-v2`) has content
  other than an upgrade notice (convert it: `writeEditorToYDoc` writes the
  layout root next to the old one). The initial content is written with a
  client id hashed from the layout version, the target shared type (its
  top-level name or item id) and the exact items written (encoded from a
  scratch document), so two clients initializing the same content into the
  same root at once write it once, while different roots or content never
  share an id; outside the undo history.
- Every container (the root and every node stored as its own Y.Node) holds
  one sequence of text, child nodes and line markers (Yjs 14 Y.Node children
  are unified, so no XmlText per container is needed).
- A line (declared `'line'`, schema-complete) is its inline content followed
  by a marker: a child `Y.Node` named `¶` whose map attributes hold the
  line's type (left out for a paragraph), schema fields (minus derived),
  NodeState, and for a group item the group type, key fields and level. Not
  a character with formats (#9386's U+2029) and not an embed:
  * map attributes merge per key (last writer wins), so a concurrent heading
    change and indent both apply, without format start/end items in the
    sequence;
  * the marker's identity (its item) never changes when its attributes do,
    where an immutable embed would have to be replaced (and could be
    duplicated by concurrent replacements);
  * block attributes never mix with inline formats, and text may contain
    any character.
- Groups (lists) are rebuilt from consecutive items; local groups are kept
  in the same canonical shape by a transform (adjacent equal groups and
  wrapper items merged, empty groups removed); derived fields (list
  numbering) are recomputed by a refresh update on every client. All of a
  group's synced fields (and NodeState) identify it; a nested item's marker
  also records its outer groups and their wrapper items' fields (`o`), so an
  indented first item keeps its outer list's type and the wrappers' fields
  sync.
- Storage follows the class, never the instance: a declared line stays a
  line even with a block child (the child is stored as a node inside its
  content). Undeclared or invalid blocks are `b:<type>` child nodes with the
  class's own (compact) JSON as attributes; inline elements that are not
  formats and inline decorators are `i:<type>` children.
- A container records what it holds (`c`: blocks or inline content) when it
  is created, from `collab.content` or its children, and never changes it:
  leftover inline content of a block container reads as a paragraph on every
  reader; inline content directly in a block container is always ended by a
  `¦` terminator.
- Inline wrappers declared `inline: 'format'` are one format key each
  (`w:link`, whose value holds the wrapper's fields); text formats are one
  key per format (`f:bold`), plus type, JSON fields, NodeState and, for text
  nodes Lexical would not merge, a segment key (`k`). Formats apply to any
  child, so a link can span a line break or an inline decorator; a line
  break's NodeState is a format of its `\n`. Two adjacent equal links keep an
  instance key (`#`) so they stay two links on every peer.
- NodeState equal to its default is not stored (setting it back deletes
  the key). Element `textFormat`/`textStyle` are always stored.
- Schema completeness (own `$config()`, no hand-written `exportJSON`,
  `updateFromJSON` or `afterCloneFrom` below the declaring class) is
  required for lines, groups and inline formats; anything else is a node.
- Editor instances (nested caption editors) are not synchronized; JSON
  snapshots of them are (members that JSON would drop are dropped).
- A class with a hand-written serialization is a node; an edit to one of its
  own fields alone is written (the whole node's JSON is compared) and read
  through `updateFromJSON`, then `importJSON` for fields it does not know.
- Unknown types fail closed: a client that meets a node, line, text or
  group type it does not register goes read only with a warning, so it never
  hides and later deletes content it cannot show.

Write path:
- Anchored edits: Y.Node#insert/delete/format walk the type from its start
  on every call in rc.28, so the binding edits the sequence from the item it
  knows (the previous line's marker) with a port of Yjs' text position
  algorithm. A test runs random operations through it and through
  Y.Node#applyDelta and requires identical documents (byte for byte).
- A keystroke (one text node of a line changed, same formats, every other
  child unchanged including inside links) diffs only that node's old and
  new text, anchored at the caret, and writes at its offset: cost in the line's
  items, not its length (0.4 ms in a 200,000-character paragraph).
-  Identity-anchored structure: units matched by node key (a weighted
  longest increasing subsequence: as many blocks as possible stay in place,
  a list counting as one block; between equal counts a block node, whose
  rewrite copies its subtree, outweighs lines). A line whose content did not
  change (node identity against the previous state, inline elements
  included) is never diffed; removed or moved units are deleted exactly;
  only split, join and type-change segments are diffed, as one sequence of
  the segment's items with the caret as the diff anchor: text that moved to
  another line keeps its items (no re-insert of a moved tail, so text a peer
  deleted is not resurrected). Each character keeps its old item only if it
  comes from the same Lexical text node as before (text nodes merged by a
  join or an unlink are attributed using the caret at the join, else by
  common prefix and suffix, among the nodes removed from the content being
  rewritten; text merged from elsewhere is new), so text that moved between
  nodes or lines is written as new text, never built from equal old
  characters. Diffs never split a surrogate pair. A Lexical node replaced in
  place by a new one keeps its shared node and content: a different type is
  recorded in the node's `t` attribute (a paragraph held by a list item
  turned into a heading keeps a peer's concurrent typing). Enter inserts a
  marker, Backspace deletes one, a type, indent or list type change only
  sets marker attributes.
- Structure is read from node links (the root is always marked dirty);
  attributes are written only for changed keys; inserted content carries its
  formats (no reformat after insert); format passes walk runs, not
  characters.
- Development self-check (default on outside production; `selfCheck` and
  `selfCheckSample` for production, also options of `YCollabExtension`):
  every line a write touched is read back from Yjs (text, formats, line
  break NodeState, marker), and every container a structural write touched,
  or where a group item's marker changed, is read whole into a fresh editor
  and compared with the editor's JSON (node types, list structure, wrapper
  fields, NodeState); mismatches go to the editor's `onWarn`. The whole
  container read runs every time for containers of up to 256 units and is
  sampled in proportion above that (Enter in a 2,000-block document went
  from about 50 to about 12 ms in development). All tests run with it and
  fail on a warning.

Read path: a pending local `editor.update()` is committed before a remote
transaction is read; changed items are bucketed by container once per
transaction; an inserted or deleted format item re-derives the start formats
of the following units (past block nodes too) until they agree again; each
changed item is located by walking to the next end item; text edits update
lines in place; structural changes re-parse only the touched units (groups
next to them are regrouped without re-reading untouched lines); formats that
span a marker propagate only while the value at the next unit's start
changes (re-reading the next unit as a region when it cannot be updated in
place); an inline element that cannot be empty is not shown when peers
deleted all its content; NodeState keys are read in sorted order. The local
selection is captured as relative positions before each remote transaction
(a caret anchored to the character on its left, a range to its edge
characters) and restored in the same update (an end item a peer deleted is
skipped when a position is resolved). While the local editor is composing
(IME), remote inserts into the composing line are applied to Yjs but not to
that line's nodes (the browser composes into their DOM); readers and writers
of that line skip those ids, and the line is read again when the composition
ends. Deletions, formats and structure in the composing line are read at
once, keeping the composed text node (its key and text): text a peer joins
into the line goes into nodes of its own, and a composing line joined into
the next keeps its node for the merged line. Remote reads skip Lexical's
transforms, so every list whose children a read changed, or whose items
gained or lost a nested list, is refreshed afterwards by running the list
class's own transforms with its siblings hidden (list numbering is computed
the same way on every peer, and a transform never merges two lists on one
peer only); groups are told apart by their first declared key field only (a
list by its type, as Lexical merges lists), and a region read back empty
regroups its neighbours. Groups and wrapper items carry their textFormat and
textStyle (Lexical serializes them only while an element has no text), and
each wrapper reads the fields its own group recorded. A list stored as a
node inside a line (Lexical keeps blocks pasted into a list item inside it)
reads text left without a marker as one of its items; an element that cannot
be empty is shown only while its content is not, on every reader; and two
such lists of one type that end up next to each other (added by two peers at
once) are merged (see Repairs). When the local tree joins two wrapper items,
the nested lists they hold are joined too, as a reader builds them. A link's
own textFormat is stored with its value. The character diff of a line places
a change at the caret only while the text after the caret is unchanged
(after a join the caret is before the new text). A marker attribute a peer
removed resets the field even when exportJSON hides it (`checked` outside a
check list). A NodeState value read before its key's config was known is
replaced by the known value when the node is written (a reset comment is
removed on every peer).

Recovery: a stored node a write deletes without giving it a new shared node
loses its mapping (no later write goes into a deleted node, where Yjs drops
what is inserted; this was the "cursor advanced past the end" exception on
paste). A write that throws part way is followed by a rewrite of every
container in a fresh transaction; a remote read that throws is followed by a
rebuild of the editor from the shared content (what every fresh reader
shows) in a fresh update; both are reported through `onWarn`. When the
self-check finds the editor different from the shared content after a
remote change (the shared content is right, the editor is not), those
containers are read again. (After a local write the editor is the intent,
so a mismatch there is only reported.)
A text diff with a run of equal characters places the change at the caret
(a space typed next to a space), and never splits a surrogate pair.
Repairs: concurrent edits can leave shapes Lexical would normalize, which
remote reads do not (they skip transforms): a ragged table (row insert ‖
column insert) and two equal lists side by side inside a list item. Every
client that sees one repairs it, so no particular client (or session) has to
be around. A repair is a pure function of the shared content: its inputs are
read from Yjs (never from the editor) and described independently of how
items are split (text runs with their formats, coalesced id ranges, the id
of the last character of the container it appends to), its output is
computed from that description, and it is written under a client id hashed
from the repair version, the inputs and the output encoded on a scratch
document. Clients with the same inputs write the same items once; clients
with different inputs never share an id (at worst both apply). Repairs wait
while the editor is composing or has a pending update, are read back like a
peer's change, and are not part of the undo history. Padding cells carry a
mark; an empty padding cell at the end of a row wider than the table is
removed again (an undo of the column insert), and undo of a row insert
removes its padding with it.

Containers opt out of Yjs' remote formatting cleanup, which rescans every
type with formats after a remote format change (O(document) here): the
binding marks its containers as having no formats before Yjs decides. The
document's `cleanupFormatting` flag and the app's other types are untouched.

Servers on yrs before 0.28 read client ids as 32-bit numbers, while Yjs 14
draws 53-bit ones. With Yjs 14's default ids:
- a ywasm 0.23.5 relay stores an author's content under a truncated id, and
  the author receives its own content back as another client's on reconnect,
  duplicating it;
- a real yrs 0.23 server rejects the reconnect ("the awareness update is
  malformed"), and edits made offline are lost.
yrs/ywasm 0.28.0 is fine. Opt-in compatibility: `clientIDRange: 'uint32'`
(binding, extension, `writeEditorToYDoc`) or `createYDoc({compat:
'yrs-0.23'})` keeps the document's client id in 32 bits, including when Yjs
draws a new one; the id the binding uses for the initial content is always
32-bit. The default, `'uint53'`, leaves Yjs 14's ids unchanged. The binding
does not own the awareness, which takes the document's client id when it is
created; the README tells apps to create the awareness and provider from a
document that already has a 32-bit id. With 32-bit ids, a yrs 0.23 server
converges, including offline edits, reconnects and late joiners.

Undo: Yjs 14 UndoManager on the root, tracking only this binding's writes. A
container the undone change inserted that holds another client's content is
kept whole (its fields and own content too), unless the undo also restores
a container of the same type (the change was a move: keeping the copy
would duplicate it).
Cursors: `getCursor()` / `$resolveCursor()` (relative positions on items;
no provider wiring or rendering).

`@y/y` internals used (all in rc.28; a bump must re-run the cursor
equivalence test): `new Item(...)`, `item.integrate`, `getItemCleanStart`,
`createID`, `Item.left/right/origin/rightOrigin/parent/content/deleted/
countable/length`, `YNode._start`, `_item`, `_map`, `_length`,
`_searchMarker`, `_hasFormatting`, `_legacyTypeRef` (upgrade notice), the
`beforeObserverCalls` event, `doc.store.getItem/getClock`,
`iterateStructsByIdSet`, `decodeUpdate`, `findRootTypeKey`.

Supported: split, join, partial joins, heading/quote/paragraph, list type,
indent/outdent, Enter in list items, checked state, alignment and NodeState
of lines, links and other inline formats (incl. property changes and spans
across line breaks), text formats, comments as NodeState, tables and any
nested containers (collapsible-like container > title + content, cell >
collapsible, box > box), block and inline decorators, inline elements
(MarkNode) with nested content, undo/redo, cursors, local selection across
remote edits.

Known limits:
- A move is a delete and a reinsert: text a peer types into a moved line
  lands in its old neighbour. The cheaper side is rewritten: a long move
  rewrites the moved block, not every block it passed; in a swap the smaller
  block is re-created (a collapsible dragged past a box keeps a peer's
  typing inside it); between equal blocks the moved one (Lexical's record of
  explicit moves, `_recordNodeMoves`).
- Lexical restructures written as moves lose a peer's concurrent typing in
  the moved paragraph: a list created from a paragraph inside a container
  that is not a shadow root (a box), indenting or pasting list items that
  hold blocks. Two peers pulling the same text across a container edge
  (range deletes from a list item into a collapsible title) both copy it.
- Properties a class keeps outside its `$config()` schema and NodeState are
  not synced; such classes are stored as nodes with a warning naming the
  properties (Lexical itself drops them when it clones the node).
- MarkNode is an element with its own content: wrapping a range moves the
  text into it, and concurrent typing in that range stays outside. Comments
  should use per-id NodeState (MarkStateExtension).
- A split racing a type change gives the first half the splitter's type;
  text typed into a line a peer removed joins the next line.
- Slots are not synchronized; a link's fields merge as a whole (last
  writer wins).
- Yjs format semantics: bold ‖ bold on adjacent ranges of one line can leave
  part unformatted (the same on Yjs 13).
- A join ‖ removal of the joined line also joins the next line (nothing
  deleted comes back); unwrapping a container is a removal and a
  reinsertion of its lines, so text a peer types inside it at the same time
  is lost, as is text typed inside a container a peer removed (delete
  wins).
- Two clients initializing with different content at once both keep their
  content (converged).
- Undo never deletes a container another client has put content in (it is
  kept whole): after two peers' lists inside one list item are merged,
  undoing either addition keeps the merged list. Two clients that repair the
  same shape from different content (one has an edit in one of the lists
  the other has not received) both apply their repair, so the moved list's
  items can show twice. A list that ends up right before a line of an equal
  nested list (a peer deleted the text between them) shows inside that
  line's item rather than merged (every client shows the same).
- Several edits to one line in a single update are written as one replace
  (a peer's caret inside it moves to the edge).
- Structural edits in a large list cost time proportional to the list on
  both sides (regrouping and renumbering): about 4x main end to end at 10,000
  items. Enter at 10,000 blocks (core text walk skipped) is 26.4 ms against
  main's 19.6 ms.
- Relies on the @y/y internals listed above.
- Version gate: the layout version must be an integer from 1 to
  `LAYOUT_VERSION`; anything else is read only.
- With Yjs 14's default 53-bit client ids, servers on yrs before 0.28
  duplicate content or lose offline edits on reconnect; use the opt-in
  32-bit range for them, and create the awareness from that document.

Known open issues (from randomized runs; see Fuzz below):
- Two peers moving the same blocks at once (move ‖ move) can duplicate or
  lose a block; 2 of 9,983 differential seeds are worse than both Yjs 13
  layouts (see Fuzz).
- NodeState keys of a node keep the order of the author's local history in
  its own editor (values equal; other clients read them sorted).
- Not a binding issue: `$toggleLink(null)` on a range that ends at the edge
  of a link's text throws in `$splitLinkAtSelection` (empty
  `extractedChildren`), in any editor on main; the fuzz no longer generates
  it.

## Test plan

### Before

The Yjs 13 layouts on the same scenarios, from their own branches: main v2,
#9383 and #9386 lose or misplace concurrent typing on split, join, retype,
indent and nested containers (#9386 fixes most of them on Yjs 13); bytes per
operation are in the table below.

### After

New tests in `packages/lexical-y/src/__tests__/unit` (headless peers with
pinned client ids, offline edits then sync, both id orders, causal and
per-sender delivery, two and three peers; every case checks every peer, a
fresh reader, no exception and no self-check warning):
- `BlockMarkers.test.ts`: split, join, heading, quote, list indent, list
  type, Enter in a list item, link, table cell, custom block, removals with
  three peers, and 40 randomized intent seeds;
- `Races.test.ts`: links, unlink, undo of a link, overlapping formats,
  heading/quote/split/join/indent/list type/Enter races, moves, table rows
  and cells, row insert ‖ column insert, MarkNode; moves and MarkNode are
  documented limits (converged, intent not kept);
- `Nested.test.ts`, `NestedFuzz.test.ts`: collapsible-like containers,
  collapsible in a table cell in a collapsible, box > box, six-level lists,
  mixed inline and block content, emptied containers, list numbering,
  content inside marks (links, equations, nested marks), comment state ‖
  link wrap, 20 randomized nested seeds;
- `Selection.test.ts`: carets and ranges across remote edits, link URL
  change, a space typed next to a space;
- `WriteRecovery.test.ts`: a write that throws part way is rewritten and
  reported; a remote read that throws rebuilds the editor, reported, and
  later edits converge; a nested list that becomes a level is not written
  into its old shared node;
- `Repairs.test.ts`: row ‖ column insert then either inserter undoes (the
  table stays rectangular, both id orders); two lists added to one item
  merge whether or not the second list's author has reloaded (fresh reader
  agrees); undo after a merge keeps the merged list (documented);
- `RepairsConcurrent.test.ts`: several clients repairing at once, one of
  them composing in the moved list while a peer types there, and with the
  author's items split by undo/redo (lists and tables); one copy, every peer
  and fresh reader equal;
- `RepairFuzz.test.ts`: 60 randomized seeds (4 peers: lists added to one
  item, table rows and columns, composition with a peer typing into the
  composed line, undo/undo/redo, partial delivery); convergence, fresh
  readers, no warning;
- `BulkScale.test.ts`: select all + remove bold and join every pair of lines
  at 5,000 and 20,000 lines (linear; 20,000 lines in about 2 s);
- `ListsInLines.test.ts`: lists inside a list item added by two peers merge
  once; text left in a removed item reads as an item; an emptied list is
  hidden on every reader; joined wrapper items join their lists; wrapper,
  group and link text formats; a join ‖ delete keeps the joined text whole;
  a marker-only write on a line holding a list peers emptied;
- `Composition.test.ts`: IME composition (composition key) with a peer
  inserting before, right before, after and inside the composed text, edits
  in other lines, structural edits and deletions in the composing line, a
  peer joining the lines while composing at the start of line 2 or the end
  of line 1;
- `NestedLists.test.ts`: a nested list in a table cell removed ‖ Enter in
  two of its items (3 peers), undo of a list type change after a peer
  checked an item, paste + indent + undo numbering, typing ‖ a paragraph
  turned into a list in the root, a cell and after a list;
- `LineBreakState.test.ts`: NodeState set, reset and combined with text on
  an existing line break;
- `Init.test.ts`: undo after initialization, concurrent initializations
  (same and different content, two different roots with equal content),
  legacy roots, upgrade notice, conversion in
  place, extension (status, undo state, history conflict);
- `Storage.test.ts`: layout, every node kind, keystroke/Enter/Backspace and
  attribute-only updates, block child in a line, schema-incomplete
  subclasses, newer layout read only, no write before initialization,
  headless writer, undo, cursors;
- `Cursor.test.ts`: write cursor ≡ Y.Node#applyDelta (60 random seeds);
- `Size.test.ts`: byte budgets per operation and for a 10,000-edit session;
- `YrsCompat.test.ts`: a relay on ywasm 0.23.5 duplicates a 53-bit
  author's content on reconnect, not with `clientIDRange: 'uint32'` or
  `createYDoc({compat: 'yrs-0.23'})`, ywasm 0.28.0 handles 53-bit ids, and
  the 32-bit range survives Yjs drawing a new id (ywasm 0.23.5 and 0.28.0
  are dev dependencies);
- Regression tests: `Concurrency.test.ts` (lists, links, moves, formats in
  every order), `BlocksAndLines.test.ts` (a block inserted before a line ‖
  typing at its start, undo of a container a peer typed into, nested list
  shapes, paragraphs held by list items, moves past tables and their undo),
  `Ranges.test.ts` (range deletes across lines, line break NodeState,
  adjacent equal links), `Links.test.ts`, `EmptyMarks.test.ts`,
  `Tabs.test.ts`, `NestedItems.test.ts`, `NodeStateDefaults.test.ts`,
  `Document.test.ts` (group fields, pending local update),
  `Surrogates.test.ts`, `Lifecycle.test.ts` (version gate, concurrent init,
  undo across peers, dispose of a read-only binding restores editability),
  `OtherRoots.test.ts`, `Nodes.test.ts` (link fields, schema subclasses,
  hand-written classes, object values, unknown types read only);
- `Fuzz.test.ts`: 300 seeds plus 100 with gc (3 peers, every delivery mode,
  typing, formats, links, comments, lists, tables, containers, undo/redo;
  convergence, fresh reader, canonical shape, self-check, no lost or
  duplicated tokens), longer runs through `FUZZ_SEEDS`, a differential run
  through `FUZZ_DIFF=1` (absolute checks on @lexical/y's full script,
  including reads or writes the binding recovered from, and worse-than-both
  on cut scripts); one seed where all three layouts lose the
  same token is listed in the test. `FuzzReplay.test.ts` replays 46
  minimized scripts of fixed failures;
- `Server.test.ts`, `ServerScale.test.ts`, `Source.test.ts`: server helpers
  (old client's update, delete-only update, linear time on 8,000-paragraph
  updates, notice readable by a Yjs 13 client), fail-closed editability, no
  `process.env` but NODE_ENV in shipped source.
- Core: `LexicalCollabNodeConfig.test.ts` covers `content`.

Fuzz, differential: the same scripts run on this binding, on #9386 and on
the default v2 layout of @lexical/yjs as it is in this stack (origin/main's
v2 plus the stack's fix that writes only changed text attributes; on the
duplicate seeds origin/main behaves the same). Two checks per seed:
- absolute, on @lexical/y's full script: divergence, an exception, a
  fragmented token, a self-check warning or a fresh-reader mismatch: 0 of
  the 22,474 seeds below (9,983 with moves, 9,995 without, 2,496 with gc);
- relative, "worse than both": each pair is compared on the script cut
  before the first op the two runs resolved differently, and @lexical/y
  loses or duplicates more unique tokens, or diverges, throws, fragments or
  hangs, than #9386 and than v2; text typed into a container a peer
  removed, which the other layout keeps only by bringing back deleted
  content, is not counted as lost (`resurrectionExcuse`). With moves: 2,
  both move classes (a list moved ‖ two of its items swapped duplicates an
  item; a delete across a table ‖ a paragraph moved past it). Without
  moves: 0. With gc: 0.
@lexical/y loses fewer tokens than #9386 on about 7% of seeds and than v2 on
about 38%. Hangs: #9386 26, @lexical/y 0.
Within a partition, the fuzz relays updates as a sync protocol would.

A second, list-heavy generator (3-4 peers, partitions, gc on some seeds,
collapsible > table > cell > list shapes, deep lists in boxes, emoji, CJK
and Ext-B text, overlapping MarkStateExtension comments, links, line breaks,
rich paste into list items, indent storms, undo/redo; run locally, as it
needs MarkStateExtension, which is not in this stack), full scripts: 6,000
seeds with line breaks, 6,000 without and 3,000 with moves: 0 divergence, 0
fresh-reader mismatches, 0 self-check warnings and 0 non-canonical shapes
(adjacent equal lists, empty lists, lists with other children); remaining
findings are delete-wins losses, the restructure-as-move limit above (1.2%,
1.3% and 2.5% of seeds duplicate an item), fragmented tokens in 4, 6 and 2
seeds (the one examined: a container removed while a peer pastes into
it) and NodeState key order in the author's own editor.

Real browsers (Chromium, Firefox, WebKit through Playwright; separate
contexts over a Yjs 14 WebSocket relay with a 200 ms delay; real key events;
convergence, fresh load, token checks, no console warnings, editor errors
or self-check warnings): Chromium 60/60, Firefox 53/53 and WebKit 53/53;
17 more cases (nested containers with 3 peers, lists in cells, emoji and
CJK, IME at a line boundary while a peer joins, drag and drop, comments,
reloads, a 2,000-block document): Chromium 17/17, Firefox and WebKit 13/13
(IME cases need CDP and are skipped in Firefox and WebKit). The WebKit
split + join race under load (4 workers, 100 runs): 98 passed, 2 lost to
browser crashes; an earlier caret
jump there was a position resolving across a deleted line marker.

Performance (headless Node, shared VM, medians, ms):

```
                                N=2,000            N=10,000
keystroke (end to end, 2 peers) 9.0                55.1      (main 54.3, B 50.3)
  core text walk skipped        0.53               2.1       (main 7.1, B 2.6)
Enter / Backspace               13.7 / 13.6        75.7 / 75.8 (main 74.2 / 74.7)
  core text walk skipped        4.8 / 4.8          26.4 / 27.0 (main 19.6 / 19.4)
document size (bytes)           164,000            833,603   (main 872,754,
                                (main 171,110)      A 1,006,407, B 1,391,890)
fresh load                      90                 416       (main 427, B 945)
initial bulk write (1 update)   271                1,104     (main 894, B 1,260)
```

Stress shapes (local update + write + peer read): 400 nested sections
(collapsible > table > cell > collapsible > list, box) paste 300, load 130,
208 KB; 10x10 tables 100/200/400 paste 1,099/1,875/3,864, load
412/776/1,570; bold everything in a list of 5k/10k/20k items 302/548/1,170;
add a NodeState comment in a 10k/20k/40k list 37/77/237; indent in a flat
list of 2.5k/5k/10k items 81/134/271; keystroke in a 50k/200k-character
paragraph 0.34/0.43. All linear.

Bytes per operation (gc off, client ids in Yjs' random range; op / undo /
redo):

```
                         main v2        #9383 (A)      #9386 (B)      @lexical/y
type a char mid line     25/11/26       25/11/26       25/11/26       24/10/24
paste 1k chars           1025/12/1026   1025/12/1026   1025/12/1026   1024/11/1025
Enter mid line           86/57/88       86/57/88       78/11/81       26/10/26
Backspace join           70/107/78      70/107/78      10/76/11       10/26/10
heading toggle           124/108/126    124/108/126    122/48/127     48/10/38
indent list item         134/58/135     134/58/135     54/37/57       65/27/60
link a word              175/73/190     276/11/292     282/11/292     103/10/103
bold a range             131/11/143     131/11/143     137/11/143     59/10/59
add a comment            137/11/149     137/11/149     143/11/149     65/10/65
table row insert         146/11/153     146/11/153     335/11/335     189/10/188
delete a table           10/439/11      10/439/11      11/1089/11     11/563/10
10,000-edit session      2,839,497      3,124,314      404,571        210,029
```

A Yjs 14 document written by this binding, with concurrent updates relayed
through yrs (ywasm 0.28.0), reloads into a fresh client identically; on yrs
0.23 it does with `clientIDRange: 'uint32'`.

```
$ npx vitest --project unit --no-watch packages/lexical-y/src \
    packages/lexical/src/__tests__/unit/LexicalCollabNodeConfig.test.ts
$ pnpm run tsc; pnpm run tsc-test   # exit 0
$ pnpm run flow                     # Found 0 errors
$ npx vitest --project scripts-unit --no-watch \
    scripts/__tests__/unit/treeShakingSource.test.ts
$ pnpm run prepare-release           # release build, package and type checks
$ pnpm --filter lexical-playground run build-vercel
$ pnpm --filter @lexical/website run build
```
zurfyx added a commit that referenced this pull request Oct 21, 2026
…ding with block markers

## Description

PROTOTYPE, not for merge. Stacked on #9386 (block markers on Yjs 13), whose
`$config({collab})` declarations it reuses. It shows the block-marker data
model on Yjs 14 (`@y/y`), as a new experimental package, `@lexical/y`.
`@lexical/yjs` (Yjs 13) is unchanged: Yjs 14 is a different npm package, so
a Yjs 14 binding cannot replace it in place.

Entries (all `@experimental`):
- `@lexical/y`: `YBinding`, `YCollabExtension` (binding, collaborative undo,
  `status` signal; conflicts with the history extensions),
  `writeEditorToYDoc` (headless writer for converters), `createYDoc`,
  `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and the types `YBindingOptions`,
  `YBindingStatus`, `YCursor`, `YCollabConfig`, `ClientIDRange`. No React,
  no DOM requirement.
- `@lexical/y/server`: `inspectUpdateRoots`, `isUpdateForLayout`,
  `writeUpgradeNotice`, `UpdateRoots`. No editor dependencies.
- `@lexical/y/migrate` is reserved for a converter from the Yjs 13 layouts.

`@y/y` is a peer dependency pinned to 14.0.0-rc.28, the newest release the
repository's minimum release age (7 days) allowed when this was written
(npm's `latest` tag points at an older release candidate).

Core:
- `CollabNodeConfig.content?: 'block' | 'inline'` (what a block node stored
  as its own node holds), declared `'inline'` on CodeNode.
- Text normalization no longer merges text into or out of the node being
  composed (IME): merging rewrote its DOM text node and the browser's
  composition range took in the merged text; the nodes merge when the
  composition ends.
  (Also proposed on its own against main.)

Data model (the semantics of #9386):
- Shared root `doc.get('lexical-y')`, a new root name, with a layout version
  attribute. The editor stays read only until that record has been read; a
  newer version, or content without a version, stays read only.
- `initialize()` (after the provider's first sync) marks only an empty root.
  It refuses when an older layout's root (`root`, `root-v2`) has content
  other than an upgrade notice (convert it: `writeEditorToYDoc` writes the
  layout root next to the old one). The initial content is written with a
  client id hashed from the layout version, the target shared type (its
  top-level name or item id) and the exact items written (encoded from a
  scratch document), so two clients initializing the same content into the
  same root at once write it once, while different roots or content never
  share an id; outside the undo history.
- Every container (the root and every node stored as its own Y.Node) holds
  one sequence of text, child nodes and line markers (Yjs 14 Y.Node children
  are unified, so no XmlText per container is needed).
- A line (declared `'line'`, schema-complete) is its inline content followed
  by a marker: a child `Y.Node` named `¶` whose map attributes hold the
  line's type (left out for a paragraph), schema fields (minus derived),
  NodeState, and for a group item the group type, key fields and level. Not
  a character with formats (#9386's U+2029) and not an embed:
  * map attributes merge per key (last writer wins), so a concurrent heading
    change and indent both apply, without format start/end items in the
    sequence;
  * the marker's identity (its item) never changes when its attributes do,
    where an immutable embed would have to be replaced (and could be
    duplicated by concurrent replacements);
  * block attributes never mix with inline formats, and text may contain
    any character.
- Groups (lists) are rebuilt from consecutive items; local groups are kept
  in the same canonical shape by a transform (adjacent equal groups and
  wrapper items merged, empty groups removed); derived fields (list
  numbering) are recomputed by a refresh update on every client. All of a
  group's synced fields (and NodeState) identify it; a nested item's marker
  also records its outer groups and their wrapper items' fields (`o`), so an
  indented first item keeps its outer list's type and the wrappers' fields
  sync.
- Storage follows the class, never the instance: a declared line stays a
  line even with a block child (the child is stored as a node inside its
  content). Undeclared or invalid blocks are `b:<type>` child nodes with the
  class's own (compact) JSON as attributes; inline elements that are not
  formats and inline decorators are `i:<type>` children.
- A container records what it holds (`c`: blocks or inline content) when it
  is created, from `collab.content` or its children, and never changes it:
  leftover inline content of a block container reads as a paragraph on every
  reader; inline content directly in a block container is always ended by a
  `¦` terminator.
- Inline wrappers declared `inline: 'format'` are one format key each
  (`w:link`, whose value holds the wrapper's fields); text formats are one
  key per format (`f:bold`), plus type, JSON fields, NodeState and, for text
  nodes Lexical would not merge, a segment key (`k`). Formats apply to any
  child, so a link can span a line break or an inline decorator; a line
  break's NodeState is a format of its `\n`. Two adjacent equal links keep an
  instance key (`#`) so they stay two links on every peer.
- NodeState equal to its default is not stored (setting it back deletes
  the key). Element `textFormat`/`textStyle` are always stored.
- Schema completeness (own `$config()`, no hand-written `exportJSON`,
  `updateFromJSON` or `afterCloneFrom` below the declaring class) is
  required for lines, groups and inline formats; anything else is a node.
- Editor instances (nested caption editors) are not synchronized; JSON
  snapshots of them are (members that JSON would drop are dropped).
- A class with a hand-written serialization is a node; an edit to one of its
  own fields alone is written (the whole node's JSON is compared) and read
  through `updateFromJSON`, then `importJSON` for fields it does not know.
- Unknown types fail closed: a client that meets a node, line, text or
  group type it does not register goes read only with a warning, so it never
  hides and later deletes content it cannot show.

Write path:
- Anchored edits: Y.Node#insert/delete/format walk the type from its start
  on every call in rc.28, so the binding edits the sequence from the item it
  knows (the previous line's marker) with a port of Yjs' text position
  algorithm. A test runs random operations through it and through
  Y.Node#applyDelta and requires identical documents (byte for byte).
- A keystroke (one text node of a line changed, same formats, every other
  child unchanged including inside links) diffs only that node's old and
  new text, anchored at the caret, and writes at its offset: cost in the line's
  items, not its length (0.4 ms in a 200,000-character paragraph).
-  Identity-anchored structure: units matched by node key (a weighted
  longest increasing subsequence: as many blocks as possible stay in place,
  a list counting as one block; between equal counts a block node, whose
  rewrite copies its subtree, outweighs lines). A line whose content did not
  change (node identity against the previous state, inline elements
  included) is never diffed; removed or moved units are deleted exactly;
  only split, join and type-change segments are diffed, as one sequence of
  the segment's items with the caret as the diff anchor: text that moved to
  another line keeps its items (no re-insert of a moved tail, so text a peer
  deleted is not resurrected). Each character keeps its old item only if it
  comes from the same Lexical text node as before (text nodes merged by a
  join or an unlink are attributed using the caret at the join, else by
  common prefix and suffix, among the nodes removed from the content being
  rewritten; text merged from elsewhere is new), so text that moved between
  nodes or lines is written as new text, never built from equal old
  characters. Diffs never split a surrogate pair. A Lexical node replaced in
  place by a new one keeps its shared node and content: a different type is
  recorded in the node's `t` attribute (a paragraph held by a list item
  turned into a heading keeps a peer's concurrent typing). Enter inserts a
  marker, Backspace deletes one, a type, indent or list type change only
  sets marker attributes.
- Structure is read from node links (the root is always marked dirty);
  attributes are written only for changed keys; inserted content carries its
  formats (no reformat after insert); format passes walk runs, not
  characters.
- Development self-check (default on outside production; `selfCheck` and
  `selfCheckSample` for production, also options of `YCollabExtension`):
  every line a write touched is read back from Yjs (text, formats, line
  break NodeState, marker), and every container a structural write touched,
  or where a group item's marker changed, is read whole into a fresh editor
  and compared with the editor's JSON (node types, list structure, wrapper
  fields, NodeState); mismatches go to the editor's `onWarn`. The whole
  container read runs every time for containers of up to 256 units and is
  sampled in proportion above that (Enter in a 2,000-block document went
  from about 50 to about 12 ms in development). All tests run with it and
  fail on a warning.

Read path: a pending local `editor.update()` is committed before a remote
transaction is read; changed items are bucketed by container once per
transaction; an inserted or deleted format item re-derives the start formats
of the following units (past block nodes too) until they agree again; each
changed item is located by walking to the next end item; text edits update
lines in place; structural changes re-parse only the touched units (groups
next to them are regrouped without re-reading untouched lines); formats that
span a marker propagate only while the value at the next unit's start
changes (re-reading the next unit as a region when it cannot be updated in
place); an inline element that cannot be empty is not shown when peers
deleted all its content; NodeState keys are read in sorted order. The local
selection is captured as relative positions before each remote transaction
(a caret anchored to the character on its left, a range to its edge
characters) and restored in the same update (an end item a peer deleted is
skipped when a position is resolved). While the local editor is composing
(IME), remote inserts into the composing line are applied to Yjs but not to
that line's nodes (the browser composes into their DOM); readers and writers
of that line skip those ids, and the line is read again when the composition
ends. Deletions, formats and structure in the composing line are read at
once, keeping the composed text node (its key and text): text a peer joins
into the line goes into nodes of its own, and a composing line joined into
the next keeps its node for the merged line. Remote reads skip Lexical's
transforms, so every list whose children a read changed, or whose items
gained or lost a nested list, is refreshed afterwards by running the list
class's own transforms with its siblings hidden (list numbering is computed
the same way on every peer, and a transform never merges two lists on one
peer only); groups are told apart by their first declared key field only (a
list by its type, as Lexical merges lists), and a region read back empty
regroups its neighbours. Groups and wrapper items carry their textFormat and
textStyle (Lexical serializes them only while an element has no text), and
each wrapper reads the fields its own group recorded. A list stored as a
node inside a line (Lexical keeps blocks pasted into a list item inside it)
reads text left without a marker as one of its items; an element that cannot
be empty is shown only while its content is not, on every reader; and two
such lists of one type that end up next to each other (added by two peers at
once) are merged (see Repairs). When the local tree joins two wrapper items,
the nested lists they hold are joined too, as a reader builds them. A link's
own textFormat is stored with its value. The character diff of a line places
a change at the caret only while the text after the caret is unchanged
(after a join the caret is before the new text). A marker attribute a peer
removed resets the field even when exportJSON hides it (`checked` outside a
check list). A NodeState value read before its key's config was known is
replaced by the known value when the node is written (a reset comment is
removed on every peer).

Recovery: a stored node a write deletes without giving it a new shared node
loses its mapping (no later write goes into a deleted node, where Yjs drops
what is inserted; this was the "cursor advanced past the end" exception on
paste). A write that throws part way is followed by a rewrite of every
container in a fresh transaction; a remote read that throws is followed by a
rebuild of the editor from the shared content (what every fresh reader
shows) in a fresh update; both are reported through `onWarn`. When the
self-check finds the editor different from the shared content after a
remote change (the shared content is right, the editor is not), those
containers are read again. (After a local write the editor is the intent,
so a mismatch there is only reported.)
A text diff with a run of equal characters places the change at the caret
(a space typed next to a space), and never splits a surrogate pair.
Repairs: concurrent edits can leave shapes Lexical would normalize, which
remote reads do not (they skip transforms): a ragged table (row insert ‖
column insert) and two equal lists side by side inside a list item. Every
client that sees one repairs it, so no particular client (or session) has to
be around. A repair is a pure function of the shared content: its inputs are
read from Yjs (never from the editor) and described independently of how
items are split (text runs with their formats, coalesced id ranges, the id
of the last character of the container it appends to), its output is
computed from that description, and it is written under a client id hashed
from the repair version, the inputs and the output encoded on a scratch
document. Clients with the same inputs write the same items once; clients
with different inputs never share an id (at worst both apply). Repairs wait
while the editor is composing or has a pending update, are read back like a
peer's change, and are not part of the undo history. Padding cells carry a
mark; an empty padding cell at the end of a row wider than the table is
removed again (an undo of the column insert), and undo of a row insert
removes its padding with it.

Containers opt out of Yjs' remote formatting cleanup, which rescans every
type with formats after a remote format change (O(document) here): the
binding marks its containers as having no formats before Yjs decides. The
document's `cleanupFormatting` flag and the app's other types are untouched.

Servers on yrs before 0.28 read client ids as 32-bit numbers, while Yjs 14
draws 53-bit ones. With Yjs 14's default ids:
- a ywasm 0.23.5 relay stores an author's content under a truncated id, and
  the author receives its own content back as another client's on reconnect,
  duplicating it;
- a real yrs 0.23 server rejects the reconnect ("the awareness update is
  malformed"), and edits made offline are lost.
yrs/ywasm 0.28.0 is fine. Opt-in compatibility: `clientIDRange: 'uint32'`
(binding, extension, `writeEditorToYDoc`) or `createYDoc({compat:
'yrs-0.23'})` keeps the document's client id in 32 bits, including when Yjs
draws a new one; the id the binding uses for the initial content is always
32-bit. The default, `'uint53'`, leaves Yjs 14's ids unchanged. The binding
does not own the awareness, which takes the document's client id when it is
created; the README tells apps to create the awareness and provider from a
document that already has a 32-bit id. With 32-bit ids, a yrs 0.23 server
converges, including offline edits, reconnects and late joiners.

Undo: Yjs 14 UndoManager on the root, tracking only this binding's writes. A
container the undone change inserted that holds another client's content is
kept whole (its fields and own content too), unless the undo also restores
a container of the same type (the change was a move: keeping the copy
would duplicate it).
Cursors: `getCursor()` / `$resolveCursor()` (relative positions on items;
no provider wiring or rendering).

`@y/y` internals used (all in rc.28; a bump must re-run the cursor
equivalence test): `new Item(...)`, `item.integrate`, `getItemCleanStart`,
`createID`, `Item.left/right/origin/rightOrigin/parent/content/deleted/
countable/length`, `YNode._start`, `_item`, `_map`, `_length`,
`_searchMarker`, `_hasFormatting`, `_legacyTypeRef` (upgrade notice), the
`beforeObserverCalls` event, `doc.store.getItem/getClock`,
`iterateStructsByIdSet`, `decodeUpdate`, `findRootTypeKey`.

Supported: split, join, partial joins, heading/quote/paragraph, list type,
indent/outdent, Enter in list items, checked state, alignment and NodeState
of lines, links and other inline formats (incl. property changes and spans
across line breaks), text formats, comments as NodeState, tables and any
nested containers (collapsible-like container > title + content, cell >
collapsible, box > box), block and inline decorators, inline elements
(MarkNode) with nested content, undo/redo, cursors, local selection across
remote edits.

Known limits:
- A move is a delete and a reinsert: text a peer types into a moved line
  lands in its old neighbour. The cheaper side is rewritten: a long move
  rewrites the moved block, not every block it passed; in a swap the smaller
  block is re-created (a collapsible dragged past a box keeps a peer's
  typing inside it); between equal blocks the moved one (Lexical's record of
  explicit moves, `_recordNodeMoves`).
- Lexical restructures written as moves lose a peer's concurrent typing in
  the moved paragraph: a list created from a paragraph inside a container
  that is not a shadow root (a box), indenting or pasting list items that
  hold blocks. Two peers pulling the same text across a container edge
  (range deletes from a list item into a collapsible title) both copy it.
- Properties a class keeps outside its `$config()` schema and NodeState are
  not synced; such classes are stored as nodes with a warning naming the
  properties (Lexical itself drops them when it clones the node).
- MarkNode is an element with its own content: wrapping a range moves the
  text into it, and concurrent typing in that range stays outside. Comments
  should use per-id NodeState (MarkStateExtension).
- A split racing a type change gives the first half the splitter's type;
  text typed into a line a peer removed joins the next line.
- Slots are not synchronized; a link's fields merge as a whole (last
  writer wins).
- Yjs format semantics: bold ‖ bold on adjacent ranges of one line can leave
  part unformatted (the same on Yjs 13).
- A join ‖ removal of the joined line also joins the next line (nothing
  deleted comes back); unwrapping a container is a removal and a
  reinsertion of its lines, so text a peer types inside it at the same time
  is lost, as is text typed inside a container a peer removed (delete
  wins).
- The list merge copies the second list's content into the first and
  deletes the second, so text anyone types into the second list (its author
  included) before the merge reaches them is lost.
- A peer's repair can move the line the editor is composing in (IME): the
  development self-check may warn until the composition ends (it then
  converges), and composed text in the moved line follows the move ‖ typing
  limit.
- Repair detection walks every container a remote change touched (linear;
  about 27 ms at 320,000 items in one container, some 8% of receiving a
  keystroke).
- Two clients initializing with different content at once both keep their
  content (converged).
- Undo never deletes a container another client has put content in (it is
  kept whole): after two peers' lists inside one list item are merged,
  undoing either addition keeps the merged list; undoing the addition of
  the list a peer is merging away does nothing, and a later redo adds it
  again, so its items show twice. Two clients that repair the
  same shape from different content (one has an edit in one of the lists
  the other has not received) both apply their repair, so the moved list's
  items can show twice. A list that ends up right before a line of an equal
  nested list (a peer deleted the text between them) shows inside that
  line's item rather than merged (every client shows the same).
- Several edits to one line in a single update are written as one replace
  (a peer's caret inside it moves to the edge).
- Structural edits in a large list cost time proportional to the list on
  both sides (regrouping and renumbering): about 4x main end to end at 10,000
  items. Enter at 10,000 blocks (core text walk skipped) is 26.4 ms against
  main's 19.6 ms.
- Relies on the @y/y internals listed above.
- Version gate: the layout version must be an integer from 1 to
  `LAYOUT_VERSION`; anything else is read only.
- With Yjs 14's default 53-bit client ids, servers on yrs before 0.28
  duplicate content or lose offline edits on reconnect; use the opt-in
  32-bit range for them, and create the awareness from that document.

Known open issues (from randomized runs; see Fuzz below):
- Two peers moving the same blocks at once (move ‖ move) can duplicate or
  lose a block; 2 of 9,983 differential seeds are worse than both Yjs 13
  layouts (see Fuzz).
- NodeState keys of a node keep the order of the author's local history in
  its own editor (values equal; other clients read them sorted).
- Not a binding issue: `$toggleLink(null)` on a range that ends at the edge
  of a link's text throws in `$splitLinkAtSelection` (empty
  `extractedChildren`), in any editor on main; the fuzz no longer generates
  it.

## Test plan

### Before

The Yjs 13 layouts on the same scenarios, from their own branches: main v2,
#9383 and #9386 lose or misplace concurrent typing on split, join, retype,
indent and nested containers (#9386 fixes most of them on Yjs 13); bytes per
operation are in the table below.

### After

New tests in `packages/lexical-y/src/__tests__/unit` (headless peers with
pinned client ids, offline edits then sync, both id orders, causal and
per-sender delivery, two and three peers; every case checks every peer, a
fresh reader, no exception and no self-check warning):
- `BlockMarkers.test.ts`: split, join, heading, quote, list indent, list
  type, Enter in a list item, link, table cell, custom block, removals with
  three peers, and 40 randomized intent seeds;
- `Races.test.ts`: links, unlink, undo of a link, overlapping formats,
  heading/quote/split/join/indent/list type/Enter races, moves, table rows
  and cells, row insert ‖ column insert, MarkNode; moves and MarkNode are
  documented limits (converged, intent not kept);
- `Nested.test.ts`, `NestedFuzz.test.ts`: collapsible-like containers,
  collapsible in a table cell in a collapsible, box > box, six-level lists,
  mixed inline and block content, emptied containers, list numbering,
  content inside marks (links, equations, nested marks), comment state ‖
  link wrap, 20 randomized nested seeds;
- `Selection.test.ts`: carets and ranges across remote edits, link URL
  change, a space typed next to a space;
- `WriteRecovery.test.ts`: a write that throws part way is rewritten and
  reported; a remote read that throws rebuilds the editor, reported, and
  later edits converge; a nested list that becomes a level is not written
  into its old shared node;
- `Repairs.test.ts`: row ‖ column insert then either inserter undoes (the
  table stays rectangular, both id orders); two lists added to one item
  merge whether or not the second list's author has reloaded (fresh reader
  agrees); undo after a merge keeps the merged list (documented);
- `RepairsConcurrent.test.ts`: several clients repairing at once, one of
  them composing in the moved list while a peer types there, and with the
  author's items split by undo/redo (lists and tables); one copy, every peer
  and fresh reader equal;
- `RepairFuzz.test.ts`: 60 randomized seeds (4 peers: lists added to one
  item, table rows and columns, composition with a peer typing into the
  composed line, undo/undo/redo, partial delivery); convergence, fresh
  readers, no warning;
- `BulkScale.test.ts`: select all + remove bold and join every pair of lines
  at 5,000 and 20,000 lines (linear; 20,000 lines in about 2 s);
- `ListsInLines.test.ts`: lists inside a list item added by two peers merge
  once; text left in a removed item reads as an item; an emptied list is
  hidden on every reader; joined wrapper items join their lists; wrapper,
  group and link text formats; a join ‖ delete keeps the joined text whole;
  a marker-only write on a line holding a list peers emptied;
- `Composition.test.ts`: IME composition (composition key) with a peer
  inserting before, right before, after and inside the composed text, edits
  in other lines, structural edits and deletions in the composing line, a
  peer joining the lines while composing at the start of line 2 or the end
  of line 1;
- `NestedLists.test.ts`: a nested list in a table cell removed ‖ Enter in
  two of its items (3 peers), undo of a list type change after a peer
  checked an item, paste + indent + undo numbering, typing ‖ a paragraph
  turned into a list in the root, a cell and after a list;
- `LineBreakState.test.ts`: NodeState set, reset and combined with text on
  an existing line break;
- `Init.test.ts`: undo after initialization, concurrent initializations
  (same and different content, two different roots with equal content),
  legacy roots, upgrade notice, conversion in
  place, extension (status, undo state, history conflict);
- `Storage.test.ts`: layout, every node kind, keystroke/Enter/Backspace and
  attribute-only updates, block child in a line, schema-incomplete
  subclasses, newer layout read only, no write before initialization,
  headless writer, undo, cursors;
- `Cursor.test.ts`: write cursor ≡ Y.Node#applyDelta (60 random seeds);
- `Size.test.ts`: byte budgets per operation and for a 10,000-edit session;
- `YrsCompat.test.ts`: a relay on ywasm 0.23.5 duplicates a 53-bit
  author's content on reconnect, not with `clientIDRange: 'uint32'` or
  `createYDoc({compat: 'yrs-0.23'})`, ywasm 0.28.0 handles 53-bit ids, and
  the 32-bit range survives Yjs drawing a new id (ywasm 0.23.5 and 0.28.0
  are dev dependencies);
- Regression tests: `Concurrency.test.ts` (lists, links, moves, formats in
  every order), `BlocksAndLines.test.ts` (a block inserted before a line ‖
  typing at its start, undo of a container a peer typed into, nested list
  shapes, paragraphs held by list items, moves past tables and their undo),
  `Ranges.test.ts` (range deletes across lines, line break NodeState,
  adjacent equal links), `Links.test.ts`, `EmptyMarks.test.ts`,
  `Tabs.test.ts`, `NestedItems.test.ts`, `NodeStateDefaults.test.ts`,
  `Document.test.ts` (group fields, pending local update),
  `Surrogates.test.ts`, `Lifecycle.test.ts` (version gate, concurrent init,
  undo across peers, dispose of a read-only binding restores editability),
  `OtherRoots.test.ts`, `Nodes.test.ts` (link fields, schema subclasses,
  hand-written classes, object values, unknown types read only);
- `Fuzz.test.ts`: 300 seeds plus 100 with gc (3 peers, every delivery mode,
  typing, formats, links, comments, lists, tables, containers, undo/redo;
  convergence, fresh reader, canonical shape, self-check, no lost or
  duplicated tokens), longer runs through `FUZZ_SEEDS`, a differential run
  through `FUZZ_DIFF=1` (absolute checks on @lexical/y's full script,
  including reads or writes the binding recovered from, and worse-than-both
  on cut scripts); one seed where all three layouts lose the
  same token is listed in the test. `FuzzReplay.test.ts` replays 46
  minimized scripts of fixed failures;
- `Server.test.ts`, `ServerScale.test.ts`, `Source.test.ts`: server helpers
  (old client's update, delete-only update, linear time on 8,000-paragraph
  updates, notice readable by a Yjs 13 client), fail-closed editability, no
  `process.env` but NODE_ENV in shipped source.
- Core: `LexicalCollabNodeConfig.test.ts` covers `content`.

Fuzz, differential: the same scripts run on this binding, on #9386 and on
the default v2 layout of @lexical/yjs as it is in this stack (origin/main's
v2 plus the stack's fix that writes only changed text attributes; on the
duplicate seeds origin/main behaves the same). Two checks per seed:
- absolute, on @lexical/y's full script: divergence, an exception, a
  fragmented token, a self-check warning or a fresh-reader mismatch: 0 of
  the 22,474 seeds below (9,983 with moves, 9,995 without, 2,496 with gc);
- relative, "worse than both": each pair is compared on the script cut
  before the first op the two runs resolved differently, and @lexical/y
  loses or duplicates more unique tokens, or diverges, throws, fragments or
  hangs, than #9386 and than v2; text typed into a container a peer
  removed, which the other layout keeps only by bringing back deleted
  content, is not counted as lost (`resurrectionExcuse`). With moves: 2,
  both move classes (a list moved ‖ two of its items swapped duplicates an
  item; a delete across a table ‖ a paragraph moved past it). Without
  moves: 0. With gc: 0.
@lexical/y loses fewer tokens than #9386 on about 7% of seeds and than v2 on
about 38%. Hangs: #9386 26, @lexical/y 0.
Within a partition, the fuzz relays updates as a sync protocol would.

A second, list-heavy generator (3-4 peers, partitions, gc on some seeds,
collapsible > table > cell > list shapes, deep lists in boxes, emoji, CJK
and Ext-B text, overlapping MarkStateExtension comments, links, line breaks,
rich paste into list items, indent storms, undo/redo; run locally, as it
needs MarkStateExtension, which is not in this stack), full scripts: 6,000
seeds with line breaks, 6,000 without and 3,000 with moves: 0 divergence, 0
fresh-reader mismatches, 0 self-check warnings and 0 non-canonical shapes
(adjacent equal lists, empty lists, lists with other children); remaining
findings are delete-wins losses, the restructure-as-move limit above (1.2%,
1.3% and 2.5% of seeds duplicate an item), fragmented tokens in 4, 6 and 2
seeds (the one examined: a container removed while a peer pastes into
it) and NodeState key order in the author's own editor.

Real browsers (Chromium, Firefox, WebKit through Playwright; separate
contexts over a Yjs 14 WebSocket relay with a 200 ms delay; real key events;
convergence, fresh load, token checks, no console warnings, editor errors
or self-check warnings): Chromium 60/60, Firefox 53/53 and WebKit 53/53;
17 more cases (nested containers with 3 peers, lists in cells, emoji and
CJK, IME at a line boundary while a peer joins, drag and drop, comments,
reloads, a 2,000-block document): Chromium 17/17, Firefox and WebKit 13/13
(IME cases need CDP and are skipped in Firefox and WebKit). The WebKit
split + join race under load (4 workers, 100 runs): 98 passed, 2 lost to
browser crashes; an earlier caret
jump there was a position resolving across a deleted line marker.

Performance (headless Node, shared VM, medians, ms):

```
                                N=2,000            N=10,000
keystroke (end to end, 2 peers) 9.0                55.1      (main 54.3, B 50.3)
  core text walk skipped        0.53               2.1       (main 7.1, B 2.6)
Enter / Backspace               13.7 / 13.6        75.7 / 75.8 (main 74.2 / 74.7)
  core text walk skipped        4.8 / 4.8          26.4 / 27.0 (main 19.6 / 19.4)
document size (bytes)           164,000            833,603   (main 872,754,
                                (main 171,110)      A 1,006,407, B 1,391,890)
fresh load                      90                 416       (main 427, B 945)
initial bulk write (1 update)   271                1,104     (main 894, B 1,260)
```

Stress shapes (local update + write + peer read): 400 nested sections
(collapsible > table > cell > collapsible > list, box) paste 300, load 130,
208 KB; 10x10 tables 100/200/400 paste 1,099/1,875/3,864, load
412/776/1,570; bold everything in a list of 5k/10k/20k items 302/548/1,170;
add a NodeState comment in a 10k/20k/40k list 37/77/237; indent in a flat
list of 2.5k/5k/10k items 81/134/271; keystroke in a 50k/200k-character
paragraph 0.34/0.43. All linear.

Bytes per operation (gc off, client ids in Yjs' random range; op / undo /
redo):

```
                         main v2        #9383 (A)      #9386 (B)      @lexical/y
type a char mid line     25/11/26       25/11/26       25/11/26       24/10/24
paste 1k chars           1025/12/1026   1025/12/1026   1025/12/1026   1024/11/1025
Enter mid line           86/57/88       86/57/88       78/11/81       26/10/26
Backspace join           70/107/78      70/107/78      10/76/11       10/26/10
heading toggle           124/108/126    124/108/126    122/48/127     48/10/38
indent list item         134/58/135     134/58/135     54/37/57       65/27/60
link a word              175/73/190     276/11/292     282/11/292     103/10/103
bold a range             131/11/143     131/11/143     137/11/143     59/10/59
add a comment            137/11/149     137/11/149     143/11/149     65/10/65
table row insert         146/11/153     146/11/153     335/11/335     189/10/188
delete a table           10/439/11      10/439/11      11/1089/11     11/563/10
10,000-edit session      2,839,497      3,124,314      404,571        210,029
```

A Yjs 14 document written by this binding, with concurrent updates relayed
through yrs (ywasm 0.28.0), reloads into a fresh client identically; on yrs
0.23 it does with `clientIDRange: 'uint32'`.

```
$ npx vitest --project unit --no-watch packages/lexical-y/src \
    packages/lexical/src/__tests__/unit/LexicalCollabNodeConfig.test.ts
$ pnpm run tsc; pnpm run tsc-test   # exit 0
$ pnpm run flow                     # Found 0 errors
$ npx vitest --project scripts-unit --no-watch \
    scripts/__tests__/unit/treeShakingSource.test.ts
$ pnpm run prepare-release           # release build, package and type checks
$ pnpm --filter lexical-playground run build-vercel
$ pnpm --filter @lexical/website run build
```
@zurfyx zurfyx closed this Oct 23, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — 095ed3f3 Deployed Oct 20, 2026 by vercel[bot]
Preview – lexical-playground — 095ed3f3 Deployed Oct 20, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants