diff --git a/.changeset/37856-ask-ai-action-type-retired.md b/.changeset/37856-ask-ai-action-type-retired.md new file mode 100644 index 00000000000..aaf5e0d7988 --- /dev/null +++ b/.changeset/37856-ask-ai-action-type-retired.md @@ -0,0 +1,41 @@ +--- +'@objectstack/spec': minor +'@objectstack/metadata-protocol': patch +'@objectstack/metadata': patch +'@objectstack/core': patch +'@objectstack/runtime': patch +'@objectstack/service-datasource': patch +'@object-ui/core': minor +'@object-ui/react': minor +'@object-ui/components': patch +'@object-ui/plugin-grid': patch +'@object-ui/plugin-detail': patch +'@object-ui/app-shell': minor +--- + +feat(spec)!: retire the `ask_ai` action type — the shell's 「问 AI」 entry is the one way into the assistant + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: follow-up #37857 + + + +**BREAKING** enum value removal on `ActionType` (`@objectstack/spec/ui`), ADR-0160 D7 as its seventh amendment rules. `ask_ai` was published only on the 19 prerelease line (`19.0.0-next.0`) and in no stable release; it leaves before 19.0.0 with no compatibility shim. A button per page is a second entry to the assistant, and the shell's 「问 AI」 entry in the page header already opens on the record in view. The accepted cost: a list row has no ask-AI action of its own. + +| FROM | TO | +|:--|:--| +| `{ name: 'ask_about_case', type: 'ask_ai', locations: ['record_header'] }` | nothing: delete the action and every reference to it; the shell's 「问 AI」 entry opens on the record | +| `{ type: 'action:button', properties: { actionType: 'ask_ai' } }` | nothing: delete the row | + +The one-line fix: delete each `ask_ai` action and every name that points at it (a page header's `actions`, a list view's `rowActions` / `bulkActions`, a related list's `actions`, a quick-actions list, a record alert's `actionName`, an app navigation entry). `os migrate meta --from 18` lists the edits; `--write` deletes an `ask_ai` action that nothing in the stack names and every inline row and container member that spells it, and leaves a named one, with its references, for you to delete by hand. + +- **`@objectstack/spec`**: every slot that takes an action type refuses `ask_ai` with one prescription: a declared or inline action's `type`, an `action:button` / `action:icon` row's `actionType`, an `action:group` / `action:menu` member's `type`, and a dashboard header action's `actionType`. The D2 conversion `action-type-ask-ai-removed` (retired from the load path) deletes, over sources, only what nothing names and, at rest (stored rows, built artifacts), every `ask_ai` action, row and member. The D3 entry `ui-action-type-ask-ai-retired` names what is done by hand. `applyConversionsToStoredItem` now answers `undefined` when the chain leaves no item of a row, which a stored `action` row of this type is; `ConversionContext` gains `atRest`. `ActionSchema`'s ask_ai refinements and the dashboard's record-less refusal leave with the type. +- **`@objectstack/metadata-protocol`**, **`@objectstack/metadata`**, **`@objectstack/core`**, **`@objectstack/service-datasource`**: a stored row the seam yields no item of is registered and served as nothing. The database loader still finds it by name, so `DELETE /api/v1/meta/action/` removes it, and `migrateStoredMetadata` lists it `skipped` with that instruction instead of re-saving it. +- **`@objectstack/runtime`**: the action-execution branches for `ask_ai` are gone. +- **`@object-ui/core`**: `ActionRunner.setAssistantFocusHandler`, `ActionRunner.drawsAction`, `ActionRunner.bulkRefusal`, `isAskAiAction` and the `AssistantFocus` / `AssistantFocusHandler` types are removed; `ActionEngine` no longer filters undrawn actions or refuses a bulk run of one. +- **`@object-ui/react`**: `` and `useDrawsAction()` are removed. +- **`@object-ui/components`**, **`@object-ui/plugin-grid`**, **`@object-ui/plugin-detail`**: the renderers drop their drawn-action gates. +- **`@object-ui/app-shell`**: `setChatFocus` and its `follow` option are removed; the conversation's record pin is set from the composer chip only. `useAskAiHandler`, `AiSurfaceState.focusServed` and the catalog `focus` lookup behind them leave with the type. This also closes #37827, the record page that dropped the shell's ask-AI handler: there is no handler left to drop. + +Correction to two prerelease notes already published in `19.0.0-next.0` (`.changeset/pre/37142-ask-ai-action-type.md` and the `setChatFocus` line of `.changeset/pre/36999-conversation-focus.md`): the `ask_ai` action type and the `setChatFocus` setter they announce do not ship in 19.0.0. The in-composer record pin from #36999 stays. diff --git a/content/docs/protocol/objectui/actions.mdx b/content/docs/protocol/objectui/actions.mdx index a0d2b05524a..efc5299bdf2 100644 --- a/content/docs/protocol/objectui/actions.mdx +++ b/content/docs/protocol/objectui/actions.mdx @@ -41,7 +41,7 @@ refreshAfter: true ## Action Types -The `type` field selects how an action is dispatched. The complete enum is **`script`, `url`, `modal`, `flow`, `api`, `form`, `ask_ai`** — there are no other types. `type` defaults to `script` when omitted. +The `type` field selects how an action is dispatched. The complete enum is **`script`, `url`, `modal`, `flow`, `api`, `form`** — there are no other types. `type` defaults to `script` when omitted. | Type | Behavior | `target` required? | | --- | --- | --- | @@ -51,7 +51,6 @@ The `type` field selects how an action is dispatched. The complete enum is **`sc | `modal` | Open a modal/page by name. | Yes | | `api` | Call an API endpoint (`method` defaults to `POST`). | Yes | | `form` | Open a FormView by name, routed to `/_console/forms/:name` **inside the console shell**; the submit lands on the created record. | Yes | -| `ask_ai` | Open the console's in-app assistant on a fresh conversation focused on the one record the action runs on (ADR-0160 D7); a conversation the assistant showed before keeps its own focus. Sends no message and calls no server. It is not drawn with no in-app assistant, nor where no single record is held: never in a bulk bar or a related list's toolbar, and in a list toolbar only while exactly one row is selected. A dashboard header refuses it. Never an AI tool: `ai.exposed: true` beside it is refused. | No — a `target` is refused | The one thing that is not a type: the **declarative single-record field write**. It is spelled `operation: 'update'` + `patch` — the same words a list view's `bulkActionDefs` uses for the bulk form — and it rides the default `script` route: the platform action route performs the write on the data plane **as the caller** (never system-elevated), so the caller's permissions, the object's hooks and its validations fire exactly as for a user edit. Beside `operation: 'update'` an action carries no executor binding of its own — `target`, `body`, `method`, `bodyExtra` and any other explicit `type` are refused — and `patch` is merged under whatever the `params` dialog collects, so a fixed value can be declared without exposing it in the dialog. `undoable` has its anchor here: the capture is the prior value of every field the action writes — the merged bag, `patch` under `params`, not `patch` alone. @@ -225,7 +224,7 @@ interface Action { order?: number; // Sort order within a location group (lower = higher) // Behavior - type?: 'script' | 'url' | 'modal' | 'flow' | 'api' | 'form' | 'ask_ai'; // default 'script' + type?: 'script' | 'url' | 'modal' | 'flow' | 'api' | 'form'; // default 'script' target?: string; // URL / script / flow / modal / endpoint operation?: 'update'; // Declarative single-record field write (rides the default script route) patch?: Record; // Static field values for operation: 'update', merged under params diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index c200a39b108..5c7d8a78ade 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -523,7 +523,7 @@ const result = ApiMethod.parse(data); | **icon** | `string` | optional | Icon name | | **locations** | `Enum<'list_toolbar' \| 'list_item' \| 'record_header' \| 'record_more' \| …>[]` | optional | Locations where this action is visible. `record_section` is drawn only by an authored record page block that renders it; the standard record page (on a phone, in the side preview, and for an object with no authored page) does not draw it, so an action that must reach every surface adds `record_more` as well. | | **component** | `Enum<'action:button' \| 'action:icon' \| 'action:menu' \| 'action:group'>` | optional | Visual component override | -| **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | +| **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | | **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. Its system elevation does not lift the organization wall: the body has its reads and writes judged by the invoking user's organization wall. A write whose own data names an organization outside it, or empties a record's organization, is refused with PERMISSION_DENIED. Where the wall denies the user (no active organization under isolated, no membership under group), its reads of an organization's records return none, its deletes remove none, and its other writes are refused with PERMISSION_DENIED. | diff --git a/content/docs/references/kernel/metadata-plugin.mdx b/content/docs/references/kernel/metadata-plugin.mdx index 8fc86c41bfd..1a0df677fb7 100644 --- a/content/docs/references/kernel/metadata-plugin.mdx +++ b/content/docs/references/kernel/metadata-plugin.mdx @@ -331,7 +331,7 @@ const result = MetadataBulkResultSchema.parse(data); | **icon** | `string` | optional | Icon name | | **locations** | `Enum<'list_toolbar' \| 'list_item' \| 'record_header' \| 'record_more' \| …>[]` | optional | Locations where this action is visible. `record_section` is drawn only by an authored record page block that renders it; the standard record page (on a phone, in the side preview, and for an object with no authored page) does not draw it, so an action that must reach every surface adds `record_more` as well. | | **component** | `Enum<'action:button' \| 'action:icon' \| 'action:menu' \| 'action:group'>` | optional | Visual component override | -| **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | +| **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | | **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. Its system elevation does not lift the organization wall: the body has its reads and writes judged by the invoking user's organization wall. A write whose own data names an organization outside it, or empties a record's organization, is refused with PERMISSION_DENIED. Where the wall denies the user (no active organization under isolated, no membership under group), its reads of an organization's records return none, its deletes remove none, and its other writes are refused with PERMISSION_DENIED. | diff --git a/content/docs/references/ui/action.mdx b/content/docs/references/ui/action.mdx index 10d40d785ab..200d38e198f 100644 --- a/content/docs/references/ui/action.mdx +++ b/content/docs/references/ui/action.mdx @@ -50,7 +50,7 @@ const result = ActionSchema.parse(data); | **icon** | `string` | optional | Icon name | | **locations** | `Enum<'list_toolbar' \| 'list_item' \| 'record_header' \| 'record_more' \| 'record_related' \| 'record_section'>[]` | optional | Locations where this action is visible. `record_section` is drawn only by an authored record page block that renders it; the standard record page (on a phone, in the side preview, and for an object with no authored page) does not draw it, so an action that must reach every surface adds `record_more` as well. | | **component** | `Enum<'action:button' \| 'action:icon' \| 'action:menu' \| 'action:group'>` | optional | Visual component override | -| **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | +| **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | | **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. Its system elevation does not lift the organization wall: the body has its reads and writes judged by the invoking user's organization wall. A write whose own data names an organization outside it, or empties a record's organization, is refused with PERMISSION_DENIED. Where the wall denies the user (no active organization under isolated, no membership under group), its reads of an organization's records return none, its deletes remove none, and its other writes are refused with PERMISSION_DENIED. | @@ -419,7 +419,6 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities * `flow` * `api` * `form` -* `ask_ai` --- @@ -430,7 +429,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | +| **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | | **name** | `string` | optional | Machine name (lowercase snake_case) | | **label** | `string \| Record` | optional | Display label | | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | diff --git a/content/docs/references/ui/component.mdx b/content/docs/references/ui/component.mdx index 97721ea6aff..f033aeae03e 100644 --- a/content/docs/references/ui/component.mdx +++ b/content/docs/references/ui/component.mdx @@ -218,14 +218,14 @@ const result = ActionButtonPropsSchema.parse(data); | **icon** | `string` | optional | Lucide icon name rendered inside the button, left or right of the label per `iconPosition`. Read on this component — the renderer resolves it through `lucide-react`'s `icons` map via the shared `resolveIcon` helper every `action:*` site uses (a PascalCase normaliser plus a one-entry rename map), NOT the `LazyIcon` slot the container icons use; the two paths accept different spellings, and an unknown name here renders nothing rather than a fallback glyph. | | **iconPosition** | `Enum<'left' \| 'right'>` | optional (default: `"left"`) | Icon position relative to label | | **disabled** | `boolean` | optional (default: `false`) | Disable the button | -| **action** | `{ type?: Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>; name?: string; label?: string \| Record; target?: string; … }` | optional | Inline action executed on click | +| **action** | `{ type?: Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>; name?: string; label?: string \| Record; target?: string; … }` | optional | Inline action executed on click | | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes | ### Nested Shape: `ElementButtonProps.action` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | +| **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | | **name** | `string` | optional | Machine name (lowercase snake_case) | | **label** | `string \| Record` | optional | Display label | | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | diff --git a/content/docs/references/ui/dashboard.mdx b/content/docs/references/ui/dashboard.mdx index 3923b8f61f1..531d81dea9d 100644 --- a/content/docs/references/ui/dashboard.mdx +++ b/content/docs/references/ui/dashboard.mdx @@ -56,7 +56,7 @@ const result = DashboardSchema.parse(data); | :--- | :--- | :--- | :--- | | **showTitle** | `boolean` | optional (default: `true`) | Show dashboard title in header | | **showDescription** | `boolean` | optional (default: `true`) | Show dashboard description in header | -| **actions** | `{ label: string \| Record; actionUrl: string; actionType?: Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>; icon?: string }[]` | optional | Header action buttons | +| **actions** | `{ label: string \| Record; actionUrl: string; actionType?: Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>; icon?: string }[]` | optional | Header action buttons | ### Nested Shape: `Dashboard.widgets[number]` @@ -131,7 +131,7 @@ Dashboard header configuration | :--- | :--- | :--- | :--- | | **showTitle** | `boolean` | optional (default: `true`) | Show dashboard title in header | | **showDescription** | `boolean` | optional (default: `true`) | Show dashboard description in header | -| **actions** | `{ label: string \| Record; actionUrl: string; actionType?: Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>; icon?: string }[]` | optional | Header action buttons | +| **actions** | `{ label: string \| Record; actionUrl: string; actionType?: Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>; icon?: string }[]` | optional | Header action buttons | ### Nested Shape: `DashboardHeader.actions[number]` @@ -141,7 +141,7 @@ Dashboard header action | :--- | :--- | :--- | :--- | | **label** | `string \| Record` | ✅ | Action button label | | **actionUrl** | `string` | ✅ | URL or target for the action. When actionType is 'url' or omitted: an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ — every other scheme and a protocol-relative //host are refused. | -| **actionType** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>` | optional | Type of action | +| **actionType** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional | Type of action | | **icon** | `string` | optional | Icon identifier for the action button | @@ -157,7 +157,7 @@ Dashboard header action | :--- | :--- | :--- | :--- | | **label** | `string \| Record` | ✅ | Action button label | | **actionUrl** | `string` | ✅ | URL or target for the action. When actionType is 'url' or omitted: an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ — every other scheme and a protocol-relative //host are refused. | -| **actionType** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>` | optional | Type of action | +| **actionType** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional | Type of action | | **icon** | `string` | optional | Icon identifier for the action button | @@ -375,7 +375,6 @@ Widget action type * `flow` * `api` * `form` -* `ask_ai` --- diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index a6f3c1f57c8..bfe628ba5e4 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -21,7 +21,6 @@ The types you'll actually use: | `modal` | Open a modal page — client-side only, no server dispatch | `target` names the modal page (to collect input *and* run logic, use `script` + `params`) | | `api` | Call an HTTP endpoint | `target` is the endpoint; `method` / `bodyShape` / `bodyExtra` shape the request. A same-origin `target` is dispatched through the action doors (REST and MCP), which forward it in-process after their gates; an off-origin one is called by the browser directly | | `form` | Open a form view, prefilled with the current record — in-shell, and the submit lands on the created record ([contract](/docs/protocol/objectui/actions#what-type-form-promises)) | `target` names the FormView; routed to `/forms/:target?recordId=…` | -| `ask_ai` | Open the in-app assistant focused on the current record — client-side only, no message sent | No server dispatch; no `target` (refused). Not drawn where the console has no in-app assistant, nor where no single record is held (the bulk bar, a related list's toolbar, a list toolbar unless exactly one row is selected); never an AI tool | Prefer `confirmText`/`params` over the two action properties that are **not @@ -806,7 +805,6 @@ The endpoint dispatches on the **declared `type`**, exactly like the MCP | `flow` | Runs `target` on the automation engine, with your identity forwarded (a `runAs: 'user'` flow enforces RLS as you). Dispatches the same flow as `POST /api/v1/automation/:target/trigger`, without having to know the flow name — **and answers the same way**: a run that ran and was rejected is **400** `FLOW_FAILED`, while a dispatch that never happened is separated out (**404** unknown flow, a stored flow with no `start` node included, as it is never armed / **409** `FLOW_DISABLED` / **422** `FLOW_INPUT_SCHEMA_INVALID`). A target declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`) is refused **403** `PERMISSION_DENIED` to every caller but the system principal, exactly as at the trigger door, and nothing runs; holding the action's `requiredPermissions` does not open it. A target that declares its own `requiredPermissions` is refused **403** `PERMISSION_DENIED` to a caller who does not hold every capability it names, even when the action declares none. An [AI service account](/docs/ai/agents) is refused a target declared `runAs: 'system'` **403** `PERMISSION_DENIED` unless the action declares `ai.exposed: true`: an action with the opt-in is the one way an account starts a flow that runs as the system, here and over MCP `run_action`. See [Run a flow via API](/docs/automation/flows#run-a-flow-via-api) for the full table — it is one table, read by both doors. | | `api` | **Same-origin `target`** (a path starting with `/`): the door runs its gates — the sign-in floor, `requiredPermissions`, the packaged-action switch, the param contract, the subject-row load — and then **forwards the request in-process** to `target` with your own credentials, assembling the body exactly as the Console does (`recordIdParam` / `recordIdField` from the subject row, `bodyShape`, `bodyExtra` merged last, `organizationId` for an `/api/v1/auth/` target, `method`). The target endpoint still authorizes you itself; its status and body come back as the answer (its `data` unwrapped), and a credential rotation it emits (`Set-Cookie`, `set-auth-token`) is relayed. A `${ctx.selection.*}` or `{{page.}}` token exists only in the browser and is refused **400** by name. **Off-origin `target`** (another host): **400** — the browser calls it directly, and such an action cannot be switched off in the activation ledger (the write door refuses, **409**, with the reason). | | `url` / `modal` / `form` | **400** — client-side navigation; there is nothing for the server to run. | -| `ask_ai` | **400** — the console opens its in-app assistant on the record; there is nothing for the server to run. | ## Headless actions: declare it, then hide it @@ -999,7 +997,7 @@ envelope, with `resume_run`'s `{ ok, action, objectName, recordId, result }` as |:---|:---| | Button doesn't appear | `locations` doesn't include the surface (empty `locations` is right for a selection-only action that a list view's `bulkActions` places); or the `visible` CEL throws (e.g. a bare, unprefixed field name) and fail-closed hides it; or the user fails `requiredPermissions`, which hides the button at every location with no greyed-out control and no message | | Click → `Action 'x' … not found` | `target`-style script with no registered handler — add the `registerAction` call in `onEnable` (Path B above) | -| REST → 400 naming the action's `type` | The type has no server dispatch (`url`/`modal`/`form`/`api`/`ask_ai`) — open its `target` in the client, or call that endpoint directly (`ask_ai` has none: it runs only in the console) | +| REST → 400 naming the action's `type` | The type has no server dispatch (`url`/`modal`/`form`/`api`) — open its `target` in the client, or call that endpoint directly | | Appears in UI, missing from `list_actions` (MCP) | `ai.exposed` not `true`, `ai.description` under 40 characters, or the type isn't headless-callable | | Runs but the list looks stale | Add `refreshAfter: true` (an `operation: 'update'` action re-reads its record and the object's lists on its own) | diff --git a/examples/app-showcase/src/system/translations/index.ts b/examples/app-showcase/src/system/translations/index.ts index 9739dedf869..02ea621ac16 100644 --- a/examples/app-showcase/src/system/translations/index.ts +++ b/examples/app-showcase/src/system/translations/index.ts @@ -569,7 +569,6 @@ export const ShowcaseTranslationBundle = { showcase_bulk_reassign: { label: '重新分配…' }, showcase_quick_view: { label: '快速查看' }, showcase_log_time: { label: '记录工时' }, - showcase_ask_about_task: { label: '问 AI' }, showcase_new_task: { label: '新建任务' }, showcase_archive_task: { label: '归档', diff --git a/examples/app-showcase/src/ui/actions/index.ts b/examples/app-showcase/src/ui/actions/index.ts index be0fd4a42d7..60343794403 100644 --- a/examples/app-showcase/src/ui/actions/index.ts +++ b/examples/app-showcase/src/ui/actions/index.ts @@ -279,21 +279,6 @@ export const LogTimeAction = defineAction({ refreshAfter: true, }); -/** - * ask_ai — open the in-app assistant focused on this task (ADR-0160 D7). It - * takes no `target`: what the assistant reads about the record is chosen by - * the record's context pack, not by the action. The console draws it only - * where its assistant honours a focus, and sends nothing on a click. - */ -export const AskAboutTaskAction = defineAction({ - name: 'showcase_ask_about_task', - label: 'Ask AI', - icon: 'sparkles', - objectName: task, - type: 'ask_ai', - locations: ['record_header'], -}); - /** * headless command action — "New Task" (`locations: []`). * @@ -588,7 +573,6 @@ export const allActions = [ RecalcEstimateAction, RecalcSelectionAction, LogTimeAction, - AskAboutTaskAction, NewTaskAction, SubmitForSignoffAction, GenerateInvoicePdfAction, diff --git a/examples/app-showcase/src/ui/pages/task-detail.page.ts b/examples/app-showcase/src/ui/pages/task-detail.page.ts index ea25cbcc485..6745057b7f5 100644 --- a/examples/app-showcase/src/ui/pages/task-detail.page.ts +++ b/examples/app-showcase/src/ui/pages/task-detail.page.ts @@ -63,8 +63,6 @@ export const TaskDetailPage = definePage({ // record_header — inline buttons. 'showcase_mark_done', 'showcase_log_time', - // ask_ai — opens the in-app assistant on this task (ADR-0160 D7). - 'showcase_ask_about_task', 'showcase_archive_task', // record_more only — the ⋯ overflow (url, api). 'showcase_open_docs', diff --git a/packages/core/src/fallbacks/authored-translation-sync.ts b/packages/core/src/fallbacks/authored-translation-sync.ts index b116f4ceddc..414e8442807 100644 --- a/packages/core/src/fallbacks/authored-translation-sync.ts +++ b/packages/core/src/fallbacks/authored-translation-sync.ts @@ -185,6 +185,9 @@ export async function readAuthoredTranslationLayer( }, }); + // The chain yields no item of the row: nothing to merge (the stored seam's + // contract; no translation conversion deletes a row today). + if (data === undefined) continue; const locale: string | undefined = (typeof data?.locale === 'string' && data.locale) || (typeof row?.name === 'string' && LOCALE_LIKE.test(row.name) ? row.name : undefined) diff --git a/packages/drivers/driver-sql/src/sql-driver-unique-tenancy.test.ts b/packages/drivers/driver-sql/src/sql-driver-unique-tenancy.test.ts index 345d2e71421..25894b31004 100644 --- a/packages/drivers/driver-sql/src/sql-driver-unique-tenancy.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-unique-tenancy.test.ts @@ -373,7 +373,7 @@ describe('SqlDriver unique × tenancy (#3696)', () => { }, ].map((o) => ({ ...o, fields: { organization_id: { type: 'string' }, ...o.fields } })); - const converted = () => NINE_KEY_CORPUS.map((o) => applyConversionsToStoredItem('object', o)); + const converted = () => NINE_KEY_CORPUS.map((o) => applyConversionsToStoredItem('object', o)!); /** What the driver asks the database for, per table — serialized, so "identical" means bytes. */ const expectedBytes = (objects: Array<{ name: string; fields: Record; indexes: any[] }>) => diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index 1defe596d6b..092841c7fb6 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -1406,6 +1406,9 @@ export class ProtocolDiffDeleteLoadFacet { ? JSON.parse(record.metadata) : record.metadata, ); + // The stored seam yields no item of this row (ADR-0160 D7: a stored action + // row of the retired type): nothing is registered or served for it. + if (data === undefined) continue; const verdict = computeMetadataDiagnostics(normalizedType, data); if (verdict && !verdict.valid) { invalid++; diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index e409d542465..93e55468c45 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -1081,13 +1081,19 @@ export async function readMetaItem(host: Pick ({ ...placeDraft(record), standIn: true })), ...overrideDraftRecords.map((record) => ({ ...placeDraft(record), standIn: true })), - ]; + // The stored seam yields no item of this row (ADR-0160 D7: a stored action + // row of the retired type): nothing is registered or served for it. + ].filter((draft) => draft.data !== undefined); // [#7774] Same bundle slot as the active merge above — a // draft of one locale must preview over that locale, not // over the whole bundle. diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index 2b2d8a6707e..51fb172efa7 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -546,6 +546,9 @@ export class ProtocolPackageCommitsFacet { // set to `newName`, a permission set's field rules following the // renamed objects — or the collision that refuses the item, before // anything is written for it. + // The stored seam yields no item of this row (ADR-0160 D7: a stored + // action row of the retired type): the copy carries nothing for it. + if (item === undefined) continue; const outcome = rename.rewrite(row.type, row.name, item); if ('refusal' in outcome) { failed.push({ type: row.type, name: row.name, error: outcome.refusal }); @@ -793,6 +796,9 @@ export class ProtocolPackageCommitsFacet { unconvertible.push(`${planned.type} '${declaredName}': ${e?.message ?? String(e)}`); continue; } + // The stored seam yields no item of this body (ADR-0160 D7: an + // action of the retired type): nothing is imported for it. + if (converted === undefined) continue; // [#30808] A seed item's records are data: the plan already named // its object as the copy names it, and the free-text rewrite below // would turn any record value spelled like an object name. diff --git a/packages/metadata-protocol/src/protocol-registry-hydration.ts b/packages/metadata-protocol/src/protocol-registry-hydration.ts index 445e3e1a8f8..efa63c12472 100644 --- a/packages/metadata-protocol/src/protocol-registry-hydration.ts +++ b/packages/metadata-protocol/src/protocol-registry-hydration.ts @@ -1960,10 +1960,14 @@ export class ProtocolRegistryHydrationFacet { // every row has been tried. let refused: RegistryHealStop | undefined; for (const row of remainingRows) { + const item = host.convertStoredItem(String(row.type ?? canonical), storedRowDocument(row)); + // The stored seam yields no item of this row (ADR-0160 D7: a stored action + // row of the retired type): nothing is registered or served for it. + if (item === undefined) continue; const refusal = await host.applyRegistryWriteThrough({ type: canonical, name, - item: host.convertStoredItem(String(row.type ?? canonical), storedRowDocument(row)), + item, packageId: boundPackageOf(row.package_id) ?? null, organizationId: null, answerFaults: true, diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 9aa7c074415..54b95ec41da 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -2950,6 +2950,26 @@ export class ProtocolSaveFacet { ...echoNotices, ]; + // ADR-0160 D7, seventh amendment: the chain yields no item of the + // row — a stored `action` row of the retired action type IS the + // action the conversion deletes. The reads serve and register + // nothing for it already; this pass lists it on a preview and an + // apply run alike and deletes no row, because deleting it is the + // operator's, by name, through the metadata API's delete door. + if (!flowResult && item === undefined) { + record({ + ...base, + notices: flattened, + todos: flattenedTodos, + outcome: 'skipped', + reason: 'the conversion chain leaves nothing of this row: the row is itself the item a ' + + 'conversion removes, so the reads serve and register nothing for it and there is no ' + + 'body to re-save. Delete the row by name through the metadata API (DELETE ' + + `/api/v1/meta/${singular}/${base.name}) once nothing needs it.`, + }); + continue; + } + if (!apply) { record({ ...base, notices: flattened, todos: flattenedTodos, outcome: 'pending' }); continue; diff --git a/packages/metadata-protocol/src/protocol-stored-overlay-reads.ts b/packages/metadata-protocol/src/protocol-stored-overlay-reads.ts index fdb1d32e78f..dd672863c89 100644 --- a/packages/metadata-protocol/src/protocol-stored-overlay-reads.ts +++ b/packages/metadata-protocol/src/protocol-stored-overlay-reads.ts @@ -154,13 +154,16 @@ export function storedOverlayEntries( // software-package binding so the sidebar package filter and // provenance classification see overlay rows the way they see // registry items. - return records.map((record) => { + return records.flatMap((record) => { const parsed = this.convertStoredItem( String(record.type ?? request.type), typeof record.metadata === 'string' ? JSON.parse(record.metadata) : record.metadata, ) as any; + // The stored seam yields no item of this row (ADR-0160 D7: a stored action + // row of the retired type): nothing is registered or served for it. + if (parsed === undefined) return []; const recPkg = (record as { package_id?: string | null }).package_id ?? undefined; // [#28594] The row's package is its COLUMN's, and only the column's: a // `_packageId` the stored body carries is not served (dropped when the @@ -179,10 +182,10 @@ export function storedOverlayEntries( // ({@link readActiveOverlayRows}) leave a legacy organization's // rows out off the physical column. (The form doors' legacy layer // that once needed the row's own scope here is deleted.) - return { + return [{ name: String(record.name), data, packageId: recPkg, organizationId: null, type: String(record.type ?? request.type), - }; + }]; }); } diff --git a/packages/metadata-protocol/src/protocol.stored-ask-ai-retired-row.test.ts b/packages/metadata-protocol/src/protocol.stored-ask-ai-retired-row.test.ts new file mode 100644 index 00000000000..da180adac8f --- /dev/null +++ b/packages/metadata-protocol/src/protocol.stored-ask-ai-retired-row.test.ts @@ -0,0 +1,230 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0160 D7, seventh amendment — a stored `action` row whose `type` is the + * retired `ask_ai` IS the action the conversion `action-type-ask-ai-removed` + * deletes, so the stored seam (`applyConversionsToStoredItem`) yields no item + * of it. Pinned here on the protocol's own doors, over the same stub engine as + * `protocol.migrate-stored-noncanonical-type.test.ts`: + * + * - `migrateStoredMetadata` lists the row `skipped` with the way out (delete + * it by name through the metadata API), on a preview and an apply run + * alike, and writes nothing — there is no body to re-save; + * - the list read serves nothing for it, and the live row beside it as + * stored; + * - a by-name read previewing drafts treats a pending draft row of it as no + * draft, and serves the active item; + * - the layered read reports no overlay for it and no pending draft, and + * its version token still names the stored row, so a publish pinned to + * it replaces the row; + * - the metadata API's delete (`deleteMetaItem`, through + * `SysMetadataRepository`) still reaches the row and takes it out. + */ +import { describe, expect, it } from 'vitest'; +// Paid during collection, not inside a clocked case: the diagnostics `import()` it in a function body (`scripts/check-test-source-alias.mjs`). +import '@objectstack/lint'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +import { NO_PACKAGE_SCOPED_READS } from './no-package-scoped-reads.testkit.js'; +import { ObjectStackProtocolImplementation } from './protocol.js'; + +interface Row { + id: string; + type: string; + name: string; + organization_id: string | null; + package_id: string | null; + state: string; + checksum: string | null; + metadata: string; +} + +/** + * What {@link makeStubEngine} accepts for one seeded row. + * + * `metadata` is `Omit`-ed out of the `Partial` half rather than merely + * intersected over it: on the row `metadata` is the STORED string, and + * `string & unknown` is `string`, so a plain intersection refuses every body + * written as an object literal — the seeding convenience this harness exists + * for. Stated once, here, so the fixtures below need no casts. + */ +type SeedRow = Omit, 'metadata'> & { type: string; name: string; metadata: unknown }; + +function matches(r: Record, where: Record): boolean { + for (const [k, v] of Object.entries(where)) { + if (v === undefined) continue; + if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); + if ((r[k] ?? null) !== v) return false; + } + return true; +} + +/** + * The same multi-table stub as `protocol.stored-migration.test.ts`: rows are + * seeded STRAIGHT into `sys_metadata`, the only way to hold a row that every + * authoring door now refuses. + */ +function makeStubEngine(seedRows: SeedRow[], registered: Record[] = []) { + let nextId = 0; + const tables = new Map[]>(); + tables.set( + 'sys_metadata', + seedRows.map((r) => ({ + id: `r_${++nextId}`, + organization_id: null, + package_id: null, + state: 'active', + checksum: `sha256:seed_${nextId}`, + ...r, + metadata: typeof r.metadata === 'string' ? r.metadata : JSON.stringify(r.metadata), + })), + ); + const rowsOf = (t: string): Record[] => { + let rows = tables.get(t); + if (!rows) tables.set(t, (rows = [])); + return rows; + }; + + const engine: any = { + async find(t: string, opts?: { where?: Record; limit?: number }) { + const rows = rowsOf(t).filter((r) => matches(r, opts?.where ?? {})); + return typeof opts?.limit === 'number' ? rows.slice(0, opts.limit) : rows; + }, + async findOne(t: string, opts?: { where?: Record }) { + assertEngineFindOnePredicate(t, opts); + return rowsOf(t).find((r) => matches(r, opts?.where ?? {})) ?? null; + }, + async insert(t: string, row: Record) { + const withId = { id: row.id ?? `r_${++nextId}`, ...row }; + rowsOf(t).push(withId); + return withId; + }, + async update(t: string, patch: Record, opts: { where: Record }) { + assertEngineUpdateDispatch(patch, opts); + const target = rowsOf(t).find((r) => matches(r, opts.where)); + if (target) Object.assign(target, patch); + return target ?? { id: 'x' }; + }, + async delete(t: string, opts?: Record) { + // [#4550] The producer's own delete-verb dispatch contract. + assertEngineDeleteDispatch(opts); + const rows = rowsOf(t); + const at = rows.findIndex((r) => r.id === (opts as { where?: { id?: unknown } })?.where?.id); + if (at >= 0) rows.splice(at, 1); + return { deleted: at >= 0 ? 1 : 0 }; + }, + registry: { + ...NO_PACKAGE_SCOPED_READS, + listItems: () => [], + getItem: (type: string, name: string) => + (type === 'action' ? registered.find((i) => i.name === name) : undefined), + isPackageDisabled: () => false, + registerItem: () => { /* no-op */ }, + registerObject: () => { /* no-op */ }, + removeRuntimeShadow: () => false, + removeOverlayEntry: () => { /* no-op */ }, + }, + }; + return { engine, tables }; +} + +const metaRows = (tables: Map[]>) => tables.get('sys_metadata')!; +const historyRows = (tables: Map[]>) => + tables.get('sys_metadata_history') ?? []; + +const askAiRow: SeedRow = { + type: 'action', + name: 'ask_about_ticket', + metadata: { name: 'ask_about_ticket', label: 'Ask AI', objectName: 'ticket', type: 'ask_ai' }, +}; +const liveRow: SeedRow = { + type: 'action', + name: 'close_ticket', + metadata: { name: 'close_ticket', label: 'Close', objectName: 'ticket', type: 'script', target: 'close_ticket' }, +}; + +describe('a stored ask_ai action row (ADR-0160 D7)', () => { + it('the stored pass lists it skipped, with the delete door named', async () => { + const { engine } = makeStubEngine([askAiRow, liveRow]); + const protocol = new ObjectStackProtocolImplementation(engine); + + const report = await protocol.migrateStoredMetadata(); + + expect(report.skipped).toBe(1); + const row = report.rows.find((r) => r.name === 'ask_about_ticket')!; + expect(row).toMatchObject({ type: 'action', outcome: 'skipped' }); + expect(row.notices.map((n) => n.conversionId)).toContain('action-type-ask-ai-removed'); + expect(row.reason).toContain('DELETE /api/v1/meta/action/ask_about_ticket'); + }); + + it('an apply run writes nothing for it', async () => { + const { engine, tables } = makeStubEngine([askAiRow]); + const before = JSON.stringify(metaRows(tables)); + const protocol = new ObjectStackProtocolImplementation(engine); + + const report = await protocol.migrateStoredMetadata({ apply: true }); + + expect(report.skipped).toBe(1); + expect(report.rewritten).toBe(0); + expect(JSON.stringify(metaRows(tables))).toBe(before); + expect(historyRows(tables)).toHaveLength(0); + }); + + it('the list read serves nothing for it, and the live row beside it', async () => { + const { engine } = makeStubEngine([askAiRow, liveRow]); + const protocol = new ObjectStackProtocolImplementation(engine); + + const served = await protocol.getMetaItems({ type: 'action' }); + const names = ((served as { items?: Array<{ name: string }> }).items ?? []).map((i) => i.name); + + expect(names).toContain('close_ticket'); + expect(names).not.toContain('ask_about_ticket'); + }); + + it('a by-name read previewing drafts treats a pending ask_ai draft as no draft, and serves the active item', async () => { + // The active item is the registry's (a hydrated live row); the draft + // row of the same name is of the retired type. + const active = { name: 'ask_about_ticket', label: 'Close', objectName: 'ticket', type: 'script', target: 'close_ticket' }; + const { engine } = makeStubEngine([{ ...askAiRow, state: 'draft' }], [active]); + const protocol = new ObjectStackProtocolImplementation(engine); + + const served = await protocol.getMetaItem({ type: 'action', name: 'ask_about_ticket', previewDrafts: true }); + + expect((served as { item?: unknown }).item).toMatchObject(active); + expect((served as { item?: Record }).item?._draft).toBeUndefined(); + }); + + it('the layered read reports no overlay and no pending draft for it', async () => { + const { engine } = makeStubEngine([askAiRow, { ...askAiRow, state: 'draft' }]); + const protocol = new ObjectStackProtocolImplementation(engine); + + const layered = await protocol.getMetaItemLayered({ type: 'action', name: 'ask_about_ticket' }, { withDraft: true, withVersion: true }); + + expect(layered).toMatchObject({ overlay: null, overlayScope: null, draft: null }); + expect(layered.overlayVersion).toEqual(expect.any(String)); + }); + + it('the layered version token still names the stored row, so a publish pinned to it replaces the row', async () => { + // Studio pins a publish to the layered read's `overlayVersion`. A + // `null` token would pin `If-None-Match: *`, which the row still + // stored at the address refuses `409`; the stored row's token lets a + // new action of the name be published over it. + const { engine, tables } = makeStubEngine([askAiRow]); + const protocol = new ObjectStackProtocolImplementation(engine); + const { overlayVersion } = await protocol.getMetaItemLayered({ type: 'action', name: 'ask_about_ticket' }, { withVersion: true }); + const live = { name: 'ask_about_ticket', label: 'Close', objectName: 'ticket', type: 'script', target: 'close_ticket' }; + + await protocol.saveMetaItem({ type: 'action', name: 'ask_about_ticket', item: live, mode: 'draft' }); + await protocol.publishMetaItem({ type: 'action', name: 'ask_about_ticket', parentVersion: overlayVersion }); + + expect(metaRows(tables).map((r) => [r.state, JSON.parse(r.metadata).type])).toEqual([['active', 'script']]); + }); + + it('the metadata API delete reaches the row and takes it out', async () => { + const { engine, tables } = makeStubEngine([askAiRow, liveRow]); + const protocol = new ObjectStackProtocolImplementation(engine); + + await protocol.deleteMetaItem({ type: 'action', name: 'ask_about_ticket' }); + + expect(metaRows(tables).map((r) => r.name)).toEqual(['close_ticket']); + }); +}); diff --git a/packages/metadata/src/loaders/database-loader-ask-ai-retired-row.test.ts b/packages/metadata/src/loaders/database-loader-ask-ai-retired-row.test.ts new file mode 100644 index 00000000000..3e45c7032df --- /dev/null +++ b/packages/metadata/src/loaders/database-loader-ask-ai-retired-row.test.ts @@ -0,0 +1,89 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0160 D7, seventh amendment — a stored `action` row whose `type` is the + * retired `ask_ai` IS the action the conversion `action-type-ask-ai-removed` + * deletes, so the stored seam yields no item of it. What this file pins on the + * real store (`driver-sqlite-wasm`, read back from the rows): + * + * - the read serves NOTHING for that row — `load` answers no data — while a + * live action row beside it is served as stored; + * - the row is still found BY NAME: `exists` answers true and `delete` + * takes it out, so the metadata API's delete door reaches it. A loader + * that resolved a row's identity through the converted body would find no + * name for it and leave it in the store for good; + * - a write of the same name still reads the row's object binding from its + * stored body, so the loader names the row's object and keeps the two + * bindings apart (red when identity is read through the converted body). + */ + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; +import { DatabaseLoader } from './database-loader.js'; + +const ASK = { name: 'ask_about_ticket', label: 'Ask AI', objectName: 'ticket', type: 'ask_ai' }; +const CLOSE = { name: 'close_ticket', label: 'Close', objectName: 'ticket', type: 'script', target: 'close_ticket' }; + +describe('DatabaseLoader — a stored ask_ai action row (ADR-0160 D7)', () => { + let driver: SqliteWasmDriver; + let loader: DatabaseLoader; + + const seed = (id: string, body: Record) => + driver.create('sys_metadata', { + id, + type: 'action', + name: body.name, + state: 'active', + version: 1, + checksum: `seed_${id}`, + source: 'database', + package_id: null, + metadata: JSON.stringify(body), + }); + + const storedNames = async () => + ((await driver.find('sys_metadata', { where: { type: 'action' } })) as Array<{ name: string }>) + .map((r) => r.name) + .sort(); + + beforeEach(async () => { + driver = new SqliteWasmDriver({ filename: ':memory:' }); + await driver.connect(); + loader = new DatabaseLoader({ driver, cache: { enabled: false } }); + await loader.list('action'); + await seed('r_ask', ASK); + await seed('r_close', CLOSE); + }); + + afterEach(async () => { + await driver.disconnect(); + }); + + it('serves nothing for the ask_ai row, and the live row beside it as stored', async () => { + expect((await loader.load('action', 'ask_about_ticket')).data ?? null).toBeNull(); + expect((await loader.load('action', 'close_ticket')).data).toMatchObject(CLOSE); + }); + + it('still finds the row by name, and the delete door takes it out', async () => { + expect(await loader.exists('action', 'ask_about_ticket')).toBe(true); + await loader.delete('action', 'ask_about_ticket'); + expect(await storedNames()).toEqual(['close_ticket']); + expect(await loader.exists('action', 'ask_about_ticket')).toBe(false); + }); + + it('a write of the same name still reads the row\'s own object binding, so the two bindings keep apart', async () => { + // The row was written before the loader named objects (`bundle_member` + // empty). Its object comes from its stored body, which the converted read + // no longer has; a loader that took identity from that read would count + // it object-less and leave it unnamed beside the new binding. + await loader.save('action', 'ask_about_ticket', { ...CLOSE, name: 'ask_about_ticket', objectName: 'case' }); + const rows = (await driver.find('sys_metadata', { where: { type: 'action', name: 'ask_about_ticket' } })) as Array<{ + id: string; + bundle_member: string | null; + }>; + expect(rows.map((r) => [r.id === 'r_ask' ? 'stored' : 'saved', r.bundle_member]).sort()).toEqual([ + ['saved', 'case'], + ['stored', 'ticket'], + ]); + }); +}); diff --git a/packages/metadata/src/loaders/database-loader.ts b/packages/metadata/src/loaders/database-loader.ts index ce468d2066f..64a81525748 100644 --- a/packages/metadata/src/loaders/database-loader.ts +++ b/packages/metadata/src/loaders/database-loader.ts @@ -1038,6 +1038,21 @@ export class DatabaseLoader implements MetadataLoader { * open-namespace conflict guard; flows canonicalize at `registerFlow`. */ private rowToData(row: Record): Record | null { + return this.convertRow(row, false); + } + + /** + * The body a row's IDENTITY is read from (its name, its bundle member): the + * converted body, or the stored one where the conversion chain yields no item + * of the row (ADR-0160 D7 — a stored action row of the retired type). Such a row is + * served as nothing ({@link rowToData} answers `null`), and it must still be + * found by name, so the delete door can take it out. + */ + private rowIdentityData(row: Record): Record | null { + return this.convertRow(row, true); + } + + private convertRow(row: Record, identity: boolean): Record | null { if (!row || !row.metadata) return null; const payload = typeof row.metadata === 'string' @@ -1046,7 +1061,7 @@ export class DatabaseLoader implements MetadataLoader { const singular = PLURAL_TO_SINGULAR[row.type as string] ?? (row.type as string); if (singular === 'flow') return payload as Record; - return applyConversionsToStoredItem(singular, payload as Record, { + const converted = applyConversionsToStoredItem(singular, payload as Record, { onNotice: (n) => { const key = `${n.conversionId}|${singular}|${String(row.name ?? '')}`; if (this.storedConversionWarned.has(key)) return; @@ -1056,6 +1071,8 @@ export class DatabaseLoader implements MetadataLoader { ); }, }); + if (converted !== undefined) return converted; + return identity ? (payload as Record) : null; } /** @@ -1356,8 +1373,8 @@ export class DatabaseLoader implements MetadataLoader { // holds it once named (`namedRowColumnOf`): a row whose object the column // cannot store keeps the object-less binding's place. const memberOf = (of: Record) => { - const column = namedRowColumnOf(type, this.rowToData(of), of.bundle_member); - return column !== undefined ? column : (storedRowMemberOf(type, this.rowToData(of), of.bundle_member) ?? null); + const column = namedRowColumnOf(type, this.rowIdentityData(of), of.bundle_member); + return column !== undefined ? column : (storedRowMemberOf(type, this.rowIdentityData(of), of.bundle_member) ?? null); }; const target = memberOf(row); const ofPackage = rows.filter((other) => other !== row && other.package_id === read.packageId); @@ -1366,8 +1383,8 @@ export class DatabaseLoader implements MetadataLoader { // written before their object was named are named first, and this row's // object is named in the same update — otherwise two of the package's // bindings would share the object-less place of the unique key. - const owned = namedRowColumnOf(type, this.rowToData(row), row.bundle_member) !== undefined; - if (owned) await this.nameUnnamedRows(type, name, unnamedRowsOf(type, ofPackage, (of) => this.rowToData(of))); + const owned = namedRowColumnOf(type, this.rowIdentityData(row), row.bundle_member) !== undefined; + if (owned) await this.nameUnnamedRows(type, name, unnamedRowsOf(type, ofPackage, (of) => this.rowIdentityData(of))); const naming = owned && typeof target === 'string' && row.bundle_member !== target ? { bundle_member: target } : {}; await this._update(this.tableName, read.id, { package_id: read.packageId, ...naming }); // [#37039] The handed-out body answers the column as this update left it, not as the @@ -1915,7 +1932,7 @@ export class DatabaseLoader implements MetadataLoader { const rowsOfName = slot && member !== undefined ? slot.rows : []; const existing = member === undefined ? (slot ? slot.rows[0] ?? null : await this._findOne(this.tableName, { where: this.baseFilter(type, name) })) - : rowsOfName.find((row) => (storedRowMemberOf(type, this.rowToData(row), row.bundle_member) ?? null) === member) ?? null; + : rowsOfName.find((row) => (storedRowMemberOf(type, this.rowIdentityData(row), row.bundle_member) ?? null) === member) ?? null; // [#32540 C9] The restored body may be bound to an object the slot holds no // row of (a row written before held one binding and was later re-bound // to another object): it is restored as that binding's own row, in the @@ -1946,7 +1963,7 @@ export class DatabaseLoader implements MetadataLoader { // [#32540 C3] A rollback is a write of the slot too: its rows written // before their object was named are named first. if (member !== undefined && !isBundledStoreType(type)) { - await this.nameUnnamedRows(type, name, unnamedRowsOf(type, rowsOfName, (row) => this.rowToData(row))); + await this.nameUnnamedRows(type, name, unnamedRowsOf(type, rowsOfName, (row) => this.rowIdentityData(row))); } const previousChecksum = existing?.checksum as string | undefined; @@ -2144,7 +2161,7 @@ export class DatabaseLoader implements MetadataLoader { // (`storeRowSlotKey`): an action bound to an object by its package, object // and name, so the write counts the holders of its `(object, name)` as // `storeWriteKey` does, never every package holding the name. - const memberOf = (row: Record) => storedRowMemberOf(type, this.rowToData(row), row.bundle_member); + const memberOf = (row: Record) => storedRowMemberOf(type, this.rowIdentityData(row), row.bundle_member); const slotOf = (row: Record) => storeRowSlotKey(type, name, storedRowPackageId(row), memberOf(row)); const bySlot = new Map>(); for (const row of rows) { @@ -2184,7 +2201,7 @@ export class DatabaseLoader implements MetadataLoader { const buckets = new Set([key, ...replaces].map((slot) => storeRowKey(name, slotPackageOf(slot)))); const unnamed = isBundledStoreType(type) ? [] - : unnamedRowsOf(type, rows.filter((row) => buckets.has(storeRowKey(name, storedRowPackageId(row)))), (row) => this.rowToData(row)); + : unnamedRowsOf(type, rows.filter((row) => buckets.has(storeRowKey(name, storedRowPackageId(row)))), (row) => this.rowIdentityData(row)); return { existing, packageId: slotPackageOf(key), rows, member: member ?? null, unnamed }; } const existing = bySlot.get(key) ?? replaces.map((replaced) => bySlot.get(replaced)).find(Boolean) ?? null; @@ -2244,7 +2261,7 @@ export class DatabaseLoader implements MetadataLoader { for (const row of rows) { if (row === except || bucket(row.package_id) !== bucket(into.packageColumn)) continue; if (typeof row.bundle_member === 'string' && row.bundle_member !== '') continue; - const member = storedRowMemberOf(type, this.rowToData(row), row.bundle_member); + const member = storedRowMemberOf(type, this.rowIdentityData(row), row.bundle_member); if (typeof member !== 'string' || member.length <= STORED_MEMBER_MAX_LENGTH) continue; const where = bucket(into.packageColumn) === '' ? 'with no package' : `of package "${bucket(into.packageColumn)}"`; throw new Error( @@ -2318,7 +2335,7 @@ export class DatabaseLoader implements MetadataLoader { if (slot?.unnamed !== undefined && !isBundledStoreType(type) && (!existing || Object.keys(binding).length > 0)) { this.refuseUnnameableHolder(type, name, slot.rows, { packageColumn: slot.packageId ?? existing?.package_id, - column: existing ? namedRowColumnOf(type, this.rowToData(existing), existing.bundle_member) : slot.member, + column: existing ? namedRowColumnOf(type, this.rowIdentityData(existing), existing.bundle_member) : slot.member, }, existing); } await this.nameUnnamedRows(type, name, slot?.unnamed); diff --git a/packages/runtime/src/action-ask-ai-headless.test.ts b/packages/runtime/src/action-ask-ai-headless.test.ts deleted file mode 100644 index 23bb6272a86..00000000000 --- a/packages/runtime/src/action-ask-ai-headless.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * ADR-0160 D7 — `type: 'ask_ai'` has no server dispatch. - * - * The console focuses its in-app assistant on the record and sends nothing. - * The two predicates every headless door asks are the whole of the server - * half: - * - * · `isHeadlessInvokableAction` answers `false`, so MCP `list_actions` skips - * it and the `ai` posture of the action door refuses it — whatever the - * declaration carries beside the type (a data-at-rest row can carry keys - * the parse refuses, such as a `target` or `ai.exposed: true`); - * · `headlessActionTypeError` answers the REST caller with a sentence that - * describes THIS type — not the generic "the renderer opens its `target`", - * which names a key `ask_ai` refuses at parse. - */ -import { describe, it, expect } from 'vitest'; -import { isHeadlessInvokableAction, headlessActionTypeError } from './action-execution.js'; -// Paid at collection, not inside a clocked case (check:test-source-alias). -import '@objectstack/metadata'; - -const NO_DEPS = {} as never; -const ASK = { name: 'ask_about_account', type: 'ask_ai' }; - -describe('ask_ai — no server dispatch (ADR-0160 D7)', () => { - it('is not headless-invokable, with or without an automation service', () => { - expect(isHeadlessInvokableAction(NO_DEPS, ASK, true)).toBe(false); - expect(isHeadlessInvokableAction(NO_DEPS, ASK, false)).toBe(false); - }); - - it('stays not invokable for a row at rest that carries what the parse refuses', () => { - const atRest = { - ...ASK, - target: '/api/v1/data/account', - body: { language: 'js', source: 'return 1;' }, - ai: { exposed: true, description: 'Opens the assistant focused on this account record.' }, - }; - expect(isHeadlessInvokableAction(NO_DEPS, atRest, true)).toBe(false); - }); - - it('is refused at the REST door with a sentence about the assistant, naming no target', () => { - const error = headlessActionTypeError(NO_DEPS, ASK, 'account'); - expect(error).not.toBeNull(); - expect(error!.split(' — ')[0]).toBe("Action 'ask_about_account' on 'account' is `type: 'ask_ai'`"); - expect(error).toContain('in-app assistant'); - expect(error).not.toContain('target'); - }); - - it('leaves the other client types on the generic sentence', () => { - expect(headlessActionTypeError(NO_DEPS, { name: 'go', type: 'url', target: '/x' }, 'account')) - .toContain('The renderer opens its `target`'); - }); -}); diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 2aa7db94e87..86856dffb3d 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -1360,9 +1360,6 @@ export function isHeadlessInvokableAction(_deps: ActionExecutionDeps, action: an // forwards it in-process to its declared `target` (see // {@link forwardApiAction}). An off-origin one stays browser-only. if (type === 'api') return isSameOriginApiTarget(action?.target); - // `url`, `modal`, `form` and `ask_ai` (ADR-0160 D7 — it focuses the - // console's assistant on a record and is never an AI tool) have no server - // dispatch. return false; } @@ -2507,16 +2504,6 @@ export function headlessActionTypeError(_deps: ActionExecutionDeps, action: any, `${typeof action?.method === 'string' ? ` (${action.method})` : ''}.` ); } - if (type === 'ask_ai') { - // ADR-0160 D7: `ask_ai` names nothing and runs nothing server-side — - // the console focuses its in-app assistant on the record. The generic - // sentence below ("the renderer opens its `target`") would describe a - // key this type refuses at parse. - return ( - `Action '${name}'${on} is \`type: 'ask_ai'\` — a client-side action with no server dispatch. ` + - `The console opens its in-app assistant focused on the record; there is nothing for the server to run.` - ); - } return ( `Action '${name}'${on} is \`type: '${type}'\` — a client-side action with no server dispatch. ` + `The renderer opens its \`target\`${target ? ` ('${target}')` : ''}; there is nothing for the server to run.` diff --git a/packages/services/service-datasource/src/datasource-admin-plugin.ts b/packages/services/service-datasource/src/datasource-admin-plugin.ts index 9d5577207f3..78f0091acce 100644 --- a/packages/services/service-datasource/src/datasource-admin-plugin.ts +++ b/packages/services/service-datasource/src/datasource-admin-plugin.ts @@ -203,7 +203,9 @@ async function loadDatasourceRows(engine: DataEngineLike | undefined): Promise ({ + actions: [ + { name: 'ask_about_ticket', label: 'Ask AI', objectName: 'ticket', type: 'ask_ai' }, + { name: 'ask_unnamed', label: 'Ask AI', objectName: 'ticket', type: 'ask_ai' }, + { name: 'close_ticket', label: 'Close', objectName: 'ticket', type: 'script' }, + ], + views: [{ name: 'ticket_list', object: 'ticket', rowActions: ['ask_about_ticket', 'close_ticket'] }], +}); + +describe('action-type-ask-ai-removed (ADR-0160 D7)', () => { + it('is registered for protocol 19 and retired from the authoring load path', () => { + const entry = ALL_CONVERSIONS.find((c) => c.id === ID); + expect(entry, 'the conversion is registered').toBeDefined(); + expect(entry!.toMajor).toBe(19); + expect(entry!.retiredFromLoadPath).toBe(true); + }); + + it('over sources: a named ask_ai action is kept with its reference, an unnamed one is deleted, the D3 entry is listed', () => { + const before = referencedStack(); + const result = applyMetaMigrations(before, 18, 19); + const after = result.stack as ReturnType; + expect(after.actions.map((a) => a.name)).toEqual(['ask_about_ticket', 'close_ticket']); + expect(after.views).toEqual(before.views); + expect(result.applied.filter((a) => a.conversionId === ID).map((a) => a.path)).toEqual(['actions[1]']); + expect(result.todos.map((t) => t.id)).toContain('ui-action-type-ask-ai-retired'); + }); + + it('over sources: the kept action is reported as a todo when the caller listens', () => { + const entry = ALL_CONVERSIONS.find((c) => c.id === ID)!; + const todos: ConversionTodoDetail[] = []; + const out = entry.apply(referencedStack(), () => {}, { reportTodo: (t) => todos.push(t) }); + expect((out.actions as { name: string }[]).map((a) => a.name)).toEqual(['ask_about_ticket', 'close_ticket']); + expect(todos).toHaveLength(1); + expect(todos[0]).toMatchObject({ path: 'actions[0]', from: 'ask_ai' }); + expect(todos[0].reason).toContain('`ask_about_ticket`'); + }); + + it('an object-nested action named by its own object is kept over sources', () => { + const stack = { + objects: [{ + name: 'ticket', + actions: [{ name: 'ask_row', label: 'Ask AI', type: 'ask_ai' }], + listViews: { all: { rowActions: ['ask_row'] } }, + }], + }; + const out = applyMetaMigrations(stack, 18, 19).stack as typeof stack; + expect(out.objects[0].actions).toEqual(stack.objects[0].actions); + }); + + it('at rest: every ask_ai action is deleted, named or not, and the reference is left as it was', () => { + const { stack, notices } = collectConversionNotices(referencedStack(), { includeRetired: true }); + const after = stack as ReturnType; + expect(after.actions.map((a) => a.name)).toEqual(['close_ticket']); + expect(after.views[0].rowActions).toEqual(['ask_about_ticket', 'close_ticket']); + expect(notices.filter((n) => n.conversionId === ID).map((n) => n.path)).toEqual(['actions[0]', 'actions[1]']); + }); + + it('is idempotent: the at-rest result replays to the same reference', () => { + const once = applyConversions(referencedStack(), { includeRetired: true }); + expect(applyConversions(once, { includeRetired: true })).toBe(once); + }); + + it('the stored seam: an action row that IS an ask_ai action yields no item', () => { + expect(applyConversionsToStoredItem('action', { name: 'ask_about_ticket', label: 'Ask AI', type: 'ask_ai' })) + .toBeUndefined(); + }); + + it('the stored seam: a live action row and an object row with an ask_ai action keep the rest', () => { + const live = { name: 'close_ticket', label: 'Close', type: 'script' }; + expect(applyConversionsToStoredItem('action', live)).toEqual(live); + const object = applyConversionsToStoredItem('object', { + name: 'ticket', + label: 'Ticket', + actions: [ + { name: 'ask_row', label: 'Ask AI', type: 'ask_ai' }, + { name: 'reopen_ticket', label: 'Reopen', type: 'script' }, + ], + }) as { actions: { name: string }[] }; + expect(object.actions.map((a) => a.name)).toEqual(['reopen_ticket']); + }); +}); diff --git a/packages/spec/src/conversions/apply.ts b/packages/spec/src/conversions/apply.ts index 81b64fca5c3..2159c42d6aa 100644 --- a/packages/spec/src/conversions/apply.ts +++ b/packages/spec/src/conversions/apply.ts @@ -159,6 +159,9 @@ export function applyConversions( if (conversion.retiredFromLoadPath && !includeRetired) continue; const retiresIn = conversion.toMajor + 1; const context: ConversionContext = { + // Only the data-at-rest doors (and the fixture CI) replay retired + // entries, so the window this pass opens says what it reads. + atRest: includeRetired, reportTodo: onTodo ? (detail) => onTodo({ diff --git a/packages/spec/src/conversions/conversions.test.ts b/packages/spec/src/conversions/conversions.test.ts index 37a2ba34e83..cef0da64a66 100644 --- a/packages/spec/src/conversions/conversions.test.ts +++ b/packages/spec/src/conversions/conversions.test.ts @@ -1024,7 +1024,7 @@ describe('conversion layer (ADR-0087 D2)', () => { // The row as written is what the parse now refuses … expect(JobSchema.safeParse(raw).success).toBe(false); // … and the seam's replay (stored-row rehydration) makes it load, three retries and all. - const converted = applyConversionsToStoredItem('job', structuredClone(raw)); + const converted = applyConversionsToStoredItem('job', structuredClone(raw))!; expect(converted.retryPolicy).toEqual({ backoffMs: 5000, maxRetries: 3, backoffMultiplier: 2 }); expect(JobSchema.safeParse(converted).success).toBe(true); }); @@ -1316,7 +1316,7 @@ describe('conversion layer (ADR-0087 D2)', () => { name: 'crm_lead_detail', regions: [{ name: 'header', components: [{ type: 'page-header', properties: { title: 'Leads', description: 'All open leads' } }] }], }; - const out = applyConversionsToStoredItem('page', row, { onNotice: (n) => notices.push(n) }); + const out = applyConversionsToStoredItem('page', row, { onNotice: (n) => notices.push(n) })!; expect(out.regions[0]!.components[0]!.properties).toEqual({ title: 'Leads', subtitle: 'All open leads' }); expect(notices.map((n) => n.conversionId)).toEqual(['page-header-subtitle-alias']); }); @@ -1583,7 +1583,7 @@ describe('conversion layer (ADR-0087 D2)', () => { label: 'Contact', fields: { company_id: { type: 'lookup', label: 'Company', reference_to: 'crm_company' } }, }; - const out = applyConversionsToStoredItem('object', row, { onNotice: (n) => notices.push(n) }); + const out = applyConversionsToStoredItem('object', row, { onNotice: (n) => notices.push(n) })!; expect(out.fields.company_id).toEqual({ type: 'lookup', label: 'Company', reference: 'crm_company' }); expect(notices.map((n) => n.conversionId)).toEqual(['field-reference-to-alias']); }); diff --git a/packages/spec/src/conversions/entries/19/action-type-ask-ai-removed.ts b/packages/spec/src/conversions/entries/19/action-type-ask-ai-removed.ts new file mode 100644 index 00000000000..69f70c2192c --- /dev/null +++ b/packages/spec/src/conversions/entries/19/action-type-ask-ai-removed.ts @@ -0,0 +1,295 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { ConversionContext, MetadataConversion } from '../../types.js'; +import { mapCollection, mapPageComponents, removePageComponents } from '../../walk.js'; +import { ACTION_CONTAINER_BLOCK_TYPES, ACTION_RUNNER_BLOCK_TYPES, isDict, type Dict, type Emit } from '../shared.js'; + +/** + * The `ask_ai` action type leaves the spec (protocol 19; ADR-0160 D7 as its + * seventh amendment rules, "What a legacy `ask_ai` action meets"). + * + * `ask_ai` was published only on the 19 prerelease line (`19.0.0-next.0`) and + * in no stable release. The maintainer retired it with no compatibility shim: + * the shell's 「问 AI」 entry is the one way into the assistant, and nothing + * converts an `ask_ai` action into something else. So every edit here is a + * DELETE, and every authoring surface refuses the value with its prescription + * (`ui/action-ask-ai-retired.ts`); this entry is retired from the load path + * from the day it lands. + * + * What it deletes, in each slot that takes an action type: + * + * - a declared action, `actions[]` or an object's own `objects[].actions[]`, + * whose `type` is `ask_ai` — the entry; + * - an `action:button` / `action:icon` row whose `properties.actionType` is + * `ask_ai`, and an `element:button` whose inline `properties.action.type` is + * `ask_ai` — the component, the smallest part that leaves the page + * parseable (a button left without its executor would draw and do nothing); + * - an `action:group` / `action:menu` member whose `type` is `ask_ai` — the + * member, the rest of the list kept in order. + * + * Where it reads decides how much (`ConversionContext.atRest`): + * + * - **Over sources** (`os migrate meta --from 18`) it deletes a declared + * action only when NOTHING in the stack names it. "Names" is tested + * conservatively: the action's name appearing as any string value outside + * the `ask_ai` entries themselves keeps it, so the stack it leaves names no + * action it does not define on any surface the rule `ACTION_NAME_UNDEFINED` + * walks — and where it cannot tell, it keeps the action. A kept action stays + * as written with each reference, so the source still meets the refusal; + * the D3 entry `ui-action-type-ask-ai-retired` says what is done by hand. + * The conversion never deletes a reference. + * - **At rest** (a stored row, a built artifact) it deletes every `ask_ai` + * action, named or not: there is no author to teach, and a reference left + * resolving nowhere is what an undefined action name already does. + * + * Inline rows and members are deleted on both paths: nothing names them. A + * stored `action` row that IS one such action yields no item at all, which the + * stored seam answers as such (`applyConversionsToStoredItem`). + * + * Idempotent by construction: a pass finds no `ask_ai` left to delete, and a + * kept one is kept again for the same reference. + */ + +const ASK_AI = 'ask_ai'; + +const isAskAiAction = (entry: unknown): entry is Dict => isDict(entry) && entry.type === ASK_AI; + +/** + * Every string value in `value`, skipping the declared `ask_ai` entries (an + * entry's own `name` does not name it, and two copies of one action do not + * name each other). + */ +function collectStrings(value: unknown, into: Set, depth = 0): void { + if (depth > 64) return; + if (typeof value === 'string') { + into.add(value); + return; + } + if (Array.isArray(value)) { + for (const v of value) collectStrings(v, into, depth + 1); + return; + } + if (!isDict(value)) return; + for (const v of Object.values(value)) collectStrings(v, into, depth + 1); +} + +function namedStrings(stack: Dict): Set { + const strings = new Set(); + for (const [key, value] of Object.entries(stack)) { + if (key === 'actions' && Array.isArray(value)) { + for (const entry of value) if (!isAskAiAction(entry)) collectStrings(entry, strings); + continue; + } + if (key === 'objects' && Array.isArray(value)) { + for (const obj of value) { + if (!isDict(obj)) { + collectStrings(obj, strings); + continue; + } + for (const [objKey, objValue] of Object.entries(obj)) { + if (objKey === 'actions' && Array.isArray(objValue)) { + for (const entry of objValue) if (!isAskAiAction(entry)) collectStrings(entry, strings); + } else { + collectStrings(objValue, strings); + } + } + } + continue; + } + collectStrings(value, strings); + } + return strings; +} + +function removeDeclared( + list: unknown[], + basePath: string, + emit: Emit, + keep: (action: Dict) => boolean, + context: ConversionContext | undefined, +): unknown[] { + let changed = false; + const next = list.filter((entry, i) => { + if (!isAskAiAction(entry)) return true; + const path = `${basePath}[${i}]`; + if (keep(entry)) { + context?.reportTodo?.({ + path, + from: ASK_AI, + reason: + `the \`ask_ai\` action \`${String(entry.name)}\` is named elsewhere in the stack, so it is left as written ` + + 'with each reference: delete the action and every reference to it by hand', + }); + return true; + } + changed = true; + emit({ from: ASK_AI, to: '(removed)', path }); + return false; + }); + return changed ? next : list; +} + +const actionTypeAskAiRemoved: MetadataConversion = { + id: 'action-type-ask-ai-removed', + toMajor: 19, + retiredFromLoadPath: true, + retiredAfter: '18.6.0', + surface: 'action.type / object.actions[].type / page.component.action:button.actionType / ' + + 'page.component.action:icon.actionType / page.component.element:button.action.type / ' + + 'page.component.action:group.actions[].type / page.component.action:menu.actions[].type', + summary: + "action type 'ask_ai' removed (ADR-0160 D7): the shell's 「问 AI」 entry is the one way into the " + + 'assistant. An `ask_ai` action, row or member is deleted; over sources a declared action that ' + + 'something names is left with its references, for the author to delete by hand', + apply(stack, emit, context) { + const atRest = context?.atRest === true; + let referenced: Set | undefined; + const keep = (action: Dict): boolean => { + if (atRest || typeof action.name !== 'string') return false; + referenced ??= namedStrings(stack); + return referenced.has(action.name); + }; + + let next = stack; + if (Array.isArray(next.actions)) { + const kept = removeDeclared(next.actions, 'actions', emit, keep, context); + if (kept !== next.actions) next = { ...next, actions: kept }; + } + next = mapCollection(next, 'objects', (obj, path) => { + if (!Array.isArray(obj.actions)) return obj; + const kept = removeDeclared(obj.actions, `${path}.actions`, emit, keep, context); + return kept === obj.actions ? obj : { ...obj, actions: kept }; + }); + + next = removePageComponents(next, (component, path) => { + const type = component.type; + const properties = component.properties; + if (typeof type !== 'string' || !isDict(properties)) return false; + if (ACTION_RUNNER_BLOCK_TYPES.has(type) && properties.actionType === ASK_AI) { + emit({ from: ASK_AI, to: '(removed)', path: `${path}.properties.actionType` }); + return true; + } + if (type === 'element:button' && isAskAiAction(properties.action)) { + emit({ from: ASK_AI, to: '(removed)', path: `${path}.properties.action.type` }); + return true; + } + return false; + }); + + return mapPageComponents(next, (component, path) => { + const type = component.type; + const properties = component.properties; + if (typeof type !== 'string' || !ACTION_CONTAINER_BLOCK_TYPES.has(type) || !isDict(properties)) return component; + const members = properties.actions; + if (!Array.isArray(members) || !members.some(isAskAiAction)) return component; + const kept = members.filter((member, i) => { + if (!isAskAiAction(member)) return true; + emit({ from: ASK_AI, to: '(removed)', path: `${path}.properties.actions[${i}].type` }); + return false; + }); + return { ...component, properties: { ...properties, actions: kept } }; + }); + }, + fixture: { + // Only what both paths delete: no `ask_ai` action here is named anywhere, + // so the source run and the at-rest read agree. The named case is pinned + // by `action-type-ask-ai-removed.test.ts`. + before: { + actions: [ + { name: 'ask_about_ticket', label: 'Ask AI', objectName: 'ticket', type: 'ask_ai', locations: ['record_header'] }, + { name: 'close_ticket', label: 'Close', objectName: 'ticket', type: 'script', locations: ['record_header'] }, + ], + objects: [ + { + name: 'ticket', + actions: [ + { name: 'ask_about_ticket_row', label: 'Ask AI', type: 'ask_ai', locations: ['list_item'] }, + { name: 'reopen_ticket', label: 'Reopen', type: 'script' }, + ], + }, + ], + pages: [ + { + name: 'ticket_desk', + regions: [ + { + name: 'main', + components: [ + { type: 'action:button', properties: { label: 'Ask AI', actionType: 'ask_ai' } }, + { type: 'action:button', properties: { label: 'Escalate', actionType: 'flow', target: 'escalate' } }, + { type: 'element:button', properties: { label: 'Ask', action: { type: 'ask_ai', label: 'Ask' } } }, + { + type: 'action:group', + properties: { + actions: [ + { label: 'Ask AI', type: 'ask_ai' }, + { label: 'Run', type: 'api', target: '/api/v1/tickets/run' }, + ], + }, + }, + { + type: 'page:card', + properties: { + title: 'Help', + children: [{ type: 'action:icon', properties: { icon: 'sparkles', actionType: 'ask_ai' } }], + }, + }, + ], + }, + ], + }, + { + name: 'ticket_detail', + kind: 'slotted', + regions: [], + slots: { + header: { type: 'action:icon', properties: { icon: 'sparkles', actionType: 'ask_ai' } }, + details: [{ type: 'action:menu', properties: { actions: [{ label: 'Ask AI', type: 'ask_ai' }] } }], + }, + }, + ], + }, + after: { + actions: [ + { name: 'close_ticket', label: 'Close', objectName: 'ticket', type: 'script', locations: ['record_header'] }, + ], + objects: [ + { + name: 'ticket', + actions: [{ name: 'reopen_ticket', label: 'Reopen', type: 'script' }], + }, + ], + pages: [ + { + name: 'ticket_desk', + regions: [ + { + name: 'main', + components: [ + { type: 'action:button', properties: { label: 'Escalate', actionType: 'flow', target: 'escalate' } }, + { + type: 'action:group', + properties: { actions: [{ label: 'Run', type: 'api', target: '/api/v1/tickets/run' }] }, + }, + { type: 'page:card', properties: { title: 'Help', children: [] } }, + ], + }, + ], + }, + { + name: 'ticket_detail', + kind: 'slotted', + regions: [], + slots: { + details: [{ type: 'action:menu', properties: { actions: [] } }], + }, + }, + ], + }, + // Two declared actions, the button, the element button, the group member, + // the nested icon, the slotted header icon and the slotted menu member. + expectedNotices: 8, + }, +}; + +export { actionTypeAskAiRemoved }; diff --git a/packages/spec/src/conversions/registry.ts b/packages/spec/src/conversions/registry.ts index c402e587509..2941c5818e7 100644 --- a/packages/spec/src/conversions/registry.ts +++ b/packages/spec/src/conversions/registry.ts @@ -138,6 +138,7 @@ import { permissionRlsTagsRemoved } from './entries/18/permission-rls-tags-remov import { flowDecisionModeInclusiveExplicit } from './entries/18/flow-decision-mode-inclusive-explicit.js'; // Major 19: imported after every major-18 conversion, in `MAJOR_19_CONVERSIONS`'s // identifier order. +import { actionTypeAskAiRemoved } from './entries/19/action-type-ask-ai-removed.js'; import { agentModelProviderRemoved } from './entries/19/agent-model-provider-removed.js'; import { permissionViewAllFieldsBesideRecordBypass } from './entries/19/permission-view-all-fields-beside-record-bypass.js'; @@ -315,6 +316,7 @@ const MAJOR_18_CONVERSIONS: readonly OrderedConversion[] = [ * `CONVERSIONS_BY_MAJOR[19]`, which is this list in `order`. */ const MAJOR_19_CONVERSIONS: readonly OrderedConversion[] = [ + { conversion: actionTypeAskAiRemoved, order: 3 }, { conversion: agentModelProviderRemoved, order: 2 }, { conversion: permissionViewAllFieldsBesideRecordBypass, order: 1 }, ]; diff --git a/packages/spec/src/conversions/stored.test.ts b/packages/spec/src/conversions/stored.test.ts index 34bfa73e83c..9b27a332b93 100644 --- a/packages/spec/src/conversions/stored.test.ts +++ b/packages/spec/src/conversions/stored.test.ts @@ -78,7 +78,7 @@ describe('applyConversionsToStoredItem (stored sys_metadata rows)', () => { }, }; const notices: ConversionNotice[] = []; - const out = applyConversionsToStoredItem('object', row, { onNotice: (n) => notices.push(n) }); + const out = applyConversionsToStoredItem('object', row, { onNotice: (n) => notices.push(n) })!; expect(out.fields.amount).toEqual({ type: 'number', precision: 18 }); expect(out.fields.weight).toEqual({ type: 'number', scale: 2 }); // A well-formed count is untouched. diff --git a/packages/spec/src/conversions/stored.ts b/packages/spec/src/conversions/stored.ts index 23c4b77e54d..ced159223cd 100644 --- a/packages/spec/src/conversions/stored.ts +++ b/packages/spec/src/conversions/stored.ts @@ -143,6 +143,11 @@ export type StoredConversionOptions = Omit( type: string, item: T, options: StoredConversionOptions = {}, -): T { +): T | undefined { if (item == null || typeof item !== 'object' || Array.isArray(item)) return item; const singular = PLURAL_TO_SINGULAR[type] ?? type; const collection = SINGULAR_TO_PLURAL[singular] ?? STORED_ONLY_COLLECTIONS[singular]; @@ -169,5 +174,12 @@ export function applyConversionsToStoredItem( }, ); const items = converted[collection]; - return Array.isArray(items) && items.length > 0 ? (items[0] as T) : item; + // ADR-0160 D7, seventh amendment: a conversion may leave NO item of a row — + // a stored `action` row whose type is the retired one IS the action + // the conversion deletes. The seam says so with `undefined`, and its callers + // register and serve nothing for that row; the row itself stays as stored + // until it is deleted by name through the metadata API's delete door. A + // chain that never touched the collection hands it back as it was. + if (!Array.isArray(items)) return item; + return items.length > 0 ? (items[0] as T) : undefined; } diff --git a/packages/spec/src/conversions/types.ts b/packages/spec/src/conversions/types.ts index a277a9112e5..61777814530 100644 --- a/packages/spec/src/conversions/types.ts +++ b/packages/spec/src/conversions/types.ts @@ -150,6 +150,17 @@ export interface ConversionContext { * conversion calls it optionally and leaves the site unchanged either way. */ reportTodo?: (detail: ConversionTodoDetail) => void; + /** + * The pass reads metadata AT REST — a stored row, a stored flow, a built + * artifact — rather than an author's sources. `applyConversions` sets it + * exactly when it replays retired entries (`includeRetired`, which only the + * data-at-rest doors and the fixture CI pass); `os migrate meta`, which runs + * over sources, leaves it unset. A conversion whose rewrite of a source + * depends on what the author can still decide reads it: the retired + * action type (`action-type-ask-ai-removed`, ADR-0160 D7) deletes + * from sources only an action nothing names, and at rest every one. + */ + atRest?: boolean; } /** diff --git a/packages/spec/src/conversions/walk.ts b/packages/spec/src/conversions/walk.ts index 9ee89145e68..e5f77463af2 100644 --- a/packages/spec/src/conversions/walk.ts +++ b/packages/spec/src/conversions/walk.ts @@ -461,6 +461,137 @@ export function mapPageComponents( }); } +/** + * Remove the components of one page list that `shouldRemove` names, and walk + * into each component it keeps. Returns the SAME array reference when nothing + * under it changed (the {@link mapPages} contract). + */ +function removeFromComponentList( + list: unknown[], + basePath: string, + shouldRemove: (component: Dict, path: string) => boolean, + depth: number, +): unknown[] { + let changed = false; + const next: unknown[] = []; + list.forEach((child, i) => { + if (!isDict(child)) { + next.push(child); + return; + } + const path = `${basePath}[${i}]`; + if (shouldRemove(child, path)) { + changed = true; + return; + } + const kept = removeInComponentTree(child, path, shouldRemove, depth); + if (kept !== child) changed = true; + next.push(kept); + }); + return changed ? next : list; +} + +/** {@link removePageComponents} below one kept component, at every slot position. */ +function removeInComponentTree( + component: Dict, + path: string, + shouldRemove: (component: Dict, path: string) => boolean, + depth: number, +): Dict { + if (depth >= MAX_COMPONENT_DEPTH) return component; + const properties = component.properties; + if (!isDict(properties)) return component; + let nextProps = properties; + for (const { key, panelKey } of pageComponentSlotPositions()) { + const list = nextProps[key]; + if (!Array.isArray(list)) continue; + if (panelKey === undefined) { + const next = removeFromComponentList(list, `${path}.properties.${key}`, shouldRemove, depth + 1); + if (next !== list) nextProps = { ...nextProps, [key]: next }; + continue; + } + let panelsChanged = false; + const nextPanels = list.map((panel, i) => { + if (!isDict(panel)) return panel; + const children = panel[panelKey]; + if (!Array.isArray(children)) return panel; + const nextChildren = removeFromComponentList( + children, + `${path}.properties.${key}[${i}].${panelKey}`, + shouldRemove, + depth + 1, + ); + if (nextChildren === children) return panel; + panelsChanged = true; + return { ...panel, [panelKey]: nextChildren }; + }); + if (panelsChanged) nextProps = { ...nextProps, [key]: nextPanels }; + } + return nextProps === properties ? component : { ...component, properties: nextProps }; +} + +/** + * Immutably REMOVE every page component `shouldRemove` names, wherever it + * sits: {@link mapPageComponents}' reach (region components, a slot's one + * component or its list, and every slot position nested under a component, + * retired spellings included), with the same paths and the same copy-on-write + * contract. A component removed takes its sub-tree with it, unvisited. A slot + * that held the removed component alone is dropped from `slots`; a list keeps + * its other members in order. `shouldRemove` is called once per visited + * component, so a caller emits its notice there. + * + * Written for the rows of the retired action type (ADR-0160 D7, `action-type-ask-ai-removed`), where the + * smallest part that leaves the page parseable is the row itself. + */ +export function removePageComponents( + stack: Dict, + shouldRemove: (component: Dict, path: string) => boolean, +): Dict { + return mapPages(stack, (page, pagePath) => { + let nextPage = page; + const regions = page.regions; + if (Array.isArray(regions)) { + let regionsChanged = false; + const nextRegions = regions.map((region, ri) => { + if (!isDict(region)) return region; + const components = region.components; + if (!Array.isArray(components)) return region; + const next = removeFromComponentList(components, `${pagePath}.regions[${ri}].components`, shouldRemove, 0); + if (next === components) return region; + regionsChanged = true; + return { ...region, components: next }; + }); + if (regionsChanged) nextPage = { ...nextPage, regions: nextRegions }; + } + const slots = page.slots; + if (isDict(slots)) { + let slotsChanged = false; + const nextSlots: Dict = { ...slots }; + for (const [slot, value] of Object.entries(slots)) { + const slotPath = `${pagePath}.slots.${slot}`; + if (Array.isArray(value)) { + const next = removeFromComponentList(value, slotPath, shouldRemove, 0); + if (next === value) continue; + nextSlots[slot] = next; + slotsChanged = true; + } else if (isDict(value)) { + if (shouldRemove(value, slotPath)) { + delete nextSlots[slot]; + slotsChanged = true; + continue; + } + const kept = removeInComponentTree(value, slotPath, shouldRemove, 0); + if (kept === value) continue; + nextSlots[slot] = kept; + slotsChanged = true; + } + } + if (slotsChanged) nextPage = { ...nextPage, slots: nextSlots }; + } + return nextPage; + }); +} + /** * Immutably map every datasource in `stack.datasources[]`. * diff --git a/packages/spec/src/data/currency-precision-iso4217.test.ts b/packages/spec/src/data/currency-precision-iso4217.test.ts index 0000aba9b38..f2a8b19041d 100644 --- a/packages/spec/src/data/currency-precision-iso4217.test.ts +++ b/packages/spec/src/data/currency-precision-iso4217.test.ts @@ -187,7 +187,7 @@ describe('the removed `currencyConfig.precision` at rest: a stored row carrying const notices: string[] = []; const converted = applyConversionsToStoredItem('object', storedRow, { onNotice: (n) => notices.push(`${n.conversionId}@${n.path}`), - }); + })!; expect(converted.fields.amount.currencyConfig).toEqual({ currencyMode: 'fixed', defaultCurrency: 'USD' }); // The baked `'CNY'` on the dynamic config goes too, by the later major-18 // entry `currency-config-dynamic-default-currency-removed` (#27157). diff --git a/packages/spec/src/migrations/entries/semantic/19.ui-action-type-ask-ai-retired.ts b/packages/spec/src/migrations/entries/semantic/19.ui-action-type-ask-ai-retired.ts new file mode 100644 index 00000000000..7ceb9232197 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.ui-action-type-ask-ai-retired.ts @@ -0,0 +1,37 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// ADR-0160 D7, seventh amendment — the D3 entry of the `ask_ai` action type's +// retirement. The data half is the D2 conversion `action-type-ask-ai-removed`, +// which deletes what it can prove nothing names; what it leaves is a declared +// `ask_ai` action that something in the stack names, and the references to it, +// which only the author can take out. +export const entry: SemanticMigration = { + id: 'ui-action-type-ask-ai-retired', + surface: 'the `ask_ai` action type, in every slot that takes one: a declared action\'s `type` (top-level or ' + + 'embedded in an object), an `element:button` inline action\'s `type`, `actionType` on an `action:button` / ' + + '`action:icon` row, `type` on an `action:group` / `action:menu` member, and a dashboard header action\'s ' + + '`actionType`', + replacement: + 'none: delete the action and every reference to it — the names in a page header\'s `actions`, a list ' + + 'view\'s `rowActions` / `bulkActions`, a related list\'s `actions`, a quick-actions list, a record alert\'s ' + + '`actionName`, an app navigation entry. The shell\'s 「问 AI」 entry in the page header is the one way into ' + + 'the assistant, and it opens on the record in view by itself', + reason: + 'ADR-0160 D7 as its seventh amendment rules: the maintainer retired `ask_ai` before 19.0.0 with no ' + + 'compatibility shim, because a button per page is a second entry to the assistant and the shell\'s 「问 AI」 ' + + 'entry already carries the record on the page; the accepted cost is that a list row has no ask-AI action ' + + 'of its own. The type was published only on the 19 prerelease line. Every authoring surface now refuses ' + + 'it with a prescription and converts nothing. The D2 conversion `action-type-ask-ai-removed` deletes from ' + + 'sources an `ask_ai` action that nothing in the stack names, and every inline row and container member ' + + 'that spells it; an action that something names is left as written with each reference, so the source ' + + 'still meets the refusal, and taking out the references is the author\'s. Stored rows and built ' + + 'artifacts are read without any `ask_ai` action, with the door\'s conversion notice; a stored `action` ' + + 'row that is one is served and registered as nothing, and is deleted by name through the metadata API', + acceptanceCriteria: + 'No action, row or member in the stack is `ask_ai`; no page, view, app or related list names an action ' + + 'the stack does not define (`os validate` reports no `action-name-undefined` finding); every source ' + + 'parses under the new schema.', + conversionIds: ['action-type-ask-ai-removed'], +}; diff --git a/packages/spec/src/shared/retired-key-removal-version.pin.test.ts b/packages/spec/src/shared/retired-key-removal-version.pin.test.ts index 34d03f50495..e477b1b55f9 100644 --- a/packages/spec/src/shared/retired-key-removal-version.pin.test.ts +++ b/packages/spec/src/shared/retired-key-removal-version.pin.test.ts @@ -80,6 +80,8 @@ import { describe, expect, it } from 'vitest'; import { ALL_CONVERSIONS } from '../conversions/registry'; import { MIGRATIONS_BY_MAJOR } from '../migrations/registry'; import { AIModelConfigSchema } from '../ai/agent.zod'; +import { ActionSchema, ActionType } from '../ui/action.zod'; +import { DashboardHeaderActionSchema } from '../ui/dashboard.zod'; import { TimeUpdateInterval } from '../data/analytics.zod'; import { CurrencyConfigSchema, FieldSchema } from '../data/field.zod'; import { IndexSchema, ObjectSchema } from '../data/object.zod'; @@ -339,6 +341,23 @@ const JOIN: Readonly> = { // #35926: a relationship field's boolean `inlineEdit`, refused by the enum's own error map. // #37712: an agent's `model.provider`, tombstoned on the model block. 'agent-model-provider-removed': [tombstone(AIModelConfigSchema, 'agent.model', 'provider')], + // #37856: the `ask_ai` action type (ADR-0160 D7), refused with one + // prescription in every slot that takes an action type. + 'action-type-ask-ai-removed': [ + refusal("ActionType 'ask_ai'", () => ActionType.safeParse('ask_ai')), + refusal( + "a declared action's type 'ask_ai'", + () => ActionSchema.safeParse({ name: 'ask_about_case', label: 'Ask AI', type: 'ask_ai' }), + 'type', + ), + refusal("an action:button row's actionType 'ask_ai'", () => ActionButtonPropsSchema.safeParse({ label: 'Ask', actionType: 'ask_ai' }), 'actionType'), + refusal("an action:menu member's type 'ask_ai'", () => ActionMenuPropsSchema.safeParse({ actions: [{ label: 'Ask', type: 'ask_ai' }] }), 'actions'), + refusal( + "a dashboard header action's actionType 'ask_ai'", + () => DashboardHeaderActionSchema.safeParse({ label: 'Ask', actionUrl: '#', actionType: 'ask_ai' }), + 'actionType', + ), + ], 'field-inline-edit-boolean-removed': [ refusal( 'field.inlineEdit: true', diff --git a/packages/spec/src/ui/action-ask-ai-retired.test.ts b/packages/spec/src/ui/action-ask-ai-retired.test.ts new file mode 100644 index 00000000000..5dcf6831d07 --- /dev/null +++ b/packages/spec/src/ui/action-ask-ai-retired.test.ts @@ -0,0 +1,96 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0160 D7, seventh amendment — `ask_ai` left `ActionType` before 19.0.0 + * with no compatibility shim. Every slot that takes an action type refuses the + * value with ONE prescription (`action-ask-ai-retired.ts`): a declared action, + * an inline `element:button` action, an `action:button` / `action:icon` row's + * `actionType`, an `action:group` / `action:menu` member's `type`, and a + * dashboard header action's `actionType`. Each pin asserts the refusal lands + * at the slot's own path with the prescription, and a control proves the slot + * still takes a live type. + */ + +import { describe, expect, it } from 'vitest'; +import type { z } from 'zod'; + +import { ASK_AI_RETIRED } from './action-ask-ai-retired'; +import { ActionSchema, ActionType } from './action.zod'; +import { + ActionButtonPropsSchema, + ActionGroupPropsSchema, + ActionIconPropsSchema, + ActionMenuPropsSchema, + ElementButtonPropsSchema, +} from './component.zod'; +import { DashboardHeaderActionSchema, DashboardHeaderSchema } from './dashboard.zod'; + +function refusal(schema: z.ZodTypeAny, input: unknown): { path: string; message: string }[] { + const result = schema.safeParse(input); + expect(result.success, 'the retired value is refused').toBe(false); + if (result.success) return []; + return result.error.issues.map((i) => ({ path: i.path.join('.'), message: i.message })); +} + +describe('ask_ai is retired from every action-type slot (ADR-0160 D7)', () => { + it('the prescription names the release, the ADR, the shell entry and the migration command', () => { + expect(ASK_AI_RETIRED).toContain('@objectstack/spec 19.0.0'); + expect(ASK_AI_RETIRED).toContain('ADR-0160 D7'); + expect(ASK_AI_RETIRED).toContain('「问 AI」'); + expect(ASK_AI_RETIRED).toContain('os migrate meta --from 18'); + }); + + it('ActionType has the six live members and refuses ask_ai with the prescription', () => { + expect(ActionType.options).toEqual(['script', 'url', 'modal', 'flow', 'api', 'form']); + expect(refusal(ActionType, 'ask_ai')).toEqual([{ path: '', message: ASK_AI_RETIRED }]); + }); + + it('a declared action whose type is ask_ai is refused at `type`', () => { + const issues = refusal(ActionSchema, { name: 'ask_about_case', label: 'Ask AI', type: 'ask_ai' }); + expect(issues).toContainEqual({ path: 'type', message: ASK_AI_RETIRED }); + }); + + it('control: a declared script action still parses', () => { + expect(ActionSchema.safeParse({ name: 'close_case', label: 'Close', type: 'script', target: 'close_case' }).success) + .toBe(true); + }); + + it('an element:button inline action of ask_ai is refused at `action.type`', () => { + const issues = refusal(ElementButtonPropsSchema, { label: 'Ask', action: { type: 'ask_ai', label: 'Ask' } }); + expect(issues).toContainEqual({ path: 'action.type', message: ASK_AI_RETIRED }); + }); + + it.each([ + ['action:button', ActionButtonPropsSchema, { label: 'Ask AI', actionType: 'ask_ai' }], + ['action:icon', ActionIconPropsSchema, { icon: 'sparkles', actionType: 'ask_ai' }], + ])('an %s row whose actionType is ask_ai is refused at `actionType`', (_label, schema, row) => { + expect(refusal(schema, row)).toContainEqual({ path: 'actionType', message: ASK_AI_RETIRED }); + }); + + it.each([ + ['action:group', ActionGroupPropsSchema], + ['action:menu', ActionMenuPropsSchema], + ])('an %s member whose type is ask_ai is refused at `actions.N.type`', (_label, schema) => { + const issues = refusal(schema, { + actions: [ + { label: 'Run', type: 'api', target: '/api/v1/tickets/run' }, + { label: 'Ask AI', type: 'ask_ai' }, + ], + }); + expect(issues).toContainEqual({ path: 'actions.1.type', message: ASK_AI_RETIRED }); + }); + + it('control: the rows and members still take a live executor', () => { + expect(ActionButtonPropsSchema.safeParse({ label: 'Escalate', actionType: 'flow', target: 'escalate' }).success) + .toBe(true); + expect(ActionMenuPropsSchema.safeParse({ actions: [{ label: 'Run', type: 'api', target: '/api/v1/run' }] }).success) + .toBe(true); + }); + + it('a dashboard header action whose actionType is ask_ai is refused at `actionType`', () => { + expect(refusal(DashboardHeaderActionSchema, { label: 'Ask AI', actionUrl: '#', actionType: 'ask_ai' })) + .toContainEqual({ path: 'actionType', message: ASK_AI_RETIRED }); + expect(refusal(DashboardHeaderSchema, { actions: [{ label: 'Ask AI', actionUrl: '#', actionType: 'ask_ai' }] })) + .toContainEqual({ path: 'actions.0.actionType', message: ASK_AI_RETIRED }); + }); +}); diff --git a/packages/spec/src/ui/action-ask-ai-retired.ts b/packages/spec/src/ui/action-ask-ai-retired.ts new file mode 100644 index 00000000000..08647838aa9 --- /dev/null +++ b/packages/spec/src/ui/action-ask-ai-retired.ts @@ -0,0 +1,25 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0160 D7, seventh amendment — the one prescription a retired `ask_ai` + * action type is answered with, in every slot that takes an action type: + * + * - `ActionType` itself (`action.zod.ts`), declared with + * `enumWithRetiredValues`, which a dashboard header action's `actionType` + * is (`WidgetActionTypeSchema`, `dashboard.zod.ts`); + * - an action's own `type` key, on a declared action and an inline one + * (`ActionSchema`, `InlineActionSchema`), a second enum over the same + * members with an error of its own; + * - a page action row's open executor string (`component.zod.ts`): + * `actionType` on an `action:button` / `action:icon` row, and `type` on each + * `action:group` / `action:menu` member. + * + * Kept in a module of its own, never re-exported from a barrel, so the two + * schema modules share one sentence without adding a public export. + */ +export const ASK_AI_RETIRED = + '`ask_ai` was removed from `ActionType` in @objectstack/spec 19.0.0 (ADR-0160 D7) — the shell\'s ' + + '「问 AI」 entry (Ask AI) in the page header is the one way into the assistant, and it already carries the ' + + 'record on the page, so an action that opens the assistant would be a second entry. Delete this action ' + + 'and its references; use the shell\'s 「问 AI」 entry. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; diff --git a/packages/spec/src/ui/action-ask-ai.test.ts b/packages/spec/src/ui/action-ask-ai.test.ts deleted file mode 100644 index ea2b3375b8d..00000000000 --- a/packages/spec/src/ui/action-ask-ai.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -// ADR-0160 D7 — `type: 'ask_ai'`: an action on one record that focuses the -// in-app assistant on that record. What this file pins: -// · the member exists and needs no `target`; -// · a `target` beside it is refused at parse, on the registered and the -// inline shape alike; -// · `ai.exposed: true` beside it is refused at parse (`false` is not); -// · the neighbours keep their rules: `script` still needs `body` or -// `target`, the target-bound types still need a `target`. -import { describe, it, expect } from 'vitest'; -import type { z } from 'zod'; -import { ActionSchema, ActionType, InlineActionSchema } from './action.zod'; - -const base = { name: 'ask_about_account', label: 'Ask AI', objectName: 'account', locations: ['record_header'] }; - -function issuePaths(result: { success: boolean; error?: z.ZodError }): string[] { - return result.success ? [] : (result.error as z.ZodError).issues.map((i) => i.path.join('.')); -} - -describe('ActionType — `ask_ai` (ADR-0160 D7)', () => { - it('is a member of the dispatch-route vocabulary', () => { - expect(ActionType.options).toContain('ask_ai'); - }); - - it('parses with no `target`: the action names nothing', () => { - const r = ActionSchema.safeParse({ ...base, type: 'ask_ai' }); - expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); - expect((r as { data: { type: string } }).data.type).toBe('ask_ai'); - }); - - it('parses beside ordinary presentation keys (icon, order, visible, confirmText)', () => { - const r = ActionSchema.safeParse({ - ...base, - type: 'ask_ai', - icon: 'sparkles', - order: 1, - visible: "record.status != 'closed'", - confirmText: 'Open the assistant on this account?', - }); - expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); - }); -}); - -describe('ActionSchema — refusals beside `type: ask_ai`', () => { - it('refuses a `target`, at the `target` path', () => { - const r = ActionSchema.safeParse({ ...base, type: 'ask_ai', target: 'account_overview' }); - expect(r.success).toBe(false); - expect(issuePaths(r as never)).toEqual(['target']); - const issue = (r as { error: z.ZodError }).error.issues[0]; - expect(issue.code).toBe('custom'); - expect(issue.message.split('.')[0]).toBe("A `type: 'ask_ai'` action takes no `target`: it focuses the in-app assistant on the record it runs on, and the material the assistant reads about that record is chosen by the record's context pack, not by the action"); - }); - - it('refuses `ai.exposed: true`, at the `ai.exposed` path', () => { - const r = ActionSchema.safeParse({ - ...base, - type: 'ask_ai', - ai: { exposed: true, description: 'Opens the assistant focused on this account so the user can ask about it.' }, - }); - expect(r.success).toBe(false); - expect(issuePaths(r as never)).toEqual(['ai.exposed']); - expect((r as { error: z.ZodError }).error.issues[0].code).toBe('custom'); - }); - - it('accepts `ai.exposed: false` — nothing is advertised', () => { - const r = ActionSchema.safeParse({ ...base, type: 'ask_ai', ai: { exposed: false } }); - expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); - }); - - it('reports both refusals in one parse', () => { - const r = ActionSchema.safeParse({ - ...base, - type: 'ask_ai', - target: 'x', - ai: { exposed: true, description: 'Opens the assistant focused on this account so the user can ask about it.' }, - }); - expect(issuePaths(r as never).sort()).toEqual(['ai.exposed', 'target']); - }); - - it('refuses a `body`: only `script` runs one', () => { - const r = ActionSchema.safeParse({ ...base, type: 'ask_ai', body: { language: 'js', source: 'return 1;' } }); - expect(r.success).toBe(false); - expect(issuePaths(r as never)).toContain('body'); - }); -}); - -describe('InlineActionSchema — `type: ask_ai`', () => { - it('parses with no `target`', () => { - const r = InlineActionSchema.safeParse({ type: 'ask_ai', label: 'Ask AI' }); - expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); - }); - - it('refuses a `target`, and its legacy spelling `to`', () => { - for (const body of [{ type: 'ask_ai', target: 'x' }, { type: 'ask_ai', to: '/x' }]) { - const r = InlineActionSchema.safeParse(body); - expect(r.success, JSON.stringify(body)).toBe(false); - expect(issuePaths(r as never)).toEqual(['target']); - } - }); -}); - -describe('the neighbours keep their rules', () => { - it('`script` still needs a `body` or a `target`', () => { - const r = ActionSchema.safeParse({ ...base, type: 'script' }); - expect(r.success).toBe(false); - expect(issuePaths(r as never)).toContain('body'); - }); - - it.each(['url', 'modal', 'flow', 'api', 'form'])('`%s` still needs a `target`', (type) => { - const r = ActionSchema.safeParse({ ...base, type }); - expect(r.success).toBe(false); - expect(issuePaths(r as never)).toContain('target'); - }); - - it('a `target` on any other type is not refused by the ask_ai rule', () => { - const r = ActionSchema.safeParse({ ...base, type: 'flow', target: 'lead_reassignment' }); - expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); - }); -}); diff --git a/packages/spec/src/ui/action-row-update.test.ts b/packages/spec/src/ui/action-row-update.test.ts index af94e480cc7..7db484abcce 100644 --- a/packages/spec/src/ui/action-row-update.test.ts +++ b/packages/spec/src/ui/action-row-update.test.ts @@ -161,14 +161,12 @@ describe('`operation: \'update\'` + `patch` is accepted (the bulk def\'s vocabul }); describe('key shape: a parallel key beside `type`, not an `ActionType` member', () => { - it('adds no `update` member to the ActionType vocabulary', () => { + it('leaves the ActionType vocabulary exactly as it was', () => { // objectui types its dispatch table `Record` so a // member added here stops the console compiling until it has an executor — // a coupling the contract-first split must not carry. The write rides the - // existing `script` route instead. (`ask_ai`, ADR-0160 D7, is the one - // member added since, and it landed with its console executor.) - expect([...ActionType.options]).toEqual(['script', 'url', 'modal', 'flow', 'api', 'form', 'ask_ai']); - expect(ActionType.options).not.toContain('update'); + // existing `script` route instead. + expect([...ActionType.options]).toEqual(['script', 'url', 'modal', 'flow', 'api', 'form']); }); it('refuses `type: \'update\'` with the prescription, not zod\'s bare enum list', () => { diff --git a/packages/spec/src/ui/action-undoable-fulfillment.test.ts b/packages/spec/src/ui/action-undoable-fulfillment.test.ts index b80ff740aec..d284c96b9e3 100644 --- a/packages/spec/src/ui/action-undoable-fulfillment.test.ts +++ b/packages/spec/src/ui/action-undoable-fulfillment.test.ts @@ -30,7 +30,6 @@ const shapeByType: Record> = { modal: { type: 'modal', target: 'lead_reassign_modal' }, form: { type: 'form', target: 'lead_reassign_form' }, api: { type: 'api', target: 'lead' }, - ask_ai: { type: 'ask_ai' }, }; /** The two shapes some runtime fulfils — the closed accepted set. */ diff --git a/packages/spec/src/ui/action.zod.ts b/packages/spec/src/ui/action.zod.ts index 25cc2698a9a..af8b97bfc1d 100644 --- a/packages/spec/src/ui/action.zod.ts +++ b/packages/spec/src/ui/action.zod.ts @@ -18,7 +18,8 @@ */ import { z } from 'zod'; -import { retiredKey } from '../shared/retired-key'; +import { enumWithRetiredValues, retiredKey } from '../shared/retired-key'; +import { ASK_AI_RETIRED } from './action-ask-ai-retired'; import { FieldType } from '../data/field.zod'; // #6970 — the authoring gate on `defaultValue` runs the SAME value contract the // dispatcher runs at submit, through the shared `defaultValue` discriminator @@ -691,75 +692,29 @@ export const ActionParamSchema = lazySchema(() => strictObject( * contract-first split (spec now, executor halves downstream) must not carry — * and a member would be a second spelling of the bulk def's `operation`. * - * `ask_ai` (ADR-0160 D7) IS a member, and the coupling above is why it lands - * with its executor: the spec member and the console executor ship in one PR, - * so the console never compiles against a type it cannot run. It is an action - * on one record that focuses the in-app assistant on that record. It names - * nothing — a `target` beside it is refused at parse — and it is never an AI - * tool: `ai.exposed: true` beside it is refused at parse, and no server - * dispatch admits it (the runtime's headless predicate answers `false`), so - * neither `list_actions`/`run_action` nor the `action_` tool family serves it. - * A client draws it only where it draws the assistant's pin control (the - * assistant surface on, and the AI service advertising that it honours a - * conversation focus); elsewhere the action is absent, not disabled. + * `ask_ai` was a member on the 19 prerelease line only and is RETIRED (ADR-0160 + * D7, seventh amendment): the shell's 「问 AI」 entry is the one way into the + * assistant. It is declared with `enumWithRetiredValues`, so writing it is + * answered with the prescription (`action-ask-ai-retired.ts`) rather than with + * zod's list of members; no authoring surface converts it. Stored rows and + * built artifacts are read without the action (the ADR-0087 conversion + * `action-type-ask-ai-removed`), and `os migrate meta --from 18` deletes from + * sources an `ask_ai` action that nothing names. */ -export const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api', 'form', 'ask_ai']); +const ACTION_TYPE_VALUES = ['script', 'url', 'modal', 'flow', 'api', 'form'] as const; +export const ActionType = enumWithRetiredValues(ACTION_TYPE_VALUES, { ask_ai: ASK_AI_RETIRED }); export type ActionType = z.input; -/** - * Action types whose dispatch names nothing, so a `target` is not required: - * `script` (an inline `body` may stand in for it) and `ask_ai` (ADR-0160 D7: - * it focuses the assistant on the record it runs on, and a `target` beside it - * is refused — see {@link refuseAskAiContradictions}). - */ -const TARGETLESS_TYPES: ReadonlySet = new Set(['script', 'ask_ai']); - /** * Action types that require a `target` field. - * Derived from ActionType, excluding the targetless types above. + * Derived from ActionType, excluding 'script' which allows inline handlers. * These types reference an external resource (URL, flow, modal, or API endpoint) * and cannot function without a target binding. */ const TARGET_REQUIRED_TYPES: ReadonlySet = new Set( - ActionType.options.filter((t) => !TARGETLESS_TYPES.has(t)), + ActionType.options.filter((t) => t !== 'script'), ); -/** - * ADR-0160 D7 — the two things an `ask_ai` action may not declare. - * - * - `target`: the action names nothing. The context pack the assistant reads - * is chosen by the pack-selection rule of `get_record_context`, never by the - * action, so a `target` here would be a declaration no runtime reads. - * - `ai.exposed: true` (registered actions only — the inline shape has no - * `ai` key): an `ask_ai` action has no server dispatch, so no agent could - * ever run it; exposing it would advertise a tool that cannot exist. - */ -function refuseAskAiContradictions( - data: { type?: string; target?: unknown; ai?: { exposed?: boolean } | undefined }, - ctx: z.RefinementCtx, -): void { - if (data.type !== 'ask_ai') return; - if (data.target !== undefined) { - ctx.addIssue({ - code: 'custom', - path: ['target'], - message: - "A `type: 'ask_ai'` action takes no `target`: it focuses the in-app assistant on the record it " - + "runs on, and the material the assistant reads about that record is chosen by the record's " - + 'context pack, not by the action. Drop `target`.', - }); - } - if (data.ai?.exposed === true) { - ctx.addIssue({ - code: 'custom', - path: ['ai', 'exposed'], - message: - "A `type: 'ask_ai'` action is never an AI tool: it has no server dispatch (it only opens the " - + 'assistant in the console), so no agent could run it. Drop `ai.exposed`, or set it to `false`.', - }); - } -} - /** * Action Schema * @@ -1449,7 +1404,8 @@ const actionObject = () => strictObject({ + "`operation: 'update'` with a `patch: { … }` of static field values (the list view's " + "`bulkActionDefs` vocabulary, mirrored). Leave `type` at its default `'script'`: that is the " + 'platform action route the write is performed on.' - : undefined), + // ADR-0160 D7: the retired member answers here as it does on `ActionType`. + : issue.input === 'ask_ai' ? ASK_AI_RETIRED : undefined), }).default('script').describe("Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route."), /** @@ -3035,8 +2991,7 @@ export const ActionSchema = lazySchema(() => actionObject().refine((data) => { }, { message: "Action 'target' is required when type is 'url', 'flow', 'modal', 'api', or 'form'.", path: ['target'], -}).superRefine(refuseUnopenableUrlTarget("A `type: 'url'` action's `target`")) - .superRefine(refuseAskAiContradictions).refine((data) => { +}).superRefine(refuseUnopenableUrlTarget("A `type: 'url'` action's `target`")).refine((data) => { // A `script` action must be *executable*: it needs either an inline `body` // (the runtime invokes it in the sandbox) or a `target` naming a registered // bundle function. With neither, AppPlugin registers no engine handler and @@ -3454,7 +3409,7 @@ export const InlineActionSchema = lazySchema(() => z.preprocess( CONFIRM_BESIDE_PARAMS_REFUSAL, ).superRefine(refuseUnopenableUrlTarget( "An inline `type: 'url'` action's `target` (or its legacy spelling `to`)", - )).superRefine(refuseAskAiContradictions), + )), )); /** diff --git a/packages/spec/src/ui/component.zod.ts b/packages/spec/src/ui/component.zod.ts index c95e9ed541b..c022bd9daa8 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, ActionLocationSchema } from './action.zod'; +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'; import { ON_SUCCESS_EXECUTORS, onSuccessBesideExecutorRefusal } from './action-on-success-executor'; @@ -3802,6 +3803,24 @@ function refuseRowUrlExecutorAlias(executorKey: 'actionType' | 'type', subject: }; } +/** + * ADR-0160 D7, seventh amendment — a page action row refuses the retired + * `ask_ai` executor with the one prescription `ActionType` answers it with + * (`action-ask-ai-retired.ts`). The row's executor key is an open string (a + * host registers handlers under other names), so the closed enum never sees + * it: the refusal is spelled here, on `actionType` for an `action:button` / + * `action:icon` row and on `type` for each `action:group` / `action:menu` + * member, beside {@link refuseRowUrlExecutorAlias}. No authoring surface + * converts it; `os migrate meta --from 18` and the stored-row read delete the + * row or the member (the conversion `action-type-ask-ai-removed`). + */ +function refuseRowRetiredAskAi(executorKey: 'actionType' | 'type') { + return (row: { actionType?: string; type?: string }, ctx: z.RefinementCtx): void => { + if (row[executorKey] !== 'ask_ai') return; + ctx.addIssue({ code: 'custom', path: [executorKey], message: ASK_AI_RETIRED }); + }; +} + /** * A page action row's `onSuccess`: `ActionSchema`'s own post-success block, by * reference — the one `strictObject` `{ navigate, openIn }` that @@ -3891,7 +3910,7 @@ const rowPatchRetired = (owner: string) => retiredKey( ); /** - * The console runner's built-in executors: `ActionType`'s members, which its + * The console runner's built-in executors: `ActionType`'s six, the members its * `builtinExecutors` table is typed by (`Record`, so the * table and the enum cannot drift), and its one local alias `navigation` * (read points recorded in `liveness/page.json`, row `regions`). Every other name is a handler a @@ -4142,6 +4161,7 @@ export const ActionButtonPropsSchema = lazySchema(() => strictObject({ }).superRefine(rowDeclarativeUpdate('actionType', "An `action:button`'s")) .superRefine(refuseUnopenableRowUrlTarget('actionType', "An `action:button`'s")) .superRefine(refuseRowUrlExecutorAlias('actionType', "An `action:button`'s `actionType: 'navigation'`")) + .superRefine(refuseRowRetiredAskAi('actionType')) .superRefine(refuseRowOnSuccessBesideExecutor('actionType', "An `action:button`'s")) // #29844 (ruling record 6597621758, letter A): the third door of the // `confirmText` + non-empty `params` refusal, beside `ActionSchema` and @@ -4249,6 +4269,7 @@ export const ActionIconPropsSchema = lazySchema(() => strictObject({ }).superRefine(rowDeclarativeUpdate('actionType', "An `action:icon`'s")) .superRefine(refuseUnopenableRowUrlTarget('actionType', "An `action:icon`'s")) .superRefine(refuseRowUrlExecutorAlias('actionType', "An `action:icon`'s `actionType: 'navigation'`")) + .superRefine(refuseRowRetiredAskAi('actionType')) .superRefine(refuseRowOnSuccessBesideExecutor('actionType', "An `action:icon`'s")) // #30017 (ruling record 6624208841, letter A): the fourth door of the // `confirmText` + non-empty `params` refusal, `action:button`'s predicate and @@ -4492,6 +4513,7 @@ function buildActionGroupMember() { .superRefine(actionContainerMemberParamsFitType('action:group')) .superRefine(refuseUnopenableRowUrlTarget('type', "An `action:group` member's")) .superRefine(refuseRowUrlExecutorAlias('type', "An `action:group` member's `type: 'navigation'`")) + .superRefine(refuseRowRetiredAskAi('type')) .superRefine(refuseRowOnSuccessBesideExecutor('type', "An `action:group` member's")) // #30017 (ruling record 6624208841, letter A): `action:button`'s // `confirmText` + non-empty ARRAY `params` refusal, its predicate and its @@ -4523,6 +4545,7 @@ function buildActionMenuMember() { .superRefine(actionContainerMemberParamsFitType('action:menu')) .superRefine(refuseUnopenableRowUrlTarget('type', "An `action:menu` member's")) .superRefine(refuseRowUrlExecutorAlias('type', "An `action:menu` member's `type: 'navigation'`")) + .superRefine(refuseRowRetiredAskAi('type')) .superRefine(refuseRowOnSuccessBesideExecutor('type', "An `action:menu` member's")) // #30017 (ruling record 6624208841, letter A): `action:button`'s // `confirmText` + non-empty ARRAY `params` refusal, its predicate and its diff --git a/packages/spec/src/ui/dashboard-header-ask-ai-37142.test.ts b/packages/spec/src/ui/dashboard-header-ask-ai-37142.test.ts deleted file mode 100644 index a922457842a..00000000000 --- a/packages/spec/src/ui/dashboard-header-ask-ai-37142.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -// ADR-0160 D7 — a dashboard header runs on no record, so it cannot carry the -// one member of the derived action vocabulary that needs one: `ask_ai`. The -// header refuses it at parse, at the `actionType` path, and keeps every other -// member of `ActionType`. -import { describe, it, expect } from 'vitest'; -import { ActionType } from './action.zod'; -import { DashboardHeaderActionSchema, WidgetActionTypeSchema } from './dashboard.zod'; - -describe('DashboardHeaderActionSchema — `actionType: ask_ai`', () => { - it('is refused at the `actionType` path, naming where an ask_ai action belongs', () => { - const r = DashboardHeaderActionSchema.safeParse({ label: 'Ask AI', actionType: 'ask_ai', actionUrl: 'account' }); - expect(r.success).toBe(false); - const issues = r.error!.issues; - expect(issues.map((i) => i.path.join('.'))).toEqual(['actionType']); - expect(issues[0].code).toBe('custom'); - expect(issues[0].message).toContain("locations: ['record_header']"); - }); - - it('keeps the vocabulary derived: ask_ai is still a member, refused by the header alone', () => { - expect(WidgetActionTypeSchema.options).toEqual(ActionType.options); - }); - - it.each(['script', 'url', 'modal', 'flow', 'api', 'form'])('still accepts `actionType: %s`', (actionType) => { - const r = DashboardHeaderActionSchema.safeParse({ label: 'Go', actionType, actionUrl: actionType === 'url' ? '/target_x' : 'target_x' }); - expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); - }); -}); diff --git a/packages/spec/src/ui/dashboard.zod.ts b/packages/spec/src/ui/dashboard.zod.ts index fcb1f7adf49..434793d1c5f 100644 --- a/packages/spec/src/ui/dashboard.zod.ts +++ b/packages/spec/src/ui/dashboard.zod.ts @@ -65,9 +65,7 @@ export const WidgetColorVariantSchema = lazySchema(() => z.enum([ * * Derived rather than restated: a type added to `ActionType` is dispatchable * from a header action the moment the runner implements it, with no second list - * to remember. The one member a header cannot serve — `ask_ai`, which runs on - * a record (ADR-0160 D7) — stays in the vocabulary and is refused by - * `DashboardHeaderActionSchema` with the reason, not by a narrower enum. + * to remember. */ export const WidgetActionTypeSchema = lazySchema(() => ActionType.describe('Widget action type')); @@ -113,28 +111,6 @@ function refuseUnopenableHeaderActionUrl( if (refusal !== undefined) ctx.addIssue({ code: 'custom', path: ['actionUrl'], message: refusal }); } -/** - * ADR-0160 D7 — `ask_ai` is an action on ONE record: it focuses the in-app - * assistant on the record it runs on. A dashboard header runs on no record, - * so the runner could only refuse the click ("select a row first"), and the - * button would parse clean and never work. Refused here, on the one member of - * the derived vocabulary a header cannot serve; the rest stay derived. - */ -function refuseRecordlessAskAi( - data: { actionType?: string }, - ctx: z.core.$RefinementCtx, -): void { - if (data.actionType !== 'ask_ai') return; - ctx.addIssue({ - code: 'custom', - path: ['actionType'], - message: - "A dashboard header action cannot be `actionType: 'ask_ai'`: that type focuses the in-app assistant on " - + 'the one record an action runs on, and a dashboard header runs on none. Put an `ask_ai` action on the ' - + "object (`locations: ['record_header']` or `['record_more']`), where it runs on the record shown.", - }); -} - /** * Dashboard Header Action Schema * An action button displayed in the dashboard header area. @@ -181,7 +157,7 @@ export const DashboardHeaderActionSchema = lazySchema(() => strictObject({ /** Icon identifier */ icon: z.string().optional().describe('Icon identifier for the action button').meta({ title: 'Icon' }), -}).superRefine(refuseUnopenableHeaderActionUrl).superRefine(refuseRecordlessAskAi).describe('Dashboard header action')); +}).superRefine(refuseUnopenableHeaderActionUrl).describe('Dashboard header action')); /** * Dashboard Header Schema diff --git a/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts b/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts index 8fa0084ac73..f454d317b40 100644 --- a/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts +++ b/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts @@ -186,7 +186,7 @@ describe(`D2 conversion \`${CONVERSION_ID}\``, () => { it("a stored form view row replays clean: 'grid' → 'vertical', `columns` kept, and the row parses", () => { const row = { object: 'crm_lead', form: { type: 'simple', layout: 'grid', columns: 3 } }; expect(ViewSchema.safeParse(row).success).toBe(false); - const replayed = applyConversionsToStoredItem('view', structuredClone(row)); + const replayed = applyConversionsToStoredItem('view', structuredClone(row))!; expect(replayed.form).toEqual({ type: 'simple', layout: 'vertical', columns: 3 }); expect(ViewSchema.safeParse(replayed).success).toBe(true); }); @@ -194,7 +194,7 @@ describe(`D2 conversion \`${CONVERSION_ID}\``, () => { it("a stored flattened form overlay replays clean: 'inline' → 'vertical', and the overlay parses", () => { const row = { object: 'crm_lead', viewKind: 'form', type: 'simple', layout: 'inline' }; expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse(row).success).toBe(false); - const replayed = applyConversionsToStoredItem('view', structuredClone(row)); + const replayed = applyConversionsToStoredItem('view', structuredClone(row))!; expect(replayed.layout).toBe('vertical'); expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse(replayed).success).toBe(true); }); diff --git a/packages/spec/src/ui/inline-action.test.ts b/packages/spec/src/ui/inline-action.test.ts index 976078bdc92..31866b1f179 100644 --- a/packages/spec/src/ui/inline-action.test.ts +++ b/packages/spec/src/ui/inline-action.test.ts @@ -87,8 +87,8 @@ describe('InlineActionSchema is derived from ActionSchema, not restated', () => it('shares ActionType, so a new action type is inline-authorable for free', () => { for (const type of ActionType.options) { - const needsTarget = type !== 'script' && type !== 'ask_ai'; - const body = type === 'ask_ai' ? { type } : needsTarget ? { type, target: '/x' } : { type, target: 'fn_name' }; + const needsTarget = type !== 'script'; + const body = needsTarget ? { type, target: '/x' } : { type, target: 'fn_name' }; expect(InlineActionSchema.safeParse(body).success, `type "${type}" rejected`).toBe(true); } }); diff --git a/scripts/check-skill-identifier-liveness.mjs b/scripts/check-skill-identifier-liveness.mjs index ad5315e1204..9446c817635 100644 --- a/scripts/check-skill-identifier-liveness.mjs +++ b/scripts/check-skill-identifier-liveness.mjs @@ -385,7 +385,9 @@ const BINDINGS = [ id: 'action-types', file: 'skills/objectstack-ui/SKILL.md', heading: '### Action Types', - symbol: 'ActionType', + // [#37856] `ActionType` is an `enumWithRetiredValues` call this gate does + // not read whole; its live members are the `ACTION_TYPE_VALUES` array it wraps. + symbol: 'ACTION_TYPE_VALUES', source: 'packages/spec/src/ui/action.zod.ts', why: 'The complete action-type table. A different skill documents a deliberate 3-of-6 subset of the same enum, which is exactly why the binding names THIS section and not that one.', }, diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 5ffa3642ad8..e578585a9bf 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -2276,6 +2276,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/protocol.stored-ask-ai-retired-row.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.stored-ask-ai-retired-row.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.stored-ask-ai-retired-row.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/protocol.stored-conversions.test.ts", "verb": "delete", diff --git a/ui/packages/app-shell/src/console/ConsoleShell.tsx b/ui/packages/app-shell/src/console/ConsoleShell.tsx index 23de90968e1..58ac3dff1fb 100644 --- a/ui/packages/app-shell/src/console/ConsoleShell.tsx +++ b/ui/packages/app-shell/src/console/ConsoleShell.tsx @@ -119,7 +119,6 @@ function GlobalActionRuntimeProvider({ dataSource, children }: { dataSource: unk onNavigate={runtime.actionProviderProps.onNavigate} onParamCollection={runtime.actionProviderProps.onParamCollection} onResultDialog={runtime.actionProviderProps.onResultDialog} - onAskAi={runtime.actionProviderProps.onAskAi} onModal={modalHandler} handlers={{ api: runtime.apiHandler, diff --git a/ui/packages/app-shell/src/console/__tests__/RequireAiSurface.test.tsx b/ui/packages/app-shell/src/console/__tests__/RequireAiSurface.test.tsx index 8293f3c3b88..9d0e151bc58 100644 --- a/ui/packages/app-shell/src/console/__tests__/RequireAiSurface.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/RequireAiSurface.test.tsx @@ -11,7 +11,7 @@ import { useAiSurfaceEnabled } from '../../hooks/useAiSurface'; // The guard gates purely on the AI-surface signal (the agent catalog); that // hook's own plumbing is covered by useAiSurface.test.ts. vi.mock('../../hooks/useAiSurface', () => ({ - useAiSurfaceEnabled: vi.fn(() => ({ enabled: true, isLoading: false, buildServed: true, focusServed: false })), + useAiSurfaceEnabled: vi.fn(() => ({ enabled: true, isLoading: false, buildServed: true })), })); const mockSurface = vi.mocked(useAiSurfaceEnabled); @@ -90,7 +90,7 @@ function renderGuardedAi(apps?: MetadataContextValue['apps']) { describe('RequireAiSurface', () => { beforeEach(() => { - mockSurface.mockReturnValue({ enabled: true, isLoading: false, buildServed: true, focusServed: false }); + mockSurface.mockReturnValue({ enabled: true, isLoading: false, buildServed: true }); viewer.isAdmin = true; viewer.canAuthorMetadata = true; viewer.aiStudio = true; @@ -106,7 +106,7 @@ describe('RequireAiSurface', () => { it('says in place that no assistant is enabled when no agents are served (objectstack#26614)', () => { // Community Edition. It used to redirect home, which read like a broken // link; now the URL stays and the screen says why, with the way home. - mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false }); renderGuardedAi(); expect(screen.queryByText('AI CHAT')).not.toBeInTheDocument(); expect(screen.queryByText('HOME')).not.toBeInTheDocument(); @@ -120,7 +120,7 @@ describe('RequireAiSurface', () => { }); it('offers Studio\'s new-package flow to a session that may author (objectstack#26614)', () => { - mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false }); renderGuardedAi(); const studio = screen.getByTestId('ai-unavailable-studio'); expect(studio).toHaveTextContent('«home.build.inStudio»'); @@ -133,14 +133,14 @@ describe('RequireAiSurface', () => { ['a runtime that offers no authoring', () => { viewer.aiStudio = false; }], ])('offers no Studio link to %s (objectstack#26614)', (_who, arrange) => { arrange(); - mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false }); renderGuardedAi(); expect(screen.getByTestId('ai-unavailable')).toBeInTheDocument(); expect(screen.queryByTestId('ai-unavailable-studio')).toBeNull(); }); it('waits (neither chat nor the no-assistant screen) while the agent catalog is still resolving', () => { - mockSurface.mockReturnValue({ enabled: false, isLoading: true, buildServed: false, focusServed: false }); + mockSurface.mockReturnValue({ enabled: false, isLoading: true, buildServed: false }); renderGuardedAi(); expect(screen.queryByText('AI CHAT')).not.toBeInTheDocument(); expect(screen.queryByTestId('ai-unavailable')).not.toBeInTheDocument(); @@ -155,7 +155,7 @@ describe('RequireAiSurface', () => { // On a phone, which still has its own Home page (#36732). viewer.phone = true; const user = userEvent.setup(); - mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false }); renderGuardedAi([ { name: 'cloud_control', label: 'Cloud', isDefault: true }, { name: 'account', label: 'Account' }, @@ -171,7 +171,7 @@ describe('RequireAiSurface', () => { // on a desktop is no longer the launcher page but the resolver that lands // in the declared app once it knows. const user = userEvent.setup(); - mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false }); renderGuardedAi([ { name: 'cloud_control', label: 'Cloud', isDefault: true }, { name: 'account', label: 'Account' }, @@ -188,7 +188,7 @@ describe('RequireAiSurface', () => { // once it knows which apps a permission set hides (#36732); a guard mounted // outside a metadata provider resolves there too (every other case here). const user = userEvent.setup(); - mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false }); renderGuardedAi([{ name: 'crm', label: 'CRM' }, { name: 'setup', label: 'Setup' }]); await user.click(screen.getByTestId('ai-unavailable-home')); expect(screen.getByText('HOME')).toBeInTheDocument(); @@ -198,7 +198,7 @@ describe('RequireAiSurface', () => { describe('the no-assistant screen\'s way home names where it goes, by viewport (objectstack#37163)', () => { beforeEach(() => { - mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false }); viewer.phone = false; }); diff --git a/ui/packages/app-shell/src/hooks/__tests__/useAiSurface.test.ts b/ui/packages/app-shell/src/hooks/__tests__/useAiSurface.test.ts index 5293807ed5f..11f9d65e47a 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useAiSurface.test.ts +++ b/ui/packages/app-shell/src/hooks/__tests__/useAiSurface.test.ts @@ -26,7 +26,7 @@ describe('useAiSurfaceEnabled', () => { it('is enabled when the catalog serves at least one agent (cloud / agents present)', () => { mockAgents.mockReturnValue(agentsResult(['ask'], false)); const { result } = renderHook(() => useAiSurfaceEnabled()); - expect(result.current).toEqual({ enabled: true, isLoading: false, buildServed: false, focusServed: false }); + expect(result.current).toEqual({ enabled: true, isLoading: false, buildServed: false }); }); it('reports loading on the first frame before the catalog fetch has started', () => { @@ -34,13 +34,13 @@ describe('useAiSurfaceEnabled', () => { // yet", not "no agents", so the guard must keep waiting (not redirect). mockAgents.mockReturnValue(agentsResult([], false)); const { result } = renderHook(() => useAiSurfaceEnabled()); - expect(result.current).toEqual({ enabled: false, isLoading: true, buildServed: false, focusServed: false }); + expect(result.current).toEqual({ enabled: false, isLoading: true, buildServed: false }); }); it('reports loading while the catalog fetch is in flight', () => { mockAgents.mockReturnValue(agentsResult([], true)); const { result } = renderHook(() => useAiSurfaceEnabled()); - expect(result.current).toEqual({ enabled: false, isLoading: true, buildServed: false, focusServed: false }); + expect(result.current).toEqual({ enabled: false, isLoading: true, buildServed: false }); }); it('is disabled — not loading — once a fetch resolves empty (Community Edition: no agents)', () => { @@ -53,7 +53,7 @@ describe('useAiSurfaceEnabled', () => { mockAgents.mockReturnValue(agentsResult([], false)); rerender(); - expect(result.current).toEqual({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); + expect(result.current).toEqual({ enabled: false, isLoading: false, buildServed: false }); }); }); @@ -71,18 +71,6 @@ describe('useAiSurfaceEnabled — buildServed reads the build agent itself (obje ])('%s in the catalog: building is served', (_served, names) => { mockAgents.mockReturnValue(agentsResult(names, false)); const { result } = renderHook(() => useAiSurfaceEnabled()); - expect(result.current).toEqual({ enabled: true, isLoading: false, buildServed: true, focusServed: false }); - }); -}); - -describe('useAiSurfaceEnabled — focusServed reads `capabilities.focus` (objectstack#37142)', () => { - it('is served only when an agent in the catalog advertises focus', () => { - mockAgents.mockReturnValue({ - ...agentsResult([], false), - agents: [{ name: 'ask', label: 'ask', capabilities: { focus: true } }], - } as never); - expect(renderHook(() => useAiSurfaceEnabled()).result.current.focusServed).toBe(true); - mockAgents.mockReturnValue(agentsResult(['ask'], false)); - expect(renderHook(() => useAiSurfaceEnabled()).result.current.focusServed).toBe(false); + expect(result.current).toEqual({ enabled: true, isLoading: false, buildServed: true }); }); }); diff --git a/ui/packages/app-shell/src/hooks/__tests__/useAskAiHandler-37142.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useAskAiHandler-37142.test.tsx deleted file mode 100644 index 8b4901686fe..00000000000 --- a/ui/packages/app-shell/src/hooks/__tests__/useAskAiHandler-37142.test.tsx +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#37142 (ADR-0160 D7) — `useAskAiHandler`, the console's answer to - * "can an `ask_ai` click be served here?". - * - * Pinned, against a real `ChatDockControlProvider` and the real hook: - * 1. No drawer handle (no layout hosting the assistant, i.e. the AI surface - * off) → no handler, and the agent catalog is not even fetched. - * 2. A drawer, but no catalog agent declaring `capabilities.focus` → no - * handler (the action stays absent). - * 3. A drawer and a focus-honouring agent → a handler that opens the drawer - * on a fresh thread OF that agent, so the drawer's pin control (which - * asks the active agent) is drawn, then pins the record through - * `setChatFocus` as a `follow` hand-off; it sends nothing. An `ask` agent - * is preferred among several that honour it. - * - * What the hand-off does to a drawer already open on another conversation is - * pinned against the real host in `layout/__tests__/chatFocus-36999.test.tsx` - * (the objectstack#37142 block). - */ - -import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest'; -import { renderHook } from '@testing-library/react'; -import React from 'react'; - -const harness = vi.hoisted(() => ({ - agents: [] as Array<{ name: string; capabilities?: Record }>, - agentsCalls: [] as Array<{ enabled?: boolean }>, - setChatFocus: vi.fn(), -})); - -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal>()), - useAgents: (options: { enabled?: boolean }) => { - harness.agentsCalls.push(options); - return { agents: options.enabled === false ? [] : harness.agents, isLoading: false, refetch: () => {} }; - }, -})); - -vi.mock('../../layout/chatFocus.js', async (importOriginal) => ({ - ...(await importOriginal>()), - setChatFocus: harness.setChatFocus, -})); - -import { ChatDockControlProvider, type ChatDockControl } from '../../layout/chatDockControl.js'; -import { useAskAiHandler } from '../useAskAiHandler.js'; - -function dock(): ChatDockControl & { open: Mock } { - return { expanded: false, fullWindow: false, toggle: vi.fn(), open: vi.fn() }; -} - -function renderWith(control: ChatDockControl | null) { - const wrapper = ({ children }: { children: React.ReactNode }) => ( - {children} - ); - return renderHook(() => useAskAiHandler(), { wrapper }); -} - -const FOCUS_AGENT = { name: 'ask', capabilities: { focus: true } }; -const PLAIN_AGENT = { name: 'ask', capabilities: { focus: false } }; - -beforeEach(() => { - harness.agents = []; - harness.agentsCalls = []; - harness.setChatFocus.mockReset(); -}); - -describe('useAskAiHandler (ADR-0160 D7)', () => { - it('answers nothing without a drawer, and fetches no catalog', () => { - harness.agents = [FOCUS_AGENT]; - const { result } = renderWith(null); - expect(result.current).toBeUndefined(); - expect(harness.agentsCalls.every((call) => call.enabled === false)).toBe(true); - }); - - it('answers nothing when no served agent honours a focus', () => { - harness.agents = [PLAIN_AGENT, { name: 'build' }]; - const { result } = renderWith(dock()); - expect(result.current).toBeUndefined(); - }); - - it('pins the record and opens the drawer where both hold', () => { - harness.agents = [PLAIN_AGENT, { ...FOCUS_AGENT, name: 'custom' }]; - const control = dock(); - const { result } = renderWith(control); - expect(result.current).toBeTypeOf('function'); - - result.current!({ object: 'account', id: 'acc_1' }); - - expect(harness.setChatFocus).toHaveBeenCalledTimes(1); - expect(harness.setChatFocus).toHaveBeenCalledWith({ object: 'account', id: 'acc_1' }, { follow: true }); - expect(control.open).toHaveBeenCalledTimes(1); - // On a fresh thread of the agent that honours the focus, and with no - // hand-off message: the `ask` agent here does not declare it, so `custom`. - expect(control.open).toHaveBeenCalledWith({ agent: 'custom', fresh: true }); - // The chat moves first; the pin follows it. - expect(control.open.mock.invocationCallOrder[0]).toBeLessThan( - harness.setChatFocus.mock.invocationCallOrder[0], - ); - expect(control.toggle).not.toHaveBeenCalled(); - }); - - it('prefers an `ask` agent among several that honour a focus', () => { - harness.agents = [{ ...FOCUS_AGENT, name: 'custom' }, FOCUS_AGENT]; - const control = dock(); - const { result } = renderWith(control); - result.current!({ object: 'account', id: 'acc_1' }); - expect(control.open).toHaveBeenCalledWith({ agent: 'ask', fresh: true }); - }); -}); diff --git a/ui/packages/app-shell/src/hooks/aiApiBase.ts b/ui/packages/app-shell/src/hooks/aiApiBase.ts deleted file mode 100644 index b6b55f072cf..00000000000 --- a/ui/packages/app-shell/src/hooks/aiApiBase.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * The AI service base URL, in a module of its own so a hook that only needs - * the URL (`useAskAiHandler`, objectstack#37142) does not import the surface - * hook's module, which many layout tests replace with a mock. - */ - -/** - * Resolve the AI service base URL, mirroring AiChatPage / the Home CTAs: - * an explicit `VITE_AI_BASE_URL` wins, otherwise `${VITE_SERVER_URL}/api/v1/ai`. - * Shared so every catalog fetch (route guard, layouts, Home) hits the same URL. - */ -export function resolveAiApiBase(): string { - const env = (import.meta as any).env ?? {}; - const fromEnv = env.VITE_AI_BASE_URL as string | undefined; - if (fromEnv) return fromEnv.replace(/\/$/, ''); - const serverUrl = (env.VITE_SERVER_URL as string | undefined) ?? ''; - return `${serverUrl.replace(/\/$/, '')}/api/v1/ai`; -} diff --git a/ui/packages/app-shell/src/hooks/surfaceAgent.ts b/ui/packages/app-shell/src/hooks/surfaceAgent.ts index 0ee033ac848..f786b80c041 100644 --- a/ui/packages/app-shell/src/hooks/surfaceAgent.ts +++ b/ui/packages/app-shell/src/hooks/surfaceAgent.ts @@ -91,28 +91,6 @@ export function catalogServesBuild(agents: readonly AgentDescriptor[]): boolean return resolveAgentParam('build', agents.map((a) => a.name)) !== undefined; } -/** - * objectstack#37142 — does the live catalog serve an agent that declares it - * honours a conversation focus (`capabilities.focus`, objectstack#36999)? The - * second half of the gate ADR-0160 D7 puts on the `ask_ai` action (the first - * is the AI surface itself). An undeclared capability is off. - */ -export function catalogServesFocus(agents: readonly AgentDescriptor[]): boolean { - return focusAgentName(agents) !== undefined; -} - -/** - * objectstack#37142 — the agent an `ask_ai` click opens the drawer on: one - * that declares `capabilities.focus`, so the drawer's pin control (drawn only - * when the ACTIVE agent honours the focus) is drawn on the record the click - * pinned. An `ask` agent is preferred among them; `undefined` when none - * declares it, which leaves the action absent. - */ -export function focusAgentName(agents: readonly AgentDescriptor[]): string | undefined { - const honouring = agents.filter((agent) => agent.capabilities?.focus === true); - return (honouring.find((agent) => isAskAgent(agent.name)) ?? honouring[0])?.name; -} - /** * cloud#1674 — is this session on the CONVERGED maker surface? True when the * principal may author, the deployment offers authoring, and the catalog diff --git a/ui/packages/app-shell/src/hooks/useAiSurface.ts b/ui/packages/app-shell/src/hooks/useAiSurface.ts index 539f4bf3548..1d4591c0810 100644 --- a/ui/packages/app-shell/src/hooks/useAiSurface.ts +++ b/ui/packages/app-shell/src/hooks/useAiSurface.ts @@ -42,11 +42,20 @@ import { useRef } from 'react'; import { useAgents } from '@object-ui/plugin-chatbot/core'; -import { catalogServesBuild, catalogServesFocus } from './surfaceAgent.js'; -import { resolveAiApiBase } from './aiApiBase.js'; +import { catalogServesBuild } from './surfaceAgent.js'; -// Re-exported where its callers have always imported it from. -export { resolveAiApiBase }; +/** + * Resolve the AI service base URL, mirroring AiChatPage / the Home CTAs: + * an explicit `VITE_AI_BASE_URL` wins, otherwise `${VITE_SERVER_URL}/api/v1/ai`. + * Shared so every catalog fetch (route guard, layouts, Home) hits the same URL. + */ +export function resolveAiApiBase(): string { + const env = (import.meta as any).env ?? {}; + const fromEnv = env.VITE_AI_BASE_URL as string | undefined; + if (fromEnv) return fromEnv.replace(/\/$/, ''); + const serverUrl = (env.VITE_SERVER_URL as string | undefined) ?? ''; + return `${serverUrl.replace(/\/$/, '')}/api/v1/ai`; +} export interface AiSurfaceState { /** True when the AI UI should render — the CALLER can reach >= 1 agent (access-filtered). */ @@ -60,14 +69,6 @@ export interface AiSurfaceState { * (`build` persisted inactive, `ask` still served). */ buildServed: boolean; - /** - * objectstack#37142 — true when the same catalog serves an agent that - * declares it honours a conversation focus (`capabilities.focus`, - * objectstack#36999). With `enabled`, the gate ADR-0160 D7 puts on the - * `ask_ai` action: it is drawn where the pin control can be. False while - * loading and on a server that declares no capabilities. - */ - focusServed: boolean; } /** @@ -89,7 +90,6 @@ export function useAiSurfaceEnabled(): AiSurfaceState { return { enabled, buildServed: catalogServesBuild(agents), - focusServed: catalogServesFocus(agents), // Agents present → resolved/available. Otherwise we're loading until a fetch // has both started and finished with an empty result. isLoading: enabled ? false : isLoading || !fetchStartedRef.current, diff --git a/ui/packages/app-shell/src/hooks/useAskAiHandler.ts b/ui/packages/app-shell/src/hooks/useAskAiHandler.ts deleted file mode 100644 index 6e4d4e07463..00000000000 --- a/ui/packages/app-shell/src/hooks/useAskAiHandler.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#37142 — the console's in-app assistant, as a `type: 'ask_ai'` - * action reaches it (ADR-0160 D7). - * - * The answer is a handler for ``, or `undefined` where - * the console cannot serve the click — and `undefined` is what makes every - * `ask_ai` action under that provider absent rather than disabled. It is - * defined exactly where the assistant's pin control is drawn: - * - * - the assistant surface is on: a layout that hosts the drawer hands its - * handle (`useChatDockControl`) only while `useAiSurfaceEnabled` answers - * `enabled`, so the handle's presence IS that gate, read without a second - * catalog fetch where there is no drawer; - * - the AI service advertises that it honours a focus (`capabilities.focus` - * on a catalog row, objectstack#36999). - * - * The handler does what the pin control does, on a conversation of its own: - * it opens the drawer on a FRESH thread of an agent that declares the - * capability ({@link focusAgentName}), so the drawer's own pin control, which - * asks the ACTIVE agent, is drawn, and pins the record to that thread through - * the one setter (`setChatFocus`). The pin is a `follow` hand-off: a drawer - * already open on another conversation keeps that conversation's focus, and - * the fresh thread it moves to takes the record (its first send carries it - * onto the id that send mints). A drawer that is closed has no chat host yet; - * the setter holds the focus for the host that opening it mounts. It sends no - * message and makes no server call; an unsent fresh thread creates nothing. - */ - -import { useMemo } from 'react'; -import { useAgents } from '@object-ui/plugin-chatbot/core'; -import type { AssistantFocusHandler } from '@object-ui/core'; -import { useChatDockControl } from '../layout/chatDockControl.js'; -import { setChatFocus } from '../layout/chatFocus.js'; -import { resolveAiApiBase } from './aiApiBase.js'; -import { focusAgentName } from './surfaceAgent.js'; - -export function useAskAiHandler(): AssistantFocusHandler | undefined { - const dock = useChatDockControl(); - // No drawer, no fetch: the catalog is read only where the surface is on. - const { agents } = useAgents({ apiBase: resolveAiApiBase(), enabled: dock !== null }); - const agent = focusAgentName(agents); - const open = dock?.open; - return useMemo( - () => - open && agent - ? (focus) => { - open({ agent, fresh: true }); - setChatFocus({ object: focus.object, id: focus.id }, { follow: true }); - } - : undefined, - [open, agent], - ); -} diff --git a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx index 6e1a02cf701..ab73465d18c 100644 --- a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx +++ b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx @@ -54,7 +54,6 @@ import { entitlementDialogFromError, type EntitlementDialogSpec } from '../envir import { resolvePageVarTokens } from '../utils/resolvePageVarTokens.js'; import { launchConsoleFlow } from '../utils/flowLaunch.js'; import { useScreenFlowQueue } from './useScreenFlowQueue.js'; -import { useAskAiHandler } from './useAskAiHandler.js'; import type { TranslateFn } from '@object-ui/i18n'; import { apiActionRefusalResult } from '../utils/flowResponse.js'; import { invitationVerifyEmailPromptPath, isAcceptNeedsVerifiedEmail } from '../console/organizations/orgErrorMessage.js'; @@ -156,11 +155,7 @@ export interface ConsoleActionRuntime { | 'onResultDialog' | 'handlers' > - > & - // objectstack#37142 — present only where the console can serve an - // `ask_ai` click (see `useAskAiHandler`); its absence is what keeps every - // `ask_ai` action under the provider undrawn. - Pick; + >; /** Confirm / param / result / paused-flow / flow-refusal dialogs — render inside the provider. */ dialogs: React.ReactNode; } @@ -959,9 +954,6 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons }; }, [resolveModalTarget, modalHandler]); - // ADR-0160 D7 — the assistant an `ask_ai` action hands its record to. - const askAiHandler = useAskAiHandler(); - const actionProviderProps = useMemo(() => ({ context: { ...(objectName ? { objectName } : {}), @@ -993,11 +985,10 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons onResultDialog: resultDialogHandler, onModal: modalHandler, handlers: { api: apiActionHandler, flow: flowHandler, script: serverActionHandler, modal: modalActionHandler }, - ...(askAiHandler ? { onAskAi: askAiHandler } : {}), }), [ objectName, objectDef, currentUser, activeOrganization, confirmHandler, toastHandler, navigateHandler, paramCollectionHandler, resultDialogHandler, apiActionHandler, - flowHandler, serverActionHandler, modalHandler, modalActionHandler, askAiHandler, + flowHandler, serverActionHandler, modalHandler, modalActionHandler, ]); // The run FlowRunner shows; its close and completion settle that run alone. diff --git a/ui/packages/app-shell/src/index.ts b/ui/packages/app-shell/src/index.ts index 0fc1b501719..51f24048fca 100644 --- a/ui/packages/app-shell/src/index.ts +++ b/ui/packages/app-shell/src/index.ts @@ -411,9 +411,8 @@ export { type ChatDockControl, } from './layout/chatDockControl.js'; export type { ChatDockTarget } from './layout/chatDockTarget.js'; -// objectstack#36999 — the one setter every entry point pins a record through -// (the page chip's pin, the record drawer, the `ask_ai` action); chat-free. -export { setChatFocus, type ChatFocus } from './layout/chatFocus.js'; +// objectstack#36999 — the record a conversation is pinned to; chat-free. +export type { ChatFocus } from './layout/chatFocus.js'; // Conversation-history hydration helpers — reused by the public read-only // share page (`/s/:token`) so a shared transcript renders identically to the // live chat (tool cards included) instead of dumping raw envelopes. diff --git a/ui/packages/app-shell/src/layout/ChatDockConversation.tsx b/ui/packages/app-shell/src/layout/ChatDockConversation.tsx index e1e6cb726db..19052f6578d 100644 --- a/ui/packages/app-shell/src/layout/ChatDockConversation.tsx +++ b/ui/packages/app-shell/src/layout/ChatDockConversation.tsx @@ -218,11 +218,7 @@ export function ChatDockConversation({ // held here for the same reason. It rides on the thread the scope resolved // and never re-keys it: a focus does not change which conversation the // drawer shows (ADR-0057 as amended for objectui#10926). - // objectstack#37142 — keyed on the target too: a hand-off's carry goes to the - // thread this target resolves, never to a history row or another app's - // thread the user moves to before the first send. - const focusTarget = React.useMemo(() => (target ? JSON.stringify(target) : undefined), [target]); - const conversationFocus = useConversationFocus(paneConversationId, createError, focusTarget); + const conversationFocus = useConversationFocus(paneConversationId, createError); // A first send creates the conversation: the id it mints takes the focus // pinned before it (and no other arriving id does). const { markSending: markFocusSending } = conversationFocus; diff --git a/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx b/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx index dccaff45936..ca049a8ab3d 100644 --- a/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx @@ -11,7 +11,7 @@ * The console dock body (`ChatDockConversation`) and the full-page chat * (`AiChatPage` at `/ai/ask`), each with the REAL `ChatPane`, the REAL * `useChatConversation`, the REAL `useObjectChat` transport, the REAL focus - * state (`useConversationFocus`, `setChatFocus`) and the REAL composer row + * state (`useConversationFocus`) and the REAL composer row * (`ChatFocusRow`). What is pinned is the JSON body of each POST to the * agent's chat route (captured off a `fetch` stub) and the row the pane hands * the composer. The stand-ins: the agent catalog, the model allowlist, and @@ -91,15 +91,10 @@ import { ChatDockConversation } from '../ChatDockConversation'; import { buildFocusContext, readStoredChatFocus, - resetChatFocusForTests, - setChatFocus, type ChatFocus, } from '../chatFocus'; import type { ChatSurfaceContext } from '../chatSurfaceContext'; import type { ChatDockTarget } from '../chatDockTarget'; -import { ChatDockControlProvider, type ChatDockControl } from '../chatDockControl'; -import { useAskAiHandler } from '../../hooks/useAskAiHandler'; -import type { AssistantFocusHandler } from '@object-ui/core'; window.matchMedia = ((query: string) => ({ matches: false, @@ -187,10 +182,10 @@ function mountDock(initial: ChatSurfaceContext | undefined = record('rec_1')): v ); } -function mountPage(): void { +function mountPage(path = '/ai/ask'): void { render( - + } /> } /> @@ -229,7 +224,6 @@ beforeEach(() => { state.failCreate = false; window.localStorage.clear(); window.sessionStorage.clear(); - resetChatFocusForTests(); installFetch(); }); @@ -247,16 +241,6 @@ describe('buildFocusContext — the one shape both chat hosts send (objectstack# }); }); -describe('setChatFocus — the setter every entry point calls (objectstack#36999)', () => { - it('with no chat mounted it waits, and the chat that mounts next takes it', async () => { - setChatFocus(ACCOUNT_1); - mountDock(undefined); - await composerReady(); - await waitFor(() => expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('Asking about: account · rec_1')); - expect((await send('first')).focus).toEqual([ACCOUNT_1]); - }); -}); - describe('the console dock — conversation focus (objectstack#36999)', () => { it('the pin on the page chip pins the record; every turn carries it, the first included, across navigation', async () => { mountDock(); @@ -378,28 +362,6 @@ describe('the console dock — conversation focus (objectstack#36999)', () => { expect(readStoredChatFocus('conv-old').focus).toEqual({ object: 'account', id: 'rec_9' }); }); - it('a chip pin after a setter hand-off is the conversation\'s own: it does not follow the user into an existing one', async () => { - window.sessionStorage.setItem( - 'ai-chat-focus:conv-old', - JSON.stringify({ focus: { object: 'account', id: 'rec_9' }, declined: false }), - ); - mountDock(record('rec_2')); - await composerReady(); - // The setter lands on the fresh conversation (no id yet), then the user - // moves the focus through the chip to the record in view. - act(() => setChatFocus(ACCOUNT_1)); - expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('account · rec_1'); - fireEvent.click(screen.getByTestId('chat-focus-switch-accept')); - expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('account · rec_2'); - - page.open({ agent: 'ask', conversationId: 'conv-old' }); - await waitFor(() => expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('account · rec_9')); - await composerReady(); - expect((await send('and now?')).focus).toEqual([{ object: 'account', id: 'rec_9' }]); - expect(readStoredChatFocus('conv-old').focus).toEqual({ object: 'account', id: 'rec_9' }); - expect(state.minted).toBe(0); - }); - it('a page that shows no one record offers no pin', async () => { mountDock({ artifact: { type: 'object', name: 'account' } }); await composerReady(); @@ -409,14 +371,14 @@ describe('the console dock — conversation focus (objectstack#36999)', () => { }); describe('the full-page chat — conversation focus behaves as in the dock (objectstack#36999)', () => { - it('a focus pinned through the setter rides the first turn and the next; removing it stops it', async () => { - mountPage(); + it('a conversation pinned in the dock rides every turn on the full page; removing it stops it', async () => { + window.sessionStorage.setItem('ai-chat-focus:conv-old', JSON.stringify({ focus: ACCOUNT_1, declined: false })); + mountPage('/ai/ask/conv-old'); await composerReady(); - act(() => setChatFocus(ACCOUNT_1)); - expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('account · rec_1'); + await waitFor(() => expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('account · rec_1')); expect((await send('first')).focus).toEqual([ACCOUNT_1]); - expect(state.minted).toBe(1); + expect(state.minted).toBe(0); expect((await send('second')).focus).toEqual([ACCOUNT_1]); fireEvent.click(screen.getByTestId('chat-focus-remove')); @@ -425,14 +387,14 @@ describe('the full-page chat — conversation focus behaves as in the dock (obje }); describe.each([ - ['the console dock', () => mountDock()], - ['the full-page chat', mountPage], + ['the console dock', () => { mountDock(); page.open({ agent: 'ask', conversationId: 'conv-old' }); }], + ['the full-page chat', () => mountPage('/ai/ask/conv-old')], ])('%s — an agent that does not declare `capabilities.focus` (objectstack#36999)', (_surface, mount) => { - it('draws no pin and no chip, and sends no `focus` key even after a pin request', async () => { + it('draws no pin and no chip, and sends no `focus` key even for a conversation with a stored focus', async () => { state.agents = [{ name: 'ask', label: 'Ask', capabilities: { ...CAPS } }]; + window.sessionStorage.setItem('ai-chat-focus:conv-old', JSON.stringify({ focus: ACCOUNT_1, declined: false })); mount(); await composerReady(); - act(() => setChatFocus(ACCOUNT_1)); expect(screen.queryByTestId('chat-focus-row')).toBeNull(); expect(screen.queryByTestId('chat-focus-pin')).toBeNull(); @@ -450,136 +412,3 @@ describe('the console dock — no flag leaves the page chip where it was (object expect(screen.queryByTestId('chat-focus-row')).toBeNull(); }); }); - -/** - * objectstack#37142 (ADR-0160 D7) — the `ask_ai` action's console handler - * (`useAskAiHandler`) against the REAL dock body and the REAL focus host: the - * drawer's handle moves its target the way `useConsoleChatDock`'s `open` does. - * The click opens a fresh thread and pins the record to IT; a conversation the - * drawer showed before keeps its own focus. - */ -const ask: { run?: AssistantFocusHandler } = {}; -function AskAiProbe() { - const handler = useAskAiHandler(); - React.useEffect(() => { - ask.run = handler; - }, [handler]); - return null; -} -function AssistantDock({ initial }: { initial?: ChatSurfaceContext }) { - const [target, setTarget] = React.useState(undefined); - page.open = (next) => act(() => setTarget(next)); - const control = React.useMemo( - () => ({ - expanded: true, - fullWindow: false, - toggle: () => {}, - open: (next) => { - if (next === null) setTarget(undefined); - else if (next !== undefined) setTarget(next); - }, - }), - [], - ); - return ( - - - - - ); -} -function mountAssistantDock(initial: ChatSurfaceContext): void { - render( - - - - - , - ); -} - -describe('the `ask_ai` action — the pin follows the fresh thread it opens (objectstack#37142)', () => { - beforeEach(() => { - ask.run = undefined; - }); - - it('a drawer open on another conversation keeps that one\'s focus; the fresh thread takes the record', async () => { - const REC_9: ChatFocus = { object: 'account', id: 'rec_9' }; - window.sessionStorage.setItem('ai-chat-focus:conv-old', JSON.stringify({ focus: REC_9, declined: false })); - mountAssistantDock(record('rec_2')); - await composerReady(); - page.open({ agent: 'ask', conversationId: 'conv-old' }); - await waitFor(() => expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('account · rec_9')); - await waitFor(() => expect(ask.run).toBeTypeOf('function')); - - act(() => ask.run!(ACCOUNT_1)); - - await waitFor(() => expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('account · rec_1')); - // The conversation left behind is not pinned to the record. - expect(readStoredChatFocus('conv-old').focus).toEqual(REC_9); - await composerReady(); - // The fresh thread's first send carries the record and mints the thread it pins. - expect((await send('what about it?')).focus).toEqual([ACCOUNT_1]); - expect(state.minted).toBe(1); - expect(readStoredChatFocus('conv-1').focus).toEqual(ACCOUNT_1); - expect(readStoredChatFocus('conv-old').focus).toEqual(REC_9); - }); - - it('a drawer on an unsent thread takes the record at once, and its first send carries it', async () => { - mountAssistantDock(record('rec_2')); - await composerReady(); - await waitFor(() => expect(ask.run).toBeTypeOf('function')); - - act(() => ask.run!(ACCOUNT_1)); - - await waitFor(() => expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('account · rec_1')); - await composerReady(); - expect((await send('first')).focus).toEqual([ACCOUNT_1]); - expect(readStoredChatFocus('conv-1').focus).toEqual(ACCOUNT_1); - }); - - it('a history conversation picked before the first send keeps its own focus', async () => { - const REC_9: ChatFocus = { object: 'account', id: 'rec_9' }; - window.sessionStorage.setItem('ai-chat-focus:conv-old', JSON.stringify({ focus: REC_9, declined: false })); - mountAssistantDock(record('rec_2')); - await composerReady(); - await waitFor(() => expect(ask.run).toBeTypeOf('function')); - act(() => ask.run!(ACCOUNT_1)); - await waitFor(() => expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('account · rec_1')); - - // No send: the user opens a conversation from the history instead. - page.open({ agent: 'ask', conversationId: 'conv-old' }); - await waitFor(() => expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('account · rec_9')); - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); - expect(readStoredChatFocus('conv-old').focus).toEqual(REC_9); - await composerReady(); - expect((await send('and this one?')).focus).toEqual([REC_9]); - expect(state.minted).toBe(0); - }); - - it('a history conversation with no focus of its own is not pinned to the record', async () => { - mountAssistantDock(record('rec_2')); - await composerReady(); - await waitFor(() => expect(ask.run).toBeTypeOf('function')); - act(() => ask.run!(ACCOUNT_1)); - await waitFor(() => expect(screen.getByTestId('chat-focus-chip')).toHaveTextContent('account · rec_1')); - - page.open({ agent: 'ask', conversationId: 'conv-bare' }); - await waitFor(() => expect(screen.queryByTestId('chat-focus-chip')).toBeNull()); - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); - expect(readStoredChatFocus('conv-bare').focus).toBeNull(); - await composerReady(); - expect(await send('anything?')).not.toHaveProperty('focus'); - }); -}); diff --git a/ui/packages/app-shell/src/layout/chatFocus.ts b/ui/packages/app-shell/src/layout/chatFocus.ts index f9555fb5f8c..4fddee2246d 100644 --- a/ui/packages/app-shell/src/layout/chatFocus.ts +++ b/ui/packages/app-shell/src/layout/chatFocus.ts @@ -20,9 +20,9 @@ * the conversation id, so the first send — which mints that id and remounts * the pane — still carries it. * - * Kept free of chat code: `setChatFocus` is exported from the package root, so - * the record drawer and the `ask_ai` action can call it from the eager console - * graph (objectui#13410). + * The focus is set from the chip in the composer only. The external setter + * the retired ask-AI action type pinned through left with that type + * (ADR-0160 D7, seventh amendment). */ import * as React from 'react'; @@ -92,64 +92,6 @@ export function buildFocusContext( return honoured && focus ? { focus: [{ object: focus.object, id: focus.id }] } : {}; } -// ── The one setter ───────────────────────────────────────────────────────── -// Every entry point pins through `setChatFocus`: the pin on the page chip, the -// record drawer and the `ask_ai` action. It applies to the chat host on -// screen; with none mounted (the drawer is closed) it waits, and the next host -// to mount takes it, so "pin, then open the drawer" lands on the drawer's -// conversation. -// -// objectstack#37142 — a caller that MOVES the chat in the same event (the -// `ask_ai` action opens a fresh thread) says so with `follow`: the focus is the -// next conversation's, so a host that shows one now leaves it untouched and -// hands the focus to the conversation it moves to. - -/** How `setChatFocus` lands. */ -export interface SetChatFocusOptions { - /** - * The caller is moving the chat to another conversation in this same event: - * the focus belongs to that one, not to the conversation on screen. A host - * with no conversation id yet takes it at once; a host showing one keeps - * that conversation's focus and gives this one to the next it shows. - */ - follow?: boolean; -} - -type ChatFocusHost = (focus: ChatFocus | null, follow: boolean) => void; -const hosts: ChatFocusHost[] = []; -let pending: { focus: ChatFocus | null; follow: boolean } | null = null; - -/** - * Pins `focus` to the conversation the chat shows (or clears it with `null`). - * A new focus starts with a fresh 「ask about this one instead?」 offer. - */ -export function setChatFocus(focus: ChatFocus | null, options?: SetChatFocusOptions): void { - const next = focus && isChatFocus(focus) ? { object: focus.object, id: focus.id } : null; - const follow = options?.follow === true; - const host = hosts[hosts.length - 1]; - if (host) host(next, follow); - else pending = { focus: next, follow }; -} - -function registerChatFocusHost(host: ChatFocusHost): () => void { - hosts.push(host); - if (pending) { - const { focus, follow } = pending; - pending = null; - host(focus, follow); - } - return () => { - const at = hosts.lastIndexOf(host); - if (at >= 0) hosts.splice(at, 1); - }; -} - -/** Test seam: forget every host and a waiting request. */ -export function resetChatFocusForTests(): void { - hosts.length = 0; - pending = null; -} - /** What a chat host hands its pane. */ export interface ConversationFocus extends ChatFocusEntry { /** Pin (or clear) the focus of the conversation on screen. */ @@ -169,91 +111,44 @@ export interface ConversationFocus extends ChatFocusEntry { interface FocusState { key: string | undefined; entry: ChatFocusEntry; - /** - * The id that arrives next takes this conversation's focus: set by a - * `setChatFocus` hand-off that landed before the host had an id ("pin, then - * open the drawer"); a first send says the same through `markSending`. Any - * other arrival of an id — a resumed thread resolving, a history row, the - * scope blanking the id between apps — reads that conversation's own stored - * focus instead. Only the hand-off's own focus is carried: the chip's pin, - * remove or decline drops the flag, and so does any change of what the host - * was asked to show ({@link FocusState.target}): an id that arrives for a - * history row picked, or an app moved to, before the first send is that - * conversation's own (objectstack#37142). - */ - carry: boolean; - /** - * What the host was asked to show when the state last moved (a key of the - * dock's target). A change drops the hand-off's carry. - */ - target: string | undefined; - /** - * A `follow` hand-off that landed while this host showed a conversation - * (objectstack#37142): the focus of the NEXT conversation the host shows, - * applied when the id changes (and carried, as a hand-off is, when that - * next one has no id yet). The chip's own moves drop it. - */ - follow?: { focus: ChatFocus | null }; } /** * The focus of the conversation `conversationId` names, held by the chat * host. `undefined` is a conversation the host has no id for yet. A focus - * pinned there reaches an id only on a CARRY (see {@link FocusState.carry}): - * the first send minting it, or the setter's hand-off — and then in the same - * render, so the first turn, sent by the pane that remounts on that id, - * already carries it. Every other move to a conversation restores that one's - * chip from storage. + * pinned there reaches an id only when the first send mints it (the host's + * `markSending`), and then in the same render, so the first turn, sent by the + * pane that remounts on that id, already carries it. Every other arrival of an + * id (a resumed thread resolving, a history row, the scope blanking the id + * between apps) restores that conversation's own chip from storage. */ export function useConversationFocus( conversationId: string | undefined, /** The host's `createError`: a first send whose create failed minted nothing. */ createError?: unknown, - /** - * A key of what the host was asked to show (the dock's target): while it - * holds, an id the host resolves takes a hand-off's carry; once it changes, - * the next id is the conversation's own. A host that passes none keeps the - * carry until an id arrives. - */ - target?: string, ): ConversationFocus { const [state, setState] = React.useState(() => ({ key: conversationId, entry: readStoredChatFocus(conversationId), - carry: false, - target, })); // A first send in flight: a ref, not state, so marking it re-renders // nothing while the pane holds the message it is creating the row for. const sendingRef = React.useRef(false); let current = state; - // The host was asked for something else (a history row, another app): a - // hand-off's carry does not go with it. A pending `follow` does — the caller - // that moved the target set it for exactly that move. - if (current.target !== target) current = { ...current, target, carry: false }; - if (current.key !== conversationId) { + if (state.key !== conversationId) { const carried = - current.key === undefined && + state.key === undefined && conversationId !== undefined && - (current.carry || sendingRef.current) && - current.entry.focus !== null; - current = current.follow - ? { - key: conversationId, - entry: { focus: current.follow.focus, declined: false }, - carry: conversationId === undefined, - target, - } - : { - key: conversationId, - entry: carried ? current.entry : readStoredChatFocus(conversationId), - carry: false, - target, - }; + sendingRef.current && + state.entry.focus !== null; + current = { + key: conversationId, + entry: carried ? state.entry : readStoredChatFocus(conversationId), + }; + // Derived state set during render: React re-renders before committing, so + // no child of this commit sees the previous conversation's focus. + setState(current); } - // Derived state set during render: React re-renders before committing, so - // no child of this commit sees the previous conversation's focus. - if (current !== state) setState(current); const { key, entry } = current; React.useEffect(() => { @@ -271,38 +166,15 @@ export function useConversationFocus( if (createError) sendingRef.current = false; }, [createError]); - // The chip's own moves drop a hand-off's carry: what the user pins (or - // keeps) here is this conversation's, and follows no other one. const setFocus = React.useCallback((focus: ChatFocus | null) => { - setState((s) => - sameChatFocus(s.entry.focus, focus) && !s.follow - ? s - : { ...s, entry: { focus, declined: false }, carry: false, follow: undefined }, - ); + setState((s) => (sameChatFocus(s.entry.focus, focus) ? s : { ...s, entry: { focus, declined: false } })); }, []); const decline = React.useCallback(() => { - setState((s) => - s.entry.declined && !s.carry && !s.follow - ? s - : { ...s, entry: { ...s.entry, declined: true }, carry: false, follow: undefined }, - ); + setState((s) => (s.entry.declined ? s : { ...s, entry: { ...s.entry, declined: true } })); }, []); const markSending = React.useCallback(() => { sendingRef.current = true; }, []); - // The setter's hand-off: applied here, and carried onto the id the host - // resolves next when it has none yet. A `follow` hand-off to a host showing - // a conversation waits for the next one instead (see `FocusState.follow`). - const handOff = React.useCallback((focus: ChatFocus | null, follow: boolean) => { - setState((s) => - follow && s.key !== undefined - ? { ...s, follow: { focus } } - : { ...s, entry: { focus, declined: false }, carry: s.key === undefined, follow: undefined }, - ); - }, []); - - React.useEffect(() => registerChatFocusHost(handOff), [handOff]); - return React.useMemo( () => ({ focus: entry.focus, declined: entry.declined, setFocus, decline, markSending }), [entry, setFocus, decline, markSending], diff --git a/ui/packages/app-shell/src/views/DeclaredActionsBar.tsx b/ui/packages/app-shell/src/views/DeclaredActionsBar.tsx index d583204e8dc..88e4dc90be3 100644 --- a/ui/packages/app-shell/src/views/DeclaredActionsBar.tsx +++ b/ui/packages/app-shell/src/views/DeclaredActionsBar.tsx @@ -53,7 +53,6 @@ import { MetadataCtx, useAction, useCapabilityGate, - useDrawsAction, useCondition, toPredicateInput, usePredicateRecordContext, @@ -1031,12 +1030,9 @@ const DeclaredActionsToolbar: React.FC< > = ({ actions, objectName, record, className, label, foldOverrides, foldDecisions, onDrawnActionsChange, headerParts, requireRejectReason }) => { const { t } = useObjectTranslation(); const mayInvoke = useCapabilityGate(); - // [ADR-0160 D7] An `ask_ai` action is absent where this provider has no - // in-app assistant to hand the record to. - const drawsAction = useDrawsAction(); const permitted = useMemo( - () => actions.filter((action) => mayInvoke(action.requiredPermissions) && !isActionSwitchedOff(action) && drawsAction(action)), - [actions, mayInvoke, drawsAction], + () => actions.filter((action) => mayInvoke(action.requiredPermissions) && !isActionSwitchedOff(action)), + [actions, mayInvoke], ); // objectstack#25877 — which of the permitted levers fold into the override // menu. Only for a viewer admitted through the override door alone diff --git a/ui/packages/app-shell/src/views/__tests__/DeclaredActionsBar.askAi-37142.test.tsx b/ui/packages/app-shell/src/views/__tests__/DeclaredActionsBar.askAi-37142.test.tsx deleted file mode 100644 index 4b3405be1f1..00000000000 --- a/ui/packages/app-shell/src/views/__tests__/DeclaredActionsBar.askAi-37142.test.tsx +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * DeclaredActionsBar — the `ask_ai` action on a record (objectstack#37142, - * ADR-0160 D7). - * - * The bar mounts its own `` from the console runtime, and the - * runtime hands that provider `onAskAi` only where the console can serve the - * click (`useAskAiHandler`, pinned in its own suite). What is pinned here is - * the surface: - * - * 1. No `onAskAi` → the `ask_ai` action is ABSENT (not disabled), while a - * neighbouring action of another type is drawn. - * 2. With `onAskAi` → it is drawn, and a click hands the record the bar - * shows to the assistant, once, and dispatches nothing else. - * - * As in the capability suite next door, `@object-ui/react` is not doubled: the - * gate must read the provider this bar mounts itself. - */ - -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/react'; -import React from 'react'; - -const harness = vi.hoisted(() => ({ - onAskAi: undefined as undefined | ((focus: { object: string; id: string }) => void), - script: vi.fn(async () => ({ success: true })), -})); - -vi.mock('../../hooks/useConsoleActionRuntime', () => ({ - useConsoleActionRuntime: () => ({ - actionProviderProps: { - context: { objectName: 'account', user: { id: 'u_1' } }, - handlers: { script: harness.script }, - ...(harness.onAskAi ? { onAskAi: harness.onAskAi } : {}), - }, - dialogs: null, - }), -})); - -vi.mock('../../providers/AdapterProvider', () => ({ useAdapter: () => ({}) })); -vi.mock('../../utils/getIcon', () => ({ getIcon: () => () => null })); - -vi.mock('@object-ui/i18n', async (importOriginal) => ({ - ...(await importOriginal>()), - useObjectLabel: () => ({ - actionLabel: (_o: unknown, _n: unknown, fallback: string) => fallback, - actionConfirm: (_o: unknown, _n: unknown, fallback?: string) => fallback, - actionSuccess: (_o: unknown, _n: unknown, fallback?: string) => fallback, - }), - useObjectTranslation: () => ({ - t: (key: string, options?: any) => String(options?.defaultValue ?? key), - language: 'en', - }), - pickLocalized: (value: unknown) => (typeof value === 'string' ? value : ''), -})); - -vi.mock('@object-ui/components', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - Button: ({ children, onClick, ...props }: any) => ( - - ), - Separator: () =>
, - cn: (...args: any[]) => args.filter(Boolean).join(' '), - }; -}); - -import { DeclaredActionsBar } from '../DeclaredActionsBar'; - -const ASK = { name: 'ask_about_account', type: 'ask_ai', label: 'Ask AI', locations: ['record_section'] }; -const CLOSE = { name: 'close_account', type: 'script', target: 'close_account', label: 'Close', locations: ['record_section'] }; -const RECORD = { id: 'acc_1', name: 'Acme' }; - -function renderBar() { - return render( - , - ); -} - -beforeEach(() => { - harness.onAskAi = undefined; - harness.script.mockClear(); -}); - -describe('DeclaredActionsBar — ask_ai (ADR-0160 D7)', () => { - it('leaves the action out where the console has no in-app assistant', () => { - renderBar(); - expect(screen.queryByTestId('declared-action-ask_about_account')).toBeNull(); - // Lit control: the bar rendered, and the neighbour is drawn. - expect(screen.getByTestId('declared-action-close_account')).toBeInTheDocument(); - }); - - it('draws it with an assistant, and a click focuses the assistant on the record and sends nothing', async () => { - const onAskAi = vi.fn(); - harness.onAskAi = onAskAi; - renderBar(); - const button = screen.getByTestId('declared-action-ask_about_account'); - fireEvent.click(button); - await waitFor(() => expect(onAskAi).toHaveBeenCalledTimes(1)); - expect(onAskAi).toHaveBeenCalledWith({ object: 'account', id: 'acc_1' }); - expect(harness.script).not.toHaveBeenCalled(); - }); -}); diff --git a/ui/packages/app-shell/src/views/__tests__/objectViewHeaderLaunchGate.askAi-37142.test.tsx b/ui/packages/app-shell/src/views/__tests__/objectViewHeaderLaunchGate.askAi-37142.test.tsx deleted file mode 100644 index afa1c991971..00000000000 --- a/ui/packages/app-shell/src/views/__tests__/objectViewHeaderLaunchGate.askAi-37142.test.tsx +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#37142 (ADR-0160 D7) — a list header holds no record until the - * user selects one. An `ask_ai` action there is drawn only while exactly one - * row is selected; with none or several it is ABSENT, not greyed out with a - * reason as other refused launches are. - */ - -import * as React from 'react'; -import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, cleanup, act } from '@testing-library/react'; -import '@object-ui/components'; -import { ActionProvider, useAction } from '@object-ui/react'; -import type { ActionRunner } from '@object-ui/core'; -import { ListHeaderActionBar } from '../objectViewHeaderLaunchGate'; - -afterEach(() => cleanup()); - -const ASK = { name: 'ask_about_account', label: 'Ask AI', type: 'ask_ai' }; -const CLOSE = { name: 'close_selected', label: 'Close', type: 'script', target: 'close' }; - -let runnerRef: ActionRunner | undefined; -const keepRunner = (runner: ActionRunner) => { - runnerRef = runner; -}; -/** Hands the provider's runner out, so a case can publish a new selection. */ -function GrabRunner({ onRunner }: { onRunner: (runner: ActionRunner) => void }) { - const { runner } = useAction(); - React.useEffect(() => onRunner(runner), [runner, onRunner]); - return null; -} - -function mount(selectedRecords: Array<{ id: string }>) { - render( - - - - , - ); -} - -describe('ListHeaderActionBar — ask_ai needs exactly one selected row', () => { - it('is absent with no row selected, while other actions stay', () => { - mount([]); - expect(screen.queryByRole('button', { name: /Ask AI/ })).toBeNull(); - expect(screen.getByRole('button', { name: /Close/ })).toBeInTheDocument(); - }); - - it('is absent with several rows selected', () => { - mount([{ id: 'a' }, { id: 'b' }]); - expect(screen.queryByRole('button', { name: /Ask AI/ })).toBeNull(); - }); - - it('is drawn, enabled, with one row selected, and leaves again when a second is selected', () => { - mount([{ id: 'a' }]); - const button = screen.getByRole('button', { name: /Ask AI/ }); - expect(button).toBeEnabled(); - act(() => runnerRef!.updateContext({ selectedRecords: [{ id: 'a' }, { id: 'b' }] })); - expect(screen.queryByRole('button', { name: /Ask AI/ })).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ActionDefaultInspector.typeSwitch-26736.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ActionDefaultInspector.typeSwitch-26736.test.tsx index 5c5bcec04bd..67a51e9ddb2 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ActionDefaultInspector.typeSwitch-26736.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ActionDefaultInspector.typeSwitch-26736.test.tsx @@ -183,9 +183,6 @@ describe('typeSwitchPin — TYPE_SCOPED_KEYS matches the spec (objectstack#26736 const base = (type: string): Draft => type === 'script' ? { name: 'probe', label: 'Probe', type, body: { language: 'expression', source: 'true' } } - : type === 'ask_ai' - // ADR-0160 D7: `ask_ai` takes no target, so its minimal action has none. - ? { name: 'probe', label: 'Probe', type } : { name: 'probe', label: 'Probe', type, target: type === 'url' ? 'https://example.com' : 'probe_target' }; const SAMPLE: Record = { body: { language: 'expression', source: 'true' }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/ObjectFormCanvas.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/ObjectFormCanvas.test.tsx index d134ae786e3..31d63f1e77a 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/ObjectFormCanvas.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/ObjectFormCanvas.test.tsx @@ -13,11 +13,11 @@ import { useAiSurfaceEnabled } from '../../../hooks/useAiSurface'; // up a discovery data source; every test starts with AI enabled (see // beforeEach), and the Community-Edition case overrides it to disabled. vi.mock('../../../hooks/useAiSurface', () => ({ - useAiSurfaceEnabled: vi.fn(() => ({ enabled: true, isLoading: false, buildServed: true, focusServed: false })), + useAiSurfaceEnabled: vi.fn(() => ({ enabled: true, isLoading: false, buildServed: true })), })); beforeEach(() => { - vi.mocked(useAiSurfaceEnabled).mockReturnValue({ enabled: true, isLoading: false, buildServed: true, focusServed: false }); + vi.mocked(useAiSurfaceEnabled).mockReturnValue({ enabled: true, isLoading: false, buildServed: true }); }); afterEach(cleanup); @@ -359,7 +359,7 @@ describe('ObjectFormCanvas — Ask AI entry point', () => { }); it('hides both Ask AI affordances when AI is unavailable (Community Edition)', () => { - vi.mocked(useAiSurfaceEnabled).mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); + vi.mocked(useAiSurfaceEnabled).mockReturnValue({ enabled: false, isLoading: false, buildServed: false }); // Populated canvas: the toolbar "Ask AI" is gone, but the rest of the // toolbar (Add field / Add section) stays. diff --git a/ui/packages/app-shell/src/views/objectViewHeaderLaunchGate.tsx b/ui/packages/app-shell/src/views/objectViewHeaderLaunchGate.tsx index a3d287c8599..eae2a671623 100644 --- a/ui/packages/app-shell/src/views/objectViewHeaderLaunchGate.tsx +++ b/ui/packages/app-shell/src/views/objectViewHeaderLaunchGate.tsx @@ -29,7 +29,6 @@ import { useCallback, useSyncExternalStore } from 'react'; import { SchemaRenderer, useAction } from '@object-ui/react'; -import { isAskAiAction } from '@object-ui/core'; import { useObjectTranslation } from '@object-ui/i18n'; import type { ActionBarSchema, UIActionSchema } from '@object-ui/types'; @@ -52,10 +51,6 @@ function useListHeaderLaunchGate(actions: readonly UIActionSchema[] | undefined) : runner.launchRefusal(action as Parameters[0]); if (refusal === undefined) { gated.push(action); - } else if (isAskAiAction(action)) { - // [ADR-0160 D7] `ask_ai` is absent where no single record is held - // (no row, or several, selected), not greyed out (objectstack#37142). - continue; } else if (selectionAvailable !== false) { gated.push({ ...action, disabled: true, disabledReason: refusal }); } diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.presets-11861.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.presets-11861.test.tsx index 00820ad47a7..ea85f3a7ad1 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.presets-11861.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.presets-11861.test.tsx @@ -343,13 +343,6 @@ describe('the preset module’s written-out tables agree with the spec (objectui // A `url` target is a path since `@objectstack/spec` 18, which refuses a bare // relative one at `target` (objectui#12030); every other type takes a name. const target = type === 'url' ? '/x_target' : 'x_target'; - // `ask_ai` takes no target at all (ADR-0160 D7): one is refused, and the - // editor holds nothing for it, because there is no input to fill. - if (type === 'ask_ai') { - expect(refusedAt({ ...seed, type, target }, 'target')).toBe(true); - expect(heldInputKey({ ...seed, type })).toBeNull(); - return; - } expect(refusedAt({ ...seed, type, target }, 'target')).toBe(false); expect(heldInputKey({ ...seed, type, target })).toBeNull(); }, diff --git a/ui/packages/components/src/renderers/action/action-bar.tsx b/ui/packages/components/src/renderers/action/action-bar.tsx index e816fbe3f01..8c7a7954765 100644 --- a/ui/packages/components/src/renderers/action/action-bar.tsx +++ b/ui/packages/components/src/renderers/action/action-bar.tsx @@ -51,7 +51,7 @@ import React, { forwardRef, useMemo } from 'react'; import { ComponentRegistry, isActionSwitchedOff } from '@object-ui/core'; import type { UIActionSchema, ActionBarSchema, ActionComponent } from '@object-ui/types'; import { ACTION_LOCATIONS, actionRendersAt } from '@object-ui/types'; -import { useCondition, toPredicateInput, useCapabilityGate, useConfigBagEvaluator, useDrawsAction } from '@object-ui/react'; +import { useCondition, toPredicateInput, useCapabilityGate, useConfigBagEvaluator } from '@object-ui/react'; import { useObjectTranslation } from '@object-ui/i18n'; import { cn } from '../../lib/utils'; import { useIsMobile } from '../../hooks/use-mobile'; @@ -128,9 +128,6 @@ const ActionBarRenderer = forwardRef mayInvoke((a as any)?.requiredPermissions) && !isActionSwitchedOff(a) && drawsAction(a)); + const permitted = actions.filter(a => mayInvoke((a as any)?.requiredPermissions) && !isActionSwitchedOff(a)); // Placement is `actionRendersAt`'s call, not ours (objectui#3142): an // action renders here only if it DECLARES this location. This bar used // to show a locationless action at every location, which is how an @@ -195,7 +192,7 @@ const ActionBarRenderer = forwardRef