Skip to content

[lexical-yjs] Bug Fix: Local range selection grows when collaborator … - #8611

Merged
etrepum merged 4 commits into
meta:mainfrom
sahiee-dev:fix/yjs-selection-right-edge-growth
Jun 3, 2026
Merged

etrepum merged 4 commits into
meta:mainfrom
sahiee-dev:fix/yjs-selection-right-edge-growth

Conversation

@sahiee-dev

Copy link
Copy Markdown
Contributor

Description

Current behavior:

When two users edit the same document via @lexical/yjs, a remote user typing immediately after the right edge of a local user's range selection causes that selection to silently expand to include the newly typed characters. This also means the expanded text lands in the clipboard if the local user presses Ctrl+C — a silent content leak.

Root cause: createRelativePosition and createRelativePositionV2 in SyncCursors.ts call Y.createRelativePositionFromTypeIndex without passing the third assoc argument, so it defaults to 0 (right-associated) for both endpoints. A right-associated position at the end of an XmlText resolves to type._length after every insert — drifting the right edge of the selection rightward with each new character typed by a remote peer.

Changes introduced by this PR:

For a non-collapsed range selection, each endpoint now receives the correct associativity:

  • Left endpoint (assoc = 0): anchors to the first selected character — insertions before the selection stay outside.
  • Right endpoint (assoc = -1): anchors to the last selected character — insertions after the selection stay outside.
  • Collapsed carets keep assoc = 0 on both sides (unchanged) so the caret follows typing normally.

The assoc parameter is threaded through createRelativePosition (V1) and both return sites of createRelativePositionV2 (text path and element path). The Flow libdef for createRelativePositionFromTypeIndex is updated to accept the optional third argument. No protocol or schema change — RelativePosition.assoc is already encoded in the Yjs wire format; older peers ignore the field.

Closes #8608

Test plan

Before

Steps to reproduce (documented in #8608):

  1. Open the same collaborative document in two tabs
  2. Tab A: select a word or phrase
  3. Tab B: type immediately after the end of Tab A's selection
  4. Tab A's selection visibly expands to include the newly typed characters
  5. Tab A presses Ctrl+C — clipboard contains the original text plus Tab B's characters

After

Regression test added in packages/lexical-react/src/__tests__/unit/Collaboration.test.ts inside the existing describe.each([[false], [true]]) block, covering both V1 and V2 binding paths:

  • Client 1 inserts "foo bar" and sets a forward range selection over it
  • Client 2 appends "ZZZ" at the right edge of that selection
  • Asserts sel.getTextContent() === 'foo bar' on client 1 after the Yjs update propagates

Run with:

pnpm run test-unit

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

vercel Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
lexical Ready Ready Preview, Comment Jun 2, 2026 7:00pm
lexical-playground Ready Ready Preview, Comment Jun 2, 2026 7:00pm

Request Review

@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.

The unit tests fail and the prettier check is also failing pnpm run ci-check and pnpm run test-unit can be used locally to reproduce these failures.

@sahiee-dev

Copy link
Copy Markdown
Contributor Author

Hi @etrepum,

While reproducing the unit test failure, I found that the original regression assertion (checking the local selection text after a remote update) doesn't appear to be stable in the shared collaboration test harness, since the local selection state doesn't reliably survive the round-trip in that environment.

I have an alternative regression test that validates the underlying invariant directly instead:

  • verifies the range selection's right endpoint is serialized with assoc = -1
  • resolves that position before and after a remote insertion
  • verifies the resolved index does not drift

The test still runs through both V1 and V2 binding paths and is specifically validating the behavior fixed by this change.

Would you prefer that approach, or would you rather keep the regression test focused on observable selection behavior?

Happy to implement either approach, I just wanted to confirm before making assumptions about the preferred testing strategy here.

@potatowagon

Copy link
Copy Markdown
Contributor

Review (Navi — Sherry's AI assistant)

The core logic in this PR is sound and well-reasoned:

✅ What I verified:

  • The assoc = -1 approach for the right endpoint of non-collapsed ranges correctly prevents selection drift when remote collaborators insert at the boundary
  • Both V1 and V2 binding paths are properly covered with the same fix pattern
  • The isBackward handling is correct: when backward, anchor is the rightmost point (gets assoc=-1), otherwise focus is
  • Collapsed selections correctly keep assoc=0 on both sides, preserving existing caret behavior
  • The Flow type addition to libdefs/yjs.js for the optional assoc parameter is accurate
  • The regression test logic is a clean demonstration of the bug fix

⚠️ CI Status:

  • core-tests/integrity and core-tests/unit (Node 22.x + 24.x) are still failing
  • All e2e tests pass (including all collab suites across chromium/firefox/webkit on all platforms)

Assessment: The production code is correct and safe. Waiting on test fix (author discussing approach with maintainer). NOT ready to approve until CI green.

@etrepum

etrepum commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator

Writing an e2e test instead of a unit test would be the typical approach when a real browser environment is better

@sahiee-dev

Copy link
Copy Markdown
Contributor Author

Hi again @etrepum,

I investigated an e2e approach and put together a prototype in Collaboration.spec.mjs to see whether this regression could be exercised in a real browser environment.

After running it both with and without the fix applied, the test produced the same result in both cases, so it wasn't able to distinguish the broken behavior from the fixed behavior.

I added some diagnostics while tracing through the synchronization path and confirmed that the local selection state changes during the collaboration update in a way that causes both code paths to converge on the same observable result in this test setup. As a result, I wasn't able to construct a reliable e2e regression test for this issue using the current collaboration harness.

The unit test, on the other hand, consistently fails without the fix and passes with it because it asserts the underlying Yjs relative position invariant directly rather than relying on browser level selection behavior.

Before making further changes, I wanted to check what direction you'd prefer here:

  • keep the unit level regression test,
  • pursue a different e2e strategy,
  • or test this at a different layer of the collaboration stack.

Happy to continue in whichever direction you think is most appropriate.

@etrepum

etrepum commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator

Any approach that you can write a passing test for, that fails without the patch, is fine so long as it doesn't cause other regressions (unless those regressions are test expectations that specifically look for the behavior that this is changing, in which case the expectations should change).

…types at right edge (meta#8608)

Regression test rewritten to assert the Yjs relative-position invariant
directly (focusPos.assoc === -1, resolved index stable after remote insert)
instead of relying on selection state surviving a jsdom round-trip.
@sahiee-dev

Copy link
Copy Markdown
Contributor Author

Thanks for clarifying.

I've updated the regression test to assert the underlying relative-position invariant directly.

I verified that the test fails without the patch and passes with the patch for both the V1 and V2 collaboration bindings. I've also rerun pnpm run test-unit and pnpm run ci-check locally.

The updated test and fix have now been pushed.

@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.

Looks good, confirmed with manual two-browser QA that it behaves correctly in a real situation. Refactored the tests a little bit to use RangeSelection APIs for selection/input which is a bit closer to how the editors work with real input.

@etrepum
etrepum added this pull request to the merge queue Jun 3, 2026
Merged via the queue into meta:main with commit 931abba Jun 3, 2026
36 checks passed

@potatowagon potatowagon left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed by Navi (Tater Thoughts Bobblehead) on behalf of @potatowagon.

LGTM ✅ — Solid fix for collaborative selection growth bug (#8608).

What this does: Fixes a bug where a local user's range selection would incorrectly grow to include text typed by a remote collaborator at the selection boundary. The fix passes assoc (association) parameters to Yjs createRelativePositionFromTypeIndex so that the right endpoint of a selection sticks to the last selected character (assoc=-1) rather than drifting rightward when remote inserts land at the boundary.

What I checked:

  • ✅ Logic correctness: The assoc assignment is correct — for a forward selection (non-backward), the focus is the right edge and needs assoc=-1 (left-sticky), while the anchor is the left edge and keeps assoc=0 (right-sticky). For backward selections, the roles reverse correctly. Collapsed carets keep assoc=0 on both sides (preserving existing typing-follows-caret behavior).
  • ✅ Both V1 and V2 bindings: The fix is applied symmetrically to createRelativePosition (V1) and createRelativePositionV2 (V2).
  • ✅ Flow types updated: libdefs/yjs.js correctly adds the optional assoc?: number parameter to match yjs's actual API signature.
  • ✅ Comprehensive test: The new test (95 lines) validates that after a remote insert at the right edge of a selection, the relative position resolves to the same index as before — with clear documentation explaining why the test asserts on RelativePosition rather than $getSelection() (shared global document selection limitation of the test harness).
  • ✅ www compat: No breaking changes to exports or public API. The assoc parameter is purely internal to SyncCursors. Meta's internal www codebase consuming lexical-yjs won't be affected.
  • ✅ CI: All checks green (CLA, core-tests, e2e-tests, Vercel).

Safe to land. Clean, well-tested fix for a real collaborative editing UX bug.

@etrepum etrepum mentioned this pull request Jun 25, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — 27eddb01 Deployed Jun 2, 2026 by vercel[bot]
Preview – lexical-playground — 27eddb01 Deployed Jun 2, 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. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Local range selection silently grows when a collaborator types at its right edge

3 participants