From 950475918ac98eaaa2b81683dfd887f8ce2959ea Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 15:51:36 +0000 Subject: [PATCH 1/3] wip(list): undo a list cell save from its toast and Ctrl+Z Claude-Session: https://claude.ai/code/session_01L6bhgVGwmuaJgApFaitJDY Co-authored-by: Claude --- ui/packages/plugin-grid/src/ObjectGrid.tsx | 177 +++++++++++++++--- .../plugin-grid/src/objectGridCellUndo.ts | 79 ++++++++ .../plugin-grid/src/objectGridTranslations.ts | 7 + ui/packages/react/src/record-save-feedback.ts | 21 ++- 4 files changed, 249 insertions(+), 35 deletions(-) create mode 100644 ui/packages/plugin-grid/src/objectGridCellUndo.ts diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 15b1a552dc1..daddfefafdd 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -61,7 +61,7 @@ import { GridCellSelectionProvider, type GridCellSelection, } from '@object-ui/components'; -import { resolveConditionalFormatting, declaredNameField, buildExportFileName, resolveAffordance, resolveAffordanceGrant, resolveFieldAffordance, type SchemaLike, isExpandableFieldType, isUnmaterializedFieldType, readObjectSortability, isPlatformSortableField, filterPlatformSortableSort, filterRefusalSubject, FilterOperatorError, resolveRecordSourceConfig, resolveRecordSourceObjectName, partitionRowsByPredicate, csvBlob, readActionPayload } from '@object-ui/core'; +import { captureUpdateUndoData, resolveConditionalFormatting, declaredNameField, buildExportFileName, resolveAffordance, resolveAffordanceGrant, resolveFieldAffordance, type SchemaLike, isExpandableFieldType, isUnmaterializedFieldType, readObjectSortability, isPlatformSortableField, filterPlatformSortableSort, filterRefusalSubject, FilterOperatorError, resolveRecordSourceConfig, resolveRecordSourceObjectName, partitionRowsByPredicate, csvBlob, readActionPayload } from '@object-ui/core'; import { usePermissions } from '@object-ui/permissions'; import { RECORD_OVERLAY_DEFAULT_WIDTH, @@ -94,6 +94,7 @@ import { inlineEditRuleRefusals, inlineRuleRefusalError } from './objectGridInli import { DEFAULT_DISPLAY_PAGE_SIZE, DEFAULT_SELECTION_TYPE, type RowHeightMode, resolvePageSize, resolveRowHeightMode } from './objectGridDefaults'; import { type BatchSaveOutcome, type RowConflictChoice, type WrittenRowVersion, rowVersionOf, rowVersionToSend } from './objectGridRowVersion'; import { type RowPatch, mergeSavedRow } from './objectGridRowPatch'; +import { type CellSaveUndo, createCellUndoStack, isCellUndoKey, undoKeyCellOf } from './objectGridCellUndo'; import { type ObjectGridExternalPaginationProps, type ObjectGridFooterSummary, type ObjectGridRowGroup } from './objectGridProps'; import { FooterSummaryReport } from './objectGridFooterSummaryReport'; import { useObjectGridDiagnostics } from './objectGridDiagnostics'; @@ -791,6 +792,12 @@ export const ObjectGrid: React.FC = ({ // saved from (`RowPatch.base`); the next load's rows replace them. const [rowPatches, setRowPatches] = useState>(new Map()); const patchedRowsCacheRef = React.useRef(new WeakMap; rows: any[] }>()); + // objectstack#35685 — the select-first saves Undo can still take back + // (`./objectGridCellUndo`), and what an undo reads when it runs, which may + // be well after the render that offered it: the patches over the rows. + const cellUndoRef = React.useRef(createCellUndoStack()); + const rowPatchesRef = React.useRef(rowPatches); + useEffect(() => { rowPatchesRef.current = rowPatches; }, [rowPatches]); const [showExport, setShowExport] = useState(false); const [exportBusy, setExportBusy] = useState(false); const [exportError, setExportError] = useState(null); @@ -1312,7 +1319,10 @@ export const ObjectGrid: React.FC = ({ groupingProjectionKey, predicateProjectionKey, schemaFilter, schemaFilterRefusal, schemaSort, schemaPagination, schemaPageSize, serverPage, setServerPage, headerSort, querySearchTerm, searchFieldsKey, serverGroupedFetch, groupingNeedsHeaderQuery, fetchWindow, setGroupRowQuery, - ownWrites, + // Only a grid that draws its own writes skips them. A grid without cell + // selection re-reads on every write, the host list's included: a related + // list in that list's record drawer shows the outer grid's write too. + ownWrites: hostCellSelection ? ownWrites : null, }); // --- NavigationConfig support --- @@ -1532,6 +1542,12 @@ export const ObjectGrid: React.FC = ({ serverPageSize, groupRowQuery, groupingKeyReadable, groupingRefusesNothing, unmaskedGroupingFields, serverGroupedFetch, invalidationNonce, }); + // objectstack#35685 — the rows the grid read, as an undo finds its record + // among them when it runs: the page's rows, and a server-grouped group's. + const loadedRowsRef = React.useRef<{ data: any[]; pages: Record }>({ data, pages: {} }); + useEffect(() => { + loadedRowsRef.current = { data, pages: (groupRows.pages ?? {}) as Record }; + }); // The fan-out query, the resolved match total and the column summaries, in // hook order (`./objectGridSummaries`). @@ -2600,6 +2616,101 @@ export const ObjectGrid: React.FC = ({ return refusals.length > 0 ? inlineRuleRefusalError(refusals) : null; }; + /** + * objectstack#35685 — one select-first write of `changes` on `row`, drawn + * in place: the list holding the grid lets the write's own bus change go by + * (held until the write settles, the 409's "keep mine" write included; only + * "reload latest" lets go first, so that reload reaches the list), and the + * row alone is redrawn from the write's answer, so no other row is read + * again and a sorted or grouped row keeps its place until the next load. + * `shown` is what the row draws for the written fields when it is not + * `changes` itself (an undo draws a relation as the row read it, and sends + * its id). Resolves the write's answer, or `reloaded` when nothing was + * written. Rejects as the write does. + */ + const writeRowInPlace = async ( + id: string, + changes: Record, + row: any, + shown: Record = changes, + ): Promise<{ outcome: 'saved'; result: unknown } | { outcome: 'reloaded' }> => { + const releaseOwnWrite = ownWrites.hold(objectName!, id); + try { + let answer: unknown; + try { + answer = await writeRowGuarded(dataSource!, objectName!, id, changes, row); + } catch (err) { + if (!isConcurrentUpdateError(err)) throw err; + const resolved = await resolveRowConflict(dataSource!, objectName!, id, changes, row, err, releaseOwnWrite); + if (resolved.outcome === 'reloaded') return resolved; + answer = resolved.result; + } + setRowPatches((prev) => { + const next = new Map(prev); + const held = prev.get(id); + next.set(id, { base: held && held.row === row ? held.base : row, row: mergeSavedRow(row, shown, answer) }); + return next; + }); + return { outcome: 'saved', result: answer }; + } finally { + releaseOwnWrite(); + } + }; + + /** + * objectstack#35685 — the row an undo of record `id` writes over: the row + * the grid draws for it now (a later save's patch over the row it read), so + * its `If-Match` is the newest version this grid knows. `fallback` is the + * row the save left, for a record no longer among the rows in hand. + */ + const currentRowOf = (id: string, fallback: any): any => { + const { data: rows, pages } = loadedRowsRef.current; + const isRecord = (r: any) => { + const rid = resolveRecordId(r); + return rid !== undefined && rid !== null && String(rid) === id; + }; + const loaded = rows.find(isRecord) + ?? Object.values(pages).flatMap((page) => page?.rows ?? []).find(isRecord); + const patch = rowPatchesRef.current.get(id); + if (loaded === undefined) return patch?.row ?? fallback; + return patch && patch.base === loaded ? patch.row : loaded; + }; + + /** + * objectstack#35685 — take back one landed cell save: a new guarded update + * writing what the record held before it, drawn in place like the save + * (one more write, so one more audit entry). An entry already taken back, + * by its toast or by Ctrl+Z, does nothing. A refusal is said on a toast; + * a 409 the user cancels writes nothing and says nothing more. + */ + const undoCellSave = async (entry: CellSaveUndo, fallbackRow: any): Promise => { + if (!dataSource || !objectName || !cellUndoRef.current.take(entry)) return; + const claim = claimAnswerWarnings(dataSource, { operation: 'update', resource: objectName, id: entry.id }); + try { + const written = await writeRowInPlace(entry.id, entry.restore, currentRowOf(entry.id, fallbackRow), entry.shown); + if (written.outcome === 'saved') toastRecordSave(toast, t('actions.undone'), claim.take(undefined)); + } catch (err) { + if (isConcurrentUpdateError(err)) return; + console.error('Failed to undo the cell save:', err); + toast.error(t('table.saveFailed'), { description: err instanceof Error ? err.message : String(err) }); + } finally { + claim.release(); + } + }; + + /** Ctrl+Z (Cmd+Z) on one of this grid's cells: the newest save goes back. */ + const handleUndoKeyDown = (e: React.KeyboardEvent) => { + if (!hostCellSelection || e.defaultPrevented || !isCellUndoKey(e)) return; + if (!undoKeyCellOf(e.target, e.currentTarget)) return; + const entry = cellUndoRef.current.peek(); + if (!entry) return; + // This grid's key: the console's own Ctrl+Z (its shared undo stack) and + // the browser's are not reached. + e.preventDefault(); + e.stopPropagation(); + void undoCellSave(entry, undefined); + }; + const defaultRowSave = async ( _rowIndex: number, changes: Record, @@ -2618,45 +2729,49 @@ export const ObjectGrid: React.FC = ({ // warnings and its hook's notice) rides the save toast below, so the // write is one toast. const claim = claimAnswerWarnings(dataSource, { operation: 'update', resource: objectName, id }); - // objectstack#35685 — the select-first grid draws this write's answer - // itself (below), so the list holding it lets the write's bus change go by - // instead of reading every row again. Held until the write settles, the - // 409's "keep mine" write included; only "reload latest" lets go first, - // so that reload reaches the list. - const releaseOwnWrite = hostCellSelection ? ownWrites.hold(objectName, String(id)) : () => {}; try { - let answer: unknown; + if (hostCellSelection) { + // objectstack#35685 — the select-first model: the row redraws in + // place, and the save can be taken back. What Undo restores is read + // off the row before the write (relations as their stored ids); a + // written field the row does not carry offers no Undo at all. + const key = String(id); + const restore = captureUpdateUndoData(Object.keys(changes), row, objectSchema?.fields); + const written = await writeRowInPlace(key, changes, row); + // A reload re-reads through the bus; there is nothing of ours to show. + if (written.outcome === 'reloaded') return; + const feedback = claim.take(undefined); + if (!restore) { + toastRecordSave(toast, t('table.saved', { count: 1 }), feedback); + return; + } + const entry: CellSaveUndo = { + id: key, + restore, + shown: Object.fromEntries(Object.keys(changes).map((field) => [field, row[field]])), + }; + cellUndoRef.current.push(entry); + const savedRow = mergeSavedRow(row, changes, written.result); + toastRecordSave(toast, t('table.saved', { count: 1 }), feedback, { + label: t('actions.undo'), + onClick: () => { void undoCellSave(entry, savedRow); }, + }); + return; + } try { - answer = await writeRowGuarded(dataSource, objectName, id, changes, row); + await writeRowGuarded(dataSource, objectName, id, changes, row); } catch (err) { if (!isConcurrentUpdateError(err)) throw err; // A reload re-reads through the bus; there is nothing of ours to show. - const resolved = await resolveRowConflict(dataSource, objectName, id, changes, row, err, releaseOwnWrite); - if (resolved.outcome === 'reloaded') return; - answer = resolved.result; - } - if (hostCellSelection) { - // objectstack#35685 — the select-first model redraws this row alone, - // from the write's answer: no other row is read again, so the table - // does not move, and a sorted or grouped row keeps its place until - // the next load. - const key = String(id); - setRowPatches((prev) => { - const next = new Map(prev); - const held = prev.get(key); - next.set(key, { base: held && held.row === row ? held.base : row, row: mergeSavedRow(row, changes, answer) }); - return next; - }); - } else { - // Refresh so the grid shows the persisted values. - setRefreshKey(k => k + 1); + if ((await resolveRowConflict(dataSource, objectName, id, changes, row, err)).outcome === 'reloaded') return; } + // Refresh so the grid shows the persisted values. + setRefreshKey(k => k + 1); // objectui#12303 — the write is said, through the console's shared toast // (the one the form, kanban and view surfaces raise). Only here, once the // row landed: a refusal rejects above, and the table flags the row. toastRecordSave(toast, t('table.saved', { count: 1 }), claim.take(undefined)); } finally { - releaseOwnWrite(); claim.release(); } }; @@ -4345,7 +4460,7 @@ export const ObjectGrid: React.FC = ({ ); return ( -
+
{/* Re-fetch indicator while existing rows remain visible (filter/sort change). The initial-load skeleton above handles the empty case. */} 0} ariaLabel={t('grid.refreshing')} /> diff --git a/ui/packages/plugin-grid/src/objectGridCellUndo.ts b/ui/packages/plugin-grid/src/objectGridCellUndo.ts new file mode 100644 index 00000000000..ce1a0c50764 --- /dev/null +++ b/ui/packages/plugin-grid/src/objectGridCellUndo.ts @@ -0,0 +1,79 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * Undo of a list cell's save (objectstack#35685). + * + * A select-first grid saves each committed cell at once, so the save itself is + * what Undo takes back: the save toast's Undo button, or Ctrl+Z (Cmd+Z) on the + * grid. Undo is a new guarded update that writes the values the record held + * before the save, never a local rollback, so the server's rules, hooks and + * audit see it as the write it is. + */ + +/** One landed cell save that Undo can still take back. */ +export interface CellSaveUndo { + /** The record the save wrote. */ + id: string; + /** What Undo sends: each written field's value before the save, as stored. */ + restore: Record; + /** What Undo draws: each written field as the row showed it before the save. */ + shown: Record; +} + +/** The most saves one grid keeps for Undo; the oldest goes first. */ +export const CELL_UNDO_LIMIT = 50; + +/** The grid's saves Undo can take back, newest last. */ +export interface CellUndoStack { + push(entry: CellSaveUndo): void; + /** Take `entry` off the stack: `false` when it is no longer on it. */ + take(entry: CellSaveUndo): boolean; + /** The newest save, or `undefined` when there is none. */ + peek(): CellSaveUndo | undefined; +} + +export function createCellUndoStack(limit = CELL_UNDO_LIMIT): CellUndoStack { + const entries: CellSaveUndo[] = []; + return { + push(entry) { + entries.push(entry); + if (entries.length > limit) entries.splice(0, entries.length - limit); + }, + take(entry) { + const at = entries.lastIndexOf(entry); + if (at < 0) return false; + entries.splice(at, 1); + return true; + }, + peek() { + return entries[entries.length - 1]; + }, + }; +} + +/** The undo key: Ctrl+Z, or Cmd+Z, with no Shift (redo) and no Alt. */ +export function isCellUndoKey(e: { key: string; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; altKey: boolean }): boolean { + return (e.ctrlKey || e.metaKey) && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'z'; +} + +/** + * The grid cell a key pressed on `target` is meant for, when it is one of + * `root`'s own cells and no editor holds the key: the selected cell's typing + * catcher, or the cell itself. An open editor keeps Ctrl+Z as the field's own + * text undo, and a cell of a grid nested inside this one (a related list in + * the record drawer) belongs to that grid. + */ +export function undoKeyCellOf(target: EventTarget | null, root: HTMLElement): HTMLElement | null { + const el = target as HTMLElement | null; + if (!el || typeof el.closest !== 'function' || !root.contains(el)) return null; + const onCatcher = el.matches('[data-slot="cell-type-catcher"]'); + const tag = el.tagName.toUpperCase(); + if (!onCatcher && (el.isContentEditable || tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT')) return null; + const cell = el.closest('[data-grid-cell]'); + if (!cell || cell.closest('[data-object-grid-root]') !== root) return null; + return cell.hasAttribute('data-editing-cell') ? null : cell; +} diff --git a/ui/packages/plugin-grid/src/objectGridTranslations.ts b/ui/packages/plugin-grid/src/objectGridTranslations.ts index ecb48bb1b71..0227c227dbb 100644 --- a/ui/packages/plugin-grid/src/objectGridTranslations.ts +++ b/ui/packages/plugin-grid/src/objectGridTranslations.ts @@ -59,6 +59,13 @@ const GRID_DEFAULT_TRANSLATIONS: Record = { 'table.saved': '{{count}} row saved', 'table.saved_one': '{{count}} row saved', 'table.saved_other': '{{count}} rows saved', + // objectstack#35685 — a list cell save's Undo: the toast's button, the + // toast once it has run, and the toast when the server refuses it. The + // action runner's and the record page's own keys, byte-identical to the + // `en` pack. + 'actions.undo': 'Undo', + 'actions.undone': 'Change undone', + 'table.saveFailed': 'Save failed', // The field rules an inline edit is checked against before it is sent // (objectstack-ai/objectstack#27520), worded as the record form words them. // Byte-identical to the `en` pack, which `defaults-maps-mirror-en-pack` diff --git a/ui/packages/react/src/record-save-feedback.ts b/ui/packages/react/src/record-save-feedback.ts index 995c453403f..645ebedfcf6 100644 --- a/ui/packages/react/src/record-save-feedback.ts +++ b/ui/packages/react/src/record-save-feedback.ts @@ -169,10 +169,16 @@ export function claimAnswerWarnings(adapter: object, scope: AnswerWarningScope): }; } +/** A button on a record save toast, such as the save's Undo. */ +export interface RecordSaveToastAction { + label: string; + onClick: () => void; +} + /** Where a record save toast goes. Structurally satisfied by sonner's `toast`. */ export interface RecordSaveSink { - success(title: string, options?: { description?: string }): void; - warning(title: string, options?: { description?: string }): void; + success(title: string, options?: { description?: string; action?: RecordSaveToastAction }): void; + warning(title: string, options?: { description?: string; action?: RecordSaveToastAction }): void; } /** @@ -180,15 +186,22 @@ export interface RecordSaveSink { * title, and under it the write's notice and then its advisory warnings, one * per line. Any warning puts it on the warning variant; a notice alone keeps * it a success, because a notice reports an outcome, never a problem. + * `action` is a button the toast carries whichever variant it takes (a list + * cell save's Undo, objectstack#35685). */ export function toastRecordSave( sink: RecordSaveSink, message: string, feedback: Partial = {}, + action?: RecordSaveToastAction, ): void { const warnings = feedback.warnings ?? []; const lines = feedback.notice ? [feedback.notice, ...warnings] : [...warnings]; - if (warnings.length > 0) sink.warning(message, { description: lines.join('\n') }); - else if (lines.length > 0) sink.success(message, { description: lines.join('\n') }); + const options: { description?: string; action?: RecordSaveToastAction } = {}; + if (lines.length > 0) options.description = lines.join('\n'); + if (action) options.action = action; + const hasOptions = options.description !== undefined || options.action !== undefined; + if (warnings.length > 0) sink.warning(message, options); + else if (hasOptions) sink.success(message, options); else sink.success(message); } From 1837a4af9275f7205c2c36f5acb4aa75d9e4b496 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 15:57:29 +0000 Subject: [PATCH 2/3] test(list): pin the cell save's undo and the drawer grid's re-read Claude-Session: https://claude.ai/code/session_01L6bhgVGwmuaJgApFaitJDY Co-authored-by: Claude --- .changeset/35685-list-cell-undo.md | 18 ++ content/docs/frontend/plugins/plugin-grid.mdx | 7 + .../ObjectGrid.autosave-35685.test.tsx | 182 +++++++++++++++++- .../react/src/record-save-feedback.test.ts | 10 + 4 files changed, 216 insertions(+), 1 deletion(-) create mode 100644 .changeset/35685-list-cell-undo.md diff --git a/.changeset/35685-list-cell-undo.md b/.changeset/35685-list-cell-undo.md new file mode 100644 index 00000000000..8b17549c561 --- /dev/null +++ b/.changeset/35685-list-cell-undo.md @@ -0,0 +1,18 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/react': patch +--- + +feat(list): undo a list cell save from its toast or with Ctrl+Z + +Clause-②: yes (widening) — `toastRecordSave` in `@object-ui/react` takes an optional fourth argument, an `action` button the toast carries (new exported type `RecordSaveToastAction`), and `RecordSaveSink`'s options accept that `action`; nothing removed or renamed +Metadata-protocol: none + +In a grid that mounts `GridCellSelection` (the select-first grid every `ListView` draws), a landed cell save can be taken back: + +- **The save toast has an Undo button**, and **Ctrl+Z** (Cmd+Z on macOS) on a cell of the grid undoes the newest save, then the one before it. Each save is taken back once. +- **An undo is a new update, not a local rollback.** It writes the value each saved field held before the save (a relation as its stored id), with the record's newest known version as `If-Match`, so a 409 opens the same conflict dialog as a save. The server's history records the save and its undo as two changes. Only the row is redrawn, as for a save. +- Inside an open editor Ctrl+Z stays the editor's own text undo. On a cell, the grid's key is handled by the grid alone: the console's shared Ctrl+Z undo stack is not popped by it. +- A save of a field the row did not read offers no Undo, rather than a partial one. + +A grid without `GridCellSelection` (a related list in a record drawer, for one) now re-reads on every write of its object again, including a write the list around it draws itself: before, it skipped the writes that list held while they ran. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 31d1c45621c..79b92a179d8 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -395,6 +395,13 @@ row whose new value would sort it elsewhere stays in place until the next load - **A newer version** (409) still opens the conflict dialog: "Reload latest" re-reads the list, "Overwrite anyway" writes over it and keeps the row in place. +- **Undo** takes a save back: the save toast's Undo button, or Ctrl+Z (Cmd+Z on + macOS) on a cell of the grid, newest save first. An undo is a new update that + writes the value the record held before the save, guarded by the record's + newest version like any save (a 409 opens the same dialog), so the record's + history shows the save and its undo as two changes. Each save is taken back + once. Inside an open editor Ctrl+Z stays the editor's own text undo. A save + of a field the row did not read offers no Undo. ### Keyboard navigation diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx index b39ffeecc7c..4d88b552752 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx @@ -21,15 +21,29 @@ * either; "Reload latest" does read again. * 4. Control: without `cellSelection` the save bar's row save still * re-reads the grid. + * 5. Undo (slice S2): the save toast's Undo button and Ctrl+Z / Cmd+Z on a + * cell take a save back as a NEW guarded update of the prior value, + * newest first, each once; an open editor keeps Ctrl+Z for its text. + * 6. A grid without `cellSelection` inside a list's own-writes registry + * (the related list in that list's record drawer) still re-reads on a + * write the outer grid holds. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; +// The grid's toast, to read the save toast's Undo button (the components +// entry is the module the grid imports `toast` from). +const toasts = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() })); +vi.mock('@object-ui/components', async (importOriginal) => { + const actual = await importOriginal>(); + return { ...actual, toast: Object.assign(vi.fn(), toasts) }; +}); + import { ObjectGrid } from '../ObjectGrid'; import { registerAllFields } from '@object-ui/fields'; -import { ActionProvider, notifyDataChanged } from '@object-ui/react'; +import { ActionProvider, notifyDataChanged, createOwnWrites, OwnWritesContext } from '@object-ui/react'; import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; import { __resetApprovalsServiceLatch } from '../hooks/useRowApprovalLocks'; import { installExplainDouble } from './explainDouble'; @@ -42,6 +56,7 @@ beforeEach(() => { afterEach(() => { cleanup(); vi.unstubAllGlobals(); + for (const fn of Object.values(toasts)) fn.mockClear(); }); registerAllFields(); @@ -231,3 +246,168 @@ describe('ObjectGrid autosave — control: without cellSelection the row save re await waitFor(() => expect(ds.find.mock.calls.length).toBeGreaterThan(reads)); }); }); + +/** The Undo button of the `n`th success toast (0-based), as the grid handed it to the toast. */ +function undoOfToast(n: number): { label: string; onClick: () => void } | undefined { + return (toasts.success.mock.calls[n]?.[1] as { action?: { label: string; onClick: () => void } } | undefined)?.action; +} + +/** Ctrl+Z on the selected cell (its typing catcher holds the focus). */ +function pressUndo(container: HTMLElement, init: Record = { ctrlKey: true }) { + const catcher = container.querySelector('[data-slot="cell-type-catcher"]')!; + expect(catcher).toBeTruthy(); + fireEvent.keyDown(catcher, { key: 'z', ...init }); +} + +describe('ObjectGrid autosave — Undo takes a save back as a new guarded update (objectstack#35685)', () => { + it("the save toast's Undo writes the prior value with the save's version, and reads nothing again", async () => { + const ds = makeDataSource(); + const { container } = renderGrid(ds, true); + await screen.findByText('beta'); + const reads = ds.find.mock.calls.length; + await editSelectFirst(container, dataCell(container, 0, '10'), '11'); + await screen.findByText('11'); + await waitFor(() => expect(toasts.success).toHaveBeenCalledTimes(1)); + const undo = undoOfToast(0); + expect(undo?.label).toBe('Undo'); + undo!.onClick(); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(2)); + // One more write, guarded by the version the save answered with: the + // server's audit sees the save and its undo as two writes. + expect(ds.update.mock.calls[1].slice(1)).toEqual(['d1', { amount: 10 }, { ifMatch: '2026-11-20T11:00:01.000Z' }]); + expect(ds.store.d1.amount).toBe(10); + await screen.findByText('10'); + expect(screen.queryByText('11')).toBeNull(); + await waitFor(() => expect(toasts.success).toHaveBeenLastCalledWith('Change undone')); + expect(ds.find.mock.calls.length).toBe(reads); + // Taken back once: the same button again writes nothing. + undo!.onClick(); + await new Promise((r) => setTimeout(r, 20)); + expect(ds.update).toHaveBeenCalledTimes(2); + }); + + it('Ctrl+Z and Cmd+Z on a cell undo the newest save first, each once', async () => { + const ds = makeDataSource(); + const { container } = renderGrid(ds, true); + await screen.findByText('beta'); + await editSelectFirst(container, dataCell(container, 0, '10'), '11'); + await screen.findByText('11'); + await editSelectFirst(container, dataCell(container, 1, '20'), '21'); + await screen.findByText('21'); + expect(ds.update).toHaveBeenCalledTimes(2); + pressUndo(container); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(3)); + expect(ds.update.mock.calls[2].slice(1, 3)).toEqual(['d2', { amount: 20 }]); + await screen.findByText('20'); + pressUndo(container, { metaKey: true }); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(4)); + expect(ds.update.mock.calls[3].slice(1, 3)).toEqual(['d1', { amount: 10 }]); + await screen.findByText('10'); + // Nothing left to take back: the key writes nothing. + pressUndo(container); + await new Promise((r) => setTimeout(r, 20)); + expect(ds.update).toHaveBeenCalledTimes(4); + // The toast of a save Ctrl+Z already took back does nothing either. + undoOfToast(0)!.onClick(); + await new Promise((r) => setTimeout(r, 20)); + expect(ds.update).toHaveBeenCalledTimes(4); + }); + + it("an earlier save's Undo is guarded by the newest version of its record", async () => { + const ds = makeDataSource(); + const { container } = renderGrid(ds, true); + await screen.findByText('beta'); + await editSelectFirst(container, dataCell(container, 0, '10'), '11'); + await screen.findByText('11'); + await editSelectFirst(container, dataCell(container, 0, 'alpha'), 'a2'); + await screen.findByText('A2'); + undoOfToast(0)!.onClick(); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(3)); + expect(ds.update.mock.calls[2].slice(1)).toEqual(['d1', { amount: 10 }, { ifMatch: '2026-11-20T11:00:02.000Z' }]); + await screen.findByText('10'); + expect(screen.getByText('A2')).toBeInTheDocument(); + }); + + it('an open editor keeps Ctrl+Z for its own text: no undo is sent', async () => { + const ds = makeDataSource(); + const { container } = renderGrid(ds, true); + await screen.findByText('beta'); + await editSelectFirst(container, dataCell(container, 0, '10'), '11'); + await screen.findByText('11'); + fireEvent.click(dataCell(container, 1, 'beta')); + const catcher = container.querySelector('[data-slot="cell-type-catcher"]')!; + fireEvent.keyDown(catcher, { key: 'Enter' }); + const input = await waitFor(() => { + const el = container.querySelector('td[data-editing-cell] input'); + expect(el).toBeTruthy(); + return el!; + }); + fireEvent.keyDown(input, { key: 'z', ctrlKey: true }); + await new Promise((r) => setTimeout(r, 20)); + expect(ds.update).toHaveBeenCalledTimes(1); + }); + + it('a refused undo keeps the row and says why on a toast', async () => { + const ds = makeDataSource(); + const { container } = renderGrid(ds, true); + await screen.findByText('beta'); + await editSelectFirst(container, dataCell(container, 0, '10'), '11'); + await screen.findByText('11'); + ds.update.mockImplementationOnce(async () => { throw new Error('Amount is locked'); }); + pressUndo(container); + await waitFor(() => expect(toasts.error).toHaveBeenCalledWith('Save failed', { description: 'Amount is locked' })); + expect(screen.getByText('11')).toBeInTheDocument(); + }); + + it('control: without cellSelection the save toast carries no Undo', async () => { + const ds = makeDataSource(); + const { container } = renderGrid(ds, false); + await screen.findByText('beta'); + const cell = dataCell(container, 0, 'alpha'); + fireEvent.click(cell); + const input = await waitFor(() => { + const el = cell.querySelector('input') as HTMLInputElement; + expect(el).toBeTruthy(); + return el; + }); + fireEvent.change(input, { target: { value: 'alpha one' } }); + fireEvent.keyDown(input, { key: 'Enter' }); + const saveAll = await waitFor(() => { + const btn = Array.from(container.querySelectorAll('button')).find((b) => /Save All/.test(b.textContent || '')); + expect(btn).toBeTruthy(); + return btn as HTMLButtonElement; + }); + fireEvent.click(saveAll); + await waitFor(() => expect(toasts.success).toHaveBeenCalledTimes(1)); + expect(undoOfToast(0)).toBeUndefined(); + }); +}); + +describe("ObjectGrid — a grid without cellSelection re-reads on the host list's own write (objectstack#35685)", () => { + it("the record drawer's related grid reads again while the outer grid holds the record", async () => { + const ds = makeDataSource(); + const registry = createOwnWrites(); + const schema: any = { + type: 'object-grid', + objectName: OBJECT, + columns: [{ field: 'name', label: 'Name' }], + pagination: { pageSize: 50 }, + }; + render( + + + + + , + ); + await screen.findByText('beta'); + const reads = ds.find.mock.calls.length; + // The outer list grid is writing d1 and draws that write itself. + const release = registry.hold(OBJECT, 'd1'); + ds.store.d1 = { ...ds.store.d1, name: 'outer write' }; + notifyDataChanged({ objectName: OBJECT, recordId: 'd1' }); + await screen.findByText('outer write'); + expect(ds.find.mock.calls.length).toBeGreaterThan(reads); + release(); + }); +}); diff --git a/ui/packages/react/src/record-save-feedback.test.ts b/ui/packages/react/src/record-save-feedback.test.ts index 96b424906a9..e111b1a54b7 100644 --- a/ui/packages/react/src/record-save-feedback.test.ts +++ b/ui/packages/react/src/record-save-feedback.test.ts @@ -95,4 +95,14 @@ describe('toastRecordSave', () => { expect(sink.warning).toHaveBeenCalledWith('Quote "Q-1" updated', { description: 'a\nb' }); expect(sink.success).toHaveBeenCalledTimes(1); }); + + it('an action rides the toast on either variant (a list cell save\'s Undo, objectstack#35685)', () => { + const sink = { success: vi.fn(), warning: vi.fn() }; + const action = { label: 'Undo', onClick: vi.fn() }; + toastRecordSave(sink, '1 row saved', {}, action); + toastRecordSave(sink, '1 row saved', { warnings: ['a'], notice: 'n' }, action); + + expect(sink.success).toHaveBeenCalledWith('1 row saved', { action }); + expect(sink.warning).toHaveBeenCalledWith('1 row saved', { description: 'n\na', action }); + }); }); From e92be60e8f88b9ad7500bb805ea8f8ce8a1736ed Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 17:52:51 +0000 Subject: [PATCH 3/3] fix(list): guard a cell save's undo with the grid's own write version; checklist follows the undo Claude-Session: https://claude.ai/code/session_01L6bhgVGwmuaJgApFaitJDY Co-authored-by: Claude --- .changeset/35685-list-cell-undo.md | 2 +- content/docs/frontend/plugins/plugin-grid.mdx | 14 ++++--- .../areas/records-forms.json | 12 ++++-- .../areas/ux-conventions.json | 10 ++++- ui/packages/plugin-grid/src/ObjectGrid.tsx | 40 ++++++++++++------ .../ObjectGrid.autosave-35685.test.tsx | 42 ++++++++++++++++++- .../plugin-grid/src/objectGridCellUndo.ts | 4 ++ 7 files changed, 100 insertions(+), 24 deletions(-) diff --git a/.changeset/35685-list-cell-undo.md b/.changeset/35685-list-cell-undo.md index 8b17549c561..2e1173f0565 100644 --- a/.changeset/35685-list-cell-undo.md +++ b/.changeset/35685-list-cell-undo.md @@ -11,7 +11,7 @@ Metadata-protocol: none In a grid that mounts `GridCellSelection` (the select-first grid every `ListView` draws), a landed cell save can be taken back: - **The save toast has an Undo button**, and **Ctrl+Z** (Cmd+Z on macOS) on a cell of the grid undoes the newest save, then the one before it. Each save is taken back once. -- **An undo is a new update, not a local rollback.** It writes the value each saved field held before the save (a relation as its stored id), with the record's newest known version as `If-Match`, so a 409 opens the same conflict dialog as a save. The server's history records the save and its undo as two changes. Only the row is redrawn, as for a save. +- **An undo is a new update, not a local rollback.** It writes the value each saved field held before the save (a relation as its stored id), with the version this grid's own newest write of the record answered as `If-Match`, so a change someone else made since answers 409 and opens the same conflict dialog as a save instead of being overwritten. A refused or cancelled undo is used up; the next Ctrl+Z undoes the save before it. The server's history records the save and its undo as two changes. Only the row is redrawn, as for a save. - Inside an open editor Ctrl+Z stays the editor's own text undo. On a cell, the grid's key is handled by the grid alone: the console's shared Ctrl+Z undo stack is not popped by it. - A save of a field the row did not read offers no Undo, rather than a partial one. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 79b92a179d8..c343f1f8776 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -397,11 +397,15 @@ row whose new value would sort it elsewhere stays in place until the next load place. - **Undo** takes a save back: the save toast's Undo button, or Ctrl+Z (Cmd+Z on macOS) on a cell of the grid, newest save first. An undo is a new update that - writes the value the record held before the save, guarded by the record's - newest version like any save (a 409 opens the same dialog), so the record's - history shows the save and its undo as two changes. Each save is taken back - once. Inside an open editor Ctrl+Z stays the editor's own text undo. A save - of a field the row did not read offers no Undo. + writes the value the record held before the save, guarded by the version + this grid's own newest write of the record answered: if someone else changed + the record since, the 409 dialog opens instead of their change being + overwritten. The record's history shows the save and its undo as two + changes. Each save is taken back once, and a refused or cancelled undo is + used up too, so the next Ctrl+Z undoes the save before it. A toast's Undo + takes back that toast's save, while Ctrl+Z always goes newest first. Inside + an open editor Ctrl+Z stays the editor's own text undo. A save of a field the + row did not read offers no Undo. ### Keyboard navigation diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 6f68c5d6256..c5ef69d11e8 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -4067,7 +4067,7 @@ "title": "Record edit undo: toast Undo / Ctrl+Z restores the prior value through the API and logs a revert; undo after a concurrent change must not silently clobber", "since": "v16", "status": "active", - "revision": 7, + "revision": 8, "priority": "P2", "surface": "browser", "personas": [ @@ -4077,11 +4077,11 @@ "fixtures": { "app": "showcase", "requires": [ - "a writable record and an action that declares `undoable: true` with operation 'update' (a patch of one field) — at objectui 1fb1ced36243, and still on main f2fdac5d under ui/, the ONLY path that pushes an Undo op: useConsoleActionRuntime and RecordDetailView attach the toast Undo for `undoable` actions, while inline grid and form edits push none. objectui react/src/hooks/useGlobalUndo.ts + core globalUndoManager hold the stack. ⚠ The stock showcase declares NO undoable action (examples/app-showcase has zero `undoable` keys), and a runtime-authored action is not joined into the served object's actions[] (records-forms.action-location-matrix knownGaps), so the action must ship PACKAGED in the showcase — see `blocked`" + "a writable record and an action that declares `undoable: true` with operation 'update' (a patch of one field) — at objectui 1fb1ced36243, and still on main f2fdac5d under ui/, the ONLY path that pushes an Undo op: useConsoleActionRuntime and RecordDetailView attach the toast Undo for `undoable` actions, while form edits push none and inline grid edits push none onto that stack. Since #35685 a list grid's cell save (every grid a ListView draws) offers an Undo of its own — the save toast's Undo button and Ctrl+Z / Cmd+Z on a cell, a new If-Match update of the prior value — but on the grid's own stack (ObjectGrid), not globalUndoManager, with no redo; it is not this item's fixture, whose clauses read the shared stack and its redo. objectui react/src/hooks/useGlobalUndo.ts + core globalUndoManager hold the stack. ⚠ The stock showcase declares NO undoable action (examples/app-showcase has zero `undoable` keys), and a runtime-authored action is not joined into the served object's actions[] (records-forms.action-location-matrix knownGaps), so the action must ship PACKAGED in the showcase — see `blocked`" ], "knownGaps": [ "AUTOMATION LIVES IN THE objectui TREE, WHICH IS ui/ IN THIS CHECKOUT — `automated.ref` names objectui specs exclusively, by objectui-relative paths that resolve under ui/ (a unit suite at ui/packages/…, a Playwright spec at ui/e2e/…). They run from that tree: a unit suite with cwd ui/ (pnpm exec vitest run FILE), a live spec only against a booted stack serving a console built by pnpm console:build. Drive the item by hand in the browser and score it as a manual run, OR run the pin from ui/ and cite its output naming the framework commit it ran at. ⛔ Never score it as covered on the strength of the `automated` field alone — an unrun pin is a claim, not evidence. Full protocol: RUNNER.md, the objectui-pinned-automation standing fact, whose 'none of those specs exist here' predates the ui/ import.", - "BLOCKED(fixture) on stock, all four clauses (QA run #23163, objectstack 36b2889c, objectui 1fb1ced36243). Inline edits push no Undo op at this pin — only actions declaring `undoable` do — and the showcase declares none, while a runtime-authored undoable action is not served. The item becomes runnable when examples/app-showcase ships a packaged undoable update action on a writable object (operation 'update' with a patch, so the Undo captures the prior value of every written field — ActionSchema.undoable in packages/spec/src/ui/action.zod.ts). Lift `blocked` in the revision that names that fixture. ⛔ Do not score an inline edit's missing Undo as this item's FAIL: the console never offers one by design. Re-checked at main f2fdac5d (wave anchor #25807, slice C): the premise holds — examples/ carries zero `undoable` keys and no packaged action in packages/ declares `undoable: true`, and inline edits still push no Undo op (ui/packages/core/src/actions/ActionRunner.ts pushes only an action result's undo onto globalUndoManager). Since the spec's semantic migration ui-action-undoable-unfulfillable-refused (packages/spec/src/migrations/entries/semantic/18.ui-action-undoable-unfulfillable-refused.ts), `undoable: true` parses only on the two shapes some runtime fulfils — operation 'update' with a patch (the framework runtime snapshots the prior value, packages/runtime/src/action-execution.ts#DeclarativeUpdateUndo) or type 'api' (the console builds the undo envelope) — so the lifting fixture may be either" + "BLOCKED(fixture) on stock, all four clauses (QA run #23163, objectstack 36b2889c, objectui 1fb1ced36243). Inline edits push no Undo op at this pin — only actions declaring `undoable` do — and the showcase declares none, while a runtime-authored undoable action is not served. The item becomes runnable when examples/app-showcase ships a packaged undoable update action on a writable object (operation 'update' with a patch, so the Undo captures the prior value of every written field — ActionSchema.undoable in packages/spec/src/ui/action.zod.ts). Lift `blocked` in the revision that names that fixture. ⛔ Do not score an inline edit as this item's FAIL or PASS: a form edit offers no Undo by design, and a list cell save's Undo (since #35685) is the grid's own guarded stack, not the shared stack these clauses read. Re-checked at main f2fdac5d (wave anchor #25807, slice C): the premise holds — examples/ carries zero `undoable` keys and no packaged action in packages/ declares `undoable: true`, and inline edits still push no Undo op (ui/packages/core/src/actions/ActionRunner.ts pushes only an action result's undo onto globalUndoManager). Since the spec's semantic migration ui-action-undoable-unfulfillable-refused (packages/spec/src/migrations/entries/semantic/18.ui-action-undoable-unfulfillable-refused.ts), `undoable: true` parses only on the two shapes some runtime fulfils — operation 'update' with a patch (the framework runtime snapshots the prior value, packages/runtime/src/action-execution.ts#DeclarativeUpdateUndo) or type 'api' (the console builds the undo envelope) — so the lifting fixture may be either" ] }, "steps": [ @@ -4178,6 +4178,12 @@ "date": "2026-11-20", "change": "steps[2] re-pointed (#35595, #35596): the stream opens from the Activity tab of the record's tab row, from the title of the Overview rail's 最近动态 card (the right column's 动态 panel is retired), or ?related=timeline. No clause changed. Read from source at the PR's head.", "ref": "#35595" + }, + { + "revision": 8, + "date": "2026-11-20", + "change": "fixtures.requires[0] and knownGaps[1] follow #35685: a list grid's cell save now offers its own Undo (the save toast's button and Ctrl+Z / Cmd+Z on a cell, a new If-Match update of the prior value), so 'inline grid edits push none' is narrowed to the shared globalUndoManager stack these clauses read. That Undo is the grid's own stack, with no redo, and is not this item's lifting fixture; `blocked` unchanged. No clause changed. Read at the PR's head", + "ref": "#35898" } ] }, diff --git a/docs/qa/platform-checklist/areas/ux-conventions.json b/docs/qa/platform-checklist/areas/ux-conventions.json index 54b8f86f10c..bba524e2474 100644 --- a/docs/qa/platform-checklist/areas/ux-conventions.json +++ b/docs/qa/platform-checklist/areas/ux-conventions.json @@ -9,7 +9,7 @@ "title": "Every user-initiated write answers visibly — success names what changed, a refusal says why, and a no-op claims nothing", "since": "v17.7", "status": "active", - "revision": 15, + "revision": 16, "priority": "P1", "surface": "browser", "personas": [ @@ -27,7 +27,7 @@ "FIXED, regression row, expected PASS (objectui#11817): Setup → Users → Invite User toasts the copy of the delivery outcome the server answers (#27843): on a deployment that does not deliver mail the declared outcomeMessages.link_only, 'Invitation created for EMAIL. Mail is not configured on this server, so no email went out. Use Copy Invite Link on the invitation to share it.' (QA run #29890 read it verbatim), and 'Invitation sent to EMAIL' (outcomeMessages.sent) only where mail is delivered (packages/platform-objects/src/identity/invite-outcome-messages.ts#INVITE_USER_OUTCOME_MESSAGES on packages/platform-objects/src/identity/sys-user.object.ts#invite_user, whose successMessage `Invitation sent to {{ result.email }}` is the fallback for an answer without an outcome), interpolating the invitee from the action result — while the sys_invitation and sys_email rows are written (QA run #23163 at objectui 1fb1ced36243; pin ObjectView.inviteFeedback-11817.test.tsx)", "FIXED, regression rows, expected PASS (QA run #23953 at objectui daeb77fc84dd): Studio Publish gives a success confirmation (objectui#11807); the task grid's row save toasts '1 row saved' (objectui#12303 fixed for this row; since #35685 it is the save each committed cell makes, with no Save All); the approval decision's Approve toasted the framework-declared successMessage, read in the approvals drawer that route no longer has (variants[6]) `Approved \"{{ result.request.record_title }}\"` (packages/plugins/plugin-approvals/src/sys-approval-request.object.ts), e.g. Approved \"EXP-2001\" (#23157, closed). Studio's 'Discard draft' toast and its confirm now name the item by its LABEL — QA run #24570 at objectui 4016370a read 'Draft discarded: QA Widget' — a regression row, expected PASS (objectstack-ai/objectui#12690, closed by objectui PR #12830, 0f42aaf8, in the console pin 4016370a and on objectui main; ResourceEditPage.tsx falls back to type/name only for an item with no label)", "FIXED, regression row, expected PASS (objectui#11816): leaving an inline editor with no value change no longer reads '1 row modified · Save All (1)' (QA run #23163 at objectui 1fb1ced36243; pin data-table-noop-edit-11816.test.tsx) — negative[1]", - "Undo is scored only where a surface offers it, and on stock ONE surface does: the import. An import run as a job (the wizard's 'runs as an undoable job' option) is listed in the import history with 'Undo import', which deletes the records it created and restores the records it updated to their previous values; QA run #25817 at 6679644a read it working in both create and update modes. Elsewhere no stock surface offers Undo: only an action declaring `undoable` pushes an Undo op (inline and form edits push none), and the showcase declares no undoable action (records-forms.record-edit-undo, blocked(fixture)). So acceptance[5] is scored on the import variant. Undo's absence elsewhere is recorded in the evidence and is never a FAIL of this item: which writes should offer Undo is a product decision, not this item's oracle" + "Undo is scored only where a surface offers it, and on stock TWO surfaces do: the import, and since #35685 a list cell save (the save toast's Undo button, or Ctrl+Z / Cmd+Z on the cell, sends a new If-Match update of the prior value and toasts 'Change undone'; the grid's own stack, not the shared one). An import run as a job (the wizard's 'runs as an undoable job' option) is listed in the import history with 'Undo import', which deletes the records it created and restores the records it updated to their previous values; QA run #25817 at 6679644a read it working in both create and update modes. Elsewhere no stock surface offers Undo: only an action declaring `undoable` pushes an Undo op onto the shared stack (form edits push none, and a list cell save's Undo is its grid's own), and the showcase declares no undoable action (records-forms.record-edit-undo, blocked(fixture)). So acceptance[5] is scored on the import variant, and may be read on variants[1]'s cell save too. Undo's absence elsewhere is recorded in the evidence and is never a FAIL of this item: which writes should offer Undo is a product decision, not this item's oracle" ] }, "variants": [ @@ -195,6 +195,12 @@ "date": "2026-11-20", "change": "variants[1] and knownGaps[1] follow #35685: a list cell saves the moment it is committed, with a saving and a saved mark on the cell and the '1 row saved' toast, and there is no Save row or Save All to press. The clauses are unchanged. Read at base 2ad42b5d", "ref": "#35864" + }, + { + "revision": 16, + "date": "2026-11-20", + "change": "knownGaps[3] follows #35685: a list cell save now offers Undo (the save toast's button and Ctrl+Z / Cmd+Z on a cell, a new If-Match update of the prior value), so the stock surfaces with an Undo are the import and the list cell save, and 'inline edits push none' is narrowed to the shared stack. The clauses are unchanged. Read at the PR's head", + "ref": "#35898" } ] }, diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index daddfefafdd..782fcd9b3c4 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -2546,16 +2546,21 @@ export const ObjectGrid: React.FC = ({ else writtenVersionsRef.current.delete(id); }; - /** One row's guarded write. Rejects with whatever the data source threw. */ + /** + * One row's guarded write. Rejects with whatever the data source threw. + * `guard` is the version to send in place of the one the row implies (an + * undo's: the version this grid's own write answered). + */ const writeRowGuarded = async ( ds: DataSource, resource: string, id: string, changes: Record, row: any, + guard?: string, ): Promise => { const readVersion = rowVersionOf(row); - const ifMatch = rowVersionToSend(writtenVersionsRef.current.get(id), readVersion); + const ifMatch = guard ?? rowVersionToSend(writtenVersionsRef.current.get(id), readVersion); const result = await ds.update(resource, id, changes, ifMatch ? { ifMatch } : undefined); rememberRowWrite(id, readVersion, result); return result; @@ -2625,7 +2630,8 @@ export const ObjectGrid: React.FC = ({ * again and a sorted or grouped row keeps its place until the next load. * `shown` is what the row draws for the written fields when it is not * `changes` itself (an undo draws a relation as the row read it, and sends - * its id). Resolves the write's answer, or `reloaded` when nothing was + * its id), and `guard` the `If-Match` to send in place of the one the row + * implies. Resolves the write's answer, or `reloaded` when nothing was * written. Rejects as the write does. */ const writeRowInPlace = async ( @@ -2633,12 +2639,13 @@ export const ObjectGrid: React.FC = ({ changes: Record, row: any, shown: Record = changes, + guard?: string, ): Promise<{ outcome: 'saved'; result: unknown } | { outcome: 'reloaded' }> => { const releaseOwnWrite = ownWrites.hold(objectName!, id); try { let answer: unknown; try { - answer = await writeRowGuarded(dataSource!, objectName!, id, changes, row); + answer = await writeRowGuarded(dataSource!, objectName!, id, changes, row, guard); } catch (err) { if (!isConcurrentUpdateError(err)) throw err; const resolved = await resolveRowConflict(dataSource!, objectName!, id, changes, row, err, releaseOwnWrite); @@ -2658,10 +2665,10 @@ export const ObjectGrid: React.FC = ({ }; /** - * objectstack#35685 — the row an undo of record `id` writes over: the row - * the grid draws for it now (a later save's patch over the row it read), so - * its `If-Match` is the newest version this grid knows. `fallback` is the - * row the save left, for a record no longer among the rows in hand. + * objectstack#35685 — the row an undo of record `id` is drawn over: the row + * the grid draws for it now (a later save's patch over the row it read, or + * the row a later load brought). `fallback` is the row the save left, for a + * record no longer among the rows in hand. */ const currentRowOf = (id: string, fallback: any): any => { const { data: rows, pages } = loadedRowsRef.current; @@ -2679,15 +2686,22 @@ export const ObjectGrid: React.FC = ({ /** * objectstack#35685 — take back one landed cell save: a new guarded update * writing what the record held before it, drawn in place like the save - * (one more write, so one more audit entry). An entry already taken back, - * by its toast or by Ctrl+Z, does nothing. A refusal is said on a toast; - * a 409 the user cancels writes nothing and says nothing more. + * (one more write, so one more audit entry). Its `If-Match` is the version + * this grid's own newest write of the record answered, never a version a + * later load read: a change someone else made since then answers 409 and + * opens the conflict dialog instead of being overwritten. An entry already + * taken back, by its toast or by Ctrl+Z, does nothing, and one of another + * object (the grid was pointed elsewhere) is dropped unsent. A refusal is + * said on a toast; a 409 the user cancels writes nothing and says nothing + * more. Either way the entry is spent. */ const undoCellSave = async (entry: CellSaveUndo, fallbackRow: any): Promise => { if (!dataSource || !objectName || !cellUndoRef.current.take(entry)) return; + if (entry.objectName !== objectName) return; const claim = claimAnswerWarnings(dataSource, { operation: 'update', resource: objectName, id: entry.id }); try { - const written = await writeRowInPlace(entry.id, entry.restore, currentRowOf(entry.id, fallbackRow), entry.shown); + const guard = writtenVersionsRef.current.get(entry.id)?.version ?? entry.version; + const written = await writeRowInPlace(entry.id, entry.restore, currentRowOf(entry.id, fallbackRow), entry.shown, guard); if (written.outcome === 'saved') toastRecordSave(toast, t('actions.undone'), claim.take(undefined)); } catch (err) { if (isConcurrentUpdateError(err)) return; @@ -2746,7 +2760,9 @@ export const ObjectGrid: React.FC = ({ return; } const entry: CellSaveUndo = { + objectName, id: key, + version: rowVersionOf(written.result), restore, shown: Object.fromEntries(Object.keys(changes).map((field) => [field, row[field]])), }; diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx index 4d88b552752..199f97d1be0 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx @@ -23,7 +23,9 @@ * re-reads the grid. * 5. Undo (slice S2): the save toast's Undo button and Ctrl+Z / Cmd+Z on a * cell take a save back as a NEW guarded update of the prior value, - * newest first, each once; an open editor keeps Ctrl+Z for its text. + * newest first, each once, guarded by the version the grid's own write + * answered (a later change by someone else answers 409); an open editor + * keeps Ctrl+Z for its text. * 6. A grid without `cellSelection` inside a list's own-writes registry * (the related list in that list's record drawer) still re-reads on a * write the outer grid holds. @@ -328,6 +330,44 @@ describe('ObjectGrid autosave — Undo takes a save back as a new guarded update expect(screen.getByText('A2')).toBeInTheDocument(); }); + it("someone else's later change answers 409 on the undo, even after a re-read: Cancel keeps their value", async () => { + const ds = makeDataSource(); + // The server refuses a write whose If-Match is not the record's version. + const land = ds.update.getMockImplementation(); + ds.update.mockImplementation(async (object: string, id: string, changes: Record, opts?: any) => { + if (opts?.ifMatch && opts.ifMatch !== ds.store[id].updated_at) { + throw Object.assign(new Error('Record changed since you read it'), { + code: 'CONCURRENT_UPDATE', + currentVersion: ds.store[id].updated_at, + currentRecord: { ...ds.store[id] }, + }); + } + return land(object, id, changes, opts); + }); + const { container } = renderGrid(ds, true); + await screen.findByText('beta'); + await editSelectFirst(container, dataCell(container, 0, '10'), '11'); + await screen.findByText('11'); + // Another user sets the amount; a change naming no record makes the grid read again. + ds.store.d1 = { ...ds.store.d1, amount: 50, updated_at: '2026-11-20T12:00:00.000Z' }; + notifyDataChanged({ objectName: OBJECT }); + await screen.findByText('50'); + undoOfToast(0)!.onClick(); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(2)); + // Guarded by the version this grid's own save answered, not the re-read's. + expect(ds.update.mock.calls[1][3]).toEqual({ ifMatch: '2026-11-20T11:00:01.000Z' }); + fireEvent.click(await screen.findByRole('button', { name: /^Cancel$/ })); + await new Promise((r) => setTimeout(r, 20)); + expect(ds.update).toHaveBeenCalledTimes(2); + expect(ds.store.d1.amount).toBe(50); + expect(screen.getByText('50')).toBeInTheDocument(); + expect(toasts.success).not.toHaveBeenCalledWith('Change undone'); + // The cancelled undo is spent: the key has nothing left to send. + pressUndo(container); + await new Promise((r) => setTimeout(r, 20)); + expect(ds.update).toHaveBeenCalledTimes(2); + }); + it('an open editor keeps Ctrl+Z for its own text: no undo is sent', async () => { const ds = makeDataSource(); const { container } = renderGrid(ds, true); diff --git a/ui/packages/plugin-grid/src/objectGridCellUndo.ts b/ui/packages/plugin-grid/src/objectGridCellUndo.ts index ce1a0c50764..19e139aee66 100644 --- a/ui/packages/plugin-grid/src/objectGridCellUndo.ts +++ b/ui/packages/plugin-grid/src/objectGridCellUndo.ts @@ -16,8 +16,12 @@ /** One landed cell save that Undo can still take back. */ export interface CellSaveUndo { + /** The object the save wrote, so a grid pointed elsewhere never aims it at another. */ + objectName: string; /** The record the save wrote. */ id: string; + /** The version the save's write answered: what Undo's `If-Match` falls back to. */ + version: string | undefined; /** What Undo sends: each written field's value before the save, as stored. */ restore: Record; /** What Undo draws: each written field as the row showed it before the save. */