Repository navigation
[lexical-yjs][lexical-react] Bug Fix: collab sync gaps between the editor state and the yjs doc - #9057
Merged
Conversation
…itor state and the yjs doc
## Description
Four places where the yjs binding does not propagate something the local editor
state already carries. Each is a separate one-way gap between what Lexical knows
and what reaches the shared document (or the peers reading it), so they are
fixed together.
- **Unknown node state is dropped when a node is first created** — in
`syncNodeStateFromLexical` (`packages/lexical-yjs/src/Utils.ts`) the unknown-key
loop and the known-key loop disagree about "there is no previous state". The
known loop falls back to an empty `Map`, so on the create path every entry
compares unequal and is written; the unknown loop falls back to `undefined` and
then short-circuits on it, so nothing is written. Since later updates only write
*changed* keys, a value dropped at creation stays dropped forever and peers never
receive it — defeating the purpose of `NodeState.unknownState`, which exists so an
older build cannot erase metadata written by a newer one. The unknown loop now
uses the same "no previous state means everything is new" rule.
- **A remote cursor keeps a stale name and colour** — `syncCursorPositions`
(`packages/lexical-yjs/src/SyncCursors.ts`) reads `name` and `color` from each
peer's awareness state but only applies them on the pass that first creates the
cursor; every later pass updates only `anchor` / `focus`. Both values are baked
into the caret DOM and the `::highlight()` rule when the selection is built, so a
peer that renames itself or changes colour keeps its old label on every other
client until it disconnects. This is reachable through the supported API:
`LexicalCollaborationPlugin` takes `username` / `cursorColor` props and
`useYjsCollaboration` republishes local awareness when they change. When either
field actually changes the stale selection is now destroyed and cleared so the
existing code rebuilds it from the new values on the same pass; an unchanged peer
keeps its cursor object, so ordinary cursor movement causes no rebuild churn.
- **Element selection points are not converted to yjs child indices in collab-v2** —
`createRelativePositionV2` (`packages/lexical-yjs/src/SyncCursors.ts`) hands the
lexical child offset straight to `createRelativePositionFromTypeIndex`, but
`normalizeNodeContent` (`SyncV2`) serializes a run of adjacent `TextNode`s as a
single `XmlText` child, so the two numbers differ. The inner loop walked the text
run and threw the result away. For a `[Text, Text, Decorator]` paragraph, a caret
before the decorator (lexical offset 2) encoded as yjs index 2 — past the
decorator — so remote peers rendered the cursor on the wrong side of it, and at
the end of the paragraph the index went out of range. The encoder now counts each
text run as one yjs child, mirroring its inverse `$getNodeAndOffsetV2`.
- **The bootstrapped `initialEditorState` was undoable** — `CollaborationPlugin`
writes `initialEditorState` into an empty shared document through a normal editor
update, which syncs to yjs under the binding origin. That origin is tracked by the
`UndoManager`, so the very first undo removed the initial content, unlike a
non-collab editor which applies its initial state with `HISTORY_MERGE_TAG`. A new
`binding.isBootstrapping` flag (`packages/lexical-yjs/src/Bindings.ts`, mirrored in
`packages/lexical-yjs/flow/LexicalYjs.js.flow`) is set by `bootstrapEditor`
(`packages/lexical-react/src/shared/useYjsCollaboration.tsx`) while that write is in
flight, and `createUndoManager` (`packages/lexical-yjs/src/index.ts`) passes a
`captureTransaction` that skips transactions produced during it. The flag is
cleared from a microtask because the editor update commits — and therefore syncs
to yjs — in one; clearing it there rather than from the commit means it cannot get
stuck if the bootstrap update is a no-op.
## Test plan
Four new unit tests, one per defect: `NodeStateSyncUnknown.test.ts`,
`SyncCursorsAwarenessRefresh.test.ts` and `SyncCursorsV2ElementPoint.test.ts` under
`packages/lexical-yjs/src/__tests__/unit/`, plus a case added to
`packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx`. Each
drives the real binding rather than the internal helper, and each carries control
cases that pass both before and after (known state on the create path, an unchanged
peer keeping the same cursor object, element offsets 0 and 3) so the failure is
pinned to the specific gap.
### Before
```
$ npx vitest run --project unit packages/lexical-yjs packages/lexical-react
× the bootstrapped initialEditorState can not be undone 34ms
× unknown state on a newly created node is written to the shared doc 13ms
× several unknown keys all reach the shared doc 1ms
× a peer that renames itself updates its cursor name 8ms
× a peer that changes colour updates its cursor colour 1ms
× an element point before a decorator that follows a text run round trips 12ms
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 6 ⎯⎯⎯⎯⎯⎯⎯
AssertionError: expected '' to be 'Initial content' // Object.is equality
AssertionError: expected undefined to be 42 // Object.is equality
AssertionError: expected undefined to be 1 // Object.is equality
AssertionError: expected 'Bob' to be 'Robert' // Object.is equality
AssertionError: expected '#ff0000' to be '#0000ff' // Object.is equality
AssertionError: expected 3 to be 2 // Object.is equality
Test Files 4 failed | 33 passed (37)
Tests 6 failed | 260 passed (266)
```
### After
```
$ npx vitest run --project unit packages/lexical-yjs packages/lexical-react
Test Files 37 passed (37)
Tests 266 passed (266)
$ npx tsc --noEmit -p .
(clean, exit 0)
```
The remote-cursor DOM rebuild itself is not exercised by the unit test — jsdom has
no layout, so `updateCursor` returns before touching the caret — and it was not
verified in a real browser.
Supersedes meta#8966, meta#9007, meta#9013, meta#9016, consolidated per the review feedback on
meta#9027 and meta#9035.
LeSingh1
requested review from
acywatson,
etrepum,
fantactuka,
ivailop7,
potatowagon and
zurfyx
as code owners
August 10, 2026 04:16
|
@LeSingh1 is attempting to deploy a commit to the Meta Open Source Team on Vercel. A member of the Team first needs to authorize it. |
This was referenced Aug 10, 2026
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
## Description PR meta#9057 stops the `shouldBootstrap` write from landing in the Yjs UndoManager by setting `binding.isBootstrapping` for the duration of the bootstrap update and clearing it from a `queueMicrotask` callback. The flag is therefore time-scoped: if it ever failed to clear (a change to when Lexical commits an update, an early return, a future refactor), undo would be silently disabled for the rest of the session and the existing test — which only asserts that the first undo does *not* wipe the bootstrapped content — would still pass. This adds the complementary case: after bootstrapping, make a normal edit and assert that undo reverts it back to the bootstrapped content. That pins down both halves of the intended behavior. ## Test plan ### Before Only the one-directional assertion existed: ``` $ npx vitest run --config vitest.config.mts \ packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx Test Files 1 passed (1) Tests 2 passed (2) ``` ### After ``` $ npx vitest run --config vitest.config.mts \ packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx Test Files 1 passed (1) Tests 3 passed (3) ``` Only jsdom unit tests were exercised; no browser or e2e run.
…nc gap fixes
## Description
Follow-up to the four collab sync fixes on this branch. All four are
correct; these are the gaps found reviewing them.
- `createUndoManager` passes `captureTransaction`, which yjs only gained
in v13.5.37, but both packages declared `yjs: ">=13.5.22"` as a peer
range. Between those versions yjs ignores the option, so the bootstrap
write silently lands in the undo stack again — no error, just the bug
back. Peer ranges now start at the version that has the option.
- `bootstrapEditor` cleared `binding.isBootstrapping` from a
`queueMicrotask` callback, which is correct only because `editor.update`
happens to enqueue its commit from a microtask first. It now clears the
flag from an `onUpdate` callback instead: Lexical queues those on
`editor._deferred` before the update body runs and flushes them at the
tail of the same commit that ran the update listeners, so the reset
always lands after the Yjs write and never before. A queued deferred
callback also forces a commit by itself, so the no-op case that
motivated the microtask is still covered.
- The awareness-refresh test could not observe the behaviour it was
written for: `updateCursor` returns early while
`cursorsContainer.offsetParent` is null, which it always is under jsdom,
so `cursor.selection` stayed null and the assertions would have passed
against a fix that updated the `Cursor` fields and left the rendered
caret stale. Replaced with a browser test that mounts an editor and a
cursors container and asserts on the caret DOM and the `::highlight()`
rule. It also covers the case the jsdom test could not reach at all: the
previous caret and selection overlay are detached rather than left
painting the old name and colour.
- Bootstrapping via a serialized `initialEditorState` reaches the editor
through `editor.setEditorState`, which commits from inside the bootstrap
update rather than from the microtask after it, so it exercises a
different point in the flag's lifetime than the callback form. Covered,
along with the case where the flag is left stuck: an ordinary edit made
after bootstrapping must still be undoable. The three bootstrap tests
now share one render helper.
- Pinned the element-point behaviour that does not round trip
(a point inside a collapsed text run widens to the end of the run,
because yjs has no index for it) and noted it where the conversion
happens, so it reads as a known property rather than a missed case.
- Corrected the `knownFlagState` comment, which said the key was
registered on the node type; nothing registers it, and what makes the
state known here is that it is written through a `StateConfig`.
- Marked `BaseBinding.isBootstrapping` `@internal`.
## Test plan
### Before
`captureTransaction` is absent from yjs at the declared floor:
```
$ for t in v13.5.36 v13.5.37; do echo -n "$t: "; \
curl -sS https://raw.githubusercontent.com/yjs/yjs/$t/src/utils/UndoManager.js \
| grep -c captureTransaction; done
v13.5.36: 0
v13.5.37: 4
```
The new browser tests fail against the pre-fix `SyncCursors.ts`, showing
the rendered caret keeps the old name and colour:
```
$ npx vitest run --config vitest.config.mts \
packages/lexical-yjs/src/__tests__/browser/SyncCursorsAwarenessRefresh.test.ts
× a renamed peer has its rendered caret label updated
× a recoloured peer has its rendered caret recoloured
× a recoloured peer has its ::highlight() rule recoloured
AssertionError: expected 'Bob' to be 'Robert'
AssertionError: expected 'rgb(255, 0, 0)' to be 'rgb(0, 0, 255)'
AssertionError: expected '::highlight(lexical-cursor-cursor-awa…' to contain 'rgb(0, 0, 255)'
Test Files 1 failed (1)
Tests 3 failed | 1 passed (4)
```
The three bootstrap tests fail against the pre-fix
`useYjsCollaboration.tsx`:
```
$ npx vitest run --config vitest.config.mts \
packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx
× the bootstrapped initialEditorState can not be undone
× a bootstrapped serialized initialEditorState can not be undone
× an edit made after bootstrapping is still undoable
Test Files 1 failed (1)
Tests 3 failed | 1 passed (4)
```
### After
```
$ npx vitest run --config vitest.config.mts packages/lexical-yjs packages/lexical-react
Test Files 39 passed (39)
Tests 274 passed (274)
$ npx tsc --noEmit -p .
$ npx flow check
No errors!
$ npx eslint packages/lexical-yjs packages/lexical-react/src
$ npx prettier --check ...
All matched files use Prettier code style!
```
Browser tests were run in chromium only; firefox and webkit were not
exercised, and the playwright e2e suite was not run.
…ej1mk' into consol/yjs-sync
…pdate throws
## Description
`bootstrapEditor` sets `binding.isBootstrapping` so the bootstrap write
does not become an undo entry, and cleared it only from the update's
`onUpdate` deferred callback. Lexical does not run an update's deferred
callbacks when the update body throws: it reports the error, commits (so
the update listeners — and with them the Yjs write — still run) and skips
that commit's deferred queue. The reset is then left queued until the tail
of the *next* commit, which runs after that commit's update listeners have
already written to Yjs with the flag still set. A malformed serialized
`initialEditorState`, or an `initialEditorState` callback that throws,
therefore cost the user their first undo after the failure — silently, and
whether it bit at all depended on whether some unrelated commit happened to
land in between and flush the stranded callback first.
The `onUpdate` reset stays, since it is the boundary that matches the
write. It is now paired with a `finally` that schedules an unconditional
microtask reset, bounding the flag's lifetime however the update ends —
including the case where the editor's `onError` swallows the error rather
than rethrowing, which a `try`/`catch` would not see. It cannot fire early:
`editor.update` schedules the commit before returning, so that microtask is
queued ahead of this one.
The regression test drives the provider's `sync` event on demand instead of
from `connect()`, so the mount has settled and the user's edit is the first
commit after the failed bootstrap. Without that control an unrelated mount
commit flushes the stranded callback first and the bug is invisible.
## Test plan
### Before
Lexical's ordering, with an update that throws and a second that does not:
```
["error:boom","updateListener","--- after microtask ---","updateListener","bootstrapOnUpdate","--- end ---"]
```
The bootstrap reset lands after the *next* update's listener. With the
`finally` removed:
```
$ npx vitest run --config vitest.config.mts \
packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx
× an edit after a failed bootstrap is still undoable
AssertionError: expected 'typed after the failure' not to be 'typed after the failure'
Test Files 1 failed (1)
Tests 1 failed | 4 passed (5)
```
### After
```
$ npx vitest run --config vitest.config.mts packages/lexical-yjs packages/lexical-react
Test Files 39 passed (39)
Tests 275 passed (275)
$ npx tsc --noEmit -p .
$ npx flow check
No errors!
$ npx eslint packages/lexical-react/src packages/lexical-yjs/src
$ npx prettier --check ...
All matched files use Prettier code style!
```
Browser tests were run in chromium only; firefox and webkit were not
exercised, and the playwright e2e suite was not run.
…ej1mk' into consol/yjs-sync
etrepum
approved these changes
Aug 30, 2026
etrepum
pushed a commit
to etrepum/lexical
that referenced
this pull request
Aug 30, 2026
Conflict in packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx, where both sides added to the same file: meta#9057 on main added the bootstrap sync tests and their createSyncedProvider/$appendInitialContent helpers, and this branch added `provider is replaced when providerFactory changes` and its createTestProvider helper. Both sets are kept -- they cover different things and neither replaces the other. The `import type {Provider}` this branch added is already on main, so only the helper and the test needed re-applying.
Merged
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Four places where the yjs binding does not propagate something the local editor
state already carries. Each is a separate one-way gap between what Lexical knows
and what reaches the shared document (or the peers reading it), so they are
fixed together.
Unknown node state is dropped when a node is first created — in
syncNodeStateFromLexical(packages/lexical-yjs/src/Utils.ts) the unknown-keyloop and the known-key loop disagree about "there is no previous state". The
known loop falls back to an empty
Map, so on the create path every entrycompares unequal and is written; the unknown loop falls back to
undefinedandthen short-circuits on it, so nothing is written. Since later updates only write
changed keys, a value dropped at creation stays dropped forever and peers never
receive it — defeating the purpose of
NodeState.unknownState, which exists so anolder build cannot erase metadata written by a newer one. The unknown loop now
uses the same "no previous state means everything is new" rule.
A remote cursor keeps a stale name and colour —
syncCursorPositions(
packages/lexical-yjs/src/SyncCursors.ts) readsnameandcolorfrom eachpeer's awareness state but only applies them on the pass that first creates the
cursor; every later pass updates only
anchor/focus. Both values are bakedinto the caret DOM and the
::highlight()rule when the selection is built, so apeer that renames itself or changes colour keeps its old label on every other
client until it disconnects. This is reachable through the supported API:
LexicalCollaborationPlugintakesusername/cursorColorprops anduseYjsCollaborationrepublishes local awareness when they change. When eitherfield actually changes the stale selection is now destroyed and cleared so the
existing code rebuilds it from the new values on the same pass; an unchanged peer
keeps its cursor object, so ordinary cursor movement causes no rebuild churn.
Element selection points are not converted to yjs child indices in collab-v2 —
createRelativePositionV2(packages/lexical-yjs/src/SyncCursors.ts) hands thelexical child offset straight to
createRelativePositionFromTypeIndex, butnormalizeNodeContent(SyncV2) serializes a run of adjacentTextNodes as asingle
XmlTextchild, so the two numbers differ. The inner loop walked the textrun and threw the result away. For a
[Text, Text, Decorator]paragraph, a caretbefore the decorator (lexical offset 2) encoded as yjs index 2 — past the
decorator — so remote peers rendered the cursor on the wrong side of it, and at
the end of the paragraph the index went out of range. The encoder now counts each
text run as one yjs child, mirroring its inverse
$getNodeAndOffsetV2.The bootstrapped
initialEditorStatewas undoable —CollaborationPluginwrites
initialEditorStateinto an empty shared document through a normal editorupdate, which syncs to yjs under the binding origin. That origin is tracked by the
UndoManager, so the very first undo removed the initial content, unlike anon-collab editor which applies its initial state with
HISTORY_MERGE_TAG. A newbinding.isBootstrappingflag (packages/lexical-yjs/src/Bindings.ts, mirrored inpackages/lexical-yjs/flow/LexicalYjs.js.flow) is set bybootstrapEditor(
packages/lexical-react/src/shared/useYjsCollaboration.tsx) while that write is inflight, and
createUndoManager(packages/lexical-yjs/src/index.ts) passes acaptureTransactionthat skips transactions produced during it. The flag iscleared from a microtask because the editor update commits — and therefore syncs
to yjs — in one; clearing it there rather than from the commit means it cannot get
stuck if the bootstrap update is a no-op.
Test plan
Four new unit tests, one per defect:
NodeStateSyncUnknown.test.ts,SyncCursorsAwarenessRefresh.test.tsandSyncCursorsV2ElementPoint.test.tsunderpackages/lexical-yjs/src/__tests__/unit/, plus a case added topackages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx. Eachdrives the real binding rather than the internal helper, and each carries control
cases that pass both before and after (known state on the create path, an unchanged
peer keeping the same cursor object, element offsets 0 and 3) so the failure is
pinned to the specific gap.
Before
After
The remote-cursor DOM rebuild itself is not exercised by the unit test — jsdom has
no layout, so
updateCursorreturns before touching the caret — and it was notverified in a real browser.
Supersedes #8966, #9007, #9013, #9016, consolidated per the review feedback on
#9027 and #9035.