Skip to content

Commit 1647fb3

Browse files
fix(grid): an earlier save's Undo right after a newer save keeps the newer row on screen (#36064)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuVwX4pUdM1qvNLSqRZNSvv3)_ Fixes #35999 Clause-②: no Metadata-protocol: none Skills-docs: none repo:objectstack#1 · os-sales · session_01L6bhgW85kwjGaz7HqsmEuv ## 维护者速读 - 用户能看到什么变化:列表里先后改了同一行的两个单元格,随即撤销较早那一次时,这一行不再退回最初读到的旧值,较新那次修改留在屏幕上。 - 为什么做:这是列表单元格自动保存与撤销那一组工作里的一处时序缺陷,它也让界面测试在无关的 PR 上偶尔变红。 - 出错会怎样:只有显示错,服务器上的数据一直是对的,下次刷新列表就恢复;改动可以直接撤回。 - 要你做什么:无。 ## What changes A select-first grid draws an Undo's answer over the row as the grid shows it now. `currentRowOf` reads that row from `rowPatchesRef`. The ref was mirrored from the `rowPatches` state by a passive `useEffect`, and the save's `setRowPatches` runs after an `await`, so it is a default-lane update. Its effects are therefore scheduled after the commit instead of inside it. That leaves a window in which the newer save is already in the DOM while the ref still holds the earlier save's patch. An Undo of the earlier save inside that window: 1. read the stale patch row (old name, the earlier save's amount); 2. failed the `held.row === row` check in `writeRowInPlace` against the real state, so it re-based the new patch onto that stale row; 3. `patchedRowOf` rejected a patch whose `base` is not the loaded row, so the grid drew the row as first read (`alpha` / `10`) until the next load. The server's record was right throughout. The guard came from `writtenVersionsRef`, which was always written synchronously. That is why the CI failure was the `getByText('A2')` after `findByText('10')`, and never the `If-Match` assertion before it. Fix: `writeRowInPlace`, the only writer of the patches, builds the next map from the ref, assigns the ref, then calls `setRowPatches(next)`. The mirroring effect is gone. Nothing else sets the patches; a load does not reset them, because a load hands the grid new row objects and each patch stops applying by its `base`. So no effect is needed for load-driven resets. Files to read first, by risk: 1. `ui/packages/plugin-grid/src/ObjectGrid.tsx`: the `writeRowInPlace` hunk (ref set together with the state) and the removed `useEffect` beside `rowPatchesRef`. 2. `ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx`: the new test "an earlier save's Undo pressed the moment a newer save is drawn keeps the newer save on screen". The existing "an earlier save's Undo is guarded by the newest version of its record" is unchanged. Two-minute check: `pnpm --dir ui exec vitest run packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx` should report 19 passed. ## Tests The new test presses the earlier save's toast Undo inside a `MutationObserver` callback the moment `A2` reaches the DOM. That is a microtask after React's commit and before the render's scheduled passive effects, so the test lands in the window on every run, not only under load. It asserts the third update's arguments and `If-Match`, that `A2` is still shown, and that `alpha` is not. <details><summary>Fixed tree (1ed9d92): window test 3/3, whole file 19/19, load loop 108/108</summary> ``` == leg fixed HEAD 1ed9d92 markers: ref-assign=1 effect=0 window test run 1 exit=0 Tests 1 passed | 18 skipped (19) window test run 2 exit=0 Tests 1 passed | 18 skipped (19) window test run 3 exit=0 Tests 1 passed | 18 skipped (19) whole file exit=0 Tests 19 passed (19) RESULT tag=fixed-load runs=108 fail=0 ``` The load loop ran 3 parallel loops of the original "is guarded by the newest version" test, with 1 `yes` CPU burner, on a shared 4-core box. </details> <details><summary>Ablation (fix reverted to main's code): window test red 3/3, with the CI failure's signature; restore proven</summary> The ablation reverted both halves through `scripts/ablation-replace.mjs`: the mirroring `useEffect` was put back, and the functional `setRowPatches` updater was put back in place of the ref assignment. Each mutation showed the anchor moving 1 -> 0 and the blob changing. ``` == leg ablated HEAD 1ed9d92 markers: ref-assign=0 effect=1 window test run 1 exit=1 Tests 1 failed | 18 skipped (19) window test run 2 exit=1 Tests 1 failed | 18 skipped (19) window test run 3 exit=1 Tests 1 failed | 18 skipped (19) whole file exit=1 Tests 1 failed | 18 passed (19) TestingLibraryElementError: Unable to find an element with the text: A2. RESULT tag=ablated-load runs=33 fail=0 ablation-replace: ok restored: blob == HEAD (f49d4e1) and `git diff HEAD` is empty ``` On the ablated (main-equivalent) tree, the original test passed 33/33 under this box's load. The CI flake did not reproduce here by load alone, which matches the 3/3 and 5x18 local greens on the card. The deterministic window test is what pins the defect. </details> ## Acceptance notes - The original flaky test is unchanged. It now has nothing to race: the ref is current from the moment the newer save's state is set. - No skip, quarantine, retry or timeout change. ## Verification <details><summary>Derived gates (dispatch-gates --commands, 1ed9d92)</summary> ``` dispatch-gates --ran: 39 derived famil(ies) accounted for, 39 run, 0 NOT-MEASURED; all 39 exit 0 (incl. pnpm --dir ui exec vitest run scripts/: Test Files 172 passed | 2 skipped, Tests 5111 passed | 2 skipped) pnpm --filter @object-ui/plugin-grid run type-check (after building its ^... closure): exit 0 scoped cell-selection save tests (autosave-35685, cellSelection-35684, requiredPrompt-35956, inCellSelectMultipleRouting-35688, objectGridRowPatch-35685): Test Files 5 passed, Tests 42 passed pnpm --dir ui run check:new-line-citations: 0 new citation(s), exit 0 overlap-check --branch=HEAD: clean vs origin/main, #36054, #36045, #36024 (all share ObjectGrid.tsx, all merge cleanly) ``` The whole @object-ui/plugin-grid suite and the Test UI shards are left to CI. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgW85kwjGaz7HqsmEuv Co-authored-by: Claude <noreply@anthropic.com>
1 parent 33d0169 commit 1647fb3

3 files changed

Lines changed: 51 additions & 8 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/plugin-grid': patch
3+
---
4+
5+
fix(grid): undoing an earlier cell save right after a newer save of the same row keeps the newer save on screen
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
In a select-first grid, the Undo of an earlier save (its toast's Undo, or Ctrl+Z / Cmd+Z) draws its answer over the row as the grid shows it now. If that Undo arrived in the short window after a newer save of the same record was drawn, but before React ran that render's effects, the grid read the older patch. The row then dropped back to the values it was first read with, for example the name before the newer save, until the next load. The server's record was right the whole time. The patches the Undo reads now move together with the save that writes them, so an Undo pressed at any moment draws over the newest save.

‎ui/packages/plugin-grid/src/ObjectGrid.tsx‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -907,10 +907,10 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
907907
const patchedRowsCacheRef = React.useRef(new WeakMap<any[], { patches: ReadonlyMap<string, RowPatch>; rows: any[] }>());
908908
// objectstack#35685 — the select-first saves Undo can still take back
909909
// (`./objectGridCellUndo`), and what an undo reads when it runs, which may
910-
// be well after the render that offered it: the patches over the rows.
910+
// be well after the render that offered it: the patches over the rows,
911+
// which `writeRowInPlace` sets together with the state it renders from.
911912
const cellUndoRef = React.useRef(createCellUndoStack());
912913
const rowPatchesRef = React.useRef(rowPatches);
913-
useEffect(() => { rowPatchesRef.current = rowPatches; }, [rowPatches]);
914914
const [showExport, setShowExport] = useState(false);
915915
const [exportBusy, setExportBusy] = useState(false);
916916
const [exportError, setExportError] = useState<string | null>(null);
@@ -2879,12 +2879,15 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
28792879
if (resolved.outcome === 'reloaded') return resolved;
28802880
answer = resolved.result;
28812881
}
2882-
setRowPatches((prev) => {
2883-
const next = new Map(prev);
2884-
const held = prev.get(id);
2885-
next.set(id, { base: held && held.row === row ? held.base : row, row: mergeSavedRow(row, shown, answer) });
2886-
return next;
2887-
});
2882+
// The ref is the patches' one source and moves with the write, not after
2883+
// the render: an undo pressed once this row is drawn, before React's
2884+
// effects ran, reads this patch and not the one it replaced.
2885+
const prev = rowPatchesRef.current;
2886+
const next = new Map(prev);
2887+
const held = prev.get(id);
2888+
next.set(id, { base: held && held.row === row ? held.base : row, row: mergeSavedRow(row, shown, answer) });
2889+
rowPatchesRef.current = next;
2890+
setRowPatches(next);
28882891
return { outcome: 'saved', result: answer };
28892892
} finally {
28902893
releaseOwnWrite();

‎ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,36 @@ describe('ObjectGrid autosave — Undo takes a save back as a new guarded update
334334
expect(screen.getByText('A2')).toBeInTheDocument();
335335
});
336336

337+
it("an earlier save's Undo pressed the moment a newer save is drawn keeps the newer save on screen", async () => {
338+
// The Undo runs in the very turn the newer row reaches the DOM, before
339+
// React's effects for that render have run: what the undo draws over must
340+
// already be the newer save, or the row falls back to the values it was
341+
// read with (objectstack#35999).
342+
const ds = makeDataSource();
343+
const { container } = renderGrid(ds, true);
344+
await screen.findByText('beta');
345+
await editSelectFirst(container, dataCell(container, 0, '10'), '11');
346+
await screen.findByText('11');
347+
let pressed = false;
348+
const observer = new MutationObserver(() => {
349+
if (pressed || !container.textContent?.includes('A2')) return;
350+
pressed = true;
351+
undoOfToast(0)!.onClick();
352+
});
353+
observer.observe(container, { subtree: true, childList: true, characterData: true });
354+
try {
355+
await editSelectFirst(container, dataCell(container, 0, 'alpha'), 'a2');
356+
await waitFor(() => expect(pressed).toBe(true));
357+
} finally {
358+
observer.disconnect();
359+
}
360+
await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(3));
361+
expect(ds.update.mock.calls[2].slice(1)).toEqual(['d1', { amount: 10 }, { ifMatch: '2026-11-20T11:00:02.000Z' }]);
362+
await screen.findByText('10');
363+
expect(screen.getByText('A2')).toBeInTheDocument();
364+
expect(screen.queryByText('alpha')).toBeNull();
365+
});
366+
337367
it("someone else's later change answers 409 on the undo, even after a re-read: Cancel keeps their value", async () => {
338368
const ds = makeDataSource();
339369
// The server refuses a write whose If-Match is not the record's version.

0 commit comments

Comments
 (0)