diff --git a/.changeset/39182-action-notices.md b/.changeset/39182-action-notices.md new file mode 100644 index 00000000000..95d88b48019 --- /dev/null +++ b/.changeset/39182-action-notices.md @@ -0,0 +1,32 @@ +--- +'@objectstack/spec': minor +'@objectstack/lint': minor +'@objectstack/metadata-core': minor +'@object-ui/core': patch +--- + +feat(spec): `notices` on an action, warnings its dialog draws before submit, in `record:alert`'s vocabulary + +Clause-②: yes (widening) +Metadata-protocol: added + +An action that opens a dialog before it runs (a param dialog, or the confirm dialog of `confirmText`) can now declare `notices`: a map from a snake_case notice name to a notice the dialog draws above its description, each while its condition holds. + +```yaml +notices: + mail_not_delivered: + severity: warning + title: No email will be sent + body: This deployment does not deliver mail. + visible: features.emailDelivery != true +``` + +- **`record:alert`'s vocabulary.** A notice takes the record page banner's names: `severity`, `title`, `body`, and `visible` for its condition. `severity` is the banner's own closed set (`info`, `warning`, `error`, `success`), one schema mounted by both: `RecordAlertProps.severity` now mounts it too, with the same values. The banner's `icon`, `action`, `dismissible` and `dismissKey` are refused on a notice, each with a sentence saying why; `label` renames to `title`, as it does in a translation bundle. +- **Plain text.** `title` and `body` are `I18nLabel`s: a non-blank string or an inline locale map, with no markup, link, button or template. A notice declares at least one of them. An unknown severity, a non-string label, a blank one, or a notice with neither is refused at parse. +- **Named, so each notice has a stable translation key.** The text is translated at `objects.._actions..notices..title` / `.body` (`globalActions..notices..*` for an action with no object). `translateAction` overlays it leaf by leaf, only for the leaves a declared notice authors. `os validate` reports a translated notice the action does not declare, or a translated leaf the notice does not author (`translation-target-unknown`), and the translation extractor lists each declared leaf. +- **The action's own condition.** `visible` takes the shape of the action's `visible` and reads the same scope (the record the surface holds, the signed-in user, `features`), with no new root. `os validate` checks it as it checks the action's `visible`. Omitted, the notice is drawn whenever the dialog opens. +- **Only on a dialog host.** `notices` on an action with neither `confirmText` nor a non-empty `params` is refused at parse: no dialog opens to draw it. +- **Display only.** Nothing gates on a notice. The action's endpoint, its outcome and its outcome copy are unchanged by it. The served object schema's field mask reads only a notice's `visible`: a notice whose `title` or `body` mentions a field the caller cannot read does not remove the action from what that caller is served, and a notice whose `visible` reads such a field removes the action, as any other condition on it does. +- `alerts` and `warnings` on an action are refused with a rename to `notices`. + +The key is `planned` in the liveness ledger: it parses, translates and is checked, and the console's dialogs do not draw it yet. `@object-ui/core` lists `notices` among the spec's action keys, so the console stops treating it as an unknown key. diff --git a/content/docs/protocol/objectui/actions.mdx b/content/docs/protocol/objectui/actions.mdx index 03833395726..da4e6d0af65 100644 --- a/content/docs/protocol/objectui/actions.mdx +++ b/content/docs/protocol/objectui/actions.mdx @@ -234,6 +234,7 @@ interface Action { params?: ActionParam[]; // Inputs collected before execution submitText?: I18nLabel; // The param dialog's submit button verb (default "Confirm") cancelText?: I18nLabel; // The confirm or param dialog's dismiss button label (default "Cancel") + notices?: Record; // Notices the confirm or param dialog draws above its description, each while its condition holds preflight?: Preflight; // A same-origin GET the param dialog sends and shows above the params before submit method?: 'POST' | 'PATCH' | 'PUT' | 'DELETE'; // for type: 'api' @@ -565,6 +566,36 @@ cancelText: Keep invitation - `cancelLabel` (the button's spelling on the console's `form` and `alert-dialog` renderers) is refused with a rename to `cancelText`. - The console draws it on the dismiss button of both dialogs, from the translation bundle first and then the authored text. Without it, the button says **Cancel**. `sys_invitation`'s **Cancel Invitation** action declares **Keep invitation**. +### Warning before submit: `notices` + +> **Planned.** The key parses, translates and is checked at build time, but the console's dialogs do not draw it yet. An author who writes it today sees no notice in the dialog. + +Some actions need to tell the user something before they click, and only when a condition holds: no mail is delivered on this deployment, so the invitation will not reach anyone by email; this quote is past its expiry. `description` says the same thing every time. `notices` says it when it applies. + +```yaml +name: invite_user +label: Invite User +objectName: sys_member +type: api +target: /api/v1/auth/organization/invite-member +params: + - { name: email, type: email, required: true } +notices: + mail_not_delivered: + severity: warning + title: No email will be sent + body: This deployment does not deliver mail. Only an invitee who signs in with a social or SSO account that verifies the address can accept. + visible: features.emailDelivery != true +``` + +- **`record:alert`'s vocabulary.** Each notice takes the record page banner's field names: `severity` (`info`, `warning`, `error` or `success`, the same closed set; omitted, the console draws `info`), `title`, `body`, and `visible` for its condition. The banner's `icon`, `action`, `dismissible` and `dismissKey` are not declared here, and each is refused with a sentence that says why. +- **Plain text.** `title` and `body` are `I18nLabel`s: a plain string or an inline locale map, never blank, with no markup, link, button or `${…}` template. A notice declares at least one of the two. +- **Named, so each has a stable translation key.** The map key is a snake_case notice name, and the text is translated at `objects.._actions..notices..title` and `.body` (`globalActions..notices..*` for an action with no `objectName`). A translation keyed to a notice the action does not declare is reported by `os validate` (`translation-target-unknown`). Several notices are drawn in the order they are declared. +- **The condition is the action's own.** `visible` takes the shape of the action's `visible` (a boolean, a CEL string or a `{ dialect, source }` envelope) and reads the same scope: the record the surface holds, the signed-in user and `features`. It does not see the values typed into the dialog. Omit it to draw the notice whenever the dialog opens. `os validate` checks it as it checks the action's `visible`. +- **Either pre-run dialog.** The confirm dialog of a param-less action with `confirmText` and the param dialog of an action with a non-empty `params` draw the notices above the description. An action that declares neither opens no dialog, so `notices` there is refused at parse. +- **Display only.** The action's endpoint, its `outcome` answer and its outcome copy are the same with or without a notice. A notice that is wrong or not drawn misleads the reader and gates nothing. +- `alerts` and `warnings` are refused with a rename to `notices`. + ### Showing a server read before submit: `preflight` > **Live.** The console's param dialog sends the read once every `${param.NAME}` hole in `read.url` has a value, draws the answer at `path` above the params (each `fields` row as the result dialog draws it), and applies each `seed` only from the answer to the current URL. A seeded param is drawn read-only and submitted as shown. A refused, unbound or failed read leaves the seeds empty. diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 7c60c56deea..20d66d474ce 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -547,6 +547,7 @@ const result = ApiMethod.parse(data); | **params** | `{ name?: string; field?: string; objectOverride?: string; label?: string \| Record; … }[]` | optional | Input parameters required from user — an ActionParam[] DEFINITION array, never a payload map (a static request body goes in `bodyExtra`). A param name (its `name`, or the `field` a field-backed param reads) may repeat only for per-gate variants of ONE input (declarations that differ in `visible` / `requiresFeature`, e.g. one optional and one required); the params check treats the name as `required` only when EVERY declaration of it requires it, and judges its value by the FIRST declaration's shape (`type`, `multiple`, `options`), so keep that shape identical across them. | | **submitText** | `string \| Record` | optional | Label of the submit button in the action's param dialog, the verb the button performs (e.g. "Send", "Log Call"), in place of the default "Confirm" — the default-language string, or an inline locale map; translated at `objects.OBJECT._actions.ACTION.submitText` (`globalActions.ACTION.submitText` for an object-less action). Only on an action with a non-empty `params`: without one no param dialog opens, so it is refused. Not `confirmText`, which is the message of a param-less action's confirm dialog. A blank label is refused. | | **cancelText** | `string \| Record` | optional | Label of the dismiss button on the dialog the action opens before it runs — the confirm dialog of a param-less action that declares `confirmText`, or the param dialog of an action with a non-empty `params` — in place of the default "Cancel". Name what dismissing keeps where the action's own verb is "Cancel …" or "Close …" (e.g. "Keep invitation" beside "Cancel Invitation"). The default-language string, or an inline locale map; translated at `objects.OBJECT._actions.ACTION.cancelText` (`globalActions.ACTION.cancelText` for an object-less action). Only on an action that opens one of those dialogs: with neither `confirmText` nor a non-empty `params` no dialog opens, so it is refused. The dismiss twin of `submitText`, as on `object-form`. A blank label is refused. | +| **notices** | `Record; title?: string \| Record; body?: string \| Record; visible?: boolean \| string \| object }>` | optional | Notices the dialog the action opens before it runs (the confirm dialog of a param-less action that declares `confirmText`, or the param dialog of an action with a non-empty `params`) draws above its description, each while its condition holds — keyed by a snake_case notice name, drawn in declared order. Each notice takes `record:alert`'s vocabulary: `severity` (info / warning / error / success), `title` and `body` (plain text, a string or an inline locale map, at least one of the two; translated at `objects.OBJECT._actions.ACTION.notices.NAME.title` / `.body`, `globalActions.ACTION.notices.NAME.*` for an object-less action), and `visible`, a condition in the shape and scope of the action's own `visible`, without the dialog's typed values. Display only: the action runs and answers the same with or without a notice. Only on an action that opens one of those dialogs, else refused. | | **variant** | `Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'link'>` | optional | Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent) | | **order** | `number` | optional | Sort order within a location group (lower = higher). Promotes/demotes an action toward the record page header's primary button; stable, so actions without `order` keep their registration order. | | **confirmText** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object } \| string \| Record` | optional | Confirmation message before execution — a `template` slot (ADR-0032): a bare string is shorthand for `{ dialect: 'template', source }`, and text with no hole is shown as written. Holes are `{{ path }}` or `{{ path \| formatter[:arg] }}` over `record`, the record the action runs against (the clicked row on a list, else the page's record), and — only when the action's `params` is an object of static values — `params` (`{{ params.tier }}`); an input list binds nothing, since its values are collected after the confirmation. Formatters come from the template engine's whitelist (`TEMPLATE_FORMATTERS`, `@objectstack/formula`); a hole holds no logic (no CEL, no arithmetic). Example: 'Delete `{{ record.name }}`?'. A hole over any other root, a `${…}` or single-brace `{x}` token (each named with its `{{ }}` spelling), a hole holding logic or an unknown formatter, and a blank sentence are named and refused at `objectstack validate`, `compile` and the publish gate; the text still parses, so a stored one loads until its next save. An inline locale map (`{ en, "zh-CN" }`) is accepted too, each value such a sentence. Pairing this with a non-empty `params` is refused — that opens a second dialog for one decision; put the question on `description` instead. Correct on a param-LESS action, where the confirm is the only dialog there is. | diff --git a/content/docs/references/ui/action.mdx b/content/docs/references/ui/action.mdx index b362c01d8b6..59e36d1db06 100644 --- a/content/docs/references/ui/action.mdx +++ b/content/docs/references/ui/action.mdx @@ -62,6 +62,7 @@ const result = ActionSchema.parse(data); | **params** | `{ name?: string; field?: string; objectOverride?: string; label?: string \| Record; … }[]` | optional | Input parameters required from user — an ActionParam[] DEFINITION array, never a payload map (a static request body goes in `bodyExtra`). A param name (its `name`, or the `field` a field-backed param reads) may repeat only for per-gate variants of ONE input (declarations that differ in `visible` / `requiresFeature`, e.g. one optional and one required); the params check treats the name as `required` only when EVERY declaration of it requires it, and judges its value by the FIRST declaration's shape (`type`, `multiple`, `options`), so keep that shape identical across them. | | **submitText** | `string \| Record` | optional | Label of the submit button in the action's param dialog, the verb the button performs (e.g. "Send", "Log Call"), in place of the default "Confirm" — the default-language string, or an inline locale map; translated at `objects.OBJECT._actions.ACTION.submitText` (`globalActions.ACTION.submitText` for an object-less action). Only on an action with a non-empty `params`: without one no param dialog opens, so it is refused. Not `confirmText`, which is the message of a param-less action's confirm dialog. A blank label is refused. | | **cancelText** | `string \| Record` | optional | Label of the dismiss button on the dialog the action opens before it runs — the confirm dialog of a param-less action that declares `confirmText`, or the param dialog of an action with a non-empty `params` — in place of the default "Cancel". Name what dismissing keeps where the action's own verb is "Cancel …" or "Close …" (e.g. "Keep invitation" beside "Cancel Invitation"). The default-language string, or an inline locale map; translated at `objects.OBJECT._actions.ACTION.cancelText` (`globalActions.ACTION.cancelText` for an object-less action). Only on an action that opens one of those dialogs: with neither `confirmText` nor a non-empty `params` no dialog opens, so it is refused. The dismiss twin of `submitText`, as on `object-form`. A blank label is refused. | +| **notices** | `Record; title?: string \| Record; body?: string \| Record; visible?: boolean \| string \| object }>` | optional | Notices the dialog the action opens before it runs (the confirm dialog of a param-less action that declares `confirmText`, or the param dialog of an action with a non-empty `params`) draws above its description, each while its condition holds — keyed by a snake_case notice name, drawn in declared order. Each notice takes `record:alert`'s vocabulary: `severity` (info / warning / error / success), `title` and `body` (plain text, a string or an inline locale map, at least one of the two; translated at `objects.OBJECT._actions.ACTION.notices.NAME.title` / `.body`, `globalActions.ACTION.notices.NAME.*` for an object-less action), and `visible`, a condition in the shape and scope of the action's own `visible`, without the dialog's typed values. Display only: the action runs and answers the same with or without a notice. Only on an action that opens one of those dialogs, else refused. | | **variant** | `Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'link'>` | optional | Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent) | | **order** | `number` | optional | Sort order within a location group (lower = higher). Promotes/demotes an action toward the record page header's primary button; stable, so actions without `order` keep their registration order. | | **confirmText** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object } \| string \| Record` | optional | Confirmation message before execution — a `template` slot (ADR-0032): a bare string is shorthand for `{ dialect: 'template', source }`, and text with no hole is shown as written. Holes are `{{ path }}` or `{{ path \| formatter[:arg] }}` over `record`, the record the action runs against (the clicked row on a list, else the page's record), and — only when the action's `params` is an object of static values — `params` (`{{ params.tier }}`); an input list binds nothing, since its values are collected after the confirmation. Formatters come from the template engine's whitelist (`TEMPLATE_FORMATTERS`, `@objectstack/formula`); a hole holds no logic (no CEL, no arithmetic). Example: 'Delete `{{ record.name }}`?'. A hole over any other root, a `${…}` or single-brace `{x}` token (each named with its `{{ }}` spelling), a hole holding logic or an unknown formatter, and a blank sentence are named and refused at `objectstack validate`, `compile` and the publish gate; the text still parses, so a stored one loads until its next save. An inline locale map (`{ en, "zh-CN" }`) is accepted too, each value such a sentence. Pairing this with a non-empty `params` is refused — that opens a second dialog for one decision; put the question on `description` instead. Correct on a param-LESS action, where the confirm is the only dialog there is. | @@ -193,6 +194,15 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | **visible** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Param visibility predicate (CEL); omits the param when false. | | **requiresFeature** | `Enum<'twoFactor' \| 'organization' \| 'multiOrgEnabled' \| 'degradedTenancy' \| …>` | optional | Public auth feature flag gating this param; lowered into `visible` at parse time. | +### Nested Shape: `Action.notices[string]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **severity** | `Enum<'info' \| 'warning' \| 'error' \| 'success'>` | optional | Notice severity, `record:alert`'s closed set: `info`, `warning`, `error` or `success`. Styles the notice and picks its icon. Renderer default: `info`. | +| **title** | `string \| Record` | optional | Notice title — plain text, a string or an inline locale map (`{ en, "zh-CN", … }`); translated at `objects.OBJECT._actions.ACTION.notices.NAME.title` (`globalActions.ACTION.notices.NAME.title` for an object-less action). No markup, link or template. A blank title is refused. | +| **body** | `string \| Record` | optional | Notice body — plain text, a string or an inline locale map; translated at `objects.OBJECT._actions.ACTION.notices.NAME.body` (`globalActions.ACTION.notices.NAME.body` for an object-less action). Says in words what to do; no markup, link or template. A blank body is refused. | +| **visible** | `boolean \| string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | When the notice is drawn — the shape and the scope of the action's own `visible`: a boolean literal, a CEL string or a `{ dialect, source }` envelope, judged against the record the surface holds, the signed-in user and `features`. It does not see the values typed into the dialog. Omit to draw the notice whenever the dialog opens. | + ### Nested Shape: `Action.resultDialog` | Property | Type | Required | Description | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md index 8fe52322aeb..bcd6becd743 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `system/` | 413 | +| `system/` | 414 | diff --git a/packages/lint/src/i18n-walk-action-notices.ts b/packages/lint/src/i18n-walk-action-notices.ts new file mode 100644 index 00000000000..bc3b1392cdc --- /dev/null +++ b/packages/lint/src/i18n-walk-action-notices.ts @@ -0,0 +1,34 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The translation slots of an action's `notices` (`ActionSchema.notices`), for + * the extract in `i18n-walk.ts`: one `notices..title` and one + * `notices..body` per notice the action declares, relative to the + * action's translation root (`objects.._actions.` or + * `globalActions.`) — the address `translateAction` overlays + * (`spec/system/i18n-action-notices.ts`). + * + * Only for an action that opens a dialog before it runs — a declared + * `confirmText` (the confirm dialog) or a non-empty `params` (the param + * dialog) — because those are the only dialogs that draw a notice, and the + * only actions `translateAction` overlays the key onto; any other action gets + * no slot, so a translation filed there stays dangling, as `cancelText`'s does. + * + * Each leaf is optional-not-derived, like `cancelText`: a leaf the author did + * not write is not seeded, and the caller's `pushOptional` decides what an + * authored inline locale map contributes. + */ +export function actionNoticeTranslationSlots(action: any): Array<{ path: string[]; value: unknown }> { + const opensDialog = action?.confirmText != null + || (Array.isArray(action?.params) && action.params.length > 0); + const notices = action?.notices; + if (!opensDialog || !notices || typeof notices !== 'object' || Array.isArray(notices)) return []; + const slots: Array<{ path: string[]; value: unknown }> = []; + for (const [name, notice] of Object.entries(notices)) { + if (!notice || typeof notice !== 'object') continue; + for (const leaf of ['title', 'body'] as const) { + if (notice[leaf] !== undefined) slots.push({ path: ['notices', name, leaf], value: notice[leaf] }); + } + } + return slots; +} diff --git a/packages/lint/src/i18n-walk.test.ts b/packages/lint/src/i18n-walk.test.ts index 7350581b471..baeedbdffa8 100644 --- a/packages/lint/src/i18n-walk.test.ts +++ b/packages/lint/src/i18n-walk.test.ts @@ -277,6 +277,37 @@ describe('collectExpectedEntries — an action\'s declared texts (#34374 PR2)', }); }); +describe('collectExpectedEntries — an action\'s notices (#39182)', () => { + const notices = { mail_not_delivered: { severity: 'warning', title: 'No email', body: 'Mail is off.', visible: 'features.emailDelivery != true' } }; + const params = [{ name: 'email', type: 'email' }]; + const entries = collectExpectedEntries({ + objects: [{ name: 'sys_member', fields: {} }], + actions: [ + { name: 'invite_user', label: 'Invite', objectName: 'sys_member', type: 'api', target: '/x', params, notices }, + { name: 'invite', label: 'Invite', type: 'api', target: '/x', confirmText: 'Invite?', notices: { heads_up: { body: 'Read this.' } } }, + // No dialog: the spec refuses `notices` here, and the walk names no slot for it. + { name: 'resend', label: 'Resend', objectName: 'sys_member', type: 'api', target: '/x', notices }, + ], + }, { warnedGroups: new Set() }); + const at = (path: string) => entries.find((e) => e.path.join('.') === path); + + it('yields each notice\'s title and body under the bound action\'s address', () => { + expect(at('objects.sys_member._actions.invite_user.notices.mail_not_delivered.title')?.sourceValue).toBe('No email'); + expect(at('objects.sys_member._actions.invite_user.notices.mail_not_delivered.body')?.sourceValue).toBe('Mail is off.'); + }); + + it('yields an object-less action\'s notices under globalActions, and only the leaves it authors', () => { + expect(at('globalActions.invite.notices.heads_up.body')?.sourceValue).toBe('Read this.'); + expect(at('globalActions.invite.notices.heads_up.title')).toBeUndefined(); + }); + + it('names no slot for severity or the condition, nor for an action with no dialog', () => { + const noticeLeaves = entries.filter((e) => e.path.includes('notices')).map((e) => e.path[e.path.length - 1]); + expect(new Set(noticeLeaves)).toEqual(new Set(['title', 'body'])); + expect(entries.some((e) => e.path.join('.').startsWith('objects.sys_member._actions.resend.notices'))).toBe(false); + }); +}); + describe('collectExpectedEntries — an action\'s refusal catalogue (#34273)', () => { const refusals = { NOT_DRAFT: { message: 'Only a draft invoice can be signed off.' }, diff --git a/packages/lint/src/i18n-walk.ts b/packages/lint/src/i18n-walk.ts index 277a60b6069..ef7e00dffa6 100644 --- a/packages/lint/src/i18n-walk.ts +++ b/packages/lint/src/i18n-walk.ts @@ -99,6 +99,7 @@ * objects.._actions..submitText (only beside a non-empty `params`) * objects.._actions..cancelText (only beside `confirmText` or a non-empty `params`) * objects.._actions..outcomeMessages. + * objects.._actions..notices..title / .body (only beside `confirmText` or a non-empty `params`) * objects.._actions..params..label / .helpText / .placeholder * objects.._actions..params..options. * objects.._actions..resultDialog.title / .description / .acknowledge @@ -110,6 +111,7 @@ * / .disabledReason / .submitText (beside a non-empty `params`) * / .cancelText (beside `confirmText` or a non-empty `params`) * globalActions..outcomeMessages. + * globalActions..notices..title / .body (beside `confirmText` or a non-empty `params`) * globalActions..params..* / .resultDialog.* / .preflight.fields. * / .preflight.columns.. * (same shape as object actions) @@ -206,6 +208,7 @@ import { authorWarnedProperties } from './lint-liveness-properties.js'; import { walkPageComponents } from './page-walk.js'; import { objectExtensionsByTarget } from './object-graph.js'; import { addOwnerRelatedLists, emptyRelatedListTitles, foldRelatedListExtensions } from './related-list-titles.js'; +import { actionNoticeTranslationSlots } from './i18n-walk-action-notices.js'; // ─── Public types ────────────────────────────────────────────────────── @@ -1648,6 +1651,7 @@ export function collectExpectedEntries( pushActionSubmitText(out, aroot, action, 'action', objectName); pushActionCancelText(out, aroot, action, 'action', objectName); pushActionOutcomeMessages(out, aroot, action, 'action', objectName); + for (const slot of actionNoticeTranslationSlots(action)) pushOptional(out, [...aroot, ...slot.path], slot.value, 'action', { objectName }); pushActionParams(out, ['objects', objectName, '_actions', aname], action, 'action', objectName); pushActionResultDialog(out, ['objects', objectName, '_actions', aname], action, 'action', objectName); pushActionPreflight(out, ['objects', objectName, '_actions', aname], action, 'action', objectName); @@ -1756,6 +1760,7 @@ export function collectExpectedEntries( pushActionSubmitText(out, root, action, kind, objectName); pushActionCancelText(out, root, action, kind, objectName); pushActionOutcomeMessages(out, root, action, kind, objectName); + for (const slot of actionNoticeTranslationSlots(action)) pushOptional(out, [...root, ...slot.path], slot.value, kind, { objectName }); pushActionParams(out, root, action, kind, objectName); pushActionResultDialog(out, root, action, kind, objectName); pushActionPreflight(out, root, action, kind, objectName); diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 3f18e2a04f8..3577a8f351d 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -1742,6 +1742,33 @@ describe('validateStackExpressions (ADR-0032 build-time)', () => { expect(ok).toHaveLength(0); }); + it('flags a bare-field notice `visible` and accepts the record-qualified and features forms (#39182)', () => { + // A notice's condition reads the action's own scope: a bare `status` + // throws at key resolution, so the notice would never be drawn. + const host = { name: 'invite', objectName: 'crm_lead', type: 'api', target: '/x', params: [{ name: 'email', type: 'email' }] }; + const bad = validateStackExpressions({ + objects: [{ name: 'crm_lead', fields: { status: { type: 'text' } } }], + actions: [{ ...host, notices: { closed_lead: { body: 'Closed.', visible: 'status == "closed"' } } }], + }); + const noticeIssues = bad.filter(i => i.where.includes("action 'invite' notice 'closed_lead' visible")); + expect(noticeIssues).toHaveLength(1); + expect(noticeIssues[0].severity).toBe('error'); + expect(noticeIssues[0].message).toMatch(/bare reference `status`/); + + const ok = validateStackExpressions({ + objects: [{ name: 'crm_lead', fields: { status: { type: 'text' } } }], + actions: [{ + ...host, + notices: { + closed_lead: { body: 'Closed.', visible: 'record.status == "closed"' }, + mail_not_delivered: { body: 'No mail.', visible: 'features.emailDelivery != true' }, + always: { body: 'Always.' }, + }, + }], + }); + expect(ok).toHaveLength(0); + }); + it('judges an app landing predicate with the data-independent verdicts and no record scope (#28022)', () => { const nav = [{ id: 'nav_leads', type: 'object', label: 'Leads', objectName: 'lead' }]; // `===` is not CEL: the predicate can never evaluate, so the landing could never match. @@ -4342,8 +4369,9 @@ const READ_SURFACES: Array<{ receiver: string; expected: string[]; declaredBy: s receiver: 'action', // `object` is absent — the action schema's canonical key is `objectName`. // `disabledReason` is absent by contract (#26619): display copy beside - // `disabled`, never read as a condition. - expected: ['disabled', 'name', 'objectName', 'pressed', 'visible'], + // `disabled`, never read as a condition. `notices` is read for each + // notice's `visible` (#39182). + expected: ['disabled', 'name', 'notices', 'objectName', 'pressed', 'visible'], declaredBy: 'ObjectStackSchema.actions[]', keys: () => shapeKeysOf(ObjectStackSchema.shape.actions), }, diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index 62f25a8bf58..378853fe9e0 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -320,7 +320,9 @@ function buildAttachedOnReadIndex(objects: AnyRec[]): Map (#39182)', () => { + it('refuses a notice `_actions.` does not declare', () => { + const findings = validateTranslationReferences( + actionStack(onEnv({ invite_env: { notices: { mail_not_delivered: { body: '不会发送邮件。' }, mail_not_deliverd: { body: '拼错' } } } })), + ); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [TRANSLATION_TARGET_UNKNOWN, 'error', `${ENV}.invite_env.notices.mail_not_deliverd`], + ]); + expect(findings[0]?.message).toContain('mail_not_delivered'); + }); + + it('refuses a notice `globalActions.` does not declare', () => { + const findings = validateTranslationReferences( + actionStack({ globalActions: { invite_org: { notices: { ghost: { title: '幽灵' } } } } }), + ); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [TRANSLATION_TARGET_UNKNOWN, 'error', `${GLOBAL}.invite_org.notices.ghost`], + ]); + }); + + it('accepts every notice the action declares, at both addresses (the control)', () => { + expect( + validateTranslationReferences( + actionStack({ + ...onEnv({ invite_env: { notices: { mail_not_delivered: { title: '不会发送邮件', body: '此部署不投递邮件。' } } } }), + globalActions: { invite_org: { notices: { mail_not_delivered: { title: '不发邮件' } } } }, + }), + ), + ).toEqual([]); + }); + + it('refuses a leaf the declared notice does not author: the bundle translates text, it does not add it', () => { + const findings = validateTranslationReferences( + actionStack({ globalActions: { invite_org: { notices: { mail_not_delivered: { title: '不发邮件', body: '多出来的正文' } } } } }), + ); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [TRANSLATION_TARGET_UNKNOWN, 'error', `${GLOBAL}.invite_org.notices.mail_not_delivered.body`], + ]); + }); + + it('refuses every notice on an action that declares no `notices`', () => { + const findings = validateTranslationReferences( + actionStack(onEnv({ plain_env: { notices: { mail_not_delivered: { body: '不会发送邮件。' } } } })), + ); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [TRANSLATION_TARGET_UNKNOWN, 'error', `${ENV}.plain_env.notices.mail_not_delivered`], + ]); + }); + }); + describe('resultDialog.fields.', () => { it('refuses a result field `_actions.` does not declare, quoting a dotted path as ONE key', () => { const findings = validateTranslationReferences( @@ -4644,7 +4712,7 @@ describe('validateTranslationReferences — keyed children of an action entry (# }; type Address = 'bound' | 'global'; - type Host = 'outcome' | 'dialog' | 'noDialog' | 'noParams' | 'noPreRunDialog' | 'preflight' | 'noRefusals' | 'noTexts'; + type Host = 'outcome' | 'dialog' | 'noDialog' | 'noParams' | 'noPreRunDialog' | 'preflight' | 'noRefusals' | 'noTexts' | 'noNotices'; /** * Which declared action a ghost is written under, per address. `noDialog` * names an action that declares no `resultDialog`: the dialog's leaves @@ -4669,6 +4737,9 @@ describe('validateTranslationReferences — keyed children of an action entry (# // [#34374 PR2] An action that declares no `texts`, so a text key under // it is read by nothing (`coverageStack` gives the outcome hosts some). noTexts: { bound: 'plain_env', global: 'mint_token' }, + // [#39182] An action that declares no `notices`, so a notice key under + // it is read by nothing (`coverageStack` gives the outcome hosts one). + noNotices: { bound: 'plain_env', global: 'mint_token' }, }; type Coverage = | { kind: 'reference-checked'; host: Host; ghost: Record; suffix: string; rule: string } @@ -4789,6 +4860,13 @@ describe('validateTranslationReferences — keyed children of an action entry (# suffix: '.texts.ghost_key', rule: TRANSLATION_TARGET_UNKNOWN, }, + notices: { + kind: 'reference-checked', + host: 'noNotices', + ghost: { notices: { ghost_notice: { body: 'x' } } }, + suffix: '.notices.ghost_notice', + rule: TRANSLATION_TARGET_UNKNOWN, + }, }; // The global action needs a param with inline options for the options ghost. @@ -4805,6 +4883,10 @@ describe('validateTranslationReferences — keyed children of an action entry (# (stack.actions.find((a) => a.name === name) as Record).texts = { audit_line: { message: 'Done.' }, }; + // [#39182] …and a notice (both hosts open a param dialog). + (stack.actions.find((a) => a.name === name) as Record).notices = { + heads_up: { title: 'Heads up', body: 'Read this first.' }, + }; } return stack; }; @@ -4851,6 +4933,7 @@ describe('validateTranslationReferences — keyed children of an action entry (# params: { mode: { label: 'x', helpText: 'x', placeholder: 'x', options: { soft: 'x' } } }, refusals: { NOT_READY: { message: 'x', reasons: { stale: { message: 'x' } } } }, texts: { audit_line: { message: 'x' } }, + notices: { heads_up: { title: 'x', body: 'x' } }, }, [dialog]: { resultDialog: { title: 'x', description: 'x', acknowledge: 'x', fields: { token: 'x' }, columns: { rows: { id: 'x' } } }, diff --git a/packages/lint/src/validate-translation-references.ts b/packages/lint/src/validate-translation-references.ts index e394900d708..702ed4c63d4 100644 --- a/packages/lint/src/validate-translation-references.ts +++ b/packages/lint/src/validate-translation-references.ts @@ -3114,6 +3114,7 @@ interface ActionEntryContext { * | `resultDialog.columns..` / `preflight.columns..` | that field's `columns[].path` | `resolveActionResultDialog` / `resolveActionPreflight` | * | `submitText` | a non-empty `params` (the param dialog) | `translateAction` | * | `cancelText` | `confirmText` or a non-empty `params` (either dialog) | `translateAction` | + * | `notices..title` / `.body` | the action's `notices` keys (only on an action with either dialog) | `overlayActionNotices` (#39182) | * | `refusals.[.reasons.]` | the action's `refusals` codes (and each code's `reasons`) | `resolveActionRefusal` (#34273) | * | `texts.` | the action's `texts` keys | `buildActionTextSurface` (#34374 PR2) | * @@ -3147,6 +3148,7 @@ function checkActionEntry(findings: TranslationRefFinding[], ctx: ActionEntryCon checkActionAnswerTableColumns(findings, ctx, 'preflight'); checkActionSubmitText(findings, ctx); checkActionCancelText(findings, ctx); + checkActionNotices(findings, ctx); checkActionRefusals(findings, ctx); checkActionTexts(findings, ctx); } @@ -3551,6 +3553,62 @@ function checkActionOutcomeMessages(findings: TranslationRefFinding[], ctx: Acti } } +/** + * [#39182] `notices.` — keyed by a notice the action's own `notices` + * declares (`ActionSchema.notices`). + * + * `translateAction` overlays notice by notice over the DECLARED map + * (`overlayActionNotices`), so a translated notice the action does not declare + * is never drawn: the bundle cannot add a notice, only translate one — the + * `outcomeMessages` rule. Nor can it add a leaf: only the `title` / `body` the + * notice itself authors is overlaid, so a translated leaf the notice does not + * write is reported at its own path. The spec refuses `notices` on an action + * that opens no dialog, so a declared notice always has a dialog to be drawn in. + */ +function checkActionNotices(findings: TranslationRefFinding[], ctx: ActionEntryContext): void { + const rawNotices = asRecord(isRec(ctx.rawAction) ? ctx.rawAction.notices : undefined); + if (Object.keys(rawNotices).length === 0) return; + const declaredNotices = asRecord(ctx.action.notices); + const declared = new Set(Object.keys(declaredNotices)); + for (const [notice, translated] of Object.entries(rawNotices)) { + if (!declared.has(notice)) { + findings.push({ + severity: TRANSLATION_TARGET_UNKNOWN_SEVERITY, + rule: TRANSLATION_TARGET_UNKNOWN, + where: `${ctx.where} · notice "${notice}"`, + path: `${ctx.path}.notices.${notice}`, + message: + (declared.size > 0 + ? `Translations are keyed to notice "${notice}", which ${ctx.subject} does not ` + + `declare in \`notices\`, so this copy is never drawn.` + + suggest(notice, declared) + : `Translations are keyed to notice "${notice}", but ${ctx.subject} declares no ` + + `\`notices\` at all, so nothing reads this map and this copy is never drawn.`), + hint: + `Match the key to a notice name the action's \`notices\` declares, declare the notice ` + + `there first, or drop it.`, + }); + continue; + } + // A leaf the notice does not author is never overlaid (`overlayActionNotices` + // translates only authored text), so a translated one is never drawn. + const authored = asRecord(declaredNotices[notice]); + for (const leaf of ['title', 'body'] as const) { + if (!isRec(translated) || translated[leaf] === undefined || authored[leaf] !== undefined) continue; + findings.push({ + severity: TRANSLATION_TARGET_UNKNOWN_SEVERITY, + rule: TRANSLATION_TARGET_UNKNOWN, + where: `${ctx.where} · notice "${notice}" ${leaf}`, + path: `${ctx.path}.notices.${notice}.${leaf}`, + message: + `Translations give notice "${notice}" a \`${leaf}\`, but ${ctx.subject} writes no ` + + `\`${leaf}\` on it, so this copy is never drawn.`, + hint: `Author the \`${leaf}\` on the notice first, or drop it from the bundle.`, + }); + } + } +} + /** The result dialog's prose leaves — every key `ActionResultDialogTranslationSchema` declares beside `fields`. */ const RESULT_DIALOG_LEAVES = ['title', 'description', 'acknowledge'] as const; diff --git a/packages/metadata-core/src/object-schema-fls-references.test.ts b/packages/metadata-core/src/object-schema-fls-references.test.ts index de4d9418da1..ee011417af1 100644 --- a/packages/metadata-core/src/object-schema-fls-references.test.ts +++ b/packages/metadata-core/src/object-schema-fls-references.test.ts @@ -10,7 +10,7 @@ import { describe, it, expect } from 'vitest'; import { FieldSchema, InlineGridColumnSchema, ObjectSchema } from '@objectstack/spec/data'; -import { ColumnPrefixSchema, ColumnSummaryConfigSchema, ListColumnSchema } from '@objectstack/spec/ui'; +import { ActionSchema, ColumnPrefixSchema, ColumnSummaryConfigSchema, ListColumnSchema } from '@objectstack/spec/ui'; import { applyObjectSchemaMask, relateObjectSchemaMaskPosture, @@ -25,6 +25,7 @@ import { LIST_COLUMN_POSITIONS, LOOKUP_AUTOFILL_PAIR_POSITIONS, OBJECT_REFERENCE_POSITIONS, + ACTION_NOTICE_POSITIONS, mentionsDenied, } from './object-schema-fls-references.js'; import { @@ -257,6 +258,29 @@ describe('[ADR-0106 D1] references to a denied field — object level', () => { expect(served.actions.map((a: any) => a.name)).toEqual(['retitle']); }); + // [#39182] A notice is display only: its sentence never costs the caller the + // action; only its condition is a read, as every other predicate on it is. + it('keeps an action whose notice SAYS a denied field\'s name, and drops one whose notice condition READS it', () => { + const host = { type: 'api', target: '/x', params: [{ name: 'note', type: 'text' }] }; + const served = mask({ + name: 'thing', + fields: fieldsWith(), + actions: [ + { ...host, name: 'prose_body', notices: { heads_up: { severity: 'warning', body: 'The secret_score is not sent.' } } }, + { ...host, name: 'locale_body', notices: { heads_up: { title: 'Heads up', body: { en: 'secret_score stays.', 'zh-CN': 'secret_score 保留。' } } } }, + { ...host, name: 'named_like_it', notices: { secret_score: { body: 'Named like the field.' } } }, + { ...host, name: 'reads_it', notices: { heads_up: { body: 'High.', visible: 'record.secret_score > 10' } } }, + { ...host, name: 'reads_envelope', notices: { heads_up: { body: 'High.', visible: { dialect: 'cel', source: 'record.secret_score > 10' } } } }, + { ...host, name: 'reads_other', notices: { heads_up: { body: 'secret_score aside.', visible: 'record.title != ""' } } }, + { ...host, name: 'unknown_key', notices: { heads_up: { body: 'x', futureFacet: 'secret_score' } } }, + { ...host, name: 'top_level_body', type: 'script', body: { language: 'js', source: 'return record.secret_score;' } }, + ], + }); + expect(served.actions.map((a: any) => a.name)).toEqual(['prose_body', 'locale_body', 'named_like_it', 'reads_other']); + // Served as written: the mask removes an action, never part of a notice. + expect(served.actions[0].notices).toEqual({ heads_up: { severity: 'warning', body: 'The secret_score is not sent.' } }); + }); + it('drops a list view KEYED by the denied field\'s name; the others stay', () => { const served = mask({ name: 'thing', @@ -873,6 +897,26 @@ describe('[ADR-0106 D1] every position is classified — closed against the live }); } + // [#39182] An action notice's keys: a new one must be classified before it ships. + it('classifies every action notice key, and nothing it no longer declares', () => { + // Through the wrappers in the way (`lazy`, `pipe`, `optional`) to the + // action's shape, then to the notice map's value schema. + const peel = (schema: unknown, done: (node: any) => boolean): any => { + let node: any = schema; + for (let i = 0; i < 12 && !done(node); i++) { + const def = node?._def ?? node?.def; + node = def?.getter?.() ?? def?.innerType ?? def?.in ?? def?.schema; + } + if (!done(node)) throw new Error('the pin could not reach the notice schema'); + return node; + }; + const action = peel(ActionSchema, (n) => n?.shape && 'notices' in n.shape); + const record = peel(action.shape.notices, (n) => (n?._def ?? n?.def)?.type === 'record'); + const keys = declaredKeys((record._def ?? record.def).valueType); + expect(keys.filter((key) => !(key in ACTION_NOTICE_POSITIONS)), 'classify each new action notice key').toEqual([]); + expect(Object.keys(ACTION_NOTICE_POSITIONS).filter((key) => !keys.includes(key))).toEqual([]); + }); + it('classifies nothing the spec no longer declares', () => { const objectKeys = new Set(declaredKeys(ObjectSchema)); const fieldKeys = new Set(declaredKeys(FieldSchema)); diff --git a/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index 4efb8515321..7270a43c245 100644 --- a/packages/metadata-core/src/object-schema-fls-references.ts +++ b/packages/metadata-core/src/object-schema-fls-references.ts @@ -477,6 +477,48 @@ export function actionParamReadsDenied(param: unknown, denied: ReadonlySet; + +/** + * [#39182] An action's `notices`: display only by contract, so a notice's + * sentence never costs the caller the action — a body that says "no email will + * be sent" on an object with a denied `email` field is prose, not a read. Only + * a notice's `visible` (and a key {@link ACTION_NOTICE_POSITIONS} does not + * classify) is read against this object, and a hit drops the action, the rule + * every other predicate on it follows. The notice NAMES are map keys the + * dialog never shows and the translation address carries; they are not read. + * A value of the wrong shape is read whole, the fail-safe way. + */ +const actionNotices: EntryRead = (value, denied, scope) => { + if (!value || typeof value !== 'object' || Array.isArray(value)) return readsAsThisObject('notices')(value, denied, scope); + return Object.values(value as Record).some((notice) => { + if (!notice || typeof notice !== 'object' || Array.isArray(notice)) return readsAsThisObject('notices')(notice, denied, scope); + const read: Record = {}; + for (const [key, inner] of Object.entries(notice as Record)) { + const position = (ACTION_NOTICE_POSITIONS as Record)[key]; + if (position === 'prose' || position === 'vocabulary') continue; + read[key] = inner; + } + return mentionsDenied(read, denied, 'skip', 'classified'); + }); +}; + /** An action's `params`: the action reads a denied field when any one param does. */ const actionParams: EntryRead = (value, denied, scope) => ( Array.isArray(value) @@ -908,7 +950,9 @@ export const OBJECT_REFERENCE_POSITIONS: Readonly> = { listViews: recordOf(presentationEntry(LIST_VIEW_NAME_LISTS), true), // An action's `params` are read one by one: a param's `field` under // `objectOverride` belongs to the object it names (see `actionParamReadsDenied`). - actions: arrayOf(presentationEntry({}, { params: actionParams })), + // An action's `notices` are display only: only each notice's `visible` is + // read (see `actionNotices`); its `title` / `body` are prose. + actions: arrayOf(presentationEntry({}, { params: actionParams, notices: actionNotices })), ...PROTECTION_ENVELOPE, }; diff --git a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts index 8c23cbd92e3..98fa5efda16 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts @@ -280,10 +280,13 @@ describe('#17501 — /meta/types serves a real schema for `action`, and moves no // [#34374, action half] 54 → 55: `texts` (the sentences the action's // body writes into records, in the organization's language) joined // the accepted set, and the sample names it. - expect(Object.keys(properties).length + retiredTopLevelCount('action')).toBe(55); + // [#39182] 55 → 56: `notices` (the notices the action's confirm or + // param dialog draws, each while its condition holds) joined the + // accepted set, and the sample names it. + expect(Object.keys(properties).length + retiredTopLevelCount('action')).toBe(56); // A sample an author would actually address, and the one #17500's // repeater titles need a node to sit on. - for (const key of ['name', 'label', 'objectName', 'type', 'params', 'locations', 'outcomeMessages', 'requiresMembershipReach', 'disabledReason', 'pressed', 'submitText', 'cancelText', 'overrides', 'preflight', 'refusals', 'texts']) { + for (const key of ['name', 'label', 'objectName', 'type', 'params', 'locations', 'outcomeMessages', 'requiresMembershipReach', 'disabledReason', 'pressed', 'submitText', 'cancelText', 'overrides', 'preflight', 'refusals', 'texts', 'notices']) { expect(Object.keys(properties)).toContain(key); } }); diff --git a/packages/qa/dogfood/test/expression-conformance.ledger.ts b/packages/qa/dogfood/test/expression-conformance.ledger.ts index 20a124500c1..ca136a7cfdb 100644 --- a/packages/qa/dogfood/test/expression-conformance.ledger.ts +++ b/packages/qa/dogfood/test/expression-conformance.ledger.ts @@ -459,6 +459,16 @@ export const EXPRESSION_SURFACE: ExprSurface[] = [ covers: ['ui/action.zod.ts:actionObject.pressed'], note: 'Display only by contract — it never gates, greys or routes the action — so a fault refuses nothing: the predicate\'s effect (the pressed face) is dropped and the fault is logged, which is `fail-soft-log`, not `fail-closed`. The unpressed face is also the one that never claims the reader acted. Split from `cel-action-visible` / `cel-action-disabled` for the collision rule those two were split on: one row cannot state three fault faces. A menu item (the header overflow, the bar\'s override menu) draws no pressed state at all. Measured here: the ui half is in this checkout and its suites pin the TRUE / FALSE / fault faces on both surfaces.', }, + { + // The key arrived spec-first (card 39182); the console dialogs that draw it are the console half of card 39045. + id: 'cel-action-notice-visible', + summary: "registered action notice condition (Action.notices[name].visible) — whether the confirm or param dialog the action opens draws that notice", + dialect: 'cel', mode: 'interpret', state: 'experimental', failPolicy: 'unevaluated', + enforcement: + 'PARSE, measured here: `notices` mounts the file-local `ActionConditionInputSchema` (the alias `visible` and `disabled` mount) through `actionNoticesSchema` (ui/action-notices.ts), so a bare string normalizes to `{dialect:"cel",source}` and an `ast`-only envelope or a blank source is refused; the key itself is refused on an action that opens no confirm or param dialog. BUILD-TIME GATE, measured here: lint/validate-expressions.ts `checkAction` checks each notice\'s non-boolean `visible` against the `record` scope the action\'s own `visible` is checked in, as a served-row site (`action notice visible`). NO EVALUATOR FOUND: no console dialog reads the key yet', + covers: ['ui/action.zod.ts:actionObject.notices'], + note: 'Display only by contract: a notice gates, greys and routes nothing, and the action runs and answers the same with or without it. `experimental` / `unevaluated` until the console half of card 39045 draws the notices in the param and confirm dialogs, which re-classifies this row with its evaluator and its fault face; the liveness row `action.notices` flips to `live` with it. The ratchet key names the `notices` map, not its `visible` leaf, because the condition schema is handed into the notice factory as an argument and the scan attributes the hit to the `field:` it is written under.', + }, { // The key arrived spec-first (card 28022); the console landing redirect reads it (card 28450). id: 'cel-app-landing', diff --git a/packages/spec/authorable-surface/ui.json b/packages/spec/authorable-surface/ui.json index fe3e5d27113..79cf32a068a 100644 --- a/packages/spec/authorable-surface/ui.json +++ b/packages/spec/authorable-surface/ui.json @@ -29,6 +29,7 @@ "ui/Action:mode", "ui/Action:name", "ui/Action:newTabUrl", + "ui/Action:notices", "ui/Action:objectName", "ui/Action:onSuccess", "ui/Action:openIn", diff --git a/packages/spec/docs/references/kernel/metadata-plugin.md b/packages/spec/docs/references/kernel/metadata-plugin.md index dfedb31c35d..4161564bd51 100644 --- a/packages/spec/docs/references/kernel/metadata-plugin.md +++ b/packages/spec/docs/references/kernel/metadata-plugin.md @@ -339,6 +339,7 @@ const result = MetadataBulkResultSchema.parse(data); | **params** | `{ name?: string; field?: string; objectOverride?: string; label?: string \| Record; … }[]` | optional | Input parameters required from user — an ActionParam[] DEFINITION array, never a payload map (a static request body goes in `bodyExtra`). A param name (its `name`, or the `field` a field-backed param reads) may repeat only for per-gate variants of ONE input (declarations that differ in `visible` / `requiresFeature`, e.g. one optional and one required); the params check treats the name as `required` only when EVERY declaration of it requires it, and judges its value by the FIRST declaration's shape (`type`, `multiple`, `options`), so keep that shape identical across them. | | **submitText** | `string \| Record` | optional | Label of the submit button in the action's param dialog, the verb the button performs (e.g. "Send", "Log Call"), in place of the default "Confirm" — the default-language string, or an inline locale map; translated at `objects.OBJECT._actions.ACTION.submitText` (`globalActions.ACTION.submitText` for an object-less action). Only on an action with a non-empty `params`: without one no param dialog opens, so it is refused. Not `confirmText`, which is the message of a param-less action's confirm dialog. A blank label is refused. | | **cancelText** | `string \| Record` | optional | Label of the dismiss button on the dialog the action opens before it runs — the confirm dialog of a param-less action that declares `confirmText`, or the param dialog of an action with a non-empty `params` — in place of the default "Cancel". Name what dismissing keeps where the action's own verb is "Cancel …" or "Close …" (e.g. "Keep invitation" beside "Cancel Invitation"). The default-language string, or an inline locale map; translated at `objects.OBJECT._actions.ACTION.cancelText` (`globalActions.ACTION.cancelText` for an object-less action). Only on an action that opens one of those dialogs: with neither `confirmText` nor a non-empty `params` no dialog opens, so it is refused. The dismiss twin of `submitText`, as on `object-form`. A blank label is refused. | +| **notices** | `Record; title?: string \| Record; body?: string \| Record; visible?: boolean \| string \| object }>` | optional | Notices the dialog the action opens before it runs (the confirm dialog of a param-less action that declares `confirmText`, or the param dialog of an action with a non-empty `params`) draws above its description, each while its condition holds — keyed by a snake_case notice name, drawn in declared order. Each notice takes `record:alert`'s vocabulary: `severity` (info / warning / error / success), `title` and `body` (plain text, a string or an inline locale map, at least one of the two; translated at `objects.OBJECT._actions.ACTION.notices.NAME.title` / `.body`, `globalActions.ACTION.notices.NAME.*` for an object-less action), and `visible`, a condition in the shape and scope of the action's own `visible`, without the dialog's typed values. Display only: the action runs and answers the same with or without a notice. Only on an action that opens one of those dialogs, else refused. | | **variant** | `Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'link'>` | optional | Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent) | | **order** | `number` | optional | Sort order within a location group (lower = higher). Promotes/demotes an action toward the record page header's primary button; stable, so actions without `order` keep their registration order. | | **confirmText** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object } \| string \| Record` | optional | Confirmation message before execution — a `template` slot (ADR-0032): a bare string is shorthand for `{ dialect: 'template', source }`, and text with no hole is shown as written. Holes are `{{ path }}` or `{{ path \| formatter[:arg] }}` over `record`, the record the action runs against (the clicked row on a list, else the page's record), and — only when the action's `params` is an object of static values — `params` (`{{ params.tier }}`); an input list binds nothing, since its values are collected after the confirmation. Formatters come from the template engine's whitelist (`TEMPLATE_FORMATTERS`, `@objectstack/formula`); a hole holds no logic (no CEL, no arithmetic). Example: 'Delete `{{ record.name }}`?'. A hole over any other root, a `${…}` or single-brace `{x}` token (each named with its `{{ }}` spelling), a hole holding logic or an unknown formatter, and a blank sentence are named and refused at `objectstack validate`, `compile` and the publish gate; the text still parses, so a stored one loads until its next save. An inline locale map (`{ en, "zh-CN" }`) is accepted too, each value such a sentence. Pairing this with a non-empty `params` is refused — that opens a second dialog for one decision; put the question on `description` instead. Correct on a param-LESS action, where the confirm is the only dialog there is. | diff --git a/packages/spec/docs/references/system/translation.md b/packages/spec/docs/references/system/translation.md index 426bc1df5db..029f2484114 100644 --- a/packages/spec/docs/references/system/translation.md +++ b/packages/spec/docs/references/system/translation.md @@ -132,6 +132,7 @@ Translation data for a single field | **submitText** | `string` | optional | Translated label of the submit button in the action's param dialog (the action must declare `params`) | | **cancelText** | `string` | optional | Translated label of the dismiss button on the action's confirm or param dialog (the action must declare `confirmText` or `params`) | | **outcomeMessages** | `Record` | optional | Translated success copy per handler outcome, keyed by the snake_case outcome name the action's `outcomeMessages` declares | +| **notices** | `Record` | optional | Translated notices the action's dialog draws, keyed by the snake_case notice name the action's `notices` declares | | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | @@ -256,6 +257,7 @@ Translation data for a single object | **submitText** | `string` | optional | Translated label of the submit button in the action's param dialog (the action must declare `params`) | | **cancelText** | `string` | optional | Translated label of the dismiss button on the action's confirm or param dialog (the action must declare `confirmText` or `params`) | | **outcomeMessages** | `Record` | optional | Translated success copy per handler outcome, keyed by the snake_case outcome name the action's `outcomeMessages` declares | +| **notices** | `Record` | optional | Translated notices the action's dialog draws, keyed by the snake_case notice name the action's `notices` declares | | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | @@ -467,6 +469,7 @@ Translation data for a single object | **submitText** | `string` | optional | Translated label of the submit button in the action's param dialog (the action must declare `params`) | | **cancelText** | `string` | optional | Translated label of the dismiss button on the action's confirm or param dialog (the action must declare `confirmText` or `params`) | | **outcomeMessages** | `Record` | optional | Translated success copy per handler outcome, keyed by the snake_case outcome name the action's `outcomeMessages` declares | +| **notices** | `Record` | optional | Translated notices the action's dialog draws, keyed by the snake_case notice name the action's `notices` declares | | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | @@ -741,6 +744,7 @@ Translation data for a single object | **submitText** | `string` | optional | Translated label of the submit button in the action's param dialog (the action must declare `params`) | | **cancelText** | `string` | optional | Translated label of the dismiss button on the action's confirm or param dialog (the action must declare `confirmText` or `params`) | | **outcomeMessages** | `Record` | optional | Translated success copy per handler outcome, keyed by the snake_case outcome name the action's `outcomeMessages` declares | +| **notices** | `Record` | optional | Translated notices the action's dialog draws, keyed by the snake_case notice name the action's `notices` declares | | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | @@ -984,6 +988,7 @@ Translation data for a single object | **submitText** | `string` | optional | Translated label of the submit button in the action's param dialog (the action must declare `params`) | | **cancelText** | `string` | optional | Translated label of the dismiss button on the action's confirm or param dialog (the action must declare `confirmText` or `params`) | | **outcomeMessages** | `Record` | optional | Translated success copy per handler outcome, keyed by the snake_case outcome name the action's `outcomeMessages` declares | +| **notices** | `Record` | optional | Translated notices the action's dialog draws, keyed by the snake_case notice name the action's `notices` declares | | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | diff --git a/packages/spec/liveness/action.json b/packages/spec/liveness/action.json index 37f52723b10..741e07e329f 100644 --- a/packages/spec/liveness/action.json +++ b/packages/spec/liveness/action.json @@ -30,6 +30,40 @@ "evidence": "ui/packages/react/src/hooks/useActionTextLocalizer.ts (the confirm path: the bundle's `objects.{o}._actions.{a}.cancelText`, or `globalActions.{a}.cancelText` for an object-less action, through `actionCancelText`, then the authored `I18nLabel` collapsed to the active language, only when the action declares one); ui/packages/core/src/actions/ActionRunner.ts#confirmOptions (hands the resolved string to the confirm handler as `options.cancelText`) and ui/packages/core/src/actions/ActionRunner.ts#ActionDef (the key derived from the spec); ui/packages/app-shell/src/views/ActionConfirmDialog.tsx (draws `options.cancelText` over `actionConfirm.cancel`); ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx#paramCollectionHandler and ui/packages/app-shell/src/views/RecordDetailView.tsx#paramCollectionHandler (the param path, resolved the same way); ui/packages/app-shell/src/views/ActionParamDialog.tsx (draws it on the dismiss button, `actionDialog.cancel` when absent); ui/packages/components/src/renderers/action/action-button.tsx, ui/packages/components/src/renderers/action/action-icon.tsx, ui/packages/components/src/renderers/action/action-group.tsx, ui/packages/components/src/renderers/action/action-menu.tsx (the four action renderers forward it to the runner); packages/spec/src/system/i18n-resolver.ts#translateAction (the served overlay); packages/lint/src/validate-translation-references.ts#checkActionCancelText (a translation under an action that opens neither dialog is refused)", "note": "LIVE since #28879 (the console half of #28519). An action that asks first or collects `params` names its dialog's dismiss button (\"Keep invitation\" beside \"Cancel Invitation\"): the confirm dialog and the param dialog draw the translated or authored `cancelText` and fall back to \"Cancel\" when the action declares none. `sys_invitation`'s `cancel_invitation` is the first consumer. The Studio action form offers the key (`action.metadata-form.ts`). `authorWarn` / `authorHint` were dropped in the same edit (a warned `live` row reds this gate)." }, + "notices": { + "status": "planned", + "verifiedAt": "2026-12-02", + "authorWarn": true, + "authorHint": "Keep it, but nothing draws it yet: no console reads an action's `notices`, so its confirm and param dialogs show no notice until the console's two action dialogs read the key.", + "evidence": "packages/spec/src/ui/action-notices.ts#actionNoticeSchema (the parse: a map of snake_case notice names to `record:alert`'s vocabulary — `severity` from packages/spec/src/ui/alert-severity.ts#AlertSeveritySchema, `title` / `body` plain I18nLabels, at least one, never blank, and `visible` in the action's own condition shape); packages/spec/src/ui/action.zod.ts#notices (only on an action that declares `confirmText` or a non-empty `params`, `declaresNoticesWithoutDialog`); packages/spec/src/system/i18n-resolver.ts#translateAction overlays each declared notice's translated `objects.{o}._actions.{a}.notices.{n}.title` / `.body` (or `globalActions.{a}.notices.{n}.*`) through packages/spec/src/system/i18n-action-notices.ts#overlayActionNotices; packages/spec/src/system/translation.zod.ts declares the translation slot; packages/lint/src/i18n-walk.ts extracts the slots (packages/lint/src/i18n-walk-action-notices.ts#actionNoticeTranslationSlots); packages/lint/src/validate-translation-references.ts#checkActionNotices refuses a translation keyed to an undeclared notice; packages/lint/src/validate-expressions.ts checks each notice's `visible` in the `record` scope the action's own `visible` is checked in.", + "note": "PLANNED until the console half of #39045 lands (spec PR first, console card second, the #27944 split). The framework half is live, but no renderer reads the key yet: ui/packages/app-shell/src/views/ActionParamDialog.tsx and ui/packages/app-shell/src/views/ActionConfirmDialog.tsx draw no notice, and ui/packages/core/src/actions/ActionRunner.ts#ActionDef does not declare the key. `authorWarn` is set because an author who writes the key today sees nothing in the dialog. The console PR flips this row to `live` with its read points, and drops `authorWarn` / `authorHint` in that same edit (a warned `live` row reds this gate).", + "children": { + "severity": { + "status": "planned", + "verifiedAt": "2026-12-02", + "evidence": "packages/spec/src/ui/action-notices.ts#actionNoticeSchema (the parse: `record:alert`'s closed set, packages/spec/src/ui/alert-severity.ts#AlertSeveritySchema, no default)", + "note": "Planned with its container `notices`: drawn by no dialog until the console half of #39045 reads the key." + }, + "title": { + "status": "planned", + "verifiedAt": "2026-12-02", + "evidence": "packages/spec/src/ui/action-notices.ts#actionNoticeSchema (the parse: a plain I18nLabel, never blank, at least one of `title` / `body`; overlaid by packages/spec/src/system/i18n-action-notices.ts#overlayActionNotices)", + "note": "Planned with its container `notices`: drawn by no dialog until the console half of #39045 reads the key." + }, + "body": { + "status": "planned", + "verifiedAt": "2026-12-02", + "evidence": "packages/spec/src/ui/action-notices.ts#actionNoticeSchema (the parse: a plain I18nLabel, never blank, at least one of `title` / `body`; overlaid by packages/spec/src/system/i18n-action-notices.ts#overlayActionNotices)", + "note": "Planned with its container `notices`: drawn by no dialog until the console half of #39045 reads the key." + }, + "visible": { + "status": "planned", + "verifiedAt": "2026-12-02", + "evidence": "packages/spec/src/ui/action-notices.ts#actionNoticeSchema (the parse: the action's own condition shape, handed in from packages/spec/src/ui/action.zod.ts; checked in the `record` scope by packages/lint/src/validate-expressions.ts)", + "note": "Planned with its container `notices`: drawn by no dialog until the console half of #39045 reads the key." + } + } + }, "objectName": { "status": "live", "verifiedAt": "2026-09-15", diff --git a/packages/spec/liveness/state-counts/action.md b/packages/spec/liveness/state-counts/action.md index f329b814cef..45bf317bf21 100644 --- a/packages/spec/liveness/state-counts/action.md +++ b/packages/spec/liveness/state-counts/action.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `action` | 88 | 0 | 0 | 1 | 2 | 91 | +| `action` | 88 | 0 | 0 | 1 | 6 | 95 | diff --git a/packages/spec/src/shared/evaluated-slot-population.test.ts b/packages/spec/src/shared/evaluated-slot-population.test.ts index 4d92653e3c0..ef502a65b35 100644 --- a/packages/spec/src/shared/evaluated-slot-population.test.ts +++ b/packages/spec/src/shared/evaluated-slot-population.test.ts @@ -177,6 +177,19 @@ function slot(schema: unknown, ...path: string[]): z.ZodType { return node as z.ZodType; } +/** A record key's VALUE schema, through the same wrappers. */ +function recordValue(schema: unknown, ...path: string[]): z.ZodType { + let node: any = slot(schema, ...path); + for (let i = 0; i < 8; i++) { + const def = node?._def ?? node?.def; + if (def?.type === 'record' && def.valueType) return def.valueType as z.ZodType; + const next = def?.getter?.() ?? def?.in ?? def?.innerType ?? def?.schema; + if (!next || next === node) break; + node = next; + } + throw new Error('recordValue: not a record schema'); +} + /** An array key's ELEMENT schema, through the same wrappers. */ function element(schema: unknown, ...path: string[]): z.ZodType { let node: any = slot(schema, ...path); @@ -191,10 +204,16 @@ function element(schema: unknown, ...path: string[]): z.ZodType { } /** - * The 33 declaring positions, keyed the way the ADR-0058 D7 conformance ledger + * The 34 declaring positions, keyed the way the ADR-0058 D7 conformance ledger * keys them (`file:Schema.field`). Re-derived by identity on this tree, ⛔ not * inherited from the card: 31 declaring source lines, two of which are - * file-local alias consts mounting two slots each. + * file-local alias consts mounting two slots each, and one of those alias + * consts handed into a factory for a third. + * + * [#39182] It was 33 over 31 lines. `ui/action.zod.ts:actionObject.notices` + * joined: each action notice's `visible`, the action's own + * `ActionConditionInputSchema` handed into `actionNoticesSchema` + * (`ui/action-notices.ts`), so a new evaluated position on no new line. * * [#28022] It was 32 over 30 lines. `ui/app.zod.ts:AppLandingEntrySchema.visible` * joined: an app's per-audience landing predicate, a new evaluated position. @@ -241,6 +260,8 @@ const POSITIONS: ReadonlyArray z.ZodType]> = [ ['ui/action.zod.ts:actionObject.disabled', () => slot(ActionSchema, 'disabled')], // [#27946] Mounted directly, no boolean arm: the reader's pressed state. ['ui/action.zod.ts:actionObject.pressed', () => slot(ActionSchema, 'pressed')], + // [#39182] The same alias, through the notice factory: a notice's condition. + ['ui/action.zod.ts:actionObject.notices', () => slot(recordValue(ActionSchema, 'notices'), 'visible')], ['ui/app.zod.ts:BaseNavItemSchema.visible', () => slot(ObjectNavItemSchema, 'visible')], // [#28022] Mounted directly, required: the audience a landing entry is for. ['ui/app.zod.ts:AppLandingEntrySchema.visible', () => slot(AppLandingEntrySchema, 'visible')], @@ -263,10 +284,10 @@ const POSITIONS: ReadonlyArray z.ZodType]> = [ ]; describe('every evaluated slot refuses the two shapes no engine can run', () => { - it('reaches exactly the 33 declaring positions the census enumerated', () => { + it('reaches exactly the 34 declaring positions the census enumerated', () => { // A position that stops being reachable must red here rather than fall out // of the table: that silent drop is the #17630 failure in another costume. - expect(POSITIONS.length).toBe(33); + expect(POSITIONS.length).toBe(34); for (const [key, get] of POSITIONS) { expect(() => get(), `unreachable: ${key}`).not.toThrow(); } @@ -307,7 +328,7 @@ describe('every evaluated slot refuses the two shapes no engine can run', () => }); it('CONTROL — the persistence contract is NOT narrowed and still accepts both shapes', () => { - // This is what makes the 33 `false`s above a reading. Ruling item 2: + // This is what makes the 34 `false`s above a reading. Ruling item 2: // `ExpressionSchema` / `ExpressionInputSchema` keep `source` OR `ast`. for (const schema of [ExpressionSchema, ExpressionInputSchema, PredicateInputSchema]) { expect(schema.safeParse(AST_ONLY).success).toBe(true); @@ -315,7 +336,7 @@ describe('every evaluated slot refuses the two shapes no engine can run', () => } }); - it('CONTROL — a healthy predicate still parses at every one of the 33 positions', () => { + it('CONTROL — a healthy predicate still parses at every one of the 34 positions', () => { // The narrowing removes accepted shapes and adds none. The settings-manifest // pair speaks its own closed non-CEL grammar (#7169), so it gets the // predicate that grammar accepts; every other slot gets CEL. diff --git a/packages/spec/src/system/i18n-action-notices.ts b/packages/spec/src/system/i18n-action-notices.ts new file mode 100644 index 00000000000..6dc99120238 --- /dev/null +++ b/packages/spec/src/system/i18n-action-notices.ts @@ -0,0 +1,68 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * An action's `notices` (`ui/action-notices.ts`) for the reader's locale. + * + * Each notice's `title` and `body` live at the notice's one translation + * address, keyed by the snake_case notice NAME the action declares: + * `objects.._actions..notices..title` / `.body` for a + * bound action, `globalActions..notices..*` for an object-less + * one — the action's one address, as every other action copy key. + * + * Overlaid NOTICE BY NOTICE and leaf by leaf, only where the action itself + * authors the text: a bundle cannot add a notice (a translated entry under a + * name the action does not declare is never drawn and is not copied in), nor + * a leaf the notice does not author (a translated `title` on a notice that + * writes only `body` would give it a heading in one locale and none in the + * source; `os validate` reports both). A leaf the bundle does not carry keeps + * the authored text — a string or an inline locale map, left as written for + * the renderer to resolve. Nothing else on a notice is touched: `severity` + * and the `visible` condition are not copy. + * + * Internal to `@objectstack/spec`: {@link translateAction} is the one caller, + * and hands in the lookup that walks the locale chain at the action's + * address, so this module never learns the bundle's shape. + */ + +/** One declared notice as the resolver sees it — the copy leaves only. */ +export interface ActionNoticeLike { + title?: unknown; + body?: unknown; + [key: string]: unknown; +} + +/** + * The bundle's sentence for one leaf of one declared notice, across the + * locale chain, or `undefined` when no locale carries it. + */ +export type ActionNoticeLookup = (notice: string, leaf: 'title' | 'body') => string | undefined; + +/** + * The translated `notices` map, or the declared map itself (same reference) + * when the bundle overlays nothing — {@link translateAction} decides from the + * reference whether to write the key at all. + */ +export function overlayActionNotices>( + declared: N | undefined, + lookup: ActionNoticeLookup, +): N | undefined { + if (!declared || typeof declared !== 'object') return declared; + let out: Record | undefined; + for (const name of Object.keys(declared)) { + const notice = declared[name]; + if (!notice || typeof notice !== 'object') continue; + let translated: ActionNoticeLike | undefined; + for (const leaf of ['title', 'body'] as const) { + if (notice[leaf] === undefined) continue; + const sentence = lookup(name, leaf); + if (sentence === undefined) continue; + translated ??= { ...notice }; + translated[leaf] = sentence; + } + if (translated) { + out ??= { ...declared }; + out[name] = translated; + } + } + return (out as N | undefined) ?? declared; +} diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index 712b7adecac..eeab33f84c3 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -19,6 +19,7 @@ * objects.._actions..submitText * objects.._actions..cancelText * objects.._actions..outcomeMessages. + * objects.._actions..notices..title / .body * objects.._actions..params..label * objects.._actions..params..helpText * objects.._actions..params..placeholder @@ -54,7 +55,8 @@ * * globalActions..label / .description / .confirmText / * .successMessage / .disabledReason / .submitText / .cancelText / - * .outcomeMessages. / .params..* / .resultDialog.* / + * .outcomeMessages. / .notices..title / .body / + * .params..* / .resultDialog.* / * .preflight.fields. / .preflight.columns.. * * That is the declaration `TranslationDataSchema.globalActions` makes: global @@ -93,6 +95,7 @@ import { pageComponentSlotPositions } from '../ui/component.zod.js'; import { templateSlotSource } from '../automation/flow-text-slot-template.js'; import { PLATFORM_LOCALE_TAGS, platformLocaleTagOf } from './platform-locales.js'; import { mergeNavKeywords } from './i18n-nav-keywords.js'; +import { overlayActionNotices, type ActionNoticeLike } from './i18n-action-notices.js'; import type { PlatformTranslationBundle, @@ -255,6 +258,12 @@ export interface ActionLike { * entry a `template` slot like `successMessage` (#27948). */ outcomeMessages?: Record; + /** + * `ActionSchema.notices` (#39182) — the notices the action's confirm or + * param dialog draws, keyed by notice name; overlaid by + * `overlayActionNotices` (`i18n-action-notices.ts`). + */ + notices?: Record; /** `ActionSchema.params` — the param dialog's own copy. */ params?: ActionParamLike[]; /** When omitted, the action is treated as global. */ @@ -1927,7 +1936,8 @@ export function translateForm( * `label`, `description`, `confirmText`, `successMessage`, `disabledReason`, * `submitText` (for an action that declares `params`), `cancelText` (for an * action that declares `confirmText` or `params`), each declared - * `outcomeMessages` entry, the `params[]` copy, the `resultDialog` copy and + * `outcomeMessages` entry, each declared notice's `title` / `body` (for an + * action that declares `confirmText` or `params`), the `params[]` copy, the `resultDialog` copy and * the `preflight` panel's field labels with translated values when available. The * original document is not mutated; a shallow copy is returned. * @@ -1978,6 +1988,19 @@ export function translateAction( ? lookupActionField(bundle, action, 'cancelText', opts) ?? action.cancelText : action.cancelText; const outcomeMessages = resolveActionOutcomeMessages(bundle, action, opts); + // [#39182] The notices either dialog draws, overlaid notice by notice for + // the notices the action declares, and only for an action that opens one of + // those dialogs, judged like `cancelText` above. The lookup reads the + // action's one address across the locale chain. + const notices = opensDialog && bundle + ? overlayActionNotices(action.notices, (notice, leaf) => { + for (const code of localeChain(opts)) { + const candidate = actionTranslationNode(pickData(bundle, code), action)?.notices?.[notice]?.[leaf]; + if (typeof candidate === 'string' && candidate.length > 0) return candidate; + } + return undefined; + }) + : action.notices; const resultDialog = resolveActionResultDialog(bundle, action, opts); // [#31885] The preflight panel's field labels, overlaid like the result // dialog's: only for the fields the action declares. @@ -1993,6 +2016,7 @@ export function translateAction( ...(submitText !== undefined ? { submitText } : {}), ...(cancelText !== undefined ? { cancelText } : {}), ...(outcomeMessages !== action.outcomeMessages ? { outcomeMessages } : {}), + ...(notices !== action.notices ? { notices } : {}), ...(resultDialog !== undefined ? { resultDialog } : {}), ...(preflight !== action.preflight ? { preflight } : {}), ...(params !== action.params ? { params } : {}), diff --git a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts index cc0958b12d4..2668ba5687e 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -486,6 +486,18 @@ const LEDGER: ReadonlyArray = [ key: 'pressed', why: "planned, not yet rendered — the reader's pressed-state predicate is validated at parse (CEL only, no boolean literal) and judged at the authoring doors in the `record` scope, but no action surface draws the pressed face until the console's header buttons read it. A form control offered today would let an author write a predicate nothing shows", }, + // #39182 — the notices an action's confirm and param dialogs draw land + // spec-first the same way: `planned` in the liveness ledger, drawn by + // neither dialog until the console half of #39045 reads the key. The + // console change that flips the ledger row deletes this row and offers the + // key in `action.metadata-form.ts`. + { + kind: 'omit', + type: 'action', + path: ROOT_PATH, + key: 'notices', + why: "planned, not yet rendered — each notice's `record:alert` vocabulary is validated at parse (a closed severity, a plain title or body, a condition in the action's own shape, only on an action that opens a confirm or param dialog), translated by `translateAction` and its condition checked at the authoring doors, but neither dialog draws a notice until the console reads it. A form control offered today would let an author write a notice nothing shows", + }, // #31840 — an action's preflight read lands spec-first the same way: // `planned` in the liveness ledger, sent by no param dialog until the console // card (#31808) draws the panel and applies the seeds. diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index d7e1972695e..91ec32f300b 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -432,6 +432,7 @@ const actionTranslationSchema = (surface: string) => strictObject({ disabledHint: 'disabledReason', disabledText: 'disabledReason', submitLabel: 'submitText', confirmLabel: 'submitText', cancelLabel: 'cancelText', + alerts: 'notices', warnings: 'notices', parameters: 'params', args: 'params', inputs: 'params', result: 'resultDialog', dialog: 'resultDialog', refusal: 'refusals', @@ -467,6 +468,20 @@ const actionTranslationSchema = (surface: string) => strictObject({ // `translateAction` key by key, only for outcomes the action declares. outcomeMessages: z.record(SnakeCaseIdentifierSchema, z.string()).optional() .describe('Translated success copy per handler outcome, keyed by the snake_case outcome name the action\'s `outcomeMessages` declares'), + // [#39182] `ActionSchema.notices` — each notice's title and body, keyed by + // the same snake_case notice name the action declares, so a bundle key that + // names no declared notice is refused by the translation-reference lint + // rather than shipped as a translation nothing draws. Overlaid by + // `translateAction` per notice, only for notices the action declares and + // only on an action that opens the dialog that draws them. + notices: z.record(SnakeCaseIdentifierSchema, strictObject({ + surface: 'this action notice translation', + history: TRANSLATION_HISTORY, + aliases: { message: 'body', text: 'body', description: 'body', label: 'title' }, + }, { + title: z.string().optional().describe('Translated notice title'), + body: z.string().optional().describe('Translated notice body'), + })).optional().describe('Translated notices the action\'s dialog draws, keyed by the snake_case notice name the action\'s `notices` declares'), params: z.record(z.string(), strictObject({ surface: 'this action parameter translation', history: TRANSLATION_HISTORY, @@ -792,6 +807,7 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ * objects.._actions..submitText * objects.._actions..cancelText * objects.._actions..outcomeMessages. + * objects.._actions..notices..title / .body * objects.._actions..params..label * objects.._actions..params..helpText * objects.._actions..params..placeholder @@ -1412,6 +1428,7 @@ const appTranslationDataShape = () => ({ * globalActions..submitText * globalActions..cancelText * globalActions..outcomeMessages. + * globalActions..notices..title / .body * globalActions..params..label * globalActions..params..helpText * globalActions..params..placeholder diff --git a/packages/spec/src/ui/action-notices.test.ts b/packages/spec/src/ui/action-notices.test.ts new file mode 100644 index 00000000000..a94d0267eee --- /dev/null +++ b/packages/spec/src/ui/action-notices.test.ts @@ -0,0 +1,271 @@ +// Copyright (c) 2026 ObjectStack contributors. Apache-2.0 license. +// +// objectstack#39182 — `notices` on the action contract: notices the dialog an +// action opens before it runs draws above its description, each while its +// condition holds (ruling A on #39045, comment 7359751238). +// +// These pins hold the spec half: the parse on both host dialogs, the ruled +// refusals (an unknown severity, a non-string label, a blank, a notice with +// nothing to say, a host that opens no dialog), the reuse of `record:alert`'s +// severity set — ONE schema object, not a copy — and the translation slot +// with its `translateAction` overlay. The dangling-translation and condition +// legs are pinned in `packages/lint`. + +import { describe, it, expect } from 'vitest'; +import { ActionSchema } from './action.zod'; +import { RecordAlertProps } from './component.zod'; +import { AlertSeveritySchema } from './alert-severity'; +import { ObjectTranslationDataSchema, TranslationDataSchema, type TranslationBundle } from '../system/translation.zod'; +import { translateAction, type ActionLike } from '../system/i18n-resolver'; + +/** The invite action the ruling is about: a param dialog host. */ +const paramHost = { + name: 'invite_user', + label: 'Invite User', + objectName: 'sys_member', + type: 'api', + target: '/api/v1/auth/organization/invite-member', + params: [{ name: 'email', label: 'Email', type: 'email', required: true }], +}; + +/** A param-less action that asks first: the confirm dialog's host. */ +const confirmHost = { + name: 'resend_invitation', + label: 'Resend', + objectName: 'sys_invitation', + type: 'api', + target: '/api/v1/auth/organization/resend-invitation', + confirmText: 'Send this invitation again?', +} as const; + +/** An action that opens neither dialog: it runs on click. */ +const { confirmText: _confirmText, ...noDialog } = confirmHost; + +const mailNotice = { + severity: 'warning', + title: 'No email will be sent', + body: 'This deployment does not deliver mail.', + visible: 'features.emailDelivery != true', +} as const; + +const issues = (input: unknown) => { + const result = ActionSchema.safeParse(input); + expect(result.success).toBe(false); + return result.success ? [] : result.error.issues; +}; + +/** Walk zod wrappers (`lazy`, `pipe`, `optional`, refinements) to a node. */ +function peel(schema: unknown, stop: (node: any) => boolean): any { + let node: any = schema; + for (let i = 0; i < 12; i++) { + if (stop(node)) return node; + const def = node?._def ?? node?.def; + const next = def?.getter?.() ?? def?.in ?? def?.innerType ?? def?.schema; + if (!next || next === node) break; + node = next; + } + throw new Error('peel: did not reach the node'); +} +const shapeOf = (schema: unknown) => + peel(schema, (n) => n?.shape && Object.keys(n.shape).length > 0).shape as Record; +const enumOf = (schema: unknown) => peel(schema, (n) => (n?._def ?? n?.def)?.type === 'enum'); +const recordValueOf = (schema: unknown) => + (peel(schema, (n) => (n?._def ?? n?.def)?.type === 'record')._def ?? {}).valueType; + +describe('ActionSchema.notices — the parse', () => { + it('accepts the ruled shape on the param dialog\'s host', () => { + const result = ActionSchema.safeParse({ ...paramHost, notices: { mail_not_delivered: mailNotice } }); + + expect(result.success).toBe(true); + // The copy and severity verbatim; the condition normalized to the + // `{ dialect, source }` envelope, exactly as the action's own `visible` is. + expect(result.success && result.data.notices).toEqual({ + mail_not_delivered: { ...mailNotice, visible: { dialect: 'cel', source: mailNotice.visible } }, + }); + expect(result.success && result.data.visible).toBeUndefined(); + }); + + it('normalizes the condition the way the action\'s own `visible` is normalized', () => { + const parsed = ActionSchema.parse({ ...paramHost, visible: mailNotice.visible, notices: { mail_not_delivered: mailNotice } }); + expect(parsed.notices?.mail_not_delivered?.visible).toEqual(parsed.visible); + }); + + it('accepts it on the confirm dialog\'s host', () => { + const result = ActionSchema.safeParse({ ...confirmHost, notices: { heads_up: { body: 'The old link stops working.' } } }); + + expect(result.success).toBe(true); + }); + + it('accepts every severity of record:alert, inline locale maps, and every condition form', () => { + const notices = { + info_note: { severity: 'info', body: { en: 'Read this.', 'zh-CN': '请阅读。' } }, + warning_note: { severity: 'warning', title: 'Careful', visible: true }, + error_note: { severity: 'error', title: 'Blocked', visible: { dialect: 'cel', source: 'record.status == "locked"' } }, + success_note: { severity: 'success', title: { en: 'Ready' } }, + }; + const result = ActionSchema.safeParse({ ...paramHost, notices }); + + expect(result.success).toBe(true); + expect(result.success && Object.keys(result.data.notices ?? {})).toEqual(['info_note', 'warning_note', 'error_note', 'success_note']); + }); + + it('is optional', () => { + const result = ActionSchema.safeParse(paramHost); + expect(result.success && 'notices' in result.data).toBe(false); + }); +}); + +describe('ActionSchema.notices — the refusals', () => { + it('refuses an unknown severity at parse', () => { + const found = issues({ ...paramHost, notices: { notice_a: { severity: 'danger', body: 'x' } } }); + expect(found.some((i) => i.path.join('.') === 'notices.notice_a.severity')).toBe(true); + }); + + it('refuses a non-string label at parse', () => { + for (const bad of [{ title: 42 }, { body: ['line'] }, { body: { en: 7 } }]) { + const found = issues({ ...paramHost, notices: { notice_a: bad } }); + expect(found.some((i) => i.path[0] === 'notices' && i.path[1] === 'notice_a')).toBe(true); + } + }); + + it('refuses a blank title or body', () => { + const found = issues({ ...paramHost, notices: { notice_a: { title: ' ', body: 'x' } } }); + expect(found.some((i) => i.message.includes('blank notice `title`'))).toBe(true); + }); + + it('refuses a notice with neither title nor body', () => { + const found = issues({ ...paramHost, notices: { notice_a: { severity: 'warning', visible: true } } }); + expect(found.some((i) => i.message.includes('neither `title` nor `body`'))).toBe(true); + }); + + it('refuses a notice name that is not snake_case', () => { + const found = issues({ ...paramHost, notices: { MailNotice: mailNotice, n: mailNotice } }); + expect(found.some((i) => i.path[0] === 'notices')).toBe(true); + }); + + it('refuses the key on an action that opens no dialog', () => { + const found = issues({ ...noDialog, notices: { notice_a: { body: 'x' } } }); + expect(found.some((i) => i.path.join('.') === 'notices')).toBe(true); + }); + + it('refuses an empty params list as a dialog host', () => { + const found = issues({ ...noDialog, params: [], notices: { notice_a: { body: 'x' } } }); + expect(found.some((i) => i.path.join('.') === 'notices')).toBe(true); + }); + + it('refuses the banner keys it does not declare, each with its own sentence', () => { + const guidance: Record = { + action: 'A notice carries no button in this version', + icon: 'A notice draws the default icon of its `severity`', + dismissible: 'there is nothing to dismiss', + dismissKey: 'A notice is never dismissed, so it has no `dismissKey`', + }; + for (const [key, sentence] of Object.entries(guidance)) { + const found = issues({ ...paramHost, notices: { notice_a: { body: 'x', [key]: true } } }); + const unknown = found.find((i) => i.code === 'unrecognized_keys' && i.path.join('.') === 'notices.notice_a'); + expect(unknown?.message, key).toContain(`\`${key}\``); + expect(unknown?.message, key).toContain(sentence); + } + }); + + it('renames the near-misses on a notice and on the action', () => { + const onNotice = issues({ ...paramHost, notices: { notice_a: { message: 'x' } } }); + expect(onNotice.some((i) => i.message.includes('`message` → `body`'))).toBe(true); + + const label = issues({ ...paramHost, notices: { notice_a: { label: 'x' } } }); + expect(label.some((i) => i.message.includes('`label` → `title`'))).toBe(true); + + const onAction = issues({ ...paramHost, warnings: { notice_a: { body: 'x' } } }); + expect(onAction.some((i) => i.message.includes('`warnings` → `notices`'))).toBe(true); + }); +}); + +describe('ActionSchema.notices — one severity set with record:alert', () => { + it('mounts the very schema record:alert mounts, not a copy', () => { + const bannerSeverity = enumOf(shapeOf(RecordAlertProps).severity); + const notice = recordValueOf(shapeOf(ActionSchema).notices); + const noticeSeverity = enumOf(shapeOf(notice).severity); + + expect(bannerSeverity).toBe(AlertSeveritySchema); + expect(noticeSeverity).toBe(AlertSeveritySchema); + }); + + it('is the closed set record:alert has always taken', () => { + expect(AlertSeveritySchema.options).toEqual(['info', 'warning', 'error', 'success']); + }); +}); + +describe('the translation slot and its overlay', () => { + it('accepts the key at the object-scoped address', () => { + const result = ObjectTranslationDataSchema.safeParse({ + _actions: { invite_user: { notices: { mail_not_delivered: { title: '不会发送邮件', body: '此部署不投递邮件。' } } } }, + }); + + expect(result.success).toBe(true); + expect(result.success && result.data._actions?.invite_user?.notices?.mail_not_delivered?.title).toBe('不会发送邮件'); + }); + + it('accepts it at the globalActions address an object-less action reads', () => { + const result = TranslationDataSchema.safeParse({ + globalActions: { invite: { notices: { mail_not_delivered: { body: '此部署不投递邮件。' } } } }, + }); + expect(result.success).toBe(true); + }); + + it('refuses a non-copy key inside a translated notice', () => { + const result = ObjectTranslationDataSchema.safeParse({ + _actions: { invite_user: { notices: { mail_not_delivered: { severity: 'warning' } } } }, + }); + expect(result.success).toBe(false); + }); + + const bundle: TranslationBundle = { + 'zh-CN': { + objects: { + sys_member: { + _actions: { + invite_user: { notices: { mail_not_delivered: { title: '不会发送邮件' }, undeclared: { body: '不应出现' } } }, + }, + }, + sys_invitation: { _actions: { resend_invitation: { notices: { heads_up: { body: '旧链接将失效。' } } } } }, + }, + globalActions: { invite: { notices: { mail_not_delivered: { body: '此部署不投递邮件。' } } } }, + }, + }; + const inviteAction = { ...paramHost, notices: { mail_not_delivered: mailNotice } }; + + it('translateAction overlays the translated leaf and keeps the rest of the notice', () => { + const translated = translateAction(inviteAction, bundle, { locale: 'zh-CN' }); + + expect(translated.notices?.mail_not_delivered).toEqual({ ...mailNotice, title: '不会发送邮件' }); + }); + + it('never adds a leaf the notice does not author', () => { + const bodyOnly = { ...paramHost, notices: { mail_not_delivered: { body: 'Mail is off.' } } }; + const bundleWithTitle: TranslationBundle = { + 'zh-CN': { objects: { sys_member: { _actions: { invite_user: { notices: { mail_not_delivered: { title: '不应出现', body: '不发邮件。' } } } } } } }, + }; + expect(translateAction(bodyOnly, bundleWithTitle, { locale: 'zh-CN' }).notices).toEqual({ + mail_not_delivered: { body: '不发邮件。' }, + }); + }); + + it('never adds a notice the action does not declare', () => { + const translated = translateAction(inviteAction, bundle, { locale: 'zh-CN' }); + expect(Object.keys(translated.notices ?? {})).toEqual(['mail_not_delivered']); + }); + + it('reads an object-less action at globalActions', () => { + const invite = { name: 'invite', label: 'Invite', params: [{ name: 'email' }], notices: { mail_not_delivered: mailNotice } }; + expect(translateAction(invite, bundle, { locale: 'zh-CN' }).notices?.mail_not_delivered?.body).toBe('此部署不投递邮件。'); + }); + + it('keeps the authored notices (same reference) when the locale has none', () => { + expect(translateAction(inviteAction, bundle, { locale: 'ja-JP' }).notices).toBe(inviteAction.notices); + }); + + it('overlays on the confirm dialog\'s host too', () => { + const resend = { ...confirmHost, notices: { heads_up: { body: 'The old link stops working.' } } }; + expect(translateAction(resend, bundle, { locale: 'zh-CN' }).notices?.heads_up?.body).toBe('旧链接将失效。'); + }); +}); diff --git a/packages/spec/src/ui/action-notices.ts b/packages/spec/src/ui/action-notices.ts new file mode 100644 index 00000000000..9a9b7972e3c --- /dev/null +++ b/packages/spec/src/ui/action-notices.ts @@ -0,0 +1,155 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { z } from 'zod'; +import { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod'; +import { NON_BLANK_STRING, requiredOneOf } from '../shared/refinement-projection'; +import { strictObject } from '../shared/strict-object'; +import { AlertSeveritySchema } from './alert-severity'; +import { InlineLocaleMapSchema } from './i18n.zod'; + +/** + * `ActionSchema.notices` — notices the dialog an action opens before it runs + * draws above its description, each while its condition holds. + * + * The case it exists for: an action whose outcome depends on a fact about the + * deployment or the record that the user cannot see from the form — the + * platform's invite actions on a deployment that delivers no mail, a quote + * action on a quote past its expiry — needs to say so BEFORE the click, not + * only in the toast after it. Until this key an author had no declared place + * for that sentence: `description` is unconditional, and the alternatives + * were twin actions per condition or console chrome keyed by action name. + * + * ## The vocabulary is `record:alert`'s + * + * Each notice takes the record page banner's own field names — `severity` + * (the one closed set in `alert-severity.ts`, mounted by both), `title`, + * `body`, and `visible` for its condition — so an author who knows one + * surface knows the other. It takes a SUBSET: the banner's `icon`, `action`, + * `dismissible` and `dismissKey` are not declared here. A notice is plain + * text in this version — no markup, no link, no button — and a dialog is + * gone the moment it closes, so there is nothing to dismiss or remember. + * + * ## Named, so each notice has a stable translation key + * + * The key is a map from a snake_case notice name to the notice, the shape + * `outcomeMessages` takes for the same reason: the name is the notice's + * translation address, `objects.OBJECT._actions.ACTION.notices.NAME.title` / + * `.body` (`globalActions.ACTION.notices.NAME.*` for an object-less action), + * which an array index could not give — reordering or inserting one would + * silently move every translation after it. Several notices are drawn in the + * order they are declared, each judged on its own condition. + * + * ## The condition reads the scope the action's own predicates read + * + * `visible` is the shape the action's `visible` and `disabled` take (a + * boolean literal, a CEL string or a `{ dialect, source }` envelope), handed + * in from `action.zod.ts` so the three cannot drift apart, and it is judged + * against the same scope — the record the surface holds, the signed-in user, + * `features` — with no new root: it does not see the values typed into the + * dialog. Omitted, the notice is drawn whenever the dialog is. + * + * ## Display only + * + * No door reads a notice. The action's endpoint, its `outcome` answer and its + * outcome copy are the same with or without one, and a notice that is wrong + * or not drawn misleads a reader and gates nothing; the server's own rules + * stay the authority on what the action does. + * + * Lives in its own module, beside `action.zod.ts` rather than in it, and + * takes the condition schema as an argument rather than importing it, so the + * file-local `ActionConditionInputSchema` stays the one source. + */ + +const ACTION_NOTICE_HISTORY = + 'Until this shape was closed these were dropped silently: the notice still parsed, and the ' + + 'dialog drew it without whatever the key was meant to say or style.'; + +/** + * A notice's `title` / `body`: an I18nLabel — a plain string, translated at + * the notice's address, or an inline locale map. Plain text, never a + * template: the copy keys' `${record.*}` interpolation is not declared here, + * so a `${` in a notice is drawn as written. A blank string is refused: it + * would draw an empty line in the dialog. + */ +const noticeText = (key: 'title' | 'body') => z.union([ + z.string().refine(NON_BLANK_STRING, { + message: + `a blank notice \`${key}\` would draw an empty line in the action's dialog. Write the ` + + 'sentence, or omit the key.', + }), + InlineLocaleMapSchema, +]); + +/** + * One notice, given the action's condition schema. A factory for the reason + * the module header names: the condition is `action.zod.ts`'s file-local + * `ActionConditionInputSchema`, passed in. + */ +export const actionNoticeSchema = (condition: C) => strictObject({ + surface: 'this action notice', + history: ACTION_NOTICE_HISTORY, + aliases: { + // The record banner's own aliases for `visible` (`RecordAlertProps`), and + // the action's (`showWhen`): the words an author brings from either + // neighbouring surface for the same condition. + visibleWhen: 'visible', visibility: 'visible', showWhen: 'visible', + // The words for the sentence itself on neighbouring surfaces: a toast's + // `message`, an element's `text`, the dialog's own `description`. + message: 'body', text: 'body', description: 'body', + level: 'severity', + // The translation entry's own alias for the same leaf (`translation.zod.ts`). + label: 'title', + }, + guidance: { + action: 'A notice carries no button in this version: it says what to do in words, in its ' + + '`body`. `record:alert`\'s `action` is a record page banner\'s, not an action notice\'s.', + icon: 'A notice draws the default icon of its `severity`; it declares no `icon` of its own.', + dismissible: 'A notice is drawn while the dialog is open and gone when it closes, so there is ' + + 'nothing to dismiss. Narrow when it is drawn with `visible` instead.', + dismissKey: 'A notice is never dismissed, so it has no `dismissKey`. Narrow when it is drawn ' + + 'with `visible` instead.', + }, +}, { + severity: AlertSeveritySchema.optional().describe('Notice severity, `record:alert`\'s closed set: `info`, `warning`, `error` or `success`. Styles the notice and picks its icon. Renderer default: `info`.'), + title: noticeText('title').optional().describe('Notice title — plain text, a string or an inline locale map ({ en, "zh-CN", … }); translated at `objects.OBJECT._actions.ACTION.notices.NAME.title` (`globalActions.ACTION.notices.NAME.title` for an object-less action). No markup, link or template. A blank title is refused.'), + body: noticeText('body').optional().describe('Notice body — plain text, a string or an inline locale map; translated at `objects.OBJECT._actions.ACTION.notices.NAME.body` (`globalActions.ACTION.notices.NAME.body` for an object-less action). Says in words what to do; no markup, link or template. A blank body is refused.'), + visible: condition.optional().describe('When the notice is drawn — the shape and the scope of the action\'s own `visible`: a boolean literal, a CEL string or a `{ dialect, source }` envelope, judged against the record the surface holds, the signed-in user and `features`. It does not see the values typed into the dialog. Omit to draw the notice whenever the dialog opens.'), +}).refine(requiredOneOf(['title', 'body']), { + message: + 'A notice with neither `title` nor `body` draws nothing in the dialog. Write the sentence the ' + + 'user should read before submitting, in `body` (and a short `title` if it helps), or drop the ' + + 'notice.', + path: ['body'], +}); + +/** The `notices` map, given the action's condition schema. */ +export const actionNoticesSchema = (condition: C) => + z.record(SnakeCaseIdentifierSchema, actionNoticeSchema(condition)); + +/** + * An action opens a dialog before it runs only for a declared `confirmText` + * (the confirm dialog of a param-less action) or a non-empty `params` array + * (the param dialog) — the console's action runner, objectui + * `ActionRunner.execute`. `notices` on any other action parses clean and is + * never drawn, the ADR-0078 shape, so it is refused: the predicate the + * `ActionSchema` refinement reads. + */ +export function declaresNoticesWithoutDialog(data: { + notices?: unknown; + confirmText?: unknown; + params?: unknown; +}): boolean { + return data.notices != null + && data.confirmText == null + && !(Array.isArray(data.params) && data.params.length > 0); +} + +export const NOTICES_WITHOUT_DIALOG_REFUSAL = { + message: + '`notices` are drawn in the dialog an action opens before it runs: the confirm dialog of an ' + + 'action that declares `confirmText`, or the param dialog of one that declares `params`. This ' + + 'action declares neither, so it runs on click, opens no dialog, and its notices would never ' + + 'show. Declare the `confirmText` question or the `params` the dialog collects, or drop ' + + '`notices`.', + path: ['notices'], +}; diff --git a/packages/spec/src/ui/action.zod.ts b/packages/spec/src/ui/action.zod.ts index 347cf036a4b..e3c81deb52c 100644 --- a/packages/spec/src/ui/action.zod.ts +++ b/packages/spec/src/ui/action.zod.ts @@ -92,6 +92,7 @@ import { ACTION_TARGET_ALIASES } from './action-target-aliases'; import { ON_SUCCESS_EXECUTORS, onSuccessBesideExecutorRefusal } from './action-on-success-executor'; import { refuseDeclarativeUpdateContradictions, type DeclarativeUpdateSurface } from './action-declarative-update'; import { CONFIRM_BESIDE_PARAMS_REFUSAL, declaresConfirmBesideParams } from './action-confirm-beside-params'; +import { NOTICES_WITHOUT_DIALOG_REFUSAL, actionNoticesSchema, declaresNoticesWithoutDialog } from './action-notices'; import { navigationTargetRefusal } from './navigation-target'; // [#31840] The same-origin read rule an action's `preflight` reads under — the // one a page element's `api` data source reads under too (`page.zod.ts`). An @@ -1430,6 +1431,11 @@ const actionObject = () => strictObject({ // `alert-dialog` renderers, the `*Label` twin of `submitLabel` above. Not // reachable by distance from `cancelText`. cancelLabel: 'cancelText', + // [#39182] The record page banner's own word for the same thing + // (`record:alert`), and the dialog's other word for a caution, both for + // the notices the action's dialog draws. Neither is reachable by distance + // from `notices`. + alerts: 'notices', warnings: 'notices', // [#27946] The card's own second spelling (`active`) and the `*When` // predicate family's spelling of the pressed-state predicate. active: 'pressed', activeWhen: 'pressed', pressedWhen: 'pressed', @@ -1974,6 +1980,16 @@ const actionObject = () => strictObject({ */ cancelText: actionCancelText().optional().describe('Label of the dismiss button on the dialog the action opens before it runs — the confirm dialog of a param-less action that declares `confirmText`, or the param dialog of an action with a non-empty `params` — in place of the default "Cancel". Name what dismissing keeps where the action\'s own verb is "Cancel …" or "Close …" (e.g. "Keep invitation" beside "Cancel Invitation"). The default-language string, or an inline locale map; translated at `objects.OBJECT._actions.ACTION.cancelText` (`globalActions.ACTION.cancelText` for an object-less action). Only on an action that opens one of those dialogs: with neither `confirmText` nor a non-empty `params` no dialog opens, so it is refused. The dismiss twin of `submitText`, as on `object-form`. A blank label is refused.'), + /** + * [#39182] Notices the dialog the action opens before it runs draws above + * its description, each while its condition holds — the contract, the + * `record:alert` vocabulary and the translation address are on + * `action-notices.ts`. The condition is this file's + * {@link ActionConditionInputSchema}, the shape `visible` and `disabled` + * take, handed in so the three stay one source. + */ + notices: actionNoticesSchema(ActionConditionInputSchema).optional().describe('Notices the dialog the action opens before it runs (the confirm dialog of a param-less action that declares `confirmText`, or the param dialog of an action with a non-empty `params`) draws above its description, each while its condition holds — keyed by a snake_case notice name, drawn in declared order. Each notice takes `record:alert`\'s vocabulary: `severity` (info / warning / error / success), `title` and `body` (plain text, a string or an inline locale map, at least one of the two; translated at `objects.OBJECT._actions.ACTION.notices.NAME.title` / `.body`, `globalActions.ACTION.notices.NAME.*` for an object-less action), and `visible`, a condition in the shape and scope of the action\'s own `visible`, without the dialog\'s typed values. Display only: the action runs and answers the same with or without a notice. Only on an action that opens one of those dialogs, else refused.'), + /** Visual Style */ variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'), @@ -3299,7 +3315,13 @@ export const ActionSchema = lazySchema(() => actionObject().refine((data) => { + 'never show. Declare the `confirmText` question or the `params` the dialog collects, or drop ' + '`cancelText`.', path: ['cancelText'], -}).superRefine((data, ctx) => { +}).refine((data) => { + // [#39182] The same rule for the notices the dialog draws, whose host is + // either dialog, as `cancelText`'s is. The predicate and the refusal live + // beside the notice schema (`action-notices.ts`). Scoped by schema + // boundary like the rules above: `InlineActionSchema` does not pick the key. + return !declaresNoticesWithoutDialog(data); +}, NOTICES_WITHOUT_DIALOG_REFUSAL).superRefine((data, ctx) => { // #9566/#9474 — `onSuccess` is scoped to the action types whose success // carries a result for `${result.*}` to read: `api` (the `target` call's // response body), `script` (the handler's return value) and `flow` (the diff --git a/packages/spec/src/ui/alert-severity.ts b/packages/spec/src/ui/alert-severity.ts new file mode 100644 index 00000000000..46ca41275da --- /dev/null +++ b/packages/spec/src/ui/alert-severity.ts @@ -0,0 +1,26 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { z } from 'zod'; + +/** + * The closed severity set of a declared notice — ONE source for the two + * surfaces that draw one: + * + * - `record:alert`'s `severity` (`RecordAlertProps`, `component.zod.ts`), the + * banner a record page declares; + * - each entry of an action's `notices` (`action-notices.ts`), the notice + * the dialog an action opens before it runs draws above its description. + * + * The action's notice reuses the record banner's vocabulary on purpose: an + * author who knows one knows the other, and a renderer styles both from the + * same four values. It lives in its own module because `component.zod.ts` + * imports `action.zod.ts`, so the action side cannot read the set out of + * `RecordAlertProps` without closing an import cycle; both mount this enum + * instead, so the two can never drift into two dialects. + * + * Closed, and with NO schema default: a renderer falls back to `info` on an + * omitted value, and an out-of-vocabulary value is an authoring mistake the + * parse refuses rather than a style it absorbs. + */ +export const AlertSeveritySchema = z.enum(['info', 'warning', 'error', 'success']); +export type AlertSeverity = z.infer; diff --git a/packages/spec/src/ui/component.zod.ts b/packages/spec/src/ui/component.zod.ts index d22ac0a3782..bc30f4d7e03 100644 --- a/packages/spec/src/ui/component.zod.ts +++ b/packages/spec/src/ui/component.zod.ts @@ -69,6 +69,7 @@ import { AggregationFunction } from '../data/query.zod'; // outside the `ui` barrel so the two carriers share it without publishing it. import { ListViewExportOptionsSchema } from './list-view-export-options'; import { ActionSchema, ActionType, InlineActionSchema, PageComponentActionLocationSchema, RecordQuickActionsLocationSchema } from './action.zod'; +import { AlertSeveritySchema } from './alert-severity'; import { ASK_AI_RETIRED } from './action-ask-ai-retired'; import { CONFIRM_BESIDE_PARAMS_REFUSAL, declaresConfirmBesideParams } from './action-confirm-beside-params'; import { ACTION_TARGET_ALIASES } from './action-target-aliases'; @@ -2431,7 +2432,7 @@ export const RecordAlertProps = strictObject({ visibility: 'visible', }, }, { - severity: z.enum(['info', 'warning', 'error', 'success']).optional().describe('Banner severity — styling, default icon, and the a11y role (`error` renders `role="alert"`/assertive; the rest `role="status"`/polite). Renderer default: `info`.'), + severity: AlertSeveritySchema.optional().describe('Banner severity — styling, default icon, and the a11y role (`error` renders `role="alert"`/assertive; the rest `role="status"`/polite). Renderer default: `info`.'), title: I18nLabelSchema.optional().describe('Banner title — a string or an inline locale map ({ en, "zh-CN", … }), resolved to the current language at render (pickLocalized).'), body: I18nLabelSchema.optional().describe('Banner body — a string or an inline locale map, resolved like `title`.'), visible: z.union([z.boolean(), EvaluatedExpressionInputSchema], { diff --git a/ui/packages/core/src/actions/actionKeys.ts b/ui/packages/core/src/actions/actionKeys.ts index d983648deb9..269cff82a57 100644 --- a/ui/packages/core/src/actions/actionKeys.ts +++ b/ui/packages/core/src/actions/actionKeys.ts @@ -289,6 +289,12 @@ export const SPEC_ACTION_KEYS = [ 'mode', 'name', 'newTabUrl', + // Added to `ActionSchema` by objectstack#39182: the notices the action's + // confirm or param dialog draws, each while its condition holds. Listed for + // this array's contract alone, like `description` above: `ActionDef` does + // not declare it yet, and the dialogs drawing it are the console's own + // follow-up. + 'notices', 'objectName', // Declared by `ActionSchema` as of @objectstack/spec 17.1.0 (objectui#5328). // All four declared action surfaces forward it since objectui#5493/#6304, and