Commit b909ce6877 for handsontable.com

commit b909ce68771eede64dab721c1a30fbed9120d493
Author: Artur Mędrygał <artur.medrygal@handsontable.com>
Date:   Tue Nov 24 17:38:02 2026 +0100

    DEV-4190: Clear merge meta from the cells of an undone merge (#14444) (#14452)

    * DEV-4190: Clear merge meta from the cells of an undone merge

    * DEV-4190: Clear copyable on the top-left of a merge the undo restores

    * DEV-4190: Clear the inner merge's span on the redo of a merge over it

    * DEV-4190: Share one clipboard read helper across the page objects

    (cherry picked from commit 26e9034328aecbff63859be44db2655e2406b4b6)

diff --git a/handsontable/src/plugins/mergeCells/AGENTS.md b/handsontable/src/plugins/mergeCells/AGENTS.md
index 19ff98ec9e..8205bf8d32 100644
--- a/handsontable/src/plugins/mergeCells/AGENTS.md
+++ b/handsontable/src/plugins/mergeCells/AGENTS.md
@@ -309,10 +309,22 @@ hooks). Six rules keep it narrow:
   (`#clearCoveredFlagsOfCellsReleasedByStep()`): each captured merge carries its anchor rows and its
   `physicalColumns`, so the cells the other side covered and the restored side does not are known without
   reading a live merge's columns. Only the merges the step changed are walked, and a cell the restored side's
-  changed merges cover is skipped. A cell an unchanged merge covers is not looked at, so it may be cleaned and
+  changed merges cover is skipped, except the cell one of them is drawn from: a merge the undo puts back
+  inside a larger one it takes off (`mergeSelection()` over an older merge) is drawn from a cell the larger merge
+  covered, and `afterGetCellMeta` never writes `copyable` back on a top-left, so that cell loses `hidden` and
+  `copyable` and keeps its span keys. The redo of that step is the mirror: the cell the inner merge was drawn
+  from is covered by the outer one, and the hook never takes a span off a covered cell, so it loses its span
+  keys and keeps `hidden` and `copyable`. A cell an unchanged merge covers is not looked at, so it may be cleaned and
   `afterGetCellMeta` stores the flags again on the next read. Never build the released set from the live
   merges' visual columns. A guard that reads the live lookup was tried and dropped: no test needed it, and the
-  recorded sides already hold the answer. It does nothing
+  recorded sides already hold the answer. **This path does not wait for an own `hidden` or `spanned`**, as the
+  move paths do: the merge stored both through `setCellMeta()`, so on the undo of a merge the UndoRedo journal,
+  replayed before `restoreState()`, has already taken them back, while the `copyable: false`, `rowspan` and
+  `colspan` the hook wrote are in no journal. Gated on the marks, the undo of a merge left them all on the cells,
+  and a copy of the area dropped the covered cells' values. So each released cell loses `hidden`/`spanned` where
+  they are still own, and `copyable`, `rowspan` and `colspan` unless recorded (the `wasInMerge` argument of
+  `#clearCoveredFlagsOfTopLeftCell` and `#clearSpanKeysOfCell`). Pinned by `__tests__/undoMergeMeta.unit.js` and
+  `tests/e2e/merge-cells-undo-copy.spec.ts`. The cleanup does nothing
   without a recorded other side (no `context.other`), for a merge captured with no `physicalColumns`, or when
   the replay inserted or removed rows or columns (`context.reordered`): the recorded physical indexes are
   numbered like the grid before that replay. A row move's redo was already clean, because dropping the live merge cleans it by the
@@ -359,7 +371,9 @@ hooks). Six rules keep it narrow:
     `#settleMergesAfterAxisMove` (only while a row is trimmed), and the top and bottom of `restoreState()`. UndoRedo replays the cell meta journal before it restores plugin states, so the cleanup is
     not overwritten by a replayed `spanned`.
   - **It cleans only where `#clearSpanKeysOfCell` does** (an own `spanned`), so a cell that was never a top-left
-    is untouched whatever ends up in the diff, and a stale recording mostly misses a cleanup.
+    is untouched whatever ends up in the diff, and a stale recording mostly misses a cleanup. The released cells of
+    an undo step are the one exception: `#clearCoveredFlagsOfCellsReleasedByStep` passes `wasInMerge`, because the
+    journal has already taken `spanned` back there.
   - **An intermediate diff can clean a cell the final state draws from, and the next read puts the keys back.**
     UndoRedo restores the index maps, which fires the mapper diff against the merges that are not restored yet,
     and a row move runs that diff before `translateAfterAxisMove` replaces the anchors. `afterGetCellMeta`
diff --git a/handsontable/src/plugins/mergeCells/__tests__/undoMergeMeta.unit.js b/handsontable/src/plugins/mergeCells/__tests__/undoMergeMeta.unit.js
new file mode 100644
index 0000000000..b41769af7f
--- /dev/null
+++ b/handsontable/src/plugins/mergeCells/__tests__/undoMergeMeta.unit.js
@@ -0,0 +1,227 @@
+import Handsontable from 'handsontable';
+import { TEST_LICENSE_KEY } from '../../../../test/helpers/licenseKey';
+
+const MERGE_KEYS = ['hidden', 'copyable', 'spanned', 'rowspan', 'colspan'];
+
+/**
+ * A merge stores `hidden` and `spanned` through `setCellMeta()`, so the UndoRedo journal takes them back on undo.
+ * `afterGetCellMeta` stores `copyable: false`, `rowspan` and `colspan` on the same cells without a record, and the
+ * journal cannot see them. The undo of the merge must take those off too, or the cells keep a span nothing backs
+ * and a copy of the area drops the values of the cells the merge covered.
+ */
+describe('MergeCells cell meta after the undo of a merge', () => {
+  let container;
+  let hot;
+
+  beforeEach(() => {
+    container = document.createElement('div');
+    document.body.appendChild(container);
+  });
+
+  afterEach(() => {
+    hot?.destroy();
+    hot = null;
+    container.remove();
+  });
+
+  function createGrid(settings = {}) {
+    hot = new Handsontable(container, {
+      data: Handsontable.helper.createSpreadsheetData(6, 6),
+      mergeCells: true,
+      licenseKey: TEST_LICENSE_KEY,
+      ...settings,
+    });
+
+    return hot;
+  }
+
+  /**
+   * Reads every cell of a range, so `afterGetCellMeta` stores the merge keys on each one, the way a render does.
+   *
+   * @param {number[]} range The range as `[startRow, startColumn, endRow, endColumn]`.
+   */
+  function readMeta([startRow, startColumn, endRow, endColumn]) {
+    for (let row = startRow; row <= endRow; row++) {
+      for (let column = startColumn; column <= endColumn; column++) {
+        hot.getCellMeta(row, column);
+      }
+    }
+  }
+
+  /**
+   * Lists the merge keys stored on the cells of a range, read without the `afterGetCellMeta` hook.
+   *
+   * @param {number[]} range The range as `[startRow, startColumn, endRow, endColumn]`.
+   * @returns {string[]} Entries as `"row,column:key"`.
+   */
+  function storedMergeKeys([startRow, startColumn, endRow, endColumn]) {
+    const found = [];
+
+    for (let row = startRow; row <= endRow; row++) {
+      for (let column = startColumn; column <= endColumn; column++) {
+        const meta = hot._getMetaManager().getCellMetaIfExists(row, column);
+
+        MERGE_KEYS.forEach((key) => {
+          if (meta && Object.prototype.hasOwnProperty.call(meta, key)) {
+            found.push(`${row},${column}:${key}`);
+          }
+        });
+      }
+    }
+
+    return found;
+  }
+
+  it('takes the span and the covered flags off the cells', () => {
+    createGrid();
+
+    hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+    readMeta([1, 1, 2, 2]);
+    hot.getPlugin('undoRedo').undo();
+
+    expect(hot.getPlugin('mergeCells').mergedCellsCollection.mergedCells).toEqual([]);
+    expect(storedMergeKeys([1, 1, 2, 2])).toEqual([]);
+    expect(hot.getCellMeta(1, 1).rowspan).toBeUndefined();
+    expect(hot.getCellMeta(1, 1).colspan).toBeUndefined();
+    expect(hot.getCellMeta(2, 2).copyable).toBe(true);
+    expect(hot.getCopyableText(1, 1, 2, 2)).toBe('B2\tC2\nB3\tC3');
+  });
+
+  it('keeps the cells clean through a redo and a second undo', () => {
+    createGrid();
+
+    hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+    readMeta([1, 1, 2, 2]);
+    hot.getPlugin('undoRedo').undo();
+    hot.getPlugin('undoRedo').redo();
+    readMeta([1, 1, 2, 2]);
+
+    expect(hot.getCellMeta(1, 1).rowspan).toBe(2);
+    expect(hot.getCellMeta(2, 2).copyable).toBe(false);
+
+    hot.getPlugin('undoRedo').undo();
+
+    expect(storedMergeKeys([1, 1, 2, 2])).toEqual([]);
+    expect(hot.getCopyableText(1, 1, 2, 2)).toBe('B2\tC2\nB3\tC3');
+  });
+
+  it('leaves the flags of a merge the undo puts back', () => {
+    createGrid();
+
+    hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+    readMeta([1, 1, 2, 2]);
+    hot.selectCell(0, 0, 3, 3);
+    hot.getPlugin('mergeCells').mergeSelection();
+    readMeta([0, 0, 3, 3]);
+    // The render of the undo would run `afterGetCellMeta`, which writes the span keys of the restored merge again.
+    hot.suspendRender();
+    hot.getPlugin('undoRedo').undo();
+
+    // The journal put back the `spanned` mark of the restored merge, and the cleanup leaves it there.
+    expect(storedMergeKeys([1, 1, 1, 1])).toEqual(['1,1:spanned']);
+
+    hot.resumeRender();
+    readMeta([0, 0, 3, 3]);
+
+    expect(hot.getPlugin('mergeCells').mergedCellsCollection.mergedCells.map(({ row, col, rowspan, colspan }) => (
+      [row, col, rowspan, colspan]
+    ))).toEqual([[1, 1, 2, 2]]);
+    expect(hot.getCellMeta(1, 1).rowspan).toBe(2);
+    expect(hot.getCellMeta(1, 1).copyable).toBe(true);
+    expect(hot.getCellMeta(2, 2).copyable).toBe(false);
+    // The outer merge covered B2, and the inner merge it puts back is drawn from it.
+    expect(hot.getCopyableText(1, 1, 2, 2)).toBe('B2\t\n\t');
+    expect(storedMergeKeys([0, 0, 0, 3])).toEqual([]);
+    expect(storedMergeKeys([3, 0, 3, 3])).toEqual([]);
+    expect(hot.getCopyableText(0, 0, 0, 3)).toBe('A1\tB1\tC1\tD1');
+  });
+
+  it('takes the span off the cell the inner merge was drawn from on the redo of a merge over it', () => {
+    createGrid();
+
+    hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+    readMeta([1, 1, 2, 2]);
+    hot.selectCell(0, 0, 3, 3);
+    hot.getPlugin('mergeCells').mergeSelection();
+    hot.getPlugin('undoRedo').undo();
+    readMeta([0, 0, 3, 3]);
+    hot.getPlugin('undoRedo').redo();
+
+    expect(hot.getPlugin('mergeCells').mergedCellsCollection.mergedCells.map(({ row, col, rowspan, colspan }) => (
+      [row, col, rowspan, colspan]
+    ))).toEqual([[0, 0, 4, 4]]);
+    expect(storedMergeKeys([1, 1, 1, 1]).filter(entry => /rowspan|colspan|spanned/.test(entry))).toEqual([]);
+    expect(hot.getCellMeta(1, 1).rowspan).toBeUndefined();
+    expect(hot.getCellMeta(1, 1).colspan).toBeUndefined();
+    expect(hot.getCellMeta(1, 1).hidden).toBe(true);
+    expect(hot.getCellMeta(1, 1).copyable).toBe(false);
+  });
+
+  it('cleans the cell the restored merge is drawn from while its first row is trimmed', () => {
+    createGrid({ trimRows: true });
+
+    hot.getPlugin('mergeCells').merge(1, 1, 3, 2);
+    hot.getPlugin('trimRows').trimRow(1);
+    readMeta([0, 0, 4, 3]);
+    hot.selectCell(0, 0, 3, 3);
+    hot.getPlugin('mergeCells').mergeSelection();
+    readMeta([0, 0, 3, 3]);
+    hot.getPlugin('undoRedo').undo();
+
+    // Physical row 1 is trimmed, so the restored merge is drawn from physical row 2 (visual row 1).
+    const drawnFrom = hot._getMetaManager().getCellMetaIfExists(2, 1);
+
+    expect(drawnFrom && Object.prototype.hasOwnProperty.call(drawnFrom, 'hidden')).toBe(false);
+    expect(drawnFrom && Object.prototype.hasOwnProperty.call(drawnFrom, 'copyable')).toBe(false);
+    expect(hot.getCellMeta(1, 1).copyable).toBe(true);
+  });
+
+  it('takes the span and the covered flags off the cells on the redo of an unmerge', () => {
+    createGrid();
+
+    hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+    readMeta([1, 1, 2, 2]);
+    hot.getPlugin('mergeCells').unmerge(1, 1, 2, 2);
+    hot.getPlugin('undoRedo').undo();
+    readMeta([1, 1, 2, 2]);
+
+    expect(hot.getCellMeta(1, 1).rowspan).toBe(2);
+    expect(hot.getCellMeta(2, 2).copyable).toBe(false);
+
+    hot.getPlugin('undoRedo').redo();
+    // The merge emptied the cells it covered, and the unmerge does not bring their values back.
+    hot.setDataAtCell(2, 2, 'new');
+
+    expect(hot.getPlugin('mergeCells').mergedCellsCollection.mergedCells).toEqual([]);
+    expect(storedMergeKeys([1, 1, 2, 2])).toEqual([]);
+    expect(hot.getCopyableText(1, 1, 2, 2)).toBe('B2\t\n\tnew');
+  });
+
+  it('keeps a `rowspan` and a `colspan` the user set before the merge', () => {
+    createGrid();
+
+    hot.setCellMeta(1, 1, 'rowspan', 3);
+    hot.setCellMeta(1, 1, 'colspan', 4);
+    hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+    readMeta([1, 1, 2, 2]);
+    hot.getPlugin('undoRedo').undo();
+
+    // The keys stay on the cell. Their values are the merge's: `afterGetCellMeta` overwrote the user's values
+    // while the merge was drawn from the cell, a known limit that `AGENTS.md` describes.
+    expect(storedMergeKeys([1, 1, 1, 1])).toEqual(['1,1:rowspan', '1,1:colspan']);
+    expect(hot.getCellMeta(2, 2).copyable).toBe(true);
+  });
+
+  it('keeps a `copyable` the user set before the merge', () => {
+    createGrid();
+
+    hot.setCellMeta(2, 2, 'copyable', false);
+    hot.getPlugin('mergeCells').merge(1, 1, 2, 2);
+    readMeta([1, 1, 2, 2]);
+    hot.getPlugin('undoRedo').undo();
+
+    expect(hot.getCellMeta(2, 2).copyable).toBe(false);
+    expect(hot.getCellMeta(2, 1).copyable).toBe(true);
+    expect(hot.getCopyableText(1, 1, 2, 2)).toBe('B2\tC2\nB3\t');
+  });
+});
diff --git a/handsontable/src/plugins/mergeCells/mergeCells.ts b/handsontable/src/plugins/mergeCells/mergeCells.ts
index 917bb13a76..359a8965cb 100644
--- a/handsontable/src/plugins/mergeCells/mergeCells.ts
+++ b/handsontable/src/plugins/mergeCells/mergeCells.ts
@@ -2026,8 +2026,16 @@ export class MergeCells extends BasePlugin {
    * restored side does not. `restoreState()` runs after UndoRedo restored the index maps, so the visual columns
    * of a live merge name the wrong physical columns and a set built from them cannot see the cell a redo takes
    * out of a merge. The recorded merges carry their physical columns, so the two sides are compared by those.
-   * A cell the restored side's changed merges cover is left alone. One an unchanged merge covers may be
-   * cleaned, and `afterGetCellMeta` stores the flags again on the next read.
+   * A cell the restored side's changed merges cover keeps what they put on it. The cell one of them is drawn
+   * from loses `hidden` and `copyable` and keeps its span keys, because `afterGetCellMeta` never writes
+   * `copyable` back on a top-left. A covered cell a merge of the other side was drawn from loses its span keys
+   * and keeps its covered flags, because the hook never takes a span off a covered cell. One an unchanged merge
+   * covers may be cleaned, and `afterGetCellMeta` stores the flags again on the next read.
+   *
+   * The span keys go too, and neither removal waits for the `hidden` or `spanned` mark. The merge stored both
+   * marks through `setCellMeta()`, so on the undo of a merge the UndoRedo journal has already taken them back,
+   * while the `copyable`, `rowspan` and `colspan` the hook wrote are not in the journal. The recorded other side
+   * is the proof that a merge covered the cell. A recorded `copyable`, `rowspan` or `colspan` still stays.
    *
    * @param {Array} state The merges on the restored side of the step.
    * @param {Array} other The merges on the other side of the step.
@@ -2039,15 +2047,54 @@ export class MergeCells extends BasePlugin {
       return;
     }

-    const covered = this.#collectRecordedCoveredCells(state.filter(entry => !isMergeListed(other, entry)));
+    const restored = state.filter(entry => !isMergeListed(other, entry));
+    const covered = this.#collectRecordedCoveredCells(restored);
+    const restoredTopLefts = this.#collectRecordedTopLeftCells(restored);
+    const leftTopLefts = this.#collectRecordedTopLeftCells(left);

     this.#collectRecordedCoveredCells(left).forEach((key) => {
-      if (covered.has(key)) {
+      const isRestoredTopLeft = restoredTopLefts.has(key);
+      const isCovered = covered.has(key);
+      // A restored merge drawn from the cell keeps its span keys; one that covers it keeps its covered flags.
+      const clearsCoveredFlags = !isCovered || isRestoredTopLeft;
+      const clearsSpanKeys = !isRestoredTopLeft && (!isCovered || leftTopLefts.has(key));
+
+      if (!clearsCoveredFlags && !clearsSpanKeys) {
         return;
       }

-      this.#clearCoveredFlagsOfTopLeftCell(Math.trunc(key / DRAWN_CELL_COLUMN_STRIDE), key % DRAWN_CELL_COLUMN_STRIDE);
+      const physicalRow = Math.trunc(key / DRAWN_CELL_COLUMN_STRIDE);
+      const physicalColumn = key % DRAWN_CELL_COLUMN_STRIDE;
+
+      if (clearsCoveredFlags) {
+        this.#clearCoveredFlagsOfTopLeftCell(physicalRow, physicalColumn, true);
+      }
+
+      if (clearsSpanKeys) {
+        this.#clearSpanKeysOfCell(physicalRow, physicalColumn, true);
+      }
+    });
+  }
+
+  /**
+   * Collects the physical cell each recorded merge is drawn from (`#getTopLeftPhysicalRow()` in the anchor's
+   * column). A merge with no anchor, or with no visible top-left, is left out.
+   *
+   * @param {Array} entries The recorded merges.
+   * @returns {Set<number>} The cells, packed as `physicalRow * DRAWN_CELL_COLUMN_STRIDE + physicalColumn`.
+   */
+  #collectRecordedTopLeftCells(entries: readonly MergeStateEntry[]): Set<number> {
+    const cells = new Set<number>();
+
+    entries.forEach(({ anchor }) => {
+      const physicalRow = anchor === null ? null : this.#getTopLeftPhysicalRow(anchor);
+
+      if (anchor !== null && physicalRow !== null) {
+        cells.add((physicalRow * DRAWN_CELL_COLUMN_STRIDE) + anchor.physicalColumn);
+      }
     });
+
+    return cells;
   }

   /**
@@ -3312,18 +3359,25 @@ export class MergeCells extends BasePlugin {
    * applies it again on the next read.
    * The meta is removed through the meta manager, by physical index and without the remove-meta hooks.
    *
+   * A caller that knows from a recorded undo step that a merge covered the cell skips the `spanned` check: the
+   * UndoRedo journal takes `spanned` back before `restoreState()` runs, and it never held `rowspan` or `colspan`.
+   *
    * @param {number} physicalRow The physical row of the cell.
    * @param {number} physicalColumn The physical column of the cell.
+   * @param {boolean} [wasInMerge=false] `true` when a recorded undo step shows that a merge covered the cell.
    */
-  #clearSpanKeysOfCell(physicalRow: number, physicalColumn: number) {
+  #clearSpanKeysOfCell(physicalRow: number, physicalColumn: number, wasInMerge = false) {
     const metaManager = this.hot._getMetaManager();
     const storedMeta = metaManager.getCellMetaIfExists(physicalRow, physicalColumn);
+    const hasMark = !!storedMeta && hasOwnProperty(storedMeta, 'spanned');

-    if (!storedMeta || !hasOwnProperty(storedMeta, 'spanned')) {
+    if (!storedMeta || (!wasInMerge && !hasMark)) {
       return;
     }

-    metaManager.removeCellMeta(physicalRow, physicalColumn, 'spanned');
+    if (hasMark) {
+      metaManager.removeCellMeta(physicalRow, physicalColumn, 'spanned');
+    }

     ['rowspan', 'colspan'].forEach((key) => {
       if (!metaManager.getCellMetaKeyState(physicalRow, physicalColumn, key).hadOwn) {
@@ -3505,18 +3559,25 @@ export class MergeCells extends BasePlugin {
    * The meta is removed through the meta manager, by physical index and without the remove-meta hooks.
    * The check costs one meta lookup per merge and no lookup in the merge collection.
    *
+   * A caller that knows from a recorded undo step that a merge covered the cell skips the `hidden` check: the
+   * UndoRedo journal takes `hidden` back before `restoreState()` runs, and it never held `copyable`.
+   *
    * @param {number} physicalRow The physical row of the cell the merge is drawn from.
    * @param {number} physicalColumn The physical column of the cell the merge is drawn from.
+   * @param {boolean} [wasInMerge=false] `true` when a recorded undo step shows that a merge covered the cell.
    */
-  #clearCoveredFlagsOfTopLeftCell(physicalRow: number, physicalColumn: number) {
+  #clearCoveredFlagsOfTopLeftCell(physicalRow: number, physicalColumn: number, wasInMerge = false) {
     const metaManager = this.hot._getMetaManager();
     const storedMeta = metaManager.getCellMetaIfExists(physicalRow, physicalColumn);
+    const hasMark = !!storedMeta && hasOwnProperty(storedMeta, 'hidden');

-    if (!storedMeta || !hasOwnProperty(storedMeta, 'hidden')) {
+    if (!storedMeta || (!wasInMerge && !hasMark)) {
       return;
     }

-    metaManager.removeCellMeta(physicalRow, physicalColumn, 'hidden');
+    if (hasMark) {
+      metaManager.removeCellMeta(physicalRow, physicalColumn, 'hidden');
+    }

     // The merge stores `hidden` through `setCellMeta()`, but the hook writes `copyable` straight onto the stored
     // object and never records it. A recorded `copyable` is left alone (a recorded `true` was already overwritten by the hook).
diff --git a/handsontable/src/plugins/undoRedo/AGENTS.md b/handsontable/src/plugins/undoRedo/AGENTS.md
index 61e41dfdf6..b1a6e8ff30 100644
--- a/handsontable/src/plugins/undoRedo/AGENTS.md
+++ b/handsontable/src/plugins/undoRedo/AGENTS.md
@@ -202,6 +202,12 @@ is part of the undo, and a recorded step there would empty the redo stack the un
   compares states by identity to decide what a step changed; a fresh equal object makes every step look
   like it changed the plugin, and the restore then re-applies it on every undo.
 - **`restoreState()` must be hook-silent for what it re-applies** - the hooks fired when the user acted.
+- **`restoreState()` runs after the journal replay, so a cleanup there cannot key on meta the journal also
+  writes.** A key the plugin stored through `setCellMeta()` is already back to its value before the step when
+  `restoreState()` runs; a key a hook wrote straight onto the stored meta is in no journal and still there.
+  MergeCells gated its undo cleanup on its own `hidden`/`spanned` marks, which the journal had already removed,
+  and left `rowspan`, `colspan` and `copyable: false` on the cells of an undone merge. Key such a cleanup on the
+  recorded state (`context.other`) instead.
 - **Derived index maps are never captured** (`autoRowSize`, `autoColumnSize`, `stretchColumns`, the
   NestedHeaders widths, `Pagination`, `AsyncValues`, `*.columnMeta` - `DERIVED_INDEX_MAP_NAMES`). They are rebuilt
   from the rest. `AsyncValues` is there because it holds in-flight requests, which an undo must not bring back. Pagination is there because it recomputes its page map on every index cache update:
diff --git a/tests/e2e/merge-cells-undo-copy.spec.ts b/tests/e2e/merge-cells-undo-copy.spec.ts
new file mode 100644
index 0000000000..787b69b82e
--- /dev/null
+++ b/tests/e2e/merge-cells-undo-copy.spec.ts
@@ -0,0 +1,61 @@
+import { randomUUID } from 'node:crypto';
+import { test, expect } from '../fixtures/test';
+import { UndoGridPage } from '../fixtures/pages/UndoGridPage';
+
+test.use({ permissions: ['clipboard-read', 'clipboard-write'] });
+
+/**
+ * A merge marks the cells it covers as not copyable and gives its top-left cell a span. Once the
+ * merge is undone, the cells are plain cells again: a copy of the area holds every value, and the
+ * top-left cell reports no span. The clipboard outlives a test, so the last copied cell gets a value
+ * unique to the run first, and a copy that drops it cannot pass on an earlier run's text.
+ */
+test.describe('copy after the undo of a merge', () => {
+  let grid: UndoGridPage;
+
+  test.beforeEach(async ({ page, theme, bundle }) => {
+    grid = new UndoGridPage(page, theme, bundle);
+    await grid.goto();
+    await grid.initGrid({ mergeCells: true, contextMenu: true });
+  });
+
+  /**
+   * Gives C3 a value of this run, copies B2:C3 with the keyboard, and checks the clipboard and the
+   * cell meta of the area.
+   */
+  async function expectPlainCellsCopied(): Promise<void> {
+    const unique = randomUUID();
+
+    await grid.setCell(2, 2, unique);
+    await grid.copyWithKeyboard([1, 1, 2, 2]);
+
+    await expect.poll(() => grid.clipboardText()).toBe(`B2\tC2\nB3\t${unique}`);
+    expect(await grid.page.evaluate(() => {
+      const { rowspan, colspan } = window.hot.getCellMeta(1, 1);
+
+      return { rowspan, colspan, copyable: window.hot.getCellMeta(2, 2).copyable };
+    })).toEqual({ rowspan: undefined, colspan: undefined, copyable: true });
+  }
+
+  test('copies every value after Ctrl+M and Ctrl+Z', async () => {
+    await grid.mergeWithShortcut([1, 1, 2, 2]);
+    await expect.poll(() => grid.merges()).toEqual([[1, 1, 2, 2]]);
+
+    await grid.undoWithKeyboard();
+    await expect.poll(() => grid.merges()).toEqual([]);
+
+    await expectPlainCellsCopied();
+  });
+
+  test('copies every value after Merge cells from the context menu and Ctrl+Z', async ({ page }) => {
+    await page.evaluate(() => window.hot.selectCells([[1, 1, 2, 2]]));
+    await grid.openContextMenuOnCell(1, 1);
+    await grid.chooseContextMenuItem('Merge cells');
+    await expect.poll(() => grid.merges()).toEqual([[1, 1, 2, 2]]);
+
+    await grid.undoWithKeyboard();
+    await expect.poll(() => grid.merges()).toEqual([]);
+
+    await expectPlainCellsCopied();
+  });
+});
diff --git a/tests/fixtures/clipboard.ts b/tests/fixtures/clipboard.ts
new file mode 100644
index 0000000000..6788f9198b
--- /dev/null
+++ b/tests/fixtures/clipboard.ts
@@ -0,0 +1,16 @@
+import { type Page } from '@playwright/test';
+
+/**
+ * Clipboard access shared by page objects.
+ */
+
+/**
+ * Reads the text on the browser clipboard. The spec grants the `clipboard-read` permission
+ * (`test.use({ permissions: ['clipboard-read', 'clipboard-write'] })`).
+ *
+ * @param {Page} page The page whose clipboard is read.
+ * @returns {Promise<string>}
+ */
+export async function readClipboardText(page: Page): Promise<string> {
+  return page.evaluate(() => navigator.clipboard.readText());
+}
diff --git a/tests/fixtures/pages/FormulasShowFormulasPage.ts b/tests/fixtures/pages/FormulasShowFormulasPage.ts
index 23a249db2b..15e9555ca1 100644
--- a/tests/fixtures/pages/FormulasShowFormulasPage.ts
+++ b/tests/fixtures/pages/FormulasShowFormulasPage.ts
@@ -1,4 +1,5 @@
 import { type Page, type Locator, expect } from '@playwright/test';
+import { readClipboardText } from '../clipboard';
 import { awaitBundle } from '../bundle';
 import './windowTypes';

@@ -69,6 +70,6 @@ export class FormulasShowFormulasPage {

   /** Read the page clipboard (requires the `clipboard-read` permission). */
   async clipboardText(): Promise<string> {
-    return this.page.evaluate(() => navigator.clipboard.readText());
+    return readClipboardText(this.page);
   }
 }
diff --git a/tests/fixtures/pages/GridPage.ts b/tests/fixtures/pages/GridPage.ts
index ee85e22988..283c63c12c 100644
--- a/tests/fixtures/pages/GridPage.ts
+++ b/tests/fixtures/pages/GridPage.ts
@@ -1,4 +1,5 @@
 import { type Page, type Locator, expect } from '@playwright/test';
+import { readClipboardText } from '../clipboard';

 /**
  * Page Object for the Handsontable demo fixture.
@@ -123,7 +124,7 @@ export class GridPage {

   /** Read the page clipboard (requires clipboard-read permission). */
   async clipboardText(): Promise<string> {
-    return this.page.evaluate(() => navigator.clipboard.readText());
+    return readClipboardText(this.page);
   }

   /**
diff --git a/tests/fixtures/pages/TwoGridsPage.ts b/tests/fixtures/pages/TwoGridsPage.ts
index 1e43e23fc0..c86037a8bf 100644
--- a/tests/fixtures/pages/TwoGridsPage.ts
+++ b/tests/fixtures/pages/TwoGridsPage.ts
@@ -1,4 +1,5 @@
 import { type Page, type Locator, expect } from '@playwright/test';
+import { readClipboardText } from '../clipboard';
 import { awaitBundle } from '../bundle';

 /**
@@ -239,6 +240,6 @@ export class TwoGridsPage {
    * @returns {Promise<string>}
    */
   async clipboardText(): Promise<string> {
-    return this.page.evaluate(() => navigator.clipboard.readText());
+    return readClipboardText(this.page);
   }
 }
diff --git a/tests/fixtures/pages/UndoGridPage.ts b/tests/fixtures/pages/UndoGridPage.ts
index 8441e8e8b5..1ab3fbe71a 100644
--- a/tests/fixtures/pages/UndoGridPage.ts
+++ b/tests/fixtures/pages/UndoGridPage.ts
@@ -1,4 +1,5 @@
 import { type Page, type Locator, expect } from '@playwright/test';
+import { readClipboardText } from '../clipboard';
 import type { CellValue, FixtureSortConfig } from './windowTypes';
 import { dragFillHandle, dragResizeHandle } from '../gestures';
 import { awaitBundle } from '../bundle';
@@ -718,6 +719,24 @@ export class UndoGridPage {
     await this.page.keyboard.press('ControlOrMeta+z');
   }

+  /**
+   * Select a range through the API, then copy it with the keyboard shortcut: `Cmd`+`C` on macOS,
+   * `Ctrl`+`C` elsewhere.
+   */
+  async copyWithKeyboard(range: [number, number, number, number]): Promise<void> {
+    await this.page.evaluate((cellRange) => {
+      window.hot.selectCells([cellRange]);
+    }, range);
+    await this.page.keyboard.press('ControlOrMeta+c');
+  }
+
+  /**
+   * The text on the browser clipboard (needs the `clipboard-read` permission).
+   */
+  async clipboardText(): Promise<string> {
+    return readClipboardText(this.page);
+  }
+
   /**
    * The value of a cell, by its visual coordinates.
    */