From 5e609364a68ef704a3ab87af1215ee3a33a9de4b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:06:25 +0000 Subject: [PATCH 1/3] feat(console): the record page reads the data lock from its one payload request (ADR-0162 item 4) Re-applies the record-page half held back from #38994. Edit and Delete read the data layer's lock (`dataLock`), which the page payload now carries (`dataLock: true` on `POST /data/:object/:id/page`), so a closed record is greyed and worded as closed without a second request. Reads the hook sends itself (the edit dialog over a list, a refresh after a change) keep asking `GET /data/:object/:id/lock`. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ --- .changeset/37773-record-page-closed-lock.md | 19 ++ ...tent.editDialogApprovalLock-27138.test.tsx | 8 +- ...eRecordApprovals.lockSource-37195.test.tsx | 54 ++++- .../app-shell/src/hooks/useRecordApprovals.ts | 193 +++++++++++++++-- ...cordDetailView.approvalLock-25934.test.tsx | 25 ++- .../views/RecordDetailView.harness.test.tsx | 197 +++++++++++++++++- .../app-shell/src/views/RecordDetailView.tsx | 89 +++++--- .../src/views/recordDeleteHeldByMaster.ts | 37 ++-- .../app-shell/src/views/recordPagePayload.ts | 24 ++- ui/packages/i18n/src/locales/ar.ts | 2 + ui/packages/i18n/src/locales/de.ts | 2 + ui/packages/i18n/src/locales/en.ts | 2 + ui/packages/i18n/src/locales/es.ts | 2 + ui/packages/i18n/src/locales/fr.ts | 2 + ui/packages/i18n/src/locales/ja.ts | 2 + ui/packages/i18n/src/locales/ko.ts | 2 + ui/packages/i18n/src/locales/pt-BR.ts | 2 + ui/packages/i18n/src/locales/ru.ts | 2 + ui/packages/i18n/src/locales/zh-Hans.ts | 2 + ui/packages/i18n/src/locales/zh-Hant.ts | 2 + ui/packages/types/src/data.ts | 10 + 21 files changed, 609 insertions(+), 69 deletions(-) create mode 100644 .changeset/37773-record-page-closed-lock.md diff --git a/.changeset/37773-record-page-closed-lock.md b/.changeset/37773-record-page-closed-lock.md new file mode 100644 index 00000000000..a1ca8b43f88 --- /dev/null +++ b/.changeset/37773-record-page-closed-lock.md @@ -0,0 +1,19 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/types': patch +'@object-ui/i18n': patch +--- + +fix(console): a closed record's page reads as closed, not as in approval, from the page's one request + +Clause-②: no +Metadata-protocol: none + +The record page now reads the data layer's lock for its Edit and Delete, and words the reason from its `lockReason`. It asks for that lock in the request it already sends when it opens (`POST /api/v1/data/{object}/{id}/page` with `dataLock: true`), so opening a record page is still one request. It no longer asks the approvals lock read for these affordances; the approvals panel and the header's approval tag keep reading it. + +- A closed record (`lockReason: 'closed_state'`, its own state or its master's) shows Edit greyed with "This record is closed, so it can't be changed.", a "Closed" chip, and no Delete, for either `lockSource`. Its master-detail lines offer no New, Edit or Delete. A record that is closed and also held by an approval reads as closed. +- A record held by an approval behaves as before: its own approval keeps Delete, and a line of a held master does not. +- The answer is read above the caller's field permissions, so a reader who may not see the state field still gets the closed wording, and the page shows neither the field nor its value. +- When nothing on screen is a record page, the edit dialog opened over a list reads the record's lock through `GET /api/v1/data/{object}/{id}/lock` next to its approvals reads. The record page does the same when it re-reads after the record changes. Over its record page, the dialog reuses the page's answer and sends nothing. +- `RecordPagePayload` (`@object-ui/types`) declares the payload's `dataLock` part. +- New strings `detail.lockedClosed` and `detail.lockedClosedTooltip` in every console locale. diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.editDialogApprovalLock-27138.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.editDialogApprovalLock-27138.test.tsx index a7824116e9b..b06a586f902 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppContent.editDialogApprovalLock-27138.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.editDialogApprovalLock-27138.test.tsx @@ -31,6 +31,8 @@ import React from 'react'; import { render, cleanup, waitFor } from '@testing-library/react'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { registerAllFields } from '@object-ui/fields'; +// The console chain reaches `@objectstack/lint` behind a dynamic import; pay its first load at collection. +import '@objectstack/lint'; registerAllFields(); @@ -138,7 +140,11 @@ let served: Approvals = { requests: [], lock: false }; // test body returns can reach a socket; handed back in `afterAll`. const fetchSpy = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const body = url.includes('/approvals/records/') + // objectstack#37773 — the dialog's lock is the data layer's one lock read + // (`/data/:object/:id/lock`), answering `lockReason: 'approval'` here. + const body = /\/data\/[^/]+\/[^/]+\/lock$/.test(url) + ? { success: true, data: served.lock ? { locked: true, lockSource: 'record', lockReason: 'approval' } : { locked: false } } + : url.includes('/approvals/records/') ? { success: true, data: { locked: served.lock } } : url.includes('/approvals/requests?') ? { data: served.requests } diff --git a/ui/packages/app-shell/src/hooks/useRecordApprovals.lockSource-37195.test.tsx b/ui/packages/app-shell/src/hooks/useRecordApprovals.lockSource-37195.test.tsx index 13175c39842..76d73c88a4c 100644 --- a/ui/packages/app-shell/src/hooks/useRecordApprovals.lockSource-37195.test.tsx +++ b/ui/packages/app-shell/src/hooks/useRecordApprovals.lockSource-37195.test.tsx @@ -13,12 +13,20 @@ * (`POST /data/:object/:id/page`) answers the lock beside the rows whether or * not a pending request decides it, so the kind is kept beside a pending * request too — a self-held line under a held master answers `'master'`. + * + * objectstack#37773 — beside the payload's approvals lock, the hook asks the + * data layer's one lock read (`GET /data/:object/:id/lock`, ADR-0162 D9), + * which the payload does not carry, and hands it back as `dataLock` in the + * same publish. The affordances read that one: `recordClosedByLock`, + * `openApprovalOf`. */ -import { describe, it, expect, afterEach } from 'vitest'; +import { describe, it, expect, afterEach, afterAll, vi } from 'vitest'; import { renderHook, waitFor, act } from '@testing-library/react'; import { __resetRecordApprovalsStore, + openApprovalOf, + recordClosedByLock, recordLockAnswerOf, seedRecordApprovals, useRecordApprovals, @@ -36,8 +44,25 @@ const PENDING_ROW = { lock_record: true, }; +/** What the data layer's lock door answers; set per test. */ +let dataLock: Record = { locked: false }; +const dataLockGets: string[] = []; +// Installed once for the whole file: the seeded read asks the data lock door +// beside the payload, and no read may reach a socket after a test returns. +vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.endsWith(`/data/${OBJECT}/${RECORD}/lock`)) { + dataLockGets.push(url); + return new Response(JSON.stringify({ success: true, data: dataLock }), { status: 200, headers: { 'content-type': 'application/json' } }); + } + return new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } }); +})); +afterAll(() => vi.unstubAllGlobals()); + afterEach(() => { __resetRecordApprovalsStore(); + dataLock = { locked: false }; + dataLockGets.length = 0; }); async function seeded(answer: SeededRecordApprovals) { @@ -87,3 +112,30 @@ describe('recordLockAnswerOf — the two bits the lock doors serve, as the grid expect(recordLockAnswerOf(null)).toEqual({ locked: false }); }); }); + +describe('useRecordApprovals — the data layer\'s lock read beside the payload (objectstack#37773)', () => { + it('a closed record: `dataLock` names `closed_state`, so the record reads closed and no approval opens', async () => { + dataLock = { locked: true, lockSource: 'record', lockReason: 'closed_state' }; + const out = await seeded({ requests: [], lock: { locked: false } }); + expect(dataLockGets).toHaveLength(1); + expect(out.dataLock).toEqual({ locked: true, lockSource: 'record', lockReason: 'closed_state' }); + expect(recordClosedByLock(out)).toBe(true); + expect(openApprovalOf(out)).toBeNull(); + // The approvals panel's lock is the payload's, untouched. + expect(out.recordLock).toEqual({ locked: false }); + }); + + it('a record held by an approval the reader cannot see: the data lock opens it, whatever the approvals-family lock says', async () => { + dataLock = { locked: true, lockSource: 'record', lockReason: 'approval' }; + const out = await seeded({ requests: [], lock: { locked: false } }); + expect(recordClosedByLock(out)).toBe(false); + expect(openApprovalOf(out)).toEqual({ locked: true }); + }); + + it('CONTROL: the approvals-family lock alone opens no approval for the affordances', async () => { + dataLock = { locked: false }; + const out = await seeded({ requests: [], lock: { locked: true, lockSource: 'record' } }); + expect(out.recordLock).toEqual({ locked: true, lockSource: 'record' }); + expect(openApprovalOf(out)).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useRecordApprovals.ts b/ui/packages/app-shell/src/hooks/useRecordApprovals.ts index 561d41985b1..0de3d0d846d 100644 --- a/ui/packages/app-shell/src/hooks/useRecordApprovals.ts +++ b/ui/packages/app-shell/src/hooks/useRecordApprovals.ts @@ -39,6 +39,23 @@ * a composition without the approvals service answers it 501, the designed * "no lock service", which is read silently and never asked again * (objectstack#26632); any other failure still logs. + * + * Beside the approvals answer, the hook hands back the data layer's ONE lock + * read (ADR-0162 D9) as `dataLock`: whether the record is locked, by which + * lock (`lockReason`: `closed_state` or `approval`) and whose (`lockSource`). + * That answer, not the approvals-family lock, is what the record page's Edit + * and Delete and the console's edit dialog read ({@link openApprovalOf}, + * {@link recordClosedByLock}); the approvals-family `recordLock` stays the + * approvals panel's and the approval tag's. + * + * Where it comes from keeps a record page open at ONE request + * (objectstack#27627): on the read the record page's payload seeds + * (`seedRecordApprovals`), it is the payload's own `dataLock` part + * (`POST /data/:object/:id/page` with `dataLock: true`), and nothing more is + * sent. Only a read the hook sends itself — a consumer with no page payload + * behind it (the console's edit dialog opened over a list), or `refresh()` + * after a change to the record — asks `GET /data/:object/:recordId/lock` + * beside its approvals reads. */ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; @@ -47,6 +64,7 @@ import { useAdapter } from '../providers/AdapterProvider.js'; import { bearerAuthHeaders } from '../utils/authToken.js'; import type { DecisionOutputDef } from '../utils/decisionOutputParams.js'; import { createAuthenticatedFetch } from '@object-ui/auth'; +import type { RecordLockReason } from '@objectstack/spec/api'; /** The console's authenticated fetch: the stored bearer token beside the session cookie. */ function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { @@ -282,22 +300,58 @@ export function recordLockAnswerOf(answer: { locked?: unknown; lockSource?: unkn return source === 'record' || source === 'master' ? { locked: true, lockSource: source } : { locked: true }; } +/** Which lock holds a locked record, as the data layer's lock read names it (the spec's own type). */ +export type { RecordLockReason }; + +/** + * The data layer's lock read for one record (`GET /data/:object/:id/lock`, + * ADR-0162 D9): `locked`, and on a locked record which lock holds it + * (`lockReason`, `closed_state` winning when both hold) and whose + * (`lockSource`). It answers every reader who can read the record, whether or + * not field permissions let them read the state field. + */ +export interface DataRecordLock { + locked: boolean; + lockSource?: ApprovalLockSource; + lockReason?: RecordLockReason; +} + +/** The data lock read's answer off the wire, kept to the values the door serves (`RecordLockSchema`). */ +export function dataRecordLockOf(answer: { locked?: unknown; lockSource?: unknown; lockReason?: unknown } | null | undefined): DataRecordLock { + if (answer?.locked !== true) return { locked: false }; + const source = answer.lockSource === 'record' || answer.lockSource === 'master' ? answer.lockSource : undefined; + const reason = answer.lockReason === 'closed_state' || answer.lockReason === 'approval' ? answer.lockReason : undefined; + return { locked: true, ...(source ? { lockSource: source } : {}), ...(reason ? { lockReason: reason } : {}) }; +} + /** - * The open approval on the record as the approvals read found it, reduced to - * its lock policy — `resolveApprovalLock`'s `openApproval` input - * (`@object-ui/react`). A pending request the viewer can read decides with its - * own node's `lock_record`; without one, the server's record lock - * (objectstack#25934) stands in for a reader outside the slate. `null` when - * neither shows an open approval. + * Is the record closed (ADR-0162), as the data lock read answered it: its own + * declared closed state, or its master's for a master-detail line. Only an + * answer says so; no answer is not closed (fail open: the server still refuses + * a write to a closed record). A record both closed and held answers closed. + */ +export function recordClosedByLock(approvals: Pick): boolean { + return approvals.dataLock?.locked === true && approvals.dataLock.lockReason === 'closed_state'; +} + +/** + * The open approval on the record, reduced to its lock policy — + * `resolveApprovalLock`'s `openApproval` input (`@object-ui/react`). A pending + * request the viewer can read decides with its own node's `lock_record`; + * without one, the data layer's lock read answering `lockReason: 'approval'` + * stands in for a reader outside the slate (objectstack#25934): it is answered + * to every reader, and also says when an approval holds the record between its + * steps (ADR-0162 D5). `null` when neither shows an open approval. The + * approvals-family `recordLock` is not read here: it is the approvals panel's. * * The record page and the console's edit dialog (objectstack#27138) both read * the lock through this, so the dialog cannot offer an edit the page locks. */ export function openApprovalOf( - approvals: Pick, + approvals: Pick, ): { locked: boolean } | null { if (approvals.pendingRequest) return { locked: recordLockedByApproval(approvals.pendingRequest) }; - return approvals.recordLock?.locked === true ? { locked: true } : null; + return approvals.dataLock?.locked === true && approvals.dataLock.lockReason === 'approval' ? { locked: true } : null; } /** @@ -399,6 +453,14 @@ interface UseRecordApprovalsResult { * while its master is held. */ lockSource: ApprovalLockSource | null; + /** + * The data layer's lock read for the record (ADR-0162 D9), the answer the + * record page's Edit and Delete read. `null` when there is no answer to + * give: no adapter is mounted, the read has not answered, the record is not + * one the reader can read (404), or the data engine has no lock read (501, + * latched). A later failed read keeps the last answer. + */ + dataLock: DataRecordLock | null; refresh: () => Promise; } @@ -409,6 +471,7 @@ export function __resetRecordApprovalsStore(): void { listeners.clear(); latestSeq.clear(); recordLockAbsent = false; + dataLockAbsent = false; } function apiBase() { @@ -541,6 +604,8 @@ interface ApprovalsSnapshot { recordLock: RecordLockAnswer | null; /** Which approval holds the record, whenever a lock answer named it. */ lockSource: ApprovalLockSource | null; + /** The data layer's lock read (ADR-0162 D9), when it answered. */ + dataLock: DataRecordLock | null; } const EMPTY_ROWS: ApprovalRequestLite[] = []; @@ -551,6 +616,7 @@ const INITIAL_SNAPSHOT: ApprovalsSnapshot = Object.freeze({ rows: EMPTY_ROWS, recordLock: null, lockSource: null, + dataLock: null, }) as ApprovalsSnapshot; interface ApprovalsEntry { @@ -637,6 +703,70 @@ async function readRecordLock(objectName: string, recordId: string): Promise { + const path = `/data/${encodeURIComponent(objectName)}/${encodeURIComponent(recordId)}/lock`; + try { + const body = await fetchJson(path); + return dataRecordLockOf(body && typeof body.success === 'boolean' && 'data' in body ? body.data : body); + } catch (err: any) { + if (err?.status === 404) return null; + if (err?.status === 501) { + dataLockAbsent = true; + return null; + } + lockReadLogger.error('HTTP request failed', undefined, { + method: 'GET', + url: `${apiBase()}${path}`, + status: err?.status, + error: { code: err?.code, message: err?.message }, + }); + throw err; + } +} + +/** The data lock read did not answer: the last answer stands. */ +const KEEP_DATA_LOCK = Symbol('keep'); + +/** + * The page payload's `dataLock` part, settled as {@link readDataRecordLock} + * settles its GET: a 404 or 501 refusal is no answer (the 501 latched, so a + * later `refresh()` does not ask the door either), and any other refusal keeps + * the last answer. Sends nothing. + */ +function settleSeededDataLock(answer: Promise): Promise { + return answer.then( + (lock) => lock, + (err: any) => { + if (err?.status === 404) return null; + if (err?.status === 501) { + dataLockAbsent = true; + return null; + } + return KEEP_DATA_LOCK; + }, + ); +} + +/** Send the data lock read; a failure, or a latched 501 before it, keeps the last answer. */ +async function readDataLock(objectName: string, recordId: string): Promise { + if (dataLockAbsent) return KEEP_DATA_LOCK; + try { + return await readDataRecordLock(objectName, recordId); + } catch { + // Logged by the read. + return KEEP_DATA_LOCK; + } +} + /** * What the record page's ONE read answered for this record's approvals * (objectstack#27627): the request rows, the pending one already enriched by @@ -655,15 +785,21 @@ export interface SeededRecordApprovals { * wire for this record, which every consumer that mounts while it is out * joins, and its answer is published exactly as a read's. A read already on * the wire for the record is left as it is. `refresh()` still reads. + * + * `dataLock` is the same payload's data lock part (objectstack#37773): the + * seeded read publishes it as `dataLock` in the same publish as the approvals + * answer, and sends no lock read of its own. A rejection carries the part's + * refusal `status`. Left out, the seeded read leaves `dataLock` as it was. */ export function seedRecordApprovals( objectName: string, recordId: string, answer: Promise, + dataLock?: Promise, ): void { const key = JSON.stringify([objectName, recordId]); if (inFlight.has(key)) return; - void startRead(key, objectName, recordId, true, answer); + void startRead(key, objectName, recordId, true, { answer, ...(dataLock ? { dataLock } : {}) }); } /** Send the record's read and publish its answer to every consumer of the key. */ @@ -672,15 +808,33 @@ function startRead( objectName: string, recordId: string, readsLock: boolean, - seeded?: Promise, + seededBy?: { answer: Promise; dataLock?: Promise }, + approvalsOff = false, ): Promise { + const seeded = seededBy?.answer; const seq = ++readSeq; latestSeq.set(key, seq); const entry = entries.get(key); if (entry) entry.read = true; publish(key, { loading: true }); + // A seeded read takes the data lock from the record page's payload and sends + // nothing (the open stays one request, objectstack#27627). A read of the + // hook's own sends the data lock read beside the approvals reads wherever an + // adapter is mounted, approvals routes served or not (ADR-0162 D9). + const dataLockRead: Promise = seededBy + ? (seededBy.dataLock ? settleSeededDataLock(seededBy.dataLock) : Promise.resolve(KEEP_DATA_LOCK)) + : readsLock ? readDataLock(objectName, recordId) : Promise.resolve(KEEP_DATA_LOCK); + // The data lock's patch, for the approvals answer to carry: both land in one + // publish, so a closed record never draws an Edit between the two answers. + let dataLockPublished = false; + const dataLockPatch = async (): Promise> => { + const dataLock = await dataLockRead; + dataLockPublished = true; + return dataLock === KEEP_DATA_LOCK ? {} : { dataLock }; + }; const promise = (async () => { try { + if (approvalsOff) return; if (seeded) { // The payload asked the list, the pending row's `getRequest` and the // lock as one read; the rows come enriched and the lock is answered @@ -689,6 +843,7 @@ function startRead( const rows = answer.requests ?? []; const pending = rows.find((r) => r.status === 'pending'); if (!answer.lock) recordLockAbsent = true; + const dataLockAnswer = await dataLockPatch(); if (latestSeq.get(key) !== seq) return; // Typed by the payload (`RecordPagePayload.approvals.lock`, the spec's // `RecordPageApprovalsSchema`): the kind rides a locked answer only. @@ -699,6 +854,7 @@ function startRead( answered: true, recordLock: !pending ? lock : null, lockSource: lock?.locked === true ? lock.lockSource ?? null : null, + ...dataLockAnswer, }); return; } @@ -724,8 +880,10 @@ function startRead( // leaves none; a failure after an answer keeps it, as the rows are. } } + const dataLockAnswer = await dataLockPatch(); if (latestSeq.get(key) !== seq) return; publish(key, { + ...dataLockAnswer, rows: full ? rows.map((r) => (r === pending ? full : r)) : rows, available: true, answered: true, @@ -741,6 +899,11 @@ function startRead( } // Other errors are transient — silently keep last state. } finally { + // Not carried by an approvals answer (none came): published on its own. + if (!dataLockPublished) { + const dataLock = await dataLockRead; + if (dataLock !== KEEP_DATA_LOCK && latestSeq.get(key) === seq) publish(key, { dataLock }); + } if (inFlight.get(key)?.seq === seq) inFlight.delete(key); if (latestSeq.get(key) === seq) publish(key, { loading: false }); if (!entries.has(key) && !inFlight.has(key)) latestSeq.delete(key); @@ -811,8 +974,9 @@ export function useRecordApprovals( // Join the read on the wire, or the answer another consumer already has; // read only when neither exists. The entry may be new while a read is in // flight (StrictMode's replayed mount): that read publishes into it. - if (entry && !entry.read && !inFlight.has(readKey) && !unavailableRef.current) { - void startRead(readKey, objectName, recordId, readsLock); + // With the approvals routes absent, the data lock is still read. + if (entry && !entry.read && !inFlight.has(readKey) && (!unavailableRef.current || readsLock)) { + void startRead(readKey, objectName, recordId, readsLock, undefined, unavailableRef.current); } else if (entry && inFlight.has(readKey)) { entry.read = true; if (!entry.snapshot.loading) publish(readKey, { loading: true }); @@ -822,8 +986,8 @@ export function useRecordApprovals( const refresh = useCallback(async () => { if (!objectName || !recordId || !readKey) return; - if (unavailableRef.current) return; - await startRead(readKey, objectName, recordId, readsLock); + if (unavailableRef.current && !readsLock) return; + await startRead(readKey, objectName, recordId, readsLock, undefined, unavailableRef.current); }, [objectName, recordId, readKey, readsLock]); const requests = readKey === null ? EMPTY_ROWS : snapshot.rows; @@ -862,6 +1026,7 @@ export function useRecordApprovals( latestRequest, recordLock: readKey === null ? null : snapshot.recordLock, lockSource: readKey === null ? null : snapshot.lockSource, + dataLock: readKey === null ? null : snapshot.dataLock, refresh, }; } diff --git a/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-25934.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-25934.test.tsx index d9b5c6ec076..0e0a1abdd1f 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-25934.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-25934.test.tsx @@ -15,9 +15,12 @@ * override reads `GET /approvals/requests?object=…&recordId=…` as * `200 { data: [] }` while a `lockRecord: true` approval runs. The page took * that for "no approval is running" and offered inline edit, and the save - * answered `409 RECORD_LOCKED`. The page now asks the record's own lock - * (`GET /approvals/records/:object/:recordId/lock`, answered to every reader) - * when the list finds no pending request. + * answered `409 RECORD_LOCKED`. The page now asks the record's own lock, + * answered to every reader: since objectstack#37773 the affordances read the + * data layer's one lock read (`GET /data/:object/:recordId/lock`, ADR-0162 + * D9), whose `lockReason: 'approval'` says a locking approval holds it; the + * approvals-family read (`GET /approvals/records/:object/:recordId/lock`) is + * still asked when the list finds no pending request, for the header's tag. * * A composition without the approvals service answers that read 501, its * designed "no lock service": the page reads it silently and does not ask @@ -34,10 +37,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, waitFor, cleanup } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; -// The approvals reads go out through the authenticated fetch too; they answer from -// the file's wire double, as before. +// The approvals reads, and the data layer's lock read (objectstack#37773), go +// out through the authenticated fetch too; they answer from the file's wire +// double, as before. const authFetchSpy = vi.fn(async (url: string, init?: RequestInit) => - String(url).includes('/approvals/') + String(url).includes('/approvals/') || /\/data\/[^/]+\/[^/]+\/lock$/.test(String(url)) ? fetch(url, init) : new Response(JSON.stringify({ data: {} }), { status: 200, @@ -154,6 +158,8 @@ type ListAnswer = { row: Record | null } | { absent: number }; type LockAnswer = { locked: boolean } | { refused: number }; const LOCK_PATH = `/approvals/records/${OBJECT_NAME}/${RECORD_ID}/lock`; +/** The data layer's lock read, which answers as the approvals one does here. */ +const DATA_LOCK_PATH = `/data/${OBJECT_NAME}/${RECORD_ID}/lock`; function stubApprovalsApi(answer: ListAnswer, lock: LockAnswer) { listGets = []; @@ -162,6 +168,13 @@ function stubApprovalsApi(answer: ListAnswer, lock: LockAnswer) { 'fetch', vi.fn(async (url: string) => { const u = String(url); + if (u.endsWith(DATA_LOCK_PATH)) { + const locked = 'locked' in lock && lock.locked; + return jsonResponse(200, { + success: true, + data: locked ? { locked: true, lockSource: 'record', lockReason: 'approval' } : { locked: false }, + }); + } if (u.endsWith(LOCK_PATH)) { lockGets.push(u); if ('refused' in lock) { diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index 1604a941ff4..31912711a5e 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -3870,9 +3870,10 @@ describe('RecordDetailView.approvalActivityLine-35723', () => { * the server deletes it and cancels the request; an unheld record keeps it, * and so does a locked answer that names no kind (only an answer says so). * - * The page reads the lock through `GET /approvals/records/:object/:id/lock` - * (no `getRecordPage` on this adapter); the composite payload's half is pinned - * in `useRecordApprovals.lockSource-37195.test.tsx`. + * Since objectstack#37773 the page reads that answer off the data layer's one + * lock read (`GET /data/:object/:id/lock`, ADR-0162 D9), under + * `lockReason: 'approval'`; the closed reason is pinned in + * `RecordDetailView.closedLock-37773` below. */ describe('RecordDetailView.deleteFollowsLockSource-37195', () => { restoreAfterBlock(); @@ -3885,7 +3886,7 @@ describe('RecordDetailView.deleteFollowsLockSource-37195', () => { managedBy: 'platform', fields: { id: { type: 'text', label: 'Id' }, name: { type: 'text', label: 'Name' } }, }]; - const LOCK_PATH = `/approvals/records/${OBJECT_NAME}/${RECORD_ID}/lock`; + const LOCK_PATH = `/data/${OBJECT_NAME}/${RECORD_ID}/lock`; let lockGets: string[] = []; function respond(body: unknown): Response { @@ -3960,11 +3961,11 @@ describe('RecordDetailView.deleteFollowsLockSource-37195', () => { }); it('a line held by its master (`lockSource: master`) offers no Delete', async () => { - expect(await overflowAfterLockRead({ locked: true, lockSource: 'master' })).not.toContain('Delete'); + expect(await overflowAfterLockRead({ locked: true, lockSource: 'master', lockReason: 'approval' })).not.toContain('Delete'); }); it('CONTROL: a record held by its own approval (`lockSource: record`) keeps Delete', async () => { - expect(await overflowAfterLockRead({ locked: true, lockSource: 'record' })).toContain('Delete'); + expect(await overflowAfterLockRead({ locked: true, lockSource: 'record', lockReason: 'approval' })).toContain('Delete'); }); it('CONTROL: an unheld record keeps Delete, and so does a locked answer that names no kind', async () => { @@ -3975,3 +3976,187 @@ describe('RecordDetailView.deleteFollowsLockSource-37195', () => { expect(await overflowAfterLockRead({ locked: true })).toContain('Delete'); }); }); + +// ── RecordDetailView.closedLock-37773 ─────────────────────────────────────── + +/** + * objectstack#37773 (ADR-0162 item 4) — the record page reads the data layer's + * one lock read (`GET /data/:object/:id/lock`, ADR-0162 D9) and words the + * reason from `lockReason`: "closed" is not "in approval". + * + * - A closed record (its own state, or its master's): Edit drawn greyed with + * the closed sentence, the 「Closed」 chip, no Delete — for either source. + * - A record both closed and held reads as closed. + * - A reader who may not see the state field: the served object here declares + * no state field at all, and the page still says closed, showing neither the + * field nor a value. + * - CONTROL: a record held by its own approval keeps today's page: no Edit, + * Delete kept. + * - The approvals-family lock door is not what the affordances read: here it + * answers unlocked throughout. + */ +describe('RecordDetailView.closedLock-37773', () => { + restoreAfterBlock(); + + const OBJECT_NAME = 'os_37773_invoice'; + const RECORD_ID = 'INV-1'; + const CLOSED_SENTENCE = "This record is closed, so it can't be changed."; + // No `status` field: the reader may not see the state field. + const OBJECTS = [{ + name: OBJECT_NAME, + label: 'Invoice', + managedBy: 'platform', + fields: { id: { type: 'text', label: 'Id' }, name: { type: 'text', label: 'Name' } }, + }]; + const DATA_LOCK_PATH = `/data/${OBJECT_NAME}/${RECORD_ID}/lock`; + const PENDING = { + id: 'req_inv', process_name: 'flow:invoice_review', object_name: OBJECT_NAME, record_id: RECORD_ID, + status: 'pending', submitter_id: 'u_other', pending_approvers: ['u_manager'], lock_record: true, + }; + let dataLockGets: string[] = []; + + function respond(body: unknown): Response { + return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); + } + + function stubWire(dataLock: Record, requests: unknown[] = []) { + dataLockGets = []; + vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + if (url.endsWith(DATA_LOCK_PATH)) { + dataLockGets.push(url); + return respond({ success: true, data: dataLock }); + } + // The approvals-family lock answers unlocked: it decides no affordance. + if (url.includes('/approvals/records/')) return respond({ success: true, data: { locked: false } }); + if (url.includes('/approvals/requests?object=')) return respond({ data: requests }); + if (url.endsWith('/approvals/requests/req_inv')) return respond(PENDING); + if (url.endsWith('/security/explain')) { + return respond({ allowed: true, record: { recordId: RECORD_ID, visible: true } }); + } + return respond({ data: [] }); + })); + } + + function headerEdit(): HTMLButtonElement | null { + const bar = document.querySelector('[role="toolbar"]'); + if (!bar) return null; + return (Array.from(bar.querySelectorAll('button')) + .find((b) => (b.textContent ?? '').trim().toLowerCase() === 'edit') as HTMLButtonElement | undefined) ?? null; + } + + /** The reason a greyed header Edit gives: its accessible description, else its title. */ + function editReason(button: HTMLButtonElement): string { + const describedBy = button.getAttribute('aria-describedby'); + const described = describedBy + ? describedBy.split(/\s+/).map((id) => document.getElementById(id)?.textContent ?? '').join(' ') + : ''; + return `${described} ${button.getAttribute('title') ?? ''} ${button.parentElement?.getAttribute('title') ?? ''}`; + } + + async function mountPage(dataLock: Record, requests: unknown[] = []) { + stubWire(dataLock, requests); + const dataSource = { + find: vi.fn(async () => ({ data: [] })), + findOne: vi.fn(async () => ({ id: RECORD_ID, name: 'Invoice one' })), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + } as any; + const metadata = { + objects: OBJECTS, pages: [], loading: false, error: null, + refresh: async () => {}, invalidate: () => {}, ensureType: async () => [], + getItem: async () => null, getItemsByType: () => [], + } as any; + const adapter = { getClient: () => ({ approvals: { getRecordLock: vi.fn() } }) } as any; + render( + + + + {}} + objectNameOverride={OBJECT_NAME} + recordIdOverride={RECORD_ID} + /> + + + , + ); + await waitFor(() => expect(dataLockGets.length).toBeGreaterThan(0)); + await waitFor(() => expect(document.querySelector('[role="toolbar"]')).toBeTruthy()); + await act(async () => { + for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); + }); + } + + async function overflowItems(): Promise { + const trigger = screen.getByRole('button', { name: /more actions/i }); + fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + await waitFor(() => expect(screen.getByRole('menu')).toBeTruthy()); + return screen.getAllByRole('menuitem').map((el) => (el.textContent ?? '').trim()); + } + + beforeEach(() => { + __resetRecordApprovalsStore(); + __clearRecordEditableCache(); + }); + + afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + __resetRecordApprovalsStore(); + }); + + it('a closed record: Edit greyed with the closed sentence, the Closed chip, no Delete — and no state field or value', async () => { + await mountPage({ locked: true, lockSource: 'record', lockReason: 'closed_state' }); + await waitFor(() => expect(headerEdit()).toBeDisabled()); + expect(editReason(headerEdit()!)).toContain(CLOSED_SENTENCE); + const chip = await screen.findByTestId('record-closed-lock'); + expect(chip).toHaveTextContent('Closed'); + expect(chip).toHaveAttribute('title', CLOSED_SENTENCE); + // Not worded as an approval. + expect(screen.queryByTestId('record-approval-tag')).toBeNull(); + expect(document.body.textContent).not.toMatch(/in approval/i); + // The page shows neither the state field nor its value. + expect(document.body.textContent).not.toMatch(/\bstatus\b|\bpaid\b/i); + expect(await overflowItems()).not.toContain('Delete'); + }); + + it('a line of a closed master: no Delete either, and Edit greyed with the closed sentence', async () => { + await mountPage({ locked: true, lockSource: 'master', lockReason: 'closed_state' }); + await waitFor(() => expect(headerEdit()).toBeDisabled()); + expect(editReason(headerEdit()!)).toContain(CLOSED_SENTENCE); + expect(await overflowItems()).not.toContain('Delete'); + }); + + it('a record both closed and held by an approval reads as closed', async () => { + await mountPage({ locked: true, lockSource: 'record', lockReason: 'closed_state' }, [PENDING]); + await waitFor(() => expect(screen.getByTestId('record-approval-tag')).toBeTruthy()); + await waitFor(() => expect(headerEdit()).toBeDisabled()); + expect(editReason(headerEdit()!)).toContain(CLOSED_SENTENCE); + // The approval's tag still names the approval, but not as the lock. + expect(screen.getByTestId('record-approval-tag')).not.toHaveAttribute('data-record-approval-locked'); + expect(screen.getByTestId('record-closed-lock')).toBeTruthy(); + expect(await overflowItems()).not.toContain('Delete'); + }); + + it('CONTROL: a record held by its own approval keeps today\'s page: no Edit, Delete kept, no Closed chip', async () => { + await mountPage({ locked: true, lockSource: 'record', lockReason: 'approval' }); + await act(async () => { + for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); + }); + expect(headerEdit()).toBeNull(); + expect(screen.queryByTestId('record-closed-lock')).toBeNull(); + expect(await overflowItems()).toContain('Delete'); + }); + + it('CONTROL: an unlocked record keeps a live Edit and Delete', async () => { + await mountPage({ locked: false }); + await waitFor(() => expect(headerEdit()).not.toBeNull()); + expect(headerEdit()).not.toBeDisabled(); + expect(screen.queryByTestId('record-closed-lock')).toBeNull(); + expect(await overflowItems()).toContain('Delete'); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index b6cfec49cec..b7d3e6d6a15 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -95,8 +95,8 @@ import type { DataSource, FeedItem, Reaction, RecordPageOperation, RecordPagePay import { arrangedHeaderActions, placedHeaderActions } from '@object-ui/types'; import type { ActionContext, ActionDef, ActionParamDef, ActionResult, ConfirmationHandler, ParamCollectionHandler } from '@object-ui/core'; import type { ConsoleActionDispatch } from '../consoleActionDispatch.js'; -import { useRecordApprovals, openApprovalOf, isSubmitterOf } from '../hooks/useRecordApprovals.js'; -import { recordDeleteHeldByMaster } from './recordDeleteHeldByMaster.js'; +import { useRecordApprovals, openApprovalOf, isSubmitterOf, recordClosedByLock } from '../hooks/useRecordApprovals.js'; +import { recordDeleteRefusedByLock } from './recordDeleteHeldByMaster.js'; import { RecordAttachmentsPanel } from './RecordAttachmentsPanel.js'; import { RecordApprovalsPanel, stepDisplayText } from './RecordApprovalsPanel.js'; import { ApprovalBandOnceScope, RecordStageMenu, RelatedListConditionsSlotContext } from '@object-ui/plugin-detail'; @@ -2577,16 +2577,28 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // // The list serves a request only to its participants, so a reader outside // the slate reads it empty while a locking approval runs (objectstack#25934). - // For them the open approval is the server's record lock: `{ locked: true }` - // says a pending request from a locking node exists, which is rule 1's input - // exactly. No lock answer (no approvals service answers its route 501) is no - // open approval, so rule 2 is unchanged. + // For them the open approval is the data layer's lock read answering + // `lockReason: 'approval'` (ADR-0162 D9, `openApprovalOf`), which is rule 1's + // input exactly. No such answer is no open approval, so rule 2 is unchanged. + // The approvals-family lock (`recordLock`) still names the approval in the + // header's tag below; it decides no affordance. const lockedForReader = !approvals.pendingRequest && approvals.recordLock?.locked === true; const { pending: approvalPending, locked: approvalLocked } = resolveApprovalLock({ readAnswered: approvals.answered, openApproval: openApprovalOf(approvals), recordStatus: (pageRecord as any)?.approval_status, }); + // ADR-0162 — the record is CLOSED (its own declared closed state, or its + // master's for a master-detail line), as the data layer's lock read says to + // every reader, whether or not they may read the state field. "Closed" and + // "in approval" are different things to tell a reader: a closed record + // keeps its Edit drawn, greyed, with this sentence, and a record both closed + // and held reads as closed. Nothing else is shown: not the state field, not + // its value. + const recordClosed = recordClosedByLock(approvals); + const closedLockReason = String(t('detail.lockedClosedTooltip', { + defaultValue: 'This record is closed, so it can\'t be changed.', + })); // objectstack#35599 — the record page's EDIT STATE (`recordEditState.tsx`): // on a page that draws master-detail body tables, Edit turns the overview // into a form — the fields become inputs, the body tables editable lines — @@ -2908,6 +2920,10 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri explain, fieldAccess: typeof dataSource.getRecordFieldAccess === 'function', approvals: true, + // objectstack#37773 — the data layer's lock (ADR-0162 D9) rides the same + // request: Edit and Delete read it, and a closed record is known without + // a second read. + dataLock: true, }); }, [hasPage, objectName, pureRecordId, dataSource, objectDef, editOffByObject, deleteOffByObject, changeOwnerOffer.asks, pageRecordExpand, effectivePage, assignedPage, childRelations, objects, perms]); // The stream parts ride whichever payload the plan above asks; they never ask @@ -5421,9 +5437,10 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // subtracts. const affordances = { edit: objectAffordances.edit && recordWriteAllowed && editVisible, - // objectstack#37195: a line held by its MASTER's approval offers no - // Delete — the server refuses it — as the grid's row menu does. - delete: objectAffordances.delete && recordDeleteAllowed && deleteVisible && !recordDeleteHeldByMaster(approvals), + // objectstack#37195 / ADR-0162 D6: a closed record (either source), and a + // line held by its MASTER's approval, offer no Delete — the server + // refuses it — as the grid's row menu does. + delete: objectAffordances.delete && recordDeleteAllowed && deleteVisible && !recordDeleteRefusedByLock(approvals), }; const items: ActionDef[] = []; // [objectstack ADR-0142 D4] Claim, ahead of Edit: on a record sitting in a @@ -5443,10 +5460,11 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri } // objectstack#35593 — a record an approval locks draws no Edit at all: the // header's approval tag says why it cannot be changed. Every other reason - // for "off" keeps Edit drawn and greyed, as below. + // for "off" keeps Edit drawn and greyed, as below — a closed record + // (ADR-0162) among them, also when an approval holds it too. // objectstack#35599 — in the edit state the Edit button's place holds the // state's Cancel and Save, through the same system-action props. - if (affordances.edit && !approvalLocked && recordEditState) { + if (affordances.edit && !approvalLocked && !recordClosed && recordEditState) { items.push({ name: 'sys_record_edit_cancel', label: t('detail.cancel', { defaultValue: 'Cancel' }), @@ -5474,15 +5492,18 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri onClick: () => { void recordEditControlRef.current?.save(); }, } as any); } - if (affordances.edit && !approvalLocked && !recordEditState) { - const editOff = approvalLocked || editDisabledByPredicate || editLockedByState; + if (affordances.edit && (!approvalLocked || recordClosed) && !recordEditState) { + const editOff = approvalLocked || recordClosed || editDisabledByPredicate || editLockedByState; // objectstack#35135 — the reason a predicate-disabled Edit gives. The // approval band and the state-lock badge explain their own locks, so // the generic sentence is spoken only when `edit.disabledWhen` is what // turned Edit off and neither of those draws: one reason at a time. - const editReason = editDisabledByPredicate && !approvalLocked && !editLockedByState - ? predicateDisabledReason - : undefined; + // ADR-0162 — a closed record's Edit says it is closed, first. + const editReason = recordClosed + ? closedLockReason + : editDisabledByPredicate && !approvalLocked && !editLockedByState + ? predicateDisabledReason + : undefined; // Single primary Edit CTA → opens the full record form. Inline editing // is no longer a standalone header button; it is entered by // double-clicking a field (or its hover pencil) in the record body, @@ -6133,7 +6154,20 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // only), as the DetailView lock band draws the approval lock's. Not while // an approval lock already explains a disabled Edit. const stateLockLabel = t('detail.lockedByState', { defaultValue: 'Not editable in its current state' }); - const stateLockChip = editLockedByState && !approvalLocked ? ( + // ADR-0162 — a closed record's chip, in the state chip's place: it names no + // field and no value, so a reader who may not see the state field reads it too. + const closedLockLabel = t('detail.lockedClosed', { defaultValue: 'Closed' }); + const stateLockChip = recordClosed ? ( + + + ) : editLockedByState && !approvalLocked ? ( {approvalTagText} @@ -6372,11 +6406,14 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri resolveRecordHeaderActionGates(objectDef, perms).edit && recordWriteAllowed && !approvalLocked + && !recordClosed && editVisible && !editDisabledByPredicate && !editLockedByState } - locked={approvalLocked} + // ADR-0162 — a record both closed and held reads as closed: the band + // keeps the approval's status, and the closed chip names the lock. + locked={approvalLocked && !recordClosed} approvalPending={approvalPending} approvalReadAnswered={approvals.answered} approvalProgress={approvalProgress} @@ -6599,9 +6636,11 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri parentRecord={pageRecord} parentObjectFields={predicateFields} /* objectstack#35599, ruling A (「一起锁」) — while an approval - locks this record, its master-detail children draw no New, - Edit or Delete: the server refuses each RECORD_LOCKED. */ - serve={approvalLocked + locks this record, or it is closed (ADR-0162 D3: a closed + record's master-detail lines are closed with it), its + master-detail children draw no New, Edit or Delete: the + server refuses each RECORD_LOCKED. */ + serve={approvalLocked || recordClosed ? (bridge) => withDetailWritesWithheld(bridge, (child, fk) => isMasterDetailChild(objects, objectName, child, fk)) : undefined} > @@ -6751,8 +6790,8 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri data={pageRecord} refresh={notifyRecordChanged} fieldLabelFor={(name: string) => (objectDef as any)?.fields?.[name]?.label || fieldLabel(objectName || '', name, name)} - locked={approvalLocked} - lockedHint={t('detail.lockedTooltip', { + locked={approvalLocked || recordClosed} + lockedHint={recordClosed ? closedLockReason : t('detail.lockedTooltip', { defaultValue: 'This record has a pending approval request; editing is locked', })} />} diff --git a/ui/packages/app-shell/src/views/recordDeleteHeldByMaster.ts b/ui/packages/app-shell/src/views/recordDeleteHeldByMaster.ts index 182769d3c7a..5a435d64db0 100644 --- a/ui/packages/app-shell/src/views/recordDeleteHeldByMaster.ts +++ b/ui/packages/app-shell/src/views/recordDeleteHeldByMaster.ts @@ -1,21 +1,30 @@ /** - * objectstack#37195 — does the record page's Delete go, because the record is - * a master-detail line held by its MASTER's approval? + * Does the record page's Delete go, because the server refuses a caller's + * delete of this record under the lock that holds it? * - * The lock doors say which approval holds a locked record (`lockSource`, - * ruling 7148474531 on objectstack#37151): its own (`'record'`) or its - * master's (`'master'`, which wins when both hold). The server deletes a - * record held by its own approval and cancels the request, so that Delete - * stays; the detail-row lock hook refuses a line's delete with - * `RECORD_LOCKED` while its master is held, so that Delete goes. This is the - * rule the grid's row menu applies (`useRowApprovalLocks.heldByMaster`, - * `objectGridActionsColumn`): only an answer says so — no answer, or one that - * names no kind, keeps Delete (fail open; the server still refuses). + * Read off the data layer's one lock read (ADR-0162 D9, `dataLock`), reason + * first: + * + * - `lockReason: 'closed_state'` — a closed record, by its own state or its + * master's: a caller's delete is refused for either source (ADR-0162 D6). + * - `lockReason: 'approval'` — the published rule (objectstack#37195, ruling + * 7148474531 on objectstack#37151): a record held by its OWN approval + * (`lockSource: 'record'`) is deleted by the server, which cancels the + * request, so that Delete stays; a master-detail line held by its MASTER's + * approval (`'master'`) is refused by the detail-row lock hook with + * `RECORD_LOCKED`, so that Delete goes. + * + * This is the rule the grid's row menu applies + * (`useRowApprovalLocks.deleteRefused`, `objectGridActionsColumn`): only an + * answer says so — no answer keeps Delete (fail open; the server still + * refuses). * * Feedback only: it decides which affordance is SHOWN, never who may delete. */ -import type { ApprovalLockSource } from '../hooks/useRecordApprovals.js'; +import type { DataRecordLock } from '../hooks/useRecordApprovals.js'; -export function recordDeleteHeldByMaster(approvals: { lockSource: ApprovalLockSource | null }): boolean { - return approvals.lockSource === 'master'; +export function recordDeleteRefusedByLock(approvals: { dataLock: DataRecordLock | null }): boolean { + const lock = approvals.dataLock; + if (lock?.locked !== true) return false; + return lock.lockReason === 'closed_state' || lock.lockSource === 'master'; } diff --git a/ui/packages/app-shell/src/views/recordPagePayload.ts b/ui/packages/app-shell/src/views/recordPagePayload.ts index e375b98db31..67d04b9e5cc 100644 --- a/ui/packages/app-shell/src/views/recordPagePayload.ts +++ b/ui/packages/app-shell/src/views/recordPagePayload.ts @@ -25,6 +25,9 @@ * - the `transfer` decision → `seedQueueClaimDecision` (Claim); * - the field projection → `seedRecordFieldAccess` (the in-place edit blocks); * - the approval rows and lock → `seedRecordApprovals`; + * - the data layer's lock (`dataLock`, ADR-0162 D9) → `seedRecordApprovals` + * too, as the hook's `dataLock`, which the header's Edit and Delete read + * (objectstack#37773), so a closed record is known from the same request; * - the attachments' count and newest rows → `RelatedCountStore.seed`, under * the key the Attachments tab badge counts and the panel takes its rows * from (objectstack#28470); @@ -71,7 +74,12 @@ import type { RecordPagePartRefusal, RecordPageRequest, } from '@object-ui/types'; -import { seedRecordApprovals, type ApprovalRequestLite } from '../hooks/useRecordApprovals.js'; +import { + dataRecordLockOf, + seedRecordApprovals, + type ApprovalRequestLite, + type DataRecordLock, +} from '../hooks/useRecordApprovals.js'; /** The most related lists one payload names (the route's own cap). */ const MAX_RELATED = 50; @@ -237,6 +245,8 @@ export function recordPageRequestOf(plan: { explain: RecordPageOperation[]; fieldAccess: boolean; approvals: boolean; + /** The record's data lock (ADR-0162 D9, objectstack#37773). */ + dataLock?: boolean; /** The record's discussion (objectstack#28470). */ discussion?: boolean; /** How many activity rows, when the page draws the feed's activity. */ @@ -259,6 +269,7 @@ export function recordPageRequestOf(plan: { ...(plan.explain.length > 0 ? { explain: plan.explain } : {}), ...(plan.fieldAccess ? { fieldAccess: true } : {}), ...(plan.approvals ? { approvals: true } : {}), + ...(plan.dataLock ? { dataLock: true } : {}), ...(plan.discussion ? { discussion: true } : {}), ...(plan.activity !== undefined ? { activity: { top: plan.activity } } : {}), ...(plan.attachments !== undefined ? { attachments: { top: plan.attachments } } : {}), @@ -397,6 +408,8 @@ export function seedRecordPageReaders(args: { explain: RecordPageOperation[]; fieldAccess: boolean; approvals: boolean; + /** Whether the payload asked the record's data lock (objectstack#37773). */ + dataLock?: boolean; /** How many attachments the payload asked, when it asked them. */ attachments?: number; }): void { @@ -475,6 +488,13 @@ export function seedRecordPageReaders(args: { if (!page || !answer) throw refusal(undefined, 'No approvals answer'); if (isRefused(answer)) throw refusal(answer.error, 'Approvals refused'); return { requests: answer.requests as ApprovalRequestLite[], lock: answer.lock }; - }))); + })), args.dataLock ? quiet(payload.then((page): DataRecordLock | null => { + // objectstack#37773 — the data lock rides the approvals read the hook + // publishes, so the header's Edit and Delete never draw between the two. + const answer = page?.dataLock; + if (!page || !answer) return null; + if (isRefused(answer)) throw refusal(answer.error, 'Data lock refused'); + return dataRecordLockOf(answer); + })) : undefined); } } diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 6e4cd350570..f026a7d9694 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1786,6 +1786,8 @@ const ar = { lockedByApproval: "مقفل للموافقة", lockedTooltip: "يحتوي هذا السجل على طلب موافقة معلق؛ التعديل مقفل", lockedByState: "غير قابل للتعديل في حالته الحالية", + lockedClosed: "مغلق", + lockedClosedTooltip: "هذا السجل مغلق ولا يمكن تغييره.", bodyTableRow: "الصف {{row}}", bodyTablesReadOnlyBulk: "تبقى جداول البنود هذه للقراءة فقط أثناء التعديل: حفظها مع السجل يتطلب تمكين الكتابة المجمعة على كائناتها. لا يزال بإمكانك تعديل حقول السجل نفسه وحفظها.", discardInlineEditsMessage: "لديك تغييرات غير محفوظة على حقول هذا السجل. تجاهلها لتعديل السجل بالكامل، أو تابع التعديل واحفظها أولاً.", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index fb4788529c3..76b505ec64a 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1601,6 +1601,8 @@ const de = { lockedByApproval: "Zur Genehmigung gesperrt", lockedTooltip: "Dieser Datensatz hat eine ausstehende Genehmigungsanfrage; die Bearbeitung ist gesperrt", lockedByState: "Im aktuellen Status nicht bearbeitbar", + lockedClosed: "Abgeschlossen", + lockedClosedTooltip: "Dieser Datensatz ist abgeschlossen und kann nicht mehr geändert werden.", bodyTableRow: "Zeile {{row}}", bodyTablesReadOnlyBulk: "Diese Positionstabellen bleiben beim Bearbeiten schreibgeschützt: Um sie zusammen mit dem Datensatz zu speichern, müssen für ihre Objekte Massenschreibvorgänge aktiviert sein. Die Felder des Datensatzes selbst können weiterhin bearbeitet und gespeichert werden.", discardInlineEditsMessage: "Sie haben ungespeicherte Änderungen an den Feldern dieses Datensatzes. Verwerfen Sie sie, um den ganzen Datensatz zu bearbeiten, oder bearbeiten Sie weiter und speichern Sie sie zuerst.", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index b44a80af555..a12e5f3b8da 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1723,6 +1723,8 @@ const en = { lockedByApproval: 'Locked for approval', lockedTooltip: 'This record has a pending approval request; editing is locked', lockedByState: 'Not editable in its current state', + lockedClosed: 'Closed', + lockedClosedTooltip: 'This record is closed, so it can\'t be changed.', bodyTableRow: 'Row {{row}}', bodyTablesReadOnlyBulk: 'These line tables stay read-only while you edit: saving them together with the record needs bulk writes enabled on their objects. The record\'s own fields can still be edited and saved.', discardInlineEditsMessage: 'You have unsaved changes to this record\'s fields. Discard them to edit the whole record, or keep editing and save them first.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 8538f879c1f..6c8ff1706b5 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1647,6 +1647,8 @@ const es = { lockedByApproval: "Bloqueado para aprobación", lockedTooltip: "Este registro tiene una solicitud de aprobación pendiente; la edición está bloqueada", lockedByState: "No editable en su estado actual", + lockedClosed: "Cerrado", + lockedClosedTooltip: "Este registro está cerrado y ya no se puede modificar.", bodyTableRow: "Fila {{row}}", bodyTablesReadOnlyBulk: "Estas tablas de líneas quedan en solo lectura mientras editas: guardarlas junto con el registro requiere habilitar escrituras masivas en sus objetos. Los campos del propio registro aún se pueden editar y guardar.", discardInlineEditsMessage: "Tienes cambios sin guardar en los campos de este registro. Descártalos para editar el registro completo, o sigue editando y guárdalos primero.", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index fc3a07a562f..6e6689e3775 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1651,6 +1651,8 @@ const fr = { lockedByApproval: "Verrouillé pour approbation", lockedTooltip: "Cet enregistrement a une demande d'approbation en attente ; la modification est verrouillée", lockedByState: "Non modifiable dans son état actuel", + lockedClosed: "Clôturé", + lockedClosedTooltip: "Cet enregistrement est clôturé et ne peut plus être modifié.", bodyTableRow: "Ligne {{row}}", bodyTablesReadOnlyBulk: "Ces tableaux de lignes restent en lecture seule pendant la modification : les enregistrer avec la fiche exige que les écritures en masse soient activées sur leurs objets. Les champs de la fiche elle-même restent modifiables et enregistrables.", discardInlineEditsMessage: "Vous avez des modifications non enregistrées dans les champs de cet enregistrement. Ignorez-les pour modifier l'enregistrement entier, ou continuez la modification et enregistrez-les d'abord.", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 61b4899cfe9..2ad40b73947 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1685,6 +1685,8 @@ const ja = { lockedByApproval: "承認のためロック中", lockedTooltip: "このレコードには承認待ちのリクエストがあります。編集はロックされています", lockedByState: "現在の状態では編集できません", + lockedClosed: "クローズ済み", + lockedClosedTooltip: "このレコードはクローズ済みのため変更できません。", bodyTableRow: "{{row}} 行目", bodyTablesReadOnlyBulk: "編集中、これらの明細テーブルは読み取り専用です。レコードと一緒に保存するには、それぞれのオブジェクトで一括書き込みを有効にする必要があります。レコード自体のフィールドは引き続き編集・保存できます。", discardInlineEditsMessage: "このレコードの項目に未保存の変更があります。破棄してレコード全体を編集するか、編集を続けて先に保存してください。", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 2c1c5a0a468..4e04adcc9fe 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1601,6 +1601,8 @@ const ko = { lockedByApproval: "승인을 위해 잠김", lockedTooltip: "이 레코드에 대기 중인 승인 요청이 있습니다. 편집이 잠겨 있습니다", lockedByState: "현재 상태에서는 편집할 수 없습니다", + lockedClosed: "마감됨", + lockedClosedTooltip: "이 레코드는 마감되어 변경할 수 없습니다.", bodyTableRow: "{{row}}행", bodyTablesReadOnlyBulk: "편집하는 동안 이 항목 표는 읽기 전용입니다. 레코드와 함께 저장하려면 해당 개체에서 일괄 쓰기를 사용하도록 설정해야 합니다. 레코드 자체의 필드는 계속 편집하고 저장할 수 있습니다.", discardInlineEditsMessage: "이 레코드의 필드에 저장하지 않은 변경 사항이 있습니다. 변경 사항을 버리고 레코드 전체를 편집하거나, 계속 편집하여 먼저 저장하세요.", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index e3701de9a95..a9d836ce3ab 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1651,6 +1651,8 @@ const pt = { lockedByApproval: "Bloqueado para aprovação", lockedTooltip: "Este registro tem uma solicitação de aprovação pendente; a edição está bloqueada", lockedByState: "Não editável no estado atual", + lockedClosed: "Fechado", + lockedClosedTooltip: "Este registro está fechado e não pode mais ser alterado.", bodyTableRow: "Linha {{row}}", bodyTablesReadOnlyBulk: "Estas tabelas de itens ficam somente leitura durante a edição: salvá-las junto com o registro exige gravações em massa habilitadas em seus objetos. Os campos do próprio registro ainda podem ser editados e salvos.", discardInlineEditsMessage: "Você tem alterações não salvas nos campos deste registro. Descarte-as para editar o registro inteiro ou continue editando e salve-as primeiro.", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index aed2cfb1f18..581c33ab50e 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1799,6 +1799,8 @@ const ru = { lockedByApproval: "Заблокировано для согласования", lockedTooltip: "У этой записи есть ожидающий запрос на согласование; редактирование заблокировано", lockedByState: "Недоступно для редактирования в текущем состоянии", + lockedClosed: "Закрыта", + lockedClosedTooltip: "Эта запись закрыта, её нельзя изменить.", bodyTableRow: "Строка {{row}}", bodyTablesReadOnlyBulk: "Эти таблицы строк при редактировании доступны только для чтения: чтобы сохранять их вместе с записью, для их объектов должна быть включена массовая запись. Поля самой записи по-прежнему можно редактировать и сохранять.", discardInlineEditsMessage: "В полях этой записи есть несохранённые изменения. Отмените их, чтобы редактировать всю запись, или продолжите редактирование и сначала сохраните их.", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 41d21babc85..e2de293d0ce 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1438,6 +1438,8 @@ const zh = { lockedByApproval: '审批中已锁定', lockedTooltip: '该记录有待审批的请求,编辑已被锁定', lockedByState: '当前状态下不可编辑', + lockedClosed: '已关闭', + lockedClosedTooltip: '此记录已关闭,无法更改。', bodyTableRow: '第 {{row}} 行', bodyTablesReadOnlyBulk: '编辑时这些明细表保持只读:要和主记录一起保存,需要在它们的对象上开启批量写入。主记录本身的字段仍可编辑和保存。', discardInlineEditsMessage: '此记录的字段有未保存的更改。放弃这些更改以编辑整条记录,或继续编辑并先保存。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 9a865b340e4..4fce3fa8e8d 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1438,6 +1438,8 @@ const zhHant = { lockedByApproval: '審批中已鎖定', lockedTooltip: '該記錄有待審批的請求,編輯已被鎖定', lockedByState: '當前狀態下不可編輯', + lockedClosed: '已關閉', + lockedClosedTooltip: '此記錄已關閉,無法更改。', bodyTableRow: '第 {{row}} 行', bodyTablesReadOnlyBulk: '編輯時這些明細表保持只讀:要和主記錄一起儲存,需要在它們的物件上開啟批次寫入。主記錄本身的欄位仍可編輯和儲存。', discardInlineEditsMessage: '此記錄的欄位有未儲存的更改。放棄這些更改以編輯整條記錄,或繼續編輯並先儲存。', diff --git a/ui/packages/types/src/data.ts b/ui/packages/types/src/data.ts index 7ebd05e04a3..a259c34faaf 100644 --- a/ui/packages/types/src/data.ts +++ b/ui/packages/types/src/data.ts @@ -24,6 +24,7 @@ import type { ImportJobStatus, ImportRowResult, ImportWriteMode, + RecordLock, RecordPageExplainOperation, RecordPagePartRefusal, RecordPageRequest, @@ -422,6 +423,15 @@ export interface RecordPagePayload { approvals?: | { requests: Record[]; lock: { locked: boolean; lockSource?: 'record' | 'master' } | null } | { error: RecordPagePartRefusal }; + /** + * The record's data lock, exactly as `GET /data/{object}/{id}/lock` answers + * the caller (`RecordLockSchema`, ADR-0162 D9): `locked`, and on a locked + * record `lockSource` and `lockReason` (`closed_state` wins when both hold), + * or that read's refusal (`501` where the data engine has no lock read). + * Asked by `dataLock: true`; the approval part's own `lock` is a different + * read. + */ + dataLock?: RecordLock | { error: RecordPagePartRefusal }; /** * The record's comment thread and those comments' reactions * (objectstack#28470), or the comment read's refusal. The reactions carry From 04735261df15483df33948f1514cd42f1ecee5b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:19:19 +0000 Subject: [PATCH 2/3] test(console): pin the record page's data lock to its one payload request Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ --- ...eRecordApprovals.lockSource-37195.test.tsx | 103 +++++++++++++----- ...etailView.recordPagePayload-27627.test.tsx | 92 ++++++++++++++-- 2 files changed, 160 insertions(+), 35 deletions(-) diff --git a/ui/packages/app-shell/src/hooks/useRecordApprovals.lockSource-37195.test.tsx b/ui/packages/app-shell/src/hooks/useRecordApprovals.lockSource-37195.test.tsx index 76d73c88a4c..0ce3cf2edfa 100644 --- a/ui/packages/app-shell/src/hooks/useRecordApprovals.lockSource-37195.test.tsx +++ b/ui/packages/app-shell/src/hooks/useRecordApprovals.lockSource-37195.test.tsx @@ -14,15 +14,18 @@ * not a pending request decides it, so the kind is kept beside a pending * request too — a self-held line under a held master answers `'master'`. * - * objectstack#37773 — beside the payload's approvals lock, the hook asks the - * data layer's one lock read (`GET /data/:object/:id/lock`, ADR-0162 D9), - * which the payload does not carry, and hands it back as `dataLock` in the - * same publish. The affordances read that one: `recordClosedByLock`, - * `openApprovalOf`. + * objectstack#37773 — the same payload carries the data layer's one lock read + * (`dataLock`, ADR-0162 D9), which the seeded read publishes as `dataLock` in + * the same publish and asks NO lock door for: the record page open stays one + * request. The affordances read that one: `recordClosedByLock`, + * `openApprovalOf`. A read the hook sends itself (`refresh()`) asks + * `GET /data/:object/:id/lock`. */ +import * as React from 'react'; import { describe, it, expect, afterEach, afterAll, vi } from 'vitest'; import { renderHook, waitFor, act } from '@testing-library/react'; +import { AdapterCtx } from '@object-ui/react'; import { __resetRecordApprovalsStore, openApprovalOf, @@ -30,6 +33,7 @@ import { recordLockAnswerOf, seedRecordApprovals, useRecordApprovals, + type DataRecordLock, type SeededRecordApprovals, } from './useRecordApprovals'; @@ -47,8 +51,9 @@ const PENDING_ROW = { /** What the data layer's lock door answers; set per test. */ let dataLock: Record = { locked: false }; const dataLockGets: string[] = []; -// Installed once for the whole file: the seeded read asks the data lock door -// beside the payload, and no read may reach a socket after a test returns. +// Installed once for the whole file: it counts every ask of the data lock door +// (a seeded read must send none), and no read may reach a socket after a test +// returns. vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => { const url = String(input); if (url.endsWith(`/data/${OBJECT}/${RECORD}/lock`)) { @@ -65,13 +70,19 @@ afterEach(() => { dataLockGets.length = 0; }); -async function seeded(answer: SeededRecordApprovals) { +async function seeded(answer: SeededRecordApprovals, dataLockPart?: Promise) { let resolve!: (a: SeededRecordApprovals) => void; - seedRecordApprovals(OBJECT, RECORD, new Promise((r) => { resolve = r; })); - const hook = renderHook(() => useRecordApprovals(OBJECT, RECORD)); + seedRecordApprovals(OBJECT, RECORD, new Promise((r) => { resolve = r; }), dataLockPart); + // Mounted as the console mounts it, under an adapter, so a read of the + // hook's own WOULD ask the data lock door. + const hook = renderHook(() => useRecordApprovals(OBJECT, RECORD), { wrapper: withAdapter }); await act(async () => { resolve(answer); }); await waitFor(() => expect(hook.result.current.answered).toBe(true)); - return hook.result.current; + return Object.assign(hook.result.current, { hook }); +} + +function withAdapter({ children }: { children: React.ReactNode }) { + return {children}; } describe('useRecordApprovals — the composite lock\'s `lockSource` (objectstack#37195)', () => { @@ -113,29 +124,71 @@ describe('recordLockAnswerOf — the two bits the lock doors serve, as the grid }); }); -describe('useRecordApprovals — the data layer\'s lock read beside the payload (objectstack#37773)', () => { - it('a closed record: `dataLock` names `closed_state`, so the record reads closed and no approval opens', async () => { - dataLock = { locked: true, lockSource: 'record', lockReason: 'closed_state' }; - const out = await seeded({ requests: [], lock: { locked: false } }); - expect(dataLockGets).toHaveLength(1); - expect(out.dataLock).toEqual({ locked: true, lockSource: 'record', lockReason: 'closed_state' }); - expect(recordClosedByLock(out)).toBe(true); - expect(openApprovalOf(out)).toBeNull(); - // The approvals panel's lock is the payload's, untouched. - expect(out.recordLock).toEqual({ locked: false }); +describe('useRecordApprovals — the data lock off the record page payload (objectstack#37773)', () => { + it('a closed record: `dataLock` names `closed_state`, so the record reads closed and no approval opens — and no lock door is asked', async () => { + const out = await seeded( + { requests: [], lock: { locked: false } }, + Promise.resolve({ locked: true, lockSource: 'record', lockReason: 'closed_state' }), + ); + const now = out.hook.result.current; + expect(now.dataLock).toEqual({ locked: true, lockSource: 'record', lockReason: 'closed_state' }); + expect(recordClosedByLock(now)).toBe(true); + expect(openApprovalOf(now)).toBeNull(); + // The approvals panel's lock is the payload's approvals part, untouched. + expect(now.recordLock).toEqual({ locked: false }); + // The payload answered it: the open sent no lock read of its own. + expect(dataLockGets).toEqual([]); + }); + + it('the data lock lands in the same publish as the approvals answer: no render sees one without the other', async () => { + let resolveAnswer!: (a: SeededRecordApprovals) => void; + const answer = new Promise((r) => { resolveAnswer = r; }); + const closed: DataRecordLock = { locked: true, lockSource: 'record', lockReason: 'closed_state' }; + seedRecordApprovals(OBJECT, RECORD, answer, answer.then(() => closed)); + const seen: Array<[boolean, boolean]> = []; + const hook = renderHook(() => { + const r = useRecordApprovals(OBJECT, RECORD); + seen.push([r.answered, r.dataLock !== null]); + return r; + }, { wrapper: withAdapter }); + await act(async () => { resolveAnswer({ requests: [], lock: { locked: false } }); }); + await waitFor(() => expect(hook.result.current.answered).toBe(true)); + expect(seen.some(([answered]) => answered)).toBe(true); + expect(seen.filter(([answered, locked]) => answered !== locked)).toEqual([]); + expect(dataLockGets).toEqual([]); }); it('a record held by an approval the reader cannot see: the data lock opens it, whatever the approvals-family lock says', async () => { - dataLock = { locked: true, lockSource: 'record', lockReason: 'approval' }; - const out = await seeded({ requests: [], lock: { locked: false } }); + const out = await seeded( + { requests: [], lock: { locked: false } }, + Promise.resolve({ locked: true, lockSource: 'record', lockReason: 'approval' }), + ); expect(recordClosedByLock(out)).toBe(false); expect(openApprovalOf(out)).toEqual({ locked: true }); }); it('CONTROL: the approvals-family lock alone opens no approval for the affordances', async () => { - dataLock = { locked: false }; - const out = await seeded({ requests: [], lock: { locked: true, lockSource: 'record' } }); + const out = await seeded({ requests: [], lock: { locked: true, lockSource: 'record' } }, Promise.resolve({ locked: false })); expect(out.recordLock).toEqual({ locked: true, lockSource: 'record' }); expect(openApprovalOf(out)).toBeNull(); }); + + it("a refresh after the open is the hook's own read: it asks the data lock door once, and takes its answer", async () => { + const out = await seeded({ requests: [], lock: { locked: false } }, Promise.resolve({ locked: false })); + expect(dataLockGets).toEqual([]); + dataLock = { locked: true, lockSource: 'record', lockReason: 'closed_state' }; + await act(async () => { await out.hook.result.current.refresh(); }); + expect(dataLockGets).toHaveLength(1); + expect(recordClosedByLock(out.hook.result.current)).toBe(true); + }); + + it('a payload whose engine has no lock read (part refused 501): no answer, and a later refresh does not ask the door either', async () => { + const refused = Promise.reject(Object.assign(new Error('Data lock refused'), { status: 501, code: 'NOT_IMPLEMENTED' })); + refused.catch(() => undefined); + const out = await seeded({ requests: [], lock: { locked: false } }, refused); + expect(out.hook.result.current.dataLock).toBeNull(); + await act(async () => { await out.hook.result.current.refresh(); }); + expect(dataLockGets).toEqual([]); + expect(out.hook.result.current.dataLock).toBeNull(); + }); }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.recordPagePayload-27627.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.recordPagePayload-27627.test.tsx index c8140a3c76b..feeec7e4ab7 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.recordPagePayload-27627.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.recordPagePayload-27627.test.tsx @@ -29,6 +29,11 @@ * them on its own; pinned below as an empty list of stream reads * (`RecordDetailView.recordOpenOneRequest-28470.test.tsx` pins the rest). * + * objectstack#37773 — the record's data lock (ADR-0162 D9) is a part of the + * same payload (`dataLock: true`): a closed record's header draws Edit greyed + * with the closed sentence from that one answer, and the open asks no lock + * door of its own (the last describe block below). + * * And once the app's metadata bundle is in (`loadAppBundle`, on app entry), the * object definitions the blocks read come from it: a record open in a warm * session asks the page and no metadata at all, and a cold one adds at most @@ -55,7 +60,7 @@ vi.mock('sonner', () => ({ }), })); -import { MetadataCtx } from '@object-ui/react'; +import { AdapterCtx, MetadataCtx } from '@object-ui/react'; import { RelatedCountStore } from '@object-ui/components'; import { ObjectStackAdapter } from '@object-ui/data-objectstack'; import { __clearRecordEditableCache } from '../../../plugin-detail/src/useRecordEditable'; @@ -98,6 +103,9 @@ interface Held { wave: number; method: string; path: string; body: any; released const json = (body: unknown, headers: Record = {}) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json', ...headers } }); +/** The data lock the page payload answers when asked (objectstack#37773); set per test. */ +let servedDataLock: Record = { locked: false }; + /** The page payload the route answers for `body`, for record `id`. */ function pageAnswer(id: string, body: any) { return { @@ -115,6 +123,7 @@ function pageAnswer(id: string, body: any) { ...(body.fieldAccess ? { fieldAccess: { object: OBJECT, recordId: id, readable: ['name', 'email', 'account'], editable: ['name', 'email'], writable: true } } : {}), ...(body.explain ? { explain: Object.fromEntries(body.explain.map((op: string) => [op, { allowed: true, record: { recordId: id, visible: true } }])) } : {}), ...(body.approvals ? { approvals: { requests: [], lock: { locked: false } } } : {}), + ...(body.dataLock ? { dataLock: servedDataLock } : {}), }, }; } @@ -134,6 +143,8 @@ function answerFor(h: Held): unknown { if (meta) return { success: true, data: ALL.find((o) => o.name === meta[1]) ?? null }; const page = /\/api\/v1\/data\/[^/?]+\/([^/?]+)\/page$/.exec(h.path); if (page) return pageAnswer(page[1], h.body); + // The data layer's lock door, asked only by a read with no payload behind it. + if (/\/api\/v1\/data\/[^/?]+\/[^/?]+\/lock$/.test(h.path)) return { success: true, data: servedDataLock }; // The record read of an adapter without the payload (`findOne`). const one = new RegExp(`/api/v1/data/${OBJECT}\\?.*\\["id","=","([^"]+)"\\]`).exec(h.path); if (one) return { success: true, data: { records: [{ id: one[1], name: `Contact ${one[1]}`, email: 'a@b.c', account: 'a1' }], total: 1 } }; @@ -194,11 +205,17 @@ beforeEach(() => { __clearRecordEditableCache(); __resetRecordApprovalsStore(); RelatedCountStore._reset(); + servedDataLock = { locked: false }; Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1440 }); }); afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); -async function boot() { +/** + * `adapter`: mount the adapter as the console's `AdapterProvider` does, which is + * what lets the approvals hook send reads of its own (the lock doors among + * them), so a lock read the open sent would show up here. + */ +async function boot(options: { adapter?: boolean } = {}) { const { fetch, held, state } = heldTransport(); vi.stubGlobal('fetch', fetch); const ds = new ObjectStackAdapter({ baseUrl: BASE, fetch, autoReconnect: false }); @@ -208,15 +225,20 @@ async function boot() { refresh: async () => {}, invalidate: () => {}, ensureType: async () => [], getItem: async () => null, getItemsByType: () => [], } as never; + const page = (rec: string, upcoming: string | readonly string[] | null, embedded: boolean) => ( + + + ({ objectName: OBJECT, recordId }))}> + {}} objectNameOverride={OBJECT} recordIdOverride={rec} embedded={embedded} /> + + + + ); const view = (rec: string, upcoming: string | readonly string[] | null, embedded: boolean) => ( - - - ({ objectName: OBJECT, recordId }))}> - {}} objectNameOverride={OBJECT} recordIdOverride={rec} embedded={embedded} /> - - - + {options.adapter + ? {page(rec, upcoming, embedded)} + : page(rec, upcoming, embedded)} ); const open = (rec: string, upcoming: string | readonly string[] | null = null, embedded = false) => { @@ -253,7 +275,7 @@ describe('objectstack#27627 — one request opens a record page', () => { expect.arrayContaining(CHILDREN.map((c) => [c, 'contact'])), ); expect(page.body.related).toHaveLength(CHILDREN.length); - expect(page.body).toMatchObject({ explain: ['update', 'delete', 'transfer'], approvals: true, expand: ['account'] }); + expect(page.body).toMatchObject({ explain: ['update', 'delete', 'transfer'], approvals: true, dataLock: true, expand: ['account'] }); // Every badge's total is the payload's. for (const c of CHILDREN) expect(RelatedCountStore.get(c, 'contact', 'c1')).toBe(TOTAL[c]); @@ -389,3 +411,53 @@ describe('objectstack#27627 — one request opens a record page', () => { expect(warm).toEqual([...CHILDREN].sort()); }); }); + +describe('objectstack#37773 — the record page reads its data lock off the one request', () => { + const isLockRead = (h: Held) => h.method === 'GET' && /\/lock$/.test(h.path); + const CLOSED_SENTENCE = "This record is closed, so it can't be changed."; + + function headerEdit(): HTMLButtonElement | null { + const bar = document.querySelector('[role="toolbar"]'); + if (!bar) return null; + return (Array.from(bar.querySelectorAll('button')) + .find((b) => (b.textContent ?? '').trim().toLowerCase() === 'edit') as HTMLButtonElement | undefined) ?? null; + } + + it('a closed record: one page request asking the lock, no lock read, and Edit greyed with the closed sentence', async () => { + servedDataLock = { locked: true, lockSource: 'record', lockReason: 'closed_state' }; + const { held, state, open } = await boot({ adapter: true }); + open('c1'); + await runWaves(held, state); + + expect(dataRequests(held).map((h) => `${h.method} ${h.path}`)).toEqual([`POST /api/v1/data/${OBJECT}/c1/page`]); + expect(dataRequests(held)[0].body).toMatchObject({ dataLock: true, approvals: true }); + expect(held.filter(isLockRead)).toEqual([]); + + const edit = headerEdit(); + expect(edit).not.toBeNull(); + expect(edit).toBeDisabled(); + const chip = document.querySelector('[data-testid="record-closed-lock"]'); + expect(chip?.getAttribute('title')).toBe(CLOSED_SENTENCE); + expect(document.body.textContent).not.toMatch(/in approval/i); + }); + + it('CONTROL: an unlocked record opens with the same one request and a live Edit', async () => { + const { held, state, open } = await boot({ adapter: true }); + open('c1'); + await runWaves(held, state); + expect(dataRequests(held).map((h) => `${h.method} ${h.path}`)).toEqual([`POST /api/v1/data/${OBJECT}/c1/page`]); + expect(held.filter(isLockRead)).toEqual([]); + expect(headerEdit()).not.toBeDisabled(); + expect(document.querySelector('[data-testid="record-closed-lock"]')).toBeNull(); + }); + + it('ablation: with no payload behind the page, the hook reads the lock itself, and the detector sees that read', async () => { + servedDataLock = { locked: true, lockSource: 'record', lockReason: 'closed_state' }; + const { held, state, open, ds } = await boot({ adapter: true }); + Object.assign(ds, { getRecordPage: undefined, prefetchRecordPage: undefined }); + open('c1'); + await runWaves(held, state); + expect(held.filter(isLockRead).map((h) => h.path)).toEqual([`/api/v1/data/${OBJECT}/c1/lock`]); + expect(headerEdit()).toBeDisabled(); + }); +}); From 9e167abf05f3b0e7b1f2fbd772c4846cf03b7b44 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:20:42 +0000 Subject: [PATCH 3/3] test(console): pin the edit dialog's lock reads over a list Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ --- ...tent.editDialogApprovalLock-27138.test.tsx | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.editDialogApprovalLock-27138.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.editDialogApprovalLock-27138.test.tsx index b06a586f902..d7e63a3b351 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppContent.editDialogApprovalLock-27138.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.editDialogApprovalLock-27138.test.tsx @@ -209,6 +209,26 @@ describe('[#27138] the console edit dialog reads the approvals record lock', () expect(lastModal().lockedBy).toBeUndefined(); }); + // objectstack#37773 — over a list, no record page payload stands behind the + // dialog, so its hook reads for itself: the approvals list, the approvals + // lock (the panel's, asked when no pending request decides) and ONE data + // lock read, which is what the dialog's lock is read from. + it('over a list, the dialog sends one data lock read beside its approvals reads', async () => { + const fetchSpy = serveApprovals({ requests: [], lock: false }); + openAt('/apps/crm/crm_contract?form=r1'); + await waitFor(() => expect(lastModal()?.schema?.mode).toBe('edit')); + const lockishReads = () => fetchSpy.mock.calls + .map(([u]) => new URL(String(u), 'http://x').pathname) + .filter((u) => u.includes('/approvals/') || u.endsWith('/lock')); + await waitFor(() => expect(lockishReads().some((u) => u.startsWith('/api/v1/data/'))).toBe(true)); + await new Promise((r) => setTimeout(r, 20)); + expect(lockishReads().sort()).toEqual([ + '/api/v1/approvals/records/crm_contract/r1/lock', + '/api/v1/approvals/requests', + '/api/v1/data/crm_contract/r1/lock', + ]); + }); + it('CONTROL — a create dialog asks nothing and is not locked', async () => { const fetchSpy = serveApprovals({ requests: [], lock: true }); openAt('/apps/crm/crm_contract?form=new');