Repository navigation
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
…ab v2 text run becomes an inline element
## Description
In collab v2 a paragraph's adjacent TextNodes share one `Y.XmlText` run, and
every other inline child (MarkNode, LinkNode, LineBreakNode, inline
decorators) is a sibling of it. When the start of a run is replaced by such a
child, for example wrapping the first word of a paragraph in a comment mark or
replacing it with a line break, the children change from `[XmlText]` to
`[XmlElement, XmlText]`.
`$updateYFragment` only reused a text run in place when it paired with the
left edge of the unmatched range. Here the left Lexical child is the new
element, so the run fell through to delete-and-insert: the whole `XmlText`
was deleted and recreated. Anything a peer had concurrently typed into that
run (anywhere later in the paragraph) was anchored to the deleted items and
was dropped on every peer. The same edit without concurrency also needlessly
gave every character of the run a new identity.
The compare loop now mirrors the left-edge text branch on the right edge:
when the rightmost unmatched pair is an `XmlText` and a run of TextNodes, the
run is updated in place with `$updateYText`. The resulting document content
is unchanged; only the shared type (and with it, concurrent inserts) is kept.
This does not cover wrapping the whole run (e.g. a comment over all of a
paragraph's text while a peer types inside it): the text then has to move
into a new container, which Yjs cannot do without a delete.
## Test plan
New `packages/lexical-yjs/src/__tests__/unit/SyncV2TextRunReuse.test.ts`
wires two v2 peers like `useYjsCollaborationV2` over an in-memory transport
that queues updates while offline. While offline, peer A wraps the first word
in a MarkNode (or replaces it with a line break) and peer B types at the end
of the paragraph; after reconnecting, both editors and a fresh reload of each
peer's Yjs document must show both edits. A third case checks that, without
concurrency, the tail run keeps its original `XmlText`.
### Before
```
$ npx vitest --project unit --no-watch packages/lexical-yjs/src/__tests__/unit/SyncV2TextRunReuse.test.ts
❯ |unit| packages/lexical-yjs/src/__tests__/unit/SyncV2TextRunReuse.test.ts (3 tests | 3 failed) 47ms
× keeps a concurrent insert when the first word is wrapped in a mark 31ms
× keeps a concurrent insert when the first word is replaced by a line break 7ms
× updates the run in place when its head is wrapped (no concurrency) 8ms
AssertionError: expected 'paragraph(mark("Revenue") " grew 4% i…' to be 'paragraph(mark("Revenue") " grew 4% i…' // Object.is equality
Expected: "paragraph(mark("Revenue") " grew 4% in Q3. more")"
Received: "paragraph(mark("Revenue") " grew 4% in Q3.")"
AssertionError: expected 'paragraph(br "grew 4% in Q3.")' to be 'paragraph(br "grew 4% in Q3. more")' // Object.is equality
Expected: "paragraph(br "grew 4% in Q3. more")"
Received: "paragraph(br "grew 4% in Q3.")"
AssertionError: expected YXmlText{ _item: Item{ …(11) }, …(9) } to be YXmlText{ _item: Item{ …(11) }, …(9) } // Object.is equality
- ""
+ " grew 4% in Q3."
Test Files 1 failed (1)
Tests 3 failed (3)
```
### After
```
$ npx vitest --project unit --no-watch packages/lexical-yjs/src/__tests__/unit/SyncV2TextRunReuse.test.ts
✓ |unit| packages/lexical-yjs/src/__tests__/unit/SyncV2TextRunReuse.test.ts (3 tests) 46ms
Test Files 1 passed (1)
Tests 3 passed (3)
$ npx vitest --project unit --no-watch packages/lexical-yjs packages/lexical-react/src/__tests__/unit/Collab* packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx
Test Files 17 passed (17)
Tests 173 passed (173)
```
`pnpm run test-unit`: 393 files, 9540 tests passed (1 skipped).
`pnpm run tsc`, `pnpm run flow` (0 errors), ESLint and Prettier on the
changed files pass.
Run headless in Node/jsdom with an in-memory
transport only; not exercised in a real browser or over a real provider.
zurfyx
added a commit
that referenced
this pull request
Oct 22, 2026
…al-devtools] Feature: Stable block ids (BlockIdExtension)
## Description
Lexical has no stable way to address a block from outside the editor. Node keys are runtime-only and change on every load, and the position of a block changes with every edit. Code that edits a document by block (an AI agent that reads blocks and answers `replace <id>`, `insert after <id>`, `delete <id>`, or a server pipeline that patches stored JSON) needs an id that survives serialization, reloads and collaboration.
This adds an `@experimental` `BlockIdExtension` to `@lexical/extension`, and an opt-in `BlockIdHTMLExtension` to `@lexical/html`:
- **Storage.** The id is NodeState (`blockIdState`, key `blockId`), serialized as `"$": {"blockId": "…"}`. It survives clones, undo/redo and the Lexical clipboard, and syncs through any binding that syncs NodeState (`@lexical/yjs` v1 and v2 both do). It is declared `resetOnCopyNode`, so `$copyNode` does not copy it. Any non-empty string of at most 128 characters is a valid id, so an app that already stores its own ids under `$.blockId` (UUIDs, for instance) can switch to `blockIdState` without migrating documents.
- **API.** `$getBlockId(node)` and `$getBlockById(id)`. The lookup goes through an index that is updated from the dirty nodes of each commit, and every hit is checked against the active state. Config: `$isIdentifiedBlock` (default `$defaultIsIdentifiedBlock`, the element and decorator children of the root; nested blocks and blocks in slots are opt-in), `generateId` (default `generateBlockId`), and `disabled` (config plus output signal). The per-editor state (index, config) is the extension's init result, so it is not reachable from the output.
- **Id format.** `generateBlockId` makes 21 URL-safe characters: 126 random bits, more than the 122 of a version 4 UUID. Ids are generated by every peer and by servers with no coordination, so the size alone must rule out collisions between ids generated concurrently (see Design).
- **Assignment.** Every identified block without an id gets one in the same update that creates it, including blocks created by `importJSON`, HTML import and markdown import. `setEditorState(parseEditorState(json))` assigns every missing id in that one commit, so a headless server can load, assign and save in a single synchronous write. Updates that skip transforms (remote collaboration changes) are repaired by a discrete follow-up update.
- **Uniqueness.** When several identified blocks share an id, the block that already had it before the update keeps it, and blocks that got it in this update (paste, duplicate, `$copyNode`, JSON or HTML import, an explicit `$setState`) get fresh ids. When several had it before (a duplicate that was committed, such as concurrent edits that meet in a merge), the earliest in document order keeps it. When none had it (several copies created in one local update), the first one created keeps it. The rule is deterministic, idempotent and O(dirty): each holder is compared with its own version in the previous editor state.
- **Slots.** Everything the extension walks visits slot values as well as children: the index rebuild, removals (a removed host takes the blocks of its slots out of the index), the lookup while disabled, and document order (a host's slots, in their canonical order, come before its children, as in `$dfsWithSlots`). Replacing a slot value with `$setSlot` keeps the id, like `replace`.
- **Lineage.** The extension carries ids across splits, joins, type changes and moves (rules below). Core does not carry NodeState across `$setBlocksType`, so the extension detects the replacement from the previous state in the update that makes it. No core behavior changes.
- **HTML.** `BlockIdHTMLExtension` writes `data-block-id` on exported identified blocks and reads it back through `DOMImportExtension`. Imported ids are validated and go through the uniqueness rule. Because it changes export output, the docs warn against adding it to editors whose HTML export must be deterministic (or to use `export: false` there). This is a separate extension in `@lexical/html` because `@lexical/html` already depends on `@lexical/extension`, so the dependency cannot go the other way. Its `export` and `import` config flags can turn off either direction.
- **Docs.** New page `docs/extensions/block-ids.md`, plus entries in the included-extensions list. Flow types are added for both extensions. The page documents the one-line agent `replace_block` (`$getBlockById(id)?.replace(newBlock)`, which keeps the id on every binding) and a known limit with `@lexical/y`: its deterministic-init deduplication cannot merge identical initial content from two clients when that content carries random ids, so initial content should be seeded on the server or given fixed ids.
- **Errors.** A `generateId` that keeps returning invalid or used ids fails through `invariant`, like the rest of the package.
`@lexical/extension` is the home because the feature is editor-level behavior with no node classes and no dependencies beyond `lexical`. That is the same shape as `NormalizeInlineElementsExtension` and `SelectBlockExtension`. A headless server needs only `lexical` and `@lexical/extension`.
Related: #9174 is an example app that implements an application-owned id policy with released APIs (a RootNode transform over `$dfsWithSlots`, 128-bit random ids, fresh ids for every paste). This PR ships the reusable version of that idea; its slot coverage and its random-id size match what that example does, and it does not touch `concepts/node-state.md`, which #9174 edits.
### Design
**Why NodeState.** The id has to mean the same thing in a headless process editing stored JSON, in a solo editor, and between collaborators on any binding. NodeState is the one storage that all of those already carry: JSON, clone, undo, clipboard, and the collaboration bindings. CRDT item identity would tie ids to one binding and one session, and would not exist at all without collaboration.
**Why 126 random bits rather than a peer prefix plus a counter.** A local collision is retried, so only ids generated concurrently by different peers can collide. Outside a collaboration session there is no peer identity to use as a prefix (a server editing stored JSON has none), so a prefix would itself be random and would need about 72 bits to stay unique across every session that ever edits a document. Prefix plus counter would then be 13 to 15 characters instead of 21, saving about 6 characters of JSON per block, and would make ids sequential: an agent that mistypes `…-17` as `…-18` would silently edit another block, where a mistyped random id names no block and the edit fails visibly. With 126 random bits (more than a v4 UUID's 122), a document with a million blocks has less than a 10⁻²⁶ chance of holding two equal ids. `generateId` stays configurable for apps that prefer prefixed ids; prompts that need shorter ids can alias them.
**Why the existing block wins, and how ties are broken.** An agent that holds an id must keep reaching the same block after someone pastes or duplicates it, wherever the copy lands, including above the original. Within one update the editor knows which holder already had the id (it is in the previous state with that id) and which got it now, so the copy always yields. Two tie-breaks cover the cases where that does not single out one block:
- *Several holders were committed together* (concurrent moves that a CRDT merges into two copies). Every peer that sees the duplicate repairs it, so every peer must pick the same survivor. Node keys cannot do this: each peer numbers the nodes it receives in its own order, so with key order each peer keeps its own copy and re-ids the other, and the merged document loses the id altogether (the concurrent-moves collab test fails exactly that way when key order is substituted). Document order is the same for every peer that sees the same document. It costs O(depth) plus a walk over the siblings between the two holders, like `isBefore`, and runs only to repair a committed duplicate.
- *All holders got the id in one local update* (several copies pasted or imported together). Only this editor decides and the others receive the result, so the cheaper creation order (node keys, which only increase) is enough. Fresh ids are also generated in creation order.
Peers that repair the same merged duplicate concurrently keep the same block and differ only in the fresh id they give the loser. The shared document keeps one of those values, after which there is nothing left to repair. A repair never creates a duplicate, so it cannot ping-pong. A local copy never reaches the shared document as a duplicate at all, because it is repaired in the update that creates it.
| Edit | Id result |
| --- | --- |
| Enter in the middle or at the end of a block | Block keeps its id; the new block gets a fresh one |
| Enter at the start of a block | The text moves into the new block below, and the id moves with it; the emptied block above gets a fresh id |
| Backspace join | The surviving block keeps its id |
| Paragraph to heading, quote or list (`$setBlocksType`, `INSERT_*_LIST_COMMAND`) and back | The replacement keeps the id |
| `replace(newNode)` with a node that has no id, or `$setSlot` replacing a slot value | The new node keeps the id |
| Move (drag and drop, `insertAfter`/`insertBefore`) | The id moves with the block |
| Paste, duplicate, JSON or HTML import of copied content | Copy keeps the id only if no other block has it; otherwise the original keeps it, even when the copy is placed above |
| Several copies created in one update, none pre-existing | The first one created keeps the id |
| Cut and paste | The pasted block keeps the id (nothing else has it any more) |
| Copies that only meet in a collaborative merge | The earliest in document order keeps the id |
| `$copyNode` | The copy has no id and gets a fresh one |
| Undo/redo | Exact ids restored |
`insertNewAfter` behavior that was checked: `ParagraphNode`, `HeadingNode` and `QuoteNode` create a new node without NodeState. `QuoteNode` creates a paragraph, so Enter at the start of a quote leaves an empty quote above and moves the text into a paragraph that keeps the id. `HeadingNode` at the start replaces itself with a paragraph (`replace(…, true)`) and moves the text into a new heading, which takes the id. `ListItemNode` uses `$copyNode`, which leaves the id behind.
### How agents use this
```ts
// What the agent reads.
const blocks = editor.read(() =>
$getRoot().getChildren().map(node => ({id: $getBlockId(node), text: node.getTextContent()})),
);
// What it answers: [{op: 'replace', id: '…', text: '…'}, {op: 'delete', id: '…'}]
editor.update(() => {
for (const op of ops) {
const block = $getBlockById(op.id);
if (block === null) continue; // gone meanwhile, or a mistyped id
if (op.op === 'delete') block.remove();
else block.replace($createParagraphNode().append($createTextNode(op.text))); // keeps the id
}
}, {discrete: true});
```
### Performance
On a 10,000-block document (headless). The harness runs an editor with the extension and one without it through the same operations, interleaved round by round, so that process drift affects both alike (`BLOCK_ID_PERF=1 npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts`):
```
10000 blocks, median, interleaved without with delta
keystroke (300) 13.809 ms 14.650 ms 0.841 ms
Enter (300) 14.341 ms 16.650 ms 2.309 ms
paste 20 blocks (50) 16.206 ms 18.891 ms 2.686 ms
paste 50 blocks (50) 18.870 ms 21.928 ms 3.058 ms
remote duplicate (50) 25.414 ms 58.428 ms 33.014 ms
load JSON (once) 131.910 ms 261.360 ms 129.450 ms
```
These numbers come from a shared machine under load. Across runs the keystroke delta moved between 0.6 and 1.3 ms, and a probe that interleaved five editors (none, a no-op root transform, no-op transforms on every node class, a no-op update listener, and the extension) measured the editor with the extension as the fastest of the five, so the keystroke delta is within noise: typing creates no block, and the extension does nothing for it beyond an O(dirty) index check. The Enter delta moved between 2.0 and 3.1 ms. Instrumentation put the extension's own work at about 0.1 ms per Enter; most of the Enter delta is Lexical running the root transforms a second time, including the O(root children) shadow-root normalization, because a transform changed a node. A ten-line extension that only sets a NodeState on new paragraphs in a transform measured +1.04 ms in the same harness. Assigning fresh ids in creation order instead of document order took the 50-block paste delta from 8 to 9 ms down to about 2 to 3 ms in the same harness. The remote-duplicate row is dominated by the second commit (the repair update) on a 10,000-block document; ordering the two holders takes 0.44 ms of it. The load row is the one-time assignment of 10,000 ids.
## Test plan
New tests:
- `packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts` (headless, 53 tests): assignment in the creating commit; importJSON; markdown; documents opened without ids; foreign states; the headless recipe; invalid stored ids; generator collisions; the default id format (21 characters, all 64 symbols used); duplicates in JSON; determinism and idempotence; duplicates after the original and above it (the original keeps the id); duplicating a block upward; several copies in one update (the first created keeps it); a committed duplicate repaired the same way whichever order its nodes were created in; `$copyNode`; explicit clashing ids; `$copyNode` right after a JSON load (before anything has read the state); copy/paste within and between editors; pasting a copy above the original; cut and paste, in two updates and in one; undo/redo of a paste; Enter at the start, middle and end of paragraph, heading, quote and list item (nested); Backspace and forward-delete joins; `$setBlocksType` single, multi and empty blocks, and back; paragraph to list; moves; manual replace; undo/redo of every step with the index checked; `$getBlockById`; O(dirty) predicate calls on a 1,000-block document; list and table nesting; disabled/enabled; repair after updates without transforms and after collaboration-tagged updates.
- `BlockIdExtension.slots.test.ts` (10 tests): blocks inside a slot container and a block that is itself a slot value get ids in the creating commit; a duplicate pasted into a slot yields; committed duplicates between a slot and its host's children, and between two slots, are repaired in document order whichever order the nodes were created in; `$setSlot` replacement keeps the id; `$setBlocksType` inside a slot; the index after undo and after `setEditorState`; removing a host frees the ids of its slots; the lookup while disabled.
- `BlockIdExtension.dom.test.ts` (jsdom, mounted editor): typing, Enter and Backspace; Backspace at the start of the first heading; clipboard paste between editors and within one; legacy HTML paste; undo.
- `packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts`: off by default; export on identified blocks only; nested export; HTML round trip (exported to a DOM document and imported from it); imported ids through the uniqueness rule (duplicates, clashes, empty, too long); `export: false`/`import: false`. Fixtures are fixed strings parsed with `DOMParser`, or built with `createElement`/`setAttribute`.
- `packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts`: a headless harness wiring v1 and v2 bindings the way the React plugins do. It runs 11 tests per binding: ids assigned once by the creator; a late joiner writes nothing; concurrent Enter; concurrent duplicates on three peers, one pasted above the original; concurrent moves that duplicate a block after merge; a document written without ids repaired concurrently by two peers; type change and move; type change concurrent with typing; Yjs undo/redo of a split; join concurrent with Enter; nested list ids. Every test checks convergence, unique ids and quiescence: a further round produces no Yjs update.
- `BlockIdCollabFuzz.test.ts`: deterministic randomized runs with 2 or 3 peers mixing typing, Enter, join, duplicate, block type changes, moves, Yjs undo/redo and partitions. They assert convergence, every block having an id, unique ids, quiescence, and that blocks never split, merged, copied or concurrently restructured keep their ids. CI runs 8 seeds per binding; `BLOCK_ID_FUZZ_SEEDS` runs more.
- `BlockIdExtension.perf.test.ts`: the measurement above; skipped unless `BLOCK_ID_PERF=1`.
### Before
On `main` with the new test files copied in:
```
$ npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts packages/lexical-extension/src/__tests__/unit/BlockIdExtension.slots.test.ts packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts
FAIL |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts > BlockIdExtension (DOM) > typing, Enter and Backspace in a mounted editor
TypeError: Cannot read properties of undefined (reading 'name')
...
Test Files 6 failed (6)
Tests 112 failed (112)
```
### After
```
$ npx vitest --project unit --no-watch <the same six files>
✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts (5 tests) 189ms
✓ |unit| packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts (6 tests) 53ms
✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.slots.test.ts (10 tests) 35ms
✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts (22 tests) 225ms
✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts (53 tests) 240ms
✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts (16 tests) 476ms
Test Files 6 passed (6)
Tests 112 passed (112)
$ BLOCK_ID_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts # run as 4 shards of 500 seeds
FAIL |unit| …BlockIdCollabFuzz.test.ts > BlockIdExtension fuzz, @lexical/yjs v2 > seed 198
# likewise v2 seeds 462, 811, 938, 1086, 1157, 1918
Tests 7 failed | 3993 passed (4000)
```
All 2,000 seeds pass on v1. The 7 v2 failures are pre-existing problems in the v2 binding, not in block ids:
- In 6 of them, the v2 binding moved text from one block element into another under concurrent moves, joins and undo. For example, seed 938 ends with a block whose text is `M4 tex zM2 textM1 zt`, and seed 1918 splits the `M1` text across two elements. NodeState stays with the element, so the id follows the element rather than the text.
- In the other one (seed 198), the peers' texts diverge.
The same harness with the extension removed (`BLOCK_ID_FUZZ_CONTROL=1`, which checks convergence only) gives `Tests 10 failed | 3990 passed (4000)`: v2 seeds 198, 479, 612, 717, 1017, 1250, 1354, 1506, 1748 and 1873 diverge, and every v1 seed passes. Both results are unchanged with #9381 and #9377 (the open v2 attribute and text-run fixes) merged in.
The same suite and 2,000-seed fuzz were also run against `@lexical/y` (#9400) on a local integration branch that adds this commit and ports the two test files to that binding (not part of this PR):
```
✓ |unit| packages/lexical-y/src/__tests__/unit/BlockIdY.test.ts (12 tests)
$ BLOCK_ID_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/BlockIdYFuzz.test.ts # 4 shards of 500
Tests 500 passed (500) # ×4: 2000/2000
```
```
$ pnpm run test-unit
Test Files 398 passed | 1 skipped (399)
Tests 9668 passed | 2 skipped (9670)
$ pnpm run tsc # clean
$ pnpm run build-types # clean
$ pnpm run flow # Found 0 errors
$ npx eslint <touched files> && npx prettier --check <touched files> # clean
$ pnpm run build-prod && npx vitest --project integration --no-watch scripts/__tests__/integration/tree-shaking.test.mjs
✓ … a bare import of a published ESM build retains nothing > @lexical/extension/BlockIdExtension (…/LexicalExtensionBlockIdExtension.prod.js)
✓ … a bare import of a published ESM build retains nothing > @lexical/extension/BlockIdExtension (…/LexicalExtensionBlockIdExtension.dev.js)
Test Files 1 passed (1)
Tests 280 passed (280)
```
`scripts/__tests__/unit/treeShakingSource.test.ts` (part of `test-unit`) passes for both new entries. Not exercised: real browsers (no browser or e2e tests were run), and bindings other than `@lexical/yjs` v1/v2 and the `@lexical/y` integration branch.
zurfyx
force-pushed
the
zurfyx/collab-v2-text-run-reuse
branch
from
October 22, 2026 14:14
fda4a3c to
95ed3fc
Compare
zurfyx
marked this pull request as ready for review
October 22, 2026 14:14
zurfyx
requested review from
acywatson,
etrepum,
fantactuka,
ivailop7 and
potatowagon
as code owners
October 22, 2026 14:14
lexical
@lexical/a11y
@lexical/clipboard
@lexical/code
@lexical/code-core
@lexical/code-prism
@lexical/code-shiki
@lexical/compiler
@lexical/devtools-core
@lexical/dragon
@lexical/eslint-plugin
@lexical/extension
@lexical/fast-check
@lexical/file
@lexical/hashtag
@lexical/headless
@lexical/history
@lexical/html
@lexical/internal
@lexical/link
@lexical/list
@lexical/mark
@lexical/markdown
@lexical/mdast
@lexical/offset
@lexical/overflow
@lexical/plain-text
@lexical/react
@lexical/rich-text
@lexical/selection
@lexical/table
@lexical/tailwind
@lexical/text
@lexical/utils
@lexical/yjs
commit: |
potatowagon
approved these changes
Oct 22, 2026
zurfyx
added a commit
that referenced
this pull request
Oct 22, 2026
…al-devtools] Feature: Stable block ids (BlockIdExtension)
## Description
Lexical has no stable way to address a block from outside the editor. Node keys are runtime-only and change on every load, and the position of a block changes with every edit. Code that edits a document by block (an AI agent that reads blocks and answers `replace <id>`, `insert after <id>`, `delete <id>`, or a server pipeline that patches stored JSON) needs an id that survives serialization, reloads and collaboration.
This adds an `@experimental` `BlockIdExtension` to `@lexical/extension`, and an opt-in `BlockIdHTMLExtension` to `@lexical/html`:
- **Storage.** The id is NodeState (`blockIdState`, key `blockId`), serialized as `"$": {"blockId": "…"}`. It survives clones, undo/redo and the Lexical clipboard, and syncs through any binding that syncs NodeState (`@lexical/yjs` v1 and v2 both do). It is declared `resetOnCopyNode`, so `$copyNode` does not copy it. Any non-empty string of at most 128 characters is a valid id, so an app that already stores its own ids under `$.blockId` (UUIDs, for instance) can switch to `blockIdState` without migrating documents.
- **API.** `$getBlockId(node)` and `$getBlockById(id)`. The lookup goes through an index that is updated from the dirty nodes of each commit, and every hit is checked against the active state. Config: `$isIdentifiedBlock` (default `$defaultIsIdentifiedBlock`, the element and decorator children of the root; nested blocks and blocks in slots are opt-in), `generateId` (default `generateBlockId`), and `disabled` (config plus output signal). The per-editor state (index, config) is the extension's init result, so it is not reachable from the output.
- **Id format.** `generateBlockId` makes 21 base64url characters: 126 random bits from `crypto.getRandomValues`, more than the 122 of a version 4 UUID. Ids are generated by every peer and by servers with no coordination, so the size alone must rule out collisions between ids generated concurrently (see Design). There is no `Math.random` fallback: without `crypto.getRandomValues` it throws and the app must configure `generateId`. Readers accept any non-empty string of at most 128 characters; writers always write 21 base64url characters. The format is documented as fixed.
- **Assignment.** Every identified block without an id gets one in the same update that creates it, including blocks created by `importJSON`, HTML import and markdown import. Blocks created by edits get random ids. `setEditorState(parseEditorState(json))` assigns every missing id in that one commit, so a headless server can load, assign and save in a single synchronous write. Updates that skip transforms (remote collaboration changes) are repaired by a discrete follow-up update.
- **Documents stored without ids.** A document loaded without ids, or with some missing, gets **positional ids**: SHA-256 of a key of the document (the SHA-256 of its canonical compact JSON, without ids) and of the block's place (its path among identified blocks), as 21 base64url characters. Every reader and every collaborator that loads the same document derives the same ids, without writing first, and they are stored with the first write. A load is a state set with `setEditorState`, the state present when the extension registers, the first content an editor gets (an initial state, a binding's first sync), and remote blocks that arrive without an id or with a repeated one. Everything else is an edit and gets random ids. A block that the previous state left unnamed takes the id readers derived, so a person's first edit keeps the ids an agent read.
- **Uniqueness.** When several identified blocks share an id, the block that already had it before the update keeps it, and blocks that got it in this update (paste, duplicate, `$copyNode`, JSON or HTML import, an explicit `$setState`) get fresh ids. When several had it before (a duplicate that was committed, such as concurrent edits that meet in a merge), the earliest in document order keeps it. When none had it (several copies created in one local update), the first one created keeps it; in a load, the first in document order. The later holders of a committed or loaded duplicate get **duplicate ids**, SHA-256 of `"dup"`, the repeated id and their ordinal in document order, so every peer repairs it with the same value in time independent of the document's size. The rule is deterministic, idempotent and O(dirty): each holder is compared with its own version in the previous editor state.
- **Slots.** Everything the extension walks visits slot values as well as children: the index rebuild, removals (a removed host takes the blocks of its slots out of the index), the lookup while disabled, and document order (a host's slots, in their canonical order, come before its children, as in `$dfsWithSlots`). Replacing a slot value with `$setSlot` keeps the id, like `replace`.
- **Lineage.** The extension carries ids across splits, joins, type changes and moves (rules below). Core does not carry NodeState across `$setBlocksType`, so the extension detects the replacement from the previous state in the update that makes it. No core behavior changes.
- **HTML.** `BlockIdHTMLExtension` writes `data-block-id` on exported identified blocks and reads it back through `DOMImportExtension`. Imported ids are validated and go through the uniqueness rule. Because it changes export output, the docs warn against adding it to editors whose HTML export must be deterministic (or to use `export: false` there). This is a separate extension in `@lexical/html` because `@lexical/html` already depends on `@lexical/extension`, so the dependency cannot go the other way. Its `export` and `import` config flags can turn off either direction.
- **Docs.** New page `docs/extensions/block-ids.md`, plus entries in the included-extensions list. Flow types are added for both extensions. The page documents the one-line agent `replace_block` (`$getBlockById(id)?.replace(newBlock)`, which keeps the id on every binding), and specifies the positional-id derivation byte for byte.
- **Errors.** A `generateId` that keeps returning invalid or used ids, and a missing `crypto.getRandomValues`, fail through `invariant`, like the rest of the package.
`@lexical/extension` is the home because the feature is editor-level behavior with no node classes and no dependencies beyond `lexical`. That is the same shape as `NormalizeInlineElementsExtension` and `SelectBlockExtension`. A headless server needs only `lexical` and `@lexical/extension`.
Related: #9174 is an example app that implements an application-owned id policy with released APIs (a RootNode transform over `$dfsWithSlots`, 128-bit random ids, fresh ids for every paste). This PR ships the reusable version of that idea; its slot coverage and its random-id size match what that example does, and it does not touch `concepts/node-state.md`, which #9174 edits.
### Design
**Why NodeState.** The id has to mean the same thing in a headless process editing stored JSON, in a solo editor, and between collaborators on any binding. NodeState is the one storage that all of those already carry: JSON, clone, undo, clipboard, and the collaboration bindings. CRDT item identity would tie ids to one binding and one session, and would not exist at all without collaboration.
**Why 126 random bits rather than a peer prefix plus a counter.** A local collision is retried, so only ids generated concurrently by different peers can collide. Outside a collaboration session there is no peer identity to use as a prefix (a server editing stored JSON has none), so a prefix would itself be random and would need about 72 bits to stay unique across every session that ever edits a document. Prefix plus counter would then be 13 to 15 characters instead of 21, saving about 6 characters of JSON per block, and would make ids sequential: an agent that mistypes `…-17` as `…-18` would silently edit another block, where a mistyped random id names no block and the edit fails visibly. With 126 random bits (more than a v4 UUID's 122), a document with a million blocks has less than a 10⁻²⁶ chance of holding two equal ids. `generateId` stays configurable for apps that prefer prefixed ids; prompts that need shorter ids can alias them.
**Why the existing block wins, and how ties are broken.** An agent that holds an id must keep reaching the same block after someone pastes or duplicates it, wherever the copy lands, including above the original. Within one update the editor knows which holder already had the id (it is in the previous state with that id) and which got it now, so the copy always yields. Two tie-breaks cover the cases where that does not single out one block:
- *Several holders were committed together* (concurrent moves that a CRDT merges into two copies). Every peer that sees the duplicate repairs it, so every peer must pick the same survivor. Node keys cannot do this: each peer numbers the nodes it receives in its own order, so with key order each peer keeps its own copy and re-ids the other, and the merged document loses the id altogether (the concurrent-moves collab test fails exactly that way when key order is substituted). Document order is the same for every peer that sees the same document. It costs O(depth) plus a walk over the siblings between the two holders, like `isBefore`, and runs only to repair a committed duplicate.
- *All holders got the id in one local update* (several copies pasted or imported together). Only this editor decides and the others receive the result, so the cheaper creation order (node keys, which only increase) is enough. Fresh ids are also generated in creation order.
Peers that repair the same merged duplicate concurrently keep the same block and give the later holder the same duplicate id, derived from the repeated id and its ordinal, so their writes agree. (Peers that repair different states may differ; the shared document keeps one value, after which there is nothing left to repair.) A repair never creates a duplicate, so it cannot ping-pong. A local copy never reaches the shared document as a duplicate at all, because it is repaired in the update that creates it.
**Why positional ids for documents stored without ids.** Ids assigned at random on load differ on every read: an agent that reads a stored document's ids for a prompt would have to store a no-op write first, and two collaborators who open an unlabelled document at the same time would each write different ids, which the shared document then settles by last-writer-wins. Deriving them from the document makes every read and every peer agree. The key of the document matters: with the place alone, the third block of version 1 ("Intro") and the third block of version 2 ("Budget") would get the same id, and an id read from one version would silently address a different block in the other. The key is the SHA-256 of the canonical compact JSON with ids left out, so naming the blocks does not change it, and the compact form omits properties restored from schema defaults, which keeps it stable as nodes gain properties. Blocks created later must stay random: content-derived ids would collide on every empty paragraph.
The positional ids have the same 21-character base64url format as random ones, rather than a marker prefix such as `~`. A prefix outside `[A-Za-z0-9_-]` fails the id validators apps commonly use for ids that also go into HTML attributes and URLs, and once stored, a positional id is an ordinary id: nothing should treat it differently. A hash collision with an id in use is retried with `#n` appended to the place, in document order, so retries are deterministic too.
Repeated ids are renamed differently: the k-th later holder (in document order) gets the first 21 base64url characters of SHA-256(`"dup"` U+0000 id U+0000 k). This depends only on the repeated id and the ordinal, so repairing a duplicate that a merge produced costs O(holders), not a pass over the document, and is still the same on every peer that sees the same document. Readers of a stored document with repeated ids use the same rule, so a reader and an editor agree there too.
Collaboration-tagged updates are never relabelled in the update that applies them (the bindings would not write such changes back); the follow-up repair writes the names that every peer derives, so peers that repair concurrently write the same values.
| Edit | Id result |
| --- | --- |
| Enter in the middle or at the end of a block | Block keeps its id; the new block gets a fresh one |
| Enter at the start of a block | The text moves into the new block below, and the id moves with it; the emptied block above gets a fresh id |
| Backspace join | The surviving block keeps its id |
| Paragraph to heading, quote or list (`$setBlocksType`, `INSERT_*_LIST_COMMAND`) and back | The replacement keeps the id |
| `replace(newNode)` with a node that has no id, or `$setSlot` replacing a slot value | The new node keeps the id |
| Move (drag and drop, `insertAfter`/`insertBefore`) | The id moves with the block |
| Paste, duplicate, JSON or HTML import of copied content | Copy keeps the id only if no other block has it; otherwise the original keeps it, even when the copy is placed above |
| Several copies created in one update, none pre-existing | The first one created keeps the id |
| Cut and paste | The pasted block keeps the id (nothing else has it any more) |
| Copies that only meet in a collaborative merge, or repeated ids in a loaded document | The earliest in document order keeps the id; the k-th later one gets the id derived from the repeated id and k |
| A document loaded without ids (or with missing ones) | Positional ids, the same for every reader and peer |
| `$copyNode` | The copy has no id and gets a fresh one |
| Undo/redo | Exact ids restored |
`insertNewAfter` behavior that was checked: `ParagraphNode`, `HeadingNode` and `QuoteNode` create a new node without NodeState. `QuoteNode` creates a paragraph, so Enter at the start of a quote leaves an empty quote above and moves the text into a paragraph that keeps the id. `HeadingNode` at the start replaces itself with a paragraph (`replace(…, true)`) and moves the text into a new heading, which takes the id. `ListItemNode` uses `$copyNode`, which leaves the id behind.
### How agents use this
```ts
// What the agent reads.
const blocks = editor.read(() =>
$getRoot().getChildren().map(node => ({id: $getBlockId(node), text: node.getTextContent()})),
);
// What it answers: [{op: 'replace', id: '…', text: '…'}, {op: 'delete', id: '…'}]
editor.update(() => {
for (const op of ops) {
const block = $getBlockById(op.id);
if (block === null) continue; // gone meanwhile, or a mistyped id
if (op.op === 'delete') block.remove();
else block.replace($createParagraphNode().append($createTextNode(op.text))); // keeps the id
}
}, {discrete: true});
```
### Performance
On a 10,000-block document (headless). The harness runs an editor with the extension and one without it through the same operations, interleaved round by round, so that process drift affects both alike (`BLOCK_ID_PERF=1 npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts`):
```
10000 blocks, median, interleaved without with delta
keystroke (300) 15.284 ms 16.341 ms 1.058 ms
Enter (300) 15.614 ms 18.385 ms 2.771 ms
paste 20 blocks (50) 18.459 ms 21.473 ms 3.015 ms
paste 50 blocks (50) 21.951 ms 26.179 ms 4.227 ms
remote duplicate (50) 27.900 ms 64.842 ms 36.942 ms
first load, no ids (12) 120.936 ms 298.521 ms 177.585 ms
of which document key: 64.103 ms
load, ids stored (12) 136.034 ms 168.679 ms 32.646 ms
```
These numbers come from a shared machine under load. Across runs the keystroke delta moved between 0.5 and 1.4 ms, and a probe that interleaved five editors (none, a no-op root transform, no-op transforms on every node class, a no-op update listener, and the extension) measured the editor with the extension as the fastest of the five, so the keystroke delta is within noise: typing creates no block, and the extension does nothing for it beyond an O(dirty) index check. The Enter delta moved between 2.0 and 3.1 ms. Instrumentation put the extension's own work at about 0.1 ms per Enter; most of the Enter delta is Lexical running the root transforms a second time, including the O(root children) shadow-root normalization, because a transform changed a node. A ten-line extension that only sets a NodeState on new paragraphs in a transform measured +1.04 ms in the same harness.
Positional ids cost one pass over the document, and only when blocks without an id appear:
- **First load without ids**: +178 ms for 10,000 blocks, of which about 55 to 65 ms is the document key (compact export, canonical JSON and SHA-256 of about 850 KB), about 20 ms is deriving 10,000 ids (one SHA-256 block each), and the rest is assigning and indexing 10,000 ids, which random ids cost as well.
- **A document stored with its ids** does not compute the key: +33 ms (indexing).
- **A remote duplicate** is repaired with duplicate ids, which do not hash the document: +37 ms on 10,000 blocks, almost all of it the repair commit itself; ordering the holders and deriving the id take well under a millisecond. A remote block without an id (only from clients without the extension) still gets a positional id, so that repair hashes the document once.
## Test plan
New tests:
- `packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts` (headless, 63 tests): assignment in the creating commit; importJSON; markdown; documents opened without ids; foreign states; the headless recipe; invalid stored ids; generator collisions; the default id format (21 characters, all 64 symbols used); duplicates in JSON; determinism and idempotence (with the random default generator); duplicates after the original and above it (the original keeps the id); duplicating a block upward; several copies in one update (the first created keeps it); a committed duplicate repaired the same way whichever order its nodes were created in; `$copyNode`; explicit clashing ids; `$copyNode` right after a JSON load (before anything has read the state); copy/paste within and between editors; pasting a copy above the original; cut and paste, in two updates and in one; undo/redo of a paste; Enter at the start, middle and end of paragraph, heading, quote and list item (nested); Backspace and forward-delete joins; `$setBlocksType` single, multi and empty blocks, and back; paragraph to list; moves; manual replace; undo/redo of every step with the index checked; `$getBlockById`; O(dirty) predicate calls on a 1,000-block document; list and table nesting; disabled/enabled; repair after updates without transforms and after collaboration-tagged updates. Documents stored without ids: two reads agree; two documents (or versions) share no id; stored ids kept, missing ones positional, a taken positional id retried; blocks created later are random; initial state functions and the default paragraph are loads; `setEditorState` is a load and updates are edits; a foreign state gets the ids its JSON gets; a person's first edits keep the ids a reader read; nested paths; one commit and idempotent. The tests that exercise edits start from an editor that has had content, so that their first blocks are edits.
- `BlockIdExtension.format.test.ts` (9 tests): the frozen format. SHA-256 against Node's crypto on every padding boundary; UTF-8 against Node's encoder, lone surrogates included; canonical JSON key order; the hashed document is the compact export without ids; positional ids and duplicate ids against an independent implementation of the specification with Node's crypto, and pinned to literal values; a loaded document with repeated ids renamed by ordinal; 20,000 positional ids well formed, using all 64 symbols, none repeated; `generateBlockId` throws without `crypto.getRandomValues`.
- `BlockIdExtension.slots.test.ts` (10 tests): blocks inside a slot container and a block that is itself a slot value get ids in the creating commit; a duplicate pasted into a slot yields; committed duplicates between a slot and its host's children, and between two slots, are repaired in document order whichever order the nodes were created in; `$setSlot` replacement keeps the id; `$setBlocksType` inside a slot; the index after undo and after `setEditorState`; removing a host frees the ids of its slots; the lookup while disabled.
- `BlockIdExtension.dom.test.ts` (jsdom, mounted editor): typing, Enter and Backspace; Backspace at the start of the first heading; clipboard paste between editors and within one; legacy HTML paste; undo.
- `packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts` (7 tests): off by default; export on identified blocks only; nested export; HTML round trip (exported to a DOM document and imported from it); imported ids through the uniqueness rule (duplicates, clashes, empty, too long); `export: false`/`import: false`; two readers of the same id-less HTML export the same `data-block-id`s. Fixtures are fixed strings parsed with `DOMParser`, or built with `createElement`/`setAttribute`.
- `packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts`: a headless harness wiring v1 and v2 bindings the way the React plugins do. It runs 13 tests per binding: ids assigned once by the creator; a late joiner writes nothing; concurrent Enter; concurrent duplicates on three peers, one pasted above the original; concurrent moves that duplicate a block after merge (all peers repair with the same duplicate id); a document written without ids opened concurrently by two peers (both derive the ids a headless reader derives, and the merge needs no repair); type change and move; type change concurrent with typing; Yjs undo/redo of a split; join concurrent with Enter; nested list ids; two peers that load an id-less document concurrently and each edit it converge on its positional ids, with no repair after the merge, and the ids read headlessly before still name the same content; two clients that put the same first content into empty editors name it alike. Every test checks convergence, unique ids and quiescence: a further round produces no Yjs update.
- `BlockIdCollabFuzz.test.ts`: deterministic randomized runs with 2 or 3 peers mixing typing, Enter, join, duplicate, block type changes, moves, Yjs undo/redo and partitions. Even seeds start from a document written without ids that every peer opens at the same time; they must name it as a headless reader does and need no repair when they meet. They assert convergence, every block having an id, unique ids, quiescence, and that blocks never split, merged, copied or concurrently restructured keep their ids. CI runs 8 seeds per binding; `BLOCK_ID_FUZZ_SEEDS` runs more.
- `BlockIdExtension.perf.test.ts`: the measurement above; skipped unless `BLOCK_ID_PERF=1`.
### Before
On `main` with the new test files copied in, every block id test fails (the extension does not exist):
```
$ npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension*.test.ts packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts packages/lexical-yjs/src/__tests__/unit/BlockIdCollab*.test.ts
FAIL |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts [ packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts ]
Error: Cannot find module '../../internal/positionalBlockId' imported from …
FAIL |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts > BlockIdExtension (DOM) > typing, Enter and Backspace in a mounted editor
TypeError: Cannot read properties of undefined (reading 'name')
...
Test Files 7 failed (7)
Tests 54 failed (54)
```
With random ids on load (the previous revision of this PR), the tests for documents stored without ids fail:
```
$ npx vitest --project unit --no-watch <BlockIdExtension, format, HTML and collab test files> -t 'stored without ids|written without ids|positional|no weaker fallback|pinned|first content|wholesale'
FAIL …BlockIdExtension.format.test.ts > block id format > positional ids follow the specification and are pinned
FAIL …BlockIdExtension.format.test.ts > block id format > generated ids need crypto.getRandomValues: there is no weaker fallback
FAIL …BlockIdExtension.test.ts > BlockIdExtension: documents stored without ids > two reads name the blocks the same way, by place, without a write
AssertionError: expected [ 'uO3D8h6oIeGZP9MgBu_qy', …(2) ] to deeply equal [ 'K9jfDU0m4JHycoFSzhV4R', …(2) ]
FAIL …BlockIdExtension.test.ts > BlockIdExtension: documents stored without ids > a person's first edits keep the ids a reader read
FAIL …BlockIdExtension.test.ts > BlockIdExtension: documents stored without ids > the first content of an empty editor is a load: initial state functions and the default paragraph
FAIL …BlockIdHTMLExtension.test.ts > BlockIdHTMLExtension: documents read without ids > every reader exports the same data-block-id for a document stored without ids
FAIL …BlockIdCollab.test.ts > BlockIdExtension with @lexical/yjs v1 > a document written without ids is repaired by peers concurrently and converges
AssertionError: expected [ 'a2', 'a3', 'a4' ] to deeply equal [ 'yi2nlmalRX7d7ppIqz_i6', …(2) ]
FAIL …BlockIdCollab.test.ts > BlockIdExtension with @lexical/yjs v1 > peers that load a document stored without ids at the same time and edit it converge on its positional ids
FAIL …BlockIdCollab.test.ts > BlockIdExtension with @lexical/yjs v2 > clients that put the same first content into empty editors name it alike
...
Tests 18 failed | 4 passed | 83 skipped (105)
```
### After
```
$ npx vitest --project unit --no-watch <the same files> -t '<the same pattern>'
Tests 22 passed | 83 skipped (105)
$ npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension*.test.ts packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts packages/lexical-yjs/src/__tests__/unit/BlockIdCollab*.test.ts
✓ |unit| packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts (7 tests) 111ms
✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts (5 tests) 178ms
↓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts (1 test | 1 skipped)
✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.slots.test.ts (10 tests) 70ms
✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts (26 tests) 287ms
✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts (16 tests) 524ms
✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.format.test.ts (9 tests) 697ms
✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts (63 tests) 432ms
Test Files 7 passed | 1 skipped (8)
Tests 136 passed | 1 skipped (137)
$ BLOCK_ID_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts # run as 4 shards of 500 seeds
FAIL |unit| …BlockIdCollabFuzz.test.ts > BlockIdExtension fuzz, @lexical/yjs v2 > seed 198
# likewise v2 seeds 462, 811, 938, 1086, 1157, 1918
Tests 7 failed | 3993 passed (4000)
```
All 2,000 seeds pass on v1, half of them starting from a document stored without ids. The 7 v2 failures are pre-existing problems in the v2 binding, not in block ids, and are the same seeds that failed before this change:
- In 6 of them, the v2 binding moved text from one block element into another under concurrent moves, joins and undo. For example, seed 938 ends with a block whose text is `M4 tex zM2 textM1 zt`, and seed 1918 splits the `M1` text across two elements. NodeState stays with the element, so the id follows the element rather than the text.
- In the other one (seed 198), the peers' texts diverge.
The same harness with the extension removed (`BLOCK_ID_FUZZ_CONTROL=1`, which checks convergence only) gives `Tests 10 failed | 3990 passed (4000)`: v2 seeds 198, 479, 612, 717, 1017, 1250, 1354, 1506, 1748 and 1873 diverge, and every v1 seed passes. Both results are unchanged with #9381 and #9377 (the open v2 attribute and text-run fixes) merged in.
The same suite and 2,000-seed fuzz were also run against `@lexical/y` (#9400) on a local integration branch that adds this commit and ports the two test files to that binding (not part of this PR). There, two clients that initialize the same empty room with the same content, the default empty paragraph included, write it once: the binding's deduplication of deterministic initial content now works with the extension on.
```
✓ |unit| packages/lexical-y/src/__tests__/unit/BlockIdY.test.ts (14 tests)
✓ |unit| packages/lexical-y/src/__tests__/unit/BlockIdYFuzz.test.ts (8 tests)
$ npx vitest --project unit --no-watch packages/lexical-y <and the block id test files>
Test Files 56 passed | 1 skipped (57)
Tests 1091 passed | 1 skipped (1092)
$ BLOCK_ID_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/BlockIdYFuzz.test.ts # 4 shards of 500
Tests 500 passed (500) # ×4: 2000/2000
```
```
$ pnpm run test-unit
Test Files 399 passed | 1 skipped (400)
Tests 9693 passed | 2 skipped (9695)
```
`pnpm run tsc`, `pnpm run flow`, ESLint and Prettier on the touched files are clean, and the tree-shaking tests pass on the sources (in `test-unit`) and on the published build (`scripts/__tests__/integration/tree-shaking.test.mjs` after `pnpm run build-prod`). Not exercised: real browsers.
zurfyx
added a commit
that referenced
this pull request
Oct 23, 2026
…al-devtools] Feature: Stable block ids (BlockIdExtension)
## Description
Lexical has no stable way to address a block from outside the editor. Node keys are runtime-only and change on every load, and the position of a block changes with every edit. Code that edits a document by block (an AI agent that reads blocks and answers `replace <id>`, `insert after <id>`, `delete <id>`, or a server pipeline that patches stored JSON) needs an id that survives serialization, reloads and collaboration.
This adds an `@experimental` `BlockIdExtension` to `@lexical/extension`, and an opt-in `BlockIdHTMLExtension` to `@lexical/html`:
- **Storage.** The id is NodeState (`blockIdState`, key `blockId`), serialized as `"$": {"blockId": "…"}`. It survives clones, undo/redo and the Lexical clipboard, and syncs through any binding that syncs NodeState (`@lexical/yjs` v1 and v2 both do). It is declared `resetOnCopyNode`, so `$copyNode` does not copy it. Any non-empty string of at most 128 characters is a valid id, so an app that already stores its own ids under `$.blockId` (UUIDs, for instance) can switch to `blockIdState` without migrating documents.
- **API.** `$getBlockId(node)` and `$getBlockById(id)`. The lookup goes through an index that is updated from the dirty nodes of each commit, and every hit is checked against the active state. Config: `$isIdentifiedBlock` (default `$defaultIsIdentifiedBlock`, the element and decorator children of the root; nested blocks and blocks in slots are opt-in), `generateId` (default `generateBlockId`), and `disabled` (config plus output signal). The per-editor state (index, config) is the extension's init result, so it is not reachable from the output.
- **Id format.** `generateBlockId` makes 21 base64url characters: 126 random bits from `crypto.getRandomValues`, more than the 122 of a version 4 UUID. Ids are generated by every peer and by servers with no coordination, so the size alone must rule out collisions between ids generated concurrently (see Design). There is no `Math.random` fallback: without `crypto.getRandomValues` it throws and the app must configure `generateId`. Readers accept any non-empty string of at most 128 characters; writers always write 21 base64url characters. The format is documented as fixed.
- **Assignment.** Every identified block without an id gets one in the same update that creates it, including blocks created by `importJSON`, HTML import and markdown import. Blocks created by edits get random ids. `setEditorState(parseEditorState(json))` assigns every missing id in that one commit, so a headless server can load, assign and save in a single synchronous write. Updates that skip transforms (remote collaboration changes) are repaired by a discrete follow-up update.
- **Documents stored without ids.** A document loaded without ids, or with some missing, gets **positional ids**: SHA-256 of a key of the document (the SHA-256 of its canonical compact JSON, without ids) and of the block's place (its path among identified blocks), as 21 base64url characters. Every reader and every collaborator that loads the same document derives the same ids, without writing first, and they are stored with the first write. A load is a state set with `setEditorState`, the state present when the extension registers, the first content an editor gets (an initial state, a binding's first sync), and remote blocks that arrive without an id or with a repeated one. Everything else is an edit and gets random ids. A block that the previous state left unnamed takes the id readers derived, so a person's first edit keeps the ids an agent read.
- **Uniqueness.** When several identified blocks share an id, the block that already had it before the update keeps it, and blocks that got it in this update (paste, duplicate, `$copyNode`, JSON or HTML import, an explicit `$setState`) get fresh ids. When several had it before (a duplicate that was committed, such as concurrent edits that meet in a merge), the earliest in document order keeps it. When none had it (several copies created in one local update), the first one created keeps it; in a load, the first in document order. The later holders of a committed or loaded duplicate get **duplicate ids**, SHA-256 of `"dup"`, the repeated id and their ordinal in document order, so every peer repairs it with the same value in time independent of the document's size. The rule is deterministic, idempotent and O(dirty): each holder is compared with its own version in the previous editor state.
- **Slots.** Everything the extension walks visits slot values as well as children: the index rebuild, removals (a removed host takes the blocks of its slots out of the index), the lookup while disabled, and document order (a host's slots, in their canonical order, come before its children, as in `$dfsWithSlots`). Replacing a slot value with `$setSlot` keeps the id, like `replace`.
- **Lineage.** The extension carries ids across splits, joins, type changes and moves (rules below). Core does not carry NodeState across `$setBlocksType`, so the extension detects the replacement from the previous state in the update that makes it. No core behavior changes.
- **HTML.** `BlockIdHTMLExtension` writes `data-block-id` on exported identified blocks and reads it back through `DOMImportExtension`. Imported ids are validated and go through the uniqueness rule. Because it changes export output, the docs warn against adding it to editors whose HTML export must be deterministic (or to use `export: false` there). This is a separate extension in `@lexical/html` because `@lexical/html` already depends on `@lexical/extension`, so the dependency cannot go the other way. Its `export` and `import` config flags can turn off either direction.
- **Docs.** New page Extensions > Block IDs: setup, addressing blocks and the agent recipe (the one-line `replace_block`, `$getBlockById(id)?.replace(newBlock)`, which keeps the id on every binding), which blocks get ids, how ids follow edits, uniqueness, documents stored without ids, HTML, collaboration, configuration, and the id format with the positional-id derivation byte for byte. Plus entries in the included-extensions list. Flow types are added for both extensions. Binding specifics stay out of the page: whether a collaborator's concurrent typing survives a `replace` depends on the binding (`@lexical/y`, #9400, keeps it), and `@lexical/y` writes identical initial content once, so two clients that put the same first content into empty editors agree on its ids.
- **Errors.** A `generateId` that keeps returning invalid or used ids, and a missing `crypto.getRandomValues`, fail through `invariant`, like the rest of the package.
`@lexical/extension` is the home because the feature is editor-level behavior with no node classes and no dependencies beyond `lexical`. That is the same shape as `NormalizeInlineElementsExtension` and `SelectBlockExtension`. A headless server needs only `lexical` and `@lexical/extension`.
Related: #9174 is an example app that implements an application-owned id policy with released APIs (a RootNode transform over `$dfsWithSlots`, 128-bit random ids, fresh ids for every paste). This PR ships the reusable version of that idea; its slot coverage and its random-id size match what that example does, and it does not touch `concepts/node-state.md`, which #9174 edits.
### Design
**Why NodeState.** The id has to mean the same thing in a headless process editing stored JSON, in a solo editor, and between collaborators on any binding. NodeState is the one storage that all of those already carry: JSON, clone, undo, clipboard, and the collaboration bindings. CRDT item identity would tie ids to one binding and one session, and would not exist at all without collaboration.
**Why 126 random bits rather than a peer prefix plus a counter.** A local collision is retried, so only ids generated concurrently by different peers can collide. Outside a collaboration session there is no peer identity to use as a prefix (a server editing stored JSON has none), so a prefix would itself be random and would need about 72 bits to stay unique across every session that ever edits a document. Prefix plus counter would then be 13 to 15 characters instead of 21, saving about 6 characters of JSON per block, and would make ids sequential: an agent that mistypes `…-17` as `…-18` would silently edit another block, where a mistyped random id names no block and the edit fails visibly. With 126 random bits (more than a v4 UUID's 122), a document with a million blocks has less than a 10⁻²⁶ chance of holding two equal ids. `generateId` stays configurable for apps that prefer prefixed ids; prompts that need shorter ids can alias them.
**Why the existing block wins, and how ties are broken.** An agent that holds an id must keep reaching the same block after someone pastes or duplicates it, wherever the copy lands, including above the original. Within one update the editor knows which holder already had the id (it is in the previous state with that id) and which got it now, so the copy always yields. Two tie-breaks cover the cases where that does not single out one block:
- *Several holders were committed together* (concurrent moves that a CRDT merges into two copies). Every peer that sees the duplicate repairs it, so every peer must pick the same survivor. Node keys cannot do this: each peer numbers the nodes it receives in its own order, so with key order each peer keeps its own copy and re-ids the other, and the merged document loses the id altogether (the concurrent-moves collab test fails exactly that way when key order is substituted). Document order is the same for every peer that sees the same document. It costs O(depth) plus a walk over the siblings between the two holders, like `isBefore`, and runs only to repair a committed duplicate.
- *All holders got the id in one local update* (several copies pasted or imported together). Only this editor decides and the others receive the result, so the cheaper creation order (node keys, which only increase) is enough. Fresh ids are also generated in creation order.
Peers that repair the same merged duplicate concurrently keep the same block and give the later holder the same duplicate id, derived from the repeated id and its ordinal, so their writes agree. (Peers that repair different states may differ; the shared document keeps one value, after which there is nothing left to repair.) A repair never creates a duplicate, so it cannot ping-pong. A local copy never reaches the shared document as a duplicate at all, because it is repaired in the update that creates it.
**Why positional ids for documents stored without ids.** Ids assigned at random on load differ on every read: an agent that reads a stored document's ids for a prompt would have to store a no-op write first, and two collaborators who open an unlabelled document at the same time would each write different ids, which the shared document then settles by last-writer-wins. Deriving them from the document makes every read and every peer agree. The key of the document matters: with the place alone, the third block of version 1 ("Intro") and the third block of version 2 ("Budget") would get the same id, and an id read from one version would silently address a different block in the other. The key is the SHA-256 of the canonical compact JSON with ids left out, so naming the blocks does not change it, and the compact form omits properties restored from schema defaults, which keeps it stable as nodes gain properties. Blocks created later must stay random: content-derived ids would collide on every empty paragraph.
The positional ids have the same 21-character base64url format as random ones, rather than a marker prefix such as `~`. A prefix outside `[A-Za-z0-9_-]` fails the id validators apps commonly use for ids that also go into HTML attributes and URLs, and once stored, a positional id is an ordinary id: nothing should treat it differently. A hash collision with an id in use is retried with `#n` appended to the place, in document order, so retries are deterministic too.
Repeated ids are renamed differently: the k-th later holder (in document order) gets the first 21 base64url characters of SHA-256(`"dup"` U+0000 id U+0000 k). This depends only on the repeated id and the ordinal, so repairing a duplicate that a merge produced costs O(holders), not a pass over the document, and is still the same on every peer that sees the same document. Readers of a stored document with repeated ids use the same rule, so a reader and an editor agree there too.
Collaboration-tagged updates are never relabelled in the update that applies them (the bindings would not write such changes back); the follow-up repair writes the names that every peer derives, so peers that repair concurrently write the same values.
| Edit | Id result |
| --- | --- |
| Enter in the middle or at the end of a block | Block keeps its id; the new block gets a fresh one |
| Enter at the start of a block | The text moves into the new block below, and the id moves with it; the emptied block above gets a fresh id |
| Backspace join | The surviving block keeps its id |
| Paragraph to heading, quote or list (`$setBlocksType`, `INSERT_*_LIST_COMMAND`) and back | The replacement keeps the id |
| `replace(newNode)` with a node that has no id, or `$setSlot` replacing a slot value | The new node keeps the id |
| Move (drag and drop, `insertAfter`/`insertBefore`) | The id moves with the block |
| Paste, duplicate, JSON or HTML import of copied content | Copy keeps the id only if no other block has it; otherwise the original keeps it, even when the copy is placed above |
| Several copies created in one update, none pre-existing | The first one created keeps the id |
| Cut and paste | The pasted block keeps the id (nothing else has it any more) |
| Copies that only meet in a collaborative merge, or repeated ids in a loaded document | The earliest in document order keeps the id; the k-th later one gets the id derived from the repeated id and k |
| A document loaded without ids (or with missing ones) | Positional ids, the same for every reader and peer |
| `$copyNode` | The copy has no id and gets a fresh one |
| Undo/redo | Exact ids restored |
`insertNewAfter` behavior that was checked: `ParagraphNode`, `HeadingNode` and `QuoteNode` create a new node without NodeState. `QuoteNode` creates a paragraph, so Enter at the start of a quote leaves an empty quote above and moves the text into a paragraph that keeps the id. `HeadingNode` at the start replaces itself with a paragraph (`replace(…, true)`) and moves the text into a new heading, which takes the id. `ListItemNode` uses `$copyNode`, which leaves the id behind.
### How agents use this
```ts
// What the agent reads.
const blocks = editor.read(() =>
$getRoot().getChildren().map(node => ({id: $getBlockId(node), text: node.getTextContent()})),
);
// What it answers: [{op: 'replace', id: '…', text: '…'}, {op: 'delete', id: '…'}]
editor.update(() => {
for (const op of ops) {
const block = $getBlockById(op.id);
if (block === null) continue; // gone meanwhile, or a mistyped id
if (op.op === 'delete') block.remove();
else block.replace($createParagraphNode().append($createTextNode(op.text))); // keeps the id
}
}, {discrete: true});
```
### Performance
On a 10,000-block document (headless). The harness runs an editor with the extension and one without it through the same operations, interleaved round by round, so that process drift affects both alike (`BLOCK_ID_PERF=1 npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts`):
```
10000 blocks, median, interleaved without with delta
keystroke (300) 15.284 ms 16.341 ms 1.058 ms
Enter (300) 15.614 ms 18.385 ms 2.771 ms
paste 20 blocks (50) 18.459 ms 21.473 ms 3.015 ms
paste 50 blocks (50) 21.951 ms 26.179 ms 4.227 ms
remote duplicate (50) 27.900 ms 64.842 ms 36.942 ms
first load, no ids (12) 120.936 ms 298.521 ms 177.585 ms
of which document key: 64.103 ms
load, ids stored (12) 136.034 ms 168.679 ms 32.646 ms
```
These numbers come from a shared machine under load. Across runs the keystroke delta moved between 0.5 and 1.4 ms, and a probe that interleaved five editors (none, a no-op root transform, no-op transforms on every node class, a no-op update listener, and the extension) measured the editor with the extension as the fastest of the five, so the keystroke delta is within noise: typing creates no block, and the extension does nothing for it beyond an O(dirty) index check. The Enter delta moved between 2.0 and 3.1 ms. Instrumentation put the extension's own work at about 0.1 ms per Enter; most of the Enter delta is Lexical running the root transforms a second time, including the O(root children) shadow-root normalization, because a transform changed a node. A ten-line extension that only sets a NodeState on new paragraphs in a transform measured +1.04 ms in the same harness.
Positional ids cost one pass over the document, and only when blocks without an id appear:
- **First load without ids**: +178 ms for 10,000 blocks, of which about 55 to 65 ms is the document key (compact export, canonical JSON and SHA-256 of about 850 KB), about 20 ms is deriving 10,000 ids (one SHA-256 block each), and the rest is assigning and indexing 10,000 ids, which random ids cost as well.
- **A document stored with its ids** does not compute the key: +33 ms (indexing).
- **A remote duplicate** is repaired with duplicate ids, which do not hash the document: +37 ms on 10,000 blocks, almost all of it the repair commit itself; ordering the holders and deriving the id take well under a millisecond. A remote block without an id (only from clients without the extension) still gets a positional id, so that repair hashes the document once.
## Test plan
New tests:
- `packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts` (headless, 63 tests): assignment in the creating commit; importJSON; markdown; documents opened without ids; foreign states; the headless recipe; invalid stored ids; generator collisions; the default id format (21 characters, all 64 symbols used); duplicates in JSON; determinism and idempotence (with the random default generator); duplicates after the original and above it (the original keeps the id); duplicating a block upward; several copies in one update (the first created keeps it); a committed duplicate repaired the same way whichever order its nodes were created in; `$copyNode`; explicit clashing ids; `$copyNode` right after a JSON load (before anything has read the state); copy/paste within and between editors; pasting a copy above the original; cut and paste, in two updates and in one; undo/redo of a paste; Enter at the start, middle and end of paragraph, heading, quote and list item (nested); Backspace and forward-delete joins; `$setBlocksType` single, multi and empty blocks, and back; paragraph to list; moves; manual replace; undo/redo of every step with the index checked; `$getBlockById`; O(dirty) predicate calls on a 1,000-block document; list and table nesting; disabled/enabled; repair after updates without transforms and after collaboration-tagged updates. Documents stored without ids: two reads agree; two documents (or versions) share no id; stored ids kept, missing ones positional, a taken positional id retried; blocks created later are random; initial state functions and the default paragraph are loads; `setEditorState` is a load and updates are edits; a foreign state gets the ids its JSON gets; a person's first edits keep the ids a reader read; nested paths; one commit and idempotent. The tests that exercise edits start from an editor that has had content, so that their first blocks are edits.
- `BlockIdExtension.format.test.ts` (9 tests): the frozen format. SHA-256 against Node's crypto on every padding boundary; UTF-8 against Node's encoder, lone surrogates included; canonical JSON key order; the hashed document is the compact export without ids; positional ids and duplicate ids against an independent implementation of the specification with Node's crypto, and pinned to literal values; a loaded document with repeated ids renamed by ordinal; 20,000 positional ids well formed, using all 64 symbols, none repeated; `generateBlockId` throws without `crypto.getRandomValues`.
- `BlockIdExtension.slots.test.ts` (10 tests): blocks inside a slot container and a block that is itself a slot value get ids in the creating commit; a duplicate pasted into a slot yields; committed duplicates between a slot and its host's children, and between two slots, are repaired in document order whichever order the nodes were created in; `$setSlot` replacement keeps the id; `$setBlocksType` inside a slot; the index after undo and after `setEditorState`; removing a host frees the ids of its slots; the lookup while disabled.
- `BlockIdExtension.dom.test.ts` (jsdom, mounted editor): typing, Enter and Backspace; Backspace at the start of the first heading; clipboard paste between editors and within one; legacy HTML paste; undo.
- `packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts` (7 tests): off by default; export on identified blocks only; nested export; HTML round trip (exported to a DOM document and imported from it); imported ids through the uniqueness rule (duplicates, clashes, empty, too long); `export: false`/`import: false`; two readers of the same id-less HTML export the same `data-block-id`s. Fixtures are fixed strings parsed with `DOMParser`, or built with `createElement`/`setAttribute`.
- `packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts`: a headless harness wiring v1 and v2 bindings the way the React plugins do. It runs 13 tests per binding: ids assigned once by the creator; a late joiner writes nothing; concurrent Enter; concurrent duplicates on three peers, one pasted above the original; concurrent moves that duplicate a block after merge (all peers repair with the same duplicate id); a document written without ids opened concurrently by two peers (both derive the ids a headless reader derives, and the merge needs no repair); type change and move; type change concurrent with typing; Yjs undo/redo of a split; join concurrent with Enter; nested list ids; two peers that load an id-less document concurrently and each edit it converge on its positional ids, with no repair after the merge, and the ids read headlessly before still name the same content; two clients that put the same first content into empty editors name it alike. Every test checks convergence, unique ids and quiescence: a further round produces no Yjs update.
- `BlockIdCollabFuzz.test.ts`: deterministic randomized runs with 2 or 3 peers mixing typing, Enter, join, duplicate, block type changes, moves, Yjs undo/redo and partitions. Even seeds start from a document written without ids that every peer opens at the same time; they must name it as a headless reader does and need no repair when they meet. They assert convergence, every block having an id, unique ids, quiescence, and that blocks never split, merged, copied or concurrently restructured keep their ids. CI runs 8 seeds per binding; `BLOCK_ID_FUZZ_SEEDS` runs more.
- `BlockIdExtension.perf.test.ts`: the measurement above; skipped unless `BLOCK_ID_PERF=1`.
### Before
On `main` with the new test files copied in, every block id test fails (the extension does not exist):
```
$ npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension*.test.ts packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts packages/lexical-yjs/src/__tests__/unit/BlockIdCollab*.test.ts
FAIL |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts [ packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts ]
Error: Cannot find module '../../internal/positionalBlockId' imported from …
FAIL |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts > BlockIdExtension (DOM) > typing, Enter and Backspace in a mounted editor
TypeError: Cannot read properties of undefined (reading 'name')
...
Test Files 7 failed (7)
Tests 54 failed (54)
```
With random ids on load (the previous revision of this PR), the tests for documents stored without ids fail:
```
$ npx vitest --project unit --no-watch <BlockIdExtension, format, HTML and collab test files> -t 'stored without ids|written without ids|positional|no weaker fallback|pinned|first content|wholesale'
FAIL …BlockIdExtension.format.test.ts > block id format > positional ids follow the specification and are pinned
FAIL …BlockIdExtension.format.test.ts > block id format > generated ids need crypto.getRandomValues: there is no weaker fallback
FAIL …BlockIdExtension.test.ts > BlockIdExtension: documents stored without ids > two reads name the blocks the same way, by place, without a write
AssertionError: expected [ 'uO3D8h6oIeGZP9MgBu_qy', …(2) ] to deeply equal [ 'K9jfDU0m4JHycoFSzhV4R', …(2) ]
FAIL …BlockIdExtension.test.ts > BlockIdExtension: documents stored without ids > a person's first edits keep the ids a reader read
FAIL …BlockIdExtension.test.ts > BlockIdExtension: documents stored without ids > the first content of an empty editor is a load: initial state functions and the default paragraph
FAIL …BlockIdHTMLExtension.test.ts > BlockIdHTMLExtension: documents read without ids > every reader exports the same data-block-id for a document stored without ids
FAIL …BlockIdCollab.test.ts > BlockIdExtension with @lexical/yjs v1 > a document written without ids is repaired by peers concurrently and converges
AssertionError: expected [ 'a2', 'a3', 'a4' ] to deeply equal [ 'yi2nlmalRX7d7ppIqz_i6', …(2) ]
FAIL …BlockIdCollab.test.ts > BlockIdExtension with @lexical/yjs v1 > peers that load a document stored without ids at the same time and edit it converge on its positional ids
FAIL …BlockIdCollab.test.ts > BlockIdExtension with @lexical/yjs v2 > clients that put the same first content into empty editors name it alike
...
Tests 18 failed | 4 passed | 83 skipped (105)
```
### After
```
$ npx vitest --project unit --no-watch <the same files> -t '<the same pattern>'
Tests 22 passed | 83 skipped (105)
$ npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension*.test.ts packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts packages/lexical-yjs/src/__tests__/unit/BlockIdCollab*.test.ts
✓ |unit| packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts (7 tests) 111ms
✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts (5 tests) 178ms
↓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts (1 test | 1 skipped)
✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.slots.test.ts (10 tests) 70ms
✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts (26 tests) 287ms
✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts (16 tests) 524ms
✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.format.test.ts (9 tests) 697ms
✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts (63 tests) 432ms
Test Files 7 passed | 1 skipped (8)
Tests 136 passed | 1 skipped (137)
$ BLOCK_ID_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts # run as 4 shards of 500 seeds
FAIL |unit| …BlockIdCollabFuzz.test.ts > BlockIdExtension fuzz, @lexical/yjs v2 > seed 198
# likewise v2 seeds 462, 811, 938, 1086, 1157, 1918
Tests 7 failed | 3993 passed (4000)
```
All 2,000 seeds pass on v1, half of them starting from a document stored without ids. The 7 v2 failures are pre-existing problems in the v2 binding, not in block ids, and are the same seeds that failed before this change:
- In 6 of them, the v2 binding moved text from one block element into another under concurrent moves, joins and undo. For example, seed 938 ends with a block whose text is `M4 tex zM2 textM1 zt`, and seed 1918 splits the `M1` text across two elements. NodeState stays with the element, so the id follows the element rather than the text.
- In the other one (seed 198), the peers' texts diverge.
The same harness with the extension removed (`BLOCK_ID_FUZZ_CONTROL=1`, which checks convergence only) gives `Tests 10 failed | 3990 passed (4000)`: v2 seeds 198, 479, 612, 717, 1017, 1250, 1354, 1506, 1748 and 1873 diverge, and every v1 seed passes. Both results are unchanged with #9381 and #9377 (the open v2 attribute and text-run fixes) merged in.
The same suite and 2,000-seed fuzz were also run against `@lexical/y` (#9400) on a local integration branch that adds this commit and ports the two test files to that binding (not part of this PR). There, two clients that initialize the same empty room with the same content, the default empty paragraph included, write it once: the binding's deduplication of deterministic initial content now works with the extension on.
```
✓ |unit| packages/lexical-y/src/__tests__/unit/BlockIdY.test.ts (14 tests)
✓ |unit| packages/lexical-y/src/__tests__/unit/BlockIdYFuzz.test.ts (8 tests)
$ npx vitest --project unit --no-watch packages/lexical-y <and the block id test files>
Test Files 56 passed | 1 skipped (57)
Tests 1091 passed | 1 skipped (1092)
$ BLOCK_ID_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/BlockIdYFuzz.test.ts # 4 shards of 500
Tests 500 passed (500) # ×4: 2000/2000
```
```
$ pnpm run test-unit
Test Files 399 passed | 1 skipped (400)
Tests 9693 passed | 2 skipped (9695)
```
`pnpm run tsc`, `pnpm run flow`, ESLint and Prettier on the touched files are clean, and the tree-shaking tests pass on the sources (in `test-unit`) and on the published build (`scripts/__tests__/integration/tree-shaking.test.mjs` after `pnpm run build-prod`). Not exercised: real browsers.
zurfyx
added a commit
that referenced
this pull request
Oct 23, 2026
…al-devtools] Feature: Stable block ids (BlockIdExtension) ## Description Lexical has no stable way to address a block from outside the editor. Node keys are runtime-only and change on every load, and the position of a block changes with every edit. Code that edits a document by block (an AI agent that reads blocks and answers `replace <id>`, `insert after <id>`, `delete <id>`, or a server pipeline that patches stored JSON) needs an id that survives serialization, reloads and collaboration. This adds an `@experimental` `BlockIdExtension` to `@lexical/extension`, and an opt-in `BlockIdHTMLExtension` to `@lexical/html`. It stacks on #9452 (`$config` node structure): the default predicate reads the `children` a class declares, through `getDeclaredNodeStructure`. - **Storage.** The id is NodeState (`blockIdState`, key `blockId`), serialized as `"$": {"blockId": "…"}`. It survives clones, undo/redo and the Lexical clipboard, and syncs through any binding that syncs NodeState (`@lexical/yjs` v1 and v2 both do). It is declared `resetOnCopyNode`, so `$copyNode` does not copy it. Any non-empty string of at most 128 characters is a valid id, so an app that already stores its own ids under `$.blockId` (UUIDs, for instance) can switch to `blockIdState` without migrating documents. - **API.** `$getBlockId(node)` and `$getBlockById(id)`. The lookup goes through an index that is updated from the dirty nodes of each commit, and every hit is checked against the active state. Config: `$isIdentifiedBlock` (default `$defaultIsIdentifiedBlock`, below; `$isRootChildBlock` is the preset for the root's children only), `generateId` (default `generateBlockId`), and `disabled` (config plus output signal). The per-editor state (index, config) is the extension's init result, so it is not reachable from the output. - **Which blocks get ids.** `$defaultIsIdentifiedBlock` identifies every element and decorator child of the root (a top-level list or table included), every nested block that holds text, and every nested block decorator (non-inline `DecoratorNode`). A nested element holds text when it is not inline (`isInline()` is false) and its class declares `children: 'inline'`, or a list that includes `'inline'` as `ListItemNode` does: paragraphs, headings, quotes and code blocks inside table cells, collapsibles or quotes, and list items (including an item that only holds a nested list). Nested wrappers get no id: nested lists, table rows and cells, shadow roots (a shadow root quote holds blocks, whatever `QuoteNode` declares, as in #9452's own normalization), and nested elements whose class declares no `children`. A class that declares nothing gets the root-only behavior: an id as a root child, none nested. The predicate stays a function of the node and its ancestors (class declarations are cached per class), so the O(dirty) bookkeeping is unchanged. - **Exports.** One preset, `$isRootChildBlock`, the root's children only (the previous default). It is the one set the new default cannot be composed into, and the one an app that addresses only top-level blocks (or wants the shortest prompts) needs; everything else composes from `$defaultIsIdentifiedBlock` with a class check, which the docs show. An "every block" preset is not exported: it would put ids on wrappers (rows, cells, nested lists) whose ids churn with structure edits, and it is a two-line predicate for apps that want it. - **Id format.** `generateBlockId` makes 21 base64url characters: 126 random bits from `crypto.getRandomValues`, more than the 122 of a version 4 UUID. Ids are generated by every peer and by servers with no coordination, so the size alone must rule out collisions between ids generated concurrently (see Design). There is no `Math.random` fallback: without `crypto.getRandomValues` it throws and the app must configure `generateId`. Readers accept any non-empty string of at most 128 characters; writers always write 21 base64url characters. The format is documented as fixed. - **Assignment.** Every identified block without an id gets one in the same update that creates it, including blocks created by `importJSON`, HTML import and markdown import. Blocks created by edits get random ids. `setEditorState(parseEditorState(json))` assigns every missing id in that one commit, so a headless server can load, assign and save in a single synchronous write. Updates that skip transforms (remote collaboration changes) are repaired by a discrete follow-up update. - **Documents stored without ids.** A document loaded without ids, or with some missing, gets **positional ids**: SHA-256 of a key of the document (the SHA-256 of its canonical compact JSON, without ids) and of the block's place (its path among identified blocks), as 21 base64url characters. Every reader and every collaborator that loads the same document derives the same ids, without writing first, and they are stored with the first write. A load is a state set with `setEditorState`, the state present when the extension registers, the first content an editor gets (an initial state, a binding's first sync), and remote blocks that arrive without an id or with a repeated one. Everything else is an edit and gets random ids. A block that the previous state left unnamed takes the id readers derived, so a person's first edit keeps the ids an agent read. - **Uniqueness.** When several identified blocks share an id, the block that already had it before the update keeps it, and blocks that got it in this update (paste, duplicate, `$copyNode`, JSON or HTML import, an explicit `$setState`) get fresh ids. When several had it before (a duplicate that was committed, such as concurrent edits that meet in a merge), the earliest in document order keeps it. When none had it (several copies created in one local update), the first one created keeps it; in a load, the first in document order. The later holders of a committed or loaded duplicate get **duplicate ids**, SHA-256 of `"dup"`, the repeated id and their ordinal in document order, so every peer repairs it with the same value in time independent of the document's size. The rule is deterministic, idempotent and O(dirty): each holder is compared with its own version in the previous editor state. - **Slots.** Everything the extension walks visits slot values as well as children: the index rebuild, removals (a removed host takes the blocks of its slots out of the index), the lookup while disabled, and document order (a host's slots, in their canonical order, come before its children, as in `$dfsWithSlots`). Replacing a slot value with `$setSlot` keeps the id, like `replace`. The default predicate treats a slot like a shadow root, as Lexical does: a slot value, or a block in a slot container, is nested and follows the nested rules (a text block or block decorator gets an id, a container does not). The previous default identified nothing in slots, because slot values have no parent. - **Lineage.** The extension carries ids across splits, joins, type changes and moves (rules below). Core does not carry NodeState across `$setBlocksType`, so the extension detects the replacement from the previous state in the update that makes it. No core behavior changes. - **HTML.** `BlockIdHTMLExtension` writes `data-block-id` on exported identified blocks and reads it back through `DOMImportExtension`. Imported ids are validated and go through the uniqueness rule. Because it changes export output, the docs warn against adding it to editors whose HTML export must be deterministic (or to use `export: false` there). This is a separate extension in `@lexical/html` because `@lexical/html` already depends on `@lexical/extension`, so the dependency cannot go the other way. Its `export` and `import` config flags can turn off either direction. - **Docs.** New page Extensions > Block IDs: setup, addressing blocks and the agent recipe (the one-line `replace_block`, `$getBlockById(id)?.replace(newBlock)`, which keeps the id on every binding), which blocks get ids (the default, the `$isRootChildBlock` preset and composing), how ids follow edits, uniqueness, documents stored without ids, HTML, collaboration, configuration, and the id format with the positional-id derivation byte for byte. Plus entries in the included-extensions list. Flow types are added for both extensions. Binding specifics stay out of the page: whether a collaborator's concurrent typing survives a `replace` depends on the binding (`@lexical/y`, #9400, keeps it), and `@lexical/y` writes identical initial content once, so two clients that put the same first content into empty editors agree on its ids. - **Errors.** A `generateId` that keeps returning invalid or used ids, and a missing `crypto.getRandomValues`, fail through `invariant`, like the rest of the package. `@lexical/extension` is the home because the feature is editor-level behavior with no node classes and no dependencies beyond `lexical`. That is the same shape as `NormalizeInlineElementsExtension` and `SelectBlockExtension`. A headless server needs only `lexical` and `@lexical/extension`. Related: #9174 is an example app that implements an application-owned id policy with released APIs (a RootNode transform over `$dfsWithSlots`, 128-bit random ids, fresh ids for every paste). This PR ships the reusable version of that idea; its slot coverage and its random-id size match what that example does, and it does not touch `concepts/node-state.md`, which #9174 edits. ### Design **Why NodeState.** The id has to mean the same thing in a headless process editing stored JSON, in a solo editor, and between collaborators on any binding. NodeState is the one storage that all of those already carry: JSON, clone, undo, clipboard, and the collaboration bindings. CRDT item identity would tie ids to one binding and one session, and would not exist at all without collaboration. **Why 126 random bits rather than a peer prefix plus a counter.** A local collision is retried, so only ids generated concurrently by different peers can collide. Outside a collaboration session there is no peer identity to use as a prefix (a server editing stored JSON has none), so a prefix would itself be random and would need about 72 bits to stay unique across every session that ever edits a document. Prefix plus counter would then be 13 to 15 characters instead of 21, saving about 6 characters of JSON per block, and would make ids sequential: an agent that mistypes `…-17` as `…-18` would silently edit another block, where a mistyped random id names no block and the edit fails visibly. With 126 random bits (more than a v4 UUID's 122), a document with a million blocks has less than a 10⁻²⁶ chance of holding two equal ids. `generateId` stays configurable for apps that prefer prefixed ids; prompts that need shorter ids can alias them. **Why the existing block wins, and how ties are broken.** An agent that holds an id must keep reaching the same block after someone pastes or duplicates it, wherever the copy lands, including above the original. Within one update the editor knows which holder already had the id (it is in the previous state with that id) and which got it now, so the copy always yields. Two tie-breaks cover the cases where that does not single out one block: - *Several holders were committed together* (concurrent moves that a CRDT merges into two copies). Every peer that sees the duplicate repairs it, so every peer must pick the same survivor. Node keys cannot do this: each peer numbers the nodes it receives in its own order, so with key order each peer keeps its own copy and re-ids the other, and the merged document loses the id altogether (the concurrent-moves collab test fails exactly that way when key order is substituted). Document order is the same for every peer that sees the same document. It costs O(depth) plus a walk over the siblings between the two holders, like `isBefore`, and runs only to repair a committed duplicate. - *All holders got the id in one local update* (several copies pasted or imported together). Only this editor decides and the others receive the result, so the cheaper creation order (node keys, which only increase) is enough. Fresh ids are also generated in creation order. Peers that repair the same merged duplicate concurrently keep the same block and give the later holder the same duplicate id, derived from the repeated id and its ordinal, so their writes agree. (Peers that repair different states may differ; the shared document keeps one value, after which there is nothing left to repair.) A repair never creates a duplicate, so it cannot ping-pong. A local copy never reaches the shared document as a duplicate at all, because it is repaired in the update that creates it. **Why this default.** An agent edits text: a paragraph in a table cell or a list item is something it must be able to name, and with the previous default those had no id unless the app opted in. Every root child keeps an id, so a top-level list or table stays addressable as a whole and ids already stored on root children never churn. Wrappers (rows, cells, nested lists) hold no text of their own; ids on them would mostly follow structure edits (a nested list is created and dropped by indent and outdent) and lengthen prompts. The rule reads class declarations rather than an instance's current children, because the predicate is evaluated when a node is marked dirty and must depend only on the node and its ancestors. Classes that declare nothing are unknown (wrapper or text block), so they keep the old rule. A root child's place never depends on the blocks nested in it or its siblings, so the positional ids of root children are the same as with the root-only predicate; a document stored with ids on its root children only keeps them, and its nested blocks get positional ids that every reader agrees on. **Why positional ids for documents stored without ids.** Ids assigned at random on load differ on every read: an agent that reads a stored document's ids for a prompt would have to store a no-op write first, and two collaborators who open an unlabelled document at the same time would each write different ids, which the shared document then settles by last-writer-wins. Deriving them from the document makes every read and every peer agree. The key of the document matters: with the place alone, the third block of version 1 ("Intro") and the third block of version 2 ("Budget") would get the same id, and an id read from one version would silently address a different block in the other. The key is the SHA-256 of the canonical compact JSON with ids left out, so naming the blocks does not change it, and the compact form omits properties restored from schema defaults, which keeps it stable as nodes gain properties. Blocks created later must stay random: content-derived ids would collide on every empty paragraph. The positional ids have the same 21-character base64url format as random ones, rather than a marker prefix such as `~`. A prefix outside `[A-Za-z0-9_-]` fails the id validators apps commonly use for ids that also go into HTML attributes and URLs, and once stored, a positional id is an ordinary id: nothing should treat it differently. A hash collision with an id in use is retried with `#n` appended to the place, in document order, so retries are deterministic too. Repeated ids are renamed differently: the k-th later holder (in document order) gets the first 21 base64url characters of SHA-256(`"dup"` U+0000 id U+0000 k). This depends only on the repeated id and the ordinal, so repairing a duplicate that a merge produced costs O(holders), not a pass over the document, and is still the same on every peer that sees the same document. Readers of a stored document with repeated ids use the same rule, so a reader and an editor agree there too. Collaboration-tagged updates are never relabelled in the update that applies them (the bindings would not write such changes back); the follow-up repair writes the names that every peer derives, so peers that repair concurrently write the same values. | Edit | Id result | | --- | --- | | Enter in the middle or at the end of a block | Block keeps its id; the new block gets a fresh one | | Enter at the start of a block | The text moves into the new block below, and the id moves with it; the emptied block above gets a fresh id | | Backspace join | The surviving block keeps its id | | Paragraph to heading or quote (`$setBlocksType`) and back | The replacement keeps the id | | Paragraph to list (`INSERT_*_LIST_COMMAND`) | The list item keeps the id; the list gets a fresh one (with `$isRootChildBlock`, the list keeps it) | | `replace(newNode)` with a node that has no id, or `$setSlot` replacing a slot value | The new node keeps the id | | Move (drag and drop, `insertAfter`/`insertBefore`) | The id moves with the block | | Paste, duplicate, JSON or HTML import of copied content | Copy keeps the id only if no other block has it; otherwise the original keeps it, even when the copy is placed above | | Several copies created in one update, none pre-existing | The first one created keeps the id | | Cut and paste | The pasted block keeps the id (nothing else has it any more) | | Copies that only meet in a collaborative merge, or repeated ids in a loaded document | The earliest in document order keeps the id; the k-th later one gets the id derived from the repeated id and k | | A document loaded without ids (or with missing ones) | Positional ids, the same for every reader and peer | | `$copyNode` | The copy has no id and gets a fresh one | | Undo/redo | Exact ids restored | `insertNewAfter` behavior that was checked: `ParagraphNode`, `HeadingNode` and `QuoteNode` create a new node without NodeState. `QuoteNode` creates a paragraph, so Enter at the start of a quote leaves an empty quote above and moves the text into a paragraph that keeps the id. `HeadingNode` at the start replaces itself with a paragraph (`replace(…, true)`) and moves the text into a new heading, which takes the id. `ListItemNode` uses `$copyNode`, which leaves the id behind. ### How agents use this ```ts // What the agent reads. const blocks = editor.read(() => $getRoot().getChildren().map(node => ({id: $getBlockId(node), text: node.getTextContent()})), ); // What it answers: [{op: 'replace', id: '…', text: '…'}, {op: 'delete', id: '…'}] editor.update(() => { for (const op of ops) { const block = $getBlockById(op.id); if (block === null) continue; // gone meanwhile, or a mistyped id if (op.op === 'delete') block.remove(); else block.replace($createParagraphNode().append($createTextNode(op.text))); // keeps the id } }, {discrete: true}); ``` ### Performance On a 10,000-block document (headless). The harness runs an editor with the extension and one without it through the same operations, interleaved round by round, so that process drift affects both alike (`BLOCK_ID_PERF=1 npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts`): ``` 10000 blocks, median, interleaved without with delta keystroke (300) 14.230 ms 15.023 ms 0.793 ms Enter (300) 15.290 ms 18.394 ms 3.104 ms paste 20 blocks (50) 17.472 ms 20.351 ms 2.880 ms paste 50 blocks (50) 19.384 ms 23.016 ms 3.631 ms remote duplicate (50) 22.541 ms 51.889 ms 29.348 ms first load, no ids (12) 112.349 ms 279.348 ms 166.999 ms of which document key: 56.692 ms load, ids stored (12) 130.119 ms 159.180 ms 29.060 ms ``` The document is flat, so the default and `$isRootChildBlock` identify the same blocks; the same harness with `$isRootChildBlock`, run right after, gave deltas of 0.829, 2.502, 2.888, 4.164, 30.875, 177.039 and 32.285 ms. The new default adds no measurable cost per keystroke, Enter or paste. On a document with 2,000 root children and 10,000 list items (one-off probe, medians of 8 interleaved rounds), the first load without ids took 169 ms without the extension, 290 ms with `$isRootChildBlock` (2,000 ids) and 438 ms with the default (12,000 ids), about 13 µs per id; keystroke and Enter inside an item stayed within 1 ms of the editor without the extension for both. These numbers come from a shared machine under load. Across runs the keystroke delta moved between 0.5 and 1.4 ms, and a probe that interleaved five editors (none, a no-op root transform, no-op transforms on every node class, a no-op update listener, and the extension) measured the editor with the extension as the fastest of the five, so the keystroke delta is within noise: typing creates no block, and the extension does nothing for it beyond an O(dirty) index check. The Enter delta moved between 2.0 and 3.1 ms across runs. Instrumentation put the extension's own work at about 0.1 ms per Enter; most of the Enter delta is Lexical running the root transforms a second time, including the O(root children) shadow-root normalization, because a transform changed a node. A ten-line extension that only sets a NodeState on new paragraphs in a transform measured +1.04 ms in the same harness. Positional ids cost one pass over the document, and only when blocks without an id appear: - **First load without ids**: +167 ms for 10,000 blocks, of which about 55 to 65 ms is the document key (compact export, canonical JSON and SHA-256 of about 850 KB), about 20 ms is deriving 10,000 ids (one SHA-256 block each), and the rest is assigning and indexing 10,000 ids, which random ids cost as well. - **A document stored with its ids** does not compute the key: +29 ms (indexing). - **A remote duplicate** is repaired with duplicate ids, which do not hash the document: +29 ms on 10,000 blocks, almost all of it the repair commit itself; ordering the holders and deriving the id take well under a millisecond. A remote block without an id (only from clients without the extension) still gets a positional id, so that repair hashes the document once. ## Test plan New tests: - `packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts` (headless, 66 tests): assignment in the creating commit; importJSON; markdown; documents opened without ids; foreign states; the headless recipe; invalid stored ids; generator collisions; the default id format (21 characters, all 64 symbols used); duplicates in JSON; determinism and idempotence (with the random default generator); duplicates after the original and above it (the original keeps the id); duplicating a block upward; several copies in one update (the first created keeps it); a committed duplicate repaired the same way whichever order its nodes were created in; `$copyNode`; explicit clashing ids; `$copyNode` right after a JSON load (before anything has read the state); copy/paste within and between editors; pasting a copy above the original; cut and paste, in two updates and in one; undo/redo of a paste; Enter at the start, middle and end of paragraph, heading, quote and list item (nested); Backspace and forward-delete joins; `$setBlocksType` single, multi and empty blocks, and back; paragraph to list; moves; manual replace; undo/redo of every step with the index checked; `$getBlockById`; O(dirty) predicate calls on a 1,000-block document; list and table nesting (the default plus table cells); paragraph to list with the default (the item keeps the id) and with `$isRootChildBlock` (the list keeps it); the default predicate on a table holding a heading, quote, code block, horizontal rule, undeclared container, shadow root quote and link, on nested lists and on an undeclared container and shadow root quote at the top level (exactly the blocks it identifies have ids); a document stored with ids on the root children only keeps them, and two readers give its list items and cell paragraphs the same positional ids; disabled/enabled; repair after updates without transforms and after collaboration-tagged updates. Documents stored without ids: two reads agree; two documents (or versions) share no id; stored ids kept, missing ones positional, a taken positional id retried; blocks created later are random; initial state functions and the default paragraph are loads; `setEditorState` is a load and updates are edits; a foreign state gets the ids its JSON gets; a person's first edits keep the ids a reader read; nested paths; one commit and idempotent. The tests that exercise edits start from an editor that has had content, so that their first blocks are edits. - `BlockIdExtension.format.test.ts` (9 tests): the frozen format. SHA-256 against Node's crypto on every padding boundary; UTF-8 against Node's encoder, lone surrogates included; canonical JSON key order; the hashed document is the compact export without ids; positional ids and duplicate ids against an independent implementation of the specification with Node's crypto, and pinned to literal values; a loaded document with repeated ids renamed by ordinal; 20,000 positional ids well formed, using all 64 symbols, none repeated; `generateBlockId` throws without `crypto.getRandomValues`. - `BlockIdExtension.slots.test.ts` (10 tests, on the default predicate, which treats a slot like a shadow root; the container itself gets no id): blocks inside a slot container and a block that is itself a slot value get ids in the creating commit; a duplicate pasted into a slot yields; committed duplicates between a slot and its host's children, and between two slots, are repaired in document order whichever order the nodes were created in; `$setSlot` replacement keeps the id; `$setBlocksType` inside a slot; the index after undo and after `setEditorState`; removing a host frees the ids of its slots; the lookup while disabled. - `BlockIdExtension.dom.test.ts` (jsdom, mounted editor): typing, Enter and Backspace; Backspace at the start of the first heading; clipboard paste between editors and within one; legacy HTML paste; undo. - `packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts` (7 tests): off by default; export on identified blocks only (list items included by default); no item ids with `$isRootChildBlock`; HTML round trip (exported to a DOM document and imported from it); imported ids through the uniqueness rule (duplicates, clashes, empty, too long); `export: false`/`import: false`; two readers of the same id-less HTML export the same `data-block-id`s. Fixtures are fixed strings parsed with `DOMParser`, or built with `createElement`/`setAttribute`. - `packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts`: a headless harness wiring v1 and v2 bindings the way the React plugins do. It runs 13 tests per binding: ids assigned once by the creator; a late joiner writes nothing; concurrent Enter; concurrent duplicates on three peers, one pasted above the original; concurrent moves that duplicate a block after merge (all peers repair with the same duplicate id); a document written without ids opened concurrently by two peers (both derive the ids a headless reader derives, and the merge needs no repair); type change and move; type change concurrent with typing; Yjs undo/redo of a split; join concurrent with Enter; nested list ids; two peers that load an id-less document concurrently and each edit it converge on its positional ids, with no repair after the merge, and the ids read headlessly before still name the same content; two clients that put the same first content into empty editors name it alike. Every test checks convergence, unique ids and quiescence: a further round produces no Yjs update. - `BlockIdCollabFuzz.test.ts`: deterministic randomized runs with 2 or 3 peers mixing typing, Enter, join, duplicate, block type changes, moves, Yjs undo/redo and partitions. Even seeds start from a document written without ids that every peer opens at the same time; they must name it as a headless reader does and need no repair when they meet. They assert convergence, every block having an id, unique ids, quiescence, and that blocks never split, merged, copied or concurrently restructured keep their ids. A nested variant adds list conversions, indents and outdents, so list items and nested lists are split, joined, moved and restructured concurrently; it checks every identified block, nested or not, and taints every id inside a block an op restructures. CI runs 8 seeds per binding and variant; `BLOCK_ID_FUZZ_SEEDS` runs more. - `BlockIdExtension.perf.test.ts`: the measurement above; skipped unless `BLOCK_ID_PERF=1`. ### Before On #9452 with the new test files copied in, every block id test fails (the extension does not exist): ``` $ npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension*.test.ts packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts packages/lexical-yjs/src/__tests__/unit/BlockIdCollab*.test.ts FAIL |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts [ packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts ] Error: Cannot find module '../../internal/positionalBlockId' imported from … FAIL |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts > BlockIdExtension (DOM) > typing, Enter and Backspace in a mounted editor TypeError: Cannot read properties of undefined (reading 'name') ... Test Files 8 failed (8) Tests 70 failed (70) ``` With the previous default (the root's children only) and the new tests, the tests of nested ids fail: ``` $ npx vitest --project unit --no-watch <the same files> FAIL …BlockIdExtension.test.ts > BlockIdExtension: the default predicate > root children, nested blocks that hold text, nested block decorators AssertionError: expected [ 'table:b1', ' tablerow', …(21) ] to deeply equal [ 'table:b1', ' tablerow', …(21) ] FAIL …BlockIdExtension.slots.test.ts > BlockIdExtension: slots > a block that is itself a slot value gets an id AssertionError: expected [ 'host:b1' ] to deeply equal [ 'host:b1', ' caption:b2' ] FAIL …BlockIdExtension.test.ts > BlockIdExtension: type changes and moves > paragraph to list: the item keeps the id, the list is new FAIL …BlockIdExtension.test.ts > BlockIdExtension: the default predicate > ids stored on the root children are kept; nested blocks get positional ids FAIL …BlockIdHTMLExtension.test.ts > BlockIdHTMLExtension > exports data-block-id on identified blocks only FAIL …BlockIdCollab.test.ts > BlockIdExtension with @lexical/yjs v1 > nested ids in lists sync # likewise the 8 other slot tests, markdown import, Enter in list items (3), nested paths, the v2 nested sync, # and the tests that use $isRootChildBlock, which does not exist there Test Files 4 failed | 3 passed | 1 skipped (8) Tests 24 failed | 131 passed | 1 skipped (156) ``` ### After ``` $ npx vitest --project unit --no-watch <the same files> ✓ |unit| packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts (7 tests) ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts (5 tests) ↓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts (1 test | 1 skipped) ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.slots.test.ts (10 tests) ✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts (26 tests) ✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts (32 tests) ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.format.test.ts (9 tests) ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts (66 tests) Test Files 7 passed | 1 skipped (8) Tests 155 passed | 1 skipped (156) $ BLOCK_ID_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts # run as 4 shards of 500 seeds FAIL |unit| …BlockIdCollabFuzz.test.ts > BlockIdExtension fuzz, @lexical/yjs v2, nested false > seed 198 # likewise v2 seeds 462, 811, 938, 1086, 1157, 1918; v2 nested: 48 seeds (below) Tests 55 failed | 7945 passed (8000) ``` v1 passes all 2,000 seeds, flat and nested, half of them starting from a document stored without ids. The flat runs only hold root blocks, which both defaults identify alike, and fail on exactly the 7 v2 seeds that failed before this change, pre-existing problems in the v2 binding: - In 6 of them, the v2 binding moved text from one block element into another under concurrent moves, joins and undo. For example, seed 938 ends with a block whose text is `M4 tex zM2 textM1 zt`, and seed 1918 splits the `M1` text across two elements. NodeState stays with the element, so the id follows the element rather than the text. - In the other one (seed 198), the peers' texts diverge. The same harness with the extension removed (`BLOCK_ID_FUZZ_CONTROL=1`, which checks convergence only) gives 10 diverging v2 seeds in the flat runs (198, 479, 612, 717, 1017, 1250, 1354, 1506, 1748 and 1873) and none on v1. Both results are unchanged with #9381 and #9377 (the open v2 attribute and text-run fixes) merged in. The nested runs fail on 48 of 2,000 v2 seeds, all in the v2 binding's handling of lists: 18 diverge only in a nested list that one peer exports as `"$": {"blockId": undefined}` (v2 applies a removed NodeState attribute as an explicit `undefined` in a class that has not registered the key), 17 throw inside the v2 sync (`$createOrUpdateNodeFromYElement` writes the NodeState of a list node that is no longer in the editor state), 9 diverge in content, 3 fail the id stability check like the flat seeds above, and 1 keeps writing Yjs updates after the last sync. The same nested runs with `$isRootChildBlock` fail on 52 v2 seeds with the same classes (39 seeds in common; the repairs change the op stream), so the new default does not make v2 worse. The same suites and the 2,000-seed fuzz, flat and nested, were also run against `@lexical/y` (#9400) on a local integration branch that adds this commit and ports the two test files to that binding (not part of this PR): ``` $ npx vitest --project unit --no-watch packages/lexical-y <and the block id test files> ✓ |unit| packages/lexical-y/src/__tests__/unit/BlockIdY.test.ts (12 tests) ✓ |unit| packages/lexical-y/src/__tests__/unit/BlockIdYFuzz.test.ts (16 tests) Test Files 65 passed | 1 skipped (66) Tests 2403 passed | 3 skipped (2406) $ BLOCK_ID_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/BlockIdYFuzz.test.ts # 4 shards of 500 Tests 1000 passed (1000) # ×4: 2000/2000 flat and 2000/2000 nested ``` ``` $ pnpm run test-unit Test Files 400 passed | 1 skipped (401) Tests 9757 passed | 2 skipped (9759) ``` Every test of #9452 passes unchanged (no test outside the block id files is modified; a per-test comparison with #9452 shows none missing and none changed); the new ones are the block id files and 20 build, Flow-subpath and tree-shaking entries for the new `@lexical/extension/BlockIdExtension` entry. `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `pnpm run flow`, ESLint and Prettier (whole repo) are clean; the tree-shaking tests pass on the sources (in `test-unit`) and on the published build (`scripts/__tests__/integration/tree-shaking.test.mjs` after `pnpm run build-prod`, 282 passed); the website builds with the broken link check on, and every TypeScript example on the Block IDs page type-checks. Not exercised: real browsers.
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
In collab v2 a paragraph's adjacent TextNodes share one
Y.XmlTextrun, andevery other inline child (MarkNode, LinkNode, LineBreakNode, inline
decorators) is a sibling of it. When the start of a run is replaced by such a
child, for example wrapping the first word of a paragraph in a comment mark or
replacing it with a line break, the children change from
[XmlText]to[XmlElement, XmlText].$updateYFragmentonly reused a text run in place when it paired with theleft edge of the unmatched range. Here the left Lexical child is the new
element, so the run fell through to delete-and-insert: the whole
XmlTextwas deleted and recreated. Anything a peer had concurrently typed into that
run (anywhere later in the paragraph) was anchored to the deleted items and
was dropped on every peer. The same edit without concurrency also needlessly
gave every character of the run a new identity.
The compare loop now mirrors the left-edge text branch on the right edge:
when the rightmost unmatched pair is an
XmlTextand a run of TextNodes, therun is updated in place with
$updateYText. The resulting document contentis unchanged; only the shared type (and with it, concurrent inserts) is kept.
This does not cover wrapping the whole run (e.g. a comment over all of a
paragraph's text while a peer types inside it): the text then has to move
into a new container, which Yjs cannot do without a delete.
Test plan
New
packages/lexical-yjs/src/__tests__/unit/SyncV2TextRunReuse.test.tswires two v2 peers like
useYjsCollaborationV2over an in-memory transportthat queues updates while offline. While offline, peer A wraps the first word
in a MarkNode (or replaces it with a line break) and peer B types at the end
of the paragraph; after reconnecting, both editors and a fresh reload of each
peer's Yjs document must show both edits. A third case checks that, without
concurrency, the tail run keeps its original
XmlText.Before
After
pnpm run test-unit: 393 files, 9540 tests passed (1 skipped).pnpm run tsc,pnpm run flow(0 errors), ESLint and Prettier on thechanged files pass.
Run headless in Node/jsdom with an in-memory
transport only; not exercised in a real browser or over a real provider.