Skip to content

[lexical-y][lexical-playground][lexical-website] Feature: Local persistence and edits that did not sync (@lexical/y/offline) - #9899

Merged
zurfyx merged 1 commit into
mainfrom
zurfyx/y-offline
Nov 13, 2026
Merged

zurfyx merged 1 commit into
mainfrom
zurfyx/y-offline

Conversation

@zurfyx

@zurfyx zurfyx commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Description

@lexical/y gives an app freeze() and describeUnsyncedEdits for a client whose room moved on, but nothing stores a Yjs 14 document on the device: y-indexeddb imports Yjs 13, and none keys by epoch or reports quota or damage. Edits that never reached a server live only in the tab.

This adds @lexical/y/offline, an experimental entry with two layers:

  • A local store on IndexedDB alone, with no new dependency (openYOfflineStore). A slot per document key and epoch holds a base (what the server is known to hold) and the updates since. Writes are incremental and compacted. Two tabs on one key keep each other's rows: each writing handle holds a Web Lock (navigator.locks by default) and writes the whole document as its first row, so its later rows build only on its own. A handle replaces or removes only the rows it wrote, or rows it loaded from a writer that is gone (a closed tab, an earlier page load). Storage failures come back as typed results, never throws: unavailable (also an open that does not answer within openTimeout), blocked, quota, corrupt (with the readable rows as salvage, and the slot's epoch), newer (a row a later release wrote: kept, never reported as damage), closed, limit and failed. Optional limits cap keys per group and bytes per key by refusing writes, never by evicting. store.keys() lists keys, so an app can clear by owner (another viewer at sign-in).

  • An offline session over any binding with binding, status and freeze() (attachYOfflineSession; a YCollabBinding is one, and an app with its own YBinding passes a freeze() over quiesce()). Stages are 'off', 'persist' and 'replay'. At 'persist' every edit is stored as it is made (persistEdits, default true). keep: 'unsynced' stores only while the server lacks edits and deletes them on markSynced(). writeDelay waits for updates to pause. One path serves every return:

    • a reconnect at the same epoch syncs;
    • a replaced or upgraded room (a new epoch) freezes the client's copy, captures it into the same store, and describes it block by block;
    • so does a copy that a closed tab left at another epoch, or that never synced;
    • an app that syncs before it binds passes the server's epoch to loadYOffline, which loads only the slot at that epoch for it to merge, so the live binding never meets a moved epoch at attach;
    • session.freeze() covers a "replaced" signal that names no new epoch.

    recoverYOfflineEdits feeds an Offline edits panel and, at 'replay', reapplies the blocks nobody else touched as one undo step, at most once across tabs: a slot left at another epoch becomes a capture in one transaction over both stores, so two tabs recovering at once make one capture. It deletes a capture with nothing left only once the fresh document's session reports no unsynced edits, so a replay that has not synced keeps its capture. A replay or a read that fails comes back as that capture's typed error, never a rejection.

The playground gets a "Collab Y Offline" mode with the panel and a "Simulate replaced" button, plus an e2e spec. y.md documents the layer. DECISIONS.md records D124 to D126.

Changeset

.changeset/lexical-y-offline.md (@lexical/y patch, [feature]).

Test plan

Before

$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline
No test files found, exiting with code 1

After

Unit tests run over an in-repo fake IndexedDB (with a fake Web Locks), gc off and on (LEXICAL_Y_GC=1). Each fault and regression test fails on the code before its fix:

  • OfflineFaults.test.ts injects a failure between two specific transactions:
    • a compaction while a confirmation is queued;
    • a merge that throws in the write queue;
    • a capture the store refuses after the freeze committed more;
    • a request callback that throws inside a transaction.
  • regressions/OfflineReviewFindings.test.ts covers what an independent review and the automated review found:
    • a sync landing while a keep: 'unsynced' write is in flight;
    • a second recovery deleting a capture whose replay has not synced;
    • a moved or adopting tab removing or moving a live tab's rows (four cases);
    • a capture put again counting its bytes twice;
    • a replay with the caret inside the block it replaces;
    • a replay that throws during recovery;
    • a replay whose update fails under a non-throwing onError;
    • recovery capturing a live tab's rows on every call;
    • a document loaded with nothing unsynced being stored as unsynced;
    • two tabs recovering the same stale slot at once, which replayed it twice;
    • a moved epoch's capture counted against bytesPerKey together with the rows it replaces;
    • a corrupt stale slot that failed recovery with no epoch to clear.
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineFaults.test.ts (4 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts (15 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineStore.test.ts (30 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineSession.test.ts (51 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineLayout3.test.ts (143 tests)
      Tests  243 passed (243)
$ pnpm exec vitest run --project unit packages/lexical-y           # and with LEXICAL_Y_GC=1
      Tests  25027 passed | 387 expected fail | 154 skipped (25568)
$ pnpm exec vitest run --project unit-size
      Tests  38 passed (38)
$ pnpm exec vitest run --project scripts-unit
      Tests  3694 passed (3694)
$ pnpm exec vitest run --project unit packages/lexical-playground
      Tests  396 passed (396)
$ pnpm run tsc && pnpm run flow
Found 0 errors

Browser tests run against Chromium's real IndexedDB and Web Locks (src/__tests__/browser/Offline.test.ts). They cover reopen, compaction, confirm, discard, adopt, two connections, claim-once, damage, a throwing callback, limits, and an upgrade from another connection. They also run a session end to end through a reload and a moved epoch, two tabs where the one whose epoch moved leaves the live one's rows, and two connections recovering one stale slot at once:

$ pnpm run test-browser                                            # Chromium
 Test Files  83 passed (83)
      Tests  1100 passed | 2 skipped (1102)

The collab Y e2e ran with pnpm run start:y:

$ pnpm run test-e2e-collab-y-chromium
  36 passed (43.7s)

I also checked the playground by hand in Chromium: online, then disconnected with an edit, then "Simulate replaced". The page reopened at epoch 2 with the edit reapplied, and the panel read "1 reapplied (undo to revert)".

Not exercised:

  • Firefox and WebKit browser runs. CI's default run is Chromium only; the extended suite (tests-extended.yml) runs the others;
  • a full quota on a real IndexedDB. Chromium's DevTools quota override did not make a write fail in Playwright's ephemeral context, so the fake covers quota.

@vercel

vercel Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
lexical Ready Ready Preview Nov 13, 2026 5:07pm UTC
lexical-playground Ready Ready Preview Nov 13, 2026 5:07pm UTC

Request Review

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

rootnode-bot Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

AI review status for this pull request.

Review status Updated
🟢 Reviewed (for maintainers only) Nov 13, 2026, 5:34 PM UTC

@pkg-pr-new

pkg-pr-new Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
lexical

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

@lexical/a11y

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

@lexical/clipboard

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

@lexical/code

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

@lexical/code-core

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

@lexical/code-prism

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

@lexical/code-shiki

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

@lexical/compiler

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

@lexical/devtools-core

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

@lexical/dragon

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

@lexical/eslint-plugin

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

@lexical/extension

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

@lexical/fast-check

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

@lexical/file

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

@lexical/hashtag

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

@lexical/headless

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

@lexical/history

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

@lexical/html

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

@lexical/internal

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

@lexical/link

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

@lexical/list

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

@lexical/mark

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

@lexical/markdown

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

@lexical/mdast

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

@lexical/offset

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

@lexical/overflow

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

@lexical/plain-text

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

@lexical/react

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

@lexical/rich-text

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

@lexical/selection

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

@lexical/table

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

@lexical/tailwind

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

@lexical/text

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

@lexical/utils

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

@lexical/y

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

@lexical/yjs

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

commit: cec038b

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for the thorough work here: the store's ownership rules, the write queue and the stage gating read well, and the fault tests pin down several queue races. One defect in the replay should be fixed before this lands; the rest are optional suggestions.

1. replayUnsyncedEdits throws when the caret is in a block it replaces

packages/lexical-y/src/internal/OfflineSession.ts:1177 swaps a changed block with existing.replace(made). Without includeChildren, LexicalNode.replace moves a selection point only when the point sits on the replaced element itself, so a caret in the block's text keeps pointing at the old text node. Garbage collection removes that node, and the update fails with updateEditor: selection has been lost because the previously selected nodes have been removed…. A sketch, on the fresh document after a capture that changed b1:

// $findBlock: any helper that finds the block with blockId 'b1'
editor.update(() => $findBlock('b1').getFirstDescendant().select(1, 1), {discrete: true});
replayUnsyncedEdits({binding, report}); // throws; nothing is applied

What follows from it:

  • recoverYOfflineEdits at stage 'replay' rejects instead of returning a YOfflineResult. By then claimCapture has already marked the capture claimed (:1335-1343), so the automatic replay never runs for that capture again.
  • With an editor onError that logs instead of throwing, the update is discarded but applied still lists the blocks, because they are pushed inside the update (:1209), and the panel reports them as reapplied.
  • It is easy to reach. The playground focuses the editor at the end of the document once it is active, so an offline edit to the last paragraph leaves the caret in the block the replay replaces. Clicking into the block you edited and then pressing Reapply does the same. Deleting a block with the caret in it works.

Suggested fix: when the selection is inside existing, move it into made (for example made.selectEnd() after the swap). Push to applied only once the update has committed. Have recoverYOfflineEdits return a failed replay as a typed error, not a rejection that leaves the capture claimed. packages/lexical-y/AGENTS.md asks every bug fix to land with a regression test in src/__tests__/unit/regressions/. Here that means a replay with a selection inside the replaced block, which no editor in the current tests has.

2. Optional: keep: 'unsynced' can store a fragment with no base

When an append fails, the queue puts its batch back unless a confirmation is queued (OfflineSession.ts:556-561). In 'unsynced' mode, markSynced() sets clearing and never sets confirmed (:644-651). So an append that fails while markSynced() runs (a full quota, say) comes back after the clear as a lone since row. loadYOffline then returns hasUnsyncedEdits: true, base: null, and a document made from that state reads empty until the next local edit replaces the row. A per-sync counter checked when an append fails would cover both modes.

3. Optional: result-typed calls that can still throw

describeYOfflineCapture rethrows any headless error other than read only (OfflineSession.ts:938-941), and recoverYOfflineEdits calls it without a catch. The playground wraps the call in try/catch, but the y.md sample (if (recovered.ok) showOfflineEditsPanel(...)) does not. Either return these failures per capture, or say in the JSDoc and in y.md that the call can throw.

4. Nit

packages/lexical-playground/__tests__/e2e/CollabYOffline.spec.mjs:14 mentions a stage capture; the stage is 'persist'.

Automated review (maintainer link)

zurfyx added a commit that referenced this pull request Nov 13, 2026
…stence and edits that did not sync (@lexical/y/offline)

## Description

`@lexical/y` gives an app `freeze()` and `describeUnsyncedEdits` for a client whose room moved on, but nothing stores a Yjs 14 document on the device: `y-indexeddb` imports Yjs 13, and none keys by epoch or reports quota or damage. Edits that never reached a server live only in the tab.

This adds `@lexical/y/offline`, an experimental entry with two layers:

- **A local store** on IndexedDB alone, with no new dependency (`openYOfflineStore`). A slot per document key and epoch holds a base (what the server is known to hold) and the updates since. Writes are incremental and compacted. Two tabs on one key keep each other's rows: each writing handle holds a Web Lock (`navigator.locks` by default) and writes the whole document as its first row, so its later rows build only on its own. A handle replaces or removes only the rows it wrote, or rows it loaded from a writer that is gone (a closed tab, an earlier page load). Storage failures come back as typed results, never throws: `unavailable` (also an open that does not answer within `openTimeout`), `blocked`, `quota`, `corrupt` (with the readable rows as salvage), `closed`, `limit` and `failed`. Optional `limits` cap keys per group and bytes per key by refusing writes, never by evicting. `store.keys()` lists keys, so an app can clear by owner (another viewer at sign-in).
- **An offline session** over any binding with `binding`, `status` and `freeze()` (`attachYOfflineSession`; a `YCollabBinding` is one, and an app with its own `YBinding` passes a `freeze()` over `quiesce()`). Stages are `'off'`, `'persist'` and `'replay'`. At `'persist'` every edit is stored as it is made (`persistEdits`, default true). `keep: 'unsynced'` stores only while the server lacks edits and deletes them on `markSynced()`. `writeDelay` waits for updates to pause. One path serves every return:
  - a reconnect at the same epoch syncs;
  - a replaced or upgraded room (a new epoch) freezes the client's copy, captures it into the same store, and describes it block by block;
  - so does a copy that a closed tab left at another epoch, or that never synced.

  `recoverYOfflineEdits` feeds an Offline edits panel and, at `'replay'`, reapplies the blocks nobody else touched as one undo step, at most once across tabs. It deletes a capture with nothing left only once the fresh document's `session` reports no unsynced edits, so a replay that has not synced keeps its capture. A replay or a read that fails comes back as that capture's typed error, never a rejection.

The playground gets a "Collab Y Offline" mode with the panel and a "Simulate replaced" button, plus an e2e spec. y.md documents the layer. DECISIONS.md records D124 to D126.

## Backport

This is #9899 on the pre-layout-4 pin (#9895: e2836f0 plus #9883, #9887, #9888 and the #9891 setup API), for apps still on layout 3. The source of the offline layer is the same as in #9899. The differences are:
- the entry is registered without the `3to4` lines this base lacks (package.json `exports`, tsconfig paths, `.flowconfig`, `Source.test.ts`);
- `OfflineLayout3.test.ts` is left out: it imports the `3to4` step. On this base the session tests already bind, edit, persist, capture and replay layout 3 documents, and "below the floor" means layout 2.

## Changeset

`.changeset/lexical-y-offline.md` (`@lexical/y` patch, `[feature]`).

## Test plan

### Before

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline
No test files found, exiting with code 1
```

### After

On this base, with gc off and on (`LEXICAL_Y_GC=1`):

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts
      Tests  90 passed (90)
$ pnpm exec vitest run --project unit packages/lexical-y
      Tests  24502 passed | 388 expected fail | 156 skipped (25046)
$ pnpm exec vitest run --project unit-size
      Tests  32 passed (32)
$ pnpm exec vitest run --project scripts-unit
      Tests  3677 passed (3677)
$ pnpm exec vitest run --project unit packages/lexical-playground
      Tests  396 passed (396)
$ pnpm run tsc && pnpm run flow
Found 0 errors
```

The 90 tests break down as 30 store, 47 session, 4 fault and 9 regression tests. The browser tests and the collab Y e2e ran on #9899 (Chromium: browser 1099 passed, e2e 36/36). They were not rerun on this base.

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This looks good, and thanks for the quick turnaround on the earlier review. A replay now moves the caret out of a block it replaces instead of failing Lexical's selection invariant, and a replay that throws releases its claim. The new cases in packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts cover both. The suggestions below are optional and non-blocking.

Optional suggestions

  1. Release the claim after a 'not-written' replay (packages/lexical-y/src/internal/OfflineSession.ts, around line 1410). When an editor's onError does not rethrow, a failed update comes back as 'not-written', but the capture stays claimed, so later recoverYOfflineEdits calls never replay it automatically. Reapply still works. Releasing the claim when nothing was applied, as the catch just below does, would cover this. A regression test with a node transform that throws and an onError that records would pin it, following packages/lexical-y/AGENTS.md, which asks for a test in src/__tests__/unit/regressions/ with every fix.
  2. Don't capture a live tab's rows again (OfflineSession.ts, step 1 of recoverYOfflineEdits, around line 1373). discard() correctly keeps the rows of a tab still open at the old epoch, but that means every later call captures them again: three calls made three captures in a quick test over the fake IndexedDB. The playground calls recover() after every Dismiss and Reapply, so a dismissed entry comes back. Capturing only the rows whose writer is gone would leave the rest for that tab's own capture. It would also make the "captured twice" sentence in packages/lexical-website/docs/collaboration/y.md (Limits of the offline layer) accurate.
  3. Store a clean loaded document's first row as a base (OfflineSession.ts, line 375). For a document loaded with nothing unsynced, the whole-document first row is a since row, so the next offline reload reports hasUnsyncedEdits: true with no edit and keeps another full copy until a sync. When loaded.hasUnsyncedEdits is false, the document equals the base, so slot.confirm(state) would keep the "first row is the whole document" property without that side effect.

The rest I checked holds up. The Flow declarations match the TypeScript exports, the changeset follows CONTRIBUTING.md, and the tree-shaking test keeps nothing from the new entry.

Automated review (maintainer link)

zurfyx added a commit that referenced this pull request Nov 13, 2026
…ind load and freeze(), and its tests on layout 3 documents

## Description

This follows the offline backport on the pre-layout-4 pin (#9895). It brings the branch level with #9899's head a023079. It also adds what this branch was missing: tests of the offline layer on layout 3 documents, the layout this release writes.

From #9899 (the offline source files are byte-identical to it):
- `loadYOffline({store, key, epoch})`: for an app that syncs before it binds, load only the slot at the server's epoch, to merge into the server's document. Slots at other epochs are left for `recoverYOfflineEdits` to capture, so the live binding never meets a moved epoch at attach.
- `session.freeze()`: for a "replaced" signal that names no new epoch. It freezes the binding, captures what it holds into the store, and ends the session.
- From the automated review:
  - a replay whose editor update failed under a non-throwing `onError` releases the capture's claim;
  - recovery captures only the stale rows whose tab is gone (`slot.load({writers: 'gone'})`);
  - a document loaded with nothing unsynced is stored as a base.

New here: `OfflineLayout3Native.test.ts` replaces the `OfflineLayout3.test.ts` that #9899 has, which needs the `3to4` step. It builds every state at this release's layout and imports no `3to4`. It covers:
- the layout 3 outputs of the 2to3 golden fixtures (21);
- the 71 layout 3 states that later builds' 3to4 golden fixtures start from, copied as data into `golden/offline-layout3-states.json`;
- every catalog node shape, with and without block ids.

Each fixture runs with gc off and on, through:
- the store returning the bytes it was given;
- an editable binding whose edits persist and survive a reload;
- the same-epoch merge into the room on sync;
- a moved epoch that freezes and captures, described against the new room;
- recovery into a fresh document: the added block is replayed with block ids, and listed by position without them;
- for the 2to3 fixtures, their layout 1 and 2 inputs as a base below the floor: gone without `migrate`, read with it.

## Test plan

### Before

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/OfflineLayout3Native.test.ts
No test files found, exiting with code 1
```

### After

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts   # and with LEXICAL_Y_GC=1
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineFaults.test.ts (4 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts (12 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineStore.test.ts (30 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineSession.test.ts (51 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineLayout3Native.test.ts (429 tests)
      Tests  526 passed (526)
$ pnpm exec vitest run --project unit packages/lexical-y           # and with LEXICAL_Y_GC=1
      Tests  24938 passed | 388 expected fail | 156 skipped (25482)
$ pnpm exec vitest run --project unit-size
      Tests  32 passed (32)
$ pnpm exec vitest run --project scripts-unit
      Tests  3677 passed (3677)
$ pnpm run tsc && pnpm run flow
Found 0 errors
```

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks, this looks good. @lexical/y/offline is cleanly layered (typed store results, epochs, writer locks, rollout stages), y.md and DECISIONS.md (D124 to D126) explain the model, and the earlier review findings come with regression cases. Everything below is optional and non-blocking.

Suggestions (optional)

  1. Two tabs recovering the same stale slot can replay it twice (packages/lexical-y/src/internal/OfflineSession.ts, lines 1426-1453). Turning a slot left at another epoch into a capture takes three separate IndexedDB transactions: load the gone writers' rows, putCapture with a new random id, then discard. Two tabs that recover at the same moment can both read the slot before either deletes it, so it becomes two captures; each tab then claims one and replays the same blocks before the documents sync. Over the PR's own fake IndexedDB this ends with block b1 reading one, mineone, mine in both documents. Doing that step in one readwrite transaction across both object stores (querying the live writers just before it), or under a per-key Web Lock, would keep the "at most once across tabs" guarantee that D124 and y.md state.
  2. limits.bytesPerKey counts the rows a capture replaces (packages/lexical-y/src/internal/OfflineStore.ts, lines 798-815). The capture is checked while the slot's rows are still counted, and both callers put the capture before discarding those rows, so a key needs roughly three documents of room (rows, capture state, base). With bytesPerKey at 2.5x a document, serverEpoch returned saved with code: 'limit', and every later recoverYOfflineEdits returned the same error: the edits stay stored but are never shown or replayed. Checking the capture with those rows as removed (in one transaction), or documenting the headroom bytesPerKey needs, would fix it.
  3. A corrupt slot at another epoch fails the whole recovery (OfflineSession.ts, lines 1427-1431). Its corrupt result becomes the call's result, so healthy captures of the key are not shown either, and YOfflineError has no epoch for the store.clear(key, {epoch, captures: false}) that y.md's error table recommends. Skipping and reporting that slot, or adding epoch to the error, would let an app act on it.
  4. A row of a newer format reads as corrupt (OfflineStore.ts, line 367). isRow accepts only v === ROW_VERSION, and the advice for corrupt is to clear the slot, so a tab still on this release that meets a future row format would be told to delete it. A distinct, non-destructive outcome for v > ROW_VERSION is cheap to add now, before old clients exist.
  5. Tests. A case for each of the above would pin the fixes; the package's AGENTS.md asks for regression tests under src/__tests__/unit/regressions/. Nit: OfflineSession.test.ts, OfflineFaults.test.ts and regressions/OfflineReviewFindings.test.ts build headless editors only, so the repository AGENTS.md's // @vitest-environment node applies to them as it does to OfflineStore.test.ts.
  6. Playground nit. collab-y-offline-status is a role="status" live region (packages/lexical-playground/src/collaborationYOffline.tsx, line 500) whose text flips between "edits waiting to sync" and "synced" each time typing pauses, so a screen reader repeats it while the user types.

The changeset ('@lexical/y': patch, [feature]) follows CONTRIBUTING.md.

Automated review (maintainer link)

…stence and edits that did not sync (@lexical/y/offline)

## Description

`@lexical/y` gives an app `freeze()` and `describeUnsyncedEdits` for a client whose room moved on, but nothing stores a Yjs 14 document on the device: `y-indexeddb` imports Yjs 13, and none keys by epoch or reports quota or damage. Edits that never reached a server live only in the tab.

This adds `@lexical/y/offline`, an experimental entry with two layers:

- **A local store** on IndexedDB alone, with no new dependency (`openYOfflineStore`). A slot per document key and epoch holds a base (what the server is known to hold) and the updates since. Writes are incremental and compacted. Two tabs on one key keep each other's rows: each writing handle holds a Web Lock (`navigator.locks` by default) and writes the whole document as its first row, so its later rows build only on its own. A handle replaces or removes only the rows it wrote, or rows it loaded from a writer that is gone (a closed tab, an earlier page load). Storage failures come back as typed results, never throws: `unavailable` (also an open that does not answer within `openTimeout`), `blocked`, `quota`, `corrupt` (with the readable rows as salvage, and the slot's epoch), `newer` (a row a later release wrote: kept, never reported as damage), `closed`, `limit` and `failed`. Optional `limits` cap keys per group and bytes per key by refusing writes, never by evicting. `store.keys()` lists keys, so an app can clear by owner (another viewer at sign-in).
- **An offline session** over any binding with `binding`, `status` and `freeze()` (`attachYOfflineSession`; a `YCollabBinding` is one, and an app with its own `YBinding` passes a `freeze()` over `quiesce()`). Stages are `'off'`, `'persist'` and `'replay'`. At `'persist'` every edit is stored as it is made (`persistEdits`, default true). `keep: 'unsynced'` stores only while the server lacks edits and deletes them on `markSynced()`. `writeDelay` waits for updates to pause. One path serves every return:
  - a reconnect at the same epoch syncs;
  - a replaced or upgraded room (a new epoch) freezes the client's copy, captures it into the same store, and describes it block by block;
  - so does a copy that a closed tab left at another epoch, or that never synced;
  - an app that syncs before it binds passes the server's epoch to `loadYOffline`, which loads only the slot at that epoch for it to merge, so the live binding never meets a moved epoch at attach;
  - `session.freeze()` covers a "replaced" signal that names no new epoch.

  `recoverYOfflineEdits` feeds an Offline edits panel and, at `'replay'`, reapplies the blocks nobody else touched as one undo step, at most once across tabs: a slot left at another epoch becomes a capture in one transaction over both stores, so two tabs recovering at once make one capture. It deletes a capture with nothing left only once the fresh document's `session` reports no unsynced edits, so a replay that has not synced keeps its capture. A replay or a read that fails comes back as that capture's typed error, never a rejection.

The playground gets a "Collab Y Offline" mode with the panel and a "Simulate replaced" button, plus an e2e spec. y.md documents the layer. DECISIONS.md records D124 to D126.

## Changeset

`.changeset/lexical-y-offline.md` (`@lexical/y` patch, `[feature]`).

## Test plan

### Before

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline
No test files found, exiting with code 1
```

### After

Unit tests run over an in-repo fake IndexedDB (with a fake Web Locks), gc off and on (`LEXICAL_Y_GC=1`). Each fault and regression test fails on the code before its fix:
- `OfflineFaults.test.ts` injects a failure between two specific transactions:
  - a compaction while a confirmation is queued;
  - a merge that throws in the write queue;
  - a capture the store refuses after the freeze committed more;
  - a request callback that throws inside a transaction.
- `regressions/OfflineReviewFindings.test.ts` covers what an independent review and the automated review found:
  - a sync landing while a `keep: 'unsynced'` write is in flight;
  - a second recovery deleting a capture whose replay has not synced;
  - a moved or adopting tab removing or moving a live tab's rows (four cases);
  - a capture put again counting its bytes twice;
  - a replay with the caret inside the block it replaces;
  - a replay that throws during recovery;
  - a replay whose update fails under a non-throwing onError;
  - recovery capturing a live tab's rows on every call;
  - a document loaded with nothing unsynced being stored as unsynced;
  - two tabs recovering the same stale slot at once, which replayed it twice;
  - a moved epoch's capture counted against `bytesPerKey` together with the rows it replaces;
  - a corrupt stale slot that failed recovery with no epoch to clear.

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineFaults.test.ts (4 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts (15 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineStore.test.ts (30 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineSession.test.ts (51 tests)
 ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineLayout3.test.ts (143 tests)
      Tests  243 passed (243)
$ pnpm exec vitest run --project unit packages/lexical-y           # and with LEXICAL_Y_GC=1
      Tests  25027 passed | 387 expected fail | 154 skipped (25568)
$ pnpm exec vitest run --project unit-size
      Tests  38 passed (38)
$ pnpm exec vitest run --project scripts-unit
      Tests  3694 passed (3694)
$ pnpm exec vitest run --project unit packages/lexical-playground
      Tests  396 passed (396)
$ pnpm run tsc && pnpm run flow
Found 0 errors
```

Browser tests run against Chromium's real IndexedDB and Web Locks (`src/__tests__/browser/Offline.test.ts`). They cover reopen, compaction, confirm, discard, adopt, two connections, claim-once, damage, a throwing callback, limits, and an upgrade from another connection. They also run a session end to end through a reload and a moved epoch, two tabs where the one whose epoch moved leaves the live one's rows, and two connections recovering one stale slot at once:

```
$ pnpm run test-browser                                            # Chromium
 Test Files  83 passed (83)
      Tests  1100 passed | 2 skipped (1102)
```

The collab Y e2e ran with `pnpm run start:y`:

```
$ pnpm run test-e2e-collab-y-chromium
  36 passed (43.7s)
```

I also checked the playground by hand in Chromium: online, then disconnected with an edit, then "Simulate replaced". The page reopened at epoch 2 with the edit reapplied, and the panel read "1 reapplied (undo to revert)".

Not exercised:
- Firefox and WebKit browser runs. CI's default run is Chromium only; the extended suite (`tests-extended.yml`) runs the others;
- a full quota on a real IndexedDB. Chromium's DevTools quota override did not make a write fail in Playwright's ephemeral context, so the fake covers `quota`.
zurfyx added a commit that referenced this pull request Nov 13, 2026
… layer recovers a stale slot once across tabs, keeps rows a newer release wrote, and counts a capture's room without the rows it replaces

## Description

This brings the offline backport on the pre-layout-4 pin (#9895) level with #9899's head cec038b, which carries the fixes from its last automated review. The offline source files are byte-identical to that head.

- **One capture per stale slot.** Two tabs recovering the same stale slot at once made two captures, and each tab replayed one, so the block was applied twice. The slot now becomes a capture in one readwrite transaction over both object stores (`store.captureSlot`), so the second tab finds no rows.
- **Moved epoch in one transaction.** A moved epoch's capture goes in through `slot.moveIntoCapture`: one transaction that deletes the slot's own rows and puts the capture. Its size is checked against `limits.bytesPerKey` with those rows already counted as removed, so a key no longer needs room for three documents.
- **Epoch on errors.** `YOfflineError.epoch` names a slot's epoch on `corrupt` and `newer`, so the app can clear that slot and recover again.
- **Newer rows.** A row a newer release wrote reads as `newer` and is kept, never `corrupt` (whose advice is to clear the slot).
- **`markSynced` docs:** it means persisted by the copy a reload or replace is seeded from (for a connector product, its save, not the relay's acknowledgement), with nothing newer in the document.
- **Playground:** the status line is no longer a live region; the problem line is.

The new store and slot methods are optional, so stores an app implements itself keep compiling, and the session falls back for them.

## Test plan

### Before

The new regressions fail on the code before this commit: two tabs recovering one stale slot apply the block twice (`one, mineone, mine`), and a capture with 2.5 documents of room returns `limit`.

### After

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts   # and with LEXICAL_Y_GC=1
      Tests  529 passed (529)
$ pnpm exec vitest run --project unit packages/lexical-y           # and with LEXICAL_Y_GC=1
      Tests  24941 passed | 388 expected fail | 156 skipped (25485)
$ pnpm exec vitest run --project unit-size
      Tests  32 passed (32)
$ pnpm exec vitest run --project scripts-unit
      Tests  3677 passed (3677)
$ pnpm run tsc && pnpm run flow
Found 0 errors
```

The browser tests and the collab Y e2e ran on #9899 cec038b (Chromium: browser 1,100 passed, offline 9/9, e2e 36/36). They were not rerun on this base.

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This looks good to me. Thanks for the thorough tests and docs. @lexical/y/offline is additive and opt-in, its TypeScript and Flow declarations match, and the store, session and replay behave as the new y.md section describes, including the playground's Collab Y Offline mode at both the persist and replay stages. The one suggestion below is optional and non-blocking.

Optional: clear the writeDelay timer when the epoch moves (packages/lexical-y/src/internal/OfflineSession.ts, in moveOn, line 797)

moveOn stops the listeners and awaits this.writing, but a pending writeDelay timer keeps running. If that timer fires while moveIntoCapture is running, drain() appends the queued batch after moveIntoCapture has chosen the rows to delete. One since row is left at the old epoch, and slot.close() releases its lock.

The next recoverYOfflineEdits captures that lone delta row (base: null). Its report comes back 'failed' on every call, so the panel keeps an entry that cannot be compared until the user dismisses it. No edit is lost: the real edit is in the first capture.

With writeDelay: 8, an epoch that moves 0 or 4–7 ms after the last edit leaves the row behind. Clearing the timer right after this.stop() avoids it at every timing, and OfflineSession.test.ts and OfflineFaults.test.ts still pass with the change:

this.isEnded = true;
this.stop();
if (this.timer !== null) {
  clearTimeout(this.timer);
  this.timer = null;
}

The queued batch is still written on the failure path, which calls flush(). If you take this, packages/lexical-y/AGENTS.md asks for a regression test in src/__tests__/unit/regressions/: for example, move the epoch with writeDelay set and assert that store.slots(key) is empty afterwards.

Automated review (maintainer link)

// Read after the freeze: it commits what the editor still held.
const wasUnsynced = this.unsynced;
this.isEnded = true;
this.stop();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Optional: a pending writeDelay timer is not cleared here. If it fires while moveIntoCapture runs, drain() appends the queued batch after the rows to delete were chosen. One since row is then left at the old epoch, and the next recoverYOfflineEdits turns it into a capture (base: null) whose report is 'failed' on every call. With writeDelay: 8 it happens when the epoch moves 0 or 4–7 ms after the last edit; clearing the timer here avoids it at every timing:

Suggested change
this.stop();
this.stop();
if (this.timer !== null) {
clearTimeout(this.timer);
this.timer = null;
}

The queued batch is still stored on the failure path, which calls flush().

@zurfyx
zurfyx added this pull request to the merge queue Nov 13, 2026
zurfyx added a commit that referenced this pull request Nov 13, 2026
… longer runs while a moved epoch captures the document

## Description

`attachYOfflineSession` with `writeDelay` holds updates in a timer until typing pauses. When the epoch moved (`serverEpoch` with another epoch, or `freeze()`) while that timer was pending, the timer kept running. If it fired while the session moved its rows into the capture, it appended the queued batch after the rows to delete had been chosen. That left one delta row at the old epoch, and its writer lock was released. The next `recoverYOfflineEdits` turned that row into a capture with no base, whose report came back `'failed'` on every call, until the user dismissed it from the panel. No edit was lost: the real edit was in the first capture.

The session now clears the pending timer as soon as the epoch moves. What the timer held is in the capture; on the failure path, `flush()` still stores it.

Found by the automated review of #9899. This is the same fix as its follow-up on main, on the pre-layout-4 pin (#9895).

## Test plan

### Before

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts
   × 13. an epoch that moves 3 ms after an edit under writeDelay leaves no row behind
   × 13. an epoch that moves 4 ms after an edit under writeDelay leaves no row behind
   × 13. an epoch that moves 5 ms after an edit under writeDelay leaves no row behind
   × 13. an epoch that moves 6 ms after an edit under writeDelay leaves no row behind
      Tests  4 failed | 20 passed (24)
```

### After

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts   # and with LEXICAL_Y_GC=1
      Tests  538 passed (538)
```
Merged via the queue into main with commit 5c9ada0 Nov 13, 2026
77 checks passed
zurfyx added a commit that referenced this pull request Nov 13, 2026
…the document's rows into its capture

## Description

When the epoch moved (`serverEpoch` with another epoch, or `freeze()`), the session moved the slot's rows into the capture in one transaction. Two writes could still run meanwhile:
- a pending `writeDelay` timer;
- a `flush()` the app called during the move. The docs ask apps to call `flush()` on `pagehide`, so a page event during a reconnect can do this.

Either one stored the queued batch after the rows to delete had been chosen, and the session then released its writer lock. That left one delta row at the old epoch. The next `recoverYOfflineEdits` turned it into a capture with no base, whose report came back `'failed'` on every call until the user dismissed it. No edit was lost: the real edit was in the first capture.

The session now clears the pending timer and holds its write queue for the length of the move: `drain()` and the re-run in `flush()` stop while a move is under way. What was queued is in the capture. On the failure paths, the hold is released before `flush()` stores what was queued.

Found by the automated reviews of #9899 and of this pull request.

## Changeset

None: `@lexical/y/offline` is unreleased, and its pending changeset (`.changeset/lexical-y-offline.md`) covers it.

## Test plan

### Before

Both regressions are deterministic: a slot stand-in holds the move open after the rows are chosen, while the timer fires (13) or the app calls `flush()` (14).

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts
   × 13. a writeDelay timer pending when the epoch moves does not run during the move
   × 14. a flush() called during the move writes nothing the move then leaves behind
      Tests  2 failed | 15 passed (17)
```

With only the timer cleared (this pull request's first head), case 14 still fails.

### After

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts   # and with LEXICAL_Y_GC=1
      Tests  245 passed (245)
$ pnpm run tsc
```
zurfyx added a commit that referenced this pull request Nov 13, 2026
…the document's rows into its capture

## Description

When the epoch moved (`serverEpoch` with another epoch, or `freeze()`), the session moved the slot's rows into the capture in one transaction. Two writes could still run meanwhile:
- a pending `writeDelay` timer;
- a `flush()` the app called during the move. The docs ask apps to call `flush()` on `pagehide`, so a page event during a reconnect can do this.

Either one stored the queued batch after the rows to delete had been chosen, and the session then released its writer lock. That left one delta row at the old epoch. The next `recoverYOfflineEdits` turned it into a capture with no base, whose report came back `'failed'` on every call until the user dismissed it. No edit was lost: the real edit was in the first capture.

The session now clears the pending timer and holds its write queue for the length of the move: `drain()` and the queue's re-run stop while a move is under way.
- What was queued is in the capture. On the failure paths, the hold is released before the session stores what was queued.
- The hold is released in a `finally`, so a store of the app's own that throws cannot leave it held.
- A `flush()` the app calls during the move resolves after the move, as its contract says ("once everything queued so far is stored, or failed to be"), not at once.

Found by the automated reviews of #9899 and of this pull request.

Besides cases 13 and 14, three tests in `OfflineFaults.test.ts` pin the rest:
- a refused capture with `writeDelay`, whose batch reaches the old slot only through the failure path's release;
- a `flush()` during a refused move, which resolves only once that batch is stored;
- a store that throws from `moveIntoCapture`, after which `flush()` still stores the batch.

Each fails with its line of the fix removed.

## Changeset

None: `@lexical/y/offline` is unreleased, and its pending changeset (`.changeset/lexical-y-offline.md`) covers it.

## Test plan

### Before

Both regressions are deterministic: a slot stand-in holds the move open after the rows are chosen, while the timer fires (13) or the app calls `flush()` (14).

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts
   × 13. a writeDelay timer pending when the epoch moves does not run during the move
   × 14. a flush() called during the move writes nothing the move then leaves behind
      Tests  2 failed | 15 passed (17)
```

With only the timer cleared (this pull request's first head), case 14 still fails.

### After

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts   # and with LEXICAL_Y_GC=1
      Tests  249 passed (249)
$ pnpm run tsc
```
@potatowagon potatowagon mentioned this pull request Dec 2, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — cec038b3 Deployed Nov 13, 2026 by vercel[bot]
Preview – lexical-playground — cec038b3 Deployed Nov 13, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant