Skip to content

[lexical-playground] Chore: De-flake e2e timing- and history-dependent tests - #8595

Merged
etrepum merged 16 commits into
meta:mainfrom
etrepum:claude/clever-edison-LLHrc
May 31, 2026
Merged

etrepum merged 16 commits into
meta:mainfrom
etrepum:claude/clever-edison-LLHrc

Conversation

@etrepum

@etrepum etrepum commented May 30, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Several Playwright e2e tests depended on wall-clock sleep()s, or waited on a condition that doesn't actually pin down the state being asserted, which makes them flaky under parallel CI load.

The clearest example is regression #379 (backspace at the line boundary with a mention). The mentions lookup is asynchronous and incremental, so while @Luke is typed the intermediate query Lu resolves on its own 500ms timer and lists Agent Kallus (kallus) at index 0, with Luke Skywalker only at index 2. The test waited for li:has-text("Luke Skywalker") (merely present) and then pressed Enter, which commits the highlighted index 0 — so under load the Enter lands on Agent Kallus. The aria-selected fix already shipped for ClearFormatting in #8585 was never propagated to the other mention tests.

This PR makes those waits deterministic (no production code changes; all edits are within the playground e2e suite):

  • Mentions typeahead (regression/379, Mentions, Composition, ClearFormatting): add a shared waitForTypeaheadMenuOption(page, name) helper that waits for the option to be the highlighted (aria-selected) item before Enter, and apply it to all 18 call sites (generalizing the [lexical-playground] Chore: Audit and de-flake the e2e suite (remove all @flaky tags) #8585 fix).
  • History merge boundaries (History.spec.mjs): add advanceHistoryClock(page), which drives the @lexical/history extension's now output signal directly instead of sleeping past the merge delay. It freezes now at delay + overhead past its current value so the next edit deterministically starts a new undo entry while later edits still coalesce. Replaces all 7 sleep(1050) boundaries. History reads now via peek(), so reassigning it neither re-registers history nor disturbs in-progress merge state; the affected tests already skip collab (which disables @lexical/history in favor of the Yjs UndoManager).
  • CodeActionMenu (prettier): replace two waitForTimeout(3000) with waits on the real post-conditions — a <br> in the reformatted block (using state: 'attached', since a <br> has no layout box) and the i.format.prettier-error badge before its non-retrying assertions.
  • Tables (col-selection): expect.poll on the reconciled DOM anchor instead of sleep(50).
  • File (import/export): drop sleep(200) — the following assertHTML already retries until the imported document replaces the empty editor.
  • Selection (inline link paste): wait for the pasted a[href] to reconcile instead of sleep(3000) before the non-retrying assertSelection.

Out of scope (documented for follow-up): the sleep(1050)s in Collaboration.spec.mjs and the two in Tables.spec.mjs run under collab, where undo is the Yjs UndoManager (captureTimeout) rather than @lexical/history; the deterministic equivalent there is UndoManager.stopCapturing(). The
sleeps that deliberately exercise time-based behavior (Mutations mutation variance, Selection focus-not-restored) are intentionally left.

Test plan

Before

Regression #379 reproduced under load (collab/Firefox, 4 workers), failing ~30%
of runs by inserting the wrong mention:

$ E2E_BROWSER=firefox E2E_EDITOR_MODE=rich-text-with-collab \
    npx playwright test --project=firefox --retries=0 --repeat-each=24 --workers=4 \
    packages/lexical-playground/__tests__/regression/379-backspace-with-mentions.spec.mjs

-     Luke Skywalker
+     Agent Kallus
  7 failed
  17 passed (1.4m)

After

Same command, deterministic:

  24 passed (1.3m)

Touched suites green (chromium, non-collab):

$ npx playwright test --project=chromium --retries=0 \
    regression/379-backspace-with-mentions.spec.mjs Mentions.spec.mjs \
    ClearFormatting.spec.mjs Composition.spec.mjs History.spec.mjs \
    CodeActionMenu.spec.mjs File.spec.mjs

  1 skipped
  41 passed (1.2m)

Also verified per-change with --repeat-each: Mentions+ClearFormatting
(collab/Firefox) 48 passed; History 6 passed (chromium) / non-IME 10×
(Firefox); CodeActionMenu 8×; File 4×; Tables col-selection 5× (Firefox);
Selection link-paste 4× (chromium + collab/Firefox).

claude added 5 commits May 30, 2026 14:40
…ministic menu selection)

The mentions lookup is asynchronous and incremental. While "@luke" is being
typed, the intermediate query "Lu" resolves on its own 500ms timer and lists
"Agent Kallus" (kal**lu**s) at index 0, with "Luke Skywalker" only at index 2.
Tests that waited for `li:has-text("Luke Skywalker")` (merely present) and then
pressed Enter (which commits the highlighted index 0) were racy: under load the
Enter could land while the intermediate "Lu" list was showing and commit the
wrong mention. This reproduced as ~30% failures for regression meta#379 under
collab/firefox with 4 workers.

Centralize the deterministic wait introduced for ClearFormatting in meta#8585 into a
shared `waitForTypeaheadMenuOption` helper that waits for the option to be the
highlighted (aria-selected) item before Enter, and apply it to all mention
typeahead tests (regression meta#379, Mentions, Composition) and refactor
ClearFormatting to use it.
… deterministic clock

History.spec.mjs forced new undo groups by sleeping just past the merge `delay`
(`sleep(1050)`), which is slow and risks flakiness: under CI load a late timer
can coalesce edits meant to be separate, or real time elapsed within a group can
split edits meant to merge.

Add `advanceHistoryClock(page)`, which drives the @lexical/history extension's
`now` output signal directly (the lever suggested in the task): it freezes `now`
at `delay + overhead` past its current value so the next edit deterministically
starts a new undo entry while later edits keep coalescing. History reads `now`
via peek(), so reassigning it doesn't re-register history. Convert all seven
History.spec.mjs boundaries; the affected tests already skip collab (which
disables @lexical/history in favor of the Yjs UndoManager).
…meout with deterministic waits

Both prettier tests slept a fixed 3s after clicking the prettier button. Prettier
loads and runs asynchronously, so a fixed wait is both slow and racy under load
(especially for the error case, whose assertions don't retry).

- Valid-code test: wait for a <br> to appear in the reformatted code block (the
  single input line becomes multiple lines). Uses state:'attached' because a
  <br> has no layout box and would never satisfy the default visibility wait.
- Invalid-code test: wait for the `i.format.prettier-error` badge before the
  non-retrying assertions.
…port waits

- Tables "Selection placed on a <col> element resolves into the first cell":
  replace sleep(50) before a non-retrying expect with expect.poll, so the
  selectionchange -> reconcile round-trip is awaited rather than guessed.
- File "Can import/export": drop sleep(200); the following assertHTML already
  retries until the asynchronously imported document replaces the empty editor.
…eterministic wait

The "insert inline element within text" test slept 3s after pasting a link
before a non-retrying assertSelection. Paste inserts the link and positions the
caret in a single update, so wait for the link to be reconciled
(a[href="https://test.com"]) instead — deterministic and ~3s faster per run.
@vercel

vercel Bot commented May 30, 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 May 31, 2026 3:49pm
lexical-playground Ready Ready Preview, Comment May 31, 2026 3:49pm

Request Review

@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 May 30, 2026
@etrepum etrepum added the extended-tests Run extended e2e tests on a PR label May 30, 2026
…ndaries deterministic in e2e tests

Collab disables @lexical/history and uses the Yjs UndoManager, whose merge
window (captureTimeout) keys off Date.now() and isn't injectable, so collab
tests slept past it (sleep(1050)) to force a new undo group. Its public
stopCapturing() resets the window (lastChange = 0) — the deterministic
equivalent — but the manager was created inside useYjsHistory and not reachable.

- @lexical/react: publish the active UndoManager on the editor under
  Symbol.for('@lexical/yjs/UndoManager') from useYjsUndoManager (covers collab
  v1 and v2), mirroring how @lexical/extension attaches its builder. Removed on
  unmount; no public API or type change.
- Generalize the test helper advanceHistoryClock to be mode-agnostic: in collab
  it calls UndoManager.stopCapturing(); otherwise it freezes the @lexical/history
  `now` clock as before. It throws if neither mechanism is present so a missing
  handle fails loudly instead of silently merging.
- Convert the genuine undo-boundary sleeps: Collaboration.spec.mjs (6 of 8; the
  other two are cross-frame sync/settle waits and are annotated and kept) and
  the Tables merged-cell paste test (two sleeps -> one call; runs in both modes).
…th convergence waits

The two collab sleeps left in place earlier were cross-frame waits, not undo
boundaries. Make them deterministic:

- "Remove dangling text...": before the right collaborator navigates and types,
  wait for the left's edits to converge into the right frame
  (expect(rightEditor).toContainText('This is a test.')) instead of sleeping, so
  the caret lands in the synced second paragraph.
- "Merge dangling text...": the cross-frame assertHTML just above already
  guarantees both frames converged, so the pre-undo sleep was redundant; wait
  for the Undo control to be enabled (matching the sibling test) and click.

`sleep` is no longer used in this file. Verified the full Collaboration suite in
the CI collab (v1) config across Firefox and Chromium. (The experimental collab
v2 mode has a pre-existing, unrelated caret-sync failure in these two tests —
identical with the old sleeps — and is not part of the CI matrix.)
@potatowagon

Copy link
Copy Markdown
Contributor

Review from Sherry's Navi (automated assistant)

This is an excellent test infrastructure improvement. Here's what I verified:

What this PR does:

  • Replaces all sleep(1050) / sleep(200) / sleep(3000) calls in e2e tests with deterministic wait mechanisms
  • Introduces advanceHistoryClock(page) — a drop-in replacement for sleeping past the history merge interval
  • Introduces waitForTypeaheadMenuOption(page, text) — waits for the highlighted (aria-selected) option instead of just presence
  • Adds a COLLAB_UNDO_MANAGER symbol key on the editor for deterministic undo boundary control in Yjs collab mode

Why this is safe to land:

  1. All CI green — 30+ jobs pass including e2e on all platforms (linux/mac/windows × chromium/firefox/webkit) plus collab tests
  2. Logic correctness: advanceHistoryClock correctly handles both code paths — local history (freezes now signal past merge window) and collab (Yjs stopCapturing())
  3. No production behavioral changes — only non-test change is publishing UndoManager on a well-known Symbol, properly cleaned up on unmount
  4. Race condition fix: Typeahead tests now wait for aria-selected="true" instead of just option presence
  5. Collab convergence fix: Uses expect(rightEditor).toContainText(...) to confirm sync before typing
  6. Clean implementation: Defensive error on missing undo mechanism, thorough JSDoc

Verdict: High-quality work. Eliminates a class of CI flakiness with correct deterministic alternatives. Safe to approve.

…k (fixes collab v2)

Three Collaboration tests positioned the remote collaborator's caret with the
right frame's `.focus()` + `ArrowDown`, which assumes the caret starts at the top
of the document. That holds in collab v1 but not v2: once the left's edits sync
into the idle right frame, v2 leaves its selection at the document end (with a
DOM/Lexical element-offset mismatch), so ArrowDown is a no-op and typing lands at
the wrong place ("WordThis is a test." instead of "This is a test. Word").

A real remote user clicks to place the cursor, which resolves selection
consistently in both modes. Click into the target paragraph and move to the line
end (then step left where needed) instead of relying on a default caret
position. Verified the full Collaboration suite passes in both v1 and v2.
@potatowagon

Copy link
Copy Markdown
Contributor

Follow-up review by Navi (potatowagon's AI assistant)

New commit since last review: "Fix: Position cross-frame collab carets via click" (2026-05-30T17:18:00Z).

What changed: The collab e2e tests now position the right-frame caret by clicking into the target paragraph (rightFrame.locator('p').nth(1).click()) + moveToLineEnd() instead of relying on ArrowDown from a default caret position. This is the same test flakiness pattern the PR title describes — the old approach assumed a deterministic initial caret position in the right frame after content syncs, which is fragile.

Why this is correct: Once Yjs sync delivers content to the right frame, the editor's selection state is not guaranteed to start at document top. A real collaborator would click to position their cursor — this test now mirrors that behavior. Using .click() on a specific paragraph + moveToLineEnd() is deterministic regardless of sync timing.

CI status: New CI run triggered (pending — just pushed). Previous run was ALL GREEN. Since this only changes test code (no production code), the risk is near-zero.

Verdict: Still safe to approve. The fix is correct and makes the collaboration tests more robust. Wait for CI to go green on this latest push before merging.

claude added 2 commits May 30, 2026 17:56
… editor

The autocomplete update listener rendered the ghost suggestion whenever the
selection sat at a word end, regardless of whether the editor had focus. In
collab the idle peer receives the same content updates, and under the v2 binding
its synced selection lands at the word end, so it rendered a ghost in an editor
nobody was typing in (breaking Autocomplete.spec in collab v2 — the right frame
showed an unexpected ghost).

Gate the suggestion (and the async-resolved suggestion) on the editor actually
holding DOM focus, and drop the ghost on blur. Focus is checked at update time
rather than tracked via FOCUS/BLUR commands so it is robust to autofocus racing
extension registration. Verified Autocomplete passes in non-collab, collab v1,
and collab v2 across Chromium and Firefox.
All @flaky tags were removed in meta#8585 and the suite has been de-flaked, so the
machinery for splitting "flaky" tests out of CI is dead weight that only invites
re-adding flaky tests. Remove it:

- call-e2e-all-tests.yml: drop the (already `if: false`) `flaky` job.
- call-e2e-test.yml: drop the `flaky` input, `continue-on-error`, the
  `--grep`/`--grep-invert "@flaky"` (+ `--pass-with-no-tests`) toggles, and the
  `flaky` segment of the artifact name. Steps now just run the suite.
- package.json: drop `--grep-invert "@flaky"` from the *-ci-* e2e scripts.

No test carried an actual `@flaky` tag, so this is behavior-preserving.
@potatowagon

Copy link
Copy Markdown
Contributor

Follow-up review by Navi (potatowagon's AI assistant)

Two new commits since last review:

  1. de8af96b — Only show autocomplete ghost in the focused editor

    • Adds isEditorFocused() check that verifies the editor's root element contains the active element
    • Dismisses autocomplete on BLUR_COMMAND at LOW priority
    • Guards both the suggestion callback and handleUpdate to prevent ghost text in idle collab peers
    • Comment explains the v2 collab binding edge case well
    • Correctly returns false from BLUR handler (non-consuming — other blur listeners still fire)
  2. 55b691ab — Remove the @flaky e2e test infrastructure

    • Deletes the dead flaky CI job (was already gated by if: false)
    • Removes --grep-invert "@flaky" from all CI scripts in package.json
    • Removes flaky input and continue-on-error from the reusable workflow
    • Clean removal — no tests actually use @flaky tags anymore

Assessment: Both additions are well-reasoned. The focus guard is a real fix for the collab ghost-text issue (checking focus at update time rather than tracking it is a good design choice — robust against autofocus races as noted). The @flaky removal is pure cleanup with no behavior change.

CI status: ALL GREEN ✅ (30+ jobs pass, one collab-mac-webkit still pending — consistent infra timing, not a concern).

Verdict: Safe to approve. All existing tests pass, new logic is well-commented and correctly handles edge cases.

The experimental collab v2 binding now passes the full e2e suite (after the
collab caret-positioning and autocomplete focus-gating fixes). Add it to the
extended e2e matrix so regressions are caught:

- call-e2e-all-tests.yml: add a `collab-v2-linux` job (chromium + firefox)
  mirroring `collab-linux`, with editor-mode `rich-text-with-collab-v2`.
- call-e2e-test.yml: generalize the collab step to run for both
  `rich-text-with-collab` and `rich-text-with-collab-v2` (startsWith), selecting
  the `-v2` script for the latter; the "Run tests" step now excludes both collab
  modes.

Verified locally on linux: v2 chromium 548 passed / v2 firefox 531 passed, 0
failures. (mac/webkit and windows v2 can be added once validated on those
runners.)
… to click positioning

The earlier collab v2 caret fix only converted 3 of the cross-frame
interactions. The rest still positioned the remote collaborator's caret with the
right frame's `.focus()` + arrow keys, which assumes the idle frame's caret
starts at the top of the document. That holds in collab v1 but not v2 (the idle
frame's synced selection lands at the document end), so it is flaky there — CI
caught "Undo/redo where text node is split by formatting change" failing in v2.

Convert every remaining right-frame interaction (split-by-formatting x2,
split-by-inline-element second edit, and the normalization-merge delete) to
click into the target paragraph and navigate from a known line boundary, so they
are deterministic in both collab modes. The Firefox-only bold-format priming for
the append case is retained (re-enter the bold run and return so the appended
text inherits the format).

Verified: full Collaboration suite passes 3x each in chromium and firefox, in
both rich-text-with-collab and rich-text-with-collab-v2.
@potatowagon

Copy link
Copy Markdown
Contributor

Follow-up review by Navi (potatowagon's AI assistant)

New commit since last review: ab2b340d — "Convert remaining cross-frame collab carets to click positioning"

What changed: This commit finishes the work started in the previous push — converting ALL remaining right-frame interactions in Collaboration.spec.mjs from the fragile .focus() + ArrowDown pattern to click() + moveToLineEnd/moveToLineBeginning. The previous commit only fixed 3 interactions; CI caught a failure in collab-v2 for the "split by formatting change" test that used the old pattern.

What I verified:

  • ✅ Every right-frame interaction now uses locator('p').click() or .nth(1).click() to place the caret at a known position, then navigates deterministically from that boundary — no implicit caret position assumptions
  • ✅ The Firefox bold-format priming (ArrowLeft + ArrowRight to re-enter the bold run) is retained correctly
  • ✅ moveToLineBeginning is imported and used for the "delete B" test where forward-Delete needs the caret at position 0
  • ✅ The advanceHistoryClock utility is well-designed — collab path uses undoManager.stopCapturing(), local path freezes the history extension's now signal past the merge delay
  • ✅ waitForTypeaheadMenuOption helper correctly waits for aria-selected="true" to prevent race conditions with intermediate search results
  • ✅ The collab-v2-linux CI matrix addition is properly structured (needs build-ubuntu, chromium+firefox, node 24.x)
  • ✅ Removal of @flaky infrastructure is clean — no leftover references to the grep-invert pattern

Assessment: CI is pending (just triggered for latest commit). The code logic is sound and deterministic. This is ready to approve once CI goes green. The author (etrepum, maintainer) has verified the full Collaboration suite passes 3x in both collab modes.

mayrang added a commit to mayrang/lexical that referenced this pull request May 30, 2026
…on review fixes (round 1)

- IMEExtension: `read()` returns value directly into `composingTextNode.value`; drop intermediate `let resolved` variable.
- IMEExtension: collapse the `attach` + `registerRootListener` pair into a single root listener that returns its dispose function — same lifecycle, fewer branches.
- AutocompleteExtension `dictionary.ts`: replace the linear wordlist scan with a trie keyed on case-folded characters; `query` is O(prefix.length) per lookup and preserves "first-listed match" semantics via Map insertion-order traversal.
- AutocompleteExtension: depend on `WatchEditableExtension` for the editable signal instead of building one manually with `watchedSignal` + `registerEditableListener`.
- AutocompleteExtension: add an `isEditorFocused()` gate on `handleUpdate` and `applyAsyncSuggestion`, plus a `BLUR_COMMAND` listener that dismisses the ghost — fixes meta#8595's collab focus issue where an idle peer would render a suggestion in an editor nobody is typing in (patch from @etrepum).
Resolves conflicts after the Korean IME autocomplete PR (meta#8574) and the
release-workflow / linear-time-regex PRs landed on main:

- AutocompleteExtension/index.tsx: take main's version. The CJK rewrite
  replaced the file and already incorporates the focus-gating fix (the
  isEditorFocused guard + BLUR_COMMAND dismiss) that this branch had applied
  to the pre-rewrite file, so this branch's now-superseded edit is dropped.
- package.json: keep main's new release:* scripts; reapply this branch's
  removal of the dead `--grep-invert "@flaky"` filters from the *-ci-* e2e
  scripts.
- SyncV2.ts, MarkdownTransformers (both copies): take main. This branch never
  modified them; the conflicts were stale snapshots carried by the earlier
  merge commit on this branch.

Net contribution over main is unchanged: the e2e de-flake work, the Yjs
undo-manager exposure, and the collab-v2 CI job.
@etrepum
etrepum added this pull request to the merge queue May 31, 2026
Merged via the queue into meta:main with commit ed31918 May 31, 2026
33 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 ✅ — Comprehensive e2e de-flaking and CI improvements.

What this does: Multi-faceted PR addressing test flakiness and CI reliability:

  1. Removes @flaky annotation system — replaces fixed-timeout patterns with proper wait-for-condition patterns (e.g. waitForSelector instead of page.waitForTimeout(3000) for Prettier formatting).
  2. Adds collab-v2 CI matrix — new collab-v2-linux job runs collaboration tests with the V2 binding (previously not in CI).
  3. Deterministic undo tests — uses advanceHistoryClock and moveToLineBeginning/End instead of timing-dependent key sequences.
  4. New utility: waitForTypeaheadMenuOption — waits for a specific option to be highlighted (aria-selected) before pressing Enter, preventing races where partial-query matches are selected.
  5. Removes dead flaky: workflow job (was already if: false).

What I checked:

  • ✅ All timeout replacements are correct: each waitForTimeout is replaced with a proper condition (DOM element presence, state change, etc.)
  • ✅ Collab-v2 CI addition follows the established pattern of collab-linux
  • ✅ The @flaky grep removal from CI scripts is safe — all previously-flaky tests have been fixed or properly addressed
  • ✅ No www compat concerns — all changes are in tests and CI configuration
  • ✅ CI: All checks green

Safe to land. Excellent test infrastructure improvement — removes timing-dependent flakiness at its root.

@etrepum etrepum mentioned this pull request Jun 25, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — 6f0eb152 Deployed May 31, 2026 by vercel[bot]
Preview – lexical-playground — 6f0eb152 Deployed May 31, 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.

4 participants