← Back to Pull requests

[lexical-y] Bug Fix: A remote change applied during a local update no longer loses that update's edits #9784

Merged
zurfyx merged 7 files (1922 lines) on Nov 05, 2026 02:14 UTC
View on GitHub
zurfyx zurfyx commented on Nov 04, 2026 12:34 UTC
Author

Description

A remote change Yjs applies while the editor has a local update pending (a provider calling Y.applyUpdate from inside editor.update(), from a command dispatched in it, or between editors on one page connected by a synchronous provider) was read inside that update. readChange commits and writes a pending local update before a remote read (commitPending), but it cannot inside an update, so the read ran nested in it: it replaced the lines the change touched with what the document stored, which did not hold the update's edits yet, and the update's commit took the read's collaborator tags, so onUpdate wrote none of it. Text typed in that update was lost, in the editor and in the document, on every client, with gc on and off:

  • append X inside editor.update(), then apply a remote change (a collaborator bolds one in one two) before the callback returns: every client shows one two (bold one);

  • the same with the change applied first, from a command dispatched in the update, or in a non-discrete update.
  • The binding now defers such a change. While the editor is updating and the update is not one of the binding's own (its reads, writes, scans and undos read changes where they run, as before), a remote change stays unread (the existing Unread view, which the local update is written on, as an update committed before a read is) and is read once that update has committed and been written:

  • applied inside an update (in its callback, a command or a transform): right after the update's commit, in a commit of its own, queued ahead of the updates the app queued meanwhile;

  • applied from a commit's listeners or $onUpdate callbacks (where the app may also queue an edit of its own, which Lexical would merge into the read's update): in an update of its own ahead of the app's, whose updates then commit, and are written, after it;

  • where the update does not commit (it threw, or changed nothing, which Lexical does not commit): once the editor is idle, in a microtask.
  • Later remote changes, applied inside an update or outside one while changes are deferred, are read after the deferred ones, in the order Yjs applied them, one at a time (those still deferred stay unread while each is read); after a read that is only queued (nested in the update queued first), the rest are read once that update has committed, so each caret is taken on a state that shows the changes before it. The self-check waits while changes are deferred or unread and then checks every container their reads rebuilt. Each write, and each cursor taken while changes are unread (getCursor() and the caret an undo step restores included, in a transaction that changes nothing, or in the one running), first splits the items at the bounds of the unread changes, which Yjs merges with neighbouring items of the same client once their transaction ends, so the Unread view tells them apart by item. With gc on, the binding wraps the document's gcFilter while a change is deferred, so Yjs does not collect what it deleted until its read has committed: the text the editor still shows is still there for the writes in between, and anyone's keep stays theirs. A read marks its change read as soon as the editor shows it, so what the app does on that read's commit sees it as read. The selection a deferred read keeps is the editor's when it reads (the update's final caret), not the one before the update; where the binding's view would place it in a node a later change already removed from the editor, the editor's own selection, or else the one the document as it is gives, is kept. queueFirst hands the updates queued behind it back after its own update commits, or once the editor is idle where a commit listener throws before Lexical runs the update's callbacks.

    Behavior change: a remote change applied inside editor.update() now shows in a commit of its own, tagged as a collaborator's change, right after the update's commit, instead of in that commit. It was never visible inside the callback (the read already ran after it); update listeners now see the local commit, written, then the remote one, where they saw one merged commit that lost the local edit.

    Test plan

    New regressions/RemoteChangeInsideUpdate.test.ts, gc off and on: a remote change applied inside editor.update() after and before a local edit, in a node transform, in a command dispatched inside the update, in an update listener, between two queued updates, in a non-discrete update, two changes in one update, an update that throws after applying the change, undoing the local edit afterwards, the order of the two commits (the local one, written, then the remote one, tagged as a collaborator's change), on a remote read's commit with an edit queued before or after the change is applied or both in an $onUpdate callback, a remote change arriving during a deferred read's commit, an edit a listener makes on the local commit (registered before and after the binding), a deferred change Yjs merged into an item of text the editor shows (and the caret a deferred read keeps there), text a deferred change deletes next to text deleted before (gc on), an app's UndoManager that keeps what a deferred change deleted, a deferred deletion once the app replaced the gcFilter, a binding started again before a deferred change was read, a deferred change that joins two lines (gc on), two remote changes in a committing update with the first before the caret (and with the first having nothing to read, both read before editor.update() returns), three remote inserts before the caret in a committing update (one change per remote commit, the next keystroke after the local edit), a later deferred change removing the table column holding the caret, two in an update that changes nothing with the second on another line (no self-check warning), the self-check still covering what an earlier deferred change read, a remote change a provider applies from a document observer, a remote change applied outside an update while an earlier one waits, an app's document observer that takes the cursor while a change waits, the cursor an app takes while a change Yjs merged into shown text waits or from every transaction while a deferred change with deletions is read, the caret an undo restores where Yjs merged a deferred change into shown text, and the caret the update set or left after its edit. Each checks the editor's text, convergence and the editor against a fresh read.

    Before

    On main a983160a (pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/RemoteChangeInsideUpdate.test.ts, gc off; the same with LEXICAL_Y_GC=1):

         × inside editor.update, after a local edit
         × inside editor.update, before a local edit
         × in a command dispatched inside editor.update
         × inside a non-discrete editor.update
         × two remote changes inside one update, read in order
         × an update that throws after the remote change is applied
         × the local update commits and is written first, then the remote change in a commit of its own
         × on a remote read's commit, edit queued, then the change applied
         × on a remote read's commit, the change applied, then an edit queued
         × on a remote read's commit, an edit queued and the change applied in an $onUpdate callback
         × an edit a listener makes on the local commit, registered after the binding
         × an edit a listener makes on the local commit, registered before the binding
         × a binding started again before a deferred change was read
         × the caret stays after the local edit
         × a deferred change that joins two lines, read in an update queued first
         × two remote changes in a committing update, the first before the caret
         × two remote inserts before the caret in a committing update
         × an app's document observer that takes the cursor while a change waits
         × the cursor an app takes while a change Yjs merged into shown text waits
         × the cursor an app takes from every transaction while a deferred change with deletions is read
         × the caret an undo restores, where Yjs merged a deferred change into shown text
         × a remote change a provider applies from a document observer, removing what a deferred read rebuilt
    AssertionError: expected 'one two' to be 'one twoX' // Object.is equality
    AssertionError: expected 'one two!' to match /^one two(X!|!X)$/
    AssertionError: expected 'paragraph("one"{1} " two")' to be 'paragraph("one two")' // Object.is equality
    AssertionError: expected [ { collab: true, …(2) } ] to deeply equal [ { collab: false, …(2) }, …(1) ]
          Tests  45 failed | 37 passed (82)
    

    After

     ✓ |unit| packages/lexical-y/src/__tests__/unit/regressions/RemoteChangeInsideUpdate.test.ts (82 tests)
          Tests  82 passed (82)
    $ LEXICAL_Y_GC=1 pnpm exec vitest run --project unit (same file)
          Tests  82 passed (82)
    

    vitest run --project unit packages/lexical-y, gc off and on:

     Test Files  268 passed | 2 skipped (270)
          Tests  19788 passed | 379 expected fail | 131 skipped (20298)
     Test Files  268 passed | 2 skipped (270)
          Tests  19785 passed | 382 expected fail | 131 skipped (20298)
    

    GuardedRead.test.ts N6 (a read admitted before the binding fails closed reads nothing after it) applied its layout change inside an update that changed nothing: that read now runs after the update, and an update that changes nothing never commits, so the failed read's commit no longer ran the test's listener. Its update now also moves the caret, so the failed read's commit runs the listener as before; the cell asserts the same outcome, and passes on main with the new setup too.

    Diff: 1922 lines (+1894 / -28) across 7 files Reviewer: zurfyx Review duration: 820m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.66) × (1 − Review Confidence (0.66)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.66 · 1922 lines diff across 7 files
    0.66
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.56 · 5 substantive comment(s)
    0.56
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    65%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Real PR Conversation Timeline
    54 items
    vercel[bot] vercel[bot] commented on Nov 04, 2026 12:34 UTC
    Bot

    [vc]: #Gr6BpBZ8VAdStwCA86EpuOcgEFQ7gX8JVNhwp6ZwQY8=:eyJpc01vbm9yZXBvIjp0cnVlLCJ0eXBlIjoiZ2l0aHViIiwicHJvamVjdHMiOlt7Im5hbWUiOiJsZXhpY2FsIiwicHJvamVjdElkIjoicHJqX01SYU1PMzFlRklrWTYxU0JxcVBEUjJPank4cVAiLCJ2MCI6ZmFsc2UsInJvb3REaXJlY3RvcnkiOiJwYWNrYWdlcy9sZXhpY2FsLXdlYnNpdGUiLCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vZmJvcGVuc291cmNlL2xleGljYWwvNDZOc0pRWVhBU3ZEMXZVWVJETnh5VUE5R0xuaSIsInByZXZpZXdVcmwiOiJsZXhpY2FsLWdpdC16dXJmeXgteS1yZWFkLWluc2lkZS11cGRhdGUtZmJvcGVuc291cmNlLnZlcmNlbC5hcHAiLCJuZXh0Q29tbWl0U3RhdHVzIjoiREVQTE9ZRUQifSx7Im5hbWUiOiJsZXhpY2FsLXBsYXlncm91bmQiLCJwcm9qZWN0SWQiOiJwcmpfZWE4MnZMajY4NFh6U1JkZU83SlNkMFFOa2F3cyIsInYwIjpmYWxzZSwicm9vdERpcmVjdG9yeSI6InBhY2thZ2VzL2xleGljYWwtcGxheWdyb3VuZCIsImluc3BlY3RvclVybCI6Imh0dHBzOi8vdmVyY2VsLmNvbS9mYm9wZW5zb3VyY2UvbGV4aWNhbC1wbGF5Z3JvdW5kL0RMWjUxaGtIelFibXprNmNIYlFlTFFUR1V6b1YiLCJwcmV2aWV3VXJsIjoibGV4aWNhbC1wbGF5Z3JvdW5kLWdpdC16dXJmeXgteS1yZWFkLWluc2lkZS11cGRhdGUtZmJvcGVuc291cmNlLnZlcmNlbC5hcHAiLCJuZXh0Q29tbWl0U3RhdHVzIjoiREVQTE9ZRUQifV0sInJlcXVlc3RSZXZpZXdVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vdmVyY2VsLWFnZW50L3JlcXVlc3QtcmV2aWV3P293bmVyPW1ldGEmcmVwbz1sZXhpY2FsJnByPTk3ODQifQ==
    The latest updates on your projects. Learn more about Vercel for GitHub.

    | Project | Deployment | Actions | Updated |
    | :--- | :----- | :------ | :------ |
    | <a href="https://vercel.com/fbopensource/lexical"><sup><img src="https://vercel.com/api/www/avatar?projectId=prj_MRaMO31eFIkY61SBqqPDR2Ojy8qP&teamId=team_QNIQyH5DJlqUjeCckcCcBEjE&s=32" width="16" height="16" align="middle" alt="" /></sup></a> lexical | !Ready Ready | Preview | <relative-time datetime="2026-11-05T01:13:03.959Z">Nov 5, 2026 1:13am UTC</relative-time> |
    | <a href="https://vercel.com/fbopensource/lexical-playground"><sup><img src="https://vercel.com/api/www/avatar?projectId=prj_ea82vLj684XzSRdeO7JSd0QNkaws&teamId=team_QNIQyH5DJlqUjeCckcCcBEjE&s=32" width="16" height="16" align="middle" alt="" /></sup></a> lexical-playground | !Ready Ready | Preview | <relative-time datetime="2026-11-05T01:13:03.959Z">Nov 5, 2026 1:13am UTC</relative-time> |

    <a href="https://vercel.com/vercel-agent/request-review?owner=meta&repo=lexical&pr=9784" rel="noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://agents-vade-review.vercel.sh/request-review-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://agents-vade-review.vercel.sh/request-review-light.svg"><img src="https://agents-vade-review.vercel.sh/request-review-light.svg" alt="Request Review"></picture></a>

    meta-code-review[bot] meta-code-review[bot] commented on Nov 04, 2026 12:34 UTC
    Bot

    AI review status for this pull request.

    | Review status | Updated |
    | :--- | :--- |
    | 🔄 In progress (for maintainers only) | <relative-time datetime="2026-11-05T02:04:56Z">Nov 5, 2026, 2:04 AM UTC</relative-time> |

    <!-- codebunny-status:1 r=318341089 p=9784 rv=2 -->

    pkg-pr-new[bot] pkg-pr-new[bot] commented on Nov 04, 2026 12:37 UTC
    Bot

    <details><summary><b>lexical</b></summary><p>

      npm i https://pkg.pr.new/lexical@9784
      


    </p></details>

    <details><summary><b>@lexical/a11y</b></summary><p>

      npm i https://pkg.pr.new/@lexical/a11y@9784
      


    </p></details>

    <details><summary><b>@lexical/clipboard</b></summary><p>

      npm i https://pkg.pr.new/@lexical/clipboard@9784
      


    </p></details>

    <details><summary><b>@lexical/code</b></summary><p>

      npm i https://pkg.pr.new/@lexical/code@9784
      


    </p></details>

    <details><summary><b>@lexical/code-core</b></summary><p>

      npm i https://pkg.pr.new/@lexical/code-core@9784
      


    </p></details>

    <details><summary><b>@lexical/code-prism</b></summary><p>

      npm i https://pkg.pr.new/@lexical/code-prism@9784
      


    </p></details>

    <details><summary><b>@lexical/code-shiki</b></summary><p>

      npm i https://pkg.pr.new/@lexical/code-shiki@9784
      


    </p></details>

    <details><summary><b>@lexical/compiler</b></summary><p>

      npm i https://pkg.pr.new/@lexical/compiler@9784
      


    </p></details>

    <details><summary><b>@lexical/devtools-core</b></summary><p>

      npm i https://pkg.pr.new/@lexical/devtools-core@9784
      


    </p></details>

    <details><summary><b>@lexical/dragon</b></summary><p>

      npm i https://pkg.pr.new/@lexical/dragon@9784
      


    </p></details>

    <details><summary><b>@lexical/eslint-plugin</b></summary><p>

      npm i https://pkg.pr.new/@lexical/eslint-plugin@9784
      


    </p></details>

    <details><summary><b>@lexical/extension</b></summary><p>

      npm i https://pkg.pr.new/@lexical/extension@9784
      


    </p></details>

    <details><summary><b>@lexical/fast-check</b></summary><p>

      npm i https://pkg.pr.new/@lexical/fast-check@9784
      


    </p></details>

    <details><summary><b>@lexical/file</b></summary><p>

      npm i https://pkg.pr.new/@lexical/file@9784
      


    </p></details>

    <details><summary><b>@lexical/hashtag</b></summary><p>

      npm i https://pkg.pr.new/@lexical/hashtag@9784
      


    </p></details>

    <details><summary><b>@lexical/headless</b></summary><p>

      npm i https://pkg.pr.new/@lexical/headless@9784
      


    </p></details>

    <details><summary><b>@lexical/history</b></summary><p>

      npm i https://pkg.pr.new/@lexical/history@9784
      


    </p></details>

    <details><summary><b>@lexical/html</b></summary><p>

      npm i https://pkg.pr.new/@lexical/html@9784
      


    </p></details>

    <details><summary><b>@lexical/internal</b></summary><p>

      npm i https://pkg.pr.new/@lexical/internal@9784
      


    </p></details>

    <details><summary><b>@lexical/link</b></summary><p>

      npm i https://pkg.pr.new/@lexical/link@9784
      


    </p></details>

    <details><summary><b>@lexical/list</b></summary><p>

      npm i https://pkg.pr.new/@lexical/list@9784
      


    </p></details>

    <details><summary><b>@lexical/mark</b></summary><p>

      npm i https://pkg.pr.new/@lexical/mark@9784
      


    </p></details>

    <details><summary><b>@lexical/markdown</b></summary><p>

      npm i https://pkg.pr.new/@lexical/markdown@9784
      


    </p></details>

    <details><summary><b>@lexical/mdast</b></summary><p>

      npm i https://pkg.pr.new/@lexical/mdast@9784
      


    </p></details>

    <details><summary><b>@lexical/offset</b></summary><p>

      npm i https://pkg.pr.new/@lexical/offset@9784
      


    </p></details>

    <details><summary><b>@lexical/overflow</b></summary><p>

      npm i https://pkg.pr.new/@lexical/overflow@9784
      


    </p></details>

    <details><summary><b>@lexical/plain-text</b></summary><p>

      npm i https://pkg.pr.new/@lexical/plain-text@9784
      


    </p></details>

    <details><summary><b>@lexical/react</b></summary><p>

      npm i https://pkg.pr.new/@lexical/react@9784
      


    </p></details>

    <details><summary><b>@lexical/rich-text</b></summary><p>

      npm i https://pkg.pr.new/@lexical/rich-text@9784
      


    </p></details>

    <details><summary><b>@lexical/selection</b></summary><p>

      npm i https://pkg.pr.new/@lexical/selection@9784
      


    </p></details>

    <details><summary><b>@lexical/table</b></summary><p>

      npm i https://pkg.pr.new/@lexical/table@9784
      


    </p></details>

    <details><summary><b>@lexical/tailwind</b></summary><p>

      npm i https://pkg.pr.new/@lexical/tailwind@9784
      


    </p></details>

    <details><summary><b>@lexical/text</b></summary><p>

      npm i https://pkg.pr.new/@lexical/text@9784
      


    </p></details>

    <details><summary><b>@lexical/utils</b></summary><p>

      npm i https://pkg.pr.new/@lexical/utils@9784
      


    </p></details>

    <details><summary><b>@lexical/y</b></summary><p>

      npm i https://pkg.pr.new/@lexical/y@9784
      


    </p></details>

    <details><summary><b>@lexical/yjs</b></summary><p>

      npm i https://pkg.pr.new/@lexical/yjs@9784
      


    </p></details>

    _commit: <a href="https://github.com/meta/lexical/runs/126981704714"><code>ce2e415</code></a>_

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 12:53 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -2785,6 +2806,14 @@ export class YBinding {
       }
     
       private onAfterTransaction(tr: Transaction): void {
    +    if (this.defersChange(tr)) {
    +      this.deferChange(tr);
    +      return;
    +    }
    +    if (this.deferred.length > 0 && !this.readingDeferred) {

    This branch also runs for the binding's own write transaction, which ends inside its update listener, where defersChange returns false (no pending state). The held change is then read here through guardedRead, which queues a plain update at the end of Lexical's queue, so the queueFirst read at line 1114 never runs. An edit an app listener queues on the local commit then merges into the read's COLLABORATION_TAG commit and is never written: a listener registered after the binding gives one twoXY on peer a and one twoX on peer b, and one registered before the binding loses Y everywhere. Requiring tr.origin to be none of this, initOrigin, followUpOrigin, scanOrigin and runEndOrigin here lets queueFirst take over, and both cases then converge.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 12:53 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -2796,6 +2825,79 @@ export class YBinding {
         }
       }
     
    +  /**
    +   * Whether remote change `tr` is read after the local update the editor is
    +   * making (a provider applying it from inside `editor.update`, a command or
    +   * a transform of that update): see deferChange. Not a change of the
    +   * binding's own, nor one Yjs applies inside a read or an undo the binding
    +   * runs, which read it there.
    +   */
    +  private defersChange(tr: Transaction): boolean {
    +    const editor = this._editor;
    +    if (
    +      this.readingDeferred ||
    +      this.readsNow > 0 ||
    +      !editor._updating ||
    +      editor._pendingEditorState === null
    +    ) {
    +      return false;
    +    }
    +    if (this.deferred.length > 0) {
    +      return true;
    +    }
    +    return (
    +      this._status !== 'pending' &&
    +      this.readsChanges() &&
    +      tr.origin !== this &&
    +      tr.origin !== this.initOrigin &&
    +      tr.origin !== this.followUpOrigin &&
    +      tr.origin !== this.scanOrigin &&
    +      tr.origin !== this.runEndOrigin &&
    +      (this._undoManager === null || tr.origin !== this._undoManager)
    +    );
    +  }
    +
    +  /**
    +   * Read remote change `tr` once the local update the editor is making has
    +   * committed, and been written, instead of in it. Invariant: a local update
    +   * is written before a remote change is read (see readChange). Why: read
    +   * in it, the change would replace what the update changed in the lines it
    +   * touches, and give its commit a collaborator's tags, so that nothing of
    +   * it is written: the update's text would be lost, in the editor and in
    +   * the document. Until it is read, the change stays unread (see Unread):
    +   * the update is written on the document as it was before it, as one
    +   * committed before a read is. It is read right after the update's commit
    +   * (see the update listener), or, where the update did not commit (it
    +   * threw), once the editor is idle.
    +   */
    +  private deferChange(tr: Transaction): void {
    +    this.deferred.push(tr);
    +    if (this.deferred.length === 1) {
    +      queueMicrotask(() =>
    +        this.guard(() =>
    +          withPins(this._pins, () => {
    +            if (this.deferred.length > 0 && this.isIdle()) {
    +              this.readDeferred();
    +            }
    +          }),
    +        ),
    +      );
    +    }
    +  }
    +
    +  /** Read the remote changes deferred so far, in order (see deferChange). */
    +  private readDeferred(): void {
    +    const list = this.deferred.splice(0);
    +    this.readingDeferred = true;
    +    try {
    +      for (const tr of list) {
    +        this.onAfterTransaction(tr);

    pendingCursor is already null here (the binding's own write reset it), and readChange recaptures it only when the committed state changed during the read, so this read restores no caret. In the "after a local edit" case the caret ends after one instead of after X. this.pendingCursor = this.getCursor(); before this call keeps it after X.

    meta-code-review[bot] meta-code-review[bot] requested changes on Nov 04, 2026 12:53 UTC
    Changes Requested Reviewer

    Thanks for tracking this down. Holding the change back fixes the lost local edit: the new regression file fails 14 cases on main and passes here, with gc off and on. Two things need fixing before this can merge.

    1. An edit an update listener makes in reply to the local commit is still lost (packages/lexical-y/src/internal/Binding.ts:2813). The binding writes the local update inside its own update listener, and that write's transaction reaches onAfterTransaction. There defersChange returns false: in Lexical's listener phase _updating is true but there is no pending state. So the new deferred.length > 0 && !readingDeferred branch reads the held change at once through guardedRead, which queues a plain update at the end of Lexical's queue. The queueFirst read in the listener (:1110-1119) never runs.

    Lexical runs all updates queued in one listener phase as one update. A listener's edit therefore commits together with the read, under COLLABORATION_TAG, and is never written. To reproduce, use the setup in RemoteChangeInsideUpdate.test.ts plus a listener that appends Y on commits without COLLABORATION_TAG, the pattern packages/lexical-website/docs/collaboration/y.md recommends under "Skip remote changes in listeners that edit":

  • Registered after the binding: peer a shows one twoXY, peer b shows one twoX.

  • Registered before the binding (for example in another extension's register): Y is lost on both peers.
  • In that branch, also require that tr.origin is none of the binding's own origins (this, initOrigin, followUpOrigin, scanOrigin, runEndOrigin). The queueFirst read then takes over. With that change both cases converge on one twoXY, and the package's unit suite still passes.

    2. The deferred read loses the caret (Binding.ts:2894). By the time the change is read, the binding's own write has reset pendingCursor. readChange recaptures it only when the committed state changed during the read, so no cursor is restored. In the "after a local edit" case the caret ends after one instead of after X. Setting this.pendingCursor = this.getCursor() before each held change is read keeps it after X.

    packages/lexical-y/AGENTS.md asks that every bug fix land with a regression test in src/__tests__/unit/regressions/, so please add both cases to RemoteChangeInsideUpdate.test.ts.

    Optional: the y.md bullet on remote changes applied in the same task could also say that a change applied inside editor.update() is read in its own commit, right after the update's.

    <!-- codebunny-pub:1 k=f7d19661653f0010c2da8ef2a7ec906826d22241736ab452ccb1a8725d21109c -->

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 14:07 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -1577,6 +1609,7 @@ export class YBinding {
         }
         this.state.clear();
         this.pending.clear();
    +    this.deferred.length = 0;

    dispose() empties deferred but leaves those transactions in unread.changes, and nothing drops them later (only a read calls dropChange). If the same binding is started again before the deferred read ran, scheduleDeferred returns early from then on (view.changes.some(c => !this.deferred.includes(c))), so later remote changes applied during an update stay unshown until a change arrives outside an update. Repro: apply a remote change in a discrete update that changes nothing, dispose and start() before the microtask, then apply another remote change inside an update that also appends text; the editor keeps showing only the local text. Suggested fix (the new test file and GuardedRead still pass with it):

        for (const tr of this.deferred) {
          this.dropChange(tr);
        }
        this.deferred.length = 0;
    

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 14:07 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -5664,11 +5852,20 @@ export class YBinding {
             try {
               this.guard(() => withPins(this._pins, fn));
               if (later.length > 0) {
    -            $onUpdate(() => {
    -              for (const [f, o] of later) {
    -                editor.update(f, o);
    +            // After the commit; where there is none (`fn` changed nothing,
    +            // and Lexical drops such an update with its callbacks), once
    +            // the editor is idle.
    +            let handed = false;
    +            const handBack = () => {
    +              if (!handed) {
    +                handed = true;
    +                for (const [f, o] of later) {
    +                  editor.update(f, o);
    +                }
                   }
    -            });
    +            };
    +            $onUpdate(handBack);
    +            queueMicrotask(handBack);

    Nit: with $onUpdate(handBack) registered, Lexical commits this update even when fn changed nothing, because $beginUpdate's shouldUpdate counts pending _deferred callbacks (packages/lexical/src/LexicalUpdates.ts). The microtask still helps where a commit listener throws before Lexical runs the callbacks (the case notifyApart describes), so the comment could name that case. No test reaches this line today: the regression and undo files pass with it removed.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 14:07 UTC
    Code Review
    .changeset/lexical-y-remote-change-inside-update.md:1
    @@ -0,0 +1,9 @@
    +---
    +'@lexical/y': patch
    +---
    +
    +[fix] A remote change applied while the editor makes a local update no longer loses that update: it is read right after the update has committed and been written, in a commit of its own
    +
    +A provider that applies a remote change to the document from inside `editor.update()` (a synchronous provider between editors on one page, a test, an app calling `Y.applyUpdate` in an update, a command or a listener that also queues an edit) made the binding read the change inside that update: the read replaced the lines it touched with what the document stored, which did not have the update's edits yet, and the commit took a collaborator's tags, so nothing of the update was written. Text typed in that update was lost, in the editor and in the document. Such a change is now read once the update has committed and been written, in a commit of its own tagged as a collaborator's change, right after it.
    +
    +Verify: inside `editor.update()`, type text and apply a remote change to the document (`Y.applyUpdate`); after the update the editor and every client show both, and update listeners see the local commit, then the remote one.

    Optional (CONTRIBUTING.md asks a behavior-changing fix to say what to test): it may help to add that a remote change applied in an update that changes nothing, or throws, now shows a microtask after editor.update() returns. Separately, packages/lexical-y/AGENTS.md asks for a DECISIONS.md row when a pull request makes a new consequential decision; the new read timing looks like one, and the setup notes in packages/lexical-website/docs/collaboration/y.md could gain a sentence about changes applied inside an update.

    meta-code-review[bot] meta-code-review[bot] approved these changes on Nov 04, 2026 14:07 UTC
    Approved Reviewer

    This looks good to me. Thanks for the thorough regression file: the new cells fail on main and pass here with GC on and off, and the full @lexical/y unit suite stays green. Everything below is optional and non-blocking.

    1. dispose() leaves deferred changes in the unread view (packages/lexical-y/src/internal/Binding.ts:1612). dispose() clears deferred, but those transactions stay in unread.changes, and only a read removes a change from there. If the same binding is started again before the deferred read ran, scheduleDeferred keeps returning early (unread holds a change that is not in deferred), so later remote changes applied during an update are not shown until some change arrives outside an update. Repro: apply a remote change in a discrete update that changes nothing, call the cleanup start() returned and then binding.start() again before the microtask, then apply another remote change inside an update that also appends text; the editor keeps showing only the local text. Dropping them first fixes it, and both changed test files stay green:

       for (const tr of this.deferred) {
         this.dropChange(tr);
       }
       this.deferred.length = 0;
       

    A cell for it in RemoteChangeInsideUpdate.test.ts would cover the path (packages/lexical-y/AGENTS.md: every bug fix lands with a regression test).

    2. Decision record and docs. packages/lexical-y/AGENTS.md asks a pull request that makes a new consequential decision to add its DECISIONS.md row in the same pull request. When a remote change applied during a local update is read (after that update commits and is written, in a commit of its own; in a microtask when the update commits nothing or throws) looks like one. The setup notes in packages/lexical-website/docs/collaboration/y.md (the bullet on several editor.update() calls in one task) describe only a change applied outside an update; one sentence there would cover this case.

    3. Changeset Verify:. CONTRIBUTING.md asks a fix that changes behavior to say what to test. Consider adding that a remote change applied in an update that changes nothing, or throws, now shows a microtask after editor.update() returns; the N6 cell in GuardedRead.test.ts needed a caret move for exactly this.

    4. Nit, queueFirst (Binding.ts:5855-5868). The comment says Lexical drops an update that changed nothing with its callbacks, but with $onUpdate(handBack) registered Lexical commits it (the shouldUpdate check in packages/lexical/src/LexicalUpdates.ts counts pending _deferred callbacks). The microtask still covers a commit listener that throws before the callbacks run; naming that case would make the comment accurate. No test reaches that line today.

    <!-- codebunny-pub:1 k=6a3771b01f6f798fae13d9c6852f37d7aa95bb2f18bf267f29da0dc34a950193 -->

    zurfyx zurfyx commented on code on Nov 04, 2026 15:06 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -2785,6 +2806,14 @@ export class YBinding {
       }
     
       private onAfterTransaction(tr: Transaction): void {
    +    if (this.defersChange(tr)) {
    +      this.deferChange(tr);
    +      return;
    +    }
    +    if (this.deferred.length > 0 && !this.readingDeferred) {

    Fixed: the binding's own write transaction no longer reads deferred changes inline (16365282: own origins are never deferred, and onAfterTransaction reads deferred changes first only while the editor is idle); while the editor updates they are read in an update of their own queued ahead of the app's (queueFirst). Cells: an edit a listener makes on the local commit, registered after/before the binding, gc off and on.

    zurfyx zurfyx commented on code on Nov 04, 2026 15:06 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -2796,6 +2825,79 @@ export class YBinding {
         }
       }
     
    +  /**
    +   * Whether remote change `tr` is read after the local update the editor is
    +   * making (a provider applying it from inside `editor.update`, a command or
    +   * a transform of that update): see deferChange. Not a change of the
    +   * binding's own, nor one Yjs applies inside a read or an undo the binding
    +   * runs, which read it there.
    +   */
    +  private defersChange(tr: Transaction): boolean {
    +    const editor = this._editor;
    +    if (
    +      this.readingDeferred ||
    +      this.readsNow > 0 ||
    +      !editor._updating ||
    +      editor._pendingEditorState === null
    +    ) {
    +      return false;
    +    }
    +    if (this.deferred.length > 0) {
    +      return true;
    +    }
    +    return (
    +      this._status !== 'pending' &&
    +      this.readsChanges() &&
    +      tr.origin !== this &&
    +      tr.origin !== this.initOrigin &&
    +      tr.origin !== this.followUpOrigin &&
    +      tr.origin !== this.scanOrigin &&
    +      tr.origin !== this.runEndOrigin &&
    +      (this._undoManager === null || tr.origin !== this._undoManager)
    +    );
    +  }
    +
    +  /**
    +   * Read remote change `tr` once the local update the editor is making has
    +   * committed, and been written, instead of in it. Invariant: a local update
    +   * is written before a remote change is read (see readChange). Why: read
    +   * in it, the change would replace what the update changed in the lines it
    +   * touches, and give its commit a collaborator's tags, so that nothing of
    +   * it is written: the update's text would be lost, in the editor and in
    +   * the document. Until it is read, the change stays unread (see Unread):
    +   * the update is written on the document as it was before it, as one
    +   * committed before a read is. It is read right after the update's commit
    +   * (see the update listener), or, where the update did not commit (it
    +   * threw), once the editor is idle.
    +   */
    +  private deferChange(tr: Transaction): void {
    +    this.deferred.push(tr);
    +    if (this.deferred.length === 1) {
    +      queueMicrotask(() =>
    +        this.guard(() =>
    +          withPins(this._pins, () => {
    +            if (this.deferred.length > 0 && this.isIdle()) {
    +              this.readDeferred();
    +            }
    +          }),
    +        ),
    +      );
    +    }
    +  }
    +
    +  /** Read the remote changes deferred so far, in order (see deferChange). */
    +  private readDeferred(): void {
    +    const list = this.deferred.splice(0);
    +    this.readingDeferred = true;
    +    try {
    +      for (const tr of list) {
    +        this.onAfterTransaction(tr);

    Fixed: readDeferred takes pendingCursor = this.getCursor() (null only while the binding is pending), and getCursor splits the items at the unread bounds first (78ac8c30), since Yjs merges a deferred change's text into neighbouring items. Cells: the caret stays after the local edit and the caret a deferred read keeps, where Yjs merged the change into shown text.

    zurfyx zurfyx commented on code on Nov 04, 2026 15:06 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -1577,6 +1609,7 @@ export class YBinding {
         }
         this.state.clear();
         this.pending.clear();
    +    this.deferred.length = 0;

    Fixed as suggested in 1cd15e6edd4e0a9e837b8be6de42f9e94353b243, with the cell a binding started again before a deferred change was read (fails before, gc off and on).

    zurfyx zurfyx commented on code on Nov 04, 2026 15:06 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -5664,11 +5852,20 @@ export class YBinding {
             try {
               this.guard(() => withPins(this._pins, fn));
               if (later.length > 0) {
    -            $onUpdate(() => {
    -              for (const [f, o] of later) {
    -                editor.update(f, o);
    +            // After the commit; where there is none (`fn` changed nothing,
    +            // and Lexical drops such an update with its callbacks), once
    +            // the editor is idle.
    +            let handed = false;
    +            const handBack = () => {
    +              if (!handed) {
    +                handed = true;
    +                for (const [f, o] of later) {
    +                  editor.update(f, o);
    +                }
                   }
    -            });
    +            };
    +            $onUpdate(handBack);
    +            queueMicrotask(handBack);

    Agreed; the comment now names that case (1cd15e6edd4e0a9e837b8be6de42f9e94353b243).

    zurfyx zurfyx commented on code on Nov 04, 2026 15:06 UTC
    Code Review
    .changeset/lexical-y-remote-change-inside-update.md:1
    @@ -0,0 +1,9 @@
    +---
    +'@lexical/y': patch
    +---
    +
    +[fix] A remote change applied while the editor makes a local update no longer loses that update: it is read right after the update has committed and been written, in a commit of its own
    +
    +A provider that applies a remote change to the document from inside `editor.update()` (a synchronous provider between editors on one page, a test, an app calling `Y.applyUpdate` in an update, a command or a listener that also queues an edit) made the binding read the change inside that update: the read replaced the lines it touched with what the document stored, which did not have the update's edits yet, and the commit took a collaborator's tags, so nothing of the update was written. Text typed in that update was lost, in the editor and in the document. Such a change is now read once the update has committed and been written, in a commit of its own tagged as a collaborator's change, right after it.
    +
    +Verify: inside `editor.update()`, type text and apply a remote change to the document (`Y.applyUpdate`); after the update the editor and every client show both, and update listeners see the local commit, then the remote one.

    Done in 1cd15e6e: the Verify line names the microtask, DECISIONS.md has the row (D108, renumbered in the next commit since D107 is taken by an open PR), and the y.md setup notes have a sentence on changes applied inside an update.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 15:47 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -2793,6 +2888,173 @@ export class YBinding {
           if (this.schemaSeenIn === tr) {
             this.schemaSeenIn = null;
           }
    +      this.releaseUnread(tr);

    With gc on, this releases what a deferred change deleted before that change is read. In the update queueFirst runs, guardedRead is nested and its editor.update only queues the read (packages/lexical/src/LexicalUpdates.ts:1564-1565), so $read runs after this tryGc. A deleted line break is then ContentDeleted, and a line join is not read: the editor keeps the deleted line, and the next edit there writes it back for every peer. Suggest releasing at the end of $read (beside dropChange(tr)), and here only when the read ran in place, or as a microtask fallback for a change still held:

    if (!this._editor._updating) {
      this.releaseUnread(tr);
    } else if (this.heldUnread.has(tr)) {
      queueMicrotask(() => this.releaseUnread(tr));
    }
    

    meta-code-review[bot] meta-code-review[bot] requested changes on Nov 04, 2026 15:47 UTC
    Changes Requested Reviewer

    Thanks for the thorough fix and the regression file. The new cells fail on main and pass here, with gc off and on, and the full @lexical/y unit suite and CI are green. One issue needs fixing before this is ready; the other points are optional.

    1. With gc on, a deferred change's deletions are collected before it is read (packages/lexical-y/src/internal/Binding.ts:2891)

    readNow calls releaseUnread(tr) in its finally, as soon as readChange returns. For a change applied inside an update that commits, the read runs from the update queueFirst queues, so guardedRead is nested. Its editor.update then only queues the read, because Lexical pushes an update made while updating onto _updates (packages/lexical/src/LexicalUpdates.ts:1564-1565). So $read runs after tryGc has collected what the change deleted. A deleted line break is ContentDeleted by then, and a line join is not read.

    Repro, with gc on (Yjs's default):

    1. b joins "alpha beta" and "gamma delta" into "ata".
    2. a bolds "p" in the update the change is applied in.
    3. a shows alpha beta / ata / epsilon zeta, while b and a fresh read of a's own document show ata / epsilon zeta.
    4. a's next edit next to that line throws in the write (Cannot read properties of undefined (reading '_map')), and "alpha beta" is then written back for every peer.

    With gc off, and with a pending local update and the change applied outside the update, the same change reads correctly. main shows the same stale line for this sequence, so this is about the new gc hold not covering it, not a new regression. It is broad, though: over random typing, deletes, bold, and line splits and joins (40 seeds, the change applied before or after the local edit), 40 of 80 gc-on runs fail. With gc off, all 80 end on the same document as the existing pending-update path.

    Releasing once the read has actually run fixes it. In readNow:

    -      this.releaseUnread(tr);
    +      if (!this._editor._updating) {
    +        this.releaseUnread(tr);
    +      } else if (this.heldUnread.has(tr)) {
    +        // Nested in an update, the read is only queued (see guardedRead):
    +        // its $read releases it; this covers a read that never runs.
    +        queueMicrotask(() => this.releaseUnread(tr));
    +      }
    

    Then add this.releaseUnread(tr); after this.dropChange(tr); at the end of $read (around line 3204). With both, the repro, all 80 runs and the whole @lexical/y unit suite (gc on and off) pass. Queueing the release for every nested read instead keeps each binding alive until the next microtask, and the memory tests in DisposeMemory.test.ts and Headless.test.ts catch that. packages/lexical-y/AGENTS.md asks for a regression test with every fix and for testing the input space. A gc-on cell in RemoteChangeInsideUpdate.test.ts for a deferred line join (or a whole-line delete), applied inside an update that commits, would pin this.

    2. D108 (optional)

    packages/lexical-y/DECISIONS.md:45 says that with gc on, the binding keeps Yjs from collecting what a deferred change deleted while the editor still shows it. Please keep that sentence true with the fix. Nit: the row links [y-setup] bare, where the other rows use [y.md: Set up an editor][y-setup].

    3. Nit: items stay split after a deferred read (Binding.ts:3114-3115)

    readChange collects a deferred change's items with iterateStructsByIdSet(tr, …) on a transaction that has already been cleaned up, so nothing merges the splits it makes. Reading b's [k7] (continuing its own [k2]) deferred leaves a with 2 structs where b has 1, and an encoded state 13 bytes larger, until a reload. One fix is to collect inside a transaction whose cleanup runs after the read.

    <!-- codebunny-pub:1 k=475b48b673b0257369a660dfa6926edecab83946f166c4b640cf5a4a7bbe8fad -->

    zurfyx zurfyx commented on code on Nov 04, 2026 16:34 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -2793,6 +2888,173 @@ export class YBinding {
           if (this.schemaSeenIn === tr) {
             this.schemaSeenIn = null;
           }
    +      this.releaseUnread(tr);

    Fixed as suggested in 62118e2b: the read releases its change's deletions at the end of $read (beside dropChange), and readNow releases in place only when not updating, else in a microtask for a change still held. Cell: a deferred change that joins two lines, read in an update queued first (fails on the previous head and on main with gc on). D108 now says the hold lasts until the read has run, and links [y.md: Set up an editor][y-setup]. On the split items (nit 3): kept deliberately. The pieces a deferred read collects stay live and exact for that read; re-merging them before it runs would leave it holding pieces merged away (the hazard closeRestoredRuns documents), and the state is the same (equal state vector; the decoded update re-encodes to the oracle's), at a few bytes until the items are next touched or the document reloads.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 16:35 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -2793,6 +2888,173 @@ export class YBinding {
           if (this.schemaSeenIn === tr) {
             this.schemaSeenIn = null;
           }
    +      this.releaseUnread(tr);

    Fair enough on nit 3: keeping the split items is an acceptable deliberate trade-off, not something to block on. The splits are what the deferred read itself relies on to tell unread text apart from shown text, and merging them away while the read still holds those pieces would risk the hazard closeRestoredRuns documents. Since the state is equivalent — same state vector, and the decoded update re-encodes to the oracle's — the cost is only a few transient bytes until the items are next touched or the document reloads. The next full review will re-evaluate this, but I won't press for the re-merge.

    <!-- codebunny-pub:1 k=4406a275554e6f921196d90eaa5a7fff48914672d51950ac3b24e4f6051f2d0a -->

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 17:29 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -2793,6 +2888,180 @@ export class YBinding {
           if (this.schemaSeenIn === tr) {
             this.schemaSeenIn = null;
           }
    +      if (!this._editor._updating) {
    +        this.releaseUnread(tr);
    +      } else if (this.heldUnread.has(tr)) {
    +        // Nested in an update, the read is only queued (see guardedRead),
    +        // and releases what it holds once it ran; this covers a read that
    +        // never runs.
    +        queueMicrotask(() => this.releaseUnread(tr));
    +      }
    +    }
    +    // Deferred while it was read (see scheduleDeferred).
    +    this.scheduleDeferred();
    +  }
    +
    +  /**
    +   * Whether remote change `tr` is read after the local update the editor is
    +   * making (a provider applying it from inside `editor.update`, a command or
    +   * a transform of that update): see deferChange. Not a change of the
    +   * binding's own, nor one Yjs applies inside a read or an undo the binding
    +   * runs, which read it there.
    +   */
    +  private defersChange(tr: Transaction): boolean {
    +    const editor = this._editor;
    +    if (
    +      this.readsNow > 0 ||
    +      !editor._updating ||
    +      tr.origin === this ||
    +      tr.origin === this.initOrigin ||
    +      tr.origin === this.followUpOrigin ||
    +      tr.origin === this.scanOrigin ||
    +      tr.origin === this.runEndOrigin ||
    +      (this._undoManager !== null && tr.origin === this._undoManager)
    +    ) {
    +      return false;
    +    }
    +    return (
    +      this.deferred.length > 0 ||
    +      (this._status !== 'pending' && this.readsChanges())
    +    );
    +  }
    +
    +  /**
    +   * Read remote change `tr` once the local update the editor is making has
    +   * committed, and been written, instead of in it. Invariant: a local update
    +   * is written before a remote change is read (see readChange). Why: read
    +   * in it, the change would replace what the update changed in the lines it
    +   * touches, and give its commit a collaborator's tags, so that nothing of
    +   * it is written: the update's text would be lost, in the editor and in
    +   * the document. Until it is read, the change stays unread (see Unread):
    +   * the update is written on the document as it was before it, as one
    +   * committed before a read is. It is read right after the update's commit
    +   * (see the update listener), or, where the update did not commit (it
    +   * threw), once the editor is idle.
    +   */
    +  private deferChange(tr: Transaction): void {
    +    this.deferred.push(tr);
    +    if (this._doc.gc) {
    +      this.holdDeleted(tr);
    +    }
    +    if (this._editor._pendingEditorState === null) {
    +      // From a commit's listeners or callbacks: in an update of its own,
    +      // ahead of the updates the app queued there, which commit, and are
    +      // written, after it.
    +      this.scheduleDeferred();
    +    }
    +    if (this.deferred.length === 1) {
    +      queueMicrotask(() =>
    +        this.guard(() => withPins(this._pins, () => this.scheduleDeferred())),
    +      );
    +    }
    +  }
    +
    +  /**
    +   * Read the deferred remote changes (see deferChange) where nothing keeps
    +   * them waiting: now where the editor is idle, else in an update of their
    +   * own ahead of those the app queued (from a commit's listeners). Not while
    +   * another change is being read further up (an update the app makes from
    +   * its listeners, on that read's commit): that read reads them when it
    +   * ends (see readNow). Why: read in it, the change being read would still
    +   * count as unread, and the read would not show it.
    +   */
    +  private scheduleDeferred(): void {
    +    const view = this.unread;
    +    if (
    +      this.deferred.length === 0 ||
    +      this.drainingDeferred ||
    +      (view !== null && view.changes.some(c => !this.deferred.includes(c)))
    +    ) {
    +      return;
    +    }
    +    if (this.isIdle()) {
    +      this.readDeferred();
    +    } else if (this._editor._updating && !this.deferredQueued) {
    +      this.deferredQueued = true;
    +      this.queueFirst(
    +        () => {
    +          this.deferredQueued = false;
    +          this.readDeferred();
    +        },
    +        {discrete: true, skipTransforms: true, tag: REMOTE_TAGS},
    +      );
    +    }
    +  }
    +
    +  /**
    +   * Let Yjs collect what deferred change `tr` deleted, now that it is read
    +   * (see deferChange), as it would have when the change was applied.
    +   */
    +  private releaseUnread(tr: Transaction): void {
    +    if (!this.heldUnread.delete(tr)) {
    +      return;
    +    }
    +    const doc = this._doc;
    +    // What no one else keeps (an UndoManager, the binding's own format
    +    // items) and the app's filter lets go.
    +    doc.transact(t => tryGc(t, tr.deleteSet, doc.gcFilter), this.scanOrigin);
    +    const filters = this.gcFilters;
    +    if (this.heldUnread.size === 0 && filters !== null) {
    +      // Unless something replaced or wrapped it since: the binding's holds
    +      // nothing now, and the next hold wraps whatever the document has.
    +      if (doc.gcFilter === filters.ours) {
    +        doc.gcFilter = filters.prev;
    +      }
    +      this.gcFilters = null;
    +    }
    +  }
    +
    +  /**
    +   * Keep Yjs from collecting the content deferred change `tr` deleted, which
    +   * it does right after this (in the change's transaction cleanup), until
    +   * the change is read: the text the editor still shows stays there for the
    +   * writes in between (see Unread), which would otherwise write it again.
    +   * Through the document's `gcFilter`, which the binding wraps while it
    +   * holds any: an item's `keep` is others' (an UndoManager's), which a
    +   * release could not tell from its own.
    +   */
    +  private holdDeleted(tr: Transaction): void {
    +    this.heldUnread.add(tr);
    +    const doc = this._doc;
    +    if (this.gcFilters !== null && doc.gcFilter === this.gcFilters.ours) {
    +      return;
    +    }
    +    // (Again if the app replaced the filter while the binding held some.)
    +    const prev = doc.gcFilter;
    +    const ours = (item: Item) => {
    +      for (const held of this.heldUnread) {
    +        if (held.deleteSet.hasId(item.id)) {
    +          return false;
    +        }
    +      }
    +      return prev(item);
    +    };
    +    this.gcFilters = {ours, prev};
    +    doc.gcFilter = ours;
    +  }
    +
    +  /** Read the remote changes deferred so far, in order (see deferChange). */
    +  private readDeferred(): void {
    +    // One at a time: those still deferred stay unread while each is read.
    +    this.drainingDeferred = true;
    +    try {
    +      for (
    +        let tr = this.deferred.shift();
    +        tr !== undefined;
    +        tr = this.deferred.shift()
    +      ) {
    +        // The selection to keep is the editor's now, on the document as it
    +        // was before the change (see Unread), not the one before the update
    +        // the change was applied in.
    +        this.pendingCursor =
    +          this._status === 'pending' ? null : this.getCursor();
    +        this.readNow(tr);

    Optional, non-blocking (cheap to fix): from the update scheduleDeferred queues, readNow only queues the read and drops the change from the unread view in its finally. The next iteration's getCursor() then reads the caret from the committed state (offsets without the first change) on a view where the first change counts as read. With two changes in one committing update (AAA inserted earlier in the line, then a bold), the caret ends at AAAone t|woX three instead of AAAone twoX| three. Reading one change per queued step fixes it: after readNow(tr), if (this._editor._updating && this.deferred.length > 0) { $onUpdate(() => this.guard(() => withPins(this._pins, () => this.scheduleDeferred()))); break; }.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 17:29 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -2793,6 +2888,180 @@ export class YBinding {
           if (this.schemaSeenIn === tr) {
             this.schemaSeenIn = null;
           }
    +      if (!this._editor._updating) {
    +        this.releaseUnread(tr);
    +      } else if (this.heldUnread.has(tr)) {
    +        // Nested in an update, the read is only queued (see guardedRead),
    +        // and releases what it holds once it ran; this covers a read that
    +        // never runs.
    +        queueMicrotask(() => this.releaseUnread(tr));
    +      }
    +    }
    +    // Deferred while it was read (see scheduleDeferred).
    +    this.scheduleDeferred();
    +  }
    +
    +  /**
    +   * Whether remote change `tr` is read after the local update the editor is
    +   * making (a provider applying it from inside `editor.update`, a command or
    +   * a transform of that update): see deferChange. Not a change of the
    +   * binding's own, nor one Yjs applies inside a read or an undo the binding
    +   * runs, which read it there.
    +   */
    +  private defersChange(tr: Transaction): boolean {
    +    const editor = this._editor;
    +    if (
    +      this.readsNow > 0 ||
    +      !editor._updating ||
    +      tr.origin === this ||
    +      tr.origin === this.initOrigin ||
    +      tr.origin === this.followUpOrigin ||
    +      tr.origin === this.scanOrigin ||
    +      tr.origin === this.runEndOrigin ||
    +      (this._undoManager !== null && tr.origin === this._undoManager)
    +    ) {
    +      return false;
    +    }
    +    return (
    +      this.deferred.length > 0 ||
    +      (this._status !== 'pending' && this.readsChanges())
    +    );
    +  }
    +
    +  /**
    +   * Read remote change `tr` once the local update the editor is making has
    +   * committed, and been written, instead of in it. Invariant: a local update
    +   * is written before a remote change is read (see readChange). Why: read
    +   * in it, the change would replace what the update changed in the lines it
    +   * touches, and give its commit a collaborator's tags, so that nothing of
    +   * it is written: the update's text would be lost, in the editor and in
    +   * the document. Until it is read, the change stays unread (see Unread):
    +   * the update is written on the document as it was before it, as one
    +   * committed before a read is. It is read right after the update's commit
    +   * (see the update listener), or, where the update did not commit (it
    +   * threw), once the editor is idle.
    +   */
    +  private deferChange(tr: Transaction): void {
    +    this.deferred.push(tr);
    +    if (this._doc.gc) {
    +      this.holdDeleted(tr);
    +    }
    +    if (this._editor._pendingEditorState === null) {
    +      // From a commit's listeners or callbacks: in an update of its own,
    +      // ahead of the updates the app queued there, which commit, and are
    +      // written, after it.
    +      this.scheduleDeferred();
    +    }
    +    if (this.deferred.length === 1) {
    +      queueMicrotask(() =>
    +        this.guard(() => withPins(this._pins, () => this.scheduleDeferred())),
    +      );
    +    }
    +  }
    +
    +  /**
    +   * Read the deferred remote changes (see deferChange) where nothing keeps
    +   * them waiting: now where the editor is idle, else in an update of their
    +   * own ahead of those the app queued (from a commit's listeners). Not while
    +   * another change is being read further up (an update the app makes from
    +   * its listeners, on that read's commit): that read reads them when it
    +   * ends (see readNow). Why: read in it, the change being read would still
    +   * count as unread, and the read would not show it.
    +   */
    +  private scheduleDeferred(): void {
    +    const view = this.unread;
    +    if (
    +      this.deferred.length === 0 ||
    +      this.drainingDeferred ||
    +      (view !== null && view.changes.some(c => !this.deferred.includes(c)))
    +    ) {
    +      return;
    +    }
    +    if (this.isIdle()) {
    +      this.readDeferred();
    +    } else if (this._editor._updating && !this.deferredQueued) {
    +      this.deferredQueued = true;
    +      this.queueFirst(
    +        () => {
    +          this.deferredQueued = false;
    +          this.readDeferred();
    +        },
    +        {discrete: true, skipTransforms: true, tag: REMOTE_TAGS},
    +      );
    +    }
    +  }
    +
    +  /**
    +   * Let Yjs collect what deferred change `tr` deleted, now that it is read
    +   * (see deferChange), as it would have when the change was applied.
    +   */
    +  private releaseUnread(tr: Transaction): void {
    +    if (!this.heldUnread.delete(tr)) {
    +      return;
    +    }
    +    const doc = this._doc;
    +    // What no one else keeps (an UndoManager, the binding's own format
    +    // items) and the app's filter lets go.
    +    doc.transact(t => tryGc(t, tr.deleteSet, doc.gcFilter), this.scanOrigin);
    +    const filters = this.gcFilters;
    +    if (this.heldUnread.size === 0 && filters !== null) {
    +      // Unless something replaced or wrapped it since: the binding's holds
    +      // nothing now, and the next hold wraps whatever the document has.
    +      if (doc.gcFilter === filters.ours) {
    +        doc.gcFilter = filters.prev;
    +      }
    +      this.gcFilters = null;
    +    }
    +  }
    +
    +  /**
    +   * Keep Yjs from collecting the content deferred change `tr` deleted, which
    +   * it does right after this (in the change's transaction cleanup), until
    +   * the change is read: the text the editor still shows stays there for the
    +   * writes in between (see Unread), which would otherwise write it again.
    +   * Through the document's `gcFilter`, which the binding wraps while it
    +   * holds any: an item's `keep` is others' (an UndoManager's), which a
    +   * release could not tell from its own.
    +   */
    +  private holdDeleted(tr: Transaction): void {
    +    this.heldUnread.add(tr);
    +    const doc = this._doc;
    +    if (this.gcFilters !== null && doc.gcFilter === this.gcFilters.ours) {
    +      return;
    +    }
    +    // (Again if the app replaced the filter while the binding held some.)
    +    const prev = doc.gcFilter;
    +    const ours = (item: Item) => {
    +      for (const held of this.heldUnread) {
    +        if (held.deleteSet.hasId(item.id)) {
    +          return false;
    +        }
    +      }
    +      return prev(item);
    +    };
    +    this.gcFilters = {ours, prev};
    +    doc.gcFilter = ours;
    +  }
    +
    +  /** Read the remote changes deferred so far, in order (see deferChange). */
    +  private readDeferred(): void {
    +    // One at a time: those still deferred stay unread while each is read.

    Optional, non-blocking: on the idle path each read commits on its own, so checkRead runs between these reads while later changes are still deferred. With selfCheck on, two changes in one update that changes nothing (a paragraph inserted, then a list made a check list) warn self-check (remote): …checked: editor undefined != shared false and re-read the root, though the documents end right. Skipping checkRead while this.deferred.length > 0, beside the refused skip, avoids it.

    meta-code-review[bot] meta-code-review[bot] approved these changes on Nov 04, 2026 17:29 UTC
    Approved Reviewer

    This looks good. The deferred read keeps the local update's edits, and with this push the gc-on hold lasts until the queued read has run. The new line-join cell pins that: it fails on the previous commit with gc on and passes now. The suggestions below are optional and non-blocking, though the first is cheap to fix before merge.

    1. Two remote changes in one committing update: the second read pulls the caret back (packages/lexical-y/src/internal/Binding.ts:3059-3061)

    When the update commits, the deferred changes are read in the update scheduleDeferred queues first. There readNow only queues each read (guardedRead is nested) and drops the change from the unread view in its finally. The next iteration's getCursor() then reads the caret from the committed state (readCursor), whose offsets do not include the first change yet, and maps it on a view where the first change already counts as read.

    Example: in one two three, a types X after one two, and inside that update two changes from b arrive (AAA inserted earlier in the line, then a bold). a ends at AAAone t|woX three instead of AAAone twoX| three, with gc on and off; the pending path and a single merged change get it right. So the description's "one at a time (those still deferred stay unread while each is read)" does not hold on this path. Reading one change per queued step fixes it:

    this.readNow(tr);
    if (this._editor._updating && this.deferred.length > 0) {
      // Nested, that read is only queued (see guardedRead), and the caret
      // (see getCursor) is the committed state's: read the rest once this
      // update has committed (which the callback makes happen).
      $onUpdate(() =>
        this.guard(() => withPins(this._pins, () => this.scheduleDeferred())),
      );
      break;
    }
    

    The $onUpdate matters: breaking without it can leave the remaining changes unread when the first read changes nothing, because nothing then commits. With this change the package's unit tests still pass with gc off and on.

    2. With selfCheck on, two changes in one idle update raise a false warning (Binding.ts:2263-2274)

    Take an update that changes nothing and applies two remote changes, say b inserts a paragraph and then turns a list into a check list. The first read's checkRead runs while the second change is still deferred. It reports self-check (remote): container root[1].children[0].checked: editor undefined != shared false and re-reads the root, though the final documents are right. Skipping the self-check while this.deferred.length > 0, next to the existing refused skip, removes the warning.

    3. Tests. packages/lexical-y/AGENTS.md asks to "test the input space", and two remote changes inside one update, read in order only appends text and asserts the text. Two more cells would pin 1 and 2: one where the first change inserts before the caret, asserting the caret, and one where the second change touches another line (insert a paragraph, then change a list's type).

    The items a deferred read leaves split were explained as deliberate in the earlier thread; no action needed there.

    <!-- codebunny-pub:1 k=8fa6c2c2106e6c3ba5d80b4bf8f461ef275adc6bbe558aaa8cc11b36e8ba297e -->

    zurfyx zurfyx commented on Nov 04, 2026 17:52 UTC
    Author

    Thanks. All three addressed in 096945dd: (1) after a read that is only queued, the rest of the deferred changes are read once that update has committed ($onUpdate, with a microtask fallback for a commit listener that throws first), as suggested; (2) the self-check skips while changes are deferred; (3) cells two remote changes in a committing update, the first before the caret (asserts the caret) and two remote changes in an update that changes nothing, the second on another line (paragraph insert, then a list turned into a check list; asserts no self-check warning). Both fail on 62118e2b, gc off and on.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 18:47 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -3185,6 +3513,7 @@ export class YBinding {
                 return;
               }
               readState = editor._pendingEditorState;
    +          this.readsNow++;
               try {
                 read.$read();

    Optional: when this read is nested (the deferred changes drained in the update scheduleDeferred queues first), Lexical runs this callback after guard() has returned, so $read sees no view and shows the changes that are still deferred. The next getCursor() maps through the unread view that hides them. With two changes from b (AAA then BB inserted at 0) applied in the update where a typed X after one two, a ends at BBAAAone twoX t| instead of after X. Wrapping it keeps the read on the binding's view:

    seenBy(this.seer, () => read.$read());
    

    meta-code-review[bot] meta-code-review[bot] approved these changes on Nov 04, 2026 18:47 UTC
    Approved Reviewer

    This looks good. Deferring a remote change applied inside editor.update() until the local update has committed and been written keeps the local edit on every peer. The new cells show it: 31 of the 62 fail on main and all pass here, and the whole @lexical/y suite and CI are green. The suggestions below are optional and non-blocking.

    1. Two remote changes in one committing update can still move the caret (packages/lexical-y/src/internal/Binding.ts:3518)

    When the update commits, the deferred changes are read in the update scheduleDeferred queues first. There each read is only queued, because guardedRead is nested, and Lexical runs the queued callback after guard() has returned. So read.$read() runs with no view: it rebuilds the line from the document as it is, the changes still deferred included. The next caret is then mapped through the unread view, which still hides them.

    Example: in one two three, a types X after one two, and in the same update two changes from b arrive: AAA inserted at the start, then BB at the start. a ends at BBAAAone twoX t| instead of BBAAAone twoX|, with gc off and on, and the first remote commit already shows BB while the binding still counts it as unread. The text and both peers' documents are right, and main loses the X here, so this is narrower than the bug being fixed. Running the queued read on the binding's view fixes it:

    // Nested, Lexical runs this once the work that queued it has
    // returned (see guard): on this binding's view still, which hides
    // the changes still deferred (see seer, deferChange).
    seenBy(this.seer, () => read.$read());
    

    With that change the package's unit tests keep the same counts with gc off and on.

    2. Tests. packages/lexical-y/AGENTS.md asks to "test the input space". two remote changes in a committing update, the first before the caret pairs an insert with a bold, which shifts no offset. A cell with two inserts before the caret that asserts the caret would pin item 1.

    <!-- codebunny-pub:1 k=a69da463f228f9f135758b4c21021950ee1969e1f250983ac87a2fcc7fbe9b11 -->

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 19:59 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -3185,6 +3526,7 @@ export class YBinding {
                 return;
               }
               readState = editor._pendingEditorState;
    +          this.readsNow++;
               try {
                 read.$read();

    Optional: nested, this callback runs after readNow has dropped the change from the unread view and guard() has returned, so the read sees the changes still deferred. With two changes that both insert before the caret (AAA, then BB, at 0), the first remote commit already shows BB and the caret ends two characters past the local edit (BBAAAone twoX t|). Running it on the binding's view keeps each read to its own change:

    seenBy(this.seer, () => read.$read());
    

    meta-code-review[bot] meta-code-review[bot] approved these changes on Nov 04, 2026 19:59 UTC
    Approved Reviewer

    This looks good. Deferring a remote change applied inside editor.update() until the local update has committed and been written keeps the local edit on every peer. The new cells show it: 35 of the 68 fail on main and all pass here with gc off and on, and the whole @lexical/y unit suite keeps the counts in the description. The changeset, D108 and the y.md note describe the new commit order. The suggestions below are optional and non-blocking.

    1. Two offset-shifting remote changes in one committing update still move the caret (packages/lexical-y/src/internal/Binding.ts:3531)

    When the update commits, the deferred changes are read in the update that scheduleDeferred queues first. The first read there is nested, so guardedRead only queues it. By the time Lexical runs it, readNow has already dropped the change from the unread view and guard() has returned, so read.$read() runs with no view. It rebuilds the line from the document as it is, which includes the changes still deferred. The next caret (getCursor() in readDeferred) is still mapped through the unread view that hides them.

    Example: in one two three, a types X after one two. In the same update, two changes from b arrive: AAA inserted at the start, then BB at the start. The first remote commit already shows BB, and a ends at BBAAAone twoX t| instead of BBAAAone twoX|. a's next keystroke then gives BBAAAone twoX tZhree on both peers, with gc off and on; a third change puts the caret three characters off. The documents converge, and main loses the X here, so this is narrower than the bug being fixed. Running the queued read on the binding's view fixes it:

    // Nested, Lexical runs this once the work that queued it has
    // returned (see guard): on this binding's view still.
    seenBy(this.seer, () => read.$read());
    

    With that line, each remote commit shows one change, the caret ends after X, and the package's unit tests keep the same counts with gc off and on. It also makes the description's "those still deferred stay unread while each is read" hold on this path.

    2. A cell for it. packages/lexical-y/AGENTS.md asks to "test the input space, not the cases you thought of". two remote changes in a committing update, the first before the caret pairs an insert with a bold, which shifts no offset. A cell with two inserts before the caret that asserts the caret, or the next keystroke, would pin item 1.

    <!-- codebunny-pub:1 k=383bec57916952032e32daa51ada10e60c9f2371807834a7b16baf8357b33174 -->

    zurfyx zurfyx commented on Nov 04, 2026 20:22 UTC
    Author

    Thanks. Both done in d5738d4c: the queued read runs seenBy(this.seer, () => read.$read()), and the cell two remote inserts before the caret in a committing update (three inserts; asserts one change per remote commit and that the next keystroke lands right after the local edit) fails on 0e41a5e5, gc off and on.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 21:05 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -3185,15 +3526,21 @@ export class YBinding {
                 return;
               }
               readState = editor._pendingEditorState;
    +          this.readsNow++;
               try {
    -            read.$read();
    +            // Nested, Lexical runs this once the work that queued it has
    +            // returned (see guard): on this binding's view still, which
    +            // hides the changes still deferred (see deferChange).
    +            seenBy(this.seer, () => read.$read());

    Optional, non-blocking: with several deferred changes, this runs each queued read on the view that hides the later ones. The Reader still rebuilds the containers the earlier change touched from Yjs as it is, so it drops what a later deferred change deleted, while the caret is resolved under the view. Repro: three remote changes applied inside one committing update (insert a table column, insert a row, delete the column holding the caret). The caret is cleared after the first read, and the next keystroke goes nowhere. Applied after the update, or as one merged update, the same changes leave the caret in the remaining cell. Documents converge.

    meta-code-review[bot] meta-code-review[bot] approved these changes on Nov 04, 2026 21:05 UTC
    Approved Reviewer

    Thanks, this looks good. Waiting until the local update has committed and been written before reading a remote change applied inside editor.update() (or a command, transform or commit listener) fixes the lost local edit. The new RemoteChangeInsideUpdate.test.ts cells fail on main and pass here, with gc off and on. Both suggestions below are optional and non-blocking.

    1. The caret is cleared when a later change in the batch deletes what holds it (packages/lexical-y/src/internal/Binding.ts: readDeferred, the seenBy(this.seer, …) in guardedRead, and $resolvePosition). With several deferred changes, each read runs on the binding's view, which hides the later changes. The Reader still rebuilds the containers an earlier change touched from Yjs as it is, so it already drops what a later change deleted, while the cursor is resolved under the view.
    Repro: apply three remote changes inside one committing update. Peer b inserts a table column, inserts a row, then deletes the column holding a's caret; in the same update a deletes another column and types in that cell. After the first deferred read a has no selection, the next two reads have no cursor, and a's next keystroke is dropped. Applied after the update, or as one merged update, the same changes leave the caret in the remaining cell. Documents converge and no text is lost.
    Two possible fixes: have the Reader treat items that only a still-deferred change deleted as live (as isGone does for writes), or have $restoreSelection fall back to the nearest line when the line it resolves is not in the editor. A regression cell would pin either.
    2. A seeded cell drawn from the catalogs. packages/lexical-y/AGENTS.md asks to "Test the input space, not the cases you thought of" and to draw inputs from src/__tests__/catalog/. A small seeded cell could draw both peers' edits from catalog/ops.ts and compare the deferred path with the pending path (the local update still pending when the changes are applied). A cell like that finds the case above.

    <!-- codebunny-pub:1 k=87a27c1e2d02031cd9bd36d4c7f1f206425a35ec2c1648ae59d544e394a4d4f3 -->

    zurfyx zurfyx commented on Nov 04, 2026 22:05 UTC
    Author

    Thanks. (1) Fixed in 49b11dc6: where the binding's view places the caret in a node the editor no longer has (a read rebuilt the container, and a change still deferred removed the node), the editor's own selection is kept if it is still valid, otherwise the caret is resolved on the document as it is. Cell: a later deferred change removes the table column holding the caret (a deletes the first column at row 3; b inserts a column and a row before, then deletes the column a's caret moves into), which fails on d5738d4c, gc off and on. (2) A seeded comparison of the deferred and pending paths over the catalog ops (2,000 seeds per gc) found that class (73 per gc on d5738d4c, 0 now); the remaining differences are carets placed at a different valid spot and concurrent edits ordered differently, with peers and fresh readers agreeing in every case, so it is not added as a cell: its oracle would have to encode which of two valid outcomes each path picks.

    meta-code-review[bot] meta-code-review[bot] commented on Nov 04, 2026 22:06 UTC
    Bot

    In reply to @zurfyx

    That reasoning for not adding the seeded comparison as a permanent cell holds. The comparison already did its job as a probe — it found the caret class (73 per gc on the previous head) and now shows 0 for it — and pinning the remaining differences would mean encoding a choice between two valid outcomes, since peers and fresh readers agree in every case. A test that asserts one valid caret placement or concurrent-edit ordering over another equally valid one would be brittle, not a regression pin. The next full review will re-evaluate this, but I won't press for the seeded cell.

    <!-- codebunny-pub:1 k=dbaf92501a3737d53275711f5922eaa8db49dcbb1ebb8d3168bbcb2f63afcc5a -->

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 22:30 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -2785,6 +2886,25 @@ export class YBinding {
       }
     
       private onAfterTransaction(tr: Transaction): void {
    +    if (tr.origin === this.scanOrigin) {
    +      // Changes nothing (see scanStackItem, getCursor).
    +      return;
    +    }
    +    if (this.defersChange(tr)) {
    +      this.deferChange(tr);
    +      return;
    +    }
    +    if (this.deferred.length > 0 && !this._editor._updating) {
    +      // Read in the order Yjs applied them. (While the editor updates, a
    +      // remote change is deferred behind them, and the binding's own writes
    +      // read nothing: see scheduleDeferred.)
    +      this.readDeferred();

    Optional, non-blocking: here tr is already applied but not in deferred. While each deferred change is read, seer returns the whole document (with tr), and the deferred reads also use up the pendingCursor that beforeTransaction took for tr, so readChange(tr) then runs with cursor === null. Repro: caret after one two in one two three. A peer's bold on another line is applied in a discrete update that changes nothing, then its AAA insert at the start of line 1 is applied outside an update in the same task: the caret ends after AAA. Pushing tr onto deferred (with holdDeleted(tr) when doc.gc) and returning after readDeferred() keeps it after one two, and the @lexical/y unit tests still pass.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 22:30 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -5909,8 +6268,19 @@ export class YBinding {
     
       /** The local selection as relative positions (JSON), or null. */
       getCursor(): YCursor | null {
    -    // On the document as this binding's editor shows it (see guard).
    -    return seenBy(this.seer, () => this.readCursor());
    +    if (this.unread === null) {
    +      // On the document as this binding's editor shows it (see guard).
    +      return seenBy(this.seer, () => this.readCursor());
    +    }
    +    // With changes not read yet: in a transaction that splits the items at
    +    // their bounds (see splitAtUnread), as a write does. The positions are
    +    // ids, which stay valid once Yjs merges the items again.
    +    let cursor: YCursor | null = null;
    +    this._doc.transact(tr => {

    Optional, non-blocking: this makes the public getCursor() emit beforeTransaction/afterTransaction whenever changes are unread. A doc.on('afterTransaction', () => binding.getCursor()) observer then re-enters itself while a change is deferred (each call's transaction cleanup calls it again) until RangeError: Maximum call stack size exceeded comes out of editor.update(). Consider taking the positions without a transaction for external callers, or documenting it, plus a cell with such an observer.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 22:30 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -6821,6 +7213,15 @@ function $showsCaret(): boolean {
      * Why: Lexical keeps such a selection as it is, and every reader of it (a
      * table's own selection handler) would throw.
      */
    +/** Whether `point` is in a node the editor shows. */

    Nit: this sits between $clampSelection's JSDoc (above) and $clampSelection, so that comment now documents $isShownPoint. Moving this function above the comment block fixes it.

    meta-code-review[bot] meta-code-review[bot] approved these changes on Nov 04, 2026 22:30 UTC
    Approved Reviewer

    This looks good, and thanks for the thorough regression file. Deferring the read until the local update has committed and been written fixes the lost edit: the new cells in regressions/RemoteChangeInsideUpdate.test.ts fail on main and pass on this branch, gc off and on. Everything below is optional and non-blocking.

    1. Caret after a remote change that arrives outside an update while an earlier one is deferred (packages/lexical-y/src/internal/Binding.ts, onAfterTransaction, around line 2897). Earlier changes can still be deferred while the editor is idle: an update that committed nothing, or a non-discrete editor.update() still pending in the task. If the next change is then applied outside any update in the same task, readDeferred() reads the deferred ones while the new change is applied but not in deferred. So seer shows it, and $restoreSelection resolves the caret on text that already holds it. The deferred reads also use up the pendingCursor that beforeTransaction took for the new change, so that change is read with cursor === null. Repro: lines one two three / alpha beta, caret after one two. A peer bolds alpha, which is applied in a discrete update that changes nothing; then the peer inserts AAA at the start of line 1, applied outside an update in the same task. The caret ends after AAA instead of after one two. Text and convergence are fine. In that branch, pushing tr onto deferred (holding its deletions when doc.gc) and returning after readDeferred() fixes it, and the @lexical/y unit tests still pass. packages/lexical-y/AGENTS.md asks for a regression cell for each fix in src/__tests__/unit/regressions/; this would be one more.
    2. getCursor() now opens a Yjs transaction while changes are unread (Binding.ts, around line 6279). It used to be a pure read; now each call emits beforeTransaction/afterTransaction to the app's document observers. An app that refreshes its awareness cursor from doc.on('afterTransaction') re-enters itself while a change is deferred: each call opens a transaction whose cleanup calls it again, until RangeError: Maximum call stack size exceeded is thrown out of editor.update(). The update-listener pattern in collaboration/y.md is not affected. Options: take the positions without a transaction in the public method, or document the transaction; a cell with such an observer would cover it either way.
    3. Nit: $isShownPoint was inserted between $clampSelection's JSDoc and the function (around line 7216), so that comment now documents the wrong function.

    <!-- codebunny-pub:1 k=549804a3cb28a72987eff1da906307e8d550e1d349cd06c15c39aced0fef8e82 -->

    zurfyx zurfyx commented on Nov 04, 2026 22:46 UTC
    Author

    Thanks. All three in 58b81689: (1) a change applied outside an update while earlier ones are deferred is pushed onto deferred (held with gc) and read by readDeferred(); cell a remote change applied outside an update while an earlier one waits. (2) The public getCursor() is a pure read again; the binding's own captures use a private takeCursor() with the split transaction; cell an app's document observer that takes the cursor while a change waits (overflowed the stack on 49b11dc6). (3) The JSDoc is back on $clampSelection.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 23:13 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -4340,6 +4693,7 @@ export class YBinding {
         let writer: Writer | null = null;
         try {
           this._doc.transact(tr => {
    +        this.splitAtUnread(tr);

    Optional: writeCursor (L4406-4415, in onUpdate) is captured with $captureCursor() before this split runs. A deferred change that Yjs merged into an item the editor shows is then counted as shown, so undoing the local edit can put the caret before the collaborator's merged text (shared base[k2], B appends [k7], A types [k4], then bolds ba and applies B's update in one editor.update(); after undo() the caret is after [k7], not [k4]). Taking writeCursor inside the same split transaction takeCursor() uses would fix it.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 04, 2026 23:13 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -5907,12 +6272,35 @@ export class YBinding {
       // -------------------------------------------------------------------------
       // Cursors
     
    -  /** The local selection as relative positions (JSON), or null. */
    +  /**
    +   * The local selection as relative positions (JSON), or null. A read of
    +   * the document only: an app may call it from its own document observers
    +   * (an awareness cursor refreshed on every transaction).

    Nit: without the split, the position can sit inside text the editor does not show yet when Yjs merged a deferred change into a shown item, until the deferred read commits (in the same task, for an update that commits). Worth a sentence here, since awareness listeners call this on every update.

    meta-code-review[bot] meta-code-review[bot] approved these changes on Nov 04, 2026 23:13 UTC
    Approved Reviewer

    This looks good to me. Holding a remote change applied during editor.update() until the local commit has been written fixes the lost-edit case. The last commit addresses the earlier caret and re-entrancy concerns: a change that arrives outside an update now queues behind the waiting ones, and getCursor() is a pure read again. Two optional, non-blocking suggestions:

    1. Undo can restore the caret before a collaborator's merged text (packages/lexical-y/src/internal/Binding.ts L4406-4415). writeCursor, the selection an undo step puts back, is captured with $captureCursor() before the write transaction calls splitAtUnread (L4696). When the deferred change continues the collaborator's own run, Yjs merges it into the item the editor shows, so the unread text is counted as shown. Repro: base[k2] is shared; peer B appends [k7] to its own run; peer A types [k4] (caret at the end), then in one editor.update() bolds ba and applies B's update. After binding.undo() the text and formats are right, but the caret lands after base[k2][k7] instead of after [k4]. Capturing writeCursor inside the same split transaction takeCursor() uses would fix it, for example with a small splitWhileUnread(fn) helper shared by both. packages/lexical-y/AGENTS.md asks that every bug fix land with a regression test in src/__tests__/unit/regressions/, so this would make a good extra cell in RemoteChangeInsideUpdate.test.ts.

    2. getCursor() can be off for one commit (Binding.ts L6275-6283). As a pure read it no longer splits items. In the same merged case, an awareness listener set up as the collaboration docs show (registerUpdateListener(() => awareness.setLocalStateField('cursor', binding.getCursor()))) shares a position inside [k7] on the local commit; the deferred read's commit right after it shares the correct one. One sentence in the JSDoc saying the position is exact once the deferred read has committed would be enough.

    Everything else reads well. The changeset ([fix], Verify:), the y.md setup note and DECISIONS.md D108 match the new commit order. The new regression cells assert text, caret, commit tags, convergence and a fresh read, gc off and on.

    <!-- codebunny-pub:1 k=a26af24a77aa6f57c8827f2ae3de2d79cf1e207116107ebb092943fbd1ae5d08 -->

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 05, 2026 00:00 UTC
    Code Review
    packages/lexical-y/src/internal/Binding.ts:1
    @@ -4340,6 +4701,7 @@ export class YBinding {
         let writer: Writer | null = null;
         try {
           this._doc.transact(tr => {
    +        this.splitAtUnread(tr);

    Optional: this split comes after onUpdate has already captured writeCursor (L4414-4423) with $captureCursor(), so with a deferred change Yjs merged into a shown item the undo step stores a caret before the collaborator's unread text, and binding.undo() puts the caret back before the local edit. Taking writeCursor with the items split, as takeCursor() does, fixes it; a cell in RemoteChangeInsideUpdate.test.ts would pin it.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 05, 2026 00:00 UTC
    Code Review
    packages/lexical-website/docs/collaboration/y.md:1
    @@ -331,7 +336,11 @@ right after that update commits, in an update of its own.
     to and from Yjs relative positions for an awareness-based cursor UI; the
     binding does not render remote cursors itself.
     `getCursor()` returns plain JSON, so it can go in the awareness state the
    -provider shares:
    +provider shares. While a remote change applied inside an update waits to be
    +read, it takes the positions in a Yjs transaction that changes nothing (the
    +document's `beforeTransaction` and `afterTransaction` observers see it);
    +called again from those observers, it returns the same positions without
    +opening another:

    Optional: takeCursor() opens this transaction whenever any remote change is unread and no transaction is running, so a document observer that calls getCursor() during a network change applied outside any update (an observeDeep handler, say) triggers one too. Maybe "while a remote change is not read yet (one applied inside an update, or during a document observer's call)", plus a line on getCursor()'s doc comment.

    meta-code-review[bot] meta-code-review[bot] approved these changes on Nov 05, 2026 00:00 UTC
    Approved Reviewer

    This looks good to me. Holding a remote change applied during editor.update() until the local commit has been written fixes the lost-edit case, and the last two commits close the earlier cursor concerns: getCursor() now takes the positions on split items while a change waits, and a gc hold is released only once its read has committed. Two optional, non-blocking suggestions:

    1. Undo can still restore the caret before a collaborator's merged text (packages/lexical-y/src/internal/Binding.ts L4414-4423). writeCursor, the selection an undo step restores, is captured with $captureCursor() before the write transaction calls splitAtUnread (L4704). When the deferred change continues the collaborator's own run, Yjs has already merged it into the item the editor shows, so the capture counts the unread text as shown. Repro: base[k2] is shared; peer B appends [k7] to its own run; peer A types [k4] (caret at the end), then in one editor.update() bolds ba and applies B's update. After binding.undo() the text and formats are right, but the caret lands after base[k2][k7] instead of after [k4], gc off and on. Taking writeCursor with the items split, the way takeCursor() does (for example through a small splitWhileUnread(fn) helper), fixes it and leaves the rest of the packages/lexical-y unit suite unchanged. packages/lexical-y/AGENTS.md asks that every bug fix land with a regression test in src/__tests__/unit/regressions/, so this would make a good extra cell in RemoteChangeInsideUpdate.test.ts.

    2. The getCursor() note in the docs is narrower than the code (packages/lexical-website/docs/collaboration/y.md L339-343). It says the no-op transaction is opened while a change applied inside an update waits to be read. takeCursor() opens one whenever any remote change is unread and no transaction is running, so an app's observeDeep handler that calls getCursor() during a network change applied outside any update makes one too, and the app's afterTransaction observer sees it. Nothing breaks (it changes nothing and emits no update), but widening that sentence, and adding a line to getCursor()'s own doc comment, would tell apps that act on every transaction what to expect.

    Everything else reads well. The changeset ([fix], Verify:), the y.md setup note and DECISIONS.md D108 match the new commit order, as CONTRIBUTING.md and packages/lexical-y/AGENTS.md ask. The new regression cells assert text, caret, commit tags, convergence and a fresh read, gc off and on.

    <!-- codebunny-pub:1 k=0ec6b1f018b5edea430c1ad64942a98b0b03069844968e90362e0724411d6381 -->

    zurfyx zurfyx commented on Nov 05, 2026 00:11 UTC
    Author

    Thanks. Both in 42f41535: (1) writeCursor is taken with the items split (a small splitWhileUnread() helper); cell the caret an undo restores, where Yjs merged a deferred change into shown text fails on e029c386, gc off and on. (2) The setup note and getCursor()'s doc comment now say it opens a transaction that changes nothing (and emits no update) whenever a remote change is not read yet.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 05, 2026 00:34 UTC
    Code Review
    .changeset/lexical-y-remote-change-inside-update.md:1
    @@ -0,0 +1,9 @@
    +---
    +'@lexical/y': patch
    +---
    +
    +[fix] A remote change applied while the editor makes a local update no longer loses that update: it is read right after the update has committed and been written, in a commit of its own
    +
    +A provider that applies a remote change to the document from inside `editor.update()` (a synchronous provider between editors on one page, a test, an app calling `Y.applyUpdate` in an update, a command or a listener that also queues an edit) made the binding read the change inside that update: the read replaced the lines it touched with what the document stored, which did not have the update's edits yet, and the commit took a collaborator's tags, so nothing of the update was written. Text typed in that update was lost, in the editor and in the document. Such a change is now read once the update has committed and been written, in a commit of its own tagged as a collaborator's change, right after it.
    +
    +Verify: inside `editor.update()`, type text and apply a remote change to the document (`Y.applyUpdate`); after the update the editor and every client show both, and update listeners see the local commit, then the remote one. A remote change applied in an update that changes nothing, or that throws, now shows a microtask after `editor.update()` returns, not when it returns.

    Optional, non-blocking: while a remote change is not read yet, getCursor() now takes its positions in a Yjs transaction that changes nothing, which document beforeTransaction/afterTransaction observers see. y.md and the doc comment say so, but release notes come from this file; CONTRIBUTING.md asks a behavior-changing fix to say what to test under Verify:. Consider adding: "While a remote change is not read yet, getCursor() takes the positions in a Yjs transaction that changes nothing (document transaction observers see it)."

    meta-code-review[bot] meta-code-review[bot] approved these changes on Nov 05, 2026 00:34 UTC
    Approved Reviewer

    This looks good to me. Deferring a remote change that a provider applies inside editor.update() (or in a command, a transform or a commit listener) until the local update has committed and been written fixes the lost local edit, and RemoteChangeInsideUpdate.test.ts covers the placements well: 45 of its 82 cells fail on main and all of them pass here with gc off and on, asserting both peers and a fresh reader, and the full @lexical/y suite matches the numbers in the Test plan.

    One optional, non-blocking suggestion:

  • .changeset/lexical-y-remote-change-inside-update.md, line 9: while a remote change is not read yet, getCursor() now takes its positions in a Yjs transaction that changes nothing, which an app's beforeTransaction/afterTransaction observers can see. y.md and the method's doc comment say so, but release notes are built from the changeset. CONTRIBUTING.md asks a fix that changes observable behavior to say what to test under Verify:, so consider one more sentence there, for example: "While a remote change is not read yet, getCursor() takes the positions in a Yjs transaction that changes nothing (document transaction observers see it)."
  • The new commit order (the local commit first, then a COLLABORATION_TAG commit for the remote change) is an intended behavior change, and it is already recorded in the changeset, y.md and DECISIONS.md D108.

    <!-- codebunny-pub:1 k=18c1eb551e22cba1a43d99d345e9c57cfb599b089b884d4b0e0a982af17a1b76 -->

    zurfyx zurfyx commented on Nov 05, 2026 00:36 UTC
    Author

    Thanks. In 7a78d785: the changeset's Verify: paragraph now says that while a remote change is not read yet, getCursor() takes its positions in a Yjs transaction that changes nothing (and emits no update), which the document's transaction observers see. Changeset only.

    meta-code-review[bot] meta-code-review[bot] commented on code on Nov 05, 2026 01:10 UTC
    Code Review
    packages/lexical-website/docs/collaboration/y.md:1
    @@ -331,7 +336,12 @@ right after that update commits, in an update of its own.
     to and from Yjs relative positions for an awareness-based cursor UI; the
     binding does not render remote cursors itself.
     `getCursor()` returns plain JSON, so it can go in the awareness state the
    -provider shares:
    +provider shares. While a remote change is not read yet (one applied inside an
    +update, or one an app's own document observers see before the binding has
    +read it), it takes the positions in a Yjs
    +transaction that changes nothing and emits no `update` (the document's
    +`beforeTransaction` and `afterTransaction` observers see it); called again from

    nit (optional): while a change waits, a getCursor() call made outside a transaction also makes the document emit beforeAllTransactions and afterAllTransactions for its no-op transaction (still no update), so an app that publishes its cursor from afterAllTransactions sees that round too. Maybe: "(the document's transaction observers, afterAllTransactions included, see it)".

    meta-code-review[bot] meta-code-review[bot] approved these changes on Nov 05, 2026 01:10 UTC
    Approved Reviewer

    This looks good to me. Deferring a remote change applied during a local update until that update has committed and been written fixes the lost local edit, and the new regression cells fail on main and pass on this branch with gc off and on, matching the Before and After in the Test plan. The new commit order is recorded where people will find it: the changeset's Verify: paragraph, the setup notes in y.md and decision D108.

    One optional, non-blocking suggestion:

  • packages/lexical-website/docs/collaboration/y.md:343: while a remote change is not read yet, a getCursor() call made outside a transaction opens a no-op Yjs transaction, and the document emits beforeAllTransactions and afterAllTransactions for it as well as beforeTransaction and afterTransaction (still no update). An app that publishes its awareness cursor from afterAllTransactions sees that round too, so the parenthesis could say "(the document's transaction observers, afterAllTransactions included, see it)". The changeset's wording already covers it.
  • <!-- codebunny-pub:1 k=de7dc06bc8f968657e23b0aeff6adf36e986dd14b488e89b207eb3f9a99b47c5 -->

    zurfyx zurfyx commented on Nov 05, 2026 01:11 UTC
    Author

    Thanks. In ce2e4151: the setup note now says the document's transaction observers, afterAllTransactions included, see that transaction. Docs only. (The dependency-check failure on 7a78d785 was the registry returning HTTP 502 for two packages; this push reruns it.)

    meta-code-review[bot] meta-code-review[bot] approved these changes on Nov 05, 2026 01:36 UTC
    Approved Reviewer

    Thanks, this looks good. A remote change applied while a local editor.update() is still running now waits until that update has committed and been written, instead of being read inside it and taking the typed text with it. The new regression cells fail on main with the edit lost on both peers and pass with this change, gc off and on. The intended behavior changes are documented in the changeset's Verify: paragraph, in DECISIONS.md D108 and in the y.md setup notes: a separate collaborator commit after the local one, and getCursor() opening a no-op Yjs transaction while a change is unread.

    One optional, non-blocking suggestion:

  • Draw the new timing from the peer catalog. apply() in packages/lexical-y/src/__tests__/catalog/peers.ts (lines 320-330) only delivers remote updates outside an update, so the matrix contracts and CatalogSoakFuzz never take the deferral path. The cells in RemoteChangeInsideUpdate.test.ts are all hand-picked. packages/lexical-y/AGENTS.md asks tests to "test the input space, not the cases you thought of". A delivery mode that applies the update inside a local editor.update() (and one from an update listener) would keep the class of caret issues the seeded comparison found covered. Checked only against convergence and the bound-editor-equals-fresh-read contract, it would not need a caret oracle.
  • <!-- codebunny-pub:1 k=6236f83df0074ff13bc1792ac764c753f1e53ae215634fd3dc8c7b5c83ece5af -->

    zurfyx zurfyx commented on Nov 05, 2026 01:56 UTC
    Author

    Thanks. On drawing the new timing from the peer catalog: agreed it belongs in the input space, and I'd rather add it as its own change than widen this one, since a delivery mode in catalog/peers.ts reaches every matrix contract and CatalogSoakFuzz run and moves their baselines. For this PR the deferral path was exercised beyond the hand-picked cells by a seeded session lane (10k sessions per gc setting, 24 modes that deliver remote changes inside a local update, from update and mutation listeners, nested, behind other deferred changes, and outside an update while changes wait), checked for convergence, fresh-read equality, no lost keystrokes and the caret, plus a 2,000-seed differential of the waiting path against the pending path per gc setting. The browser-tests (windows-2022, firefox) failure is a playground navigation timeout (elementHandle.type: Timeout 5000ms exceeded); rerunning it.

    meta-code-review[bot] meta-code-review[bot] commented on Nov 05, 2026 01:57 UTC
    Bot

    In reply to @zurfyx

    I'll run a full review to re-check this with your note.

    <!-- codebunny-pub:1 k=cca24076768e70af28f48c2ed4d0490af7e6437973f91173ecbce39cff5f1498 -->

    Reviewers
    Assignees
    zurfyx zurfyx
    Labels
    risk: low confidence: 66.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 65.8% (HIGH) · Higher = larger blast radius
    65.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 66.0% · Lower = rushed or shallow review
    66.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.4% · Safe to merge
    22.4%
    Repository