Skip to content

[lexical-website] Documentation Update: Add NodeState application identity example - #9174

Merged
potatowagon merged 3 commits into
meta:mainfrom
mpicken3:docs/node-state-application-identity
Nov 22, 2026
Merged

potatowagon merged 3 commits into
meta:mainfrom
mpicken3:docs/node-state-application-identity

Conversation

@mpicken3

Copy link
Copy Markdown
Contributor

No description provided.

@vercel

vercel Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
lexical Ready Ready Preview Sep 18, 2026 3:12pm UTC
lexical-playground Ready Ready Preview Sep 18, 2026 3:12pm UTC

Request Review

@meta-cla

meta-cla Bot commented Sep 16, 2026

Copy link
Copy Markdown

Hi @mpicken3!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@etrepum etrepum left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dev-examples is for examples that depend on features not available in a published lexical release. I haven’t looked closely but I don’t think this is using unreleased APIs. There’s also a build failure.

@mpicken3

Copy link
Copy Markdown
Contributor Author

dev-examples is for examples that depend on features not available in a published lexical release. I haven’t looked closely but I don’t think this is using unreleased APIs. There’s also a build failure.

Thanks for flagging this - you’re right that the example currently uses exported Lexical APIs rather than unreleased features. The only exception is the public experimental $dfsWithSlots helper, so I wanted to verify whether that qualifies for dev-examples... otherwise I’ll move the example under examples/ and update its package/build wiring accordingly.

I'll look into the build failure before sending over proper updates too!

@etrepum

etrepum commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

No, it does not qualify for dev-examples. @experimental doesn't mean unreleased. dev-examples is the location for examples that can not be built with a released version of lexical.

I also think that the documentation explaining how this particular example works belongs with the example itself, not the NodeState documentation. This is just one example of one way it could be done, not necessarily a general recommendation for how it should be done. If it was, the API to support it would ship with lexical.

I can't really take a closer look for consideration until the CLA is accepted.

@meta-cla

meta-cla Bot commented Sep 16, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

McKade Picken added 3 commits September 18, 2026 11:10
…ntity example

## Description

Applications may need persistent external IDs for document nodes while treating duplicated content as new logical application objects. NodeState can store those IDs, but persistence, `$copyNode`, and structured clipboard insertion require different application policies.

Adds an executable `dev-examples/node-state-identity` example, focused lifecycle tests, and guidance in the NodeState documentation. The application owns its allocator and addressing predicate, which selects non-root ElementNodes by default and leaves ordinary TextNodes mergeable.

The example preserves IDs through normal editing and JSON save/load, registers the identity StateConfig when loading, and uses existing `resetOnCopyNode` behavior for direct copies. Clipboard insertion clears only application identity; normal insertion and a RootNode transform assign fresh IDs to eligible pasted nodes. Ordinary and unknown NodeState remain intact, and undo/redo restores recorded IDs without reallocating them. Every paste, including cut/paste, creates fresh logical identity.

This example does not persist or modify Lexical NodeKeys.

Applications own allocator uniqueness and addressing granularity. The RootNode scan trades O(N) work after dirty updates for generic custom-node coverage; slot-inclusive traversal uses public, experimental `$dfsWithSlots`. Cross-editor behavior follows the receiver's policy. Generic collision reconciliation and reference remapping are outside this example's scope.

Addresses part of meta#8251 by providing application-level NodeState identity guidance and a bounded copy/paste identity policy.

## Test plan

### Before

Existing clipboard serialization intentionally preserves NodeState. This contribution documents an application policy; it does not change that core behavior.

### After

Validated on upstream `a02c61bdcaa752624fc4167e3fc05dca29c17768`, Windows, Node 24.21.0 and pnpm 11.24.0:

- `pnpm run test-unit --maxWorkers=1 dev-examples/node-state-identity/src/__tests__/unit/identity.test.ts`: 10 passed. Covers creation/editing, persistence and immediate copy after load, repeated paste, custom elements and slots, unrelated state, cross-editor policy, cut/paste, history and text normalization.
- Combined example and targeted NodeState, copy, clipboard, serialization and history run: 473 tests passed across 16 files.
- `node node_modules/typescript/bin/tsc -p dev-examples/node-state-identity/tsconfig.json --pretty false`, focused ESLint and Prettier: passed.
- `pnpm run build` and the example's Vite development build: passed.
- NodeState MDX compilation and headless Edge smoke checks for editing, identity display, copy, history and save/load: passed.
- `git diff --check`: passed.

The new upstream generated-file test required LF fixture checkout bytes on Windows; no upstream file content or test was changed. A transient Vitest worker-start timeout cleared on the final combined run. Full website deployment and other OS/browser matrices were not run.
@mpicken3
mpicken3 force-pushed the docs/node-state-application-identity branch from 47a2d8f to 2e8cd24 Compare September 18, 2026 15:10
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 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.
zurfyx added a commit that referenced this pull request Oct 24, 2026
…al-devtools] Feature: Stable block ids (BlockIdExtension)

## Description

Lexical has no stable way to address a block from outside the editor. Node keys exist only at runtime and change on every load, and a block's position changes with every edit. Code that edits a document block by block needs an id that survives serialization, reloads and changes applied from other replicas. Examples: an AI agent that reads blocks and answers `replace <id>`, `insert after <id>` or `delete <id>`, or a server pipeline that patches stored JSON.

This PR adds an `@experimental`, opt-in `BlockIdExtension` to `@lexical/extension`, and an opt-in `BlockIdHTMLExtension` to `@lexical/html`. It builds on #9452, which has merged, so its base is main. The default predicate reads the `children` a class declares, through `getDeclaredNodeStructure`. The extension also declares an optional peer dependency on `NodeStructureExtension` so that, when both are present, it registers after it (see below). Editors that do not register the extension see no change in state, JSON, transforms, exports or behavior.

- **Storage.** The id is NodeState (`blockIdState`, key `blockId`), serialized as `"$": {"blockId": "…"}`.
  - It survives clones, undo/redo and the Lexical clipboard.
  - Anything that copies NodeState carries it.
  - It is declared `resetOnCopyNode`, so `$copyNode` does not copy it.
  - A valid id is 1 to 64 characters of the base64url alphabet (`A`–`Z`, `a`–`z`, `0`–`9`, `-`, `_`): safe in URLs, HTML attributes and JSON, and wide enough for UUIDs, nanoids and shorter app ids, so an app that already stores such ids under `$.blockId` can adopt `blockIdState` without migrating documents. Any other value, from JSON, HTML, another replica, `generateId` or a direct `$setState`, reads as no id, and the block gets a new one through the normal rules (positional in a load, derived in a repair).
- **API.**
  - Lookup: `$getBlockId(node)` and `$getBlockById(id)`. While enabled, the lookup uses an index that is updated from each commit's dirty nodes (including elements created or rewritten in the commit), and every hit is checked against the active state.
  - Config: `$isIdentifiedBlock` (default `$defaultIsIdentifiedBlock`), `generateId` (default `generateBlockId`) and `disabled` (also an output signal).
  - The index lives in the extension's init result, typed `unknown` in TypeScript and Flow alike, not in its 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: a non-inline element whose class declares `children: 'inline'`, or a list that includes `'inline'`, as `ListItemNode` does;
  - every nested block decorator.

  Nested wrappers get no id: nested lists, table rows and cells, shadow roots, and nested elements whose class declares no `children`. Slot values and blocks in slots follow the nested rules. One preset is exported: `$isRootChildBlock`, the root's children only. Other sets compose from the default, as the docs show.
- **New ids.** `generateBlockId` makes 21 base64url characters: 126 random bits from `crypto.getRandomValues`, more than a v4 UUID's 122. There is no `Math.random` fallback. Without `crypto.getRandomValues` it throws, and the app must configure `generateId`. A `generateId` value that is invalid (not a string included) or already used is discarded and `generateId` is called again; 32 in a row throw.
- **Assignment.** Every identified block without an id gets one in the update that creates it, including blocks from `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 one synchronous write. Updates applied with `skipTransforms` or tagged `COLLABORATION_TAG` or `HISTORIC_TAG` are repaired by a discrete follow-up update.
- **Documents stored without ids** get **positional ids** on load: SHA-256 of the document key and the block's place, as 21 base64url characters. The key is the SHA-256 of `editorState.toJSON(true).root` without ids, written as canonical JSON. Every editor that loads the same document with the same nodes, predicate and transforms derives the same ids without writing first, and the first write stores them. Blocks created later by edits get random ids. A load is named once its transforms have settled, so the key is taken from the document the load ends with. A stored document that loading changes (equal adjacent lists that `ListNode` merges, or anything `NodeStructureExtension` repairs) therefore gets the positional ids of the loaded document, which cannot be computed from its stored JSON alone; see Known limits.
- **Uniqueness.** When several identified blocks share an id:
  - The block that was identified with it before the update keeps it; copies made in this update yield (paste, duplicate, `$copyNode`, JSON or HTML import, an explicit `$setState`). An id left on a block that is not identified is not reserved.
  - If several had it before (a duplicate produced when concurrent changes from different replicas merge), the earliest in document order keeps it. The k-th later holder gets `base64url(SHA-256("dup" U+0000 id U+0000 k))[0..21]`, so every replica repairs it alike, in time independent of document size.
  - If none had it (several copies made in one local update), a copy that took the content of the removed original keeps it (a list merged into an adjacent copy), else the first one created.
  - A copy that yields its id counts as a block without one, so a copy of a list pasted right above an equal list continues that list when the two merge.
- **Edits.** Ids stay with the content the user sees. Enter, Backspace join, `$setBlocksType`, paragraph to list, `replace`, `$setSlot` and moves keep the id. Cut and paste keeps the id; a copy gets a new one. Undo and redo restore ids exactly.
- **Ids follow the structure an update ends with.** Ids are assigned in a root transform, and other transforms can still restructure the document in later passes of the same update: `ListNode` can merge a run of equal adjacent lists over several passes, and `NodeStructureExtension` splits, joins, lifts and merges blocks in a root transform of its own. A generated id that an earlier pass gave a new block is therefore provisional within the update. A later pass can still replace it with the id of a block that the new one continues, and a copy that yielded its id takes it back once the original has been merged into it. With `NodeStructureExtension`:
  - a block split around a block lifted out of it keeps its id on the first piece, and the later pieces get fresh ids;
  - a block lifted out of a block that it leaves empty takes that block's place, and its id if it has none, as `replace` does;
  - paragraphs joined into a block as lines leave that block its id;
  - equal adjacent lists merge into the first, which keeps its id; a new list without an id continues the list merged into it.

  The result does not depend on the order in which the two extensions are listed, and edits give the same ids when `NodeStructureExtension` is enabled after the editor is built; loads then differ (see Known limits).
- **HTML.** `BlockIdHTMLExtension` writes `data-block-id` on exported identified blocks and reads it back through `DOMImportExtension`, subject to the validity and uniqueness rules. An id imported onto a block that is not identified once inserted (a table cell, a nested list) is dropped. Its `export` and `import` flags turn off either direction. It lives in `@lexical/html` because `@lexical/html` already depends on `@lexical/extension`.
- **Docs.** A new page, Extensions > Block IDs, covers:
  - setup and the agent recipe (one update per operation, keeping a person's selection when the agent replaces a block it touches);
  - which blocks get ids, and nested editors;
  - how ids follow edits, ids left on blocks that stop being identified, and uniqueness;
  - documents stored without ids, and what a load that changes the document does to their ids;
  - how ids follow the structure that `NodeStructureExtension` repairs;
  - HTML and configuration, including enabling the extension on every editor that writes;
  - the id format: exactly what is hashed, canonical JSON (ECMA-262 `JSON.stringify` semantics: integer-like keys first, escaping, number formatting), canonical slot order, what the freeze covers, and a literal end-to-end test vector for implementations in other languages.

  The PR also adds entries in the included-extensions list, and Flow types for both extensions.

### Collaboration

Block ids are plain NodeState, so they sync wherever replicas sync NodeState, and the duplicate repair gives the same result on every replica. Enable the extension on every client that writes; the positional-id limit when one does not is documented. A short new page, Collaboration > Block IDs ([`packages/lexical-website/docs/collaboration/block-ids.md`](https://lexical.dev/docs/collaboration/block-ids), added to the collaboration sidebar), covers this.

### Design notes

- **Why NodeState.** It is the one storage that JSON, clones, undo and the clipboard already carry, and that any replica copying NodeState carries too. An identity owned by one sync mechanism would tie ids to it and would not exist without it.
- **Why 126 random bits rather than a writer prefix.** A server editing stored JSON has no writer identity, so a prefix would itself have to be random. Random ids are opaque: a mistyped id names no block, instead of silently naming a neighbouring one. `generateId` stays configurable for apps that want prefixed ids.
- **Why a strict id alphabet.** The format is frozen: loosening the accepted set later is compatible, tightening it would re-id stored documents. Ids outside base64url did not survive an HTML round trip (`\r\n` became `\n`, NUL became U+FFFD). `^[A-Za-z0-9_-]{1,64}$` is the alphabet the extension writes, with room for the ids other systems already use.
- **Why document order for committed duplicates.** Each editor numbers the nodes it receives in its own order. With key order, each replica would keep its own copy, and the merged document would lose the id. The concurrent-moves test fails exactly that way when key order is substituted.
- **Why positional ids.** Random ids assigned on load would differ on every read. Deriving them from the document's content and place makes readers and replicas agree. The document key keeps the same place in two versions of a document from sharing an id.
- **Why positional ids stay keyed by the whole document.** With an editor that does not run the extension writing between two replicas' repairs, the replicas see different documents and can write different ids for the same block; the merged document keeps one, so an id one replica already wrote changes once (the replicas converge, ids stay unique, nothing changes afterwards). A per-block scheme (hash of the block's own JSON plus its rank among identical blocks) narrows but does not remove this: the blocks that editor edits still change, a block inserted with the same content as an earlier one shifts the ranks after it, and without a document-level salt identical blocks get the same id in every document; a salt every replica agrees on would have to come from the document itself, which that editor can change too. It would also give unchanged blocks the same id across versions, dropping the property above. So the scheme stays as it is, and the docs state the limit plainly: enable the extension on every editor that writes. The tests below show the behavior.

Related: #9174 is an example app with an application-owned id policy (128-bit random ids, a fresh id on every paste). This PR is the reusable version, convergent across replicas, and does not touch the files #9174 edits.

## Test plan

New tests:

- `BlockIdExtension.test.ts` (headless, 85 tests):
  - assignment and documents stored without ids, including a load during which an app transform creates a node it never inserts (still one commit, with every id);
  - id validity: invalid stored ids (numbers, empty, 65 characters, spaces, markup, control characters, lone surrogates, non-ASCII, `doc:12`) read as absent and get positional ids; 64-character, 11-character and UUID ids are kept; an invalid id from another replica is repaired; an invalid id set with `$setState` reads as absent; invalid `generateId` values, a value that is not a string included, are retried, and 32 in a row throw;
  - uniqueness: copies above and below the original, several copies in one update, committed duplicates, `$copyNode`, the clipboard, cut and paste, undo, copies of a list that merge with the original (also on both sides of it, merged over several transform passes), and a copy of a list pasted right above an equal list;
  - split and merge in paragraphs, headings, quotes and list items;
  - type changes and moves;
  - the index: `$getBlockById` finds every identified block after a document with ids on the root children only is loaded (by `setEditorState` and as the initial state), after the documented `$setState` recipe on a list or table, after a copy of such a list, and after `setEditorState` of a list whose items repeat an id; O(dirty) predicate calls;
  - ids left on blocks that stop being identified;
  - the default predicate across tables, lists, an undeclared container, a shadow root, a link and nested inline and block decorators; a custom predicate (headings at any depth); copy and cut of nested list items through the clipboard;
  - `disabled`, and repair after updates without transforms.
- `BlockIdExtension.structure.test.ts` (38 tests): the same 11 cases with `NodeStructureExtension` listed after this extension, listed before it, and enabled after the editor is built: a paragraph and a heading split around a lifted block, a block lifted out of the paragraph it empties, a list lifted out of a link (the items keep their ids and the link), paragraphs joined as lines, equal adjacent lists, nested lists joined at a seam, a new list, with and without an id, merged with the list after it, a copy of a list merged with the equal list after it, and copies of a list on both sides of it and apart from it. Each checks the exact ids and that the index finds every block. Five load tests, with the extensions in either order: a stored document with equal adjacent lists gets the positional ids of the merged document, the same as an editor without `NodeStructureExtension`; a stored paragraph that holds a quote gets the positional ids of the split document.
- `BlockIdExtension.property.test.ts` (20 seeds in CI): random sequences of 40 local edits (typing, Enter, joins, range deletes, type changes, moves, duplicates, multi-copy pastes, indent and outdent, list conversion, moves into table cells, replace, undo/redo, reloads with an injected duplicate). After every step, every identified block has exactly one id, ids are unique, `$getBlockById` finds every block, pre-existing blocks keep their ids, and undo and redo return to a state seen before. `BLOCK_ID_PROPERTY_SEEDS` runs more.
- `BlockIdExtension.format.test.ts` (10 tests): the frozen format. It checks SHA-256 and UTF-8 against Node, the canonical JSON, and positional and duplicate ids against an independent implementation, pinned to literal values, plus the end-to-end vector printed in the docs.
- `BlockIdExtension.slots.test.ts` (10 tests): slot values and slot containers, duplicates across slots and children, `$setSlot`, the index after undo and `setEditorState`, host removal, and the lookup while disabled.
- `BlockIdExtension.dom.test.ts` (5 tests, jsdom): typing, Enter, Backspace, clipboard paste, legacy HTML paste, undo.
- `BlockIdHTMLExtension.test.ts` (10 tests): off by default, export, round trip, imported ids through the uniqueness rule, invalid imported ids ignored, an imported id dropped from a block that is not identified, export into another realm's document, the `export` and `import` flags, and readers of an id-less document agreeing.
- `BlockIdDocs.test.ts` (5 tests): the code examples of the Block IDs page, as written there, with a person's caret inside the block the agent replaces, and with a selection from the block before into the replaced block, from it into the block after, backwards, and inside it.
- `BlockIdCollab.test.ts` (16 tests per binding, `@lexical/yjs` v1 and v2): assignment, late joiners, concurrent Enter, duplicates and moves, a document stored without ids opened concurrently, type changes, undo/redo, nested lists, and clients without the extension writing mid-session (a block added while the peers are apart; a block added while a peer has unsynced typing; peers that open an id-less document at different versions). Every test checks convergence, unique ids and quiescence.
- `BlockIdCollabFuzz.test.ts`: deterministic randomized runs with 2–3 replicas, flat and nested, 8 seeds per binding and variant in CI. `BLOCK_ID_FUZZ_SEEDS` runs more.
- `BlockIdExtension.perf.test.ts`: skipped unless `BLOCK_ID_PERF=1`.

### Before

On main (with #9452) with the new test files copied in, every block id test fails, because the extension does not exist:

```
$ npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension packages/lexical-html/src/__tests__/unit/BlockId packages/lexical-yjs/src/__tests__/unit/BlockIdCollab
Error: Cannot find module '../../internal/positionalBlockId' imported from …/BlockIdExtension.test.ts
TypeError: Cannot read properties of undefined (reading 'name')
TypeError: (0 , $getBlockId) is not a function
 Test Files  11 failed (11)
      Tests  142 failed (142)
```

### After

```
$ npx vitest --project unit --no-watch <the same files>
 ↓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts (1 test | 1 skipped)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.structure.test.ts (38 tests)
 ✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts (32 tests)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.property.test.ts (20 tests)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.format.test.ts (10 tests)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.slots.test.ts (10 tests)
 ✓ |unit| packages/lexical-html/src/__tests__/unit/BlockIdDocs.test.ts (5 tests)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts (85 tests)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts (5 tests)
 ✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts (32 tests)
 ✓ |unit| packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts (10 tests)
 Test Files  10 passed | 1 skipped (11)
      Tests  247 passed | 1 skipped (248)

$ pnpm run test-unit
 Test Files  405 passed | 1 skipped (406)
      Tests  9955 passed | 2 skipped (9957)
```

Every test on main passes unchanged (9618 of 9618 test ids, same status). `pnpm run tsc`, `tsc-test`, `pnpm run flow`, ESLint and Prettier are clean, the tree-shaking tests pass on the sources and on the production build, `build-prod` succeeds, and the website builds with no broken links.

Property test at 1,000 seeds: 1000 passed (`BLOCK_ID_PROPERTY_SEEDS=1000`).

Ids compared with a reference build that names blocks only once the transforms of an update have settled (otherwise the code of this PR). This used a local harness that is not committed: the property test's edits plus moves into list items and quotes, and an agent that reads ids and later replaces blocks by id, over 1,000 seeds × 40 steps, traces compared up to the naming of new ids. The ids are identical in every sequence in all five configurations: without `NodeStructureExtension`; with it listed after this extension; listed before it; enabled after the editor is built through its `disabled` output; and through `registerNodeStructure()`. Against the same reference, the first rebased version of this PR differed in 55 sequences without `NodeStructureExtension` and 127 with it listed second, and the previous version in 36, 41, 41, 57 and 57 sequences in those five configurations. Every difference of the previous version is in a list that pasted copies of a list merge into: the reference keeps on it the id of the list they merged with, where the previous version gave it a fresh id and dropped that id or left it on a copy. The cases are a copy pasted right above an equal list and, with `NodeStructureExtension` enabled after the build, several copies of a list merged with the original.

Known limits:
- **Loading a stored document that the load changes.** Positional ids are derived from the document the load ends with, not from the stored JSON. Where `ListNode` merges equal adjacent lists, editors with and without `NodeStructureExtension` derive the same ids. Where `NodeStructureExtension` repairs more (a paragraph split around a quote stored inside it, for example), the document key changes, so every block of such a document (not only the blocks the repair creates) gets ids that differ from those of an editor without `NodeStructureExtension`, and a reader working from the stored JSON must apply the same repairs first. Editors that load it with the same nodes and extensions agree. Documents that loading does not change, including the docs' test vector, are not affected. Making untouched blocks keep the ids of an editor without `NodeStructureExtension` would mean naming a load before `NodeStructureExtension`'s repairs, which run in a root transform registered before this extension's, and Lexical has no hook before the transforms of `setEditorState`.
- **`NodeStructureExtension` enabled after the editor is built.** Its repairs then run after this extension's naming in each pass. Edits give the same ids as above, but a load is named before the repairs: blocks the repairs keep get the positional ids of the document as it was before them, a list merged into another loses its id, and blocks the repairs create get ids from the document the load ends with.

Fuzz at 2,000 seeds per variant (`BLOCK_ID_FUZZ_SEEDS=2000`): v1 passes every seed, flat and nested. On v2, 55 seeds fail (7 flat, 48 nested). All 55 trace to the experimental `@lexical/yjs` v2 binding, not to this extension:
- 37 nested: when indent creates a nested list, the list's `blockId` is at its default (`$copyNode` resets it), and the v2 binding's create path writes that default into Yjs as an `undefined` attribute (its update path drops it). Receiving peers end with `"$": {"blockId": undefined}` on one peer (27) or throw on a stale list node inside the binding (10). The smallest repro is two steps on one peer: make a list, indent. A one-character change in the binding (`!== null` to `!= null` when it filters state attributes) removes all 37.
- 9 (6 flat, 3 nested): the v2 binding writes each Lexical child into whichever Y element of the same type sits at its position, so after concurrent moves an edit lands in another block's element. The binding then overwrites a block's `blockId` (last writer wins), writes one id onto two elements (the documented duplicate rule then renames one holder), or Yjs undo recreates an element without its attributes. The same minimized scripts pass on v1, and converge on v2 without the extension.
- 9 fail with the extension removed too (8 diverge or throw; 1 leaves an empty list element in Yjs that keeps the network from settling).

The v2 binding is not changed here.

Performance, on a headless 10,000-block document, with and without the extension, interleaved round by round (`BLOCK_ID_PERF=1 npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts`, shared machine under load):

```
10000 blocks, median, interleaved  without      with     delta
keystroke (300)             14.755 ms    15.279 ms     0.524 ms
Enter (300)                 15.488 ms    17.675 ms     2.187 ms
paste 20 blocks (50)        17.742 ms    20.244 ms     2.502 ms
paste 50 blocks (50)        20.080 ms    24.029 ms     3.950 ms
remote duplicate (50)       24.987 ms    55.247 ms    30.260 ms
first load, no ids (12)    113.748 ms   296.409 ms   182.660 ms
  of which document key: 58.927 ms
load, ids stored (12)      135.323 ms   177.253 ms    41.930 ms
```

Across three runs the deltas moved by a few milliseconds (keystroke 0.4 to 0.9 ms, Enter 2.0 to 2.5 ms, paste of 50 blocks 3.5 to 4.0 ms, first load 174 to 183 ms, stored ids 37 to 42 ms, remote duplicate 29 to 30 ms). Three runs of the previous version of this PR, interleaved with these, fell in the same range (keystroke 0.6 to 0.8 ms, Enter 2.2 to 2.5 ms, paste of 50 blocks 3.5 to 3.9 ms, first load 180 to 185 ms, stored ids 34 to 39 ms, remote duplicate 29 to 32 ms); a load of these documents takes the same transform passes in both. A block without an id applied from another replica (written only by editors without the extension) gets a positional id, so that repair hashes the document once.

Not exercised: real browsers.
zurfyx added a commit that referenced this pull request Oct 24, 2026
…al-devtools] Feature: Stable block ids (BlockIdExtension)

## Description

Lexical has no stable way to address a block from outside the editor. Node keys exist only at runtime and change on every load, and a block's position changes with every edit. Code that edits a document block by block needs an id that survives serialization, reloads and changes applied from other replicas. Examples: an AI agent that reads blocks and answers `replace <id>`, `insert after <id>` or `delete <id>`, or a server pipeline that patches stored JSON.

This PR adds an `@experimental`, opt-in `BlockIdExtension` to `@lexical/extension`, and an opt-in `BlockIdHTMLExtension` to `@lexical/html`. It builds on #9452, which has merged, so its base is main. The default predicate reads the `children` a class declares, through `getDeclaredNodeStructure`. The extension also declares an optional peer dependency on `NodeStructureExtension` so that, when both are present, it registers after it (see below). Editors that do not register the extension see no change in state, JSON, transforms, exports or behavior.

- **Storage.** The id is NodeState (`blockIdState`, key `blockId`), serialized as `"$": {"blockId": "…"}`.
  - It survives clones, undo/redo and the Lexical clipboard.
  - Anything that copies NodeState carries it.
  - It is declared `resetOnCopyNode`, so `$copyNode` does not copy it.
  - A valid id is 1 to 64 characters of the base64url alphabet (`A`–`Z`, `a`–`z`, `0`–`9`, `-`, `_`): safe in URLs, HTML attributes and JSON, and wide enough for UUIDs, nanoids and shorter app ids, so an app that already stores such ids under `$.blockId` can adopt `blockIdState` without migrating documents. Any other value, from JSON, HTML, another replica, `generateId` or a direct `$setState`, reads as no id, and the block gets a new one through the normal rules (positional in a load, derived in a repair).
- **API.**
  - Lookup: `$getBlockId(node)` and `$getBlockById(id)`. While enabled, the lookup uses an index that is updated from each commit's dirty nodes (including elements created or rewritten in the commit), and every hit is checked against the active state.
  - Config: `$isIdentifiedBlock` (default `$defaultIsIdentifiedBlock`), `generateId` (default `generateBlockId`) and `disabled` (also an output signal).
  - The index lives in the extension's init result, typed `unknown` in TypeScript and Flow alike, not in its 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: a non-inline element whose class declares `children: 'inline'`, or a list that includes `'inline'`, as `ListItemNode` does;
  - every nested block decorator.

  Nested wrappers get no id: nested lists, table rows and cells, shadow roots, and nested elements whose class declares no `children`. Slot values and blocks in slots follow the nested rules. One preset is exported: `$isRootChildBlock`, the root's children only. Other sets compose from the default, as the docs show.
- **New ids.** `generateBlockId` makes 21 base64url characters: 126 random bits from `crypto.getRandomValues`, more than a v4 UUID's 122. There is no `Math.random` fallback. Without `crypto.getRandomValues` it throws, and the app must configure `generateId`. A `generateId` value that is invalid (not a string included) or already used is discarded and `generateId` is called again; 32 in a row throw.
- **Assignment.** Every identified block without an id gets one in the update that creates it, including blocks from `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 one synchronous write. Updates applied with `skipTransforms` or tagged `COLLABORATION_TAG` or `HISTORIC_TAG` are repaired by a discrete follow-up update.
- **Documents stored without ids** get **positional ids** on load: SHA-256 of the document key and the block's place, as 21 base64url characters. The key is the SHA-256 of `editorState.toJSON(true).root` without ids, written as canonical JSON. Every editor that loads the same document with the same nodes, predicate and transforms derives the same ids without writing first, and the first write stores them. Blocks created later by edits get random ids. A load is named once its transforms have settled, so the key is taken from the document the load ends with. A stored document that loading changes (equal adjacent lists that `ListNode` merges, or anything `NodeStructureExtension` repairs) therefore gets the positional ids of the loaded document, which cannot be computed from its stored JSON alone; see Known limits.
- **Uniqueness.** When several identified blocks share an id:
  - The block that was identified with it before the update keeps it; copies made in this update yield (paste, duplicate, `$copyNode`, JSON or HTML import, an explicit `$setState`). An id left on a block that is not identified is not reserved.
  - If several had it before (a duplicate produced when concurrent changes from different replicas merge), the earliest in document order keeps it. The k-th later holder gets `base64url(SHA-256("dup" U+0000 id U+0000 k))[0..21]`, so every replica repairs it alike, in time independent of document size.
  - If none had it (several copies made in one local update), a copy that took the content of the removed original keeps it (a list merged into an adjacent copy), else the first one created.
  - A copy that yields its id counts as a block without one, so a copy of a list pasted right above an equal list continues that list when the two merge.
- **Edits.** Ids stay with the content the user sees. Enter, Backspace join, `$setBlocksType`, paragraph to list, `replace`, `$setSlot` and moves keep the id. Cut and paste keeps the id; a copy gets a new one. Undo and redo restore ids exactly.
- **Ids follow the structure an update ends with.** Ids are assigned in a root transform, and other transforms can still restructure the document in later passes of the same update: `ListNode` can merge a run of equal adjacent lists over several passes, and `NodeStructureExtension` splits, joins, lifts and merges blocks in a root transform of its own. A generated id that an earlier pass gave a new block is therefore provisional within the update. A later pass can still replace it with the id of a block that the new one continues, and a copy that yielded its id takes it back once the original has been merged into it. With `NodeStructureExtension`:
  - a block split around a block lifted out of it keeps its id on the first piece, and the later pieces get fresh ids;
  - a block lifted out of a block that it leaves empty takes that block's place, and its id if it has none, as `replace` does;
  - paragraphs joined into a block as lines leave that block its id;
  - equal adjacent lists merge into the first, which keeps its id; a new list without an id continues the list merged into it.

  The result does not depend on the order in which the two extensions are listed, and edits give the same ids when `NodeStructureExtension` is enabled after the editor is built; loads then differ (see Known limits).
- **HTML.** `BlockIdHTMLExtension` writes `data-block-id` on exported identified blocks and reads it back through `DOMImportExtension`, subject to the validity and uniqueness rules. An id imported onto a block that is not identified once inserted (a table cell, a nested list) is dropped. Its `export` and `import` flags turn off either direction. It lives in `@lexical/html` because `@lexical/html` already depends on `@lexical/extension`.
- **Docs.** A new page, Extensions > Block IDs, covers:
  - setup and the agent recipe (one update per operation, keeping a person's selection when the agent replaces a block it touches);
  - which blocks get ids, and nested editors;
  - how ids follow edits, ids left on blocks that stop being identified, and uniqueness;
  - documents stored without ids, and what a load that changes the document does to their ids;
  - how ids follow the structure that `NodeStructureExtension` repairs;
  - HTML and configuration, including enabling the extension on every editor that writes;
  - the id format: exactly what is hashed, canonical JSON (ECMA-262 `JSON.stringify` semantics: integer-like keys first, escaping, number formatting), canonical slot order, what the freeze covers, and a literal end-to-end test vector for implementations in other languages.

  The PR also adds entries in the included-extensions list, and Flow types for both extensions.

### Collaboration

Block ids are plain NodeState, so they sync wherever replicas sync NodeState, and the duplicate repair gives the same result on every replica. Enable the extension on every client that writes; the positional-id limit when one does not is documented. A short new page, Collaboration > Block IDs ([`packages/lexical-website/docs/collaboration/block-ids.md`](https://lexical.dev/docs/collaboration/block-ids), added to the collaboration sidebar), covers this.

### Design notes

- **Why NodeState.** It is the one storage that JSON, clones, undo and the clipboard already carry, and that any replica copying NodeState carries too. An identity owned by one sync mechanism would tie ids to it and would not exist without it.
- **Why 126 random bits rather than a writer prefix.** A server editing stored JSON has no writer identity, so a prefix would itself have to be random. Random ids are opaque: a mistyped id names no block, instead of silently naming a neighbouring one. `generateId` stays configurable for apps that want prefixed ids.
- **Why a strict id alphabet.** The format is frozen: loosening the accepted set later is compatible, tightening it would re-id stored documents. Ids outside base64url did not survive an HTML round trip (`\r\n` became `\n`, NUL became U+FFFD). `^[A-Za-z0-9_-]{1,64}$` is the alphabet the extension writes, with room for the ids other systems already use.
- **Why document order for committed duplicates.** Each editor numbers the nodes it receives in its own order. With key order, each replica would keep its own copy, and the merged document would lose the id. The concurrent-moves test fails exactly that way when key order is substituted.
- **Why positional ids.** Random ids assigned on load would differ on every read. Deriving them from the document's content and place makes readers and replicas agree. The document key keeps the same place in two versions of a document from sharing an id.
- **Why positional ids stay keyed by the whole document.** With an editor that does not run the extension writing between two replicas' repairs, the replicas see different documents and can write different ids for the same block; the merged document keeps one, so an id one replica already wrote changes once (the replicas converge, ids stay unique, nothing changes afterwards). A per-block scheme (hash of the block's own JSON plus its rank among identical blocks) narrows but does not remove this: the blocks that editor edits still change, a block inserted with the same content as an earlier one shifts the ranks after it, and without a document-level salt identical blocks get the same id in every document; a salt every replica agrees on would have to come from the document itself, which that editor can change too. It would also give unchanged blocks the same id across versions, dropping the property above. So the scheme stays as it is, and the docs state the limit plainly: enable the extension on every editor that writes. The tests below show the behavior.

Related: #9174 is an example app with an application-owned id policy (128-bit random ids, a fresh id on every paste). This PR is the reusable version, convergent across replicas, and does not touch the files #9174 edits.

## Test plan

New tests:

- `BlockIdExtension.test.ts` (headless, 85 tests):
  - assignment and documents stored without ids, including a load during which an app transform creates a node it never inserts (still one commit, with every id);
  - id validity: invalid stored ids (numbers, empty, 65 characters, spaces, markup, control characters, lone surrogates, non-ASCII, `doc:12`) read as absent and get positional ids; 64-character, 11-character and UUID ids are kept; an invalid id from another replica is repaired; an invalid id set with `$setState` reads as absent; invalid `generateId` values, a value that is not a string included, are retried, and 32 in a row throw;
  - uniqueness: copies above and below the original, several copies in one update, committed duplicates, `$copyNode`, the clipboard, cut and paste, undo, copies of a list that merge with the original (also on both sides of it, merged over several transform passes), and a copy of a list pasted right above an equal list;
  - split and merge in paragraphs, headings, quotes and list items;
  - type changes and moves;
  - the index: `$getBlockById` finds every identified block after a document with ids on the root children only is loaded (by `setEditorState` and as the initial state), after the documented `$setState` recipe on a list or table, after a copy of such a list, and after `setEditorState` of a list whose items repeat an id; O(dirty) predicate calls;
  - ids left on blocks that stop being identified;
  - the default predicate across tables, lists, an undeclared container, a shadow root, a link and nested inline and block decorators; a custom predicate (headings at any depth); copy and cut of nested list items through the clipboard;
  - `disabled`, and repair after updates without transforms.
- `BlockIdExtension.structure.test.ts` (38 tests): the same 11 cases with `NodeStructureExtension` listed after this extension, listed before it, and enabled after the editor is built: a paragraph and a heading split around a lifted block, a block lifted out of the paragraph it empties, a list lifted out of a link (the items keep their ids and the link), paragraphs joined as lines, equal adjacent lists, nested lists joined at a seam, a new list, with and without an id, merged with the list after it, a copy of a list merged with the equal list after it, and copies of a list on both sides of it and apart from it. Each checks the exact ids and that the index finds every block. Five load tests, with the extensions in either order: a stored document with equal adjacent lists gets the positional ids of the merged document, the same as an editor without `NodeStructureExtension`; a stored paragraph that holds a quote gets the positional ids of the split document.
- `BlockIdExtension.property.test.ts` (20 seeds in CI): random sequences of 40 local edits (typing, Enter, joins, range deletes, type changes, moves, duplicates, multi-copy pastes, indent and outdent, list conversion, moves into table cells, replace, undo/redo, reloads with an injected duplicate). After every step, every identified block has exactly one id, ids are unique, `$getBlockById` finds every block, pre-existing blocks keep their ids, and undo and redo return to a state seen before. `BLOCK_ID_PROPERTY_SEEDS` runs more.
- `BlockIdExtension.format.test.ts` (10 tests): the frozen format. It checks SHA-256 and UTF-8 against Node, the canonical JSON, and positional and duplicate ids against an independent implementation, pinned to literal values, plus the end-to-end vector printed in the docs.
- `BlockIdExtension.slots.test.ts` (10 tests): slot values and slot containers, duplicates across slots and children, `$setSlot`, the index after undo and `setEditorState`, host removal, and the lookup while disabled.
- `BlockIdExtension.dom.test.ts` (5 tests, jsdom): typing, Enter, Backspace, clipboard paste, legacy HTML paste, undo.
- `BlockIdHTMLExtension.test.ts` (10 tests): off by default, export, round trip, imported ids through the uniqueness rule, invalid imported ids ignored, an imported id dropped from a block that is not identified, export into another realm's document, the `export` and `import` flags, and readers of an id-less document agreeing.
- `BlockIdDocs.test.ts` (5 tests): the code examples of the Block IDs page, as written there, with a person's caret inside the block the agent replaces, and with a selection from the block before into the replaced block, from it into the block after, backwards, and inside it.
- `BlockIdCollab.test.ts` (16 tests per binding, `@lexical/yjs` v1 and v2): assignment, late joiners, concurrent Enter, duplicates and moves, a document stored without ids opened concurrently, type changes, undo/redo, nested lists, and clients without the extension writing mid-session (a block added while the peers are apart; a block added while a peer has unsynced typing; peers that open an id-less document at different versions). Every test checks convergence, unique ids and quiescence.
- `BlockIdCollabFuzz.test.ts`: deterministic randomized runs with 2–3 replicas, flat and nested, 8 seeds per binding and variant in CI. `BLOCK_ID_FUZZ_SEEDS` runs more.
- `BlockIdExtension.perf.test.ts`: skipped unless `BLOCK_ID_PERF=1`.

### Before

On main (with #9452) with the new test files copied in, every block id test fails, because the extension does not exist:

```
$ npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension packages/lexical-html/src/__tests__/unit/BlockId packages/lexical-yjs/src/__tests__/unit/BlockIdCollab
Error: Cannot find module '../../internal/positionalBlockId' imported from …/BlockIdExtension.test.ts
TypeError: Cannot read properties of undefined (reading 'name')
TypeError: (0 , $getBlockId) is not a function
 Test Files  11 failed (11)
      Tests  142 failed (142)
```

### After

```
$ npx vitest --project unit --no-watch <the same files>
 ↓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts (1 test | 1 skipped)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.structure.test.ts (38 tests)
 ✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollab.test.ts (32 tests)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.property.test.ts (20 tests)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.format.test.ts (10 tests)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.slots.test.ts (10 tests)
 ✓ |unit| packages/lexical-html/src/__tests__/unit/BlockIdDocs.test.ts (5 tests)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.test.ts (85 tests)
 ✓ |unit| packages/lexical-extension/src/__tests__/unit/BlockIdExtension.dom.test.ts (5 tests)
 ✓ |unit| packages/lexical-yjs/src/__tests__/unit/BlockIdCollabFuzz.test.ts (32 tests)
 ✓ |unit| packages/lexical-html/src/__tests__/unit/BlockIdHTMLExtension.test.ts (10 tests)
 Test Files  10 passed | 1 skipped (11)
      Tests  247 passed | 1 skipped (248)

$ pnpm run test-unit
 Test Files  408 passed | 1 skipped (409)
      Tests  10105 passed | 2 skipped (10107)
```

Every test on main passes unchanged (9768 of 9768 test ids, same status). `pnpm run tsc`, `tsc-test`, `pnpm run flow`, ESLint and Prettier are clean, the tree-shaking tests pass on the sources and on the production build, `build-prod` succeeds, and the website builds with no broken links.

Property test at 1,000 seeds: 1000 passed (`BLOCK_ID_PROPERTY_SEEDS=1000`).

Ids compared with a reference build that names blocks only once the transforms of an update have settled (otherwise the code of this PR). This used a local harness that is not committed: the property test's edits plus moves into list items and quotes, and an agent that reads ids and later replaces blocks by id, over 1,000 seeds × 40 steps, traces compared up to the naming of new ids. The ids are identical in every sequence in all five configurations: without `NodeStructureExtension`; with it listed after this extension; listed before it; enabled after the editor is built through its `disabled` output; and through `registerNodeStructure()`. Against the same reference, the first rebased version of this PR differed in 55 sequences without `NodeStructureExtension` and 127 with it listed second, and the previous version in 36, 41, 41, 57 and 57 sequences in those five configurations. Every difference of the previous version is in a list that pasted copies of a list merge into: the reference keeps on it the id of the list they merged with, where the previous version gave it a fresh id and dropped that id or left it on a copy. The cases are a copy pasted right above an equal list and, with `NodeStructureExtension` enabled after the build, several copies of a list merged with the original.

Known limits:
- **Loading a stored document that the load changes.** Positional ids are derived from the document the load ends with, not from the stored JSON. Where `ListNode` merges equal adjacent lists, editors with and without `NodeStructureExtension` derive the same ids. Where `NodeStructureExtension` repairs more (a paragraph split around a quote stored inside it, for example), the document key changes, so every block of such a document (not only the blocks the repair creates) gets ids that differ from those of an editor without `NodeStructureExtension`, and a reader working from the stored JSON must apply the same repairs first. Editors that load it with the same nodes and extensions agree. Documents that loading does not change, including the docs' test vector, are not affected. Making untouched blocks keep the ids of an editor without `NodeStructureExtension` would mean naming a load before `NodeStructureExtension`'s repairs, which run in a root transform registered before this extension's, and Lexical has no hook before the transforms of `setEditorState`.
- **`NodeStructureExtension` enabled after the editor is built.** Its repairs then run after this extension's naming in each pass. Edits give the same ids as above, but a load is named before the repairs: blocks the repairs keep get the positional ids of the document as it was before them, a list merged into another loses its id, and blocks the repairs create get ids from the document the load ends with.

Fuzz at 2,000 seeds per variant (`BLOCK_ID_FUZZ_SEEDS=2000`): v1 passes every seed, flat and nested. On v2, 55 seeds fail (7 flat, 48 nested). All 55 trace to the experimental `@lexical/yjs` v2 binding, not to this extension:
- 37 nested: when indent creates a nested list, the list's `blockId` is at its default (`$copyNode` resets it), and the v2 binding's create path writes that default into Yjs as an `undefined` attribute (its update path drops it). Receiving peers end with `"$": {"blockId": undefined}` on one peer (27) or throw on a stale list node inside the binding (10). The smallest repro is two steps on one peer: make a list, indent. A one-character change in the binding (`!== null` to `!= null` when it filters state attributes) removes all 37.
- 9 (6 flat, 3 nested): the v2 binding writes each Lexical child into whichever Y element of the same type sits at its position, so after concurrent moves an edit lands in another block's element. The binding then overwrites a block's `blockId` (last writer wins), writes one id onto two elements (the documented duplicate rule then renames one holder), or Yjs undo recreates an element without its attributes. The same minimized scripts pass on v1, and converge on v2 without the extension.
- 9 fail with the extension removed too (8 diverge or throw; 1 leaves an empty list element in Yjs that keeps the network from settling).

The v2 binding is not changed here.

Performance, on a headless 10,000-block document, with and without the extension, interleaved round by round (`BLOCK_ID_PERF=1 npx vitest --project unit --no-watch packages/lexical-extension/src/__tests__/unit/BlockIdExtension.perf.test.ts`, shared machine under load):

```
10000 blocks, median, interleaved  without      with     delta
keystroke (300)             14.755 ms    15.279 ms     0.524 ms
Enter (300)                 15.488 ms    17.675 ms     2.187 ms
paste 20 blocks (50)        17.742 ms    20.244 ms     2.502 ms
paste 50 blocks (50)        20.080 ms    24.029 ms     3.950 ms
remote duplicate (50)       24.987 ms    55.247 ms    30.260 ms
first load, no ids (12)    113.748 ms   296.409 ms   182.660 ms
  of which document key: 58.927 ms
load, ids stored (12)      135.323 ms   177.253 ms    41.930 ms
```

Across three runs the deltas moved by a few milliseconds (keystroke 0.4 to 0.9 ms, Enter 2.0 to 2.5 ms, paste of 50 blocks 3.5 to 4.0 ms, first load 174 to 183 ms, stored ids 37 to 42 ms, remote duplicate 29 to 30 ms). Three runs of the previous version of this PR, interleaved with these, fell in the same range (keystroke 0.6 to 0.8 ms, Enter 2.2 to 2.5 ms, paste of 50 blocks 3.5 to 3.9 ms, first load 180 to 185 ms, stored ids 34 to 39 ms, remote duplicate 29 to 32 ms); a load of these documents takes the same transform passes in both. A block without an id applied from another replica (written only by editors without the extension) gets a positional id, so that repair hashes the document once.

Not exercised: real browsers.

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change looks good. The policy in examples/node-state-identity/src/identity.ts does what its README says, and moving the walkthrough out of the NodeState page into the example's README follows the earlier maintainer feedback. All suggestions below are optional and non-blocking.

Suggestions

  1. Standalone build (examples/node-state-identity/tsconfig.json:2-7). The example extends the monorepo's root tsconfig.json and asks for types: ["node"]. In a checkout where only the example is installed, as the README describes, pnpm run build stops at tsc with TS2688: Cannot find type definition file for 'node', and inside the monorepo it type-checks against package sources rather than the pinned release. The sibling examples are standalone projects with a self-contained tsconfig (for example examples/vanilla-js/tsconfig.json); copying that and excluding src/__tests__ would fix both. pnpm run dev is unaffected.
  2. loadApplicationDocument may not be needed (src/identity.ts:74-85). setEditorState on a freshly parsed state already marks every node dirty and runs transforms (packages/lexical/src/LexicalEditor.ts:1793-1811), so the RootNode transform reads externalId on every node during the load. The suite still passes with the $getState read in the parse callback removed, including the test written for this case (identity.test.ts:235). Consider either dropping the helper and the README's "use loadApplicationDocument when restoring it", or keeping it for a load that happens before the policy is registered, with a test that fails without it.
  3. Test wiring (vitest.config.mts:85). The new glob also adds the agent-example and markdown-editor unit tests to the root unit run. Those examples carry their own test script and vitest.config.mts, which the release integration tests run from the example directory. Following that pattern would let this example's tests run on their own. Otherwise, a sentence in the PR saying the wider glob is intended would help.
  4. Package metadata nits (package.json:2-4). Sibling examples are named @lexical/<name>-example and are versioned with the monorepo, currently 0.51.0. This one keeps the dev- prefix from its earlier location and pins 0.50.0/0.0.0. The release script will bump the versions, but the name is worth fixing now.
  5. PR description. The body is empty, and the test plan in the first commit message refers to dev-examples/... paths. AGENTS.md ("Commits and Pull Requests") and .github/pull_request_template.md ask for a Description and a Test plan with the commands run and their real output.

Whether the NodeState concepts page should keep the short "Application identity" link section (packages/lexical-website/docs/concepts/node-state.md:342-348) is the maintainers' call. As written, it presents the example as one possible policy, which matches the earlier feedback. No changeset is needed for an example and a docs page.

Comment on lines +2 to +7
"extends": "../../tsconfig.json",
"compilerOptions": {
"types": ["node"],
"noEmit": true
},
"include": ["src", "../../libdefs/globals.d.ts"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: extending the monorepo root makes pnpm run build fail in a standalone install of this example (tsc reports TS2688: Cannot find type definition file for 'node', since @types/node is not a dependency and the inherited typeRoots points at the repo root). Inside the monorepo, the root paths also type-check it against package sources instead of the pinned release. A self-contained tsconfig like examples/vanilla-js/tsconfig.json, with src/__tests__ excluded, avoids both.

Comment on lines +79 to +83
const state = editor.parseEditorState(json, () => {
for (const {node} of $dfsWithSlots($getRoot())) {
$getState(node, externalIdState);
}
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: with the policy registered, setEditorState on a parsed state already marks every node dirty and runs the RootNode transform (packages/lexical/src/LexicalEditor.ts:1793-1811), and that transform reads externalId on every node. Plain editor.setEditorState(editor.parseEditorState(json)) therefore behaves the same, and the suite still passes with this read removed, including the test at identity.test.ts:235. Consider dropping the helper, or covering the case it is for (loading before the policy is registered) with a test that fails without it.

Comment thread vitest.config.mts
include: [
'packages/**/__tests__/unit/**/*.test{.ts,.tsx,.js,.jsx}',
'dev-examples/**/__tests__/unit/**/*.test{.ts,.tsx,.js,.jsx}',
'examples/**/__tests__/unit/**/*.test{.ts,.tsx,.js,.jsx}',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: this glob also adds examples/agent-example and examples/markdown-editor unit tests to the root run. Those examples have their own test script and vitest.config.mts, which the release integration tests run from the example directory. Giving this example the same setup would let its tests run standalone; if the wider glob is intended, a note in the PR would help.

@potatowagon
potatowagon added this pull request to the merge queue Nov 22, 2026
Merged via the queue into meta:main with commit a143f48 Nov 22, 2026
50 checks passed

This branch was successfully deployed

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants