← Back to Pull requests

[lexical-y] Bug Fix: Keep a line marker with the line that continues the line it ended #9860

Merged
zurfyx merged 6 files (1568 lines) on Nov 11, 2026 01:03 UTC
View on GitHub
zurfyx zurfyx commented on Nov 10, 2026 00:26 UTC
Author

Description

$writeSeq matched a line marker to any marker: only the kind was compared (matchSpecial). Where a collaborator replaced a line (a change of its block type, or a new block of the same type holding its text) and added a block after it in the same update, the common suffix gave the old line's marker to the new block, and the replacement got a new marker. Every reader keys a line by its marker, so on a client composing in that line the composed text node, and the line held while composing, moved to the new block. Ending the composition then re-tokenized a collaborator's untouched code block with the composer's highlighter (dropping its formats, such as underline), or wrote the text the composer typed into the block after the line.

Where a write holds more than one marker on either side, an old marker is now kept only by the line that continues the line it ended ($markerContinues, DECISIONS.md D118), the first of:

1. the line whose last atom (a character, or an inline node kept) is the old line's last atom, by Lexical's record of text edits: the tail of a split, or the line a join or a range delete across lines ends with the joined text;
2. where the old line stays: the one new line after it ending with what it lost from its end (a split the record does not explain); else, where a new line follows it, by position as before (lines pasted at its end, Enter or a paste over a selection reaching its end: the last new line keeps it); else that line itself;
3. where it is gone: a line holding a node it held (a line Lexical replaced, $setBlocksType, or one joined into another), else the one line ending with all of its text (with several, by position);
4. where no line continues it: any line, by position, as before.

A marker the record places is also kept between the common prefix and suffix (withMarkerIslands), so a join or split with a line added after it keeps it; any other marker is kept only at the common prefix or suffix, as before (kept elsewhere, a concurrent join on another client may delete it and leave the line without a boundary). Split: the line holding the tail keeps the marker and the head gets a new one. Join: the line before keeps the marker after the joined text. No character moves for a marker. The attribute repair for a marker another line had ($markerBefore) stays: a split, a join and a replacement still give a line a marker it did not own.

Accepted limit (D118, y.md Limits, test.fails): a line replaced by a new block (holding the same text, or its own nodes with its text changed), or split by app code without the record of text edits, with another line added after it in the same update, gets a new marker, so another collaborator's concurrent change of that line's alignment or block type, or a Delete at its end, is dropped (before, it was applied to the added line). No text is lost.

Stored bytes change only where a line continues the old line and main gave the marker to another one. Over the fuzz seeds and 100 random sessions per gc setting (294 paired sessions), every update and state equals main's; Jot's stored notes (40 per gc) hash equal.

Lanes (13,000 histories per lane and gc, per 1,000, main → this): blockconv ending-phase-other-block 26.5 → 4.2, untouched-block-changed 26.3 → 2.5, ending-phase-text 8.6 → 5.4, ending-phase-code-highlight-outside-code 9.2 → 6.3, ending-phase-boundary 0.1 → 0; carry ending-phase-code-highlight-outside-code 196.5 → 8.5, ending-phase-field 187.3 → 4.6, and decorator-lost, ending-phase-text, other-block-changed, ending-phase-other-block, ending-phase-state → 0. KNOWN_OPEN is updated accordingly.

Pinned outcome changes (cells): A joins a line into the one before and adds a line after it while B joins the next line into the joined one: onetwoadded / three / four (main: onetwo / addedthree / four); likewise for Enter mid-line with a line added after the tail while B deletes at the line's end (hello / worldadded / next; main: hello / world / addednext). Neither keeps both intents.

One class grows: carry:target-value, 7.2 → 9.8. All 71 histories that show it only with this fix are a collaborator joining the held code line into the paragraph before it and adding a block after it; on main the marker went to that added block, and 70 of them showed other findings there (68 decorator-lost). Replayed without the added block, all 71 fail identically on main and with this fix. The last commit records the new rate on its own, to take or drop; the join-path failure is tracked in #9865.

Test plan

Before

$ LANE_STRICT=1 LANE_REPLAY=<untouched history> pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/LaneFuzz.test.ts
untouched-block-changed: code() "let untouched = 1;"{"fmt":8,"kind":"text","note":"old","pnote":""} -> code() "let untouched = 1;"{"fmt":0,"kind":"code-highlight","note":"old","pnote":""}
ending-phase-other-block: kind "text" -> "code-highlight" on "L" (code)
$ LANE_STRICT=1 LANE_REPLAY=<end-text history> ...
ending-phase-text: ins " " in another block
ending-phase-text: ins "z" in another block
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts   # on main
      Tests  32 failed | 88 passed | 28 expected fail (148)

The 32 failures: the composed node moves into the added block, text typed at it lands there, a joined or split line's concurrent change lands on the added line, and a concurrent join of the next line lands on the added line. The 28 expected failures are the accepted limit's cells, which fail on main too.

The two histories are reproduced as cells in MarkerKeptByItsLine.test.ts (gc off and on, both orders of the collaborators' ids), with a split ending with an inline node, app-code splits, a join with a line added after it, lines removed while a collaborator types in one, concurrent deletes across lines with a replaced line, lines pasted at the end of a line, and Enter or a paste over a selection reaching a line's end.

After

$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts
      Tests  120 passed | 28 expected fail (148)
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts packages/lexical-y/src/__tests__/unit/CompositionHoldBack.test.ts packages/lexical-y/src/__tests__/unit/CompositionHoldBackBlockIds.test.ts packages/lexical-y/src/__tests__/unit/Ranges.test.ts packages/lexical-y/src/__tests__/unit/regressions/Composition.test.ts packages/lexical-y/src/__tests__/unit/BlockMarkers.test.ts packages/lexical-y/src/__tests__/unit/BlocksAndLines.test.ts packages/lexical-y/src/__tests__/unit/NormalizationConvergence.test.ts packages/lexical-y/src/__tests__/unit/regressions/ComposeHoldRestyledLineTransform.test.ts
      Tests  3974 passed | 28 expected fail (4002)
$ LEXICAL_Y_GC=1 (the same)
      Tests  3974 passed | 28 expected fail (4002)

Both histories pass strict replay at gc off and on with client ids [11,22], [22,11], [44,55] and [55,44] (and the boundary history 106259, which fails on main). The gate of record (gate20k, kf2k, invns2k) is 0 worse than main; no-hold 0 of 40,000 differ. A rewrite of every line of a 3,200-line container takes about 250 ms (main about 350 ms); remaking every line of a 6,400-line document whose lines share a long ending, or are identical, takes about the same time as on main.

Diff: 1568 lines (+1506 / -62) across 6 files Reviewer: potatowagon Review duration: 1476m
All Vouch review confidence checks passed
Residual risk 0.14 = Change Risk (0.50) × (1 − Review Confidence (0.72)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.50 · 1568 lines diff across 6 files
0.50
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.53 · 5 substantive comment(s)
0.53
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
72%
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
Real PR Conversation Timeline
47 items
vercel[bot] vercel[bot] commented on Nov 10, 2026 00:26 UTC
Bot

[vc]: #Jz0hHWTEa34fsQ4FF8nfjKKGlWRTRh54pq6UxY4ZzO4=:eyJpc01vbm9yZXBvIjp0cnVlLCJ0eXBlIjoiZ2l0aHViIiwicHJvamVjdHMiOlt7Im5hbWUiOiJsZXhpY2FsLXBsYXlncm91bmQiLCJwcm9qZWN0SWQiOiJwcmpfZWE4MnZMajY4NFh6U1JkZU83SlNkMFFOa2F3cyIsInYwIjpmYWxzZSwicm9vdERpcmVjdG9yeSI6InBhY2thZ2VzL2xleGljYWwtcGxheWdyb3VuZCIsImluc3BlY3RvclVybCI6Imh0dHBzOi8vdmVyY2VsLmNvbS9mYm9wZW5zb3VyY2UvbGV4aWNhbC1wbGF5Z3JvdW5kLzQ1cTNvMlA4d0xqaXNmOUR4enYzeGJlNVJDWGQiLCJwcmV2aWV3VXJsIjoibGV4aWNhbC1wbGF5Z3JvdW5kLWdpdC16dXJmeXgteS1tYXJrZXItaWRlbnRpdHktZmJvcGVuc291cmNlLnZlcmNlbC5hcHAiLCJuZXh0Q29tbWl0U3RhdHVzIjoiREVQTE9ZRUQifSx7Im5hbWUiOiJsZXhpY2FsIiwicHJvamVjdElkIjoicHJqX01SYU1PMzFlRklrWTYxU0JxcVBEUjJPank4cVAiLCJ2MCI6ZmFsc2UsInJvb3REaXJlY3RvcnkiOiJwYWNrYWdlcy9sZXhpY2FsLXdlYnNpdGUiLCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vZmJvcGVuc291cmNlL2xleGljYWwvM3BGMms5aEtRNmpmcmU4cnJjWlBram1GQmNDQiIsInByZXZpZXdVcmwiOiJsZXhpY2FsLWdpdC16dXJmeXgteS1tYXJrZXItaWRlbnRpdHktZmJvcGVuc291cmNlLnZlcmNlbC5hcHAiLCJuZXh0Q29tbWl0U3RhdHVzIjoiREVQTE9ZRUQifV0sInJlcXVlc3RSZXZpZXdVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vdmVyY2VsLWFnZW50L3JlcXVlc3QtcmV2aWV3P293bmVyPW1ldGEmcmVwbz1sZXhpY2FsJnByPTk4NjAifQ==
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-10T10:22:06.189Z">Nov 10, 2026 10:22am 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-10T10:22:06.189Z">Nov 10, 2026 10:22am UTC</relative-time> |

<a href="https://vercel.com/vercel-agent/request-review?owner=meta&repo=lexical&pr=9860" 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>

rootnode-bot[bot] rootnode-bot[bot] commented on Nov 10, 2026 00:26 UTC
Bot

AI review status for this pull request.

| Review status | Updated |
| :--- | :--- |
| 🟢 Reviewed (for maintainers only) | <relative-time datetime="2026-11-10T10:41:46Z">Nov 10, 2026, 10:41 AM UTC</relative-time> |

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

pkg-pr-new[bot] pkg-pr-new[bot] commented on Nov 10, 2026 00:29 UTC
Bot

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

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

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


</p></details>

_commit: <a href="https://github.com/meta/lexical/runs/129770342545"><code>6a6c75a</code></a>_

rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 01:19 UTC
Code Review
packages/lexical-y/src/internal/Write.ts:1
@@ -3982,6 +3983,208 @@ export class Writer {
   // -------------------------------------------------------------------------
   // Sequences
 
+  /**
+   * Which old line markers a desired line may keep, where a sequence holds
+   * more than one marker on either side (one line written on its own keeps
+   * its marker): null where there is no choice. Invariant: an old marker is
+   * kept only by the line that continues the line it ended (see D118), the
+   * first of:
+   * - the line whose last character is the old line's last character, by
+   *   Lexical's record of text edits (`record`, see $exactAtoms): the tail of
+   *   a split (Enter in the middle of a line: the new line keeps the marker
+   *   after the tail and the old line, holding the head, gets a new one, so
+   *   no character moves), or the line a join or a range delete across lines
+   *   ends with the joined text (it keeps the marker after that text, and its
+   *   own goes);
+   * - that line itself (the same key), where it stays;
+   * - where it is gone: the lines holding a node it held before this update
+   *   (a line Lexical replaced, `$setBlocksType`, or one joined into another),
+   *   else the lines ending with all of its text (a paste over it);
+   * - else none: the line gets a new marker (a line without a key keeps the
+   *   old rule).
+   * Why: a marker matched any marker, so where a collaborator replaced a
+   * line and added another after it, the common suffix gave the old marker
+   * to the new line; every reader keys a line by its marker, so the old
+   * line's node, and a composition in it, moved to the new line (and the
+   * composer's highlighter re-tokenized it, or its typing landed there).
+   */
+  private $markerContinues(
+    old: Atoms,
+    atoms: Atoms,
+    record: {of: Int32Array; kept: Int32Array} | null,
+  ): ((i: number, j: number) => boolean) | null {
+    const oldAt: number[] = [];
+    const newAt: number[] = [];
+    old.specials.forEach((sp, i) => {
+      if (sp.kind === 'marker') {
+        oldAt.push(i);
+      }
+    });
+    atoms.specials.forEach((sp, j) => {
+      if (sp.kind === 'marker') {
+        newAt.push(j);
+      }
+    });
+    if (oldAt.length <= 1 && newAt.length <= 1) {
+      return null;
+    }
+    oldAt.sort((x, y) => x - y);
+    newAt.sort((x, y) => x - y);
+    const prevMap = this.prevState._nodeMap;
+    // The text of the line ending at the `k`th marker (from the one before),
+    // and the atom before that marker where it is in that line (else -1).
+    const textOf = (a: Atoms, at: number[], k: number) =>
+      a.text.slice(k === 0 ? 0 : at[k - 1] + 1, at[k]);
+    const lastOf = (at: number[], k: number) =>
+      at[k] - 1 >= (k === 0 ? 0 : at[k - 1] + 1) ? at[k] - 1 : -1;
+    const newLines = newAt.map((j, k) => {
+      const d = (atoms.specials.get(j) as {ref: unknown}).ref as Desired;
+      const to = d.key === null ? null : lineOfUnit(d.key);
+      return {
+        isNew: to !== null && !prevMap.has(to),
+        j,
+        now: textOf(atoms, newAt, k),
+        to,
+      };
+    });
+    // The desired lines (or parts of one, see $pushLine) of each line key.
+    const lines = new Map<NodeKey, number[]>();
+    // Which desired lines hold each node, and end with each short text.
+    const holders = new Map<NodeKey, number[]>();
+    const enders = new Map<string, number[]>();
+    const add = <K>(m: Map<K, number[]>, k: K, v: number) => {
+      const l = m.get(k);
+      if (l === undefined) {
+        m.set(k, [v]);
+      } else if (l[l.length - 1] !== v) {
+        l.push(v);
+      }
+    };
+    const ENDING = 8;
+    newLines.forEach((n, k) => {
+      if (n.to !== null) {
+        add(lines, n.to, k);
+      }
+      for (let len = 1; len <= ENDING && len <= n.now.length; len++) {
+        add(enders, n.now.slice(-len), k);
+      }
+    });
+    // The desired line whose last character Lexical's record says is old
+    // atom `i`.
+    const recorded = new Map<number, number>();
+    if (record !== null) {
+      newAt.forEach((_, k) => {
+        const nj = lastOf(newAt, k);
+        if (nj >= 0 && record.of[nj] >= 0) {
+          recorded.set(record.of[nj], k);
+        }
+      });
+    }
+    // Built when a line that is gone is looked for (see below).
+    let indexed = false;
+    const $indexHolders = () => {
+      indexed = true;
+      newLines.forEach((n, k) => {
+        const d = (atoms.specials.get(n.j) as {ref: unknown}).ref as Desired;
+        const stack: (LexicalNode | null | undefined)[] = [...$lineChildren(d)];
+        while (stack.length > 0) {
+          const node = stack.pop();
+          if (!$isLexicalNode(node)) {
+            continue;
+          }
+          add(holders, node.getKey(), k);
+          if ($isElementNode(node)) {
+            stack.push(...node.getChildren());
+          }
+        }
+      });
+    };
+    const $heldBefore = (line: NodeKey): NodeKey[] => {
+      const out: NodeKey[] = [];
+      const stack = [line];
+      while (stack.length > 0) {
+        const n = prevMap.get(stack.pop()!);
+        if (n !== undefined && $isElementNode(n)) {
+          let c = n.__first;
+          while (c !== null) {
+            out.push(c);
+            stack.push(c);
+            const next = prevMap.get(c);
+            c = next === undefined ? null : next.__next;
+          }
+        }
+      }
+      return out;
+    };
+    // The desired lines ending with `text` (all of it).
+    const endingWith = (text: string): number[] => {
+      const l = enders.get(text.slice(-ENDING)) ?? [];
+      return text.length <= ENDING
+        ? l
+        : l.filter(k => newLines[k].now.endsWith(text));
+    };
+    const ANY = null;
+    // Lines without a key: kept as before by a marker no line claims.
+    const keyless = new Set<number>();
+    newLines.forEach((n, k) => {
+      if (n.to === null) {
+        keyless.add(k);
+      }
+    });
+    // The desired lines with the strongest claim on each old marker (ANY:
+    // every line, where the marker's line is not known), see the rules
+    // above. A line that stays keeps its marker unless the record gives its
+    // last character to another line (the tail of a split).
+    const best = new Map<number, Set<number> | null>();
+    oldAt.forEach((i, ki) => {
+      const owner = this.ownerBefore(
+        (old.specials.get(i) as {ref: unknown}).ref as Item,
+      );
+      if (owner === null) {
+        best.set(i, ANY);
+        return;
+      }
+      const oi = lastOf(oldAt, ki);
+      const byRecord =
+        oi >= 0 && !old.specials.has(oi) ? recorded.get(oi) : undefined;

Must fix. This rule only gives the old marker to the tail of a split when the old line's last atom is a character. When the line ends with an inline decorator, byRecord is undefined, the line that kept its key (the head) claims the marker at 4154, and the head cannot keep it in place. The old marker item is deleted, and a collaborator's concurrent change to that line is lost on every client.

Repro: A presses Enter after hello in hello world <equation> while B, offline, centers the paragraph, converts it to h2, or indents it. On main the tail line keeps B's change; here it does not, in either client-id order.

$exactAtoms already maps kept inline nodes (place(j, 1, key, true)), so accepting them here brings back main's result for these cases while MarkerKeptByItsLine.test.ts still passes:

const byRecord =
  oi >= 0 &&
  (!old.specials.has(oi) || old.specials.get(oi)!.kind === 'oldNode')
    ? recorded.get(oi)
    : undefined;

rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 01:19 UTC
Code Review
packages/lexical-y/src/internal/Write.ts:1
@@ -3982,6 +3983,208 @@ export class Writer {
   // -------------------------------------------------------------------------
   // Sequences
 
+  /**
+   * Which old line markers a desired line may keep, where a sequence holds
+   * more than one marker on either side (one line written on its own keeps
+   * its marker): null where there is no choice. Invariant: an old marker is
+   * kept only by the line that continues the line it ended (see D118), the
+   * first of:
+   * - the line whose last character is the old line's last character, by
+   *   Lexical's record of text edits (`record`, see $exactAtoms): the tail of
+   *   a split (Enter in the middle of a line: the new line keeps the marker
+   *   after the tail and the old line, holding the head, gets a new one, so
+   *   no character moves), or the line a join or a range delete across lines
+   *   ends with the joined text (it keeps the marker after that text, and its
+   *   own goes);
+   * - that line itself (the same key), where it stays;
+   * - where it is gone: the lines holding a node it held before this update
+   *   (a line Lexical replaced, `$setBlocksType`, or one joined into another),
+   *   else the lines ending with all of its text (a paste over it);
+   * - else none: the line gets a new marker (a line without a key keeps the
+   *   old rule).
+   * Why: a marker matched any marker, so where a collaborator replaced a
+   * line and added another after it, the common suffix gave the old marker
+   * to the new line; every reader keys a line by its marker, so the old
+   * line's node, and a composition in it, moved to the new line (and the
+   * composer's highlighter re-tokenized it, or its typing landed there).
+   */
+  private $markerContinues(
+    old: Atoms,
+    atoms: Atoms,
+    record: {of: Int32Array; kept: Int32Array} | null,
+  ): ((i: number, j: number) => boolean) | null {
+    const oldAt: number[] = [];
+    const newAt: number[] = [];
+    old.specials.forEach((sp, i) => {
+      if (sp.kind === 'marker') {
+        oldAt.push(i);
+      }
+    });
+    atoms.specials.forEach((sp, j) => {
+      if (sp.kind === 'marker') {
+        newAt.push(j);
+      }
+    });
+    if (oldAt.length <= 1 && newAt.length <= 1) {
+      return null;
+    }
+    oldAt.sort((x, y) => x - y);
+    newAt.sort((x, y) => x - y);
+    const prevMap = this.prevState._nodeMap;
+    // The text of the line ending at the `k`th marker (from the one before),
+    // and the atom before that marker where it is in that line (else -1).
+    const textOf = (a: Atoms, at: number[], k: number) =>
+      a.text.slice(k === 0 ? 0 : at[k - 1] + 1, at[k]);
+    const lastOf = (at: number[], k: number) =>
+      at[k] - 1 >= (k === 0 ? 0 : at[k - 1] + 1) ? at[k] - 1 : -1;
+    const newLines = newAt.map((j, k) => {
+      const d = (atoms.specials.get(j) as {ref: unknown}).ref as Desired;
+      const to = d.key === null ? null : lineOfUnit(d.key);
+      return {
+        isNew: to !== null && !prevMap.has(to),

isNew is computed but never read. The description's rule 3 ("or the line is new") and rule 4 ("the tail of a split: a new line ending with what the old line, which stays, lost from its end") seem to be what it was for. Without them, a split Lexical's record does not explain (app code that calls setTextContent on the head and adds a paragraph holding the tail) deletes the old marker, and a collaborator's concurrent alignment on that line is lost. On main it lands on the tail.

rootnode-bot[bot] rootnode-bot[bot] requested changes on Nov 10, 2026 01:19 UTC
Changes Requested Reviewer

Thanks for tracking this down. The two repros are real, and the new regression file proves the fix: it fails 8/8 on main and passes on this branch, and a blockconv lane run shows the three classes named in the description dropping. One regression needs fixing before this can merge, plus a few smaller follow-ups.

Must fix: a split now drops a collaborator's change to the line when the line ends with an inline node

packages/lexical-y/src/internal/Write.ts:4148-4149: the record rule only gives the old marker to the tail of a split when the old line's last atom is a character (!old.specials.has(oi)). When the line ends with an inline decorator (an equation, an image, a mention), the line that kept its key, which is the head, claims the marker. The head cannot keep it in place, because the marker sits after the tail's text. So the old marker item is deleted and two new markers are written, and whatever a collaborator wrote to that line at the same time is lost on every client.

Repro (both client-id orders; all peers and a fresh reader converge): A presses Enter after hello in hello world <equation>, while B, offline, centers that paragraph, converts it to h2, or indents it. On main the tail line ends up centered, a heading, or indented. On this branch none of the three survive. The same happens when app code splits the line with setTextContent('hello ') plus a new paragraph holding world, or by replacing the text node.

This contradicts D118 ("Split: the line holding the tail keeps the marker") and the description's statement that Enter stores the same as before. A possible fix: let the record rule accept a kept inline node as the old line's last atom. $exactAtoms already maps those (place(j, 1, key, true)), so a guard such as (!old.specials.has(oi) || old.specials.get(oi)!.kind === 'oldNode') brings back main's result for the decorator cases while MarkerKeptByItsLine.test.ts still passes. The app-code split also needs the split-by-text claim the description lists as rule 4 ("a new line ending with what the old line, which stays, lost from its end"). The code only matches text where the old line is gone, and isNew (line 4044) is computed but never read. packages/lexical-y/AGENTS.md asks that every bug fix land with a regression test in src/__tests__/unit/regressions/, so please add these repros there.

Consider

  • A line remade with the same text, with a new line added after it (a paste over it), still loses its marker. Rule 4 claims the marker for the remade line, but the record treats the remade text as new, so the diff's prefix stops before the marker and a collaborator's concurrent alignment is dropped (on main it went to the added line). D118's "a line ending with all of its text (a paste over it)" does not hold in that case.

  • KNOWN_OPEN in LaneFuzz.test.ts asks that a fix which reduces a class lower its per1000, and that the fix which brings it to zero remove the entry. Its triage note still says this fix is planned as a separate pull request. In a 400-history blockconv run, untouched-block-changed went from 8 to 0, ending-phase-other-block from 8 to 1, and ending-phase-text from 1 to 0.

  • The Test plan's LANE_REPLAY=untouched.json and end-text.json files are not in the repository, so those runs cannot be replayed.
  • Nits

  • Please add a changeset for @lexical/y (AGENTS.md "Changesets", .changeset/README.md): a [fix] entry with a Verify: paragraph, like the other pending @lexical/y fixes.

  • The enders map (Write.ts:4063-4071) is built on every multi-marker write, though only a line that is gone reads it. It could be built lazily, like $indexHolders.
  • <!-- codebunny-pub:1 k=554d77ee601e33b2fc9a3fc0420cd4ca83790baa1015ce9237ea1781015b0ce7 -->

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 03:22 UTC
    Code Review
    packages/lexical-y/src/internal/Write.ts:1
    @@ -3982,6 +3983,251 @@ export class Writer {
       // -------------------------------------------------------------------------
       // Sequences
     
    +  /**
    +   * Which old line markers a desired line may keep, where a sequence holds
    +   * more than one marker on either side (one line written on its own keeps
    +   * its marker): null where there is no choice. Invariant: an old marker is
    +   * kept only by the line that continues the line it ended (see D118), the
    +   * first of:
    +   * - the line whose last atom is the old line's last atom (a character, or
    +   *   an inline node kept), by Lexical's record of text edits (`record`, see
    +   *   $exactAtoms): the tail of a split (Enter in the middle of a line: the
    +   *   new line keeps the marker after the tail and the old line, holding the
    +   *   head, gets a new one, so no character moves), or the line a join or a
    +   *   range delete across lines ends with the joined text (it keeps the
    +   *   marker after that text, and its own goes);
    +   * - where the old line stays: a new line ending with what it lost from its
    +   *   end (a split the record does not explain: app code that sets the
    +   *   head's text and adds a line holding the tail), else that line itself;
    +   * - where it is gone: the lines holding a node it held before this update
    +   *   (a line Lexical replaced, `$setBlocksType`, or one joined into another),
    +   *   else the lines ending with all of its text (a paste over it);
    +   * - else, where no line continues it, any line, by position as before.
    +   * Why: a marker matched any marker, so where a collaborator replaced a
    +   * line and added another after it, the common suffix gave the old marker
    +   * to the new line; every reader keys a line by its marker, so the old
    +   * line's node, and a composition in it, moved to the new line (and the
    +   * composer's highlighter re-tokenized it, or its typing landed there).
    +   */
    +  private $markerContinues(
    +    old: Atoms,
    +    atoms: Atoms,
    +    record: {of: Int32Array; kept: Int32Array} | null,
    +  ): {
    +    match: (i: number, j: number) => boolean;
    +    anchored: Set<number>;
    +  } | null {
    +    const oldAt: number[] = [];
    +    const newAt: number[] = [];
    +    old.specials.forEach((sp, i) => {
    +      if (sp.kind === 'marker') {
    +        oldAt.push(i);
    +      }
    +    });
    +    atoms.specials.forEach((sp, j) => {
    +      if (sp.kind === 'marker') {
    +        newAt.push(j);
    +      }
    +    });
    +    if (oldAt.length <= 1 && newAt.length <= 1) {
    +      return null;
    +    }
    +    oldAt.sort((x, y) => x - y);
    +    newAt.sort((x, y) => x - y);
    +    const prevMap = this.prevState._nodeMap;
    +    // The text of the line ending at the `k`th marker (from the one before),
    +    // and the atom before that marker where it is in that line (else -1).
    +    const textOf = (a: Atoms, at: number[], k: number) =>
    +      a.text.slice(k === 0 ? 0 : at[k - 1] + 1, at[k]);
    +    const lastOf = (at: number[], k: number) =>
    +      at[k] - 1 >= (k === 0 ? 0 : at[k - 1] + 1) ? at[k] - 1 : -1;
    +    const newLines = newAt.map((j, k) => {
    +      const d = (atoms.specials.get(j) as {ref: unknown}).ref as Desired;
    +      const to = d.key === null ? null : lineOfUnit(d.key);
    +      return {
    +        isNew: to !== null && !prevMap.has(to),
    +        j,
    +        now: textOf(atoms, newAt, k),
    +        to,
    +      };
    +    });
    +    // The desired lines (or parts of one, see $pushLine) of each line key.
    +    const lines = new Map<NodeKey, number[]>();
    +    // Which desired lines hold each node, and end with each short text.
    +    const holders = new Map<NodeKey, number[]>();
    +    const enders = new Map<string, number[]>();
    +    const add = <K>(m: Map<K, number[]>, k: K, v: number) => {
    +      const l = m.get(k);
    +      if (l === undefined) {
    +        m.set(k, [v]);
    +      } else if (l[l.length - 1] !== v) {
    +        l.push(v);
    +      }
    +    };
    +    const ENDING = 8;
    +    newLines.forEach((n, k) => {
    +      if (n.to !== null) {
    +        add(lines, n.to, k);
    +      }
    +    });
    +    // The desired line whose last character Lexical's record says is old
    +    // atom `i`.
    +    const recorded = new Map<number, number>();
    +    if (record !== null) {
    +      newAt.forEach((_, k) => {
    +        const nj = lastOf(newAt, k);
    +        if (nj >= 0 && record.of[nj] >= 0) {
    +          recorded.set(record.of[nj], k);
    +        }
    +      });
    +    }
    +    // Built when a line that is gone is looked for (see below).
    +    let indexed = false;
    +    const $indexHolders = () => {
    +      indexed = true;
    +      newLines.forEach((n, k) => {
    +        const d = (atoms.specials.get(n.j) as {ref: unknown}).ref as Desired;
    +        const stack: (LexicalNode | null | undefined)[] = [...$lineChildren(d)];
    +        while (stack.length > 0) {
    +          const node = stack.pop();
    +          if (!$isLexicalNode(node)) {
    +            continue;
    +          }
    +          add(holders, node.getKey(), k);
    +          if ($isElementNode(node)) {
    +            stack.push(...node.getChildren());
    +          }
    +        }
    +      });
    +    };
    +    const $heldBefore = (line: NodeKey): NodeKey[] => {
    +      const out: NodeKey[] = [];
    +      const stack = [line];
    +      while (stack.length > 0) {
    +        const n = prevMap.get(stack.pop()!);
    +        if (n !== undefined && $isElementNode(n)) {
    +          let c = n.__first;
    +          while (c !== null) {
    +            out.push(c);
    +            stack.push(c);
    +            const next = prevMap.get(c);
    +            c = next === undefined ? null : next.__next;
    +          }
    +        }
    +      }
    +      return out;
    +    };
    +    // The desired lines ending with `text` (all of it).
    +    const endingWith = (text: string): number[] => {
    +      if (enders.size === 0) {
    +        newLines.forEach((n, k) => {
    +          for (let len = 1; len <= ENDING && len <= n.now.length; len++) {
    +            add(enders, n.now.slice(-len), k);
    +          }
    +        });
    +      }
    +      const l = enders.get(text.slice(-ENDING)) ?? [];
    +      return text.length <= ENDING
    +        ? l
    +        : l.filter(k => newLines[k].now.endsWith(text));
    +    };
    +    const ANY = null;
    +    // Lines without a key: kept as before by a marker no line claims.
    +    // The desired lines with the strongest claim on each old marker (ANY:
    +    // every line, where the marker's line is not known), see the rules
    +    // above. A line that stays keeps its marker unless the record gives its
    +    // last character to another line (the tail of a split).
    +    const best = new Map<number, Set<number> | null>();
    +    // Old markers the record gives a line (see withMarkerIslands).
    +    const anchored = new Set<number>();
    +    oldAt.forEach((i, ki) => {
    +      const owner = this.ownerBefore(
    +        (old.specials.get(i) as {ref: unknown}).ref as Item,
    +      );
    +      if (owner === null) {
    +        best.set(i, ANY);
    +        return;
    +      }
    +      const oi = lastOf(oldAt, ki);
    +      // A character, or an inline node kept (an equation the line ends
    +      // with), see $exactAtoms.
    +      const lastSpecial = oi < 0 ? undefined : old.specials.get(oi);
    +      const lastKind =
    +        oi < 0
    +          ? null
    +          : lastSpecial === undefined
    +            ? undefined
    +            : lastSpecial.kind;
    +      const byRecord =
    +        oi >= 0 && (lastKind === undefined || lastKind === 'oldNode')
    +          ? recorded.get(oi)
    +          : undefined;
    +      const from = lineOfUnit(owner);
    +      let set = new Set<number>();
    +      if (byRecord !== undefined) {
    +        set.add(byRecord);
    +        anchored.add(i);
    +      } else if (lines.has(from)) {
    +        // The line stays: it keeps its marker, unless a new line ends with
    +        // what it lost from its end (a split the record does not explain,
    +        // app code that sets the head's text and adds a line holding the
    +        // tail), which keeps the marker after that text.
    +        const own = lines.get(from)!;
    +        const was = textOf(old, oldAt, ki);
    +        const head = newLines[own[0]].now;
    +        let n = 0;
    +        while (n < was.length && n < head.length && was[n] === head[n]) {
    +          n++;
    +        }
    +        const tail = was.slice(n);
    +        const tails =
    +          tail.length > 0 && head.length < was.length
    +            ? endingWith(tail).filter(k => newLines[k].isNew)

    Consider (non-blocking). A split always puts the tail after the head, but this accepts any new line ending with what the line lost. App code that, in one update, sets hello world to hello and inserts a new paragraph world before it leaves the old marker claimable only by world; that marker is not anchored, so it is deleted, and a collaborator's concurrent centering or h2 of the line is lost on every client (main keeps it on hello , in both client-id orders). Limiting the claim to lines after the line gives that back and keeps MarkerKeptByItsLine.test.ts at 36/36:

                ? endingWith(tail).filter(
                    k => newLines[k].isNew && k > own[own.length - 1],
                  )
    

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 03:22 UTC
    Code Review
    packages/lexical-y/DECISIONS.md:1
    @@ -76,6 +76,7 @@ issues and docs that carry it.
     | D28 | **Text identity is fixed at the source.** While a binding is attached, core records text edits (`spliceText`, insert and remove, split and merge), and text entity plugins record a grow as a move and a remake as a retype. Text only `setTextContent` or the DOM changed is diffed. The binding adds no per-case heuristics. | No binding can recover intent an API dropped; special-case rules were fragile and regressed neighbouring cases. | `DECIDED` | 10-27 | [#9483], [y.md: Edits made by code][y-code] |
     | D29 | **Remade text keeps its common start and end by character**, whatever the node boundaries (y-prosemirror's `updateYText` rule), **and between two changes every run of unchanged whole words** (the longest common run of words, by a linear-space shortest edit script over the words both texts have, up to 2,048 edits, words only added or only removed between a shared start and end taking none, linear in the line's length; past it, only the start and end; where a word repeats next to a change, which occurrence is kept follows that edit script (`aa bb` made again as `aa aa bb` keeps the first `aa`); a word the update moved is written again; a word changed only in part is written whole, so a collaborator's undone delete of its unchanged part shows twice, [#9635]), and never brings back a collaborator's delete. Text set whole (`setTextContent`, the DOM's text) keeps its unchanged words between two changes the same way ([#9666]; not yet where text edits are not recorded and the update also changes the node's attributes). It replaces the word matching of [#9565]. | It is the industry-standard behaviour, and word matching glued words together and merged numbers oddly. Keeping only the start and end wrote everything between two changed words again, so a collaborator's delete there came back, and showed twice after the collaborator's undo ([#9621]). | `DECIDED` | 10-30 | [#9565], [#9598], [#9621] |
     | D30 | **Diffed rewrites snap to whole words**; keystrokes and IME composition keep the exact diff. Scripts without spaces treat each character as a boundary. **A diffed insertion or deletion that no caret places (none, or one at the end of the node, past the edit or in a later node) and that the diff would put inside a word goes to the first place in the run of equal text it could be in where both its ends are at word edges** (a word deleted with the separator before it); a caret's placement, and one already at word edges, stay. | Concurrent rewrites otherwise split words. Real word segmentation is a follow-up ([#9467]). Without a caret a diff takes the common start first and put deletions inside words, so a collaborator's concurrent delete of the same word took a letter of the next one ([#9636]); the first edge keeps a word typed after a deleted word apart from the next one, as typing goes (a space, then a word). | `DECIDED` | 10-30 | [#9400], [#9467], [#9636] |
    +| D118 | **A line marker is kept only by the line that continues the line it ended.** Where a write holds more than one marker on either side, an old marker is kept by the line whose last atom (a character, or an inline node kept) is the old line's last atom, by Lexical's record of text edits (D28); else, where the old line stays, by a new line ending with what it lost from its end, or else by that line itself; else, where it is gone, by a line holding a node it held (a line Lexical replaced, `$setBlocksType`, or one joined into another) or else by a line ending with all of its text (a paste over it); otherwise by position, as before. A marker the record places is kept where its line is, also between the common prefix and suffix. Split: the line holding the tail keeps the marker, and the head gets a new one. Join (and a range delete across lines): the line before keeps the marker after the joined text, and its own goes. No character moves for a marker. A marker no line continues (its line is gone, and no line holds what it held or ends with its text) is kept by position, as before, by any line: so text a collaborator typed into a removed or moved line at the same time keeps joining the end of the line before, and a client composing in a line a collaborator removed has the same result as before. | A marker matched any marker (only the kind was compared), so where a collaborator replaced a line and added another after it, the common suffix gave the old line's marker to the new line. Every reader keys a line by its marker, so the old line's node, a composition in it and the line held while composing moved to the new line: ending the composition re-tokenized a collaborator's untouched code block with the composer's highlighter, dropping its format and NodeState, or wrote what the composer typed into the block after the line. A marker kept by a line that is not its own line keeps a collaborator's concurrent change of the line's attributes on the line holding its end, as before; the attribute repair for such a marker (`$markerBefore`) stays, since a split, a join and a replacement still give a line a marker it did not own. | `DECIDED` | 11-09 | [#9860] |

    Consider (non-blocking). "or else by a line ending with all of its text (a paste over it)" does not hold when a line is added after the remade line: replace abc with a new paragraph abc and add xyz after it while a collaborator centers the line, and the marker is deleted (the record treats the remade text as new, so the prefix stops before the marker, and only record-placed markers become islands), so the centering is dropped on every client. main applied it to xyz. Either keep such a marker as an island, or narrow this sentence and add a test.fails for the case (packages/lexical-y/AGENTS.md, Testing).

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 10, 2026 03:22 UTC
    Approved Reviewer

    This looks good to me. The marker fix is well targeted, and the new regression file shows it working: 16 of its 36 cells fail on main (the composed node moves into the added block, and a joined line's concurrent change lands on the added line), and all of them pass here. In every case I tried, Enter, Backspace and range deletes across lines store the same as on main, and both items from the earlier review are fixed. The suggestions below are optional and non-blocking.

    Optional: limit the tail claim to new lines after the line (packages/lexical-y/src/internal/Write.ts:4185)

    A split always puts the tail after the head, but this claim accepts any new line that ends with what the line lost. Say app code, in one update, sets hello world to hello and inserts a new paragraph world before it. Only world can then claim the old marker, and that marker is not anchored, so it is deleted. A collaborator's concurrent centering or heading of that line is then lost on every client. On main it stays on hello . This change keeps MarkerKeptByItsLine.test.ts passing and gives main's result back:

    ? endingWith(tail).filter(
        k => newLines[k].isNew && k > own[own.length - 1],
      )
    

    Optional: D118's paste-over sentence (packages/lexical-y/DECISIONS.md:79)

    D118 says a removed line's marker is kept "by a line ending with all of its text (a paste over it)". That does not hold when a line is added after the remade line. Replace abc with a new paragraph abc and add xyz after it while a collaborator centers the line: the marker is deleted and the centering is dropped (main applied it to xyz). Either keep such a marker as an island, or narrow the sentence.

    Optional: cells for both cases. packages/lexical-y/AGENTS.md asks for a regression test in src/__tests__/unit/regressions/ with each fix, and a test.fails for a known failure. The run(...) harness in MarkerKeptByItsLine.test.ts covers both with two more calls.

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

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 04:42 UTC
    Code Review
    packages/lexical-y/src/internal/Write.ts:1
    @@ -3982,6 +3983,255 @@ export class Writer {
       // -------------------------------------------------------------------------
       // Sequences
     
    +  /**
    +   * Which old line markers a desired line may keep, where a sequence holds
    +   * more than one marker on either side (one line written on its own keeps
    +   * its marker): null where there is no choice. Invariant: an old marker is
    +   * kept only by the line that continues the line it ended (see D118), the
    +   * first of:
    +   * - the line whose last atom is the old line's last atom (a character, or
    +   *   an inline node kept), by Lexical's record of text edits (`record`, see
    +   *   $exactAtoms): the tail of a split (Enter in the middle of a line: the
    +   *   new line keeps the marker after the tail and the old line, holding the
    +   *   head, gets a new one, so no character moves), or the line a join or a
    +   *   range delete across lines ends with the joined text (it keeps the
    +   *   marker after that text, and its own goes);
    +   * - where the old line stays: a new line after it ending with what it
    +   *   lost from its end (a split the record does not explain: app code that
    +   *   sets the head's text and adds a line holding the tail), else that line
    +   *   itself;
    +   * - where it is gone: the lines holding a node it held before this update
    +   *   (a line Lexical replaced, `$setBlocksType`, or one joined into another),
    +   *   else the lines ending with all of its text (a paste over it);
    +   * - else, where no line continues it, any line, by position as before.
    +   * Why: a marker matched any marker, so where a collaborator replaced a
    +   * line and added another after it, the common suffix gave the old marker
    +   * to the new line; every reader keys a line by its marker, so the old
    +   * line's node, and a composition in it, moved to the new line (and the
    +   * composer's highlighter re-tokenized it, or its typing landed there).
    +   */
    +  private $markerContinues(
    +    old: Atoms,
    +    atoms: Atoms,
    +    record: {of: Int32Array; kept: Int32Array} | null,
    +  ): {
    +    match: (i: number, j: number) => boolean;
    +    anchored: Set<number>;
    +  } | null {
    +    const oldAt: number[] = [];
    +    const newAt: number[] = [];
    +    old.specials.forEach((sp, i) => {
    +      if (sp.kind === 'marker') {
    +        oldAt.push(i);
    +      }
    +    });
    +    atoms.specials.forEach((sp, j) => {
    +      if (sp.kind === 'marker') {
    +        newAt.push(j);
    +      }
    +    });
    +    if (oldAt.length <= 1 && newAt.length <= 1) {
    +      return null;
    +    }
    +    oldAt.sort((x, y) => x - y);
    +    newAt.sort((x, y) => x - y);
    +    const prevMap = this.prevState._nodeMap;
    +    // The text of the line ending at the `k`th marker (from the one before),
    +    // and the atom before that marker where it is in that line (else -1).
    +    const textOf = (a: Atoms, at: number[], k: number) =>
    +      a.text.slice(k === 0 ? 0 : at[k - 1] + 1, at[k]);
    +    const lastOf = (at: number[], k: number) =>
    +      at[k] - 1 >= (k === 0 ? 0 : at[k - 1] + 1) ? at[k] - 1 : -1;
    +    const newLines = newAt.map((j, k) => {
    +      const d = (atoms.specials.get(j) as {ref: unknown}).ref as Desired;
    +      const to = d.key === null ? null : lineOfUnit(d.key);
    +      return {
    +        isNew: to !== null && !prevMap.has(to),
    +        j,
    +        now: textOf(atoms, newAt, k),
    +        to,
    +      };
    +    });
    +    // The desired lines (or parts of one, see $pushLine) of each line key.
    +    const lines = new Map<NodeKey, number[]>();
    +    // Which desired lines hold each node, and end with each short text.
    +    const holders = new Map<NodeKey, number[]>();
    +    const enders = new Map<string, number[]>();
    +    const add = <K>(m: Map<K, number[]>, k: K, v: number) => {
    +      const l = m.get(k);
    +      if (l === undefined) {
    +        m.set(k, [v]);
    +      } else if (l[l.length - 1] !== v) {
    +        l.push(v);
    +      }
    +    };
    +    const ENDING = 8;
    +    newLines.forEach((n, k) => {
    +      if (n.to !== null) {
    +        add(lines, n.to, k);
    +      }
    +    });
    +    // The desired line whose last character Lexical's record says is old
    +    // atom `i`.
    +    const recorded = new Map<number, number>();
    +    if (record !== null) {
    +      newAt.forEach((_, k) => {
    +        const nj = lastOf(newAt, k);
    +        if (nj >= 0 && record.of[nj] >= 0) {
    +          recorded.set(record.of[nj], k);
    +        }
    +      });
    +    }
    +    // Built when a line that is gone is looked for (see below).
    +    let indexed = false;
    +    const $indexHolders = () => {
    +      indexed = true;
    +      newLines.forEach((n, k) => {
    +        const d = (atoms.specials.get(n.j) as {ref: unknown}).ref as Desired;
    +        const stack: (LexicalNode | null | undefined)[] = [...$lineChildren(d)];
    +        while (stack.length > 0) {
    +          const node = stack.pop();
    +          if (!$isLexicalNode(node)) {
    +            continue;
    +          }
    +          add(holders, node.getKey(), k);
    +          if ($isElementNode(node)) {
    +            stack.push(...node.getChildren());
    +          }
    +        }
    +      });
    +    };
    +    const $heldBefore = (line: NodeKey): NodeKey[] => {
    +      const out: NodeKey[] = [];
    +      const stack = [line];
    +      while (stack.length > 0) {
    +        const n = prevMap.get(stack.pop()!);
    +        if (n !== undefined && $isElementNode(n)) {
    +          let c = n.__first;
    +          while (c !== null) {
    +            out.push(c);
    +            stack.push(c);
    +            const next = prevMap.get(c);
    +            c = next === undefined ? null : next.__next;
    +          }
    +        }
    +      }
    +      return out;
    +    };
    +    // The desired lines ending with `text` (all of it).
    +    const endingWith = (text: string): number[] => {
    +      if (enders.size === 0) {
    +        newLines.forEach((n, k) => {
    +          for (let len = 1; len <= ENDING && len <= n.now.length; len++) {
    +            add(enders, n.now.slice(-len), k);
    +          }
    +        });
    +      }
    +      const l = enders.get(text.slice(-ENDING)) ?? [];
    +      return text.length <= ENDING
    +        ? l
    +        : l.filter(k => newLines[k].now.endsWith(text));
    +    };
    +    const ANY = null;
    +    // Lines without a key: kept as before by a marker no line claims.
    +    // The desired lines with the strongest claim on each old marker (ANY:
    +    // every line, where the marker's line is not known), see the rules
    +    // above. A line that stays keeps its marker unless the record gives its
    +    // last character to another line (the tail of a split).
    +    const best = new Map<number, Set<number> | null>();
    +    // Old markers the record gives a line (see withMarkerIslands).
    +    const anchored = new Set<number>();
    +    oldAt.forEach((i, ki) => {
    +      const owner = this.ownerBefore(
    +        (old.specials.get(i) as {ref: unknown}).ref as Item,
    +      );
    +      if (owner === null) {
    +        best.set(i, ANY);
    +        return;
    +      }
    +      const oi = lastOf(oldAt, ki);
    +      // A character, or an inline node kept (an equation the line ends
    +      // with), see $exactAtoms.
    +      const lastSpecial = oi < 0 ? undefined : old.specials.get(oi);
    +      const lastKind =
    +        oi < 0
    +          ? null
    +          : lastSpecial === undefined
    +            ? undefined
    +            : lastSpecial.kind;
    +      const byRecord =
    +        oi >= 0 && (lastKind === undefined || lastKind === 'oldNode')
    +          ? recorded.get(oi)
    +          : undefined;
    +      const from = lineOfUnit(owner);
    +      let set = new Set<number>();
    +      if (byRecord !== undefined) {
    +        set.add(byRecord);
    +        anchored.add(i);
    +      } else if (lines.has(from)) {
    +        // The line stays: it keeps its marker, unless a new line ends with
    +        // what it lost from its end (a split the record does not explain,
    +        // app code that sets the head's text and adds a line holding the
    +        // tail), which keeps the marker after that text.
    +        const own = lines.get(from)!;
    +        const was = textOf(old, oldAt, ki);
    +        const head = newLines[own[0]].now;
    +        let n = 0;
    +        while (n < was.length && n < head.length && was[n] === head[n]) {
    +          n++;
    +        }
    +        const tail = was.slice(n);
    +        const tails =
    +          tail.length > 0 && head.length < was.length
    +            ? endingWith(tail).filter(
    +                // A split's tail comes after its head.
    +                k => newLines[k].isNew && k > own[own.length - 1],
    +              )
    +            : [];
    +        set = new Set(tails.length > 0 ? tails : own);

    Must fix. A line that stays and only grew at its end claims only its own marker here, but that marker can be kept only at the common prefix or suffix (the islands keep record-placed markers only). So two paragraphs pasted at the end of a line (RangeSelection.insertNodes), or app code that sets hello! and adds a paragraph after it, delete the old marker. A collaborator composing at the end of that line has the composed node detached mid-composition and sees the paste at once, where main holds the line (y.md, Limits, "Input method composition"). A concurrent Delete that joins it with the next line is dropped (helloA | B | next; main: helloA | Bnext), and so is a concurrent alignment or type change, in both client-id orders.

    Falling back to position for that case restores main's result in all of these and keeps MarkerKeptByItsLine.test.ts and the regressions/ folder passing:

            // A line that only grew at its end, with a new line after it (lines
            // pasted at its end): by position, as before.
            if (
              n === was.length &&
              head.length > was.length &&
              newLines.some((x, k) => x.isNew && k > own[own.length - 1])
            ) {
              best.set(i, ANY);
              return;
            }
            set = new Set(tails.length > 0 ? tails : own);
    

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 04:42 UTC
    Code Review
    packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts:1
    @@ -0,0 +1,526 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// @vitest-environment jsdom
    +
    +// A composes at the end of a line. B replaces that line with a block of
    +// another class (or a new block of the same class) holding its text, and adds
    +// a block after it. The writer matched a line marker to any marker, so the
    +// common suffix gave the old line's marker to B's new block; every reader
    +// keys a line by its marker, so on A the composed text node, and the line
    +// held while composing, moved to the new block. Ending the composition then
    +// re-tokenized that block with A's code highlighter, dropping its format and
    +// NodeState, or wrote the text A typed into it. A marker now stays with the
    +// line that continues the line it ended (DECISIONS.md D118).
    +
    +import {$createCodeNode, $isCodeNode, CodeHighlightNode} from '@lexical/code';
    +import {PrismTokenizer, registerCodeHighlighting} from '@lexical/code-prism';
    +import {autoLinkUrlMatcher, registerAutoLink} from '@lexical/link';
    +import {$createHeadingNode, $createQuoteNode} from '@lexical/rich-text';
    +import {
    +  $createParagraphNode,
    +  $createTextNode,
    +  $getNodeByKey,
    +  $getRoot,
    +  $getSelection,
    +  $getState,
    +  $isRangeSelection,
    +  $isTextNode,
    +  $setCompositionKey,
    +  $setSelection,
    +  $setState,
    +  createState,
    +  type ElementNode,
    +  type LexicalEditor,
    +  stringValue,
    +  TextNode,
    +} from 'lexical';
    +import {describe, expect, onTestFinished, test} from 'vitest';
    +
    +import {
    +  $createEquation,
    +  $selectIn,
    +  expectConverged,
    +  freshReader,
    +  NODES,
    +  setup,
    +} from '../../utils/harness';
    +
    +const note = createState('note', {parse: stringValue()});
    +
    +/** Uppercases the text of a heading or quote (a parent-dependent transform). */
    +const upper = (editor: LexicalEditor) =>
    +  editor.registerNodeTransform(TextNode, node => {
    +    const parent = node.getParent();
    +    if (parent !== null && parent.getType() === 'quote') {
    +      const text = node.getTextContent();
    +      if (text !== text.toUpperCase()) {
    +        node.setTextContent(text.toUpperCase());
    +      }
    +    }
    +  });
    +
    +const autoLink = (editor: LexicalEditor) =>
    +  registerAutoLink(editor, {
    +    changeHandlers: [],
    +    excludeParents: [],
    +    matchers: [autoLinkUrlMatcher],
    +  });
    +
    +/**
    + * A composes `typed` at the end of the second block, in an editor attached
    + * to the DOM as an input method composes; returns the node's key.
    + */
    +function compose(editor: LexicalEditor, typed: string): string {
    +  const host = document.createElement('div');
    +  host.contentEditable = 'true';
    +  document.body.append(host);
    +  editor.setRootElement(host);
    +  host.focus();
    +  onTestFinished(() => {
    +    editor.setRootElement(null);
    +    host.remove();
    +  });
    +  let key = '';
    +  editor.update(
    +    () => {
    +      const block = $getRoot().getChildAtIndex(1) as ElementNode;
    +      const text = block.getAllTextNodes().at(-1)!;
    +      text.select(text.getTextContentSize(), text.getTextContentSize());
    +      key = text.getKey();
    +      $setCompositionKey(key);
    +      const selection = $getSelection();
    +      if ($isRangeSelection(selection)) {
    +        selection.insertText(typed);
    +      }
    +    },
    +    {discrete: true},
    +  );
    +  return key;
    +}
    +
    +/** The index of the top-level block holding node `key`, -1 if detached. */
    +const $blockOf = (key: string): number => {
    +  const node = $getNodeByKey(key);
    +  return node === null || !node.isAttached()
    +    ? -1
    +    : node.getTopLevelElementOrThrow().getIndexWithinParent();
    +};
    +
    +const $untouchedBlock = (kind: 'code' | 'paragraph') => {
    +  const text = $setState(
    +    $createTextNode('let untouched = 1;').setFormat('underline'),
    +    note,
    +    'old',
    +  );
    +  return (
    +    kind === 'code' ? $createCodeNode('javascript') : $createParagraphNode()
    +  ).append(text);
    +};
    +
    +/** The untouched block's text nodes: class, format, note. */
    +const $untouched = () =>
    +  ($getRoot().getLastChildOrThrow() as ElementNode)
    +    .getAllTextNodes()
    +    .map(n => `${n.getType()}:${n.getFormat()}:${$getState(n, note)}`)
    +    .join(' ');
    +
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [33, 11, 22],
    +    [33, 22, 11],
    +  ]) {
    +    describe(`gc ${gc}, ids ${ids.join(',')}`, () => {
    +      test('a line replaced by a quote with a code block added after it: the composition stays on the quote, the code block keeps its format and NodeState', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createParagraphNode().append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: upper},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        // Only the composing client highlights code.
    +        onTestFinished(registerCodeHighlighting(a.editor, PrismTokenizer));
    +        const key = compose(a.editor, 'word');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const quote = $createQuoteNode().append(...line.getChildren());
    +          line.replace(quote);
    +          quote.insertAfter($untouchedBlock('code'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // The composed text node is not the code block's (B's quote has a new
    +        // marker, see D118, so the node does not go with the old one).
    +        expect(a.read(() => $blockOf(key))).not.toBe(2);

    Consider (non-blocking). On this branch the composed node ends detached here ($blockOf(key) is −1 in all four cells of this test and the next one), which .not.toBe(2) also accepts, although the title says the composition stays on the quote. Pinning the expected value would catch a change in either direction.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 04:42 UTC
    Code Review
    packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts:1
    @@ -0,0 +1,526 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// @vitest-environment jsdom
    +
    +// A composes at the end of a line. B replaces that line with a block of
    +// another class (or a new block of the same class) holding its text, and adds
    +// a block after it. The writer matched a line marker to any marker, so the
    +// common suffix gave the old line's marker to B's new block; every reader
    +// keys a line by its marker, so on A the composed text node, and the line
    +// held while composing, moved to the new block. Ending the composition then
    +// re-tokenized that block with A's code highlighter, dropping its format and
    +// NodeState, or wrote the text A typed into it. A marker now stays with the
    +// line that continues the line it ended (DECISIONS.md D118).
    +
    +import {$createCodeNode, $isCodeNode, CodeHighlightNode} from '@lexical/code';
    +import {PrismTokenizer, registerCodeHighlighting} from '@lexical/code-prism';
    +import {autoLinkUrlMatcher, registerAutoLink} from '@lexical/link';
    +import {$createHeadingNode, $createQuoteNode} from '@lexical/rich-text';
    +import {
    +  $createParagraphNode,
    +  $createTextNode,
    +  $getNodeByKey,
    +  $getRoot,
    +  $getSelection,
    +  $getState,
    +  $isRangeSelection,
    +  $isTextNode,
    +  $setCompositionKey,
    +  $setSelection,
    +  $setState,
    +  createState,
    +  type ElementNode,
    +  type LexicalEditor,
    +  stringValue,
    +  TextNode,
    +} from 'lexical';
    +import {describe, expect, onTestFinished, test} from 'vitest';
    +
    +import {
    +  $createEquation,
    +  $selectIn,
    +  expectConverged,
    +  freshReader,
    +  NODES,
    +  setup,
    +} from '../../utils/harness';
    +
    +const note = createState('note', {parse: stringValue()});
    +
    +/** Uppercases the text of a heading or quote (a parent-dependent transform). */
    +const upper = (editor: LexicalEditor) =>
    +  editor.registerNodeTransform(TextNode, node => {
    +    const parent = node.getParent();
    +    if (parent !== null && parent.getType() === 'quote') {
    +      const text = node.getTextContent();
    +      if (text !== text.toUpperCase()) {
    +        node.setTextContent(text.toUpperCase());
    +      }
    +    }
    +  });
    +
    +const autoLink = (editor: LexicalEditor) =>
    +  registerAutoLink(editor, {
    +    changeHandlers: [],
    +    excludeParents: [],
    +    matchers: [autoLinkUrlMatcher],
    +  });
    +
    +/**
    + * A composes `typed` at the end of the second block, in an editor attached
    + * to the DOM as an input method composes; returns the node's key.
    + */
    +function compose(editor: LexicalEditor, typed: string): string {
    +  const host = document.createElement('div');
    +  host.contentEditable = 'true';
    +  document.body.append(host);
    +  editor.setRootElement(host);
    +  host.focus();
    +  onTestFinished(() => {
    +    editor.setRootElement(null);
    +    host.remove();
    +  });
    +  let key = '';
    +  editor.update(
    +    () => {
    +      const block = $getRoot().getChildAtIndex(1) as ElementNode;
    +      const text = block.getAllTextNodes().at(-1)!;
    +      text.select(text.getTextContentSize(), text.getTextContentSize());
    +      key = text.getKey();
    +      $setCompositionKey(key);
    +      const selection = $getSelection();
    +      if ($isRangeSelection(selection)) {
    +        selection.insertText(typed);
    +      }
    +    },
    +    {discrete: true},
    +  );
    +  return key;
    +}
    +
    +/** The index of the top-level block holding node `key`, -1 if detached. */
    +const $blockOf = (key: string): number => {
    +  const node = $getNodeByKey(key);
    +  return node === null || !node.isAttached()
    +    ? -1
    +    : node.getTopLevelElementOrThrow().getIndexWithinParent();
    +};
    +
    +const $untouchedBlock = (kind: 'code' | 'paragraph') => {
    +  const text = $setState(
    +    $createTextNode('let untouched = 1;').setFormat('underline'),
    +    note,
    +    'old',
    +  );
    +  return (
    +    kind === 'code' ? $createCodeNode('javascript') : $createParagraphNode()
    +  ).append(text);
    +};
    +
    +/** The untouched block's text nodes: class, format, note. */
    +const $untouched = () =>
    +  ($getRoot().getLastChildOrThrow() as ElementNode)
    +    .getAllTextNodes()
    +    .map(n => `${n.getType()}:${n.getFormat()}:${$getState(n, note)}`)
    +    .join(' ');
    +
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [33, 11, 22],
    +    [33, 22, 11],
    +  ]) {
    +    describe(`gc ${gc}, ids ${ids.join(',')}`, () => {
    +      test('a line replaced by a quote with a code block added after it: the composition stays on the quote, the code block keeps its format and NodeState', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createParagraphNode().append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: upper},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        // Only the composing client highlights code.
    +        onTestFinished(registerCodeHighlighting(a.editor, PrismTokenizer));
    +        const key = compose(a.editor, 'word');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const quote = $createQuoteNode().append(...line.getChildren());
    +          line.replace(quote);
    +          quote.insertAfter($untouchedBlock('code'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // The composed text node is not the code block's (B's quote has a new
    +        // marker, see D118, so the node does not go with the old one).
    +        expect(a.read(() => $blockOf(key))).not.toBe(2);
    +        a.update(() => {
    +          $setCompositionKey(null);
    +          const n = $getNodeByKey(key);
    +          if ($isTextNode(n) && n.isAttached()) {
    +            n.getWritable();
    +          }
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        await t.sync();
    +        const fresh = await freshReader(a);
    +        onTestFinished(() => fresh.stop());
    +        for (const peer of [...t.peers, fresh]) {
    +          expect(peer.read($untouched)).toBe('text:8:old');
    +          expect(
    +            peer.read(() =>
    +              $getRoot()
    +                .getChildren()
    +                .map(n => n.getTextContent()),
    +            ),
    +          ).toEqual(['intro', 'SEE WORD', 'let untouched = 1;']);
    +        }
    +        await expectConverged(t.peers);
    +      });
    +
    +      test('a code block replaced by a code block with a paragraph added after it: text typed as the composition ends stays in the code block', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createCodeNode('javascript').append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: autoLink},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        const key = compose(a.editor, 'https://lexical.dev');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const code = $createCodeNode('javascript').append(
    +            ...line.getChildren(),
    +          );
    +          line.replace(code);
    +          code.insertAfter($untouchedBlock('paragraph'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        expect(a.read(() => $blockOf(key))).not.toBe(2);
    +        a.update(() => {
    +          $setCompositionKey(null);
    +          const n = $getNodeByKey(key);
    +          if ($isTextNode(n) && n.isAttached()) {

    Consider (non-blocking). The node is detached on this branch, so this guard skips the block and z is never typed: "text typed as the composition ends stays in the code block" is not exercised, and the assertions below would pass with no typing at all. Asserting that the code block's text ends with z (or typing at the selection the composition end leaves) would cover it.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 04:42 UTC
    Code Review
    packages/lexical-y/src/internal/Write.ts:1
    @@ -3982,6 +3983,255 @@ export class Writer {
       // -------------------------------------------------------------------------
       // Sequences
     
    +  /**
    +   * Which old line markers a desired line may keep, where a sequence holds
    +   * more than one marker on either side (one line written on its own keeps
    +   * its marker): null where there is no choice. Invariant: an old marker is
    +   * kept only by the line that continues the line it ended (see D118), the
    +   * first of:
    +   * - the line whose last atom is the old line's last atom (a character, or
    +   *   an inline node kept), by Lexical's record of text edits (`record`, see
    +   *   $exactAtoms): the tail of a split (Enter in the middle of a line: the
    +   *   new line keeps the marker after the tail and the old line, holding the
    +   *   head, gets a new one, so no character moves), or the line a join or a
    +   *   range delete across lines ends with the joined text (it keeps the
    +   *   marker after that text, and its own goes);
    +   * - where the old line stays: a new line after it ending with what it
    +   *   lost from its end (a split the record does not explain: app code that
    +   *   sets the head's text and adds a line holding the tail), else that line
    +   *   itself;
    +   * - where it is gone: the lines holding a node it held before this update
    +   *   (a line Lexical replaced, `$setBlocksType`, or one joined into another),
    +   *   else the lines ending with all of its text (a paste over it);
    +   * - else, where no line continues it, any line, by position as before.
    +   * Why: a marker matched any marker, so where a collaborator replaced a
    +   * line and added another after it, the common suffix gave the old marker
    +   * to the new line; every reader keys a line by its marker, so the old
    +   * line's node, and a composition in it, moved to the new line (and the
    +   * composer's highlighter re-tokenized it, or its typing landed there).
    +   */
    +  private $markerContinues(
    +    old: Atoms,
    +    atoms: Atoms,
    +    record: {of: Int32Array; kept: Int32Array} | null,
    +  ): {
    +    match: (i: number, j: number) => boolean;
    +    anchored: Set<number>;
    +  } | null {
    +    const oldAt: number[] = [];
    +    const newAt: number[] = [];
    +    old.specials.forEach((sp, i) => {
    +      if (sp.kind === 'marker') {
    +        oldAt.push(i);
    +      }
    +    });
    +    atoms.specials.forEach((sp, j) => {
    +      if (sp.kind === 'marker') {
    +        newAt.push(j);
    +      }
    +    });
    +    if (oldAt.length <= 1 && newAt.length <= 1) {
    +      return null;
    +    }
    +    oldAt.sort((x, y) => x - y);
    +    newAt.sort((x, y) => x - y);
    +    const prevMap = this.prevState._nodeMap;
    +    // The text of the line ending at the `k`th marker (from the one before),
    +    // and the atom before that marker where it is in that line (else -1).
    +    const textOf = (a: Atoms, at: number[], k: number) =>
    +      a.text.slice(k === 0 ? 0 : at[k - 1] + 1, at[k]);
    +    const lastOf = (at: number[], k: number) =>
    +      at[k] - 1 >= (k === 0 ? 0 : at[k - 1] + 1) ? at[k] - 1 : -1;
    +    const newLines = newAt.map((j, k) => {
    +      const d = (atoms.specials.get(j) as {ref: unknown}).ref as Desired;
    +      const to = d.key === null ? null : lineOfUnit(d.key);
    +      return {
    +        isNew: to !== null && !prevMap.has(to),
    +        j,
    +        now: textOf(atoms, newAt, k),
    +        to,
    +      };
    +    });
    +    // The desired lines (or parts of one, see $pushLine) of each line key.
    +    const lines = new Map<NodeKey, number[]>();
    +    // Which desired lines hold each node, and end with each short text.
    +    const holders = new Map<NodeKey, number[]>();
    +    const enders = new Map<string, number[]>();
    +    const add = <K>(m: Map<K, number[]>, k: K, v: number) => {
    +      const l = m.get(k);
    +      if (l === undefined) {
    +        m.set(k, [v]);
    +      } else if (l[l.length - 1] !== v) {
    +        l.push(v);
    +      }
    +    };
    +    const ENDING = 8;
    +    newLines.forEach((n, k) => {
    +      if (n.to !== null) {
    +        add(lines, n.to, k);
    +      }
    +    });
    +    // The desired line whose last character Lexical's record says is old
    +    // atom `i`.
    +    const recorded = new Map<number, number>();
    +    if (record !== null) {
    +      newAt.forEach((_, k) => {
    +        const nj = lastOf(newAt, k);
    +        if (nj >= 0 && record.of[nj] >= 0) {
    +          recorded.set(record.of[nj], k);
    +        }
    +      });
    +    }
    +    // Built when a line that is gone is looked for (see below).
    +    let indexed = false;
    +    const $indexHolders = () => {
    +      indexed = true;
    +      newLines.forEach((n, k) => {
    +        const d = (atoms.specials.get(n.j) as {ref: unknown}).ref as Desired;
    +        const stack: (LexicalNode | null | undefined)[] = [...$lineChildren(d)];
    +        while (stack.length > 0) {
    +          const node = stack.pop();
    +          if (!$isLexicalNode(node)) {
    +            continue;
    +          }
    +          add(holders, node.getKey(), k);
    +          if ($isElementNode(node)) {
    +            stack.push(...node.getChildren());
    +          }
    +        }
    +      });
    +    };
    +    const $heldBefore = (line: NodeKey): NodeKey[] => {
    +      const out: NodeKey[] = [];
    +      const stack = [line];
    +      while (stack.length > 0) {
    +        const n = prevMap.get(stack.pop()!);
    +        if (n !== undefined && $isElementNode(n)) {
    +          let c = n.__first;
    +          while (c !== null) {
    +            out.push(c);
    +            stack.push(c);
    +            const next = prevMap.get(c);
    +            c = next === undefined ? null : next.__next;
    +          }
    +        }
    +      }
    +      return out;
    +    };
    +    // The desired lines ending with `text` (all of it).
    +    const endingWith = (text: string): number[] => {
    +      if (enders.size === 0) {
    +        newLines.forEach((n, k) => {
    +          for (let len = 1; len <= ENDING && len <= n.now.length; len++) {
    +            add(enders, n.now.slice(-len), k);
    +          }
    +        });
    +      }
    +      const l = enders.get(text.slice(-ENDING)) ?? [];
    +      return text.length <= ENDING
    +        ? l
    +        : l.filter(k => newLines[k].now.endsWith(text));

    Consider (non-blocking). When many lines share their last 8 characters, each gone line's lookup filters every one of them. Remaking every line of a document whose lines all end in of the document takes about twice as long as on main (6,400 lines: about 2.0 s against 1.1 s; equal with distinct endings). A map keyed by the whole line text, checked before this scan, would avoid most of it.

    rootnode-bot[bot] rootnode-bot[bot] requested changes on Nov 10, 2026 04:42 UTC
    Changes Requested Reviewer

    Thanks for the thorough write-up. The marker-ownership rule fixes the composition races it describes, and the new cells in MarkerKeptByItsLine.test.ts fail on main and pass here. One regression needs fixing before merge; the rest are optional suggestions.

    Must fix: pasting lines at the end of a line deletes that line's marker (packages/lexical-y/src/internal/Write.ts:4171-4191)

    In the "line stays" branch of $markerContinues, a line whose text only grew at its end can claim only its own marker. An own marker, though, is kept only at the common prefix or suffix (withMarkerIslands takes record-placed markers only). So when one update adds text at the end of a line and a line after it, the old marker is deleted. That happens with RangeSelection.insertNodes of two paragraphs at the end of hello (the paste path), or with app code that sets hello! and inserts a paragraph after it. With two clients, in either client-id order:

  • A collaborator composing with an IME at the end of that line has the composed text node detached mid-composition and sees the paste at once. On main the line is held and the paste shows when the composition ends, as the Limits entry "Input method composition" in packages/lexical-website/docs/collaboration/y.md documents ("pasted lines ... wait until the composition ends, and the line keeps its nodes").

  • A concurrent Delete at the end of that line (joining the next line) is dropped: helloA | B | next, where main gives helloA | Bnext.

  • A concurrent alignment or block-type change of that line is dropped; main applies it to the last pasted line.
  • D118 says such a marker is kept "by that line itself", but no line keeps it. Falling back to position for a line that only grew at its end, with a new line after it (see the inline suggestion), restores main's result in each case. It keeps MarkerKeptByItsLine.test.ts, the regressions/ folder and the lane counts as they are on this branch. Please also add paste-at-end cells (packages/lexical-y/AGENTS.md, Testing: every fix lands with a regression test).

    Suggestions (non-blocking)

  • MarkerKeptByItsLine.test.ts:164 and :213: on this branch the composed node ends detached ($blockOf returns −1), which .not.toBe(2) also accepts. With the n.isAttached() guard at :217, z is never typed, so "text typed as the composition ends stays in the code block" is not exercised. Pinning the expected index and asserting where the typed text lands (or retitling) would make the cells say what they check.

  • packages/lexical-y/AGENTS.md (Decisions) asks that accepted limits also be documented in y.md's Limits. D118's limit (a replaced or remade line with a line added after it drops a concurrent attribute change) is not there yet, and the "Input method composition" entry still says the line keeps its nodes.

  • Write.ts:4122-4134: endingWith scans every line that shares the last 8 characters. Remaking every line of a document whose lines end the same way takes about twice as long as on main (6,400 lines: about 2.0 s against 1.1 s; equal with distinct endings). An index keyed by the whole line text, checked before the suffix scan, would avoid it.

  • The Test plan's pasted output predates the current test file: it shows 36 tests, while the file now has 60 (52 pass and 8 are expected failures here; 16 fail on main). AGENTS.md (Commits and Pull Requests) asks for the real Before and After output.
  • <!-- codebunny-pub:1 k=37b1f0ba84fbd5499ae6b1932d891ccbffc7f02ad6c37eabf1afb4eb00fe0f9a -->

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 05:28 UTC
    Code Review
    packages/lexical-y/src/internal/Write.ts:1
    @@ -3982,6 +3983,299 @@ export class Writer {
       // -------------------------------------------------------------------------
       // Sequences
     
    +  /**
    +   * Which old line markers a desired line may keep, where a sequence holds
    +   * more than one marker on either side (one line written on its own keeps
    +   * its marker): null where there is no choice. Invariant: an old marker is
    +   * kept only by the line that continues the line it ended (see D118), the
    +   * first of:
    +   * - the line whose last atom is the old line's last atom (a character, or
    +   *   an inline node kept), by Lexical's record of text edits (`record`, see
    +   *   $exactAtoms): the tail of a split (Enter in the middle of a line: the
    +   *   new line keeps the marker after the tail and the old line, holding the
    +   *   head, gets a new one, so no character moves), or the line a join or a
    +   *   range delete across lines ends with the joined text (it keeps the
    +   *   marker after that text, and its own goes);
    +   * - where the old line stays: a new line after it ending with what it
    +   *   lost from its end (a split the record does not explain: app code that
    +   *   sets the head's text and adds a line holding the tail), else that line
    +   *   itself;
    +   * - where it is gone: the lines holding a node it held before this update
    +   *   (a line Lexical replaced, `$setBlocksType`, or one joined into another),
    +   *   else the lines ending with all of its text (a paste over it);
    +   * - else, where no line continues it, any line, by position as before.
    +   * Why: a marker matched any marker, so where a collaborator replaced a
    +   * line and added another after it, the common suffix gave the old marker
    +   * to the new line; every reader keys a line by its marker, so the old
    +   * line's node, and a composition in it, moved to the new line (and the
    +   * composer's highlighter re-tokenized it, or its typing landed there).
    +   */
    +  private $markerContinues(
    +    old: Atoms,
    +    atoms: Atoms,
    +    record: {of: Int32Array; kept: Int32Array} | null,
    +  ): {
    +    match: (i: number, j: number) => boolean;
    +    anchored: Set<number>;
    +  } | null {
    +    const oldAt: number[] = [];
    +    const newAt: number[] = [];
    +    old.specials.forEach((sp, i) => {
    +      if (sp.kind === 'marker') {
    +        oldAt.push(i);
    +      }
    +    });
    +    atoms.specials.forEach((sp, j) => {
    +      if (sp.kind === 'marker') {
    +        newAt.push(j);
    +      }
    +    });
    +    if (oldAt.length <= 1 && newAt.length <= 1) {
    +      return null;
    +    }
    +    oldAt.sort((x, y) => x - y);
    +    newAt.sort((x, y) => x - y);
    +    const prevMap = this.prevState._nodeMap;
    +    // The text of the line ending at the `k`th marker (from the one before),
    +    // and the atom before that marker where it is in that line (else -1).
    +    const textOf = (a: Atoms, at: number[], k: number) =>
    +      a.text.slice(k === 0 ? 0 : at[k - 1] + 1, at[k]);
    +    const lastOf = (at: number[], k: number) =>
    +      at[k] - 1 >= (k === 0 ? 0 : at[k - 1] + 1) ? at[k] - 1 : -1;
    +    const newLines = newAt.map((j, k) => {
    +      const d = (atoms.specials.get(j) as {ref: unknown}).ref as Desired;
    +      const to = d.key === null ? null : lineOfUnit(d.key);
    +      return {
    +        isNew: to !== null && !prevMap.has(to),
    +        j,
    +        now: textOf(atoms, newAt, k),
    +        to,
    +      };
    +    });
    +    // The desired lines (or parts of one, see $pushLine) of each line key.
    +    const lines = new Map<NodeKey, number[]>();
    +    // Which desired lines hold each node.
    +    const holders = new Map<NodeKey, number[]>();
    +    const add = <K>(m: Map<K, number[]>, k: K, v: number) => {
    +      const l = m.get(k);
    +      if (l === undefined) {
    +        m.set(k, [v]);
    +      } else if (l[l.length - 1] !== v) {
    +        l.push(v);
    +      }
    +    };
    +    newLines.forEach((n, k) => {
    +      if (n.to !== null) {
    +        add(lines, n.to, k);
    +      }
    +    });
    +    // The desired line whose last character Lexical's record says is old
    +    // atom `i`.
    +    const recorded = new Map<number, number>();
    +    if (record !== null) {
    +      newAt.forEach((_, k) => {
    +        const nj = lastOf(newAt, k);
    +        if (nj >= 0 && record.of[nj] >= 0) {
    +          recorded.set(record.of[nj], k);
    +        }
    +      });
    +    }
    +    // Built when a line that is gone is looked for (see below).
    +    let indexed = false;
    +    const $indexHolders = () => {
    +      indexed = true;
    +      newLines.forEach((n, k) => {
    +        const d = (atoms.specials.get(n.j) as {ref: unknown}).ref as Desired;
    +        const stack: (LexicalNode | null | undefined)[] = [...$lineChildren(d)];
    +        while (stack.length > 0) {
    +          const node = stack.pop();
    +          if (!$isLexicalNode(node)) {
    +            continue;
    +          }
    +          add(holders, node.getKey(), k);
    +          if ($isElementNode(node)) {
    +            stack.push(...node.getChildren());
    +          }
    +        }
    +      });
    +    };
    +    const $heldBefore = (line: NodeKey): NodeKey[] => {
    +      const out: NodeKey[] = [];
    +      const stack = [line];
    +      while (stack.length > 0) {
    +        const n = prevMap.get(stack.pop()!);
    +        if (n !== undefined && $isElementNode(n)) {
    +          let c = n.__first;
    +          while (c !== null) {
    +            out.push(c);
    +            stack.push(c);
    +            const next = prevMap.get(c);
    +            c = next === undefined ? null : next.__next;
    +          }
    +        }
    +      }
    +      return out;
    +    };
    +    // The desired lines ending with `text` (all of it).
    +    // The desired lines ending with `text` (all of it): their texts reversed
    +    // and sorted, so the lines ending with a text are those whose reversed
    +    // text starts with it reversed, a range found by binary search (the cost
    +    // does not grow with how many lines share an ending).
    +    let reversed: [string, number][] | null = null;
    +    const reverse = (x: string) => {
    +      let out = '';
    +      for (let i = x.length - 1; i >= 0; i--) {
    +        out += x[i];
    +      }
    +      return out;
    +    };
    +    const endingWith = (text: string): number[] => {
    +      if (reversed === null) {
    +        reversed = newLines.map((n, k): [string, number] => [
    +          reverse(n.now),
    +          k,
    +        ]);
    +        reversed.sort((x, y) =>
    +          x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : x[1] - y[1],
    +        );
    +      }
    +      const r = reverse(text);
    +      let lo = 0;
    +      let hi = reversed.length;
    +      while (lo < hi) {
    +        const mid = (lo + hi) >> 1;
    +        if (reversed[mid][0] < r) {
    +          lo = mid + 1;
    +        } else {
    +          hi = mid;
    +        }
    +      }
    +      const out: number[] = [];
    +      for (
    +        let i = lo;
    +        i < reversed.length && reversed[i][0].startsWith(r);
    +        i++
    +      ) {
    +        out.push(reversed[i][1]);
    +      }
    +      return out.sort((x, y) => x - y);
    +    };
    +    const ANY = null;
    +    // Lines without a key: kept as before by a marker no line claims.
    +    // The desired lines with the strongest claim on each old marker (ANY:
    +    // every line, where the marker's line is not known), see the rules
    +    // above. A line that stays keeps its marker unless the record gives its
    +    // last character to another line (the tail of a split).
    +    const best = new Map<number, Set<number> | null>();
    +    // Old markers the record gives a line (see withMarkerIslands).
    +    const anchored = new Set<number>();
    +    oldAt.forEach((i, ki) => {
    +      const owner = this.ownerBefore(
    +        (old.specials.get(i) as {ref: unknown}).ref as Item,
    +      );
    +      if (owner === null) {
    +        best.set(i, ANY);
    +        return;
    +      }
    +      const oi = lastOf(oldAt, ki);
    +      // A character, or an inline node kept (an equation the line ends
    +      // with), see $exactAtoms.
    +      const lastSpecial = oi < 0 ? undefined : old.specials.get(oi);
    +      const lastKind =
    +        oi < 0
    +          ? null
    +          : lastSpecial === undefined
    +            ? undefined
    +            : lastSpecial.kind;
    +      const byRecord =
    +        oi >= 0 && (lastKind === undefined || lastKind === 'oldNode')
    +          ? recorded.get(oi)
    +          : undefined;
    +      const from = lineOfUnit(owner);
    +      let set = new Set<number>();
    +      if (byRecord !== undefined) {
    +        set.add(byRecord);
    +        anchored.add(i);
    +      } else if (lines.has(from)) {
    +        // The line stays: it keeps its marker, unless a new line ends with
    +        // what it lost from its end (a split the record does not explain,
    +        // app code that sets the head's text and adds a line holding the
    +        // tail), which keeps the marker after that text.
    +        const own = lines.get(from)!;
    +        const was = textOf(old, oldAt, ki);
    +        const head = newLines[own[0]].now;
    +        let n = 0;
    +        while (n < was.length && n < head.length && was[n] === head[n]) {
    +          n++;
    +        }
    +        const tail = was.slice(n);
    +        const tails =
    +          tail.length > 0 && head.length < was.length
    +            ? endingWith(tail).filter(
    +                // A split's tail comes after its head.
    +                k => newLines[k].isNew && k > own[own.length - 1],
    +              )
    +            : [];
    +        set = new Set(tails.length > 0 ? tails : own);
    +        if (
    +          tails.length === 0 &&
    +          n === was.length &&
    +          head.length > was.length &&
    +          newLines.some((l, k) => l.isNew && k > own[own.length - 1])

    Must fix. This fallback covers only a line that grew at its end. A line that lost its end, with no new line ending with what it lost and a new line after it, still claims only its own marker (:4219), which can be kept only at the common prefix or suffix, so it is deleted. Selecting world in hello world and pressing Enter (RangeSelection.insertParagraph), or pasting two paragraphs over it (insertNodes), then drops a collaborator's concurrent center, heading change or Delete at the end of that line on every client, in both client-id orders; main keeps them on the new last line (hello / next for the Delete). The same happens on a document's last line and in a list item.

    With a new line after the line, the suffix cannot reach its marker and the prefix reaches it only while the line's text is unchanged, so any changed line without a tail line needs the fallback. This keeps MarkerKeptByItsLine.test.ts and the whole packages/lexical-y unit project passing:

              tails.length === 0 &&
              head !== was &&
              newLines.some((l, k) => l.isNew && k > own[own.length - 1])
    

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 05:28 UTC
    Code Review
    packages/lexical-website/docs/collaboration/y.md:1
    @@ -1312,7 +1312,15 @@ not merge as a user might expect:
       Enter or a paste made while composing. What removes something from the
       line (a deletion, a join, a `MarkNode` comment, which moves the text into
       it) shows at once: the text node being composed keeps its key, unless its
    -  class changes (a code block made a heading).
    +  class changes (a code block made a heading). A collaborator who replaces the
    +  line with a new block and adds another block next to it in one update gives
    +  the new block a new line marker (DECISIONS.md D118): the node being composed
    +  is no longer in the document, and the composition ends without it.
    +- **A line replaced next to a new line.** A line a collaborator replaces with

    Consider (non-blocking). This bullet lands inside the "Input method composition" entry: the paragraphs below it (:1324-1353, the held line's re-tokenization, NodeState and style caveats) belong to that entry but now render under "A line replaced next to a new line". Moving this bullet to just before "Set-valued NodeState" keeps them together.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 05:28 UTC
    Code Review
    .changeset/lexical-y-marker-kept-by-its-line.md:1
    @@ -0,0 +1,7 @@
    +---
    +'@lexical/y': patch
    +---
    +
    +[fix] Keep a line's marker with the line that continues it: where a collaborator replaced a line (a change of its block type, or a new block holding its text) and added a block after it in one update, the new block took the old line's marker, so a client composing in that line saw its composition move to the new block, and ending it re-tokenized that block with its code highlighter (dropping its format and NodeState) or wrote what it typed there
    +
    +Verify: with two clients, A composes at the end of a paragraph while B replaces that paragraph with a quote holding its text and adds a code block with underlined text after it; when A's composition ends, the code block keeps its underline and NodeState on every client, and text A types at the end of its saved node stays in the quote. Enter, Backspace across lines and a range delete across lines store the same as before.

    Nit (non-blocking). On this branch A's saved node is detached once B's update arrives (MarkerKeptByItsLine.test.ts:165 pins −1), so there is no node to type at; what the test checks is that the text A composed stays in the quote. "Enter … store the same as before" also does not hold yet for Enter over a selection that reaches a line's end (see the comment in Write.ts).

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 05:28 UTC
    Code Review
    packages/lexical-y/src/internal/Write.ts:1
    @@ -3982,6 +3983,299 @@ export class Writer {
       // -------------------------------------------------------------------------
       // Sequences
     
    +  /**
    +   * Which old line markers a desired line may keep, where a sequence holds
    +   * more than one marker on either side (one line written on its own keeps
    +   * its marker): null where there is no choice. Invariant: an old marker is
    +   * kept only by the line that continues the line it ended (see D118), the
    +   * first of:
    +   * - the line whose last atom is the old line's last atom (a character, or
    +   *   an inline node kept), by Lexical's record of text edits (`record`, see
    +   *   $exactAtoms): the tail of a split (Enter in the middle of a line: the
    +   *   new line keeps the marker after the tail and the old line, holding the
    +   *   head, gets a new one, so no character moves), or the line a join or a
    +   *   range delete across lines ends with the joined text (it keeps the
    +   *   marker after that text, and its own goes);
    +   * - where the old line stays: a new line after it ending with what it
    +   *   lost from its end (a split the record does not explain: app code that
    +   *   sets the head's text and adds a line holding the tail), else that line
    +   *   itself;
    +   * - where it is gone: the lines holding a node it held before this update
    +   *   (a line Lexical replaced, `$setBlocksType`, or one joined into another),
    +   *   else the lines ending with all of its text (a paste over it);
    +   * - else, where no line continues it, any line, by position as before.
    +   * Why: a marker matched any marker, so where a collaborator replaced a
    +   * line and added another after it, the common suffix gave the old marker
    +   * to the new line; every reader keys a line by its marker, so the old
    +   * line's node, and a composition in it, moved to the new line (and the
    +   * composer's highlighter re-tokenized it, or its typing landed there).
    +   */
    +  private $markerContinues(
    +    old: Atoms,
    +    atoms: Atoms,
    +    record: {of: Int32Array; kept: Int32Array} | null,
    +  ): {
    +    match: (i: number, j: number) => boolean;
    +    anchored: Set<number>;
    +  } | null {
    +    const oldAt: number[] = [];
    +    const newAt: number[] = [];
    +    old.specials.forEach((sp, i) => {
    +      if (sp.kind === 'marker') {
    +        oldAt.push(i);
    +      }
    +    });
    +    atoms.specials.forEach((sp, j) => {
    +      if (sp.kind === 'marker') {
    +        newAt.push(j);
    +      }
    +    });
    +    if (oldAt.length <= 1 && newAt.length <= 1) {
    +      return null;
    +    }
    +    oldAt.sort((x, y) => x - y);
    +    newAt.sort((x, y) => x - y);
    +    const prevMap = this.prevState._nodeMap;
    +    // The text of the line ending at the `k`th marker (from the one before),
    +    // and the atom before that marker where it is in that line (else -1).
    +    const textOf = (a: Atoms, at: number[], k: number) =>
    +      a.text.slice(k === 0 ? 0 : at[k - 1] + 1, at[k]);
    +    const lastOf = (at: number[], k: number) =>
    +      at[k] - 1 >= (k === 0 ? 0 : at[k - 1] + 1) ? at[k] - 1 : -1;
    +    const newLines = newAt.map((j, k) => {
    +      const d = (atoms.specials.get(j) as {ref: unknown}).ref as Desired;
    +      const to = d.key === null ? null : lineOfUnit(d.key);
    +      return {
    +        isNew: to !== null && !prevMap.has(to),
    +        j,
    +        now: textOf(atoms, newAt, k),
    +        to,
    +      };
    +    });
    +    // The desired lines (or parts of one, see $pushLine) of each line key.
    +    const lines = new Map<NodeKey, number[]>();
    +    // Which desired lines hold each node.
    +    const holders = new Map<NodeKey, number[]>();
    +    const add = <K>(m: Map<K, number[]>, k: K, v: number) => {
    +      const l = m.get(k);
    +      if (l === undefined) {
    +        m.set(k, [v]);
    +      } else if (l[l.length - 1] !== v) {
    +        l.push(v);
    +      }
    +    };
    +    newLines.forEach((n, k) => {
    +      if (n.to !== null) {
    +        add(lines, n.to, k);
    +      }
    +    });
    +    // The desired line whose last character Lexical's record says is old
    +    // atom `i`.
    +    const recorded = new Map<number, number>();
    +    if (record !== null) {
    +      newAt.forEach((_, k) => {
    +        const nj = lastOf(newAt, k);
    +        if (nj >= 0 && record.of[nj] >= 0) {
    +          recorded.set(record.of[nj], k);
    +        }
    +      });
    +    }
    +    // Built when a line that is gone is looked for (see below).
    +    let indexed = false;
    +    const $indexHolders = () => {
    +      indexed = true;
    +      newLines.forEach((n, k) => {
    +        const d = (atoms.specials.get(n.j) as {ref: unknown}).ref as Desired;
    +        const stack: (LexicalNode | null | undefined)[] = [...$lineChildren(d)];
    +        while (stack.length > 0) {
    +          const node = stack.pop();
    +          if (!$isLexicalNode(node)) {
    +            continue;
    +          }
    +          add(holders, node.getKey(), k);
    +          if ($isElementNode(node)) {
    +            stack.push(...node.getChildren());
    +          }
    +        }
    +      });
    +    };
    +    const $heldBefore = (line: NodeKey): NodeKey[] => {
    +      const out: NodeKey[] = [];
    +      const stack = [line];
    +      while (stack.length > 0) {
    +        const n = prevMap.get(stack.pop()!);
    +        if (n !== undefined && $isElementNode(n)) {
    +          let c = n.__first;
    +          while (c !== null) {
    +            out.push(c);
    +            stack.push(c);
    +            const next = prevMap.get(c);
    +            c = next === undefined ? null : next.__next;
    +          }
    +        }
    +      }
    +      return out;
    +    };
    +    // The desired lines ending with `text` (all of it).

    Nit (non-blocking). Repeated, extended, on the next line.

    rootnode-bot[bot] rootnode-bot[bot] requested changes on Nov 10, 2026 05:28 UTC
    Changes Requested Reviewer

    Thanks for the quick turnaround on the last round: lines pasted at a line's end now keep main's result, remaking every line costs the same as main again, and the composition cells pin the detached node. The marker-ownership rule fixes the races it describes, and the new cells in MarkerKeptByItsLine.test.ts fail on main and pass here. One sibling of the paste-at-end case still needs fixing before merge; the rest are optional suggestions.

    Must fix: Enter or a paste over a selection that reaches the end of a line deletes that line's marker (packages/lexical-y/src/internal/Write.ts:4220-4224)

    The new position fallback applies only when the line grew at its end (n === was.length && head.length > was.length). A line that lost its end, with no new line ending with what it lost and a new line after it, still claims only its own marker, and that marker can be kept only at the common prefix or suffix. So selecting world in hello world and pressing Enter (RangeSelection.insertParagraph), or pasting two paragraphs over it (insertNodes), deletes the old marker. With two clients, gc on and off, in both client-id orders:

  • a concurrent center or heading change of that line is dropped (main applies it to the new empty line, or to the last pasted line);

  • a concurrent Delete at its end, joining the next line, is dropped: hello / empty line / next, where main gives hello / next;

  • the same happens on the last line of a document and in a list item.
  • D118 says such a marker is kept "by that line itself", but no line keeps it, and the changeset's Verify: says Enter stores the same as before. Widening the condition fixes all of these (see the inline suggestion), and the whole packages/lexical-y unit project still passes with it. Please also add cells for Enter and a paste over a selection reaching the line's end beside the paste-at-end ones (packages/lexical-y/AGENTS.md, Testing: every bug fix lands with a regression test).

    Suggestions (non-blocking)

  • packages/lexical-website/docs/collaboration/y.md:1319: the new "A line replaced next to a new line" bullet sits inside the "Input method composition" entry, so that entry's remaining paragraphs (:1324-1353, the held line's re-tokenization and NodeState caveats) now render under the new bullet. Moving it to just before "Set-valued NodeState" keeps them together.

  • .changeset/lexical-y-marker-kept-by-its-line.md:7: "text A types at the end of its saved node stays in the quote" describes a step this branch no longer allows, since that node is detached once B's update arrives; "the text A composed stays in the quote" is what the test checks.

  • MarkerKeptByItsLine.test.ts:221: with the node pinned to −1 at :217, this guard always skips typing z, so "nothing typed lands there" holds with nothing typed.

  • Write.ts:4119 repeats the comment on :4120.

  • The Test plan's output predates the current file: it shows 36 tests, while the file now has 72 (64 pass and 8 are expected failures here; 16 fail on main). AGENTS.md (Commits and Pull Requests) asks for the real Before and After output.
  • <!-- codebunny-pub:1 k=ba79b8f3c7a62e41d59fc9b564f72be5786ac583345c20ce106bb6b01cdd181d -->

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 05:58 UTC
    Code Review
    packages/lexical-y/src/internal/Write.ts:1
    @@ -3982,6 +3983,297 @@ export class Writer {
       // -------------------------------------------------------------------------
       // Sequences
     
    +  /**
    +   * Which old line markers a desired line may keep, where a sequence holds
    +   * more than one marker on either side (one line written on its own keeps
    +   * its marker): null where there is no choice. Invariant: an old marker is
    +   * kept only by the line that continues the line it ended (see D118), the
    +   * first of:
    +   * - the line whose last atom is the old line's last atom (a character, or
    +   *   an inline node kept), by Lexical's record of text edits (`record`, see
    +   *   $exactAtoms): the tail of a split (Enter in the middle of a line: the
    +   *   new line keeps the marker after the tail and the old line, holding the
    +   *   head, gets a new one, so no character moves), or the line a join or a
    +   *   range delete across lines ends with the joined text (it keeps the
    +   *   marker after that text, and its own goes);
    +   * - where the old line stays: a new line after it ending with what it
    +   *   lost from its end (a split the record does not explain: app code that
    +   *   sets the head's text and adds a line holding the tail), else that line
    +   *   itself;
    +   * - where it is gone: the lines holding a node it held before this update
    +   *   (a line Lexical replaced, `$setBlocksType`, or one joined into another),
    +   *   else the lines ending with all of its text (a paste over it);
    +   * - else, where no line continues it, any line, by position as before.
    +   * Why: a marker matched any marker, so where a collaborator replaced a
    +   * line and added another after it, the common suffix gave the old marker
    +   * to the new line; every reader keys a line by its marker, so the old
    +   * line's node, and a composition in it, moved to the new line (and the
    +   * composer's highlighter re-tokenized it, or its typing landed there).
    +   */
    +  private $markerContinues(
    +    old: Atoms,
    +    atoms: Atoms,
    +    record: {of: Int32Array; kept: Int32Array} | null,
    +  ): {
    +    match: (i: number, j: number) => boolean;
    +    anchored: Set<number>;
    +  } | null {
    +    const oldAt: number[] = [];
    +    const newAt: number[] = [];
    +    old.specials.forEach((sp, i) => {
    +      if (sp.kind === 'marker') {
    +        oldAt.push(i);
    +      }
    +    });
    +    atoms.specials.forEach((sp, j) => {
    +      if (sp.kind === 'marker') {
    +        newAt.push(j);
    +      }
    +    });
    +    if (oldAt.length <= 1 && newAt.length <= 1) {
    +      return null;
    +    }
    +    oldAt.sort((x, y) => x - y);
    +    newAt.sort((x, y) => x - y);
    +    const prevMap = this.prevState._nodeMap;
    +    // The text of the line ending at the `k`th marker (from the one before),
    +    // and the atom before that marker where it is in that line (else -1).
    +    const textOf = (a: Atoms, at: number[], k: number) =>
    +      a.text.slice(k === 0 ? 0 : at[k - 1] + 1, at[k]);
    +    const lastOf = (at: number[], k: number) =>
    +      at[k] - 1 >= (k === 0 ? 0 : at[k - 1] + 1) ? at[k] - 1 : -1;
    +    const newLines = newAt.map((j, k) => {
    +      const d = (atoms.specials.get(j) as {ref: unknown}).ref as Desired;
    +      const to = d.key === null ? null : lineOfUnit(d.key);
    +      return {
    +        isNew: to !== null && !prevMap.has(to),
    +        j,
    +        now: textOf(atoms, newAt, k),
    +        to,
    +      };
    +    });
    +    // The desired lines (or parts of one, see $pushLine) of each line key.
    +    const lines = new Map<NodeKey, number[]>();
    +    // Which desired lines hold each node.
    +    const holders = new Map<NodeKey, number[]>();
    +    const add = <K>(m: Map<K, number[]>, k: K, v: number) => {
    +      const l = m.get(k);
    +      if (l === undefined) {
    +        m.set(k, [v]);
    +      } else if (l[l.length - 1] !== v) {
    +        l.push(v);
    +      }
    +    };
    +    newLines.forEach((n, k) => {
    +      if (n.to !== null) {
    +        add(lines, n.to, k);
    +      }
    +    });
    +    // The desired line whose last character Lexical's record says is old
    +    // atom `i`.
    +    const recorded = new Map<number, number>();
    +    if (record !== null) {
    +      newAt.forEach((_, k) => {
    +        const nj = lastOf(newAt, k);
    +        if (nj >= 0 && record.of[nj] >= 0) {
    +          recorded.set(record.of[nj], k);
    +        }
    +      });
    +    }
    +    // Built when a line that is gone is looked for (see below).
    +    let indexed = false;
    +    const $indexHolders = () => {
    +      indexed = true;
    +      newLines.forEach((n, k) => {
    +        const d = (atoms.specials.get(n.j) as {ref: unknown}).ref as Desired;
    +        const stack: (LexicalNode | null | undefined)[] = [...$lineChildren(d)];
    +        while (stack.length > 0) {
    +          const node = stack.pop();
    +          if (!$isLexicalNode(node)) {
    +            continue;
    +          }
    +          add(holders, node.getKey(), k);
    +          if ($isElementNode(node)) {
    +            stack.push(...node.getChildren());
    +          }
    +        }
    +      });
    +    };
    +    const $heldBefore = (line: NodeKey): NodeKey[] => {
    +      const out: NodeKey[] = [];
    +      const stack = [line];
    +      while (stack.length > 0) {
    +        const n = prevMap.get(stack.pop()!);
    +        if (n !== undefined && $isElementNode(n)) {
    +          let c = n.__first;
    +          while (c !== null) {
    +            out.push(c);
    +            stack.push(c);
    +            const next = prevMap.get(c);
    +            c = next === undefined ? null : next.__next;
    +          }
    +        }
    +      }
    +      return out;
    +    };
    +    // The desired lines ending with `text` (all of it): their texts reversed
    +    // and sorted, so the lines ending with a text are those whose reversed
    +    // text starts with it reversed, a range found by binary search (the cost
    +    // does not grow with how many lines share an ending).
    +    let reversed: [string, number][] | null = null;
    +    const reverse = (x: string) => {
    +      let out = '';
    +      for (let i = x.length - 1; i >= 0; i--) {
    +        out += x[i];
    +      }
    +      return out;
    +    };
    +    const endingWith = (text: string): number[] => {
    +      if (reversed === null) {
    +        reversed = newLines.map((n, k): [string, number] => [
    +          reverse(n.now),
    +          k,
    +        ]);
    +        reversed.sort((x, y) =>
    +          x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : x[1] - y[1],
    +        );
    +      }
    +      const r = reverse(text);
    +      let lo = 0;
    +      let hi = reversed.length;
    +      while (lo < hi) {
    +        const mid = (lo + hi) >> 1;
    +        if (reversed[mid][0] < r) {
    +          lo = mid + 1;
    +        } else {
    +          hi = mid;
    +        }
    +      }
    +      const out: number[] = [];
    +      for (
    +        let i = lo;
    +        i < reversed.length && reversed[i][0].startsWith(r);
    +        i++
    +      ) {
    +        out.push(reversed[i][1]);
    +      }
    +      return out.sort((x, y) => x - y);
    +    };
    +    const ANY = null;
    +    // Lines without a key: kept as before by a marker no line claims.
    +    // The desired lines with the strongest claim on each old marker (ANY:
    +    // every line, where the marker's line is not known), see the rules
    +    // above. A line that stays keeps its marker unless the record gives its
    +    // last character to another line (the tail of a split).
    +    const best = new Map<number, Set<number> | null>();
    +    // Old markers the record gives a line (see withMarkerIslands).
    +    const anchored = new Set<number>();
    +    oldAt.forEach((i, ki) => {
    +      const owner = this.ownerBefore(
    +        (old.specials.get(i) as {ref: unknown}).ref as Item,
    +      );
    +      if (owner === null) {
    +        best.set(i, ANY);
    +        return;
    +      }
    +      const oi = lastOf(oldAt, ki);
    +      // A character, or an inline node kept (an equation the line ends
    +      // with), see $exactAtoms.
    +      const lastSpecial = oi < 0 ? undefined : old.specials.get(oi);
    +      const lastKind =
    +        oi < 0
    +          ? null
    +          : lastSpecial === undefined
    +            ? undefined
    +            : lastSpecial.kind;
    +      const byRecord =
    +        oi >= 0 && (lastKind === undefined || lastKind === 'oldNode')
    +          ? recorded.get(oi)
    +          : undefined;
    +      const from = lineOfUnit(owner);
    +      let set = new Set<number>();
    +      if (byRecord !== undefined) {
    +        set.add(byRecord);
    +        anchored.add(i);
    +      } else if (lines.has(from)) {
    +        // The line stays: it keeps its marker, unless a new line ends with
    +        // what it lost from its end (a split the record does not explain,
    +        // app code that sets the head's text and adds a line holding the
    +        // tail), which keeps the marker after that text.
    +        const own = lines.get(from)!;
    +        const was = textOf(old, oldAt, ki);
    +        const head = newLines[own[0]].now;
    +        let n = 0;
    +        while (n < was.length && n < head.length && was[n] === head[n]) {
    +          n++;
    +        }
    +        const tail = was.slice(n);
    +        const tails =
    +          tail.length > 0 && head.length < was.length
    +            ? endingWith(tail).filter(
    +                // A split's tail comes after its head.
    +                k => newLines[k].isNew && k > own[own.length - 1],
    +              )
    +            : [];
    +        set = new Set(tails.length > 0 ? tails : own);
    +        if (
    +          tails.length === 0 &&
    +          newLines.some((l, k) => l.isNew && k > own[own.length - 1])
    +        ) {
    +          // With a new line after it and no line holding its old end (lines
    +          // pasted at its end, Enter or a paste over a selection that reaches
    +          // its end, app code that adds a line after it): by position, as
    +          // before (the last new line keeps the marker, which the common
    +          // suffix gives it). Kept by that line alone, the marker could not
    +          // stay (only the common prefix or suffix keeps such a marker), so
    +          // it was deleted: a composition there lost its line, and a
    +          // collaborator's concurrent change of the line, or a Delete at its
    +          // end, was dropped.
    +          set = new Set();
    +        }
    +      } else {
    +        if (!indexed) {
    +          $indexHolders();
    +        }
    +        for (const key of $heldBefore(from)) {
    +          for (const k of holders.get(key) ?? []) {
    +            set.add(k);
    +          }
    +        }
    +        if (set.size === 0) {
    +          const was = textOf(old, oldAt, ki);
    +          if (was.length > 0) {
    +            set = new Set(endingWith(was));

    Consider (non-blocking). With many identical lines remade in one update, this returns every one of them for each gone line, so each old marker gets a set of N lines and match (:4262-4272) walks it on every comparison. Replacing every paragraph with a new one of the same text takes about 6.9 s for 6,400 lines here against about 1.1 s on main (3,200: about 1.8 s against 0.7 s); distinct lines are unchanged. Claiming identical endings in order (a cursor per text, each gone line taking the next unclaimed line), or keeping position when more than one line ends with the text, keeps the set to one line; storing the claimed marker positions makes match a Set.has(j).

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 05:58 UTC
    Code Review
    packages/lexical-website/docs/collaboration/y.md:1
    @@ -1312,7 +1312,10 @@ not merge as a user might expect:
       Enter or a paste made while composing. What removes something from the
       line (a deletion, a join, a `MarkNode` comment, which moves the text into
       it) shows at once: the text node being composed keeps its key, unless its
    -  class changes (a code block made a heading).
    +  class changes (a code block made a heading). A collaborator who replaces the
    +  line with a new block and adds another block next to it in one update gives

    Consider (non-blocking). "next to it": with the block added before the replaced line (A composes at the end of see , B moves its children into a quote and inserts a code block before it), the composed node stays in the quote, as on main. Only a block added after it detaches the node, so "after it" is accurate.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 05:58 UTC
    Code Review
    packages/lexical-website/docs/collaboration/y.md:1
    @@ -1343,6 +1346,11 @@ not merge as a user might expect:
       re-tokenization is written, as on `main`. The binding reports the skip with
       `UNSUPPORTED_EDIT_WARNING` (`reason: 'other'`, `detailCode:
       'held-line-retokenize'`), once per composition.
    +- **A line replaced next to a new line.** A line a collaborator replaces with

    Consider (non-blocking). This names a line replaced by "a new one holding the same text", but the concurrent change is also dropped when the replacement holds the line's own nodes and its text changes in the same update (the first reproducer's shape, where a transform changes the quote's text), and when app code splits a line without the record (hello world set to hello , then world and extra added; main centered extra). D118 covers the first; per packages/lexical-y/AGENTS.md (accepted limits in y.md, known failures as test.fails), consider widening this bullet and adding a cell for the app-code split next to MarkerKeptByItsLine.test.ts:311.

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 10, 2026 05:58 UTC
    Approved Reviewer

    Thanks, this looks good. Keeping a line's marker with the line that continues it fixes the composition races the lanes reported, and the cases earlier revisions regressed (Enter or a paste over a line's end, lines pasted at a line's end, a split ending with an inline node, app-code splits) now give main's result, each with its own cells. Everything below is optional and non-blocking.

    1. Remaking many identical lines is quadratic (packages/lexical-y/src/internal/Write.ts:4246, :4262-4272). For a line that is gone, endingWith(was) returns every line ending with its whole text, so with identical lines each old marker gets a set of all N lines and match walks it on every comparison. One update that replaces every paragraph with a new paragraph of the same text takes about 6.9 s for 6,400 lines here against about 1.1 s on main (3,200 lines: about 1.8 s against 0.7 s); distinct lines cost the same as before. Claiming identical endings in order (a cursor per text), or keeping position when more than one line ends with the text, keeps each set to one line; storing the claimed marker positions makes match a Set.has(j).
    2. y.md's Limits bullet describes less than the code drops (packages/lexical-website/docs/collaboration/y.md:1349-1353). It names a line replaced by "a new one holding the same text". The concurrent alignment or type change is also dropped when the replacement holds the line's own nodes and its text changes in the same update (the shape of the first reproducer, where a transform changes the quote's text), and when app code splits a line without the record of text edits and adds another line after the tail (hello world set to hello , then world and extra added: main centered extra, this drops it). D118 covers the first. packages/lexical-y/AGENTS.md asks that accepted limits be documented in y.md and that known failures be test.fails cells, so consider widening the bullet and adding a cell for the app-code split next to MarkerKeptByItsLine.test.ts:311.
    3. IME note wording (packages/lexical-website/docs/collaboration/y.md:1315-1318): "adds another block next to it". With the block added before the replaced line, the composed node stays in the quote, as on main; "after it" is accurate.
    4. Test plan output: the pasted After run of MarkerKeptByItsLine.test.ts shows 72 cells, but the file now has 112 (104 passed, 8 expected fail). AGENTS.md (Commits and Pull Requests) asks for the real output of the command as run.

    The composition cells run in jsdom; a collab-Y E2E or browser run of a real IME composition would be a useful follow-up, not a requirement for this change.

    <!-- codebunny-pub:1 k=6167b286211bb7aa785cf009e3fc39cee44bf711f596850e93c3031ebe170f4b -->

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 07:08 UTC
    Code Review
    packages/lexical-website/docs/collaboration/y.md:1
    @@ -1312,7 +1312,10 @@ not merge as a user might expect:
       Enter or a paste made while composing. What removes something from the
       line (a deletion, a join, a `MarkNode` comment, which moves the text into
       it) shows at once: the text node being composed keeps its key, unless its
    -  class changes (a code block made a heading).
    +  class changes (a code block made a heading). A collaborator who replaces the
    +  line with a new block and adds another block after it in one update gives
    +  the new block a new line marker (DECISIONS.md D118): the node being composed
    +  is no longer in the document, and the composition ends without it.

    Consider (non-blocking). This holds only where Lexical's record of text edits does not explain the replacement. When the collaborator moves the line's own nodes into the new block with their text unchanged (as $setBlocksType does) and then inserts a block after it, the line keeps its marker and the composed node stays held in the new block: the first cell of MarkerKeptByItsLine.test.ts without its upper-casing transform ends with the node in the quote and the code block untouched, on main and on this branch. Reusing the qualifier from the Limits bullet below ("holding the same text, or its own nodes with its text changed") would keep the two passages in agreement.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 07:08 UTC
    Code Review
    packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts:1
    @@ -0,0 +1,788 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// @vitest-environment jsdom
    +
    +// A composes at the end of a line. B replaces that line with a block of
    +// another class (or a new block of the same class) holding its text, and adds
    +// a block after it. The writer matched a line marker to any marker, so the
    +// common suffix gave the old line's marker to B's new block; every reader
    +// keys a line by its marker, so on A the composed text node, and the line
    +// held while composing, moved to the new block. Ending the composition then
    +// re-tokenized that block with A's code highlighter, dropping its format and
    +// NodeState, or wrote the text A typed into it. A marker now stays with the
    +// line that continues the line it ended (DECISIONS.md D118).
    +
    +import {$createCodeNode, $isCodeNode, CodeHighlightNode} from '@lexical/code';
    +import {PrismTokenizer, registerCodeHighlighting} from '@lexical/code-prism';
    +import {autoLinkUrlMatcher, registerAutoLink} from '@lexical/link';
    +import {$createListItemNode, $createListNode, $isListNode} from '@lexical/list';
    +import {$createHeadingNode, $createQuoteNode} from '@lexical/rich-text';
    +import {
    +  $createParagraphNode,
    +  $createTextNode,
    +  $getNodeByKey,
    +  $getRoot,
    +  $getSelection,
    +  $getState,
    +  $isRangeSelection,
    +  $isTextNode,
    +  $setCompositionKey,
    +  $setSelection,
    +  $setState,
    +  createState,
    +  type ElementNode,
    +  type LexicalEditor,
    +  stringValue,
    +  TextNode,
    +} from 'lexical';
    +import {describe, expect, onTestFinished, test} from 'vitest';
    +
    +import {
    +  $createEquation,
    +  $selectIn,
    +  expectConverged,
    +  freshReader,
    +  NODES,
    +  setup,
    +} from '../../utils/harness';
    +
    +const note = createState('note', {parse: stringValue()});
    +
    +/** Uppercases the text of a heading or quote (a parent-dependent transform). */
    +const upper = (editor: LexicalEditor) =>
    +  editor.registerNodeTransform(TextNode, node => {
    +    const parent = node.getParent();
    +    if (parent !== null && parent.getType() === 'quote') {
    +      const text = node.getTextContent();
    +      if (text !== text.toUpperCase()) {
    +        node.setTextContent(text.toUpperCase());
    +      }
    +    }
    +  });
    +
    +const autoLink = (editor: LexicalEditor) =>
    +  registerAutoLink(editor, {
    +    changeHandlers: [],
    +    excludeParents: [],
    +    matchers: [autoLinkUrlMatcher],
    +  });
    +
    +/**
    + * A composes `typed` at the end of the second block, in an editor attached
    + * to the DOM as an input method composes; returns the node's key.
    + */
    +function compose(editor: LexicalEditor, typed: string): string {
    +  const host = document.createElement('div');
    +  host.contentEditable = 'true';
    +  document.body.append(host);
    +  editor.setRootElement(host);
    +  host.focus();
    +  onTestFinished(() => {
    +    editor.setRootElement(null);
    +    host.remove();
    +  });
    +  let key = '';
    +  editor.update(
    +    () => {
    +      const block = $getRoot().getChildAtIndex(1) as ElementNode;
    +      const text = block.getAllTextNodes().at(-1)!;
    +      text.select(text.getTextContentSize(), text.getTextContentSize());
    +      key = text.getKey();
    +      $setCompositionKey(key);
    +      const selection = $getSelection();
    +      if ($isRangeSelection(selection)) {
    +        selection.insertText(typed);
    +      }
    +    },
    +    {discrete: true},
    +  );
    +  return key;
    +}
    +
    +/** The index of the top-level block holding node `key`, -1 if detached. */
    +const $blockOf = (key: string): number => {
    +  const node = $getNodeByKey(key);
    +  return node === null || !node.isAttached()
    +    ? -1
    +    : node.getTopLevelElementOrThrow().getIndexWithinParent();
    +};
    +
    +const $untouchedBlock = (kind: 'code' | 'paragraph') => {
    +  const text = $setState(
    +    $createTextNode('let untouched = 1;').setFormat('underline'),
    +    note,
    +    'old',
    +  );
    +  return (
    +    kind === 'code' ? $createCodeNode('javascript') : $createParagraphNode()
    +  ).append(text);
    +};
    +
    +/** The untouched block's text nodes: class, format, note. */
    +const $untouched = () =>
    +  ($getRoot().getLastChildOrThrow() as ElementNode)
    +    .getAllTextNodes()
    +    .map(n => `${n.getType()}:${n.getFormat()}:${$getState(n, note)}`)
    +    .join(' ');
    +
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [33, 11, 22],
    +    [33, 22, 11],
    +  ]) {
    +    describe(`gc ${gc}, ids ${ids.join(',')}`, () => {
    +      test('a line replaced by a quote with a code block added after it: the composed node does not go to the code block, which keeps its format and NodeState', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createParagraphNode().append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: upper},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        // Only the composing client highlights code.
    +        onTestFinished(registerCodeHighlighting(a.editor, PrismTokenizer));
    +        const key = compose(a.editor, 'word');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const quote = $createQuoteNode().append(...line.getChildren());
    +          line.replace(quote);
    +          quote.insertAfter($untouchedBlock('code'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // The composed text node is not the code block's: B's quote has a new
    +        // marker (D118), so the node goes with the old one, which B deleted
    +        // (on main it went to the code block).
    +        expect(a.read(() => $blockOf(key))).toBe(-1);
    +        a.update(() => {
    +          $setCompositionKey(null);
    +          const n = $getNodeByKey(key);
    +          if ($isTextNode(n) && n.isAttached()) {
    +            n.getWritable();
    +          }
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        await t.sync();
    +        const fresh = await freshReader(a);
    +        onTestFinished(() => fresh.stop());
    +        for (const peer of [...t.peers, fresh]) {
    +          expect(peer.read($untouched)).toBe('text:8:old');
    +          expect(
    +            peer.read(() =>
    +              $getRoot()
    +                .getChildren()
    +                .map(n => n.getTextContent()),
    +            ),
    +          ).toEqual(['intro', 'SEE WORD', 'let untouched = 1;']);
    +        }
    +        await expectConverged(t.peers);
    +      });
    +
    +      test('a code block replaced by a code block with a paragraph added after it: the composed node does not go to the paragraph', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createCodeNode('javascript').append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: autoLink},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        const key = compose(a.editor, 'https://lexical.dev');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const code = $createCodeNode('javascript').append(
    +            ...line.getChildren(),
    +          );
    +          line.replace(code);
    +          code.insertAfter($untouchedBlock('paragraph'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // As above: the saved node goes with B's deleted marker (on main it
    +        // went to the paragraph after the code block, where the text typed at
    +        // it landed).
    +        expect(a.read(() => $blockOf(key))).toBe(-1);

    Consider (non-blocking). This is the only assertion in this cell that tells main from this branch (main gives 2): without it, the checks at lines 227-236 pass on main too, in all four cells, and nothing is typed after the composition ends, so the typed-text symptom in the comment above is not covered. Typing at A's selection once the composition ends and asserting which block holds the text would cover it.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 07:08 UTC
    Code Review
    .changeset/lexical-y-marker-kept-by-its-line.md:1
    @@ -0,0 +1,7 @@
    +---
    +'@lexical/y': patch
    +---
    +
    +[fix] Keep a line's marker with the line that continues it: where a collaborator replaced a line (a change of its block type, or a new block holding its text) and added a block after it in one update, the new block took the old line's marker, so a client composing in that line saw its composition move to the new block, and ending it re-tokenized that block with its code highlighter (dropping its format and NodeState) or wrote what it typed there

    Nit (non-blocking). CONTRIBUTING.md describes this entry as what people upgrading Lexical read. It might be worth one sentence on the accepted limit (D118, y.md Limits): in those shapes a collaborator's concurrent alignment or block-type change is now dropped, where before it landed on the added line.

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 10, 2026 07:08 UTC
    Approved Reviewer

    This looks good to me. Keeping a line's marker with the line that continues it fixes the replaced-line race at its source, and the new cells in MarkerKeptByItsLine.test.ts fail on main and pass here, asserting both peers and a fresh reader in both client-id orders, with gc on and off. The accepted limit is recorded the way packages/lexical-y/AGENTS.md asks (a D118 row, y.md Limits, test.fails cells).

    A few optional, non-blocking suggestions:

    1. y.md composition paragraph (packages/lexical-website/docs/collaboration/y.md, lines 1315-1318): it says any replacement with a new block plus an added block gives the line a new marker and ends the composition. A plain block-type change (the line's own nodes moved into a quote with their text unchanged, then a block inserted after it) keeps the marker through Lexical's record of text edits, and the composed node stays held in the quote. Reusing the qualifier from the Limits bullet further down ("holding the same text, or its own nodes with its text changed") would keep the two passages in agreement.
    2. Code-block composition cell (MarkerKeptByItsLine.test.ts, lines 192-238): only the $blockOf(key) check at line 218 tells main from this branch; the content assertions after it also pass on main, and nothing is typed after the composition ends, so the typed-text symptom the cell's comment mentions (lines 215-217) isn't covered. Typing at A's selection after the composition ends and asserting which block holds the text would cover it.
    3. Changeset: CONTRIBUTING.md describes the changeset as the entry people upgrading Lexical read. One sentence on the accepted limit (in the D118 shapes, a collaborator's concurrent alignment or block-type change is now dropped, where it used to land on the added line) would tell them about that behaviour change alongside the fix.
    4. Test plan: the pasted After output (104 passed | 8 expected fail (112), and "16 of the 112 cells fail" on main) predates the last test commits; the file now reports 104 passed | 24 expected fail (128), with 16 of 128 failing on main. AGENTS.md asks for the real output of the command that was run.

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

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 07:35 UTC
    Code Review
    packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts:1
    @@ -0,0 +1,795 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// @vitest-environment jsdom
    +
    +// A composes at the end of a line. B replaces that line with a block of
    +// another class (or a new block of the same class) holding its text, and adds
    +// a block after it. The writer matched a line marker to any marker, so the
    +// common suffix gave the old line's marker to B's new block; every reader
    +// keys a line by its marker, so on A the composed text node, and the line
    +// held while composing, moved to the new block. Ending the composition then
    +// re-tokenized that block with A's code highlighter, dropping its format and
    +// NodeState, or wrote the text A typed into it. A marker now stays with the
    +// line that continues the line it ended (DECISIONS.md D118).
    +
    +import {$createCodeNode, $isCodeNode, CodeHighlightNode} from '@lexical/code';
    +import {PrismTokenizer, registerCodeHighlighting} from '@lexical/code-prism';
    +import {autoLinkUrlMatcher, registerAutoLink} from '@lexical/link';
    +import {$createListItemNode, $createListNode, $isListNode} from '@lexical/list';
    +import {$createHeadingNode, $createQuoteNode} from '@lexical/rich-text';
    +import {
    +  $createParagraphNode,
    +  $createTextNode,
    +  $getNodeByKey,
    +  $getRoot,
    +  $getSelection,
    +  $getState,
    +  $isRangeSelection,
    +  $isTextNode,
    +  $setCompositionKey,
    +  $setSelection,
    +  $setState,
    +  createState,
    +  type ElementNode,
    +  type LexicalEditor,
    +  stringValue,
    +  TextNode,
    +} from 'lexical';
    +import {describe, expect, onTestFinished, test} from 'vitest';
    +
    +import {
    +  $createEquation,
    +  $selectIn,
    +  expectConverged,
    +  freshReader,
    +  NODES,
    +  setup,
    +} from '../../utils/harness';
    +
    +const note = createState('note', {parse: stringValue()});
    +
    +/** Uppercases the text of a heading or quote (a parent-dependent transform). */
    +const upper = (editor: LexicalEditor) =>
    +  editor.registerNodeTransform(TextNode, node => {
    +    const parent = node.getParent();
    +    if (parent !== null && parent.getType() === 'quote') {
    +      const text = node.getTextContent();
    +      if (text !== text.toUpperCase()) {
    +        node.setTextContent(text.toUpperCase());
    +      }
    +    }
    +  });
    +
    +const autoLink = (editor: LexicalEditor) =>
    +  registerAutoLink(editor, {
    +    changeHandlers: [],
    +    excludeParents: [],
    +    matchers: [autoLinkUrlMatcher],
    +  });
    +
    +/**
    + * A composes `typed` at the end of the second block, in an editor attached
    + * to the DOM as an input method composes; returns the node's key.
    + */
    +function compose(editor: LexicalEditor, typed: string): string {
    +  const host = document.createElement('div');
    +  host.contentEditable = 'true';
    +  document.body.append(host);
    +  editor.setRootElement(host);
    +  host.focus();
    +  onTestFinished(() => {
    +    editor.setRootElement(null);
    +    host.remove();
    +  });
    +  let key = '';
    +  editor.update(
    +    () => {
    +      const block = $getRoot().getChildAtIndex(1) as ElementNode;
    +      const text = block.getAllTextNodes().at(-1)!;
    +      text.select(text.getTextContentSize(), text.getTextContentSize());
    +      key = text.getKey();
    +      $setCompositionKey(key);
    +      const selection = $getSelection();
    +      if ($isRangeSelection(selection)) {
    +        selection.insertText(typed);
    +      }
    +    },
    +    {discrete: true},
    +  );
    +  return key;
    +}
    +
    +/** The index of the top-level block holding node `key`, -1 if detached. */
    +const $blockOf = (key: string): number => {
    +  const node = $getNodeByKey(key);
    +  return node === null || !node.isAttached()
    +    ? -1
    +    : node.getTopLevelElementOrThrow().getIndexWithinParent();
    +};
    +
    +const $untouchedBlock = (kind: 'code' | 'paragraph') => {
    +  const text = $setState(
    +    $createTextNode('let untouched = 1;').setFormat('underline'),
    +    note,
    +    'old',
    +  );
    +  return (
    +    kind === 'code' ? $createCodeNode('javascript') : $createParagraphNode()
    +  ).append(text);
    +};
    +
    +/** The untouched block's text nodes: class, format, note. */
    +const $untouched = () =>
    +  ($getRoot().getLastChildOrThrow() as ElementNode)
    +    .getAllTextNodes()
    +    .map(n => `${n.getType()}:${n.getFormat()}:${$getState(n, note)}`)
    +    .join(' ');
    +
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [33, 11, 22],
    +    [33, 22, 11],
    +  ]) {
    +    describe(`gc ${gc}, ids ${ids.join(',')}`, () => {
    +      test('a line replaced by a quote with a code block added after it: the composed node does not go to the code block, which keeps its format and NodeState', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createParagraphNode().append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: upper},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        // Only the composing client highlights code.
    +        onTestFinished(registerCodeHighlighting(a.editor, PrismTokenizer));
    +        const key = compose(a.editor, 'word');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const quote = $createQuoteNode().append(...line.getChildren());
    +          line.replace(quote);
    +          quote.insertAfter($untouchedBlock('code'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // The composed text node is not the code block's: B's quote has a new
    +        // marker (D118), so the node goes with the old one, which B deleted
    +        // (on main it went to the code block).
    +        expect(a.read(() => $blockOf(key))).toBe(-1);
    +        a.update(() => {
    +          $setCompositionKey(null);
    +          const n = $getNodeByKey(key);
    +          if ($isTextNode(n) && n.isAttached()) {
    +            n.getWritable();
    +          }
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        await t.sync();
    +        const fresh = await freshReader(a);
    +        onTestFinished(() => fresh.stop());
    +        for (const peer of [...t.peers, fresh]) {
    +          expect(peer.read($untouched)).toBe('text:8:old');
    +          expect(
    +            peer.read(() =>
    +              $getRoot()
    +                .getChildren()
    +                .map(n => n.getTextContent()),
    +            ),
    +          ).toEqual(['intro', 'SEE WORD', 'let untouched = 1;']);
    +        }
    +        await expectConverged(t.peers);
    +      });
    +
    +      test('a code block replaced by a code block with a paragraph added after it: the composed node does not go to the paragraph, and what is typed as the composition ends stays in the code block', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createCodeNode('javascript').append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: autoLink},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        const key = compose(a.editor, 'https://lexical.dev');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const code = $createCodeNode('javascript').append(
    +            ...line.getChildren(),
    +          );
    +          line.replace(code);
    +          code.insertAfter($untouchedBlock('paragraph'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // As above: the saved node goes with B's deleted marker (on main it
    +        // went to the paragraph after the code block, where the text typed at
    +        // it landed).
    +        expect(a.read(() => $blockOf(key))).toBe(-1);
    +        // The composition ends, and A types at its selection.
    +        a.update(() => {
    +          $setCompositionKey(null);
    +          const selection = $getSelection();
    +          if ($isRangeSelection(selection)) {
    +            selection.insertText(' z');
    +          }
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        await t.sync();
    +        const fresh = await freshReader(a);
    +        onTestFinished(() => fresh.stop());
    +        for (const peer of [...t.peers, fresh]) {
    +          const blocks = peer.read(() =>
    +            $getRoot()
    +              .getChildren()
    +              .map(n => [$isCodeNode(n), n.getTextContent()]),
    +          );
    +          expect(blocks[2]).toEqual([false, 'let untouched = 1;']);
    +          // What A typed is in the code block (on main, the paragraph).
    +          expect(blocks[1][1]).toContain(' z');

    Consider (non-blocking). This passes on main too, so it doesn't cover the typed-text symptom yet. On main, A's selection after B's update is the old see text node at offset 4 in the code block (the composed node, which moved to the paragraph, isn't selected), so z lands in the code block there as well; with the $blockOf check at line 218 removed, this cell passes on main in all four gc/id combinations. On both builds the text lands before what A composed (see zhttps://lexical.dev). Typing at the end of the composed node while it is still attached (on main it sits in the paragraph) would make this fail on main; otherwise the "(on main, the paragraph)" comment and the typed-text part of the title could go (packages/lexical-y/AGENTS.md, Testing).

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 07:35 UTC
    Code Review
    .changeset/lexical-y-marker-kept-by-its-line.md:1
    @@ -0,0 +1,7 @@
    +---
    +'@lexical/y': patch
    +---
    +
    +[fix] Keep a line's marker with the line that continues it: where a collaborator replaced a line (a change of its block type, or a new block holding its text) and added a block after it in one update, the new block took the old line's marker, so a client composing in that line saw its composition move to the new block, and ending it re-tokenized that block with its code highlighter (dropping its format and NodeState) or wrote what it typed there Accepted limit (DECISIONS.md D118, y.md Limits): where a collaborator replaces a line with a new block holding the same text (or its own nodes with their text changed), or splits it by app code, and adds another line after it in one update, another collaborator's concurrent change of that line's alignment or block type is now dropped (before, it landed on the added line).

    Nit (non-blocking). A period is missing before "Accepted limit", so the accepted-limit text becomes part of the one-line summary. .changeset/README.md (Format) asks for a one-line [category] summary with further paragraphs after a blank line:

    [fix] Keep a line's marker with the line that continues it: where a collaborator replaced a line (a change of its block type, or a new block holding its text) and added a block after it in one update, the new block took the old line's marker, so a client composing in that line saw its composition move to the new block, and ending it re-tokenized that block with its code highlighter (dropping its format and NodeState) or wrote what it typed there.
    
    Accepted limit (DECISIONS.md D118, y.md Limits): where a collaborator replaces a line with a new block holding the same text (or its own nodes with their text changed), or splits it by app code, and adds another line after it in one update, another collaborator's concurrent change of that line's alignment or block type is now dropped (before, it landed on the added line).
    

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 10, 2026 07:35 UTC
    Approved Reviewer

    Thanks, this looks good. Keeping a marker with the line that continues it fixes the replaced-line composition cases, the Enter, paste-at-end and Enter-over-a-selection cells give the same result as on main, and the accepted limit is recorded in D118, y.md's Limits and as test.fails cells, as packages/lexical-y/AGENTS.md asks. Run against main, the new MarkerKeptByItsLine.test.ts fails 16 of its 128 cells (the composition cells and the Backspace-with-a-line-added cells), and they pass here.

    Two optional, non-blocking suggestions:

    1. packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts:219-240: the new z typing assertion also passes on main. After B's update, A's selection on main is the old see text node at offset 4 in the code block (not the composed node, which moved to the paragraph), so z lands in the code block there too, and on both builds it lands before the composed text (see zhttps://lexical.dev). With the $blockOf check at line 218 removed, the cell passes on main in all four gc/id combinations. packages/lexical-y/AGENTS.md (Testing) asks for a control on the baseline a claim names: typing at the end of the composed node while it is still attached would make this assertion fail on main; otherwise the "(on main, the paragraph)" comment and the typed-text part of the test title could go.
    2. .changeset/lexical-y-marker-kept-by-its-line.md:5: there is no period between "typed there" and "Accepted limit", so the accepted-limit text becomes part of the one-line summary. .changeset/README.md (Format) asks for a one-line [category] summary with further paragraphs after a blank line; ending the summary at "there." and moving the accepted limit into its own paragraph keeps the changelog entry readable.

    <!-- codebunny-pub:1 k=2af27ee8f628a834a56dc68599f09add68b7255f7c9a4e48c8925d0cc657ed87 -->

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 07:57 UTC
    Code Review
    .changeset/lexical-y-marker-kept-by-its-line.md:1
    @@ -0,0 +1,9 @@
    +---
    +'@lexical/y': patch
    +---
    +
    +[fix] Keep a line's marker with the line that continues it: where a collaborator replaced a line (a change of its block type, or a new block holding its text) and added a block after it in one update, the new block took the old line's marker, so a client composing in that line saw its composition move to the new block, and ending it re-tokenized that block with its code highlighter (dropping its format and NodeState) or wrote what it typed there.
    +
    +Accepted limit (DECISIONS.md D118, y.md Limits): where a collaborator replaces a line with a new block holding the same text (or its own nodes with their text changed), or splits it by app code, and adds another line after it in one update, another collaborator's concurrent change of that line's alignment or block type is now dropped (before, it landed on the added line).
    +
    +Verify: with two clients, A composes at the end of a paragraph while B replaces that paragraph with a quote holding its text and adds a code block with underlined text after it; when A's composition ends, the code block keeps its underline and NodeState on every client, and the text A composed stays in the quote. Enter, Backspace across lines and a range delete across lines store the same as before.

    Nit (optional). As written ("a quote holding its text"), this check also passes on main when the quote holds the paragraph's own nodes unchanged, as $setBlocksType leaves them: the first cell of MarkerKeptByItsLine.test.ts without its upper-casing transform passes on both builds. Naming the shape that differs would make the check tell them apart, and match y.md's qualifier:

    Verify: with two clients, A composes at the end of a paragraph while B replaces that paragraph with a quote whose text changes in the same update (a transform that upper-cases it, or new text nodes holding the same text) and adds a code block with underlined text after it; when A's composition ends, the code block keeps its underline and NodeState on every client, and the text A composed stays in the quote. Enter, Backspace across lines and a range delete across lines store the same as before.
    

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 10, 2026 07:57 UTC
    Approved Reviewer

    This looks good to me. Keeping an old line marker with the line that continues it (D118) fixes the replaced-line case, and the "as before" cells show that pastes and Enter over a line's end keep main's results. The new regression cells fail on main and pass here, including the case where the untouched code block is re-tokenized and loses its underline. The accepted limit is recorded in DECISIONS.md, y.md's Limits and the test.fails cells, as packages/lexical-y/AGENTS.md asks.

    All suggestions below are optional and non-blocking:

  • Changeset Verify: recipe (.changeset/lexical-y-marker-kept-by-its-line.md:9). As written ("a quote holding its text"), the check also passes on main when the quote holds the paragraph's own nodes unchanged, as $setBlocksType leaves them. The first cell in MarkerKeptByItsLine.test.ts without its upper-casing transform passes on both. .changeset/README.md ("Behavior changes") says Verify: should name what to test for the change, so it could say the quote's text changes in the same update (or new text nodes hold it), matching the qualifier y.md already uses.

  • Native composition. The documented outcome for a composing client (the composed node is removed mid-composition) is shown only by jsdom cells using $setCompositionKey. If it's easy, a collab-Y browser or e2e check of that shape (pnpm run test-e2e-collab-y-chromium) would cover how a real input method reacts.

  • carry:target-value ceiling (LaneFuzz.test.ts:174). Raising it from 7.2 to 9.8 per 1,000 loosens the nightly growth check for that class. Keeping it in its own commit, as you did, leaves maintainers free to take or drop it.
  • <!-- codebunny-pub:1 k=a34ca35693335839b813de3d202d7a01e4fe40e43b99ae3f486d86609743adf3 -->

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 10, 2026 08:26 UTC
    Approved Reviewer

    This looks good to me. The new rule is clearly recorded (D118, y.md's Limits and the changeset), the composition and join cells in MarkerKeptByItsLine.test.ts fail on main and pass here, and the rest of the @lexical/y unit suite passes with gc off and on. Other concurrent shapes produce the same documents as on main, each against a concurrent alignment change or typing: moving lines, mid-line and cross-line pastes, Enter over a multi-line selection, a paragraph made a heading with a line added before or after it, removals and joins.

    Two optional, non-blocking notes:

    1. packages/lexical-y/src/__tests__/unit/LaneFuzz.test.ts:172: carry:target-value is the one known-open class this change makes more frequent (7.2 → 9.8 per 1,000). The explanation reads right: these histories now take the join path, which fails the same way on main without the added block. An issue for that join-path failure would give the raised ceiling an owner, so the last commit can be kept or dropped knowingly.
    2. packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts:217: as discussed on this line before, the $blockOf check is still the only assertion in the code-block cell that fails on main, so the typed-text symptom of that history has no cell of its own yet (packages/lexical-y/AGENTS.md, Testing). Fine as a follow-up.

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

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 08:59 UTC
    Code Review
    packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts:1
    @@ -0,0 +1,795 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// @vitest-environment jsdom
    +
    +// A composes at the end of a line. B replaces that line with a block of
    +// another class (or a new block of the same class) holding its text, and adds
    +// a block after it. The writer matched a line marker to any marker, so the
    +// common suffix gave the old line's marker to B's new block; every reader
    +// keys a line by its marker, so on A the composed text node, and the line
    +// held while composing, moved to the new block. Ending the composition then
    +// re-tokenized that block with A's code highlighter, dropping its format and
    +// NodeState, or wrote the text A typed into it. A marker now stays with the
    +// line that continues the line it ended (DECISIONS.md D118).
    +
    +import {$createCodeNode, $isCodeNode, CodeHighlightNode} from '@lexical/code';
    +import {PrismTokenizer, registerCodeHighlighting} from '@lexical/code-prism';
    +import {autoLinkUrlMatcher, registerAutoLink} from '@lexical/link';
    +import {$createListItemNode, $createListNode, $isListNode} from '@lexical/list';
    +import {$createHeadingNode, $createQuoteNode} from '@lexical/rich-text';
    +import {
    +  $createParagraphNode,
    +  $createTextNode,
    +  $getNodeByKey,
    +  $getRoot,
    +  $getSelection,
    +  $getState,
    +  $isRangeSelection,
    +  $isTextNode,
    +  $setCompositionKey,
    +  $setSelection,
    +  $setState,
    +  createState,
    +  type ElementNode,
    +  type LexicalEditor,
    +  stringValue,
    +  TextNode,
    +} from 'lexical';
    +import {describe, expect, onTestFinished, test} from 'vitest';
    +
    +import {
    +  $createEquation,
    +  $selectIn,
    +  expectConverged,
    +  freshReader,
    +  NODES,
    +  setup,
    +} from '../../utils/harness';
    +
    +const note = createState('note', {parse: stringValue()});
    +
    +/** Uppercases the text of a heading or quote (a parent-dependent transform). */
    +const upper = (editor: LexicalEditor) =>
    +  editor.registerNodeTransform(TextNode, node => {
    +    const parent = node.getParent();
    +    if (parent !== null && parent.getType() === 'quote') {
    +      const text = node.getTextContent();
    +      if (text !== text.toUpperCase()) {
    +        node.setTextContent(text.toUpperCase());
    +      }
    +    }
    +  });
    +
    +const autoLink = (editor: LexicalEditor) =>
    +  registerAutoLink(editor, {
    +    changeHandlers: [],
    +    excludeParents: [],
    +    matchers: [autoLinkUrlMatcher],
    +  });
    +
    +/**
    + * A composes `typed` at the end of the second block, in an editor attached
    + * to the DOM as an input method composes; returns the node's key.
    + */
    +function compose(editor: LexicalEditor, typed: string): string {
    +  const host = document.createElement('div');
    +  host.contentEditable = 'true';
    +  document.body.append(host);
    +  editor.setRootElement(host);
    +  host.focus();
    +  onTestFinished(() => {
    +    editor.setRootElement(null);
    +    host.remove();
    +  });
    +  let key = '';
    +  editor.update(
    +    () => {
    +      const block = $getRoot().getChildAtIndex(1) as ElementNode;
    +      const text = block.getAllTextNodes().at(-1)!;
    +      text.select(text.getTextContentSize(), text.getTextContentSize());
    +      key = text.getKey();
    +      $setCompositionKey(key);
    +      const selection = $getSelection();
    +      if ($isRangeSelection(selection)) {
    +        selection.insertText(typed);
    +      }
    +    },
    +    {discrete: true},
    +  );
    +  return key;
    +}
    +
    +/** The index of the top-level block holding node `key`, -1 if detached. */
    +const $blockOf = (key: string): number => {
    +  const node = $getNodeByKey(key);
    +  return node === null || !node.isAttached()
    +    ? -1
    +    : node.getTopLevelElementOrThrow().getIndexWithinParent();
    +};
    +
    +const $untouchedBlock = (kind: 'code' | 'paragraph') => {
    +  const text = $setState(
    +    $createTextNode('let untouched = 1;').setFormat('underline'),
    +    note,
    +    'old',
    +  );
    +  return (
    +    kind === 'code' ? $createCodeNode('javascript') : $createParagraphNode()
    +  ).append(text);
    +};
    +
    +/** The untouched block's text nodes: class, format, note. */
    +const $untouched = () =>
    +  ($getRoot().getLastChildOrThrow() as ElementNode)
    +    .getAllTextNodes()
    +    .map(n => `${n.getType()}:${n.getFormat()}:${$getState(n, note)}`)
    +    .join(' ');
    +
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [33, 11, 22],
    +    [33, 22, 11],
    +  ]) {
    +    describe(`gc ${gc}, ids ${ids.join(',')}`, () => {
    +      test('a line replaced by a quote with a code block added after it: the composed node does not go to the code block, which keeps its format and NodeState', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createParagraphNode().append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: upper},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        // Only the composing client highlights code.
    +        onTestFinished(registerCodeHighlighting(a.editor, PrismTokenizer));
    +        const key = compose(a.editor, 'word');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const quote = $createQuoteNode().append(...line.getChildren());
    +          line.replace(quote);
    +          quote.insertAfter($untouchedBlock('code'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // The composed text node is not the code block's: B's quote has a new
    +        // marker (D118), so the node goes with the old one, which B deleted
    +        // (on main it went to the code block).
    +        expect(a.read(() => $blockOf(key))).toBe(-1);
    +        a.update(() => {
    +          $setCompositionKey(null);
    +          const n = $getNodeByKey(key);
    +          if ($isTextNode(n) && n.isAttached()) {
    +            n.getWritable();
    +          }
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        await t.sync();
    +        const fresh = await freshReader(a);
    +        onTestFinished(() => fresh.stop());
    +        for (const peer of [...t.peers, fresh]) {
    +          expect(peer.read($untouched)).toBe('text:8:old');
    +          expect(
    +            peer.read(() =>
    +              $getRoot()
    +                .getChildren()
    +                .map(n => n.getTextContent()),
    +            ),
    +          ).toEqual(['intro', 'SEE WORD', 'let untouched = 1;']);
    +        }
    +        await expectConverged(t.peers);
    +      });
    +
    +      test('a code block replaced by a code block with a paragraph added after it: the composed node does not go to the paragraph', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createCodeNode('javascript').append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: autoLink},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        const key = compose(a.editor, 'https://lexical.dev');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const code = $createCodeNode('javascript').append(
    +            ...line.getChildren(),
    +          );
    +          line.replace(code);
    +          code.insertAfter($untouchedBlock('paragraph'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // As above: the saved node goes with B's deleted marker (on main it
    +        // went to the paragraph after the code block).
    +        expect(a.read(() => $blockOf(key))).toBe(-1);
    +        // The composition ends, and A types at its selection.
    +        a.update(() => {
    +          $setCompositionKey(null);
    +          const selection = $getSelection();
    +          if ($isRangeSelection(selection)) {
    +            selection.insertText(' z');
    +          }
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        await t.sync();
    +        const fresh = await freshReader(a);
    +        onTestFinished(() => fresh.stop());
    +        for (const peer of [...t.peers, fresh]) {
    +          const blocks = peer.read(() =>
    +            $getRoot()
    +              .getChildren()
    +              .map(n => [$isCodeNode(n), n.getTextContent()]),
    +          );
    +          expect(blocks[2]).toEqual([false, 'let untouched = 1;']);
    +          // What A typed at its selection is in the code block (as on main,
    +          // where the selection stays on the code block's text).
    +          expect(blocks[1][1]).toContain(' z');
    +          expect(blocks[1][0]).toBe(true);
    +          expect(peer.read($untouched)).toBe('text:8:old');
    +        }
    +        await expectConverged(t.peers);
    +      });
    +    });
    +  }
    +}
    +
    +// A split, a join and a line remade with a line added after it keep the old
    +// marker where the diff kept it (D118: the tail of a split, the line a join
    +// ends with), so a collaborator's concurrent change of the line's attributes
    +// (its alignment, its type) stays with the line that holds its end.
    +type Change = 'centers' | 'makes it a heading';
    +const $change = (change: Change, index: number) => {
    +  const line = $getRoot().getChildAtIndex(index) as ElementNode;
    +  if (change === 'centers') {
    +    line.setFormat('center');
    +  } else {
    +    line.replace($createHeadingNode('h2').append(...line.getChildren()));
    +  }
    +  $setSelection(null);
    +};
    +const $shape = () =>
    +  $getRoot()
    +    .getChildren()
    +    .map(
    +      n =>
    +        `${n.getType()}${(n as ElementNode).getFormatType()}:${n.getTextContent()}`,
    +    );
    +
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [1, 2],
    +    [2, 1],
    +  ]) {
    +    for (const change of ['centers', 'makes it a heading'] as const) {
    +      describe(`gc ${gc}, ids ${ids.join(',')}, a collaborator ${change} the line`, () => {
    +        const run = async (
    +          init: () => void,
    +          $edit: () => void,
    +          index: number,
    +          want: string[],
    +        ) => {
    +          const t = await setup(init, {gc, ids});
    +          onTestFinished(() => t.peers.forEach(p => p.stop()));
    +          t.offline();
    +          t.a.update($edit);
    +          t.b.update(() => $change(change, index));
    +          await t.sync();
    +          const fresh = await freshReader(t.a);
    +          onTestFinished(() => fresh.stop());
    +          for (const peer of [...t.peers, fresh]) {
    +            expect(peer.read($shape)).toEqual(want);
    +          }
    +          await expectConverged(t.peers);
    +        };
    +        const changed = (type: string, text: string) =>
    +          change === 'centers' ? `${type}center:${text}` : `heading:${text}`;
    +
    +        test('Enter in a line that ends with an inline node: the tail keeps the change', () =>
    +          run(
    +            () =>
    +              $getRoot().append(
    +                $createParagraphNode().append(
    +                  $createTextNode('hello world'),
    +                  $createEquation('x^2'),
    +                ),
    +              ),
    +            () => {
    +              $selectIn([0], 6).insertParagraph();
    +              $setSelection(null);
    +            },
    +            0,
    +            ['paragraph:hello ', changed('paragraph', 'world')],
    +          ));
    +
    +        test("app code that splits a line (the head's text set, a line added holding the tail): the tail keeps the change", () =>
    +          run(
    +            () =>
    +              $getRoot().append(
    +                $createParagraphNode().append($createTextNode('hello world')),
    +              ),
    +            () => {
    +              const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +              (line.getFirstChildOrThrow() as TextNode).setTextContent(
    +                'hello ',
    +              );
    +              line.insertAfter(
    +                $createParagraphNode().append($createTextNode('world')),
    +              );
    +              $setSelection(null);
    +            },
    +            0,
    +            ['paragraph:hello ', changed('paragraph', 'world')],
    +          ));
    +
    +        test("app code that sets a line's text to its start and adds a line holding its end before it: the line keeps the change", () =>
    +          run(
    +            () =>
    +              $getRoot().append(
    +                $createParagraphNode().append($createTextNode('hello world')),
    +              ),
    +            () => {
    +              const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +              (line.getFirstChildOrThrow() as TextNode).setTextContent(
    +                'hello ',
    +              );
    +              line.insertBefore(
    +                $createParagraphNode().append($createTextNode('world')),
    +              );
    +              $setSelection(null);
    +            },
    +            0,
    +            ['paragraph:world', changed('paragraph', 'hello ')],
    +          ));
    +
    +        // The same accepted limit (D118) for a line replaced by one holding
    +        // its own nodes, with its text changed, and a line added after it.
    +        test.fails(
    +          'a line replaced by a quote holding its nodes, its text changed, with a line added after it: the quote keeps the change',
    +          () =>
    +            run(
    +              () =>
    +                $getRoot().append(
    +                  $createParagraphNode().append($createTextNode('see')),
    +                ),
    +              () => {
    +                const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +                const quote = $createQuoteNode().append(...line.getChildren());
    +                line.replace(quote);
    +                (quote.getFirstChildOrThrow() as TextNode).setTextContent(
    +                  'SEE',
    +                );
    +                quote.insertAfter(
    +                  $createParagraphNode().append($createTextNode('xyz')),
    +                );
    +                $setSelection(null);
    +              },
    +              0,
    +              [
    +                change === 'centers' ? 'quotecenter:SEE' : 'heading:SEE',
    +                'paragraph:xyz',
    +              ],
    +            ),
    +        );
    +
    +        // And for app code that splits a line without the record of text
    +        // edits and adds another line after the tail.
    +        test.fails(
    +          'app code that splits a line and adds a line after the tail: the tail keeps the change',
    +          () =>
    +            run(
    +              () =>
    +                $getRoot().append(
    +                  $createParagraphNode().append($createTextNode('hello world')),
    +                ),
    +              () => {
    +                const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +                (line.getFirstChildOrThrow() as TextNode).setTextContent(
    +                  'hello ',
    +                );
    +                const tail = $createParagraphNode().append(
    +                  $createTextNode('world'),
    +                );
    +                line.insertAfter(tail);
    +                tail.insertAfter(
    +                  $createParagraphNode().append($createTextNode('extra')),
    +                );
    +                $setSelection(null);
    +              },
    +              0,
    +              [
    +                'paragraph:hello ',
    +                changed('paragraph', 'world'),
    +                'paragraph:extra',
    +              ],
    +            ),
    +        );
    +
    +        // An accepted limit (D118): the remade line gets a new marker, so the
    +        // change is dropped (before, it was applied to the added line).
    +        test.fails(
    +          'a line remade with the same text, with a line added after it: the remade line keeps the change',
    +          () =>
    +            run(
    +              () =>
    +                $getRoot().append(
    +                  $createParagraphNode().append($createTextNode('abc')),
    +                ),
    +              () => {
    +                const line = $getRoot().getFirstChildOrThrow();
    +                const remade = $createParagraphNode().append(
    +                  $createTextNode('abc'),
    +                );
    +                line.replace(remade);
    +                remade.insertAfter(
    +                  $createParagraphNode().append($createTextNode('xyz')),
    +                );
    +                $setSelection(null);
    +              },
    +              0,
    +              [changed('paragraph', 'abc'), 'paragraph:xyz'],
    +            ),
    +        );
    +
    +        test('Backspace at the start of a line, with a line added after it: the joined line keeps the change', () =>
    +          run(
    +            () =>
    +              $getRoot().append(
    +                $createParagraphNode().append($createTextNode('one')),
    +                $createParagraphNode().append($createTextNode('two')),
    +              ),
    +            () => {
    +              $selectIn([1], 0).deleteCharacter(true);
    +              $getRoot().append(
    +                $createParagraphNode().append($createTextNode('added')),
    +              );
    +              $setSelection(null);
    +            },
    +            1,
    +            [changed('paragraph', 'onetwo'), 'paragraph:added'],
    +          ));
    +      });
    +    }
    +  }
    +}
    +
    +// A removes the lines after a line while composing in one of them, and B
    +// typed into it at the same time (held on A): no line continues the removed
    +// lines' markers, so the line before keeps one by position, as before, and
    +// B's character joins its end rather than the next line's text or a line of
    +// its own (D118).
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [1, 2],
    +    [2, 1],
    +  ]) {
    +    test(`lines removed after a line while a collaborator typed in one of them (gc ${gc}, ids ${ids.join(',')}): the typed character joins the line before, as before`, async () => {
    +      const t = await setup(
    +        () =>
    +          $getRoot().append(
    +            $createParagraphNode().append($createTextNode('zero')),
    +            $createParagraphNode().append($createTextNode('one')),
    +            $createParagraphNode().append($createTextNode('two')),
    +          ),
    +        {gc, ids},
    +      );
    +      onTestFinished(() => t.peers.forEach(p => p.stop()));
    +      const {a, b} = t;
    +      a.update(() => {
    +        const text = (
    +          $getRoot().getChildAtIndex(2) as ElementNode
    +        ).getFirstChildOrThrow() as TextNode;
    +        text.select(1, 1);
    +        $setCompositionKey(text.getKey());
    +      });
    +      b.update(() => {
    +        $selectIn([2], 1).insertText('R');
    +        $setSelection(null);
    +      });
    +      await t.sync();
    +      a.update(() => {
    +        $getRoot().getChildAtIndex(2)!.remove();
    +        $getRoot().getChildAtIndex(1)!.remove();
    +        // The caret ends at the end of the line before.
    +        $getRoot().getFirstChildOrThrow().selectEnd();
    +      });
    +      await t.sync();
    +      a.update(() => $setCompositionKey(null));
    +      await t.sync();
    +      const fresh = await freshReader(a);
    +      onTestFinished(() => fresh.stop());
    +      for (const peer of [...t.peers, fresh]) {
    +        expect(
    +          peer.read(() =>
    +            $getRoot()
    +              .getChildren()
    +              .map(n => n.getTextContent()),
    +          ),
    +        ).toEqual(['zeroR']);
    +      }
    +      await expectConverged(t.peers);
    +    });
    +  }
    +}
    +
    +// Two collaborators delete across the same lines at once, and one of them
    +// also replaces the line that is left and adds a line next to it: that line
    +// gets a new marker, as before. Kept, its old marker (which the other
    +// client's join deletes) left it without a boundary, joined to the added
    +// line (D118).

    Consider (non-blocking). One concurrent shape next to these isn't pinned, and its stored outcome changes with this PR. When A joins or splits a line and adds a line after it, and B concurrently joins the next line into it, the joined line now absorbs A's added line. From one / two / three / four, A presses Backspace at the start of two and adds added after onetwo, while B presses Backspace at the start of three. main gives onetwo / addedthree / four; this branch gives onetwoadded / three / four (gc off and on, both id orders, converged). The same happens with Enter, a range delete or a removed line in place of A's join or B's Backspace. It follows from D118 (the joined line keeps the marker after two, which B deletes), so a cell here pinning it would make a later change deliberate (packages/lexical-y/AGENTS.md, Testing).

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 08:59 UTC
    Code Review
    packages/lexical-y/src/internal/Write.ts:1
    @@ -3982,6 +3983,302 @@ export class Writer {
       // -------------------------------------------------------------------------
       // Sequences
     
    +  /**
    +   * Which old line markers a desired line may keep, where a sequence holds
    +   * more than one marker on either side (one line written on its own keeps
    +   * its marker): null where there is no choice. Invariant: an old marker is
    +   * kept only by the line that continues the line it ended (see D118), the
    +   * first of:
    +   * - the line whose last atom is the old line's last atom (a character, or
    +   *   an inline node kept), by Lexical's record of text edits (`record`, see
    +   *   $exactAtoms): the tail of a split (Enter in the middle of a line: the
    +   *   new line keeps the marker after the tail and the old line, holding the
    +   *   head, gets a new one, so no character moves), or the line a join or a
    +   *   range delete across lines ends with the joined text (it keeps the
    +   *   marker after that text, and its own goes);
    +   * - where the old line stays: a new line after it ending with what it
    +   *   lost from its end (a split the record does not explain: app code that
    +   *   sets the head's text and adds a line holding the tail), else that line
    +   *   itself;
    +   * - where it is gone: the lines holding a node it held before this update
    +   *   (a line Lexical replaced, `$setBlocksType`, or one joined into another),
    +   *   else the lines ending with all of its text (a paste over it);
    +   * - else, where no line continues it, any line, by position as before.
    +   * Why: a marker matched any marker, so where a collaborator replaced a
    +   * line and added another after it, the common suffix gave the old marker
    +   * to the new line; every reader keys a line by its marker, so the old
    +   * line's node, and a composition in it, moved to the new line (and the
    +   * composer's highlighter re-tokenized it, or its typing landed there).
    +   */
    +  private $markerContinues(
    +    old: Atoms,
    +    atoms: Atoms,
    +    record: {of: Int32Array; kept: Int32Array} | null,
    +  ): {
    +    match: (i: number, j: number) => boolean;
    +    anchored: Set<number>;
    +  } | null {
    +    const oldAt: number[] = [];
    +    const newAt: number[] = [];
    +    old.specials.forEach((sp, i) => {
    +      if (sp.kind === 'marker') {
    +        oldAt.push(i);
    +      }
    +    });
    +    atoms.specials.forEach((sp, j) => {
    +      if (sp.kind === 'marker') {
    +        newAt.push(j);
    +      }
    +    });
    +    if (oldAt.length <= 1 && newAt.length <= 1) {
    +      return null;
    +    }
    +    oldAt.sort((x, y) => x - y);
    +    newAt.sort((x, y) => x - y);
    +    const prevMap = this.prevState._nodeMap;
    +    // The text of the line ending at the `k`th marker (from the one before),
    +    // and the atom before that marker where it is in that line (else -1).
    +    const textOf = (a: Atoms, at: number[], k: number) =>
    +      a.text.slice(k === 0 ? 0 : at[k - 1] + 1, at[k]);
    +    const lastOf = (at: number[], k: number) =>
    +      at[k] - 1 >= (k === 0 ? 0 : at[k - 1] + 1) ? at[k] - 1 : -1;
    +    const newLines = newAt.map((j, k) => {
    +      const d = (atoms.specials.get(j) as {ref: unknown}).ref as Desired;
    +      const to = d.key === null ? null : lineOfUnit(d.key);
    +      return {
    +        isNew: to !== null && !prevMap.has(to),
    +        j,
    +        now: textOf(atoms, newAt, k),
    +        to,
    +      };
    +    });
    +    // The desired lines (or parts of one, see $pushLine) of each line key.
    +    const lines = new Map<NodeKey, number[]>();
    +    // Which desired lines hold each node.
    +    const holders = new Map<NodeKey, number[]>();
    +    const add = <K>(m: Map<K, number[]>, k: K, v: number) => {
    +      const l = m.get(k);
    +      if (l === undefined) {
    +        m.set(k, [v]);
    +      } else if (l[l.length - 1] !== v) {
    +        l.push(v);
    +      }
    +    };
    +    newLines.forEach((n, k) => {
    +      if (n.to !== null) {
    +        add(lines, n.to, k);
    +      }
    +    });
    +    // The desired line whose last character Lexical's record says is old
    +    // atom `i`.
    +    const recorded = new Map<number, number>();
    +    if (record !== null) {
    +      newAt.forEach((_, k) => {
    +        const nj = lastOf(newAt, k);
    +        if (nj >= 0 && record.of[nj] >= 0) {
    +          recorded.set(record.of[nj], k);
    +        }
    +      });
    +    }
    +    // Built when a line that is gone is looked for (see below).
    +    let indexed = false;
    +    const $indexHolders = () => {
    +      indexed = true;
    +      newLines.forEach((n, k) => {
    +        const d = (atoms.specials.get(n.j) as {ref: unknown}).ref as Desired;
    +        const stack: (LexicalNode | null | undefined)[] = [...$lineChildren(d)];
    +        while (stack.length > 0) {
    +          const node = stack.pop();
    +          if (!$isLexicalNode(node)) {
    +            continue;
    +          }
    +          add(holders, node.getKey(), k);
    +          if ($isElementNode(node)) {
    +            stack.push(...node.getChildren());
    +          }
    +        }
    +      });
    +    };
    +    const $heldBefore = (line: NodeKey): NodeKey[] => {
    +      const out: NodeKey[] = [];
    +      const stack = [line];
    +      while (stack.length > 0) {
    +        const n = prevMap.get(stack.pop()!);
    +        if (n !== undefined && $isElementNode(n)) {
    +          let c = n.__first;
    +          while (c !== null) {
    +            out.push(c);
    +            stack.push(c);
    +            const next = prevMap.get(c);
    +            c = next === undefined ? null : next.__next;
    +          }
    +        }
    +      }
    +      return out;
    +    };
    +    // The desired lines ending with `text` (all of it): their texts reversed
    +    // and sorted, so the lines ending with a text are those whose reversed
    +    // text starts with it reversed, a range found by binary search (the cost
    +    // does not grow with how many lines share an ending).
    +    let reversed: [string, number][] | null = null;
    +    const reverse = (x: string) => {
    +      let out = '';
    +      for (let i = x.length - 1; i >= 0; i--) {
    +        out += x[i];
    +      }
    +      return out;
    +    };
    +    const endingWith = (text: string, limit = Infinity): number[] => {
    +      if (reversed === null) {
    +        reversed = newLines.map((n, k): [string, number] => [
    +          reverse(n.now),
    +          k,
    +        ]);
    +        reversed.sort((x, y) =>
    +          x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : x[1] - y[1],
    +        );
    +      }
    +      const r = reverse(text);
    +      let lo = 0;
    +      let hi = reversed.length;
    +      while (lo < hi) {
    +        const mid = (lo + hi) >> 1;
    +        if (reversed[mid][0] < r) {
    +          lo = mid + 1;
    +        } else {
    +          hi = mid;
    +        }
    +      }
    +      const out: number[] = [];
    +      for (
    +        let i = lo;
    +        i < reversed.length &&
    +        out.length < limit &&
    +        reversed[i][0].startsWith(r);
    +        i++
    +      ) {
    +        out.push(reversed[i][1]);
    +      }
    +      return out.sort((x, y) => x - y);
    +    };
    +    const ANY = null;
    +    // Lines without a key: kept as before by a marker no line claims.
    +    // The desired lines with the strongest claim on each old marker (ANY:
    +    // every line, where the marker's line is not known), see the rules
    +    // above. A line that stays keeps its marker unless the record gives its
    +    // last character to another line (the tail of a split).
    +    const best = new Map<number, Set<number> | null>();
    +    // Old markers the record gives a line (see withMarkerIslands).
    +    const anchored = new Set<number>();
    +    oldAt.forEach((i, ki) => {
    +      const owner = this.ownerBefore(
    +        (old.specials.get(i) as {ref: unknown}).ref as Item,
    +      );
    +      if (owner === null) {
    +        best.set(i, ANY);
    +        return;
    +      }
    +      const oi = lastOf(oldAt, ki);
    +      // A character, or an inline node kept (an equation the line ends
    +      // with), see $exactAtoms.
    +      const lastSpecial = oi < 0 ? undefined : old.specials.get(oi);
    +      const lastKind =
    +        oi < 0
    +          ? null
    +          : lastSpecial === undefined
    +            ? undefined
    +            : lastSpecial.kind;
    +      const byRecord =
    +        oi >= 0 && (lastKind === undefined || lastKind === 'oldNode')
    +          ? recorded.get(oi)
    +          : undefined;
    +      const from = lineOfUnit(owner);
    +      let set = new Set<number>();
    +      if (byRecord !== undefined) {
    +        set.add(byRecord);
    +        anchored.add(i);
    +      } else if (lines.has(from)) {
    +        // The line stays: it keeps its marker, unless a new line ends with
    +        // what it lost from its end (a split the record does not explain,
    +        // app code that sets the head's text and adds a line holding the
    +        // tail), which keeps the marker after that text.
    +        const own = lines.get(from)!;
    +        const was = textOf(old, oldAt, ki);
    +        const head = newLines[own[0]].now;
    +        let n = 0;
    +        while (n < was.length && n < head.length && was[n] === head[n]) {
    +          n++;
    +        }
    +        const tail = was.slice(n);
    +        const tails =
    +          tail.length > 0 && head.length < was.length
    +            ? endingWith(tail).filter(
    +                // A split's tail comes after its head.
    +                k => newLines[k].isNew && k > own[own.length - 1],
    +              )
    +            : [];
    +        set = new Set(tails.length === 1 ? tails : own);
    +        if (
    +          tails.length !== 1 &&
    +          newLines.some((l, k) => l.isNew && k > own[own.length - 1])

    Consider (non-blocking). This scan runs once per staying line. In my timings, edits that touch every line of a 6,000-line document took 8-21% longer than on main (for example 799 to 963 ms to append to every line and add a line after each), growing linearly. Typing returns at the first check above, so only bulk edits pay. If it matters, computing the index of the last new line once, before the loop, would turn this into a comparison.

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 10, 2026 08:59 UTC
    Approved Reviewer

    This looks good to me. The rule is clearly recorded (D118, y.md's Limits and the changeset). The composition and Backspace-join cells in MarkerKeptByItsLine.test.ts fail on main and pass here with gc off and on, and the quote cell reproduces the user-visible symptom (the untouched code block keeps text:8:old instead of being re-tokenized). I also tried other concurrent shapes against a collaborator centering a line, making it a heading or typing at its end: moves, mid-line pastes, Enter, $setBlocksType with a line added after, removals and range deletes all converge. They either match main or now keep the change on the line that continues the old one. The carry:target-value increase is reasonable now that #9865 tracks the join-path failure.

    Three optional, non-blocking suggestions:

    1. Pin the concurrent-join outcome (MarkerKeptByItsLine.test.ts, next to the concurrent-delete cells at line 528). When A joins or splits a line and adds a line after it, and B concurrently joins the next line into it, the joined line now absorbs A's added line. For example, from one / two / three / four, A presses Backspace at the start of two and adds added, while B presses Backspace at the start of three. main gives onetwo / addedthree / four; this branch gives onetwoadded / three / four, in both client-id orders and with gc on and off. It follows from D118, and neither result is ideal, but the stored outcome changes in a shape no cell covers. packages/lexical-y/AGENTS.md (Testing) asks to test the input space, and one cell would make a later change here deliberate.
    2. The code-block composition cell (MarkerKeptByItsLine.test.ts:217): as noted on that line before, the $blockOf check is still the only assertion in it that fails on main. With it removed, all four cells pass on main, and the text typed after the composition lands in the code block on both. So the "wrote what it typed there" symptom in the changeset has no failing-first cell yet (packages/lexical-y/AGENTS.md, Testing: every bug fix lands with a regression test). Fine as a follow-up.
    3. Whole-document writes (packages/lexical-y/src/internal/Write.ts:4223): in my timings, edits that touch every line of a 6,000-line document (reversing the lines, appending to each line and adding a line after it, removing every other line, replacing each line) took 8-21% longer than on main, growing linearly. Typing and single-line edits return at the first check of $markerContinues, so this only matters for bulk edits. If you want it back, the newLines.some(...) scan here runs once per staying line and could use a precomputed index of the last new line.

    <!-- codebunny-pub:1 k=9c152cd2eec05217ab2472761b8931ed50bafdaf700c712ca1baa4240d191d5c -->

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 09:27 UTC
    Code Review
    .changeset/lexical-y-marker-kept-by-its-line.md:1
    @@ -0,0 +1,9 @@
    +---
    +'@lexical/y': patch
    +---
    +
    +[fix] Keep a line's marker with the line that continues it: where a collaborator replaced a line (a change of its block type, or a new block holding its text) and added a block after it in one update, the new block took the old line's marker, so a client composing in that line saw its composition move to the new block, and ending it re-tokenized that block with its code highlighter (dropping its format and NodeState) or wrote what it typed there.

    Nit (optional). In this recipe's cell on main (MarkerKeptByItsLine.test.ts:140-190), the code block comes back as code-highlight nodes with format 0 and note still old on every peer, as the description's Before output also shows ("note":"old" on both sides). Only the formats are dropped, so naming those tells upgraders what they will see (CONTRIBUTING.md, Changesets):

    [fix] Keep a line's marker with the line that continues it: where a collaborator replaced a line (a change of its block type, or a new block holding its text) and added a block after it in one update, the new block took the old line's marker, so a client composing in that line saw its composition move to the new block, and ending it re-tokenized that block with its code highlighter (dropping its formats, such as underline) or wrote what it typed there.
    

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 10, 2026 09:27 UTC
    Approved Reviewer

    Thanks, this looks good. Keeping a line's marker with the line that holds its end fixes the replaced-line race cleanly: the composition and join cells in MarkerKeptByItsLine.test.ts fail on main and pass here, and the cells for Enter, pastes at or over a line's end and app-code splits end the same on both. The accepted limit (DECISIONS.md D118, y.md Limits, the three test.fails) and the pinned concurrent-join outcome read as deliberate, so nothing below blocks.

    Optional, non-blocking:

    1. Changeset summary (.changeset/lexical-y-marker-kept-by-its-line.md:5): it says ending the composition re-tokenized the block "(dropping its format and NodeState)". In the Verify: recipe's cell on main, the code block's re-tokenized nodes keep note: 'old' and lose only their underline, which matches the "note":"old" on both sides of the Before output in the description. CONTRIBUTING.md (Changesets) says this entry is what people upgrading read, so "(dropping its formats, such as underline)" would be more accurate.
    2. Test plan counts: the After block reports 104 passed | 24 expected fail (128) and 16 cells failing on main. With the typed-text and concurrent-join cells added since, the file now runs 112 passed | 24 expected fail (136), and 24 cells fail on main. AGENTS.md (Commits and Pull Requests) asks the Test plan to carry the real output of the command, so pasting the current run would keep it accurate.

    <!-- codebunny-pub:1 k=393dd09a08f7d044356dea2d132b286a37105459567d0592d19aad7d949556ce -->

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 09:53 UTC
    Code Review
    packages/lexical-y/src/internal/Write.ts:1
    @@ -3982,6 +3983,306 @@ export class Writer {
       // -------------------------------------------------------------------------
       // Sequences
     
    +  /**
    +   * Which old line markers a desired line may keep, where a sequence holds
    +   * more than one marker on either side (one line written on its own keeps
    +   * its marker): null where there is no choice. Invariant: an old marker is
    +   * kept only by the line that continues the line it ended (see D118), the
    +   * first of:
    +   * - the line whose last atom is the old line's last atom (a character, or
    +   *   an inline node kept), by Lexical's record of text edits (`record`, see
    +   *   $exactAtoms): the tail of a split (Enter in the middle of a line: the
    +   *   new line keeps the marker after the tail and the old line, holding the
    +   *   head, gets a new one, so no character moves), or the line a join or a
    +   *   range delete across lines ends with the joined text (it keeps the
    +   *   marker after that text, and its own goes);
    +   * - where the old line stays: a new line after it ending with what it
    +   *   lost from its end (a split the record does not explain: app code that
    +   *   sets the head's text and adds a line holding the tail), else that line
    +   *   itself;
    +   * - where it is gone: the lines holding a node it held before this update
    +   *   (a line Lexical replaced, `$setBlocksType`, or one joined into another),
    +   *   else the lines ending with all of its text (a paste over it);

    Nit (optional). Two of these rules lag the code: a line that stays gives its marker to any line by position when a new line follows it and no line holds its old end (:4228), and a gone line's text claims only where exactly one line ends with it (:4255). D118 already states both; this keeps the invariant comment in step:

       * - where the old line stays: a new line after it ending with what it
       *   lost from its end (a split the record does not explain: app code that
       *   sets the head's text and adds a line holding the tail); else, where a
       *   new line follows it, any line by position as before (lines pasted at
       *   its end, Enter or a paste over a selection that reaches its end); else
       *   that line itself;
       * - where it is gone: the lines holding a node it held before this update
       *   (a line Lexical replaced, `$setBlocksType`, or one joined into another),
       *   else the one line ending with all of its text (a paste over it; with
       *   several, by position);
    

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 10, 2026 09:53 UTC
    Approved Reviewer

    Thanks, this looks good. Keeping a line's marker with the line that continues it fixes the replaced-line race cleanly: the composition, join and typed-text cells in MarkerKeptByItsLine.test.ts fail on main and pass here, and the cells for Enter, pastes at or over a line's end and app-code splits end the same on both. The accepted limit (DECISIONS.md D118, y.md Limits, the three test.fails) and the pinned concurrent-join outcome read as deliberate, and the changeset now names the formats main lost.

    Optional, non-blocking:

    1. Test plan, Before: the MarkerKeptByItsLine.test.ts run on main is summarised in parentheses rather than pasted. AGENTS.md (Commits and Pull Requests) asks for the real output ("Paste real output — do not describe it"); vitest's Tests 24 failed | 112 passed (136) line for that run would do.
    2. $markerContinues JSDoc (packages/lexical-y/src/internal/Write.ts:3999-4005): it says a line that stays keeps its marker, and that a gone line's marker goes to "the lines ending with all of its text". The code gives a staying line's marker to any line by position when a new line follows it and no line holds its old end (:4228), and lets a gone line's text claim only where exactly one line ends with it (:4255). D118 already states both rules; aligning the comment keeps the function's invariant accurate for the next reader (suggestion inline).

    <!-- codebunny-pub:1 k=72ec135242baeb8b5a3ced5c36e2e9c574cfd695a6e32b6379d05841aa5bc211 -->

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 10:17 UTC
    Code Review
    packages/lexical-website/docs/collaboration/y.md:1
    @@ -1343,6 +1347,13 @@ not merge as a user might expect:
       re-tokenization is written, as on `main`. The binding reports the skip with
       `UNSUPPORTED_EDIT_WARNING` (`reason: 'other'`, `detailCode:
       'held-line-retokenize'`), once per composition.
    +- **A line replaced next to a new line.** A line a collaborator replaces with

    Consider (non-blocking). In these shapes the old marker is deleted, so a collaborator's concurrent Delete at the end of the line (or Backspace at the start of the next) is dropped too, not just an alignment or block-type change. Start from intro / see / next. A moves see's nodes into a quote, sets its text to SEE and adds xyz after it, while B presses Delete at the end of see. main gives intro / SEE / xyznext; this branch gives intro / SEE / xyz / next (gc off and on, both id orders, converged). The same holds for a line remade with the same text and for an app-code split with an extra line. No text is lost, and main joined the wrong line, but this bullet, D118 and the changeset's accepted-limit paragraph describe only alignment and block type. Per packages/lexical-y/AGENTS.md (accepted limits in y.md's Limits, known failures as test.fails), consider adding "or a Delete that joins the next line into it" here, and a test.fails cell beside MarkerKeptByItsLine.test.ts:360.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 10:17 UTC
    Code Review
    packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts:1
    @@ -0,0 +1,901 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// @vitest-environment jsdom
    +
    +// A composes at the end of a line. B replaces that line with a block of
    +// another class (or a new block of the same class) holding its text, and adds
    +// a block after it. The writer matched a line marker to any marker, so the
    +// common suffix gave the old line's marker to B's new block; every reader
    +// keys a line by its marker, so on A the composed text node, and the line
    +// held while composing, moved to the new block. Ending the composition then
    +// re-tokenized that block with A's code highlighter, dropping its format and
    +// NodeState, or wrote the text A typed into it. A marker now stays with the
    +// line that continues the line it ended (DECISIONS.md D118).
    +
    +import {$createCodeNode, $isCodeNode, CodeHighlightNode} from '@lexical/code';
    +import {PrismTokenizer, registerCodeHighlighting} from '@lexical/code-prism';
    +import {autoLinkUrlMatcher, registerAutoLink} from '@lexical/link';
    +import {$createListItemNode, $createListNode, $isListNode} from '@lexical/list';
    +import {$createHeadingNode, $createQuoteNode} from '@lexical/rich-text';
    +import {
    +  $createParagraphNode,
    +  $createTextNode,
    +  $getNodeByKey,
    +  $getRoot,
    +  $getSelection,
    +  $getState,
    +  $isRangeSelection,
    +  $isTextNode,
    +  $setCompositionKey,
    +  $setSelection,
    +  $setState,
    +  createState,
    +  type ElementNode,
    +  type LexicalEditor,
    +  stringValue,
    +  TextNode,
    +} from 'lexical';
    +import {describe, expect, onTestFinished, test} from 'vitest';
    +
    +import {
    +  $createEquation,
    +  $selectIn,
    +  expectConverged,
    +  freshReader,
    +  NODES,
    +  setup,
    +} from '../../utils/harness';
    +
    +const note = createState('note', {parse: stringValue()});
    +
    +/** Uppercases the text of a heading or quote (a parent-dependent transform). */
    +const upper = (editor: LexicalEditor) =>
    +  editor.registerNodeTransform(TextNode, node => {
    +    const parent = node.getParent();
    +    if (parent !== null && parent.getType() === 'quote') {
    +      const text = node.getTextContent();
    +      if (text !== text.toUpperCase()) {
    +        node.setTextContent(text.toUpperCase());
    +      }
    +    }
    +  });
    +
    +const autoLink = (editor: LexicalEditor) =>
    +  registerAutoLink(editor, {
    +    changeHandlers: [],
    +    excludeParents: [],
    +    matchers: [autoLinkUrlMatcher],
    +  });
    +
    +/**
    + * A composes `typed` at the end of the second block, in an editor attached
    + * to the DOM as an input method composes; returns the node's key.
    + */
    +function compose(editor: LexicalEditor, typed: string): string {
    +  const host = document.createElement('div');
    +  host.contentEditable = 'true';
    +  document.body.append(host);
    +  editor.setRootElement(host);
    +  host.focus();
    +  onTestFinished(() => {
    +    editor.setRootElement(null);
    +    host.remove();
    +  });
    +  let key = '';
    +  editor.update(
    +    () => {
    +      const block = $getRoot().getChildAtIndex(1) as ElementNode;
    +      const text = block.getAllTextNodes().at(-1)!;
    +      text.select(text.getTextContentSize(), text.getTextContentSize());
    +      key = text.getKey();
    +      $setCompositionKey(key);
    +      const selection = $getSelection();
    +      if ($isRangeSelection(selection)) {
    +        selection.insertText(typed);
    +      }
    +    },
    +    {discrete: true},
    +  );
    +  return key;
    +}
    +
    +/** The index of the top-level block holding node `key`, -1 if detached. */
    +const $blockOf = (key: string): number => {
    +  const node = $getNodeByKey(key);
    +  return node === null || !node.isAttached()
    +    ? -1
    +    : node.getTopLevelElementOrThrow().getIndexWithinParent();
    +};
    +
    +const $untouchedBlock = (kind: 'code' | 'paragraph') => {
    +  const text = $setState(
    +    $createTextNode('let untouched = 1;').setFormat('underline'),
    +    note,
    +    'old',
    +  );
    +  return (
    +    kind === 'code' ? $createCodeNode('javascript') : $createParagraphNode()
    +  ).append(text);
    +};
    +
    +/** The untouched block's text nodes: class, format, note. */
    +const $untouched = () =>
    +  ($getRoot().getLastChildOrThrow() as ElementNode)
    +    .getAllTextNodes()
    +    .map(n => `${n.getType()}:${n.getFormat()}:${$getState(n, note)}`)
    +    .join(' ');
    +
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [33, 11, 22],
    +    [33, 22, 11],
    +  ]) {
    +    describe(`gc ${gc}, ids ${ids.join(',')}`, () => {
    +      test('a line replaced by a quote with a code block added after it: the composed node does not go to the code block, which keeps its format and NodeState', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createParagraphNode().append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: upper},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        // Only the composing client highlights code.
    +        onTestFinished(registerCodeHighlighting(a.editor, PrismTokenizer));
    +        const key = compose(a.editor, 'word');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const quote = $createQuoteNode().append(...line.getChildren());
    +          line.replace(quote);
    +          quote.insertAfter($untouchedBlock('code'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // The composed text node is not the code block's: B's quote has a new
    +        // marker (D118), so the node goes with the old one, which B deleted
    +        // (on main it went to the code block).
    +        expect(a.read(() => $blockOf(key))).toBe(-1);
    +        a.update(() => {
    +          $setCompositionKey(null);
    +          const n = $getNodeByKey(key);
    +          if ($isTextNode(n) && n.isAttached()) {
    +            n.getWritable();
    +          }
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        await t.sync();
    +        const fresh = await freshReader(a);
    +        onTestFinished(() => fresh.stop());
    +        for (const peer of [...t.peers, fresh]) {
    +          expect(peer.read($untouched)).toBe('text:8:old');
    +          expect(
    +            peer.read(() =>
    +              $getRoot()
    +                .getChildren()
    +                .map(n => n.getTextContent()),
    +            ),
    +          ).toEqual(['intro', 'SEE WORD', 'let untouched = 1;']);
    +        }
    +        await expectConverged(t.peers);
    +      });
    +
    +      test('a code block replaced by a code block with a paragraph added after it: the composed node does not go to the paragraph', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createCodeNode('javascript').append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: autoLink},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        const key = compose(a.editor, 'https://lexical.dev');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const code = $createCodeNode('javascript').append(
    +            ...line.getChildren(),
    +          );
    +          line.replace(code);
    +          code.insertAfter($untouchedBlock('paragraph'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // As above: the saved node goes with B's deleted marker (on main it
    +        // went to the paragraph after the code block).
    +        expect(a.read(() => $blockOf(key))).toBe(-1);
    +        // The composition ends, and A types at its selection.
    +        a.update(() => {
    +          $setCompositionKey(null);
    +          const selection = $getSelection();
    +          if ($isRangeSelection(selection)) {
    +            selection.insertText(' z');
    +          }
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        await t.sync();
    +        const fresh = await freshReader(a);
    +        onTestFinished(() => fresh.stop());
    +        for (const peer of [...t.peers, fresh]) {
    +          const blocks = peer.read(() =>
    +            $getRoot()
    +              .getChildren()
    +              .map(n => [$isCodeNode(n), n.getTextContent()]),
    +          );
    +          expect(blocks[2]).toEqual([false, 'let untouched = 1;']);
    +          // What A typed at its selection is in the code block (as on main,
    +          // where the selection stays on the code block's text).
    +          expect(blocks[1][1]).toContain(' z');
    +          expect(blocks[1][0]).toBe(true);
    +          expect(peer.read($untouched)).toBe('text:8:old');
    +        }
    +        await expectConverged(t.peers);
    +      });
    +    });
    +  }
    +}
    +
    +// A split, a join and a line remade with a line added after it keep the old
    +// marker where the diff kept it (D118: the tail of a split, the line a join
    +// ends with), so a collaborator's concurrent change of the line's attributes
    +// (its alignment, its type) stays with the line that holds its end.
    +type Change = 'centers' | 'makes it a heading';
    +const $change = (change: Change, index: number) => {
    +  const line = $getRoot().getChildAtIndex(index) as ElementNode;
    +  if (change === 'centers') {
    +    line.setFormat('center');
    +  } else {
    +    line.replace($createHeadingNode('h2').append(...line.getChildren()));
    +  }
    +  $setSelection(null);
    +};
    +const $shape = () =>
    +  $getRoot()
    +    .getChildren()
    +    .map(
    +      n =>
    +        `${n.getType()}${(n as ElementNode).getFormatType()}:${n.getTextContent()}`,
    +    );
    +
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [1, 2],
    +    [2, 1],
    +  ]) {
    +    for (const change of ['centers', 'makes it a heading'] as const) {
    +      describe(`gc ${gc}, ids ${ids.join(',')}, a collaborator ${change} the line`, () => {
    +        const run = async (
    +          init: () => void,
    +          $edit: () => void,
    +          index: number,
    +          want: string[],
    +        ) => {
    +          const t = await setup(init, {gc, ids});
    +          onTestFinished(() => t.peers.forEach(p => p.stop()));
    +          t.offline();
    +          t.a.update($edit);
    +          t.b.update(() => $change(change, index));
    +          await t.sync();
    +          const fresh = await freshReader(t.a);
    +          onTestFinished(() => fresh.stop());
    +          for (const peer of [...t.peers, fresh]) {
    +            expect(peer.read($shape)).toEqual(want);
    +          }
    +          await expectConverged(t.peers);
    +        };
    +        const changed = (type: string, text: string) =>
    +          change === 'centers' ? `${type}center:${text}` : `heading:${text}`;
    +
    +        test('Enter in a line that ends with an inline node: the tail keeps the change', () =>
    +          run(
    +            () =>
    +              $getRoot().append(
    +                $createParagraphNode().append(
    +                  $createTextNode('hello world'),
    +                  $createEquation('x^2'),
    +                ),
    +              ),
    +            () => {
    +              $selectIn([0], 6).insertParagraph();
    +              $setSelection(null);
    +            },
    +            0,
    +            ['paragraph:hello ', changed('paragraph', 'world')],
    +          ));
    +
    +        test("app code that splits a line (the head's text set, a line added holding the tail): the tail keeps the change", () =>
    +          run(
    +            () =>
    +              $getRoot().append(
    +                $createParagraphNode().append($createTextNode('hello world')),
    +              ),
    +            () => {
    +              const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +              (line.getFirstChildOrThrow() as TextNode).setTextContent(
    +                'hello ',
    +              );
    +              line.insertAfter(
    +                $createParagraphNode().append($createTextNode('world')),
    +              );
    +              $setSelection(null);
    +            },
    +            0,
    +            ['paragraph:hello ', changed('paragraph', 'world')],
    +          ));
    +
    +        test("app code that sets a line's text to its start and adds a line holding its end before it: the line keeps the change", () =>
    +          run(
    +            () =>
    +              $getRoot().append(
    +                $createParagraphNode().append($createTextNode('hello world')),
    +              ),
    +            () => {
    +              const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +              (line.getFirstChildOrThrow() as TextNode).setTextContent(
    +                'hello ',
    +              );
    +              line.insertBefore(
    +                $createParagraphNode().append($createTextNode('world')),
    +              );
    +              $setSelection(null);
    +            },
    +            0,
    +            ['paragraph:world', changed('paragraph', 'hello ')],
    +          ));
    +
    +        // The same accepted limit (D118) for a line replaced by one holding
    +        // its own nodes, with its text changed, and a line added after it.
    +        test.fails(
    +          'a line replaced by a quote holding its nodes, its text changed, with a line added after it: the quote keeps the change',
    +          () =>
    +            run(
    +              () =>
    +                $getRoot().append(
    +                  $createParagraphNode().append($createTextNode('see')),
    +                ),
    +              () => {
    +                const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +                const quote = $createQuoteNode().append(...line.getChildren());
    +                line.replace(quote);
    +                (quote.getFirstChildOrThrow() as TextNode).setTextContent(
    +                  'SEE',
    +                );
    +                quote.insertAfter(
    +                  $createParagraphNode().append($createTextNode('xyz')),
    +                );
    +                $setSelection(null);
    +              },
    +              0,
    +              [
    +                change === 'centers' ? 'quotecenter:SEE' : 'heading:SEE',
    +                'paragraph:xyz',
    +              ],
    +            ),
    +        );
    +
    +        // And for app code that splits a line without the record of text
    +        // edits and adds another line after the tail.
    +        test.fails(
    +          'app code that splits a line and adds a line after the tail: the tail keeps the change',
    +          () =>
    +            run(
    +              () =>
    +                $getRoot().append(
    +                  $createParagraphNode().append($createTextNode('hello world')),
    +                ),
    +              () => {
    +                const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +                (line.getFirstChildOrThrow() as TextNode).setTextContent(
    +                  'hello ',
    +                );
    +                const tail = $createParagraphNode().append(
    +                  $createTextNode('world'),
    +                );
    +                line.insertAfter(tail);
    +                tail.insertAfter(
    +                  $createParagraphNode().append($createTextNode('extra')),
    +                );
    +                $setSelection(null);
    +              },
    +              0,
    +              [
    +                'paragraph:hello ',
    +                changed('paragraph', 'world'),
    +                'paragraph:extra',
    +              ],
    +            ),
    +        );
    +
    +        // An accepted limit (D118): the remade line gets a new marker, so the
    +        // change is dropped (before, it was applied to the added line).
    +        test.fails(
    +          'a line remade with the same text, with a line added after it: the remade line keeps the change',
    +          () =>
    +            run(
    +              () =>
    +                $getRoot().append(
    +                  $createParagraphNode().append($createTextNode('abc')),
    +                ),
    +              () => {
    +                const line = $getRoot().getFirstChildOrThrow();
    +                const remade = $createParagraphNode().append(
    +                  $createTextNode('abc'),
    +                );
    +                line.replace(remade);
    +                remade.insertAfter(
    +                  $createParagraphNode().append($createTextNode('xyz')),
    +                );
    +                $setSelection(null);
    +              },
    +              0,
    +              [changed('paragraph', 'abc'), 'paragraph:xyz'],
    +            ),
    +        );
    +
    +        test('Backspace at the start of a line, with a line added after it: the joined line keeps the change', () =>

    Consider (non-blocking). The split half of "a join or split with a line added after it" has no cell: the join is pinned here, and the Enter cell at :301 adds no line. This cell passes on this branch and fails on main, where the change lands on added, for both changes, both id orders and both gc settings:

    test('Enter in a line, with a line added after the tail: the tail keeps the change', () =>
      run(
        () =>
          $getRoot().append(
            $createParagraphNode().append($createTextNode('hello world')),
          ),
        () => {
          $selectIn([0], 6).insertParagraph();
          ($getRoot().getChildAtIndex(1) as ElementNode).insertAfter(
            $createParagraphNode().append($createTextNode('added')),
          );
          $setSelection(null);
        },
        0,
        ['paragraph:hello ', changed('paragraph', 'world'), 'paragraph:added'],
      ));
    

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 10, 2026 10:17 UTC
    Code Review
    packages/lexical-y/src/__tests__/unit/regressions/MarkerKeptByItsLine.test.ts:1
    @@ -0,0 +1,901 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// @vitest-environment jsdom
    +
    +// A composes at the end of a line. B replaces that line with a block of
    +// another class (or a new block of the same class) holding its text, and adds
    +// a block after it. The writer matched a line marker to any marker, so the
    +// common suffix gave the old line's marker to B's new block; every reader
    +// keys a line by its marker, so on A the composed text node, and the line
    +// held while composing, moved to the new block. Ending the composition then
    +// re-tokenized that block with A's code highlighter, dropping its format and
    +// NodeState, or wrote the text A typed into it. A marker now stays with the
    +// line that continues the line it ended (DECISIONS.md D118).
    +
    +import {$createCodeNode, $isCodeNode, CodeHighlightNode} from '@lexical/code';
    +import {PrismTokenizer, registerCodeHighlighting} from '@lexical/code-prism';
    +import {autoLinkUrlMatcher, registerAutoLink} from '@lexical/link';
    +import {$createListItemNode, $createListNode, $isListNode} from '@lexical/list';
    +import {$createHeadingNode, $createQuoteNode} from '@lexical/rich-text';
    +import {
    +  $createParagraphNode,
    +  $createTextNode,
    +  $getNodeByKey,
    +  $getRoot,
    +  $getSelection,
    +  $getState,
    +  $isRangeSelection,
    +  $isTextNode,
    +  $setCompositionKey,
    +  $setSelection,
    +  $setState,
    +  createState,
    +  type ElementNode,
    +  type LexicalEditor,
    +  stringValue,
    +  TextNode,
    +} from 'lexical';
    +import {describe, expect, onTestFinished, test} from 'vitest';
    +
    +import {
    +  $createEquation,
    +  $selectIn,
    +  expectConverged,
    +  freshReader,
    +  NODES,
    +  setup,
    +} from '../../utils/harness';
    +
    +const note = createState('note', {parse: stringValue()});
    +
    +/** Uppercases the text of a heading or quote (a parent-dependent transform). */
    +const upper = (editor: LexicalEditor) =>
    +  editor.registerNodeTransform(TextNode, node => {
    +    const parent = node.getParent();
    +    if (parent !== null && parent.getType() === 'quote') {
    +      const text = node.getTextContent();
    +      if (text !== text.toUpperCase()) {
    +        node.setTextContent(text.toUpperCase());
    +      }
    +    }
    +  });
    +
    +const autoLink = (editor: LexicalEditor) =>
    +  registerAutoLink(editor, {
    +    changeHandlers: [],
    +    excludeParents: [],
    +    matchers: [autoLinkUrlMatcher],
    +  });
    +
    +/**
    + * A composes `typed` at the end of the second block, in an editor attached
    + * to the DOM as an input method composes; returns the node's key.
    + */
    +function compose(editor: LexicalEditor, typed: string): string {
    +  const host = document.createElement('div');
    +  host.contentEditable = 'true';
    +  document.body.append(host);
    +  editor.setRootElement(host);
    +  host.focus();
    +  onTestFinished(() => {
    +    editor.setRootElement(null);
    +    host.remove();
    +  });
    +  let key = '';
    +  editor.update(
    +    () => {
    +      const block = $getRoot().getChildAtIndex(1) as ElementNode;
    +      const text = block.getAllTextNodes().at(-1)!;
    +      text.select(text.getTextContentSize(), text.getTextContentSize());
    +      key = text.getKey();
    +      $setCompositionKey(key);
    +      const selection = $getSelection();
    +      if ($isRangeSelection(selection)) {
    +        selection.insertText(typed);
    +      }
    +    },
    +    {discrete: true},
    +  );
    +  return key;
    +}
    +
    +/** The index of the top-level block holding node `key`, -1 if detached. */
    +const $blockOf = (key: string): number => {
    +  const node = $getNodeByKey(key);
    +  return node === null || !node.isAttached()
    +    ? -1
    +    : node.getTopLevelElementOrThrow().getIndexWithinParent();
    +};
    +
    +const $untouchedBlock = (kind: 'code' | 'paragraph') => {
    +  const text = $setState(
    +    $createTextNode('let untouched = 1;').setFormat('underline'),
    +    note,
    +    'old',
    +  );
    +  return (
    +    kind === 'code' ? $createCodeNode('javascript') : $createParagraphNode()
    +  ).append(text);
    +};
    +
    +/** The untouched block's text nodes: class, format, note. */
    +const $untouched = () =>
    +  ($getRoot().getLastChildOrThrow() as ElementNode)
    +    .getAllTextNodes()
    +    .map(n => `${n.getType()}:${n.getFormat()}:${$getState(n, note)}`)
    +    .join(' ');
    +
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [33, 11, 22],
    +    [33, 22, 11],
    +  ]) {
    +    describe(`gc ${gc}, ids ${ids.join(',')}`, () => {
    +      test('a line replaced by a quote with a code block added after it: the composed node does not go to the code block, which keeps its format and NodeState', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createParagraphNode().append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: upper},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        // Only the composing client highlights code.
    +        onTestFinished(registerCodeHighlighting(a.editor, PrismTokenizer));
    +        const key = compose(a.editor, 'word');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const quote = $createQuoteNode().append(...line.getChildren());
    +          line.replace(quote);
    +          quote.insertAfter($untouchedBlock('code'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // The composed text node is not the code block's: B's quote has a new
    +        // marker (D118), so the node goes with the old one, which B deleted
    +        // (on main it went to the code block).
    +        expect(a.read(() => $blockOf(key))).toBe(-1);
    +        a.update(() => {
    +          $setCompositionKey(null);
    +          const n = $getNodeByKey(key);
    +          if ($isTextNode(n) && n.isAttached()) {
    +            n.getWritable();
    +          }
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        await t.sync();
    +        const fresh = await freshReader(a);
    +        onTestFinished(() => fresh.stop());
    +        for (const peer of [...t.peers, fresh]) {
    +          expect(peer.read($untouched)).toBe('text:8:old');
    +          expect(
    +            peer.read(() =>
    +              $getRoot()
    +                .getChildren()
    +                .map(n => n.getTextContent()),
    +            ),
    +          ).toEqual(['intro', 'SEE WORD', 'let untouched = 1;']);
    +        }
    +        await expectConverged(t.peers);
    +      });
    +
    +      test('a code block replaced by a code block with a paragraph added after it: the composed node does not go to the paragraph', async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              $createParagraphNode().append($createTextNode('intro')),
    +              $createCodeNode('javascript').append($createTextNode('see ')),
    +            ),
    +          {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: autoLink},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        const key = compose(a.editor, 'https://lexical.dev');
    +        await t.sync();
    +        b.update(() => {
    +          const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +          const code = $createCodeNode('javascript').append(
    +            ...line.getChildren(),
    +          );
    +          line.replace(code);
    +          code.insertAfter($untouchedBlock('paragraph'));
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        // As above: the saved node goes with B's deleted marker (on main it
    +        // went to the paragraph after the code block).
    +        expect(a.read(() => $blockOf(key))).toBe(-1);
    +        // The composition ends, and A types at its selection.
    +        a.update(() => {
    +          $setCompositionKey(null);
    +          const selection = $getSelection();
    +          if ($isRangeSelection(selection)) {
    +            selection.insertText(' z');
    +          }
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        await t.sync();
    +        const fresh = await freshReader(a);
    +        onTestFinished(() => fresh.stop());
    +        for (const peer of [...t.peers, fresh]) {
    +          const blocks = peer.read(() =>
    +            $getRoot()
    +              .getChildren()
    +              .map(n => [$isCodeNode(n), n.getTextContent()]),
    +          );
    +          expect(blocks[2]).toEqual([false, 'let untouched = 1;']);
    +          // What A typed at its selection is in the code block (as on main,
    +          // where the selection stays on the code block's text).
    +          expect(blocks[1][1]).toContain(' z');
    +          expect(blocks[1][0]).toBe(true);
    +          expect(peer.read($untouched)).toBe('text:8:old');
    +        }
    +        await expectConverged(t.peers);
    +      });
    +    });
    +  }
    +}
    +
    +// A split, a join and a line remade with a line added after it keep the old
    +// marker where the diff kept it (D118: the tail of a split, the line a join
    +// ends with), so a collaborator's concurrent change of the line's attributes
    +// (its alignment, its type) stays with the line that holds its end.
    +type Change = 'centers' | 'makes it a heading';
    +const $change = (change: Change, index: number) => {
    +  const line = $getRoot().getChildAtIndex(index) as ElementNode;
    +  if (change === 'centers') {
    +    line.setFormat('center');
    +  } else {
    +    line.replace($createHeadingNode('h2').append(...line.getChildren()));
    +  }
    +  $setSelection(null);
    +};
    +const $shape = () =>
    +  $getRoot()
    +    .getChildren()
    +    .map(
    +      n =>
    +        `${n.getType()}${(n as ElementNode).getFormatType()}:${n.getTextContent()}`,
    +    );
    +
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [1, 2],
    +    [2, 1],
    +  ]) {
    +    for (const change of ['centers', 'makes it a heading'] as const) {
    +      describe(`gc ${gc}, ids ${ids.join(',')}, a collaborator ${change} the line`, () => {
    +        const run = async (
    +          init: () => void,
    +          $edit: () => void,
    +          index: number,
    +          want: string[],
    +        ) => {
    +          const t = await setup(init, {gc, ids});
    +          onTestFinished(() => t.peers.forEach(p => p.stop()));
    +          t.offline();
    +          t.a.update($edit);
    +          t.b.update(() => $change(change, index));
    +          await t.sync();
    +          const fresh = await freshReader(t.a);
    +          onTestFinished(() => fresh.stop());
    +          for (const peer of [...t.peers, fresh]) {
    +            expect(peer.read($shape)).toEqual(want);
    +          }
    +          await expectConverged(t.peers);
    +        };
    +        const changed = (type: string, text: string) =>
    +          change === 'centers' ? `${type}center:${text}` : `heading:${text}`;
    +
    +        test('Enter in a line that ends with an inline node: the tail keeps the change', () =>
    +          run(
    +            () =>
    +              $getRoot().append(
    +                $createParagraphNode().append(
    +                  $createTextNode('hello world'),
    +                  $createEquation('x^2'),
    +                ),
    +              ),
    +            () => {
    +              $selectIn([0], 6).insertParagraph();
    +              $setSelection(null);
    +            },
    +            0,
    +            ['paragraph:hello ', changed('paragraph', 'world')],
    +          ));
    +
    +        test("app code that splits a line (the head's text set, a line added holding the tail): the tail keeps the change", () =>
    +          run(
    +            () =>
    +              $getRoot().append(
    +                $createParagraphNode().append($createTextNode('hello world')),
    +              ),
    +            () => {
    +              const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +              (line.getFirstChildOrThrow() as TextNode).setTextContent(
    +                'hello ',
    +              );
    +              line.insertAfter(
    +                $createParagraphNode().append($createTextNode('world')),
    +              );
    +              $setSelection(null);
    +            },
    +            0,
    +            ['paragraph:hello ', changed('paragraph', 'world')],
    +          ));
    +
    +        test("app code that sets a line's text to its start and adds a line holding its end before it: the line keeps the change", () =>
    +          run(
    +            () =>
    +              $getRoot().append(
    +                $createParagraphNode().append($createTextNode('hello world')),
    +              ),
    +            () => {
    +              const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +              (line.getFirstChildOrThrow() as TextNode).setTextContent(
    +                'hello ',
    +              );
    +              line.insertBefore(
    +                $createParagraphNode().append($createTextNode('world')),
    +              );
    +              $setSelection(null);
    +            },
    +            0,
    +            ['paragraph:world', changed('paragraph', 'hello ')],
    +          ));
    +
    +        // The same accepted limit (D118) for a line replaced by one holding
    +        // its own nodes, with its text changed, and a line added after it.
    +        test.fails(
    +          'a line replaced by a quote holding its nodes, its text changed, with a line added after it: the quote keeps the change',
    +          () =>
    +            run(
    +              () =>
    +                $getRoot().append(
    +                  $createParagraphNode().append($createTextNode('see')),
    +                ),
    +              () => {
    +                const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +                const quote = $createQuoteNode().append(...line.getChildren());
    +                line.replace(quote);
    +                (quote.getFirstChildOrThrow() as TextNode).setTextContent(
    +                  'SEE',
    +                );
    +                quote.insertAfter(
    +                  $createParagraphNode().append($createTextNode('xyz')),
    +                );
    +                $setSelection(null);
    +              },
    +              0,
    +              [
    +                change === 'centers' ? 'quotecenter:SEE' : 'heading:SEE',
    +                'paragraph:xyz',
    +              ],
    +            ),
    +        );
    +
    +        // And for app code that splits a line without the record of text
    +        // edits and adds another line after the tail.
    +        test.fails(
    +          'app code that splits a line and adds a line after the tail: the tail keeps the change',
    +          () =>
    +            run(
    +              () =>
    +                $getRoot().append(
    +                  $createParagraphNode().append($createTextNode('hello world')),
    +                ),
    +              () => {
    +                const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +                (line.getFirstChildOrThrow() as TextNode).setTextContent(
    +                  'hello ',
    +                );
    +                const tail = $createParagraphNode().append(
    +                  $createTextNode('world'),
    +                );
    +                line.insertAfter(tail);
    +                tail.insertAfter(
    +                  $createParagraphNode().append($createTextNode('extra')),
    +                );
    +                $setSelection(null);
    +              },
    +              0,
    +              [
    +                'paragraph:hello ',
    +                changed('paragraph', 'world'),
    +                'paragraph:extra',
    +              ],
    +            ),
    +        );
    +
    +        // An accepted limit (D118): the remade line gets a new marker, so the
    +        // change is dropped (before, it was applied to the added line).
    +        test.fails(
    +          'a line remade with the same text, with a line added after it: the remade line keeps the change',
    +          () =>
    +            run(
    +              () =>
    +                $getRoot().append(
    +                  $createParagraphNode().append($createTextNode('abc')),
    +                ),
    +              () => {
    +                const line = $getRoot().getFirstChildOrThrow();
    +                const remade = $createParagraphNode().append(
    +                  $createTextNode('abc'),
    +                );
    +                line.replace(remade);
    +                remade.insertAfter(
    +                  $createParagraphNode().append($createTextNode('xyz')),
    +                );
    +                $setSelection(null);
    +              },
    +              0,
    +              [changed('paragraph', 'abc'), 'paragraph:xyz'],
    +            ),
    +        );
    +
    +        test('Backspace at the start of a line, with a line added after it: the joined line keeps the change', () =>
    +          run(
    +            () =>
    +              $getRoot().append(
    +                $createParagraphNode().append($createTextNode('one')),
    +                $createParagraphNode().append($createTextNode('two')),
    +              ),
    +            () => {
    +              $selectIn([1], 0).deleteCharacter(true);
    +              $getRoot().append(
    +                $createParagraphNode().append($createTextNode('added')),
    +              );
    +              $setSelection(null);
    +            },
    +            1,
    +            [changed('paragraph', 'onetwo'), 'paragraph:added'],
    +          ));
    +      });
    +    }
    +  }
    +}
    +
    +// A removes the lines after a line while composing in one of them, and B
    +// typed into it at the same time (held on A): no line continues the removed
    +// lines' markers, so the line before keeps one by position, as before, and
    +// B's character joins its end rather than the next line's text or a line of
    +// its own (D118).
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [1, 2],
    +    [2, 1],
    +  ]) {
    +    test(`lines removed after a line while a collaborator typed in one of them (gc ${gc}, ids ${ids.join(',')}): the typed character joins the line before, as before`, async () => {
    +      const t = await setup(
    +        () =>
    +          $getRoot().append(
    +            $createParagraphNode().append($createTextNode('zero')),
    +            $createParagraphNode().append($createTextNode('one')),
    +            $createParagraphNode().append($createTextNode('two')),
    +          ),
    +        {gc, ids},
    +      );
    +      onTestFinished(() => t.peers.forEach(p => p.stop()));
    +      const {a, b} = t;
    +      a.update(() => {
    +        const text = (
    +          $getRoot().getChildAtIndex(2) as ElementNode
    +        ).getFirstChildOrThrow() as TextNode;
    +        text.select(1, 1);
    +        $setCompositionKey(text.getKey());
    +      });
    +      b.update(() => {
    +        $selectIn([2], 1).insertText('R');
    +        $setSelection(null);
    +      });
    +      await t.sync();
    +      a.update(() => {
    +        $getRoot().getChildAtIndex(2)!.remove();
    +        $getRoot().getChildAtIndex(1)!.remove();
    +        // The caret ends at the end of the line before.
    +        $getRoot().getFirstChildOrThrow().selectEnd();
    +      });
    +      await t.sync();
    +      a.update(() => $setCompositionKey(null));
    +      await t.sync();
    +      const fresh = await freshReader(a);
    +      onTestFinished(() => fresh.stop());
    +      for (const peer of [...t.peers, fresh]) {
    +        expect(
    +          peer.read(() =>
    +            $getRoot()
    +              .getChildren()
    +              .map(n => n.getTextContent()),
    +          ),
    +        ).toEqual(['zeroR']);
    +      }
    +      await expectConverged(t.peers);
    +    });
    +  }
    +}
    +
    +// Two collaborators delete across the same lines at once, and one of them
    +// also replaces the line that is left and adds a line next to it: that line
    +// gets a new marker, as before. Kept, its old marker (which the other
    +// client's join deletes) left it without a boundary, joined to the added
    +// line (D118).
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [1, 2],
    +    [2, 1],
    +  ]) {
    +    for (const added of ['after', 'before'] as const) {
    +      test(`concurrent deletes across lines, one replacing the line left and adding a line ${added} it (gc ${gc}, ids ${ids.join(',')}): every line keeps its boundary`, async () => {
    +        const t = await setup(
    +          () =>
    +            $getRoot().append(
    +              ...['AB', 'CDEF', 'G'].map(text =>
    +                $createParagraphNode().append($createTextNode(text)),
    +              ),
    +            ),
    +          {gc, ids},
    +        );
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        t.offline();
    +        t.a.update(() => {
    +          const texts = $getRoot().getAllTextNodes();
    +          const selection = texts[0].select(2, 2);
    +          selection.focus.set(texts[1].getKey(), 2, 'text');
    +          selection.removeText();
    +          $setSelection(null);
    +        });
    +        t.b.update(() => {
    +          const texts = $getRoot().getAllTextNodes();
    +          const selection = texts[0].select(1, 1);
    +          selection.focus.set(texts[1].getKey(), 4, 'text');
    +          selection.removeText();
    +          const line = $getRoot().getFirstChildOrThrow() as ElementNode;
    +          const next = $createParagraphNode().append(...line.getChildren());
    +          line.replace(next);
    +          const extra = $createParagraphNode().append($createTextNode('ADDED'));
    +          if (added === 'after') {
    +            next.insertAfter(extra);
    +          } else {
    +            next.insertBefore(extra);
    +          }
    +          $setSelection(null);
    +        });
    +        await t.sync();
    +        await t.sync();
    +        const fresh = await freshReader(t.a);
    +        onTestFinished(() => fresh.stop());
    +        const want =
    +          added === 'after' ? ['A', 'ADDED', 'G'] : ['ADDED', 'A', 'G'];
    +        for (const peer of [...t.peers, fresh]) {
    +          expect(
    +            peer.read(() =>
    +              $getRoot()
    +                .getChildren()
    +                .map(n => n.getTextContent()),
    +            ),
    +          ).toEqual(want);
    +        }
    +        await expectConverged(t.peers);
    +      });
    +    }
    +  }
    +}
    +
    +// Lines pasted at the end of a line (or text and a line added after it by app
    +// code): the split's tail is empty, so the last new line keeps the marker, as
    +// before, and the line keeps its place for a collaborator composing in it
    +// (the paste waits until the composition ends), for a concurrent Delete at
    +// its end, and for a concurrent change of its alignment (D118).
    +const $pasteAtEnd = () => {
    +  $selectIn([0], 5).insertNodes([
    +    $createParagraphNode().append($createTextNode('A')),
    +    $createParagraphNode().append($createTextNode('B')),
    +  ]);
    +  $setSelection(null);
    +};
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [1, 2],
    +    [2, 1],
    +  ]) {
    +    describe(`lines pasted at the end of a line (gc ${gc}, ids ${ids.join(',')})`, () => {
    +      const $init = () =>
    +        $getRoot().append(
    +          $createParagraphNode().append($createTextNode('hello')),
    +          $createParagraphNode().append($createTextNode('next')),
    +        );
    +      const lines = (p: {read: <T>(f: () => T) => T}) =>
    +        p.read(() =>
    +          $getRoot()
    +            .getChildren()
    +            .map(
    +              n =>
    +                `${(n as ElementNode).getFormatType()}:${n.getTextContent()}`,
    +            ),
    +        );
    +
    +      test('while a collaborator composes at its end: the line keeps its nodes until the composition ends', async () => {
    +        const t = await setup($init, {gc, ids});
    +        onTestFinished(() => t.peers.forEach(p => p.stop()));
    +        const {a, b} = t;
    +        const host = document.createElement('div');
    +        host.contentEditable = 'true';
    +        document.body.append(host);
    +        a.editor.setRootElement(host);
    +        host.focus();
    +        onTestFinished(() => {
    +          a.editor.setRootElement(null);
    +          host.remove();
    +        });
    +        let key = '';
    +        a.update(() => {
    +          const text = $getRoot().getAllTextNodes()[0];
    +          text.select(5, 5);
    +          key = text.getKey();
    +          $setCompositionKey(key);
    +        });
    +        b.update($pasteAtEnd);
    +        await t.sync();
    +        expect(a.read(() => $blockOf(key))).toBe(0);
    +        a.update(() => $setCompositionKey(null));
    +        await t.sync();
    +        const fresh = await freshReader(a);
    +        onTestFinished(() => fresh.stop());
    +        for (const peer of [...t.peers, fresh]) {
    +          expect(lines(peer)).toEqual([':helloA', ':B', ':next']);
    +        }
    +        await expectConverged(t.peers);
    +      });
    +
    +      for (const change of ['Delete at its end', 'centers it'] as const) {
    +        test(`while a collaborator ${change}: as before`, async () => {
    +          const t = await setup($init, {gc, ids});
    +          onTestFinished(() => t.peers.forEach(p => p.stop()));
    +          t.offline();
    +          t.a.update($pasteAtEnd);
    +          t.b.update(() => {
    +            if (change === 'centers it') {
    +              ($getRoot().getFirstChildOrThrow() as ElementNode).setFormat(
    +                'center',
    +              );
    +            } else {
    +              $selectIn([0], 5).deleteCharacter(false);
    +            }
    +            $setSelection(null);
    +          });
    +          await t.sync();
    +          const fresh = await freshReader(t.a);
    +          onTestFinished(() => fresh.stop());
    +          for (const peer of [...t.peers, fresh]) {
    +            expect(lines(peer)).toEqual(
    +              change === 'centers it'
    +                ? [':helloA', 'center:B', ':next']
    +                : [':helloA', ':Bnext'],
    +            );
    +          }
    +          await expectConverged(t.peers);
    +        });
    +      }
    +    });
    +  }
    +}
    +
    +// Enter, or lines pasted, over a selection that reaches the end of a line
    +// (the line loses its end, which no line holds): the last new line keeps the
    +// marker, as before, for a concurrent change of the line's alignment or a
    +// Delete at its end (D118); also on the last line, and in a list item.
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [1, 2],
    +    [2, 1],
    +  ]) {
    +    for (const edit of ['Enter', 'a paste'] as const) {
    +      for (const where of [
    +        'a paragraph',
    +        'the last line',
    +        'a list item',
    +      ] as const) {
    +        for (const change of ['Delete at its end', 'centers it'] as const) {
    +          if (where === 'the last line' && change === 'Delete at its end') {
    +            continue;
    +          }
    +          test(`${edit} over the end of ${where} while a collaborator ${change} (gc ${gc}, ids ${ids.join(',')}): as before`, async () => {
    +            const t = await setup(
    +              () => {
    +                const first =
    +                  where === 'a list item'
    +                    ? $createListItemNode().append(
    +                        $createTextNode('hello world'),
    +                      )
    +                    : $createParagraphNode().append(
    +                        $createTextNode('hello world'),
    +                      );
    +                $getRoot().append(
    +                  where === 'a list item'
    +                    ? $createListNode('bullet').append(
    +                        first,
    +                        $createListItemNode().append($createTextNode('next')),
    +                      )
    +                    : first,
    +                );
    +                if (where === 'a paragraph') {
    +                  $getRoot().append(
    +                    $createParagraphNode().append($createTextNode('next')),
    +                  );
    +                }
    +              },
    +              {gc, ids},
    +            );
    +            onTestFinished(() => t.peers.forEach(p => p.stop()));
    +            const $line = () =>
    +              $getRoot().getAllTextNodes()[0].getParentOrThrow() as ElementNode;
    +            t.offline();
    +            t.a.update(() => {
    +              const text = $getRoot().getAllTextNodes()[0];
    +              const selection = text.select(6, 11);
    +              if (edit === 'Enter') {
    +                selection.insertParagraph();
    +              } else {
    +                selection.insertNodes([
    +                  $createParagraphNode().append($createTextNode('A')),
    +                  $createParagraphNode().append($createTextNode('B')),
    +                ]);
    +              }
    +              $setSelection(null);
    +            });
    +            t.b.update(() => {
    +              if (change === 'centers it') {
    +                $line().setFormat('center');
    +              } else {
    +                const text = $getRoot().getAllTextNodes()[0];
    +                text.select(11, 11).deleteCharacter(false);
    +              }
    +              $setSelection(null);
    +            });
    +            await t.sync();
    +            const fresh = await freshReader(t.a);
    +            onTestFinished(() => fresh.stop());
    +            const shape = (peer: {read: <T>(f: () => T) => T}) =>
    +              peer.read(() =>
    +                $getRoot()
    +                  .getChildren()
    +                  .flatMap(n => ($isListNode(n) ? n.getChildren() : [n]))
    +                  .map(
    +                    n =>
    +                      `${(n as ElementNode).getFormatType()}:${n.getTextContent()}`,
    +                  ),
    +              );
    +            const first = edit === 'Enter' ? ':hello ' : ':hello A';
    +            const added = edit === 'Enter' ? '' : 'B';
    +            const rest = where === 'the last line' ? [] : [':next'];
    +            const want =
    +              change === 'centers it'
    +                ? [first, `center:${added}`, ...rest]
    +                : [first, `:${added}next`];
    +            for (const peer of [...t.peers, fresh]) {
    +              expect(shape(peer)).toEqual(want);
    +            }
    +            await expectConverged(t.peers);
    +          });
    +        }
    +      }
    +    }
    +  }
    +}
    +
    +// The second repro's symptom on its own: text A types at its saved node as
    +// the composition ends. On main that node had moved to the paragraph B added
    +// after the code block, so the text landed there; here the node goes with B's
    +// deleted marker, and nothing lands in the paragraph (D118).
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [33, 11, 22],
    +    [33, 22, 11],
    +  ]) {
    +    test(`text typed at the saved node as the composition ends does not land in the block a collaborator added (gc ${gc}, ids ${ids.join(',')})`, async () => {
    +      const t = await setup(
    +        () =>
    +          $getRoot().append(
    +            $createParagraphNode().append($createTextNode('intro')),
    +            $createCodeNode('javascript').append($createTextNode('see ')),
    +          ),
    +        {gc, ids, nodes: [...NODES, CodeHighlightNode], prepare: autoLink},
    +      );
    +      onTestFinished(() => t.peers.forEach(p => p.stop()));
    +      const {a, b} = t;
    +      const key = compose(a.editor, 'https://lexical.dev');
    +      await t.sync();
    +      b.update(() => {
    +        const line = $getRoot().getChildAtIndex(1) as ElementNode;
    +        const code = $createCodeNode('javascript').append(
    +          ...line.getChildren(),
    +        );
    +        line.replace(code);
    +        code.insertAfter($untouchedBlock('paragraph'));
    +        $setSelection(null);
    +      });
    +      await t.sync();
    +      a.update(() => {
    +        $setCompositionKey(null);
    +        const n = $getNodeByKey(key);
    +        if ($isTextNode(n) && n.isAttached()) {
    +          n.select(n.getTextContentSize(), n.getTextContentSize());
    +          const selection = $getSelection();
    +          if ($isRangeSelection(selection)) {
    +            selection.insertText(' z');
    +          }
    +        }
    +        $setSelection(null);
    +      });
    +      await t.sync();
    +      await t.sync();
    +      for (const peer of t.peers) {
    +        expect(
    +          peer.read(() => $getRoot().getLastChildOrThrow().getTextContent()),
    +        ).toBe('let untouched = 1;');
    +      }
    +      await expectConverged(t.peers);
    +    });
    +  }
    +}
    +
    +// A joins a line into the one before and adds a line after it, while B joins
    +// the next line into the joined one: the joined line keeps the marker after
    +// the joined text (D118), which B's join deletes, so A's added line joins it
    +// (main gave B's join to the added line). Neither keeps both intents; pinned
    +// so a change here is deliberate.
    +for (const gc of [false, true]) {
    +  for (const ids of [
    +    [1, 2],
    +    [2, 1],
    +  ]) {
    +    test(`a join with a line added after it, while a collaborator joins the next line (gc ${gc}, ids ${ids.join(',')})`, async () => {

    Consider (non-blocking). The split counterpart of this outcome isn't pinned. From hello world / next, A runs $selectIn([0], 6).insertParagraph() and adds added after the tail, while B runs $selectIn([0], 11).deleteCharacter(false). Every peer and a fresh reader end at ['hello ', 'worldadded', 'next']; main gives ['hello ', 'world', 'addednext'] (gc off and on, both id orders). It follows from D118 in the same way: the tail keeps the marker B's Delete removes. A twin of this cell would make a later change to the split path deliberate too.

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 10, 2026 10:17 UTC
    Approved Reviewer

    Thanks, this looks good to me. Keeping an old line marker only with the line that continues it fixes the composition and concurrent-alignment cases the description lists. The new cells in MarkerKeptByItsLine.test.ts fail on main and pass here, and the accepted limit is recorded in D118, y.md's Limits and the changeset, as packages/lexical-y/AGENTS.md asks.

    A few optional, non-blocking suggestions:

    1. The accepted limit also drops a concurrent join (packages/lexical-website/docs/collaboration/y.md:1350). Start from intro / see / next. A moves see's nodes into a quote, changes its text to SEE and adds xyz after it, while B presses Delete at the end of see. main gives SEE / xyznext; this branch gives SEE / xyz / next, so B's Delete has no effect. The same happens for a line remade with the same text, with Backspace at the start of the next line, and for an app-code split with an extra line. No text is lost, but the y.md bullet, D118 and the changeset mention only alignment and block type. packages/lexical-y/AGENTS.md puts accepted limits in y.md's Limits and known failures in test.fails, so consider naming the dropped join there and adding a test.fails cell next to the existing ones.
    2. Pin the split with a line added after the tail (MarkerKeptByItsLine.test.ts:447). Press Enter after hello in hello world and add a paragraph after the tail: here a concurrent center or h2 stays on world, while on main it goes to the added paragraph. No cell covers this; only the join is pinned. packages/lexical-y/AGENTS.md asks every fix to land with a regression test in regressions/, and the inline comment has a cell that fails on main and passes here.
    3. Pin the split counterpart of the concurrent-join outcome (MarkerKeptByItsLine.test.ts:863). With that same split and added line, B's Delete at the end of hello world now gives hello / worldadded / next (main: hello / world / addednext). This is the same "neither keeps both intents" class as the join cell, so a twin cell there would make a later change deliberate.

    <!-- codebunny-pub:1 k=13bdfd2bdbe4cb776b2a7af4036d66324c4a342927ff0ebb8cf67d19446c905c -->

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 10, 2026 10:41 UTC
    Approved Reviewer

    Thanks, this looks good to me. Keeping an old line marker only with the line that continues it fixes the composition and concurrent-alignment cases in the description. At this head, 32 cells in MarkerKeptByItsLine.test.ts fail on main and pass here, and the @lexical/y unit tests pass with gc off and on. The accepted limit is recorded in D118, y.md's Limits, the changeset and test.fails cells, as packages/lexical-y/AGENTS.md asks for an accepted limit.

    Two optional, non-blocking suggestions:

    1. Refresh the Before output in the Test plan. It still shows 24 failed | 88 passed | 24 expected fail (136) for MarkerKeptByItsLine.test.ts on main. At this head the file has 148 cells, and main gives 32 failed | 88 passed | 28 expected fail (148). AGENTS.md (Commits and Pull Requests) asks the Test plan for the real output of the command that was run.
    2. Consider a collab-y e2e check of the replaced-line composition (packages/lexical-website/docs/collaboration/y.md:1315-1319). The composition cells set the composition key with $setCompositionKey in jsdom. They show that the held node leaves the document, but not what a real input method does with characters composed after the collaborator's replacement arrives; y.md says only that the composition "ends without it". A spec under packages/lexical-playground/__tests__/e2e/ (run with pnpm run test-e2e-collab-y-chromium) would show where that input goes. In it, one client composes at the end of a line while the other moves the line's nodes into a quote, changes their text and adds a block after it. AGENTS.md (Testing Strategy) sends behaviour that needs a real browser's selection engine to the browser or e2e tiers rather than jsdom.

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

    potatowagon potatowagon approved these changes on Nov 10, 2026 18:06 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    zurfyx zurfyx
    Labels
    risk: low confidence: 72.1% 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: 50.3% (MEDIUM) · Higher = larger blast radius
    50.3%
    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: 72.1% · Lower = rushed or shallow review
    72.1%
    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: 14% · Safe to merge
    14%
    Repository