Skip to content

Commit 37525bf

Browse files
committed
fix(list): a cell that waited for its record verdict reads the answer that settled the wait (#35795)
L1-b M1: the re-asked edit ran before the render that published the verdict, so describeCell read the old (unknown) verdict and opened the editor on a row the explain engine refuses. RecordCrudVerdicts gains current(), answered from the map published last, and describeCell reads it. Pins: a refusing slow verdict opens no editor on double-click, on a typed key, and writes nothing on paste. Changeset names the third outcome; a note on the unanswered lock state. Claude-Session: https://claude.ai/code/session_01L6bhgXSK9qt8je9QbZvhKb Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1c9d33c commit 37525bf

6 files changed

Lines changed: 97 additions & 10 deletions

File tree

‎.changeset/35795-batched-record-lock-read.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ fix(approvals, list): a list cell no longer opens an editor before it knows the
1313
Clause-②: yes (widening)
1414
Metadata-protocol: none
1515

16-
**What a list user sees.** On a list that edits in place, a double-click, Enter, F2 or a typed key on a cell whose record's approval lock or edit permission is still being read no longer opens an editor that the server would then refuse on save. The cell says "Checking whether this record can be edited…", and when the answer arrives the same edit goes ahead by itself (with the typed key), or the cell says the record is locked while it is in approval. Selecting another cell in the meantime drops the wait. Moving the selection with the arrow keys no longer sends a lock request per row: the first cell selected on a page asks the locks of every row on it at once.
16+
**What a list user sees.** On a list that edits in place, a double-click, Enter, F2 or a typed key on a cell whose record's approval lock or edit permission is still being read no longer opens an editor that the server would then refuse on save. The cell says "Checking whether this record can be edited…", and when the answer arrives the same edit goes ahead by itself (with the typed key), or the cell says why it does not: the record is locked while it is in approval, or the reader has no permission to edit it. Selecting another cell in the meantime drops the wait. Moving the selection with the arrow keys no longer sends a lock request per row: the first cell selected on a page asks the locks of every row on it at once.
1717

1818
**New route.** `POST /api/v1/approvals/records/:object/locks` with the body `{ "recordIds": ["<id>", ...] }` (at least one id, at most `APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`, 200) answers `{ success: true, data: { records: [{ recordId, locked }] } }`, one entry per id in order. `locked` is what `GET /api/v1/approvals/records/:object/:recordId/lock` answers for that id, and `null` where that route answers 404: a record the caller cannot read and one that does not exist answer alike. Any other body (a key other than `recordIds`, an empty list, a non-string or blank id, more ids than the cap) and any query parameter are refused whole with `400 VALIDATION_ERROR`, never trimmed. A deployment whose approvals service does not implement the read answers `501`.
1919

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1376,7 +1376,10 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
13761376
describeCell: (row, columnKey) => {
13771377
const fieldDef = objectFields?.[columnKey];
13781378
const recordId = rowRecordId(row);
1379-
const recordUpdate = recordVerdict(recordId, 'update');
1379+
// objectstack#35795 — read at call time, not from this render: an
1380+
// edit that waited for the verdict is re-asked before the render
1381+
// that publishes it.
1382+
const recordUpdate = recordVerdict.current(recordId, 'update');
13801383
const kind = cellReadOnlyKind({
13811384
fieldDef,
13821385
fieldWritable: !objectName || resolveFieldAffordance('listInlineEdit', perms, objectName, columnKey),

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

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,16 @@ describe('ObjectGrid autosave — one update, this row only (objectstack#35685)'
182182
});
183183

184184
describe("ObjectGrid autosave — a write asked while the row's lock is read waits for it (objectstack#35795)", () => {
185-
/** The approvals service answers the page's locks after `delay` ms; explain answers at once. */
186-
function stubSlowLocks(locked: ReadonlySet<string>, delay: number) {
185+
/**
186+
* The approvals service answers the page's locks after `delay` ms; explain
187+
* answers after `explain.delay` ms (at once by default), refusing `update`
188+
* on the rows in `explain.refused`.
189+
*/
190+
function stubSlowLocks(
191+
locked: ReadonlySet<string>,
192+
delay: number,
193+
explain: { delay?: number; refused?: ReadonlySet<string> } = {},
194+
) {
187195
vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => {
188196
const body = init?.body ? JSON.parse(String(init.body)) : {};
189197
const ids: string[] = Array.isArray(body.recordIds) ? body.recordIds : [];
@@ -194,7 +202,11 @@ describe("ObjectGrid autosave — a write asked while the row's lock is read wai
194202
};
195203
return new Promise((resolve) => setTimeout(() => resolve(answer), delay));
196204
}
197-
return { ok: true, status: 200, json: async () => ({ allowed: true, records: ids.map((id) => ({ recordId: id, visible: true })) }) };
205+
const verdicts = {
206+
ok: true, status: 200,
207+
json: async () => ({ allowed: true, records: ids.map((id) => ({ recordId: id, visible: !explain.refused?.has(id) })) }),
208+
};
209+
return explain.delay ? new Promise((resolve) => setTimeout(() => resolve(verdicts), explain.delay)) : verdicts;
198210
}));
199211
}
200212
function paste(container: HTMLElement, cell: HTMLElement, text: string) {
@@ -235,6 +247,21 @@ describe("ObjectGrid autosave — a write asked while the row's lock is read wai
235247
await act(async () => { await new Promise((r) => setTimeout(r, 20)); });
236248
expect(ds.update).not.toHaveBeenCalled();
237249
});
250+
251+
it('a paste on a row whose slow record verdict refuses it is never written, and the cell says why', async () => {
252+
stubSlowLocks(new Set(), 0, { delay: 2000, refused: new Set(['d1']) });
253+
const ds = makeDataSource();
254+
const { container } = renderGrid(ds, true);
255+
await screen.findByText('beta');
256+
vi.useFakeTimers();
257+
paste(container, dataCell(container, 0, 'alpha'), 'zeta');
258+
expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent('Checking whether this record can be edited…');
259+
await act(async () => { await vi.advanceTimersByTimeAsync(2000); });
260+
expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent("You don't have permission to edit this record.");
261+
vi.useRealTimers();
262+
await act(async () => { await new Promise((r) => setTimeout(r, 20)); });
263+
expect(ds.update).not.toHaveBeenCalled();
264+
});
238265
});
239266

240267
describe('ObjectGrid autosave — a 409 kept as mine re-reads nothing either (objectstack#35685)', () => {

‎ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ let lockReads: string[][] = [];
8181
let lockDelay = 0;
8282
let explainDelay = 0;
8383
let explainReads = 0;
84+
/** The rows the explain engine refuses `update` on. */
85+
let refusedIds = new Set<string>();
8486

8587
const LOCKS_URL = '/api/v1/approvals/records/probe/locks';
8688
const after = <T,>(ms: number, value: T): Promise<T> =>
@@ -95,6 +97,7 @@ beforeEach(() => {
9597
lockDelay = 0;
9698
explainDelay = 0;
9799
explainReads = 0;
100+
refusedIds = new Set();
98101
// The explain engine permits every row; the approvals service answers the locks of a page.
99102
vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => {
100103
const href = String(url);
@@ -109,7 +112,7 @@ beforeEach(() => {
109112
});
110113
}
111114
explainReads += 1;
112-
return after(explainDelay, { ok: true, status: 200, json: async () => ({ allowed: true, records: ids.map((id) => ({ recordId: id, visible: true })) }) });
115+
return after(explainDelay, { ok: true, status: 200, json: async () => ({ allowed: true, records: ids.map((id) => ({ recordId: id, visible: !refusedIds.has(id) })) }) });
113116
}));
114117
});
115118
afterEach(() => {
@@ -221,6 +224,7 @@ describe('ObjectGrid cellSelection — why a cell opens no editor', () => {
221224
describe('ObjectGrid cellSelection — an edit waits for the row\'s lock and verdict (objectstack#35795)', () => {
222225
const CHECKING = 'Checking whether this record can be edited…';
223226
const LOCKED = "This record is locked while it's in approval.";
227+
const NO_PERMISSION = "You don't have permission to edit this record.";
224228
const editor = (g: { container: HTMLElement }) => g.container.querySelector('td[data-editing-cell]');
225229
const catcher = (g: { container: HTMLElement }) => g.container.querySelector<HTMLInputElement>('[data-slot="cell-type-catcher"]')!;
226230

@@ -284,6 +288,33 @@ describe('ObjectGrid cellSelection — an edit waits for the row\'s lock and ver
284288
expect(editor(g)).not.toBeNull();
285289
});
286290

291+
// The answer that settles the wait is the one the re-asked edit reads, not
292+
// the verdict of the render the wait began in.
293+
it('a slow record verdict that refuses the row opens no editor: the cell says the reader may not edit it', async () => {
294+
explainDelay = 2000;
295+
refusedIds = new Set(['1']);
296+
const g = await renderSlow();
297+
fireEvent.click(g.cell(0, 0));
298+
fireEvent.doubleClick(g.cell(0, 0));
299+
expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(CHECKING);
300+
await act(async () => { await vi.advanceTimersByTimeAsync(2000); });
301+
expect(editor(g)).toBeNull();
302+
expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(NO_PERMISSION);
303+
});
304+
305+
it('a key typed while a refusing verdict is read opens nothing and writes nothing', async () => {
306+
explainDelay = 2000;
307+
refusedIds = new Set(['1']);
308+
const g = await renderSlow();
309+
fireEvent.click(g.cell(0, 0));
310+
fireEvent.change(catcher(g), { target: { value: 'Z' } });
311+
expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(CHECKING);
312+
await act(async () => { await vi.advanceTimersByTimeAsync(2000); });
313+
expect(editor(g)).toBeNull();
314+
expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(NO_PERMISSION);
315+
expect(g.cell(0, 0)).toHaveTextContent('Alpha');
316+
});
317+
287318
it('selecting another cell while checking drops the wait: the answer opens nothing', async () => {
288319
lockDelay = 2000;
289320
const g = await renderSlow();

‎ui/packages/plugin-grid/src/hooks/useRecordCrudVerdicts.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -476,17 +476,26 @@ export interface RecordCrudVerdicts extends RecordCrudVerdictLookup {
476476
* verdict may refuse).
477477
*/
478478
readonly settling: () => Promise<void> | null;
479+
/**
480+
* The same lookup as the function itself, but answered from the verdicts
481+
* published LAST — not the ones of the render that made this object. A
482+
* caller that holds on to this object across an answer (a wait that is
483+
* re-asked once {@link settling} settles, before React has re-rendered)
484+
* reads the answer that just landed here (objectstack#35795).
485+
*/
486+
readonly current: RecordCrudVerdictLookup;
479487
}
480488

481489
function lookupOf(
482490
verdicts: ReadonlyMap<string, boolean>,
483491
requestVerdicts: () => void,
484492
pending: boolean,
485493
settling: () => Promise<void> | null,
494+
current: RecordCrudVerdictLookup,
486495
): RecordCrudVerdicts {
487496
const lookup: RecordCrudVerdictLookup = (recordId, operation) =>
488497
recordId == null ? undefined : verdicts.get(`${operation}:${String(recordId)}`);
489-
return Object.assign(lookup, { requestVerdicts, pending, settling });
498+
return Object.assign(lookup, { requestVerdicts, pending, settling, current });
490499
}
491500

492501
export function useRecordCrudVerdicts(opts: {
@@ -537,6 +546,15 @@ export function useRecordCrudVerdicts(opts: {
537546
const [pending, setPending] = React.useState(false);
538547
const wireRef = React.useRef<Promise<void> | null>(null);
539548
const settling = React.useCallback(() => wireRef.current, []);
549+
// What was published last, written in the same stroke as `setVerdicts`: a
550+
// wait re-asked as soon as the wire settles runs before the re-render that
551+
// publishes the answer, so it reads the answer here (objectstack#35795).
552+
const publishedRef = React.useRef<ReadonlyMap<string, boolean>>(new Map());
553+
const current = React.useCallback<RecordCrudVerdictLookup>(
554+
(recordId, operation) =>
555+
recordId == null ? undefined : publishedRef.current.get(`${operation}:${String(recordId)}`),
556+
[],
557+
);
540558

541559
// [objectstack#34208] The object whose rows' actions have been reached for on
542560
// this list, or `null` until then. Until then nothing is asked: the
@@ -559,7 +577,8 @@ export function useRecordCrudVerdicts(opts: {
559577
if (wantUpdate) operations.push('update');
560578
if (wantDelete) operations.push('delete');
561579
if (!objectName || ids.length === 0 || operations.length === 0) {
562-
setVerdicts(new Map());
580+
publishedRef.current = new Map();
581+
setVerdicts(publishedRef.current);
563582
setPending(false);
564583
wireRef.current = null;
565584
return;
@@ -581,6 +600,7 @@ export function useRecordCrudVerdicts(opts: {
581600
if (typeof verdict === 'boolean') next.set(`${operation}:${id}`, verdict);
582601
}
583602
}
603+
publishedRef.current = next;
584604
setVerdicts(next);
585605
};
586606

@@ -625,7 +645,7 @@ export function useRecordCrudVerdicts(opts: {
625645
}, [objectName, ids, wantUpdate, wantDelete, updateOnMount, demanded, apiFetch, principal, invalidationNonce]);
626646

627647
return React.useMemo<RecordCrudVerdicts>(
628-
() => lookupOf(verdicts, requestVerdicts, pending, settling),
629-
[verdicts, requestVerdicts, pending, settling],
648+
() => lookupOf(verdicts, requestVerdicts, pending, settling, current),
649+
[verdicts, requestVerdicts, pending, settling, current],
630650
);
631651
}

‎ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@ export function __resetApprovalsServiceLatch(): void {
4242
approvalsServiceAbsent = false;
4343
}
4444

45+
/**
46+
* `'unanswered'` is a read that failed or answered nothing usable. It is not
47+
* asked again until the object's data is invalidated; until then the row falls
48+
* back to its `approval_status` column (fail open: the server still refuses a
49+
* write to a locked record).
50+
*/
4551
type LockAnswer = { locked: boolean } | 'asking' | 'unanswered';
4652

4753
export interface RowApprovalLocks {

0 commit comments

Comments
 (0)