diff --git a/.changeset/37448-hand-lock-remaining-surfaces.md b/.changeset/37448-hand-lock-remaining-surfaces.md new file mode 100644 index 00000000000..39d64774bb3 --- /dev/null +++ b/.changeset/37448-hand-lock-remaining-surfaces.md @@ -0,0 +1,28 @@ +--- +'@objectstack/spec': minor +'@objectstack/mcp': minor +'@objectstack/platform-objects': minor +'@object-ui/app-shell': minor +'@object-ui/plugin-calendar': minor +'@object-ui/plugin-gantt': minor +'@object-ui/plugin-list': minor +'@object-ui/plugin-timesheet': minor +'@object-ui/core': patch +--- + +feat(ui): the field hand lock (`uiReadonly` / `uiReadonlyWhen`) holds on the Gantt, the timesheet cell, the calendar quick-create and the palette prefill + +Clause-②: no +Metadata-protocol: semantic + +A field a person may not edit by hand (`uiReadonly: true`, or `uiReadonlyWhen` true over the record) now stays locked on the console surfaces that still wrote it: + +- **Gantt.** A bar's drag and edge resize, the progress handle, the title and dates edited in place, the auto-schedule and the conflict reschedule, undo and redo, and a drawn dependency link all read the one verdict of `@object-ui/core` (`fieldReadOnlyByHand`) over the stored record, with the shell's predicate scope. A write that would change a locked field is refused: nothing is sent, the bar goes back and a toast gives the read-only reason. A locked field the write only echoes back (an in-place title edit carries the dates and progress too) is dropped from the write, so the rest still saves. A field locked on every record also closes the gesture before it starts: a move closes when either date is locked, a resize only when both are (the locked edge is refused on the write), and the progress handle and the link tool close with their own field. +- **Timesheet.** A cell whose record's value field is locked by hand is drawn read-only, so it cannot be edited or cleared. A row, date or value field locked on every record closes the create, so the empty cells and **Add row** are not offered. +- **Calendar quick-create.** A click on an empty day or a range drag no longer writes a field locked by hand on every record. Where the title or a date field the dialog writes is locked, the gesture opens the full create form instead (a locked date field is not prefilled there). A required locked field is left out of the dialog's write so the server applies its `defaultValue`; one with no default sends the gesture to the full form too. +- **Command palette.** The create-as prefill skips a field that is `uiReadonly`, as it already skipped a `readonly` one; a create is judged by the static half only, as the create dialog judges it. +- **List view.** A kanban board whose block names no `groupByField` takes the object's lifecycle field as its lanes; the operands of that field's lock predicates are now read with the rows too, so a card drag is judged over the whole record. + +A kanban drag on the swimlane layout writes only the lane (column) field, never the swimlane field; that is now pinned. + +Not yet covered: the in-app assistant acting for a person. Its writes run in the AI service, which does not read the hand lock, and the field descriptions now say so. Every other console surface a person edits through honours the hand lock, and the `uiReadonly` / `uiReadonlyWhen` descriptions and the MCP `describe_object` guidance say that. Writes through the API, import, actions and flows are unchanged: only the server lock (`readonly` / `readonlyWhen`) binds them. diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index 576b4dfbf90..c94c8d6d665 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -111,7 +111,7 @@ const result = CurrencyConfigSchema.parse(data); | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`. On a `required` field the server reads it on every write: where it is not TRUE (FALSE, or null such as an unset boolean) the field is not required for that write, and a predicate the server cannot evaluate counts as shown, so the field stays required. Reads the record's own columns, with `formula` fields computed over the record being written, as the form computes them over the record being edited; a read THROUGH a reference field, or a formula that reads through one, calls label(), calls can() on a write that picks no permission-gated option, or reads current_user on a system write with no user, cannot be evaluated there. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every update that writes the field — `objectstack validate` refuses it. Put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | -| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: every console surface that honours `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the line-item grid) does not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17. | | **dueLike** | `boolean` | optional | Deadline semantic (`date` / `datetime` only): TRUE declares this date a deadline, so a renderer may show relative overdue wording ("Overdue 3d") and an overdue colour once it has passed. Absent or FALSE: not a deadline — nothing is inferred from the field's name. Pair with `settledWhen` to say when the deadline is settled for a record. Refused on any other type. Display only: nothing on the write path reads it. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -121,7 +121,7 @@ const result = CurrencyConfigSchema.parse(data); | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | -| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and quick-create, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the command palette's create-as prefill and the line-item grid — every console surface; the in-app assistant acting for a person does not honour it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index b93aac552d6..d3d7e1f0b8e 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -299,7 +299,7 @@ const result = ApiMethod.parse(data); | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`. On a `required` field the server reads it on every write: where it is not TRUE (FALSE, or null such as an unset boolean) the field is not required for that write, and a predicate the server cannot evaluate counts as shown, so the field stays required. Reads the record's own columns, with `formula` fields computed over the record being written, as the form computes them over the record being edited; a read THROUGH a reference field, or a formula that reads through one, calls label(), calls can() on a write that picks no permission-gated option, or reads current_user on a system write with no user, cannot be evaluated there. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every update that writes the field — `objectstack validate` refuses it. Put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | -| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: every console surface that honours `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the line-item grid) does not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17. | | **dueLike** | `boolean` | optional | Deadline semantic (`date` / `datetime` only): TRUE declares this date a deadline, so a renderer may show relative overdue wording ("Overdue 3d") and an overdue colour once it has passed. Absent or FALSE: not a deadline — nothing is inferred from the field's name. Pair with `settledWhen` to say when the deadline is settled for a record. Refused on any other type. Display only: nothing on the write path reads it. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -309,7 +309,7 @@ const result = ApiMethod.parse(data); | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | -| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and quick-create, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the command palette's create-as prefill and the line-item grid — every console surface; the in-app assistant acting for a person does not honour it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | @@ -700,7 +700,7 @@ const result = ApiMethod.parse(data); | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`. On a `required` field the server reads it on every write: where it is not TRUE (FALSE, or null such as an unset boolean) the field is not required for that write, and a predicate the server cannot evaluate counts as shown, so the field stays required. Reads the record's own columns, with `formula` fields computed over the record being written, as the form computes them over the record being edited; a read THROUGH a reference field, or a formula that reads through one, calls label(), calls can() on a write that picks no permission-gated option, or reads current_user on a system write with no user, cannot be evaluated there. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every update that writes the field — `objectstack validate` refuses it. Put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | -| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: every console surface that honours `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the line-item grid) does not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17. | | **dueLike** | `boolean` | optional | Deadline semantic (`date` / `datetime` only): TRUE declares this date a deadline, so a renderer may show relative overdue wording ("Overdue 3d") and an overdue colour once it has passed. Absent or FALSE: not a deadline — nothing is inferred from the field's name. Pair with `settledWhen` to say when the deadline is settled for a record. Refused on any other type. Display only: nothing on the write path reads it. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -710,7 +710,7 @@ const result = ApiMethod.parse(data); | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | -| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and quick-create, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the command palette's create-as prefill and the line-item grid — every console surface; the in-app assistant acting for a person does not honour it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index 1d37db00796..eb4e86d1ad8 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -114,7 +114,7 @@ Add a new field to an existing object | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`. On a `required` field the server reads it on every write: where it is not TRUE (FALSE, or null such as an unset boolean) the field is not required for that write, and a predicate the server cannot evaluate counts as shown, so the field stays required. Reads the record's own columns, with `formula` fields computed over the record being written, as the form computes them over the record being edited; a read THROUGH a reference field, or a formula that reads through one, calls label(), calls can() on a write that picks no permission-gated option, or reads current_user on a system write with no user, cannot be evaluated there. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every update that writes the field — `objectstack validate` refuses it. Put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | -| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: every console surface that honours `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the line-item grid) does not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17. | | **dueLike** | `boolean` | optional | Deadline semantic (`date` / `datetime` only): TRUE declares this date a deadline, so a renderer may show relative overdue wording ("Overdue 3d") and an overdue colour once it has passed. Absent or FALSE: not a deadline — nothing is inferred from the field's name. Pair with `settledWhen` to say when the deadline is settled for a record. Refused on any other type. Display only: nothing on the write path reads it. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -124,7 +124,7 @@ Add a new field to an existing object | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | -| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and quick-create, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the command palette's create-as prefill and the line-item grid — every console surface; the in-app assistant acting for a person does not honour it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | @@ -558,7 +558,7 @@ Add a new field to an existing object | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`. On a `required` field the server reads it on every write: where it is not TRUE (FALSE, or null such as an unset boolean) the field is not required for that write, and a predicate the server cannot evaluate counts as shown, so the field stays required. Reads the record's own columns, with `formula` fields computed over the record being written, as the form computes them over the record being edited; a read THROUGH a reference field, or a formula that reads through one, calls label(), calls can() on a write that picks no permission-gated option, or reads current_user on a system write with no user, cannot be evaluated there. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every update that writes the field — `objectstack validate` refuses it. Put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | -| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: every console surface that honours `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the line-item grid) does not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17. | | **dueLike** | `boolean` | optional | Deadline semantic (`date` / `datetime` only): TRUE declares this date a deadline, so a renderer may show relative overdue wording ("Overdue 3d") and an overdue colour once it has passed. Absent or FALSE: not a deadline — nothing is inferred from the field's name. Pair with `settledWhen` to say when the deadline is settled for a record. Refused on any other type. Display only: nothing on the write path reads it. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -568,7 +568,7 @@ Add a new field to an existing object | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | -| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and quick-create, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the command palette's create-as prefill and the line-item grid — every console surface; the in-app assistant acting for a person does not honour it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | diff --git a/packages/lint/src/validate-field-consumers.test.ts b/packages/lint/src/validate-field-consumers.test.ts index c68595a5a3b..dd6901a243d 100644 --- a/packages/lint/src/validate-field-consumers.test.ts +++ b/packages/lint/src/validate-field-consumers.test.ts @@ -2006,3 +2006,29 @@ describe('[#22161] one-line fixes — field-no-consumers, the carrier sites boun } }); }); + +/** + * #37448 (N8) — `uiReadonlyWhen` is deliberately NOT in `BEHAVIOUR_SEGMENTS`. + * That set earns behaviour back only inside a display root or segment, and the + * key is authorable only on a field definition under `objects`, which + * `bucketFor` already reads as behaviour; `readonlyWhen` is listed because the + * inline-grid column (under a `columns` display segment) carries it too, and + * that column declares no hand lock. What holds the verdict is this pin. + */ +describe('[#37448] validateFieldConsumers — a field-lock predicate reads the fields it names', () => { + /** `x` is named by nothing but the lock predicate each case adds to `y`. */ + const verdictOfX = (lock: AnyRec): string | undefined => + validateFieldConsumers({ + objects: [{ name: 'o', fields: { name: { type: 'text' }, x: { type: 'text' }, y: { type: 'text', ...lock } } }], + views: [{ list: { data: { object: 'o' }, columns: [{ field: 'y' }] } }], + }).find((f) => f.object === 'o' && f.field === 'x')?.verdict; + + it('baseline: unnamed, `x` is reported', () => { + expect(verdictOfX({})).toBe('inert'); + }); + + it('the hand lock `uiReadonlyWhen` reads its operand, as the server lock `readonlyWhen` does', () => { + expect(verdictOfX({ readonlyWhen: "record.x == 'done'" })).toBeUndefined(); + expect(verdictOfX({ uiReadonlyWhen: "record.x == 'done'" })).toBeUndefined(); + }); +}); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index a42f9ee0f46..bf81a274c12 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -3986,9 +3986,9 @@ export function registerObjectTools( }, ); - // #36806: the uiReadonly clause names only the console surfaces that honour - // the hand lock; the Gantt, the timesheet cell, the swimlane drag and the - // assistant are #37448. + // #36806, #37448: the uiReadonly clause names the console as a whole — every + // console surface honours the hand lock but the in-app assistant acting for + // a person, whose writes run in the AI service and do not read it yet. server.registerTool( note('describe_object'), { @@ -3996,7 +3996,8 @@ export function registerObjectTools( 'Get the schema of a data object as you may read it, with what a write needs: name, label, description; ' + 'each field\'s name, type, label, description (where set: the author\'s, or the platform\'s on a column ' + 'it injects), required, readonly (leave it out of a write), uiReadonly / uiReadonlyWhen where set ' - + '(a person cannot edit the field in the console\'s dialogs, record page, grids, kanban or calendar; ' + + '(a person cannot edit the field on any console surface, though the in-app assistant acting for a person ' + + 'does not honour it yet; ' + 'your write may still set it, judged by the validations), system, ' + 'options (send the value) and defaultValue (omit the field to get it; never copy the value); the active ' + 'validations; the enabled features. readonly is the schema\'s, not your edit permission.', diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 77aa571ceb3..d89a43fa1c0 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -1069,7 +1069,7 @@ export const arMetadataForms: NonNullable = { }, uiReadonly: { label: "للقراءة فقط في الواجهة", - helpText: "لا يمكن لأحد تعديل هذا الحقل يدويًا في وحدة التحكم (مربعات الحوار وصفحة السجل والشبكات والسحب في كانبان والتقويم)، بينما تواصل الإجراءات والاستيرادات وواجهة API والتدفقات الكتابة فيه، وتحكم قواعد التحقق الخاصة بالكائن على كل كتابة. اتركه معطلًا عند تفعيل للقراءة فقط: فهو يمنع بالفعل كل كتابة من العميل." + helpText: "لا يمكن لأحد تعديل هذا الحقل يدويًا في وحدة التحكم (مربعات الحوار وصفحة السجل والشبكات والسحب في كانبان والتقويم ومخطط جانت، وجدول ساعات العمل)، بينما تواصل الإجراءات والاستيرادات وواجهة API والتدفقات الكتابة فيه، وتحكم قواعد التحقق الخاصة بالكائن على كل كتابة. اتركه معطلًا عند تفعيل للقراءة فقط: فهو يمنع بالفعل كل كتابة من العميل. لا يلتزم به بعدُ المساعد داخل التطبيق الذي يتصرف نيابةً عن شخص." }, hidden: { label: "مخفي", @@ -1097,7 +1097,7 @@ export const arMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "للقراءة فقط في الواجهة عندما", - helpText: "شرط CEL على السجل (مثل record.status != 'draft') — ما دام TRUE، لا يمكن لأحد تعديل الحقل في سجل موجود من وحدة التحكم (مربع التعديل، صفحة السجل، الجداول، والسحب في كانبان والتقويم)؛ ولا يُقيَّم في مربع إنشاء سجل جديد. تواصل الإجراءات والاستيراد وواجهة API والتدفقات الكتابة فيه، وتحكم عليها قواعد التحقق الخاصة بالكائن. يقرأ أعمدة السجل نفسه، مثل للقراءة فقط عندما." + helpText: "شرط CEL على السجل (مثل record.status != 'draft') — ما دام TRUE، لا يمكن لأحد تعديل الحقل في سجل موجود من وحدة التحكم (مربع التعديل، صفحة السجل، الجداول، والسحب في كانبان والتقويم ومخطط جانت، وجدول ساعات العمل)؛ ولا يُقيَّم في مربع إنشاء سجل جديد. تواصل الإجراءات والاستيراد وواجهة API والتدفقات الكتابة فيه، وتحكم عليها قواعد التحقق الخاصة بالكائن. يقرأ أعمدة السجل نفسه، مثل للقراءة فقط عندما. لا يلتزم به بعدُ المساعد داخل التطبيق الذي يتصرف نيابةً عن شخص." }, requiredWhen: { label: "مطلوب عندما", diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 1918baa469d..ba3cf76e5ef 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -1069,7 +1069,7 @@ export const deMetadataForms: NonNullable = { }, uiReadonly: { label: "In der Oberfläche schreibgeschützt", - helpText: "Niemand kann dieses Feld in der Konsole von Hand bearbeiten (Dialoge, Datensatzseite, Tabellen, Ziehen im Kanban und Kalender), während Aktionen, Importe, die API und Flows es weiterhin schreiben; jeder Schreibvorgang wird von den Validierungen des Objekts beurteilt. Ausgeschaltet lassen, wenn Schreibgeschützt eingeschaltet ist: Das hält bereits jeden Client-Schreibvorgang fern." + helpText: "Niemand kann dieses Feld in der Konsole von Hand bearbeiten (Dialoge, Datensatzseite, Tabellen, Ziehen im Kanban, Kalender und Gantt, Zeiterfassung), während Aktionen, Importe, die API und Flows es weiterhin schreiben; jeder Schreibvorgang wird von den Validierungen des Objekts beurteilt. Ausgeschaltet lassen, wenn Schreibgeschützt eingeschaltet ist: Das hält bereits jeden Client-Schreibvorgang fern. Der In-App-Assistent, der im Auftrag einer Person handelt, beachtet es noch nicht." }, hidden: { label: "Ausgeblendet", @@ -1097,7 +1097,7 @@ export const deMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "In der Oberfläche schreibgeschützt wenn", - helpText: "CEL-Prädikat über den Datensatz (z. B. record.status != 'draft') – solange es TRUE ist, kann niemand das Feld eines bestehenden Datensatzes in der Konsole bearbeiten (Bearbeitungsdialog, Datensatzseite, Tabellen, Ziehen in Kanban und Kalender); der Erstellungsdialog eines neuen Datensatzes wertet es nicht aus. Aktionen, Importe, die API und Flows schreiben es weiterhin, beurteilt von den Validierungen des Objekts. Liest die eigenen Spalten des Datensatzes, wie Schreibgeschützt wenn." + helpText: "CEL-Prädikat über den Datensatz (z. B. record.status != 'draft') – solange es TRUE ist, kann niemand das Feld eines bestehenden Datensatzes in der Konsole bearbeiten (Bearbeitungsdialog, Datensatzseite, Tabellen, Ziehen in Kanban, Kalender und Gantt, Zeiterfassung); der Erstellungsdialog eines neuen Datensatzes wertet es nicht aus. Aktionen, Importe, die API und Flows schreiben es weiterhin, beurteilt von den Validierungen des Objekts. Liest die eigenen Spalten des Datensatzes, wie Schreibgeschützt wenn. Der In-App-Assistent, der im Auftrag einer Person handelt, beachtet es noch nicht." }, requiredWhen: { label: "Erforderlich wenn", diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 25f673b19c7..d15ec243034 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -1069,7 +1069,7 @@ export const enMetadataForms: NonNullable = { }, uiReadonly: { label: "Ui Readonly", - helpText: "People cannot edit this field in the console (dialogs, the record page, grids, kanban and calendar drag), while actions, imports, the API and flows still write it, each write judged by the object's validations. Leave it off when Read-only is on: that one already keeps every client write out." + helpText: "People cannot edit this field anywhere in the console (dialogs, the record page, grids, kanban, calendar and Gantt drag, the timesheet), while actions, imports, the API and flows still write it, each write judged by the object's validations. Leave it off when Read-only is on: that one already keeps every client write out. The in-app assistant acting for a person does not honour it yet." }, hidden: { label: "Hidden", @@ -1097,7 +1097,7 @@ export const enMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "Ui Readonly When", - helpText: "CEL predicate over the record (e.g. record.status != 'draft') — while it is TRUE, people cannot edit the field of an existing record in the console (the edit dialog, the record page, grids, kanban and calendar drag); a new record's create dialog is not judged. Actions, imports, the API and flows still write it, judged by the object's validations. Reads the record's own columns, as Read-only when does." + helpText: "CEL predicate over the record (e.g. record.status != 'draft') — while it is TRUE, people cannot edit the field of an existing record anywhere in the console (the edit dialog, the record page, grids, kanban, calendar and Gantt drag, the timesheet); a new record's create dialog is not judged. Actions, imports, the API and flows still write it, judged by the object's validations. Reads the record's own columns, as Read-only when does. The in-app assistant acting for a person does not honour it yet." }, requiredWhen: { label: "Required When", diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index ca94e15f7bd..925eefb1ba0 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -1069,7 +1069,7 @@ export const esESMetadataForms: NonNullable = }, uiReadonly: { label: "Solo lectura en la interfaz", - helpText: "Nadie puede editar este campo a mano en la consola (diálogos, página del registro, cuadrículas, arrastre en kanban y calendario), mientras que las acciones, las importaciones, la API y los flujos siguen escribiéndolo, y las validaciones del objeto juzgan cada escritura. Déjelo desactivado cuando Solo lectura esté activado: ese ya impide toda escritura de cliente." + helpText: "Nadie puede editar este campo a mano en la consola (diálogos, página del registro, cuadrículas, arrastre en kanban, calendario y Gantt, la hoja de horas), mientras que las acciones, las importaciones, la API y los flujos siguen escribiéndolo, y las validaciones del objeto juzgan cada escritura. Déjelo desactivado cuando Solo lectura esté activado: ese ya impide toda escritura de cliente. El asistente integrado que actúa en nombre de una persona todavía no lo respeta." }, hidden: { label: "Oculto", @@ -1097,7 +1097,7 @@ export const esESMetadataForms: NonNullable = }, uiReadonlyWhen: { label: "Condición de solo lectura en la interfaz", - helpText: "Predicado CEL sobre el registro (p. ej., record.status != 'draft'): mientras sea TRUE, nadie puede editar el campo de un registro existente en la consola (el diálogo de edición, la página del registro, las cuadrículas y el arrastre en kanban y calendario); el diálogo de creación de un registro nuevo no lo evalúa. Las acciones, las importaciones, la API y los flujos siguen escribiéndolo, juzgados por las validaciones del objeto. Lee las columnas propias del registro, como Solo lectura cuando." + helpText: "Predicado CEL sobre el registro (p. ej., record.status != 'draft'): mientras sea TRUE, nadie puede editar el campo de un registro existente en la consola (el diálogo de edición, la página del registro, las cuadrículas y el arrastre en kanban, calendario y Gantt, la hoja de horas); el diálogo de creación de un registro nuevo no lo evalúa. Las acciones, las importaciones, la API y los flujos siguen escribiéndolo, juzgados por las validaciones del objeto. Lee las columnas propias del registro, como Solo lectura cuando. El asistente integrado que actúa en nombre de una persona todavía no lo respeta." }, requiredWhen: { label: "Condición de obligatoriedad", diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index afa5dd31ca6..897b2f6a4f2 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -1069,7 +1069,7 @@ export const frMetadataForms: NonNullable = { }, uiReadonly: { label: "Lecture seule dans l'interface", - helpText: "Personne ne peut modifier ce champ à la main dans la console (boîtes de dialogue, page de l'enregistrement, grilles, glisser-déposer du kanban et du calendrier), tandis que les actions, les imports, l'API et les flux continuent de l'écrire, chaque écriture étant jugée par les validations de l'objet. Laissez-le désactivé lorsque Lecture seule est activé : celui-ci bloque déjà toute écriture client." + helpText: "Personne ne peut modifier ce champ à la main dans la console (boîtes de dialogue, page de l'enregistrement, grilles, glisser-déposer du kanban, du calendrier et du Gantt, la feuille de temps), tandis que les actions, les imports, l'API et les flux continuent de l'écrire, chaque écriture étant jugée par les validations de l'objet. Laissez-le désactivé lorsque Lecture seule est activé : celui-ci bloque déjà toute écriture client. L’assistant intégré qui agit pour le compte d’une personne ne le respecte pas encore." }, hidden: { label: "Masqué", @@ -1097,7 +1097,7 @@ export const frMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "Lecture seule dans l'interface si", - helpText: "Prédicat CEL sur l'enregistrement (p. ex. record.status != 'draft') : tant qu'il vaut TRUE, personne ne peut modifier le champ d'un enregistrement existant dans la console (la boîte d'édition, la page de l'enregistrement, les grilles, le glisser-déposer du kanban et du calendrier) ; la boîte de création d'un nouvel enregistrement ne l'évalue pas. Les actions, les imports, l'API et les flux continuent de l'écrire, jugés par les validations de l'objet. Lit les colonnes propres de l'enregistrement, comme Lecture seule si." + helpText: "Prédicat CEL sur l'enregistrement (p. ex. record.status != 'draft') : tant qu'il vaut TRUE, personne ne peut modifier le champ d'un enregistrement existant dans la console (la boîte d'édition, la page de l'enregistrement, les grilles, le glisser-déposer du kanban, du calendrier et du Gantt, la feuille de temps) ; la boîte de création d'un nouvel enregistrement ne l'évalue pas. Les actions, les imports, l'API et les flux continuent de l'écrire, jugés par les validations de l'objet. Lit les colonnes propres de l'enregistrement, comme Lecture seule si. L’assistant intégré qui agit pour le compte d’une personne ne le respecte pas encore." }, requiredWhen: { label: "Obligatoire si", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 921d9a48fef..1d46c39a341 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -1069,7 +1069,7 @@ export const jaJPMetadataForms: NonNullable = }, uiReadonly: { label: "画面上で読み取り専用", - helpText: "コンソールではこのフィールドを手で編集できません(ダイアログ、レコードページ、グリッド、かんばんとカレンダーのドラッグ)。アクション、インポート、API、フローは引き続き書き込めて、各書き込みはオブジェクトの検証ルールで判定されます。「読み取り専用」がオンのときはオフのままにしてください。そちらがすでにすべてのクライアント書き込みを拒否します。" + helpText: "コンソールではこのフィールドを手で編集できません(ダイアログ、レコードページ、グリッド、かんばん・カレンダー・ガントのドラッグ、タイムシート)。アクション、インポート、API、フローは引き続き書き込めて、各書き込みはオブジェクトの検証ルールで判定されます。「読み取り専用」がオンのときはオフのままにしてください。そちらがすでにすべてのクライアント書き込みを拒否します。ユーザーに代わって操作するアプリ内アシスタントは、まだこれに従いません。" }, hidden: { label: "非表示", @@ -1097,7 +1097,7 @@ export const jaJPMetadataForms: NonNullable = }, uiReadonlyWhen: { label: "画面上で読み取り専用の条件", - helpText: "レコードに対する CEL 述語(例: record.status != 'draft')— TRUE の間、既存レコードのこのフィールドはコンソールで編集できません(編集ダイアログ、レコードページ、グリッド、かんばんとカレンダーのドラッグ)。新規レコードの作成ダイアログでは判定されません。アクション、インポート、API、フローは引き続き書き込み、オブジェクトの検証ルールが判定します。「読み取り専用条件」と同じくレコード自身の列を読みます。" + helpText: "レコードに対する CEL 述語(例: record.status != 'draft')— TRUE の間、既存レコードのこのフィールドはコンソールで編集できません(編集ダイアログ、レコードページ、グリッド、かんばん・カレンダー・ガントのドラッグ、タイムシート)。新規レコードの作成ダイアログでは判定されません。アクション、インポート、API、フローは引き続き書き込み、オブジェクトの検証ルールが判定します。「読み取り専用条件」と同じくレコード自身の列を読みます。ユーザーに代わって操作するアプリ内アシスタントは、まだこれに従いません。" }, requiredWhen: { label: "必須条件", diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 671ad38fc06..eac467e3c99 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -1069,7 +1069,7 @@ export const koMetadataForms: NonNullable = { }, uiReadonly: { label: "화면에서 읽기 전용", - helpText: "콘솔에서는 이 필드를 직접 편집할 수 없습니다(대화 상자, 레코드 페이지, 그리드, 칸반 및 캘린더 끌기). 작업, 가져오기, API, 플로우는 계속 기록할 수 있으며 각 기록은 개체의 유효성 검사로 판정됩니다. 읽기 전용이 켜져 있으면 끈 상태로 두세요. 읽기 전용이 이미 모든 클라이언트 기록을 막습니다." + helpText: "콘솔에서는 이 필드를 직접 편집할 수 없습니다(대화 상자, 레코드 페이지, 그리드, 칸반·캘린더·간트 끌기, 작업 시간표). 작업, 가져오기, API, 플로우는 계속 기록할 수 있으며 각 기록은 개체의 유효성 검사로 판정됩니다. 읽기 전용이 켜져 있으면 끈 상태로 두세요. 읽기 전용이 이미 모든 클라이언트 기록을 막습니다. 사용자를 대신해 작업하는 앱 내 어시스턴트는 아직 이를 따르지 않습니다." }, hidden: { label: "숨김", @@ -1097,7 +1097,7 @@ export const koMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "화면에서 읽기 전용 조건", - helpText: "레코드에 대한 CEL 조건식(예: record.status != 'draft') — TRUE인 동안 기존 레코드의 이 필드는 콘솔에서 편집할 수 없습니다(편집 대화상자, 레코드 페이지, 그리드, 칸반 및 캘린더 드래그). 새 레코드의 생성 대화상자는 판단하지 않습니다. 작업, 가져오기, API 및 흐름은 계속 기록하며, 객체의 유효성 검사가 판단합니다. '읽기 전용 조건'처럼 레코드 자체의 열을 읽습니다." + helpText: "레코드에 대한 CEL 조건식(예: record.status != 'draft') — TRUE인 동안 기존 레코드의 이 필드는 콘솔에서 편집할 수 없습니다(편집 대화상자, 레코드 페이지, 그리드, 칸반·캘린더·간트 드래그, 작업 시간표). 새 레코드의 생성 대화상자는 판단하지 않습니다. 작업, 가져오기, API 및 흐름은 계속 기록하며, 객체의 유효성 검사가 판단합니다. '읽기 전용 조건'처럼 레코드 자체의 열을 읽습니다. 사용자를 대신해 작업하는 앱 내 어시스턴트는 아직 이를 따르지 않습니다." }, requiredWhen: { label: "필수 조건", diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index a9c2c2e0944..425643bc5cb 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -1069,7 +1069,7 @@ export const ptBRMetadataForms: NonNullable = }, uiReadonly: { label: "Somente leitura na interface", - helpText: "Ninguém pode editar este campo manualmente no console (diálogos, página do registro, grades, arrastar no kanban e no calendário), enquanto ações, importações, a API e fluxos continuam gravando-o, cada gravação julgada pelas validações do objeto. Deixe desativado quando Somente leitura estiver ativado: ele já bloqueia toda gravação do cliente." + helpText: "Ninguém pode editar este campo manualmente no console (diálogos, página do registro, grades, arrastar no kanban, no calendário e no Gantt, a folha de horas), enquanto ações, importações, a API e fluxos continuam gravando-o, cada gravação julgada pelas validações do objeto. Deixe desativado quando Somente leitura estiver ativado: ele já bloqueia toda gravação do cliente. O assistente do aplicativo que age em nome de uma pessoa ainda não o respeita." }, hidden: { label: "Oculto", @@ -1097,7 +1097,7 @@ export const ptBRMetadataForms: NonNullable = }, uiReadonlyWhen: { label: "Somente leitura na interface quando", - helpText: "Predicado CEL sobre o registro (ex.: record.status != 'draft') — enquanto for TRUE, ninguém pode editar o campo de um registro existente no console (a caixa de edição, a página do registro, as grades e o arrastar no kanban e no calendário); a caixa de criação de um novo registro não o avalia. Ações, importações, a API e os fluxos continuam gravando-o, julgados pelas validações do objeto. Lê as colunas do próprio registro, como Somente leitura quando." + helpText: "Predicado CEL sobre o registro (ex.: record.status != 'draft') — enquanto for TRUE, ninguém pode editar o campo de um registro existente no console (a caixa de edição, a página do registro, as grades e o arrastar no kanban, no calendário e no Gantt, a folha de horas); a caixa de criação de um novo registro não o avalia. Ações, importações, a API e os fluxos continuam gravando-o, julgados pelas validações do objeto. Lê as colunas do próprio registro, como Somente leitura quando. O assistente do aplicativo que age em nome de uma pessoa ainda não o respeita." }, requiredWhen: { label: "Obrigatório quando", diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index bd40396d57d..71bef062a35 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -1069,7 +1069,7 @@ export const ruMetadataForms: NonNullable = { }, uiReadonly: { label: "Только для чтения в интерфейсе", - helpText: "Никто не может изменить это поле вручную в консоли (диалоги, страница записи, таблицы, перетаскивание в канбане и календаре), а действия, импорт, API и потоки продолжают записывать его, и каждая запись проверяется правилами проверки объекта. Оставьте выключенным, если включено «Только для чтения»: оно уже запрещает любую запись клиентом." + helpText: "Никто не может изменить это поле вручную в консоли (диалоги, страница записи, таблицы, перетаскивание в канбане, календаре и на диаграмме Ганта, табель), а действия, импорт, API и потоки продолжают записывать его, и каждая запись проверяется правилами проверки объекта. Оставьте выключенным, если включено «Только для чтения»: оно уже запрещает любую запись клиентом. Встроенный ассистент, действующий от имени человека, пока его не учитывает." }, hidden: { label: "Скрытое", @@ -1097,7 +1097,7 @@ export const ruMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "Только для чтения в интерфейсе, когда", - helpText: "Предикат CEL над записью (например, record.status != 'draft') — пока он TRUE, никто не может изменить поле существующей записи в консоли (диалог редактирования, страница записи, таблицы, перетаскивание в канбане и календаре); диалог создания новой записи его не оценивает. Действия, импорт, API и потоки по-прежнему записывают его, и каждую запись оценивают проверки объекта. Читает собственные столбцы записи, как «Только чтение, если»." + helpText: "Предикат CEL над записью (например, record.status != 'draft') — пока он TRUE, никто не может изменить поле существующей записи в консоли (диалог редактирования, страница записи, таблицы, перетаскивание в канбане, календаре и на диаграмме Ганта, табель); диалог создания новой записи его не оценивает. Действия, импорт, API и потоки по-прежнему записывают его, и каждую запись оценивают проверки объекта. Читает собственные столбцы записи, как «Только чтение, если». Встроенный ассистент, действующий от имени человека, пока его не учитывает." }, requiredWhen: { label: "Обязательно, когда", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index c711030e0ba..10e7832ea57 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -1069,7 +1069,7 @@ export const zhCNMetadataForms: NonNullable = }, uiReadonly: { label: "界面只读", - helpText: "用户无法在控制台中编辑此字段(对话框、记录页、表格、看板和日历拖动),而动作、导入、API 和流程仍可写入,每次写入都由对象的校验规则裁决。已开启“只读”时请保持关闭:只读已经阻止所有客户端写入。" + helpText: "用户无法在控制台中编辑此字段(对话框、记录页、表格、看板、日历和甘特图拖动、工时表),而动作、导入、API 和流程仍可写入,每次写入都由对象的校验规则裁决。已开启“只读”时请保持关闭:只读已经阻止所有客户端写入。代表用户操作的应用内助手暂不遵循此设置。" }, hidden: { label: "隐藏", @@ -1097,7 +1097,7 @@ export const zhCNMetadataForms: NonNullable = }, uiReadonlyWhen: { label: "界面只读条件", - helpText: "基于记录的 CEL 谓词(例如 record.status != 'draft')——为 TRUE 时,用户无法在控制台中编辑已有记录的该字段(编辑对话框、记录页、表格、看板和日历拖动);新建记录的创建对话框不做判断。动作、导入、API 和流程仍可写入,并由对象的校验规则裁决。与“只读条件”一样读取记录自身的列。" + helpText: "基于记录的 CEL 谓词(例如 record.status != 'draft')——为 TRUE 时,用户无法在控制台中编辑已有记录的该字段(编辑对话框、记录页、表格、看板、日历和甘特图拖动、工时表);新建记录的创建对话框不做判断。动作、导入、API 和流程仍可写入,并由对象的校验规则裁决。与“只读条件”一样读取记录自身的列。代表用户操作的应用内助手暂不遵循此设置。" }, requiredWhen: { label: "必填条件", diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 34af280d9f6..c98539988cd 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -1069,7 +1069,7 @@ export const zhHantMetadataForms: NonNullable }, uiReadonly: { label: "介面唯讀", - helpText: "使用者無法在主控台中編輯此欄位(對話框、記錄頁、表格、看板與行事曆拖曳),而動作、匯入、API 與流程仍可寫入,每次寫入都由物件的驗證規則裁決。已開啟「唯讀」時請保持關閉:唯讀已經阻止所有用戶端寫入。" + helpText: "使用者無法在主控台中編輯此欄位(對話框、記錄頁、表格、看板、行事曆與甘特圖拖曳、工時表),而動作、匯入、API 與流程仍可寫入,每次寫入都由物件的驗證規則裁決。已開啟「唯讀」時請保持關閉:唯讀已經阻止所有用戶端寫入。代表使用者操作的應用程式內助理暫不遵循此設定。" }, hidden: { label: "隱藏", @@ -1097,7 +1097,7 @@ export const zhHantMetadataForms: NonNullable }, uiReadonlyWhen: { label: "介面唯讀條件", - helpText: "基於記錄的 CEL 謂詞(例如 record.status != 'draft')——為 TRUE 時,使用者無法在控制台中編輯既有記錄的該欄位(編輯對話框、記錄頁、表格、看板和行事曆拖曳);新建記錄的建立對話框不做判斷。動作、匯入、API 和流程仍可寫入,並由物件的驗證規則裁決。與「唯讀條件」一樣讀取記錄自身的欄。" + helpText: "基於記錄的 CEL 謂詞(例如 record.status != 'draft')——為 TRUE 時,使用者無法在控制台中編輯既有記錄的該欄位(編輯對話框、記錄頁、表格、看板、行事曆和甘特圖拖曳、工時表);新建記錄的建立對話框不做判斷。動作、匯入、API 和流程仍可寫入,並由物件的驗證規則裁決。與「唯讀條件」一樣讀取記錄自身的欄。代表使用者操作的應用程式內助理暫不遵循此設定。" }, requiredWhen: { label: "必填條件", diff --git a/packages/qa/dogfood/test/expression-conformance.ledger.ts b/packages/qa/dogfood/test/expression-conformance.ledger.ts index 07f89a4393e..962f8e2d42e 100644 --- a/packages/qa/dogfood/test/expression-conformance.ledger.ts +++ b/packages/qa/dogfood/test/expression-conformance.ledger.ts @@ -241,7 +241,7 @@ export const EXPRESSION_SURFACE: ExprSurface[] = [ summary: "a field's console hand lock (Field.uiReadonlyWhen) — UI only, fails closed", dialect: 'cel', mode: 'interpret', state: 'enforced', failPolicy: 'fail-closed', enforcement: - 'console (ui/) fieldReadOnlyByHand (core/evaluator/handLock.ts) → resolveFieldRuleState → evalFieldPredicate (core/evaluator/fieldRules.ts) → @objectstack/formula celEngine (interpret), evaluated per existing record with the row bound as `record` (plus `previous` and the host predicate scope), by the hosts that let a person edit a stored record: the edit dialog (which also refuses submit while the predicate faults), the record page (inline edit, highlight chip, save bar, stage path), grid cells and the line-item grid\'s stored rows, kanban drag and calendar drag. A create is not judged. A predicate that faults answers LOCKED (UI_READONLY_WHEN_FAULTED = true), because nothing behind it judges the write. UI only: no server evaluates it, and an API or automation write is not refused by it; the server lock is `readonlyWhen`. Judged at authoring by lint\'s field-rule pass (`validate-expressions.ts`) as `readonlyWhen` is', + 'console (ui/) resolveFieldRuleState → evalFieldPredicate (core/evaluator/fieldRules.ts) → @objectstack/formula celEngine (interpret) — called directly by the edit dialog and the grid cell, and through the one verdict fieldReadOnlyByHand (core/evaluator/handLock.ts) everywhere else — evaluated per existing record with the row bound as `record` (plus `previous` and the host predicate scope), by the hosts that let a person edit a stored record: the edit dialog (which also refuses submit while the predicate faults), the record page (inline edit, highlight chip, save bar, stage path), grid cells and the line-item grid\'s stored rows, kanban drag, calendar drag, the Gantt\'s writes and the timesheet cell. A create is not judged. A predicate that faults answers LOCKED (UI_READONLY_WHEN_FAULTED = true), because nothing behind it judges the write. UI only: no server evaluates it, and an API or automation write is not refused by it; the server lock is `readonlyWhen`. Judged at authoring by lint\'s field-rule pass (`validate-expressions.ts`) as `readonlyWhen` is', covers: ['data/field.zod.ts:FieldSchema.uiReadonlyWhen'], proof: 'ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts', }, diff --git a/packages/spec/liveness/field.json b/packages/spec/liveness/field.json index 30cee9a0174..bfae2abe31c 100644 --- a/packages/spec/liveness/field.json +++ b/packages/spec/liveness/field.json @@ -152,7 +152,7 @@ "status": "live", "verifiedAt": "2026-11-26", "evidenceScope": "in-repo", - "evidence": "ui/packages/core/src/evaluator/handLock.ts#fieldReadOnlyByHand (the one hand-lock verdict, the predicate run through ui/packages/core/src/evaluator/fieldRules.ts#resolveFieldRuleState); its readers are the hand surfaces listed on `uiReadonly`, with the per-record reads in the form renderer (ui/packages/components/src/renderers/form/form.tsx), the record page (DetailSection, HeaderHighlight, InlineEditSaveBar, recordPathStageChange), the grid cell (ui/packages/plugin-grid/src/objectGridCellFacts.ts#cellReadOnlyKind), the line-item cell (ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx), kanban and calendar drops; packages/runtime/src/domains/mcp.ts#describedHandLock (describe_object)", + "evidence": "ui/packages/core/src/evaluator/handLock.ts#fieldReadOnlyByHand (the one hand-lock verdict, the predicate run through ui/packages/core/src/evaluator/fieldRules.ts#resolveFieldRuleState); its readers are the hand surfaces listed on `uiReadonly`, with the per-record reads in the form renderer (ui/packages/components/src/renderers/form/form.tsx), the record page (DetailSection, HeaderHighlight, InlineEditSaveBar, recordPathStageChange), the grid cell (ui/packages/plugin-grid/src/objectGridCellFacts.ts#cellReadOnlyKind), the line-item cell (ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx), kanban and calendar drops, the Gantt's writes (ui/packages/plugin-gantt/src/ganttHandLock.ts#ganttPatchByHand), the timesheet cell (ui/packages/plugin-timesheet/src/ObjectTimesheet.tsx#valueLockedByHand); packages/runtime/src/domains/mcp.ts#describedHandLock (describe_object)", "note": "renderer only, by ruling (the two-tier field-lock model): while TRUE no person edits the field of an existing record at the console surfaces listed on `uiReadonly` (the edit dialog, not the create dialog: a create is not judged); the engine never reads it, so API, import, action and flow writes keep it, judged by validations. Allowed beside `readonlyWhen`, the stricter server lock. Fail-closed on a fault (no server judges it, ADR-0137 D2): the field locks, the edit dialog refuses to submit, and `objectstack validate` checks the predicate (packages/lint/src/validate-expressions.ts)." }, "visibleWhen": { @@ -203,8 +203,8 @@ "status": "live", "verifiedAt": "2026-11-26", "evidenceScope": "in-repo", - "evidence": "ui/packages/core/src/evaluator/handLock.ts#fieldStaticallyReadOnlyByHand and #fieldReadOnlyByHand (the one hand-lock verdict every hand surface reads): the create and edit dialogs and their payload (ui/packages/plugin-form/src/autoLayout.ts, sectionFields.ts, ObjectForm.tsx, sanitize.ts), record-page inline edit and the stage path (ui/packages/plugin-detail/src/DetailSection.tsx, InlineEditSaveBar.tsx, renderers/recordPathStageChange.tsx), the highlight-strip chip (HeaderHighlight.tsx), grid inline edit (ui/packages/plugin-grid/src/inline-edit-options.ts), kanban drag (ui/packages/plugin-kanban/src/ObjectKanban.tsx), calendar drag (ui/packages/plugin-calendar/src/ObjectCalendar.tsx), the line-item grid (packages/spec/src/data/inline-grid-columns.ts#deriveInlineGridColumns, and an authored column over the field through ui/packages/plugin-form/src/deriveMasterDetail.ts#hydrateColumns); packages/spec/src/data/field.zod.ts#uiReadonly (the parse refuses it beside `readonly: true`); packages/runtime/src/domains/mcp.ts#describedHandLock (describe_object)", - "note": "renderer only, by ruling (the two-tier field-lock model): no person edits the field at the console, and every other write keeps it — the engine never reads the key, so REST, import, action and flow writes set it, judged by validations (a state_machine rule included); a console create leaves it out and the server applies its defaultValue (so a `required` field without one fails every console create). Honoured on the surfaces in evidence only; the Gantt, the timesheet cell, the kanban swimlane drag and the in-app assistant do not read it yet (#37448). The import mapping and Studio reads stay on raw `readonly`." + "evidence": "ui/packages/core/src/evaluator/handLock.ts#fieldStaticallyReadOnlyByHand and #fieldReadOnlyByHand (the one hand-lock verdict every hand surface reads): the create and edit dialogs and their payload (ui/packages/plugin-form/src/autoLayout.ts, sectionFields.ts, ObjectForm.tsx, sanitize.ts), record-page inline edit and the stage path (ui/packages/plugin-detail/src/DetailSection.tsx, InlineEditSaveBar.tsx, renderers/recordPathStageChange.tsx), the highlight-strip chip (HeaderHighlight.tsx), grid inline edit (ui/packages/plugin-grid/src/inline-edit-options.ts), kanban drag (ui/packages/plugin-kanban/src/ObjectKanban.tsx), calendar drag and quick-create (ui/packages/plugin-calendar/src/ObjectCalendar.tsx), the Gantt's drag, resize, progress, link and in-place edit (ui/packages/plugin-gantt/src/ganttHandLock.ts), the timesheet cell and its create (ui/packages/plugin-timesheet/src/ObjectTimesheet.tsx), the command palette's create-as prefill (ui/packages/app-shell/src/chrome/paletteCreate.ts#palettePrefillField), the line-item grid (packages/spec/src/data/inline-grid-columns.ts#deriveInlineGridColumns, and an authored column over the field through ui/packages/plugin-form/src/deriveMasterDetail.ts#hydrateColumns); packages/spec/src/data/field.zod.ts#uiReadonly (the parse refuses it beside `readonly: true`); packages/runtime/src/domains/mcp.ts#describedHandLock (describe_object)", + "note": "renderer only, by ruling (the two-tier field-lock model): no person edits the field at the console, and every other write keeps it — the engine never reads the key, so REST, import, action and flow writes set it, judged by validations (a state_machine rule included); a console create leaves it out and the server applies its defaultValue (so a `required` field without one fails every console create). Honoured on every console surface (evidence); the in-app assistant acting for a person, whose writes run in the AI service, does not read it yet (#37448). The import mapping and Studio reads stay on raw `readonly`." }, "hidden": { "status": "live", diff --git a/packages/spec/src/data/field.metadata-form.ts b/packages/spec/src/data/field.metadata-form.ts index 7e63f33fedc..07b2e3de0de 100644 --- a/packages/spec/src/data/field.metadata-form.ts +++ b/packages/spec/src/data/field.metadata-form.ts @@ -467,7 +467,7 @@ export const fieldForm = defineMetadataForm({ { field: 'readonly', colSpan: 1, helpText: 'Field is read-only in forms' }, // #36806 — the hand lock: read by every console surface a person edits // through, never by the engine. The parse refuses it beside `readonly`. - { field: 'uiReadonly', colSpan: 1, helpText: 'People cannot edit this field in the console (dialogs, the record page, grids, kanban and calendar drag), while actions, imports, the API and flows still write it, each write judged by the object\'s validations. Leave it off when Read-only is on: that one already keeps every client write out.' }, + { field: 'uiReadonly', colSpan: 1, helpText: 'People cannot edit this field anywhere in the console (dialogs, the record page, grids, kanban, calendar and Gantt drag, the timesheet), while actions, imports, the API and flows still write it, each write judged by the object\'s validations. Leave it off when Read-only is on: that one already keeps every client write out. The in-app assistant acting for a person does not honour it yet.' }, { field: 'hidden', colSpan: 1, helpText: 'Hide field from default UI views' }, // #36425 — whether a create asks for the field; read by every create // surface of the Console (the create dialog, the full-page create, an @@ -483,7 +483,7 @@ export const fieldForm = defineMetadataForm({ { field: 'readonlyWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.status == 'paid') — the field is read-only while it is TRUE, enforced server-side: an update's change to a locked field is dropped and the stored value kept. Reads the record's own columns; objectstack validate refuses a read through a reference field." }, // #36806 — the hand lock's predicate: the console locks the field while it // is TRUE; writes from actions, imports, the API and flows keep it. - { field: 'uiReadonlyWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.status != 'draft') — while it is TRUE, people cannot edit the field of an existing record in the console (the edit dialog, the record page, grids, kanban and calendar drag); a new record's create dialog is not judged. Actions, imports, the API and flows still write it, judged by the object's validations. Reads the record's own columns, as Read-only when does." }, + { field: 'uiReadonlyWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.status != 'draft') — while it is TRUE, people cannot edit the field of an existing record anywhere in the console (the edit dialog, the record page, grids, kanban, calendar and Gantt drag, the timesheet); a new record's create dialog is not judged. Actions, imports, the API and flows still write it, judged by the object's validations. Reads the record's own columns, as Read-only when does. The in-app assistant acting for a person does not honour it yet." }, { field: 'requiredWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record — the field is required while it is TRUE, enforced server-side as a transition gate: a write that leaves the value missing is refused when the record complied before it, so a row already missing the value keeps passing unrelated edits. For a rule every write must meet, use a validations script rule. Refused beside storage.notNull." }, // Partial masking (#8993): a preset name or a {keepHead, keepTail} JSON // object; the runtime FieldMasker enforces it on read AND export. diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 3687ffec117..7067b11e104 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2960,7 +2960,7 @@ export const FieldSchema = lazySchema(() => { * `@object-ui/core` (`fieldReadOnlyByHand`); the engine never reads it, so a * TRUE predicate refuses no API, import, action or flow write. */ - uiReadonlyWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key."), + uiReadonlyWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: every console surface that honours `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the line-item grid) does not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key."), requiredWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17."), /** @@ -3104,10 +3104,13 @@ export const FieldSchema = lazySchema(() => { * "By hand" = the create and edit dialogs and the payload they submit, the * record page's inline edit and stage path, the highlight-strip chip, grid * inline edit and its multi-row save, kanban drag between columns grouped by - * the field, calendar drag, and the line-item grid. Those are the surfaces - * that honour it today; the Gantt's drag and in-place edit, the timesheet - * cell, the kanban swimlane drag and the in-app assistant acting for a - * person do not read it yet (#37448). NOT by hand = REST create/update, + * the field (a swimlane board's drag writes the column's field only, never + * the swimlane's), calendar drag and quick-create, the Gantt's drag, + * resize, progress handle, dependency link and in-place edit, the timesheet + * cell, the command palette's create-as prefill, the line-item grid, and the in-app assistant + * acting for a person. Every console surface honours it; the in-app + * assistant, whose writes run in the AI service, does not read it yet + * (#37448). NOT by hand = REST create/update, * import (the console import wizard included), declarative and script * actions, flows. A console create leaves the field out, so the server * applies its `defaultValue` — a `required` field with no `defaultValue` @@ -3126,7 +3129,7 @@ export const FieldSchema = lazySchema(() => { * boundary: a caller who may edit the object can write the field through * the API; field permissions (`editable` on a permission set) are that. */ - uiReadonly: z.boolean().optional().describe("Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`."), + uiReadonly: z.boolean().optional().describe("Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and quick-create, the Gantt's drag, resize, progress handle, dependency link and in-place edit, the timesheet cell, the command palette's create-as prefill and the line-item grid — every console surface; the in-app assistant acting for a person does not honour it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`."), /** * [ADR-0066 D3] Capabilities required to READ/EDIT this field. A field diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.previewCreate-36286.test.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.previewCreate-36286.test.tsx index cdd0b5d6193..b0a0aa44bc4 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.previewCreate-36286.test.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.previewCreate-36286.test.tsx @@ -345,6 +345,11 @@ describe('objectstack#36286 — which objects a create row offers', () => { expect(palettePrefillField(base as never, PERMS as never)).toBe('full_name'); expect(palettePrefillField({ ...base, fields: { full_name: { type: 'lookup' } } } as never, PERMS as never)).toBeUndefined(); expect(palettePrefillField({ ...base, fields: { full_name: { type: 'text', readonly: true } } } as never, PERMS as never)).toBeUndefined(); + // objectstack#37448 — the hand lock too: the create page leaves a + // `uiReadonly` field off the form, so the typed words would land nowhere. + expect(palettePrefillField({ ...base, fields: { full_name: { type: 'text', uiReadonly: true } } } as never, PERMS as never)).toBeUndefined(); + // A conditional hand lock is not judged on a create (no record yet). + expect(palettePrefillField({ ...base, fields: { full_name: { type: 'text', uiReadonlyWhen: 'true' } } } as never, PERMS as never)).toBe('full_name'); const noCreateField = { ...PERMS, checkField: () => false }; expect(palettePrefillField(base as never, noCreateField as never)).toBeUndefined(); }); diff --git a/ui/packages/app-shell/src/chrome/paletteCreate.ts b/ui/packages/app-shell/src/chrome/paletteCreate.ts index 9e3c3ae4743..616d644daa9 100644 --- a/ui/packages/app-shell/src/chrome/paletteCreate.ts +++ b/ui/packages/app-shell/src/chrome/paletteCreate.ts @@ -23,11 +23,15 @@ * row carries the typed words as that page's query-string prefill of the * object's title field (`resolveNameField`, the ADR-0079 ladder), and is * offered only where that field is a plain text field the member may write - * on create (`createFormFields`), so the words always land in the form. + * on create (`createFormFields`) and the create page draws an input for — not + * read-only by hand (`fieldStaticallyReadOnlyByHand`: `readonly` or the hand + * lock `uiReadonly`, the create dialog's own read) — so the words always land + * in the form. */ import { evalRowPredicate, + fieldStaticallyReadOnlyByHand, resolveAffordance, resolveFieldAffordance, resolveNameField, @@ -43,7 +47,7 @@ export interface PaletteCreateObjectDef { label?: unknown; icon?: unknown; color?: unknown; - fields?: Record | unknown; + fields?: Record | unknown; [key: string]: unknown; } @@ -104,11 +108,14 @@ export function palettePrefillField(def: PaletteCreateObjectDef, perms: PaletteC const name = resolveNameField(def); if (!name) return undefined; const fields = def.fields && typeof def.fields === 'object' && !Array.isArray(def.fields) - ? (def.fields as Record) + ? (def.fields as Record) : undefined; const field = fields?.[name]; if (!field || typeof field.type !== 'string' || !PREFILLABLE_TYPES.has(field.type)) return undefined; - if (field.readonly === true) return undefined; + // A create is judged by the static half only, as the create dialog judges + // it: the page leaves a field read-only by hand off the form, so a prefill + // of it would land nowhere (objectstack#37448). + if (fieldStaticallyReadOnlyByHand(field)) return undefined; if (!resolveFieldAffordance('createFormFields', perms, def.name, name)) return undefined; return name; } diff --git a/ui/packages/core/src/evaluator/handLock.ts b/ui/packages/core/src/evaluator/handLock.ts index 1608d3c4fd9..1f123a42513 100644 --- a/ui/packages/core/src/evaluator/handLock.ts +++ b/ui/packages/core/src/evaluator/handLock.ts @@ -26,7 +26,12 @@ * The hand surfaces (each reads this module, never `def.readonly` alone): the * create and edit dialogs and the payload they submit, the record page's * inline edit, the highlight-strip chip, grid inline edit and its multi-row - * save, kanban drag between columns grouped by the field, and calendar drag. + * save, kanban drag between columns grouped by the field, calendar drag and + * quick-create, the Gantt's drag, resize, progress handle, dependency link and in-place edit + * (`@object-ui/plugin-gantt` `ganttHandLock.ts`), the timesheet cell, and the + * command palette's create-as prefill. The in-app assistant acting for a + * person is a hand surface too; its writes run in the AI service, which does + * not read this module. * NOT hand surfaces, and so still on the raw `readonly` read: the import * wizard's target mapping (an import keeps the write) and the Studio/designer * authoring reads (they describe the declaration, not a person's edit). diff --git a/ui/packages/plugin-calendar/src/ObjectCalendar.quickCreateHandLock-37448.test.tsx b/ui/packages/plugin-calendar/src/ObjectCalendar.quickCreateHandLock-37448.test.tsx new file mode 100644 index 00000000000..871d2ffbf86 --- /dev/null +++ b/ui/packages/plugin-calendar/src/ObjectCalendar.quickCreateHandLock-37448.test.tsx @@ -0,0 +1,171 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#37448 — the calendar's quick-create judges the field hand lock + * (`uiReadonly`) by its static half, as the create dialog does. + * + * The dialog writes the title field and the date fields itself, and fills the + * other required fields it can (`quickCreateFill`). A field read-only by hand + * is never in that write: + * + * - the title, start or end field locked: the dialog cannot leave it out of + * its own write, so the gesture goes to the host's full create form, and a + * locked date field is not prefilled there; + * - another required field locked: it is left out, so the server applies its + * `defaultValue`; without one the write would be refused for it, so the + * gesture goes to the full form (`requiredFieldsQuickCreateCannotFill`). + * + * `CalendarView` is replaced by a probe that records the handlers it is + * handed, as in `ObjectCalendar.quickCreateHandoff-12291.test.tsx`. + */ +import React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; + +const probe = vi.hoisted(() => ({ + props: null as null | Record, +})); + +vi.mock('./CalendarView', async (importOriginal) => { + const actual = await importOriginal>(); + return { + ...actual, + CalendarView: (props: Record) => { + probe.props = props; + return
; + }, + }; +}); + +import { ObjectCalendar } from './ObjectCalendar'; + +const FIELDS = { + subject: { type: 'text', required: true }, + status: { + type: 'select', + required: true, + options: [ + { label: 'Planned', value: 'planned' }, + { label: 'Completed', value: 'completed' }, + ], + }, + starts_on: { type: 'date' }, + ends_on: { type: 'date' }, +}; + +const SCHEMA = { + type: 'object-calendar', + objectName: 'hlk_event', + calendar: { startDateField: 'starts_on', endDateField: 'ends_on', titleField: 'subject' }, +} as any; + +const OCT_20 = new Date(2026, 9, 20); + +const makeDataSource = (fields: Record) => + ({ + find: vi.fn().mockResolvedValue({ data: [] }), + getObjectSchema: vi.fn().mockResolvedValue({ name: 'hlk_event', fields }), + create: vi.fn().mockResolvedValue({ id: 'new-1' }), + update: vi.fn().mockResolvedValue({}), + }) as any; + +beforeEach(() => { + probe.props = null; +}); +afterEach(cleanup); + +type Handler = ((...args: unknown[]) => unknown) | undefined; +const handler = (name: string): Handler => probe.props?.[name] as Handler; + +async function mount(fields: Record) { + const ds = makeDataSource(fields); + const onEdit = vi.fn(); + render(); + await screen.findByTestId('calendar-probe'); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + return { ds, onEdit }; +} + +function clickDay() { + act(() => { + handler('onDateClick')!(OCT_20); + }); +} + +describe('ObjectCalendar quick-create — a field the dialog writes itself, locked by hand (objectstack#37448)', () => { + it('the title field `uiReadonly`: the day goes to the full form, with no dialog and no write', async () => { + const { ds, onEdit } = await mount({ ...FIELDS, subject: { ...FIELDS.subject, uiReadonly: true } }); + clickDay(); + expect(onEdit).toHaveBeenCalledTimes(1); + expect(onEdit.mock.calls[0][0]).toEqual({ starts_on: '2026-10-20', ends_on: '2026-10-20' }); + expect(screen.queryByRole('dialog')).toBeNull(); + expect(ds.create).not.toHaveBeenCalled(); + }); + + it('the start field `uiReadonly`: the day goes to the full form, which is not prefilled with the locked field', async () => { + const { ds, onEdit } = await mount({ ...FIELDS, starts_on: { type: 'date', uiReadonly: true } }); + clickDay(); + expect(onEdit).toHaveBeenCalledTimes(1); + expect(onEdit.mock.calls[0][0]).toEqual({ ends_on: '2026-10-20' }); + expect(screen.queryByRole('dialog')).toBeNull(); + expect(ds.create).not.toHaveBeenCalled(); + }); + + it('the end field `uiReadonly`: the same, for the end field', async () => { + const { onEdit } = await mount({ ...FIELDS, ends_on: { type: 'date', uiReadonly: true } }); + clickDay(); + expect(onEdit).toHaveBeenCalledTimes(1); + expect(onEdit.mock.calls[0][0]).toEqual({ starts_on: '2026-10-20' }); + expect(screen.queryByRole('dialog')).toBeNull(); + }); + + it('CONTROL: a conditional lock (`uiReadonlyWhen`) does not judge a create, so the dialog stays', async () => { + const { onEdit } = await mount({ ...FIELDS, starts_on: { type: 'date', uiReadonlyWhen: 'true' } }); + clickDay(); + expect(await screen.findByRole('dialog')).toBeTruthy(); + expect(onEdit).not.toHaveBeenCalled(); + }); +}); + +describe('ObjectCalendar quick-create — a required field the dialog fills, locked by hand (objectstack#37448)', () => { + it('a required `uiReadonly` select with no default is not auto-filled: the day goes to the full form', async () => { + const { ds, onEdit } = await mount({ ...FIELDS, status: { ...FIELDS.status, uiReadonly: true } }); + clickDay(); + expect(onEdit).toHaveBeenCalledTimes(1); + expect(screen.queryByRole('dialog')).toBeNull(); + expect(ds.create).not.toHaveBeenCalled(); + }); + + it('a required `uiReadonly` field with a default keeps the dialog and is left out of its write', async () => { + const { ds, onEdit } = await mount({ + ...FIELDS, + status: { ...FIELDS.status, uiReadonly: true, defaultValue: 'completed' }, + }); + clickDay(); + expect(await screen.findByRole('dialog')).toBeTruthy(); + expect(onEdit).not.toHaveBeenCalled(); + fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Call Ada' } }); + fireEvent.click(screen.getByRole('button', { name: 'Create' })); + await waitFor(() => expect(ds.create).toHaveBeenCalledTimes(1)); + expect(ds.create.mock.calls[0][1]).toEqual({ subject: 'Call Ada', starts_on: '2026-10-20', ends_on: '2026-10-20' }); + }); + + it('CONTROL: with no lock the dialog writes the auto-filled select', async () => { + const { ds } = await mount(FIELDS); + clickDay(); + expect(await screen.findByRole('dialog')).toBeTruthy(); + fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Call Ada' } }); + fireEvent.click(screen.getByRole('button', { name: 'Create' })); + await waitFor(() => expect(ds.create).toHaveBeenCalledTimes(1)); + expect(ds.create.mock.calls[0][1]).toEqual({ subject: 'Call Ada', starts_on: '2026-10-20', ends_on: '2026-10-20', status: 'planned' }); + }); +}); diff --git a/ui/packages/plugin-calendar/src/ObjectCalendar.tsx b/ui/packages/plugin-calendar/src/ObjectCalendar.tsx index 2ab17862fac..fa27ed8ac5c 100644 --- a/ui/packages/plugin-calendar/src/ObjectCalendar.tsx +++ b/ui/packages/plugin-calendar/src/ObjectCalendar.tsx @@ -416,6 +416,7 @@ interface QuickCreateFieldDef { type?: unknown; required?: unknown; readonly?: unknown; + uiReadonly?: unknown; system?: unknown; defaultValue?: unknown; options?: unknown; @@ -488,11 +489,33 @@ function requiredFieldsQuickCreateCannotFill(fieldsMeta: unknown, provided: Read for (const [name, def] of quickCreateFieldEntries(fieldsMeta)) { if (!name || provided.has(name) || !def?.required) continue; if (def.readonly === true || def.system === true || def.type === 'autonumber') continue; + // A field read-only by hand (`uiReadonly`) is left out of the write, as + // the create dialog leaves it out (objectstack#37448): the server applies + // its `defaultValue`, and without one the write would be refused for it. + if (fieldStaticallyReadOnlyByHand(def)) { + if (def.defaultValue === undefined || def.defaultValue === null) unfillable.push(name); + continue; + } if (!quickCreateFill(def)) unfillable.push(name); } return unfillable; } +/** + * The fields the quick-create dialog writes itself — the title field and the + * date fields — that are read-only by hand on every record (`readonly` or + * `uiReadonly`, the static half of `fieldStaticallyReadOnlyByHand`; a create + * is judged by the static half only, objectstack#37448). The dialog cannot + * leave them out of its own write, so where one is locked the gesture goes to + * the host's full create form, which leaves it off. + */ +function quickCreateLockedOwnFields(config: ObjectCalendarConfig, fieldsMeta: unknown): string[] { + const defs = new Map(quickCreateFieldEntries(fieldsMeta)); + return [config.titleField || 'name', config.startDateField, config.endDateField] + .filter((key): key is string => !!key) + .filter((key) => fieldStaticallyReadOnlyByHand(defs.get(key))); +} + /** * A record the calendar cannot place: the field declared as `startDateField` * carries no value on it, so there is no date to draw and none is invented @@ -1458,7 +1481,8 @@ export const ObjectCalendar: React.FC = ({ ), ) : []; - const quickCreateCanSucceed = quickCreateUnfillable.length === 0; + const quickCreateLockedOwn = calendarConfig ? quickCreateLockedOwnFields(calendarConfig, objectSchema?.fields) : []; + const quickCreateCanSucceed = quickCreateUnfillable.length === 0 && quickCreateLockedOwn.length === 0; // …and where it cannot, the same gesture opens the host's FULL create form // with the day it was made on (the triage direction on objectui#12291): a @@ -1468,7 +1492,10 @@ export const ObjectCalendar: React.FC = ({ const handOffToCreateForm = useCallback((start: Date, end?: Date) => { if (!calendarConfig || !schema.objectName || !onEdit) return; const fieldDefs = objectSchema?.fields as Record | undefined; - onEdit(quickCreateDateValues(calendarConfig, fieldDefs, start, end)); + // A date field read-only by hand is not prefilled: the form leaves it off. + const locked = new Set(quickCreateLockedOwnFields(calendarConfig, objectSchema?.fields)); + const values = quickCreateDateValues(calendarConfig, fieldDefs, start, end); + onEdit(Object.fromEntries(Object.entries(values).filter(([key]) => !locked.has(key)))); }, [calendarConfig, schema.objectName, onEdit, objectSchema]); // The two quick-create gestures (an empty-day click, a week / day range @@ -1507,6 +1534,8 @@ export const ObjectCalendar: React.FC = ({ // an object with any other one hands the gesture to the host's full form. for (const [name, def] of quickCreateFieldEntries(objectSchema?.fields)) { if (!name || name in payload || !def?.required) continue; + // Read-only by hand: left out, so the server applies its default. + if (fieldStaticallyReadOnlyByHand(def)) continue; const fill = quickCreateFill(def); if (fill) payload[name] = fill.value; } diff --git a/ui/packages/plugin-gantt/src/ObjectGantt.harness.test.tsx b/ui/packages/plugin-gantt/src/ObjectGantt.harness.test.tsx index f0830ac601f..fc07940adf2 100644 --- a/ui/packages/plugin-gantt/src/ObjectGantt.harness.test.tsx +++ b/ui/packages/plugin-gantt/src/ObjectGantt.harness.test.tsx @@ -50,6 +50,7 @@ import { SchemaRendererProvider, SchemaRenderer, notifyDataChanged } from '@obje import { I18nProvider } from '@object-ui/i18n'; import type { DataSource, DeclaredNode, ObjectGanttBlockNode } from '@object-ui/types'; import { safeValidateSchema } from '@object-ui/types/zod'; +import { toast } from 'sonner'; import { ObjectGantt } from './ObjectGantt'; import { GANTT_FETCH_STEP } from './ganttRowWalk'; // Module scope, not a hook: this import IS the registration (AGENTS.md @@ -2401,3 +2402,139 @@ describe('ObjectGantt.refusedRead-35317', () => { expect(screen.queryByTestId('gantt-no-access')).toBeNull(); }); }); + +// ── ObjectGantt.handLock-37448 ────────────────────────────────────────────────── + +/** + * objectstack#37448 — every in-chart write is an edit by hand, so the field + * hand lock (`@object-ui/core`'s one verdict: `readonly`, `uiReadonly`, and the + * conditional `readonlyWhen` / `uiReadonlyWhen`) holds on the Gantt. + * + * What is pinned: the STATIC half narrows the interaction switches the chart + * is handed (a move needs both dates, a resize either, the progress handle its + * field, the link UI the dependencies field); the CONDITIONAL half refuses, on + * the write, a drag, an in-place edit and a drawn link that change a field + * locked over THAT record, with the read-only reason toasted — and an in-place + * edit that only echoes a locked value is sent without it. + */ +describe('ObjectGantt.handLock-37448', () => { + const captured: { props: Record } = { props: {} }; + beforeEach(() => { + captured.props = {}; + standIns.ganttView = (props: any) => { + captured.props = props; + return
; + }; + vi.mocked(toast.error).mockClear(); + }); + + const DONE = "record.status == 'done'"; + const fieldsWith = (locks: Record>) => ({ + fields: { + name: { type: 'text' }, + status: { type: 'text' }, + start_date: { type: 'date', ...locks.start_date }, + end_date: { type: 'date', ...locks.end_date }, + progress: { type: 'number', ...locks.progress }, + deps: { type: 'text', ...locks.deps }, + }, + }); + + const ROWS = [ + { id: 't1', name: 'Open task', status: 'open', start_date: '2026-01-05', end_date: '2026-01-09', progress: 40, deps: '' }, + { id: 't2', name: 'Done task', status: 'done', start_date: '2026-01-12', end_date: '2026-01-16', progress: 100, deps: '' }, + ]; + + const SCHEMA: any = { + type: 'object-gantt', + objectName: 'project_task', + gantt: { + titleField: 'name', + startDateField: 'start_date', + endDateField: 'end_date', + progressField: 'progress', + dependenciesField: 'deps', + }, + }; + + function adapter(locks: Record>) { + return { + find: vi.fn(async () => ({ data: ROWS.map((r) => ({ ...r })), total: ROWS.length })), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(async () => ({})), + delete: vi.fn(), + getObjectSchema: vi.fn(async () => fieldsWith(locks)), + } as unknown as DataSource & { update: ReturnType }; + } + + async function mount(locks: Record>) { + const ds = adapter(locks); + render(); + await waitFor(() => expect(screen.getByTestId('gantt-view').getAttribute('data-task-count')).toBe('2')); + const task = (id: string) => (captured.props.tasks as any[]).find((t) => t.id === id); + return { ds, task }; + } + + it('the static half narrows the interaction switches the chart is handed', async () => { + await mount({ progress: { uiReadonly: true } }); + expect(captured.props.interactions).toEqual({ progress: false }); + cleanup(); + await mount({ start_date: { uiReadonly: true }, deps: { readonly: true } }); + expect(captured.props.interactions).toEqual({ move: false, link: false }); + cleanup(); + await mount({ start_date: { uiReadonly: true }, end_date: { uiReadonly: true } }); + expect(captured.props.interactions).toEqual({ move: false, resize: false }); + }); + + it('CONTROL: no lock hands the authored switches through untouched', async () => { + await mount({}); + expect(captured.props.interactions).toBeUndefined(); + }); + + it('a bar drag over a record whose date is locked by hand writes nothing and says why', async () => { + const { ds, task } = await mount({ start_date: { uiReadonlyWhen: DONE } }); + await act(async () => { + await captured.props.onTaskUpdate(task('t2'), { start: new Date(2026, 0, 13), end: new Date(2026, 0, 17) }); + }); + expect(ds.update).not.toHaveBeenCalled(); + expect(toast.error).toHaveBeenCalledWith('Save failed — the change was rolled back', { description: 'This field is read-only.' }); + // CONTROL: the open record takes the same drag. + await act(async () => { + await captured.props.onTaskUpdate(task('t1'), { start: new Date(2026, 0, 6), end: new Date(2026, 0, 10) }); + }); + expect(ds.update).toHaveBeenCalledTimes(1); + expect(ds.update.mock.calls[0][1]).toBe('t1'); + expect(Object.keys(ds.update.mock.calls[0][2]).sort()).toEqual(['end_date', 'start_date']); + }); + + it('an in-place edit that only echoes a locked value is sent without it; one that changes it is refused', async () => { + const { ds, task } = await mount({ progress: { uiReadonly: true } }); + await act(async () => { + await captured.props.onTaskUpdate(task('t1'), { title: 'Renamed', progress: 40 }); + }); + expect(ds.update).toHaveBeenCalledTimes(1); + expect(ds.update.mock.calls[0][2]).toEqual({ name: 'Renamed' }); + await act(async () => { + await captured.props.onTaskUpdate(task('t1'), { title: 'Renamed again', progress: 55 }); + }); + expect(ds.update).toHaveBeenCalledTimes(1); + expect(toast.error).toHaveBeenCalledTimes(1); + }); + + it('a drawn link into a record whose dependencies field is locked by hand writes nothing', async () => { + const { ds, task } = await mount({ deps: { uiReadonlyWhen: DONE } }); + await act(async () => { + await captured.props.onDependencyCreate(task('t1'), task('t2'), 'fs'); + }); + expect(ds.update).not.toHaveBeenCalled(); + expect(toast.error).toHaveBeenCalledTimes(1); + // CONTROL: the open record takes the link. + await act(async () => { + await captured.props.onDependencyCreate(task('t2'), task('t1'), 'fs'); + }); + expect(ds.update).toHaveBeenCalledTimes(1); + expect(ds.update.mock.calls[0][1]).toBe('t1'); + expect(ds.update.mock.calls[0][2]).toHaveProperty('deps'); + }); +}); diff --git a/ui/packages/plugin-gantt/src/ObjectGantt.tsx b/ui/packages/plugin-gantt/src/ObjectGantt.tsx index d65746de1f5..b83fa9ae809 100644 --- a/ui/packages/plugin-gantt/src/ObjectGantt.tsx +++ b/ui/packages/plugin-gantt/src/ObjectGantt.tsx @@ -39,6 +39,7 @@ import { useDataInvalidation, useFilterScope, useResolvedFilter, + usePredicateScope, classifyLoadError, } from '@object-ui/react'; import { useLocalization, useDisplayLocale, resolveFieldCurrency, formatDisplayNumber } from '@object-ui/i18n'; @@ -48,6 +49,7 @@ import { deriveRecordPageHref, } from '@object-ui/plugin-detail'; import { usePermissions } from '@object-ui/permissions'; +import { ganttHandLockedInteractions, ganttPatchByHand, type GanttLockDefs } from './ganttHandLock'; import { AlertDialog, AlertDialogAction, @@ -2106,6 +2108,19 @@ export const ObjectGantt: React.FC = ({ return () => { cancelled = true; }; }, [drawerRec, recordDetailHref, resource, dataSource]); + // The host's predicate scope, as the edit dialog binds it: the hand lock's + // conditional half is judged with it (objectstack#37448). + const predicateScope = usePredicateScope(); + + // A write the field hand lock refuses (`ganttPatchByHand`): nothing is sent, + // a fresh array identity redraws every bar from the unchanged rows, and the + // toast says why — the in-place editor closed on Enter, so a silent snap-back + // would read as a lost edit. + const refuseLockedWrite = useCallback(() => { + setData((prev) => prev.slice()); + toast.error(t('gantt.writeFailed'), { description: t('grid.readOnlyReason.readonly') }); + }, [t]); + // Persist a drag-driven reschedule back to the data source. Mirrors // ObjectCalendar.handleEventDropDefault: optimistic local patch, then // dataSource.update; on failure we revert and log. @@ -2131,6 +2146,18 @@ export const ObjectGantt: React.FC = ({ if (typeof changes.progress === 'number' && progressField) patch[progressField] = changes.progress; if (Object.keys(patch).length === 0) return; + // Every commit path lands here — drag, resize, progress, the in-place + // editor, auto-schedule, the conflict reschedule, undo and redo — so the + // field hand lock is judged here, over the stored record: a locked field + // the write changes refuses it, one it only echoes is left out of it. + const verdict = ganttPatchByHand(patch, stored, objectSchema?.fields as GanttLockDefs, predicateScope); + if (verdict.kind === 'refused') { + refuseLockedWrite(); + return; + } + for (const key of Object.keys(patch)) if (!(key in verdict.patch)) delete patch[key]; + if (Object.keys(patch).length === 0) return; + const recordId = (task as any).data?.id ?? (task as any).data?._id ?? task.id; if (recordId == null) return; @@ -2154,7 +2181,7 @@ export const ObjectGantt: React.FC = ({ notifyWriteError(err); } }, - [ganttConfig, effectiveDataSource, resource, data, reload, notifyWriteError, objectSchema], + [ganttConfig, effectiveDataSource, resource, data, reload, notifyWriteError, objectSchema, predicateScope, refuseLockedWrite], ); // Re-serialize a normalized dependency list back onto a record field, @@ -2183,6 +2210,13 @@ export const ObjectGantt: React.FC = ({ if (!depField) return; if (!effectiveDataSource || typeof effectiveDataSource.update !== 'function') return; const nextValue = serializeDependencies(raw, nextDeps); + // A link is an edit by hand of the TARGET's dependencies field: its + // hand lock over that record refuses it (`ganttPatchByHand`). + const target = data.find((r) => String(r.id ?? r._id) === String(targetId)) ?? {}; + if (ganttPatchByHand({ [depField]: nextValue }, target, objectSchema?.fields as GanttLockDefs, predicateScope).kind === 'refused') { + refuseLockedWrite(); + return; + } const prevSnapshot = data; setData((prev) => prev.map((r) => @@ -2198,7 +2232,7 @@ export const ObjectGantt: React.FC = ({ notifyWriteError(err); } }, - [ganttConfig, effectiveDataSource, resource, data, reload, notifyWriteError], + [ganttConfig, effectiveDataSource, resource, data, reload, notifyWriteError, objectSchema, predicateScope, refuseLockedWrite], ); // Persist a created/updated dependency (create + link type): upsert the source @@ -2586,7 +2620,14 @@ export const ObjectGantt: React.FC = ({ groupBy={groupByAccessor} defaultCollapsedDepth={ganttConfig?.defaultCollapsedDepth} summaryExtent={ganttConfig?.summaryExtent} - interactions={ganttConfig?.interactions} + // The static hand lock closes a gesture that can only write a field + // locked on every record (objectstack#37448); the rest is judged on + // the write, per record. + interactions={ganttHandLockedInteractions( + ganttConfig?.interactions, + objectSchema?.fields as GanttLockDefs, + ganttConfig, + )} dependencyTypes={ganttConfig?.dependencyTypes} timeZone={ganttConfig?.timeZone} onBeforeTaskUpdate={onBeforeTaskUpdate} diff --git a/ui/packages/plugin-gantt/src/ganttHandLock.ts b/ui/packages/plugin-gantt/src/ganttHandLock.ts new file mode 100644 index 00000000000..1ab2681b352 --- /dev/null +++ b/ui/packages/plugin-gantt/src/ganttHandLock.ts @@ -0,0 +1,107 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The Gantt's reads of the field hand lock (objectstack#37448, the two-tier + * field-lock model of `@objectstack/spec` `Field`, ruling record 7180466652). + * + * Every in-chart write is an edit by hand — a bar's drag and edge resize (the + * start / end fields), the progress handle (the progress field), the title and + * dates edited in place, the auto-schedule and conflict reschedule (the dates + * again) and a drawn dependency link (the dependencies field) — so each reads + * the one verdict of `@object-ui/core`, never `readonly` alone: + * + * - {@link ganttHandLockedInteractions}, the STATIC half + * (`fieldStaticallyReadOnlyByHand`: `readonly`, or the hand lock + * `uiReadonly`): a gesture that can only write a field locked on every + * record is not drawn; + * - {@link ganttPatchByHand}, the FULL verdict over the stored record + * (`fieldReadOnlyByHand`, `readonlyWhen` and `uiReadonlyWhen` included), + * judged on the write itself, so every commit path — undo and redo too — + * meets it. + */ +import { fieldReadOnlyByHand, fieldStaticallyReadOnlyByHand, type FieldHandLockDef } from '@object-ui/core'; +import type { GanttInteractions } from './GanttView'; + +/** The field definitions the verdict reads, keyed by field name. */ +export type GanttLockDefs = Record | undefined; + +/** The Gantt block's write targets. */ +export interface GanttWriteFields { + startDateField: string; + endDateField: string; + progressField?: string; + dependenciesField?: string; +} + +/** + * The author's interaction switches, narrowed by the static hand lock: a move + * writes both dates, so either locked closes it; a resize writes one edge, so + * only both locked closes it (the write gate refuses the locked edge); the + * progress handle and the link UI write one field each. The switches only + * narrow: an authored `false` stays `false`. + */ +export function ganttHandLockedInteractions( + authored: GanttInteractions | undefined, + defs: GanttLockDefs, + fields: GanttWriteFields, +): GanttInteractions | undefined { + const locked = (name: string | undefined): boolean => !!name && fieldStaticallyReadOnlyByHand(defs?.[name]); + const startLocked = locked(fields.startDateField); + const endLocked = locked(fields.endDateField); + const closed: GanttInteractions = { + ...(startLocked || endLocked ? { move: false } : {}), + ...(startLocked && endLocked ? { resize: false } : {}), + ...(locked(fields.progressField) ? { progress: false } : {}), + ...(locked(fields.dependenciesField) ? { link: false } : {}), + }; + if (Object.keys(closed).length === 0) return authored; + return { ...(authored ?? {}), ...closed }; +} + +/** The outcome of judging one write: what to send, or a refusal. */ +export type GanttPatchVerdict = + | { kind: 'write'; patch: Record } + | { kind: 'refused'; field: string }; + +/** Does `next` leave the stored value where it is? Dates compare as instants. */ +function sameStoredValue(next: unknown, stored: unknown): boolean { + if (next === stored) return true; + if (next == null || stored == null) return false; + if (typeof next === 'string' && typeof stored === 'string') { + const a = Date.parse(next); + const b = Date.parse(stored); + return !Number.isNaN(a) && a === b; + } + return false; +} + +/** + * Judge a patch over the record it writes: a field read-only by hand over that + * record whose value the patch CHANGES refuses the whole patch (the chart puts + * the bar back); one the patch leaves unchanged is dropped from it, so an + * in-place edit of the title does not send the locked dates it echoes back. + */ +export function ganttPatchByHand( + patch: Record, + stored: Record, + defs: GanttLockDefs, + scope: Record | undefined, +): GanttPatchVerdict { + const out: Record = {}; + for (const [field, value] of Object.entries(patch)) { + const def = defs?.[field]; + if (!fieldReadOnlyByHand(def, stored, { scope, fieldContext: `field '${field}'` })) { + out[field] = value; + continue; + } + if (sameStoredValue(value, stored[field])) continue; + return { kind: 'refused', field }; + } + return { kind: 'write', patch: out }; +} diff --git a/ui/packages/plugin-gantt/src/useGanttTranslation.ts b/ui/packages/plugin-gantt/src/useGanttTranslation.ts index 6bfc6358f11..3d3e9e08e5e 100644 --- a/ui/packages/plugin-gantt/src/useGanttTranslation.ts +++ b/ui/packages/plugin-gantt/src/useGanttTranslation.ts @@ -122,6 +122,9 @@ export const GANTT_DEFAULT_TRANSLATIONS: Record = { // provider-less fallback and say exactly what the `en` pack says. 'list.loadErrorForbiddenTitle': 'You don’t have access', 'list.loadErrorForbiddenMessage': 'You don’t have permission to view these records. Contact your administrator if you think you should have access.', + // The reason a write the field hand lock refuses carries (objectstack#37448), + // the grid's own sentence for a read-only cell. + 'grid.readOnlyReason.readonly': 'This field is read-only.', }; /** The defaults are English, so English plural rules pick a family's row. */ diff --git a/ui/packages/plugin-kanban/src/ObjectKanban.handLock-36806.test.tsx b/ui/packages/plugin-kanban/src/ObjectKanban.handLock-36806.test.tsx index 35291610337..d677ce6ff4a 100644 --- a/ui/packages/plugin-kanban/src/ObjectKanban.handLock-36806.test.tsx +++ b/ui/packages/plugin-kanban/src/ObjectKanban.handLock-36806.test.tsx @@ -138,3 +138,66 @@ describe('ObjectKanban: the lane field\'s lock closes the drag (objectstack#3680 } }); }); + +/** + * objectstack#37448 — the swimlane board. A drop between columns writes the + * lane field and nothing else: a drop into another swimlane's row moves the + * card's COLUMN, never its swimlane value (`KanbanImpl`'s drop hands the mover + * column ids only), so a hand-locked swimlane field is never written by a + * drag. The lane field's own lock holds on this layout as on the flat board. + */ +describe('ObjectKanban: a drag on the swimlane board (objectstack#37448)', () => { + const ROWS = [ + { id: 't1', title: CARD, status: 'backlog', owner: 'ann' }, + { id: 't2', title: 'Ship the gadget', status: 'in_progress', owner: 'bob' }, + ]; + + function swimlaneSource(laneLock: Record) { + return { + getObjectSchema: vi.fn(async () => ({ + name: OBJECT, + fields: { + title: { type: 'text', label: 'Title' }, + status: statusField(laneLock), + owner: { type: 'text', label: 'Owner', uiReadonly: true }, + }, + })), + find: vi.fn(async () => ({ value: ROWS.map((r) => ({ ...r })) })), + update: vi.fn(async () => ({ id: 't1', status: 'in_progress' })), + } as unknown as DataSource & { update: ReturnType }; + } + + async function mountSwimlanes(laneLock: Record) { + const ds = swimlaneSource(laneLock); + render(); + expect(await screen.findByText(CARD)).toBeTruthy(); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); + await act(async () => { + await Promise.resolve(); + }); + // The swimlane layout, not the flat board. + await waitFor(() => expect(document.querySelector('[data-swimlane-scroll-row]')).not.toBeNull()); + return ds; + } + + /** Drop `t1` onto `t2`: another column AND another swimlane. */ + async function dropAcrossSwimlanes() { + expect(dnd.onDragEnd).toBeTypeOf('function'); + await act(async () => { + dnd.onDragEnd!({ active: { id: 't1' }, over: { id: 't2' } }); + }); + } + + it('a drop into another swimlane writes the lane field only, never the hand-locked swimlane field', async () => { + const ds = await mountSwimlanes({}); + await dropAcrossSwimlanes(); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update).toHaveBeenCalledWith(OBJECT, 't1', { status: 'in_progress' }); + }); + + it('the lane field\'s `uiReadonlyWhen` TRUE over the dragged record writes nothing on this layout too', async () => { + const ds = await mountSwimlanes({ uiReadonlyWhen: "record.status == 'backlog'" }); + await dropAcrossSwimlanes(); + expect(ds.update).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index a4e507026cf..405adba36f2 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -4565,8 +4565,9 @@ export const ListView = React.forwardRef(({ // [objectstack#36806] The field locks' operands (`readonlyWhen`, // `uiReadonlyWhen`) of every field a person edits in place from // this list: the shown grid columns, the kanban's lane field (a card - // drag writes it) and the calendar's start / end fields (an event - // drag writes them). Each surface judges the lock over the ROW + // drag writes it — the block's `groupByField`, else the lane field + // the board detects off the object's lifecycle, `kanbanLaneFieldOf`) + // and the calendar's start / end fields (an event drag writes them). Each surface judges the lock over the ROW // (`fieldReadOnlyByHand`), so a row projected without the operand // faulted `No such key`: open for `readonlyWhen` (the server drops // the write), locked for the hand lock (nothing behind it judges @@ -4578,7 +4579,7 @@ export const ListView = React.forwardRef(({ const lockDefs = objectDef?.fields as Record | undefined; const editedInPlace = [ ...cols, - (schema.kanban as { groupByField?: unknown } | undefined)?.groupByField, + kanbanLaneFieldOf(schema, objectDef), (schema.calendar as { startDateField?: unknown } | undefined)?.startDateField, (schema.calendar as { endDateField?: unknown } | undefined)?.endDateField, ].filter((name): name is string => typeof name === 'string' && name.length > 0); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.lockOperandSelect-36806.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.lockOperandSelect-36806.test.tsx index 1f8f03d6ce9..6830b95b0f7 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.lockOperandSelect-36806.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.lockOperandSelect-36806.test.tsx @@ -75,18 +75,18 @@ const objectDef = { }, }; -const makeDataSource = () => +const makeDataSource = (def: Record = objectDef) => ({ find: vi.fn(async () => ({ data: [], total: 0 })), findOne: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn(), - getObjectSchema: vi.fn(async (name: string) => (name === OBJECT ? objectDef : null)), + getObjectSchema: vi.fn(async (name: string) => (name === OBJECT ? def : null)), }) as any; -async function selectFor(extra: Record): Promise { - const dataSource = makeDataSource(); +async function selectFor(extra: Record, def?: Record): Promise { + const dataSource = makeDataSource(def); const schema: any = { type: 'list-view', objectName: OBJECT, viewType: 'grid', userActions: { editInline: false }, ...extra }; render( @@ -130,6 +130,17 @@ describe('ListView — the field locks\' operands are projected (objectstack#368 expect(select).toContain('stage'); }); + it('objectstack#37448 — the lane field the board detects when the block names none', async () => { + // No `groupByField`: the board takes the object's declared lifecycle + // (`stageField`, ADR-0085), so a card drag writes `stage` and its + // predicate's operand rides the projection as the named lane field's does. + const select = await selectFor( + { viewType: 'kanban', columns: ['title'], kanban: {} }, + { ...objectDef, stageField: 'stage' }, + ); + expect(select).toContain('status'); + }); + it('the calendar start and end fields\' operands', async () => { const select = await selectFor({ viewType: 'calendar', diff --git a/ui/packages/plugin-timesheet/src/ObjectTimesheet.tsx b/ui/packages/plugin-timesheet/src/ObjectTimesheet.tsx index 54e4ec08996..2964a327229 100644 --- a/ui/packages/plugin-timesheet/src/ObjectTimesheet.tsx +++ b/ui/packages/plugin-timesheet/src/ObjectTimesheet.tsx @@ -49,6 +49,7 @@ import { useResolvedFilter, useSafeFieldLabel, useSettledSchema, + usePredicateScope, notifyDataChanged, NonGridRowCeilingNote, } from '@object-ui/react'; @@ -70,6 +71,8 @@ import { usePermissions } from '@object-ui/permissions'; import { applyNonGridRowCeiling, buildExpandFields, + fieldReadOnlyByHand, + fieldStaticallyReadOnlyByHand, mergeFilterNodes, nonGridRowCeilingQuery, resolveAffordance, @@ -310,9 +313,27 @@ function TimesheetGridView({ schema, objectName, binding, dataSource, className, // who may create, and a write the caller may not make is refused with a // message before it goes out. With no permission provider every row reads // open. + // + // objectstack#37448 — and each is an edit by hand, so the field hand lock + // holds (`@object-ui/core`'s one verdict, never `readonly` alone). A create + // writes the row fields, the date field and the value field, judged by the + // static half as the create dialog judges a create: one of them read-only by + // hand on every record (`readonly`, `uiReadonly`) leaves no create. Retyping + // or clearing a one-record cell edits that record's value field, judged over + // the stored record (`readonlyWhen` and `uiReadonlyWhen` included). const writeSource = { objectSchema: (objectSchema ?? null) as SchemaLike | null, objectName, perms }; + const predicateScope = usePredicateScope(); + const lockDefs = objectSchema?.fields as Record | undefined> | undefined; + const createLockedByHand = [...binding.rowFields, binding.dateField, binding.valueField].some((f) => + fieldStaticallyReadOnlyByHand(lockDefs?.[f]), + ); + const valueLockedByHand = (record: Record): boolean => + fieldReadOnlyByHand(lockDefs?.[binding.valueField], record, { + scope: predicateScope, + fieldContext: `field '${binding.valueField}'`, + }); const grants: CellWriteGrants = { - create: resolveAffordance('gridAddRow', writeSource).allowed, + create: resolveAffordance('gridAddRow', writeSource).allowed && !createLockedByHand, update: resolveAffordance('listInlineEdit', writeSource).allowed && resolveFieldAffordance('listInlineEdit', perms, objectName, binding.valueField), @@ -327,7 +348,10 @@ function TimesheetGridView({ schema, objectName, binding, dataSource, className, return; } const write = planCellWrite(binding, row, day, cell, parsed, fieldDef(binding.dateField)?.type); - if (write.kind === 'none' || write.kind === 'readonly' || !dataSource) { + // The cell drew its input before this record was locked: judged again at + // the commit, over the record the write changes. + const lockedNow = (write.kind === 'update' || write.kind === 'delete') && valueLockedByHand(cell.records[0]); + if (write.kind === 'none' || write.kind === 'readonly' || lockedNow || !dataSource) { setDrafts(({ [id]: _dropped, ...rest }) => rest); return; } @@ -458,7 +482,7 @@ function TimesheetGridView({ schema, objectName, binding, dataSource, className, const cell = row.cells[day]; const id = cellId(row.key, day); const label = t('timesheet.cellLabel', { row: name, day: dayHeading.format(fromDayKey(day)) }); - if (!cellEditable(cell, grants)) { + if (!cellEditable(cell, grants, valueLockedByHand)) { const shown = cell.records.length > 0 ? numberFormat.format(cell.sum) : ''; return ( diff --git a/ui/packages/plugin-timesheet/src/__tests__/ObjectTimesheet.test.tsx b/ui/packages/plugin-timesheet/src/__tests__/ObjectTimesheet.test.tsx index b412019a9b2..cf67c7fff3c 100644 --- a/ui/packages/plugin-timesheet/src/__tests__/ObjectTimesheet.test.tsx +++ b/ui/packages/plugin-timesheet/src/__tests__/ObjectTimesheet.test.tsx @@ -357,3 +357,63 @@ describe('ObjectTimesheet cell writes under each grant (#34382)', () => { expect(screen.getByTestId('timesheet-add-row')).toBeTruthy(); }); }); + +/** + * objectstack#37448 — a cell write is an edit by hand, so the field hand lock + * holds (`@object-ui/core`'s one verdict). Retyping or clearing a one-record + * cell edits that record's value field, judged over the record + * (`uiReadonlyWhen` included); a create writes the row, date and value fields, + * judged by the static half as the create dialog judges a create. + */ +describe('ObjectTimesheet — the field hand lock (objectstack#37448)', () => { + const lockedSchema = (locks: Record>) => ({ + ...objectSchema, + fields: { + ...objectSchema.fields, + status: { name: 'status', type: 'text', label: 'Status' }, + hours: { ...objectSchema.fields.hours, ...locks.hours }, + project: { ...objectSchema.fields.project, ...locks.project }, + }, + }); + + async function mountLocked(locks: Record>) { + const ds = makeDataSource([ + { id: 'r1', project: 'Apollo', work_date: '2026-11-16', hours: 2, status: 'approved' }, + { id: 'r2', project: 'Apollo', work_date: '2026-11-17', hours: 3, status: 'draft' }, + ]); + ds.getObjectSchema.mockResolvedValue(lockedSchema(locks) as any); + renderTimesheet(ds); + await waitFor(() => expect(screen.getAllByTestId('timesheet-row')).toHaveLength(1)); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); + return ds; + } + + /** Sunday..Saturday: whether each day's cell is an input. Monday holds r1, Tuesday r2. */ + const inputs = (): boolean[] => + Array.from(screen.getByTestId('timesheet-row').querySelectorAll('td')) + .slice(1, 8) + .map((td) => td.querySelector('[data-testid="timesheet-cell"]') !== null); + + it('a record whose value field is locked by hand draws a read-only cell; the other record still edits', async () => { + const ds = await mountLocked({ hours: { uiReadonlyWhen: "record.status == 'approved'" } }); + await waitFor(() => expect(inputs()).toEqual([true, false, true, true, true, true, true])); + const tuesday = screen.getAllByTestId('timesheet-cell')[1] as HTMLInputElement; + expect(tuesday.value).toBe('3'); + fireEvent.change(tuesday, { target: { value: '5' } }); + fireEvent.blur(tuesday); + await waitFor(() => expect(ds.update).toHaveBeenCalledWith('time_entry', 'r2', { hours: 5 })); + expect(ds.update).toHaveBeenCalledTimes(1); + }); + + it('a value field locked by hand on every record takes no create, no edit and no clear', async () => { + await mountLocked({ hours: { uiReadonly: true } }); + await waitFor(() => expect(inputs()).toEqual([false, false, false, false, false, false, false])); + expect(screen.queryByTestId('timesheet-add-row')).toBeNull(); + }); + + it('a row field locked by hand closes the create only: stored values still edit', async () => { + await mountLocked({ project: { uiReadonly: true } }); + await waitFor(() => expect(inputs()).toEqual([false, true, true, false, false, false, false])); + expect(screen.queryByTestId('timesheet-add-row')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-timesheet/src/timesheetModel.ts b/ui/packages/plugin-timesheet/src/timesheetModel.ts index 27e7f5c5dc6..369f20439db 100644 --- a/ui/packages/plugin-timesheet/src/timesheetModel.ts +++ b/ui/packages/plugin-timesheet/src/timesheetModel.ts @@ -337,10 +337,23 @@ export interface CellWriteGrants { * Whether a cell offers an input: an empty cell when the caller may create, a * one-record cell when they may update or clear it, and a cell holding * several records never. + * + * `lockedByHand` answers whether the value field is read-only by hand over a + * stored record (the field hand lock — `uiReadonly`, or `uiReadonlyWhen` TRUE + * over the record — and the server lock, `fieldReadOnlyByHand` in + * `@object-ui/core`, objectstack#37448): typing into or clearing a one-record + * cell is an edit by hand of that record, so a locked record's cell draws no + * input. An empty cell's create is judged by the static half only, as the + * create dialog judges it — the view folds that into `grants.create`. */ -export function cellEditable(cell: TimesheetCell, grants: CellWriteGrants): boolean { +export function cellEditable( + cell: TimesheetCell, + grants: CellWriteGrants, + lockedByHand: (record: Record) => boolean = () => false, +): boolean { if (cell.records.length > 1) return false; if (cell.records.length === 0) return grants.create; + if (lockedByHand(cell.records[0])) return false; return grants.update || grants.delete; }