diff --git a/.changeset/37142-ask-ai-action-type.md b/.changeset/37142-ask-ai-action-type.md new file mode 100644 index 00000000000..526de72f8da --- /dev/null +++ b/.changeset/37142-ask-ai-action-type.md @@ -0,0 +1,28 @@ +--- +'@objectstack/spec': minor +'@objectstack/runtime': 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(actions): `type: 'ask_ai'` — an action that opens the in-app assistant focused on the record it runs on + +Clause-②: yes (widening: a new `ActionType` member `ask_ai`, refused beside `target`, `ai.exposed: true` and on a dashboard header) +Metadata-protocol: added +Skills-docs: follow-up #37217 + +ADR-0160 D7. An author can now put an "Ask AI" button on a record: + +```ts +actions: [{ name: 'ask_about_account', label: 'Ask AI', type: 'ask_ai', locations: ['record_header'] }] +``` + +- **Spec.** `ActionType` gains `ask_ai`. It takes no `target`: the parse refuses one (and its inline spelling `to`) at the `target` path, because what the assistant reads about the record is chosen by the record's context pack, not by the action. It is never an AI tool: `ai.exposed: true` beside it is refused at `ai.exposed` (`false` parses). A dashboard header action cannot be `actionType: 'ask_ai'` (a header runs on no record); `WidgetActionTypeSchema` stays derived from `ActionType` and the header refuses that one member with the reason. +- **Runtime.** `ask_ai` has no server dispatch. `isHeadlessInvokableAction` answers `false` for it, so MCP `list_actions` skips it and the AI action door refuses it, and the REST action door answers with a sentence about the in-app assistant. +- **Console.** A click focuses the in-app assistant on the record (`setChatFocus`) and opens the drawer. It sends no message and makes no server call. The record is the page record, the row a row surface hands over, or the one selected row; with none, or several selected, the click is refused before any `confirmText`. New in `@object-ui/core`: `ActionRunner.setAssistantFocusHandler`, `ActionRunner.drawsAction`, `isAskAiAction`, and the `AssistantFocus` / `AssistantFocusHandler` types; `ActionEngine` leaves undrawn actions out of `getActionsForLocation` and `getBulkActions`. New in `@object-ui/react`: `` and `useDrawsAction()`. `@object-ui/app-shell` installs the handler (`useAskAiHandler`) only when the layout hosts the assistant drawer, the AI surface is on, and an agent in the catalog advertises `capabilities.focus`. +- **Absent, not disabled.** Where no in-app assistant can take it, an `ask_ai` action is not drawn on any action surface (record header, action bars, row menus, related lists, page action renderers). Where no single record is held it is absent too: the bulk bar never offers it, a related list's toolbar leaves it out (its rows draw it), and a list toolbar draws it only while exactly one row is selected. A launch that reaches the runner anyway is refused, not reported done; `ActionRunner.bulkRefusal` refuses a per-row run over a selection, and `ActionEngine.getBulkActions` / `executeBulk` leave it out. +- **The conversation it opens.** The click opens the drawer on a fresh thread of an agent that declares `capabilities.focus` (an `ask` agent first), so the drawer's own pin control is drawn on the record, and pins the record to that thread; its first send carries the focus and creates the conversation, and an unsent one creates nothing. A conversation the drawer showed before keeps its own focus. New in `@object-ui/app-shell`: `setChatFocus(focus, { follow: true })`, a pin for the conversation the caller moves the chat to in the same event. diff --git a/content/docs/protocol/objectui/actions.mdx b/content/docs/protocol/objectui/actions.mdx index efc5299bdf2..a0d2b05524a 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`** — 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`, `ask_ai`** — there are no other types. `type` defaults to `script` when omitted. | Type | Behavior | `target` required? | | --- | --- | --- | @@ -51,6 +51,7 @@ 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. @@ -224,7 +225,7 @@ interface Action { order?: number; // Sort order within a location group (lower = higher) // Behavior - type?: 'script' | 'url' | 'modal' | 'flow' | 'api' | 'form'; // default 'script' + type?: 'script' | 'url' | 'modal' | 'flow' | 'api' | 'form' | 'ask_ai'; // 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 2fa6d48943f..08f2650afd8 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -521,7 +521,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'>` | 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' \| '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. | | **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 425c2f65837..379e844b085 100644 --- a/content/docs/references/kernel/metadata-plugin.mdx +++ b/content/docs/references/kernel/metadata-plugin.mdx @@ -329,7 +329,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'>` | 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' \| '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. | | **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 200d38e198f..10d40d785ab 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'>` | 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' \| '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. | | **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,6 +419,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities * `flow` * `api` * `form` +* `ask_ai` --- @@ -429,7 +430,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'>` | 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' \| '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. | | **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 38276320f75..e8c96b8f25e 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'>; name?: string; label?: string \| Record; target?: string; … }` | optional | Inline action executed on click | +| **action** | `{ type?: Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>; 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'>` | 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' \| '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. | | **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 2cfd5179ffd..4097f4caebc 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'>; icon?: string }[]` | optional | Header action buttons | +| **actions** | `{ label: string \| Record; actionUrl: string; actionType?: Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>; 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'>; icon?: string }[]` | optional | Header action buttons | +| **actions** | `{ label: string \| Record; actionUrl: string; actionType?: Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>; 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'>` | optional | Type of action | +| **actionType** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>` | 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'>` | optional | Type of action | +| **actionType** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form' \| 'ask_ai'>` | optional | Type of action | | **icon** | `string` | optional | Icon identifier for the action button | @@ -375,6 +375,7 @@ Widget action type * `flow` * `api` * `form` +* `ask_ai` --- diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index 36da0b300f6..806fda8a8f3 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -21,6 +21,7 @@ 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 @@ -803,6 +804,7 @@ 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 @@ -995,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`) — open its `target` in the client, or call that endpoint directly | +| 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) | | 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 0d69ab6dc49..a5f7d4b905e 100644 --- a/examples/app-showcase/src/system/translations/index.ts +++ b/examples/app-showcase/src/system/translations/index.ts @@ -562,6 +562,7 @@ 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 60343794403..be0fd4a42d7 100644 --- a/examples/app-showcase/src/ui/actions/index.ts +++ b/examples/app-showcase/src/ui/actions/index.ts @@ -279,6 +279,21 @@ 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: []`). * @@ -573,6 +588,7 @@ 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 6745057b7f5..ea25cbcc485 100644 --- a/examples/app-showcase/src/ui/pages/task-detail.page.ts +++ b/examples/app-showcase/src/ui/pages/task-detail.page.ts @@ -63,6 +63,8 @@ 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/runtime/src/action-ask-ai-headless.test.ts b/packages/runtime/src/action-ask-ai-headless.test.ts new file mode 100644 index 00000000000..23bb6272a86 --- /dev/null +++ b/packages/runtime/src/action-ask-ai-headless.test.ts @@ -0,0 +1,54 @@ +// 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 306d97d2fc4..e064365170c 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -1360,6 +1360,9 @@ 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; } @@ -2499,6 +2502,16 @@ 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/spec/src/ui/action-ask-ai.test.ts b/packages/spec/src/ui/action-ask-ai.test.ts new file mode 100644 index 00000000000..ea2b3375b8d --- /dev/null +++ b/packages/spec/src/ui/action-ask-ai.test.ts @@ -0,0 +1,120 @@ +// 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 8e276b541d2..63a6a16311b 100644 --- a/packages/spec/src/ui/action-row-update.test.ts +++ b/packages/spec/src/ui/action-row-update.test.ts @@ -161,12 +161,14 @@ describe('`operation: \'update\'` + `patch` is accepted (the bulk def\'s vocabul }); describe('key shape: a parallel key beside `type`, not an `ActionType` member', () => { - it('leaves the ActionType vocabulary exactly as it was', () => { + it('adds no `update` member to the ActionType vocabulary', () => { // 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. - expect([...ActionType.options]).toEqual(['script', 'url', 'modal', 'flow', 'api', 'form']); + // 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'); }); 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 d284c96b9e3..b80ff740aec 100644 --- a/packages/spec/src/ui/action-undoable-fulfillment.test.ts +++ b/packages/spec/src/ui/action-undoable-fulfillment.test.ts @@ -30,6 +30,7 @@ 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 54db5fd0b9a..5e1bbde631a 100644 --- a/packages/spec/src/ui/action.zod.ts +++ b/packages/spec/src/ui/action.zod.ts @@ -689,20 +689,76 @@ export const ActionParamSchema = lazySchema(() => strictObject( * console compiling until an executor exists — a coupling the ruling's * 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. */ -export const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api', 'form']); +export const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api', 'form', 'ask_ai']); 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 'script' which allows inline handlers. + * Derived from ActionType, excluding the targetless types above. * 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) => t !== 'script'), + ActionType.options.filter((t) => !TARGETLESS_TYPES.has(t)), ); +/** + * 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 * @@ -2974,7 +3030,8 @@ 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`")).refine((data) => { +}).superRefine(refuseUnopenableUrlTarget("A `type: 'url'` action's `target`")) + .superRefine(refuseAskAiContradictions).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 @@ -3392,7 +3449,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 1023ae6645d..f517960464f 100644 --- a/packages/spec/src/ui/component.zod.ts +++ b/packages/spec/src/ui/component.zod.ts @@ -3891,7 +3891,7 @@ const rowPatchRetired = (owner: string) => retiredKey( ); /** - * The console runner's built-in executors: `ActionType`'s six, the members its + * The console runner's built-in executors: `ActionType`'s members, which 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 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 new file mode 100644 index 00000000000..a922457842a --- /dev/null +++ b/packages/spec/src/ui/dashboard-header-ask-ai-37142.test.ts @@ -0,0 +1,29 @@ +// 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 34f5d697441..dd608b3e790 100644 --- a/packages/spec/src/ui/dashboard.zod.ts +++ b/packages/spec/src/ui/dashboard.zod.ts @@ -65,7 +65,9 @@ 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. + * 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. */ export const WidgetActionTypeSchema = lazySchema(() => ActionType.describe('Widget action type')); @@ -111,6 +113,28 @@ 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. @@ -157,7 +181,7 @@ export const DashboardHeaderActionSchema = lazySchema(() => strictObject({ /** Icon identifier */ icon: z.string().optional().describe('Icon identifier for the action button').meta({ title: 'Icon' }), -}).superRefine(refuseUnopenableHeaderActionUrl).describe('Dashboard header action')); +}).superRefine(refuseUnopenableHeaderActionUrl).superRefine(refuseRecordlessAskAi).describe('Dashboard header action')); /** * Dashboard Header Schema diff --git a/packages/spec/src/ui/inline-action.test.ts b/packages/spec/src/ui/inline-action.test.ts index 31866b1f179..976078bdc92 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'; - const body = needsTarget ? { type, target: '/x' } : { type, target: 'fn_name' }; + const needsTarget = type !== 'script' && type !== 'ask_ai'; + const body = type === 'ask_ai' ? { type } : needsTarget ? { type, target: '/x' } : { type, target: 'fn_name' }; expect(InlineActionSchema.safeParse(body).success, `type "${type}" rejected`).toBe(true); } }); diff --git a/skills/objectstack-ui/SKILL.md b/skills/objectstack-ui/SKILL.md index 596b4952b7f..b124e547ff5 100644 --- a/skills/objectstack-ui/SKILL.md +++ b/skills/objectstack-ui/SKILL.md @@ -148,8 +148,9 @@ never its label ([Actions](./rules/actions.md)): | `flow` | Launch a screen/auto-launched flow by name; a multi-step operation is this, with a flow you also author | | `api` | Call a registered API endpoint | | `form` | Open a FormView by name (routed to `/_console/forms/:name`) | +| `ask_ai` | Open the in-app assistant focused on the one record the action runs on; no `target`, never `ai.exposed: true` | -Every type but `script` requires `target`. +Every type but `script` and `ask_ai` requires `target`. ## Report Types diff --git a/ui/packages/app-shell/src/console/ConsoleShell.tsx b/ui/packages/app-shell/src/console/ConsoleShell.tsx index 58ac3dff1fb..23de90968e1 100644 --- a/ui/packages/app-shell/src/console/ConsoleShell.tsx +++ b/ui/packages/app-shell/src/console/ConsoleShell.tsx @@ -119,6 +119,7 @@ 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 5ff0fdd0808..0d8c3b10024 100644 --- a/ui/packages/app-shell/src/console/__tests__/RequireAiSurface.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/RequireAiSurface.test.tsx @@ -10,7 +10,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 })), + useAiSurfaceEnabled: vi.fn(() => ({ enabled: true, isLoading: false, buildServed: true, focusServed: false })), })); const mockSurface = vi.mocked(useAiSurfaceEnabled); @@ -89,7 +89,7 @@ function renderGuardedAi(apps?: MetadataContextValue['apps']) { describe('RequireAiSurface', () => { beforeEach(() => { - mockSurface.mockReturnValue({ enabled: true, isLoading: false, buildServed: true }); + mockSurface.mockReturnValue({ enabled: true, isLoading: false, buildServed: true, focusServed: false }); viewer.isAdmin = true; viewer.canAuthorMetadata = true; viewer.aiStudio = true; @@ -105,7 +105,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 }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); renderGuardedAi(); expect(screen.queryByText('AI CHAT')).not.toBeInTheDocument(); expect(screen.queryByText('HOME')).not.toBeInTheDocument(); @@ -119,7 +119,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 }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); renderGuardedAi(); const studio = screen.getByTestId('ai-unavailable-studio'); expect(studio).toHaveTextContent('«home.build.inStudio»'); @@ -132,14 +132,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 }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: 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 }); + mockSurface.mockReturnValue({ enabled: false, isLoading: true, buildServed: false, focusServed: false }); renderGuardedAi(); expect(screen.queryByText('AI CHAT')).not.toBeInTheDocument(); expect(screen.queryByTestId('ai-unavailable')).not.toBeInTheDocument(); @@ -154,7 +154,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 }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); renderGuardedAi([ { name: 'cloud_control', label: 'Cloud', isDefault: true }, { name: 'account', label: 'Account' }, @@ -170,7 +170,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 }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); renderGuardedAi([ { name: 'cloud_control', label: 'Cloud', isDefault: true }, { name: 'account', label: 'Account' }, @@ -187,7 +187,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 }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); renderGuardedAi([{ name: 'crm', label: 'CRM' }, { name: 'setup', label: 'Setup' }]); await user.click(screen.getByTestId('ai-unavailable-home')); expect(screen.getByText('HOME')).toBeInTheDocument(); @@ -197,7 +197,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 }); + mockSurface.mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: 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 11f9d65e47a..5293807ed5f 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 }); + expect(result.current).toEqual({ enabled: true, isLoading: false, buildServed: false, focusServed: 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 }); + expect(result.current).toEqual({ enabled: false, isLoading: true, buildServed: false, focusServed: 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 }); + expect(result.current).toEqual({ enabled: false, isLoading: true, buildServed: false, focusServed: 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 }); + expect(result.current).toEqual({ enabled: false, isLoading: false, buildServed: false, focusServed: false }); }); }); @@ -71,6 +71,18 @@ 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 }); + 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); }); }); 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 new file mode 100644 index 00000000000..8b4901686fe --- /dev/null +++ b/ui/packages/app-shell/src/hooks/__tests__/useAskAiHandler-37142.test.tsx @@ -0,0 +1,111 @@ +// 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 new file mode 100644 index 00000000000..b6b55f072cf --- /dev/null +++ b/ui/packages/app-shell/src/hooks/aiApiBase.ts @@ -0,0 +1,20 @@ +// 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 f786b80c041..0ee033ac848 100644 --- a/ui/packages/app-shell/src/hooks/surfaceAgent.ts +++ b/ui/packages/app-shell/src/hooks/surfaceAgent.ts @@ -91,6 +91,28 @@ 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 1d4591c0810..539f4bf3548 100644 --- a/ui/packages/app-shell/src/hooks/useAiSurface.ts +++ b/ui/packages/app-shell/src/hooks/useAiSurface.ts @@ -42,20 +42,11 @@ import { useRef } from 'react'; import { useAgents } from '@object-ui/plugin-chatbot/core'; -import { catalogServesBuild } from './surfaceAgent.js'; +import { catalogServesBuild, catalogServesFocus } from './surfaceAgent.js'; +import { resolveAiApiBase } from './aiApiBase.js'; -/** - * 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`; -} +// Re-exported where its callers have always imported it from. +export { resolveAiApiBase }; export interface AiSurfaceState { /** True when the AI UI should render — the CALLER can reach >= 1 agent (access-filtered). */ @@ -69,6 +60,14 @@ 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; } /** @@ -90,6 +89,7 @@ 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 new file mode 100644 index 00000000000..6e4d4e07463 --- /dev/null +++ b/ui/packages/app-shell/src/hooks/useAskAiHandler.ts @@ -0,0 +1,55 @@ +// 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 ab73465d18c..6e1a02cf701 100644 --- a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx +++ b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx @@ -54,6 +54,7 @@ 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'; @@ -155,7 +156,11 @@ 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; } @@ -954,6 +959,9 @@ 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 } : {}), @@ -985,10 +993,11 @@ 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, + flowHandler, serverActionHandler, modalHandler, modalActionHandler, askAiHandler, ]); // The run FlowRunner shows; its close and completion settle that run alone. 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 9c4ca490385..e2cc526f233 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 @@ -95,6 +95,9 @@ import { } 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, @@ -445,3 +448,98 @@ 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); + }); +}); diff --git a/ui/packages/app-shell/src/layout/chatFocus.ts b/ui/packages/app-shell/src/layout/chatFocus.ts index eb77937bb6f..7bf0a66e0da 100644 --- a/ui/packages/app-shell/src/layout/chatFocus.ts +++ b/ui/packages/app-shell/src/layout/chatFocus.ts @@ -98,28 +98,45 @@ export function buildFocusContext( // 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. -type ChatFocusHost = (focus: ChatFocus | null) => void; +/** 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 } | null = null; +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): void { +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); - else pending = { focus: next }; + if (host) host(next, follow); + else pending = { focus: next, follow }; } function registerChatFocusHost(host: ChatFocusHost): () => void { hosts.push(host); if (pending) { - const { focus } = pending; + const { focus, follow } = pending; pending = null; - host(focus); + host(focus, follow); } return () => { const at = hosts.lastIndexOf(host); @@ -162,6 +179,13 @@ interface FocusState { * remove or decline drops the flag. */ carry: boolean; + /** + * 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 }; } /** @@ -193,11 +217,17 @@ export function useConversationFocus( conversationId !== undefined && (state.carry || sendingRef.current) && state.entry.focus !== null; - current = { - key: conversationId, - entry: carried ? state.entry : readStoredChatFocus(conversationId), - carry: false, - }; + current = state.follow + ? { + key: conversationId, + entry: { focus: state.follow.focus, declined: false }, + carry: conversationId === undefined, + } + : { + key: conversationId, + entry: carried ? state.entry : readStoredChatFocus(conversationId), + carry: false, + }; // Derived state set during render: React re-renders before committing, so // no child of this commit sees the previous conversation's focus. setState(current); @@ -223,23 +253,30 @@ export function useConversationFocus( // 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) + sameChatFocus(s.entry.focus, focus) && !s.follow ? s - : { ...s, entry: { focus, declined: false }, carry: false }, + : { key: s.key, entry: { focus, declined: false }, carry: false }, ); }, []); const decline = React.useCallback(() => { setState((s) => - s.entry.declined && !s.carry ? s : { ...s, entry: { ...s.entry, declined: true }, carry: false }, + s.entry.declined && !s.carry && !s.follow + ? s + : { key: s.key, entry: { ...s.entry, declined: true }, carry: false }, ); }, []); 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. - const handOff = React.useCallback((focus: ChatFocus | null) => { - setState((s) => ({ key: s.key, entry: { focus, declined: false }, carry: s.key === undefined })); + // 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 } } + : { key: s.key, entry: { focus, declined: false }, carry: s.key === undefined }, + ); }, []); React.useEffect(() => registerChatFocusHost(handOff), [handOff]); diff --git a/ui/packages/app-shell/src/views/DeclaredActionsBar.tsx b/ui/packages/app-shell/src/views/DeclaredActionsBar.tsx index 88e4dc90be3..d583204e8dc 100644 --- a/ui/packages/app-shell/src/views/DeclaredActionsBar.tsx +++ b/ui/packages/app-shell/src/views/DeclaredActionsBar.tsx @@ -53,6 +53,7 @@ import { MetadataCtx, useAction, useCapabilityGate, + useDrawsAction, useCondition, toPredicateInput, usePredicateRecordContext, @@ -1030,9 +1031,12 @@ 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)), - [actions, mayInvoke], + () => actions.filter((action) => mayInvoke(action.requiredPermissions) && !isActionSwitchedOff(action) && drawsAction(action)), + [actions, mayInvoke, drawsAction], ); // 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 new file mode 100644 index 00000000000..4b3405be1f1 --- /dev/null +++ b/ui/packages/app-shell/src/views/__tests__/DeclaredActionsBar.askAi-37142.test.tsx @@ -0,0 +1,110 @@ +// 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 new file mode 100644 index 00000000000..afa1c991971 --- /dev/null +++ b/ui/packages/app-shell/src/views/__tests__/objectViewHeaderLaunchGate.askAi-37142.test.tsx @@ -0,0 +1,62 @@ +// 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 393c26dcd67..5c5bcec04bd 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 @@ -32,6 +32,9 @@ const state = vi.hoisted(() => ({ vi.mock('../useMetadata', () => ({ useMetadataClient: () => state.metadataClient })); import { ActionDefaultInspector, TYPE_SCOPED_KEYS } from './ActionDefaultInspector'; +// Paid at collection, not inside a clocked case (check:test-source-alias). +import '@objectstack/formula'; +import '@objectstack/lint'; afterEach(cleanup); @@ -180,6 +183,9 @@ 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 31d63f1e77a..d134ae786e3 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 })), + useAiSurfaceEnabled: vi.fn(() => ({ enabled: true, isLoading: false, buildServed: true, focusServed: false })), })); beforeEach(() => { - vi.mocked(useAiSurfaceEnabled).mockReturnValue({ enabled: true, isLoading: false, buildServed: true }); + vi.mocked(useAiSurfaceEnabled).mockReturnValue({ enabled: true, isLoading: false, buildServed: true, focusServed: false }); }); 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 }); + vi.mocked(useAiSurfaceEnabled).mockReturnValue({ enabled: false, isLoading: false, buildServed: false, focusServed: 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 eae2a671623..a3d287c8599 100644 --- a/ui/packages/app-shell/src/views/objectViewHeaderLaunchGate.tsx +++ b/ui/packages/app-shell/src/views/objectViewHeaderLaunchGate.tsx @@ -29,6 +29,7 @@ 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'; @@ -51,6 +52,10 @@ 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 7dec755a5a4..00820ad47a7 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 @@ -63,6 +63,9 @@ import { ACTION_PRESETS, TARGET_INPUT_KEYS, heldInputKey, type ActionPresetField import { ActionDefaultInspector } from '../metadata-admin/inspectors/ActionDefaultInspector'; import { registerMetadataDefaultInspector } from '../metadata-admin/default-inspector-registry'; import { t } from '../metadata-admin/i18n'; +// Paid at collection, not inside a clocked case (check:test-source-alias). +import '@objectstack/formula'; +import '@objectstack/lint'; // The real editor, as the console registers it. registerMetadataDefaultInspector('action', ActionDefaultInspector); @@ -340,6 +343,13 @@ 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 8c7a7954765..e816fbe3f01 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 } from '@object-ui/react'; +import { useCondition, toPredicateInput, useCapabilityGate, useConfigBagEvaluator, useDrawsAction } from '@object-ui/react'; import { useObjectTranslation } from '@object-ui/i18n'; import { cn } from '../../lib/utils'; import { useIsMobile } from '../../hooks/use-mobile'; @@ -128,6 +128,9 @@ const ActionBarRenderer = forwardRef mayInvoke((a as any)?.requiredPermissions) && !isActionSwitchedOff(a)); + const permitted = actions.filter(a => mayInvoke((a as any)?.requiredPermissions) && !isActionSwitchedOff(a) && drawsAction(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 @@ -192,7 +195,7 @@ const ActionBarRenderer = forwardRef